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 |
|---|---|---|---|---|---|---|
stacksync/sync-service | src/main/java/com/stacksync/syncservice/db/postgresql/PostgresqlUserDAO.java | // Path: src/main/java/com/stacksync/syncservice/db/DAOError.java
// public enum DAOError {
//
// // These errors codes correspond to HTTP codes
// // Users
// USER_NOT_FOUND(400, "User not found."), USER_NOT_AUTHORIZED(401,
// "The user is not authorized to access to this resource."),
//
// // Workspaces
// WORKSPACES_NOT_FOUND(410, "Workspaces not found."),
//
// // Files
// FILE_NOT_FOUND(404, "File or folder not found."),
//
// // Server
// INTERNAL_SERVER_ERROR(500, "Internal Server Error");
//
// private final int code;
// private final String message;
//
// DAOError(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
// }
//
// Path: src/main/java/com/stacksync/syncservice/db/UserDAO.java
// public interface UserDAO {
//
// public User findById(UUID id) throws DAOException;
//
// public User getByEmail(String email) throws DAOException;
//
// public List<User> findAll() throws DAOException;
//
// public List<User> findByItemId(Long clientFileId) throws DAOException;
//
// public void add(User user) throws DAOException;
//
// public void update(User user) throws DAOException;
//
// public void delete(UUID id) throws DAOException;
//
// public void updateAvailableQuota(User user) throws DAOException;
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoResultReturnedDAOException.java
// public class NoResultReturnedDAOException extends DAOException {
//
// private static final long serialVersionUID = -1412276333572134887L;
//
// public NoResultReturnedDAOException(DAOError error) {
// super(error);
// }
//
// public NoResultReturnedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoResultReturnedDAOException(String message) {
// super(message);
// }
//
// public NoResultReturnedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoResultReturnedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
| import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.log4j.Logger;
import com.stacksync.commons.models.User;
import com.stacksync.syncservice.db.DAOError;
import com.stacksync.syncservice.db.UserDAO;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.exceptions.dao.NoResultReturnedDAOException; | package com.stacksync.syncservice.db.postgresql;
public class PostgresqlUserDAO extends PostgresqlDAO implements UserDAO {
private static final Logger logger = Logger.getLogger(PostgresqlUserDAO.class.getName());
public PostgresqlUserDAO(Connection connection) {
super(connection);
}
@Override | // Path: src/main/java/com/stacksync/syncservice/db/DAOError.java
// public enum DAOError {
//
// // These errors codes correspond to HTTP codes
// // Users
// USER_NOT_FOUND(400, "User not found."), USER_NOT_AUTHORIZED(401,
// "The user is not authorized to access to this resource."),
//
// // Workspaces
// WORKSPACES_NOT_FOUND(410, "Workspaces not found."),
//
// // Files
// FILE_NOT_FOUND(404, "File or folder not found."),
//
// // Server
// INTERNAL_SERVER_ERROR(500, "Internal Server Error");
//
// private final int code;
// private final String message;
//
// DAOError(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
// }
//
// Path: src/main/java/com/stacksync/syncservice/db/UserDAO.java
// public interface UserDAO {
//
// public User findById(UUID id) throws DAOException;
//
// public User getByEmail(String email) throws DAOException;
//
// public List<User> findAll() throws DAOException;
//
// public List<User> findByItemId(Long clientFileId) throws DAOException;
//
// public void add(User user) throws DAOException;
//
// public void update(User user) throws DAOException;
//
// public void delete(UUID id) throws DAOException;
//
// public void updateAvailableQuota(User user) throws DAOException;
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoResultReturnedDAOException.java
// public class NoResultReturnedDAOException extends DAOException {
//
// private static final long serialVersionUID = -1412276333572134887L;
//
// public NoResultReturnedDAOException(DAOError error) {
// super(error);
// }
//
// public NoResultReturnedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoResultReturnedDAOException(String message) {
// super(message);
// }
//
// public NoResultReturnedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoResultReturnedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
// Path: src/main/java/com/stacksync/syncservice/db/postgresql/PostgresqlUserDAO.java
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.log4j.Logger;
import com.stacksync.commons.models.User;
import com.stacksync.syncservice.db.DAOError;
import com.stacksync.syncservice.db.UserDAO;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.exceptions.dao.NoResultReturnedDAOException;
package com.stacksync.syncservice.db.postgresql;
public class PostgresqlUserDAO extends PostgresqlDAO implements UserDAO {
private static final Logger logger = Logger.getLogger(PostgresqlUserDAO.class.getName());
public PostgresqlUserDAO(Connection connection) {
super(connection);
}
@Override | public User findById(UUID userID) throws DAOException { |
stacksync/sync-service | src/main/java/com/stacksync/syncservice/db/postgresql/PostgresqlUserDAO.java | // Path: src/main/java/com/stacksync/syncservice/db/DAOError.java
// public enum DAOError {
//
// // These errors codes correspond to HTTP codes
// // Users
// USER_NOT_FOUND(400, "User not found."), USER_NOT_AUTHORIZED(401,
// "The user is not authorized to access to this resource."),
//
// // Workspaces
// WORKSPACES_NOT_FOUND(410, "Workspaces not found."),
//
// // Files
// FILE_NOT_FOUND(404, "File or folder not found."),
//
// // Server
// INTERNAL_SERVER_ERROR(500, "Internal Server Error");
//
// private final int code;
// private final String message;
//
// DAOError(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
// }
//
// Path: src/main/java/com/stacksync/syncservice/db/UserDAO.java
// public interface UserDAO {
//
// public User findById(UUID id) throws DAOException;
//
// public User getByEmail(String email) throws DAOException;
//
// public List<User> findAll() throws DAOException;
//
// public List<User> findByItemId(Long clientFileId) throws DAOException;
//
// public void add(User user) throws DAOException;
//
// public void update(User user) throws DAOException;
//
// public void delete(UUID id) throws DAOException;
//
// public void updateAvailableQuota(User user) throws DAOException;
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoResultReturnedDAOException.java
// public class NoResultReturnedDAOException extends DAOException {
//
// private static final long serialVersionUID = -1412276333572134887L;
//
// public NoResultReturnedDAOException(DAOError error) {
// super(error);
// }
//
// public NoResultReturnedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoResultReturnedDAOException(String message) {
// super(message);
// }
//
// public NoResultReturnedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoResultReturnedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
| import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.log4j.Logger;
import com.stacksync.commons.models.User;
import com.stacksync.syncservice.db.DAOError;
import com.stacksync.syncservice.db.UserDAO;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.exceptions.dao.NoResultReturnedDAOException; | package com.stacksync.syncservice.db.postgresql;
public class PostgresqlUserDAO extends PostgresqlDAO implements UserDAO {
private static final Logger logger = Logger.getLogger(PostgresqlUserDAO.class.getName());
public PostgresqlUserDAO(Connection connection) {
super(connection);
}
@Override
public User findById(UUID userID) throws DAOException {
ResultSet resultSet = null;
User user = null;
String query = "SELECT id, name, email, swift_user, swift_account, quota_limit, quota_used_logical, quota_used_real " + " FROM \"user1\" WHERE id = ?::uuid";
try {
resultSet = executeQuery(query, new Object[] { userID });
if (resultSet.next()) {
user = mapUser(resultSet);
}
} catch (SQLException e) {
logger.error(e); | // Path: src/main/java/com/stacksync/syncservice/db/DAOError.java
// public enum DAOError {
//
// // These errors codes correspond to HTTP codes
// // Users
// USER_NOT_FOUND(400, "User not found."), USER_NOT_AUTHORIZED(401,
// "The user is not authorized to access to this resource."),
//
// // Workspaces
// WORKSPACES_NOT_FOUND(410, "Workspaces not found."),
//
// // Files
// FILE_NOT_FOUND(404, "File or folder not found."),
//
// // Server
// INTERNAL_SERVER_ERROR(500, "Internal Server Error");
//
// private final int code;
// private final String message;
//
// DAOError(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
// }
//
// Path: src/main/java/com/stacksync/syncservice/db/UserDAO.java
// public interface UserDAO {
//
// public User findById(UUID id) throws DAOException;
//
// public User getByEmail(String email) throws DAOException;
//
// public List<User> findAll() throws DAOException;
//
// public List<User> findByItemId(Long clientFileId) throws DAOException;
//
// public void add(User user) throws DAOException;
//
// public void update(User user) throws DAOException;
//
// public void delete(UUID id) throws DAOException;
//
// public void updateAvailableQuota(User user) throws DAOException;
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoResultReturnedDAOException.java
// public class NoResultReturnedDAOException extends DAOException {
//
// private static final long serialVersionUID = -1412276333572134887L;
//
// public NoResultReturnedDAOException(DAOError error) {
// super(error);
// }
//
// public NoResultReturnedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoResultReturnedDAOException(String message) {
// super(message);
// }
//
// public NoResultReturnedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoResultReturnedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
// Path: src/main/java/com/stacksync/syncservice/db/postgresql/PostgresqlUserDAO.java
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.log4j.Logger;
import com.stacksync.commons.models.User;
import com.stacksync.syncservice.db.DAOError;
import com.stacksync.syncservice.db.UserDAO;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.exceptions.dao.NoResultReturnedDAOException;
package com.stacksync.syncservice.db.postgresql;
public class PostgresqlUserDAO extends PostgresqlDAO implements UserDAO {
private static final Logger logger = Logger.getLogger(PostgresqlUserDAO.class.getName());
public PostgresqlUserDAO(Connection connection) {
super(connection);
}
@Override
public User findById(UUID userID) throws DAOException {
ResultSet resultSet = null;
User user = null;
String query = "SELECT id, name, email, swift_user, swift_account, quota_limit, quota_used_logical, quota_used_real " + " FROM \"user1\" WHERE id = ?::uuid";
try {
resultSet = executeQuery(query, new Object[] { userID });
if (resultSet.next()) {
user = mapUser(resultSet);
}
} catch (SQLException e) {
logger.error(e); | throw new DAOException(DAOError.INTERNAL_SERVER_ERROR); |
stacksync/sync-service | src/main/java/com/stacksync/syncservice/db/postgresql/PostgresqlUserDAO.java | // Path: src/main/java/com/stacksync/syncservice/db/DAOError.java
// public enum DAOError {
//
// // These errors codes correspond to HTTP codes
// // Users
// USER_NOT_FOUND(400, "User not found."), USER_NOT_AUTHORIZED(401,
// "The user is not authorized to access to this resource."),
//
// // Workspaces
// WORKSPACES_NOT_FOUND(410, "Workspaces not found."),
//
// // Files
// FILE_NOT_FOUND(404, "File or folder not found."),
//
// // Server
// INTERNAL_SERVER_ERROR(500, "Internal Server Error");
//
// private final int code;
// private final String message;
//
// DAOError(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
// }
//
// Path: src/main/java/com/stacksync/syncservice/db/UserDAO.java
// public interface UserDAO {
//
// public User findById(UUID id) throws DAOException;
//
// public User getByEmail(String email) throws DAOException;
//
// public List<User> findAll() throws DAOException;
//
// public List<User> findByItemId(Long clientFileId) throws DAOException;
//
// public void add(User user) throws DAOException;
//
// public void update(User user) throws DAOException;
//
// public void delete(UUID id) throws DAOException;
//
// public void updateAvailableQuota(User user) throws DAOException;
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoResultReturnedDAOException.java
// public class NoResultReturnedDAOException extends DAOException {
//
// private static final long serialVersionUID = -1412276333572134887L;
//
// public NoResultReturnedDAOException(DAOError error) {
// super(error);
// }
//
// public NoResultReturnedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoResultReturnedDAOException(String message) {
// super(message);
// }
//
// public NoResultReturnedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoResultReturnedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
| import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.log4j.Logger;
import com.stacksync.commons.models.User;
import com.stacksync.syncservice.db.DAOError;
import com.stacksync.syncservice.db.UserDAO;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.exceptions.dao.NoResultReturnedDAOException; |
if (resultSet.next()) {
user = mapUser(resultSet);
}
} catch (SQLException e) {
logger.error(e);
throw new DAOException(DAOError.INTERNAL_SERVER_ERROR);
}
if (user == null){
throw new DAOException(DAOError.USER_NOT_FOUND);
}
return user;
}
@Override
public User getByEmail(String email) throws DAOException {
ResultSet resultSet = null;
User user = null;
String query = "SELECT * " + " FROM \"user1\" WHERE email = lower(?)";
try {
resultSet = executeQuery(query, new Object[] { email });
if (resultSet.next()) {
user = mapUser(resultSet);
}else{ | // Path: src/main/java/com/stacksync/syncservice/db/DAOError.java
// public enum DAOError {
//
// // These errors codes correspond to HTTP codes
// // Users
// USER_NOT_FOUND(400, "User not found."), USER_NOT_AUTHORIZED(401,
// "The user is not authorized to access to this resource."),
//
// // Workspaces
// WORKSPACES_NOT_FOUND(410, "Workspaces not found."),
//
// // Files
// FILE_NOT_FOUND(404, "File or folder not found."),
//
// // Server
// INTERNAL_SERVER_ERROR(500, "Internal Server Error");
//
// private final int code;
// private final String message;
//
// DAOError(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
// }
//
// Path: src/main/java/com/stacksync/syncservice/db/UserDAO.java
// public interface UserDAO {
//
// public User findById(UUID id) throws DAOException;
//
// public User getByEmail(String email) throws DAOException;
//
// public List<User> findAll() throws DAOException;
//
// public List<User> findByItemId(Long clientFileId) throws DAOException;
//
// public void add(User user) throws DAOException;
//
// public void update(User user) throws DAOException;
//
// public void delete(UUID id) throws DAOException;
//
// public void updateAvailableQuota(User user) throws DAOException;
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoResultReturnedDAOException.java
// public class NoResultReturnedDAOException extends DAOException {
//
// private static final long serialVersionUID = -1412276333572134887L;
//
// public NoResultReturnedDAOException(DAOError error) {
// super(error);
// }
//
// public NoResultReturnedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoResultReturnedDAOException(String message) {
// super(message);
// }
//
// public NoResultReturnedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoResultReturnedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
// Path: src/main/java/com/stacksync/syncservice/db/postgresql/PostgresqlUserDAO.java
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.log4j.Logger;
import com.stacksync.commons.models.User;
import com.stacksync.syncservice.db.DAOError;
import com.stacksync.syncservice.db.UserDAO;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.exceptions.dao.NoResultReturnedDAOException;
if (resultSet.next()) {
user = mapUser(resultSet);
}
} catch (SQLException e) {
logger.error(e);
throw new DAOException(DAOError.INTERNAL_SERVER_ERROR);
}
if (user == null){
throw new DAOException(DAOError.USER_NOT_FOUND);
}
return user;
}
@Override
public User getByEmail(String email) throws DAOException {
ResultSet resultSet = null;
User user = null;
String query = "SELECT * " + " FROM \"user1\" WHERE email = lower(?)";
try {
resultSet = executeQuery(query, new Object[] { email });
if (resultSet.next()) {
user = mapUser(resultSet);
}else{ | throw new NoResultReturnedDAOException(DAOError.USER_NOT_FOUND); |
stacksync/sync-service | src/main/java/com/stacksync/syncservice/db/postgresql/PostgresqlConnectionPool.java | // Path: src/main/java/com/stacksync/syncservice/db/ConnectionPool.java
// public abstract class ConnectionPool {
//
// public abstract Connection getConnection() throws SQLException;
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOConfigurationException.java
// public class DAOConfigurationException extends Exception {
//
// // Constants ----------------------------------------------------------------------------------
//
// private static final long serialVersionUID = 1L;
//
// // Constructors -------------------------------------------------------------------------------
//
// /**
// * Constructs a DAOConfigurationException with the given detail message.
// * @param message The detail message of the DAOConfigurationException.
// */
// public DAOConfigurationException(String message) {
// super(message);
// }
//
// /**
// * Constructs a DAOConfigurationException with the given root cause.
// * @param cause The root cause of the DAOConfigurationException.
// */
// public DAOConfigurationException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOConfigurationException with the given detail message and root cause.
// * @param message The detail message of the DAOConfigurationException.
// * @param cause The root cause of the DAOConfigurationException.
// */
// public DAOConfigurationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
| import java.sql.Connection;
import java.sql.SQLException;
import org.postgresql.ds.PGPoolingDataSource;
import com.stacksync.syncservice.db.ConnectionPool;
import com.stacksync.syncservice.exceptions.dao.DAOConfigurationException; | package com.stacksync.syncservice.db.postgresql;
public class PostgresqlConnectionPool extends ConnectionPool {
private PGPoolingDataSource source;
public PostgresqlConnectionPool(String host, int port, String database, String username, String password, int initialConns, int maxConns) | // Path: src/main/java/com/stacksync/syncservice/db/ConnectionPool.java
// public abstract class ConnectionPool {
//
// public abstract Connection getConnection() throws SQLException;
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOConfigurationException.java
// public class DAOConfigurationException extends Exception {
//
// // Constants ----------------------------------------------------------------------------------
//
// private static final long serialVersionUID = 1L;
//
// // Constructors -------------------------------------------------------------------------------
//
// /**
// * Constructs a DAOConfigurationException with the given detail message.
// * @param message The detail message of the DAOConfigurationException.
// */
// public DAOConfigurationException(String message) {
// super(message);
// }
//
// /**
// * Constructs a DAOConfigurationException with the given root cause.
// * @param cause The root cause of the DAOConfigurationException.
// */
// public DAOConfigurationException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOConfigurationException with the given detail message and root cause.
// * @param message The detail message of the DAOConfigurationException.
// * @param cause The root cause of the DAOConfigurationException.
// */
// public DAOConfigurationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
// Path: src/main/java/com/stacksync/syncservice/db/postgresql/PostgresqlConnectionPool.java
import java.sql.Connection;
import java.sql.SQLException;
import org.postgresql.ds.PGPoolingDataSource;
import com.stacksync.syncservice.db.ConnectionPool;
import com.stacksync.syncservice.exceptions.dao.DAOConfigurationException;
package com.stacksync.syncservice.db.postgresql;
public class PostgresqlConnectionPool extends ConnectionPool {
private PGPoolingDataSource source;
public PostgresqlConnectionPool(String host, int port, String database, String username, String password, int initialConns, int maxConns) | throws DAOConfigurationException { |
stacksync/sync-service | src/main/java/com/stacksync/syncservice/db/postgresql/PostgresqlDAO.java | // Path: src/main/java/com/stacksync/syncservice/db/DAOUtil.java
// public static PreparedStatement prepareStatement(Connection connection, String sql, boolean returnGeneratedKeys,
// Object... values) throws SQLException {
// PreparedStatement preparedStatement = connection.prepareStatement(sql,
// returnGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS);
// setValues(preparedStatement, values);
// return preparedStatement;
// }
//
// Path: src/main/java/com/stacksync/syncservice/db/DAOError.java
// public enum DAOError {
//
// // These errors codes correspond to HTTP codes
// // Users
// USER_NOT_FOUND(400, "User not found."), USER_NOT_AUTHORIZED(401,
// "The user is not authorized to access to this resource."),
//
// // Workspaces
// WORKSPACES_NOT_FOUND(410, "Workspaces not found."),
//
// // Files
// FILE_NOT_FOUND(404, "File or folder not found."),
//
// // Server
// INTERNAL_SERVER_ERROR(500, "Internal Server Error");
//
// private final int code;
// private final String message;
//
// DAOError(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoRowsAffectedDAOException.java
// public class NoRowsAffectedDAOException extends DAOException {
//
// private static final long serialVersionUID = 356684827372558709L;
//
// public NoRowsAffectedDAOException(DAOError error) {
// super(error);
// }
//
// public NoRowsAffectedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoRowsAffectedDAOException(String message) {
// super(message);
// }
//
// public NoRowsAffectedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoRowsAffectedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
| import static com.stacksync.syncservice.db.DAOUtil.prepareStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import com.stacksync.syncservice.db.DAOError;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.exceptions.dao.NoRowsAffectedDAOException; | package com.stacksync.syncservice.db.postgresql;
public class PostgresqlDAO {
private static final Logger logger = Logger.getLogger(PostgresqlDAO.class.getName());
protected Connection connection;
public PostgresqlDAO(Connection connection) {
this.connection = connection;
}
| // Path: src/main/java/com/stacksync/syncservice/db/DAOUtil.java
// public static PreparedStatement prepareStatement(Connection connection, String sql, boolean returnGeneratedKeys,
// Object... values) throws SQLException {
// PreparedStatement preparedStatement = connection.prepareStatement(sql,
// returnGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS);
// setValues(preparedStatement, values);
// return preparedStatement;
// }
//
// Path: src/main/java/com/stacksync/syncservice/db/DAOError.java
// public enum DAOError {
//
// // These errors codes correspond to HTTP codes
// // Users
// USER_NOT_FOUND(400, "User not found."), USER_NOT_AUTHORIZED(401,
// "The user is not authorized to access to this resource."),
//
// // Workspaces
// WORKSPACES_NOT_FOUND(410, "Workspaces not found."),
//
// // Files
// FILE_NOT_FOUND(404, "File or folder not found."),
//
// // Server
// INTERNAL_SERVER_ERROR(500, "Internal Server Error");
//
// private final int code;
// private final String message;
//
// DAOError(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoRowsAffectedDAOException.java
// public class NoRowsAffectedDAOException extends DAOException {
//
// private static final long serialVersionUID = 356684827372558709L;
//
// public NoRowsAffectedDAOException(DAOError error) {
// super(error);
// }
//
// public NoRowsAffectedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoRowsAffectedDAOException(String message) {
// super(message);
// }
//
// public NoRowsAffectedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoRowsAffectedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
// Path: src/main/java/com/stacksync/syncservice/db/postgresql/PostgresqlDAO.java
import static com.stacksync.syncservice.db.DAOUtil.prepareStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import com.stacksync.syncservice.db.DAOError;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.exceptions.dao.NoRowsAffectedDAOException;
package com.stacksync.syncservice.db.postgresql;
public class PostgresqlDAO {
private static final Logger logger = Logger.getLogger(PostgresqlDAO.class.getName());
protected Connection connection;
public PostgresqlDAO(Connection connection) {
this.connection = connection;
}
| protected ResultSet executeQuery(String query, Object[] values) throws DAOException { |
stacksync/sync-service | src/main/java/com/stacksync/syncservice/db/postgresql/PostgresqlDAO.java | // Path: src/main/java/com/stacksync/syncservice/db/DAOUtil.java
// public static PreparedStatement prepareStatement(Connection connection, String sql, boolean returnGeneratedKeys,
// Object... values) throws SQLException {
// PreparedStatement preparedStatement = connection.prepareStatement(sql,
// returnGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS);
// setValues(preparedStatement, values);
// return preparedStatement;
// }
//
// Path: src/main/java/com/stacksync/syncservice/db/DAOError.java
// public enum DAOError {
//
// // These errors codes correspond to HTTP codes
// // Users
// USER_NOT_FOUND(400, "User not found."), USER_NOT_AUTHORIZED(401,
// "The user is not authorized to access to this resource."),
//
// // Workspaces
// WORKSPACES_NOT_FOUND(410, "Workspaces not found."),
//
// // Files
// FILE_NOT_FOUND(404, "File or folder not found."),
//
// // Server
// INTERNAL_SERVER_ERROR(500, "Internal Server Error");
//
// private final int code;
// private final String message;
//
// DAOError(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoRowsAffectedDAOException.java
// public class NoRowsAffectedDAOException extends DAOException {
//
// private static final long serialVersionUID = 356684827372558709L;
//
// public NoRowsAffectedDAOException(DAOError error) {
// super(error);
// }
//
// public NoRowsAffectedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoRowsAffectedDAOException(String message) {
// super(message);
// }
//
// public NoRowsAffectedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoRowsAffectedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
| import static com.stacksync.syncservice.db.DAOUtil.prepareStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import com.stacksync.syncservice.db.DAOError;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.exceptions.dao.NoRowsAffectedDAOException; | package com.stacksync.syncservice.db.postgresql;
public class PostgresqlDAO {
private static final Logger logger = Logger.getLogger(PostgresqlDAO.class.getName());
protected Connection connection;
public PostgresqlDAO(Connection connection) {
this.connection = connection;
}
protected ResultSet executeQuery(String query, Object[] values) throws DAOException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try { | // Path: src/main/java/com/stacksync/syncservice/db/DAOUtil.java
// public static PreparedStatement prepareStatement(Connection connection, String sql, boolean returnGeneratedKeys,
// Object... values) throws SQLException {
// PreparedStatement preparedStatement = connection.prepareStatement(sql,
// returnGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS);
// setValues(preparedStatement, values);
// return preparedStatement;
// }
//
// Path: src/main/java/com/stacksync/syncservice/db/DAOError.java
// public enum DAOError {
//
// // These errors codes correspond to HTTP codes
// // Users
// USER_NOT_FOUND(400, "User not found."), USER_NOT_AUTHORIZED(401,
// "The user is not authorized to access to this resource."),
//
// // Workspaces
// WORKSPACES_NOT_FOUND(410, "Workspaces not found."),
//
// // Files
// FILE_NOT_FOUND(404, "File or folder not found."),
//
// // Server
// INTERNAL_SERVER_ERROR(500, "Internal Server Error");
//
// private final int code;
// private final String message;
//
// DAOError(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoRowsAffectedDAOException.java
// public class NoRowsAffectedDAOException extends DAOException {
//
// private static final long serialVersionUID = 356684827372558709L;
//
// public NoRowsAffectedDAOException(DAOError error) {
// super(error);
// }
//
// public NoRowsAffectedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoRowsAffectedDAOException(String message) {
// super(message);
// }
//
// public NoRowsAffectedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoRowsAffectedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
// Path: src/main/java/com/stacksync/syncservice/db/postgresql/PostgresqlDAO.java
import static com.stacksync.syncservice.db.DAOUtil.prepareStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import com.stacksync.syncservice.db.DAOError;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.exceptions.dao.NoRowsAffectedDAOException;
package com.stacksync.syncservice.db.postgresql;
public class PostgresqlDAO {
private static final Logger logger = Logger.getLogger(PostgresqlDAO.class.getName());
protected Connection connection;
public PostgresqlDAO(Connection connection) {
this.connection = connection;
}
protected ResultSet executeQuery(String query, Object[] values) throws DAOException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try { | preparedStatement = prepareStatement(connection, query, false, values); |
stacksync/sync-service | src/main/java/com/stacksync/syncservice/db/postgresql/PostgresqlDAO.java | // Path: src/main/java/com/stacksync/syncservice/db/DAOUtil.java
// public static PreparedStatement prepareStatement(Connection connection, String sql, boolean returnGeneratedKeys,
// Object... values) throws SQLException {
// PreparedStatement preparedStatement = connection.prepareStatement(sql,
// returnGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS);
// setValues(preparedStatement, values);
// return preparedStatement;
// }
//
// Path: src/main/java/com/stacksync/syncservice/db/DAOError.java
// public enum DAOError {
//
// // These errors codes correspond to HTTP codes
// // Users
// USER_NOT_FOUND(400, "User not found."), USER_NOT_AUTHORIZED(401,
// "The user is not authorized to access to this resource."),
//
// // Workspaces
// WORKSPACES_NOT_FOUND(410, "Workspaces not found."),
//
// // Files
// FILE_NOT_FOUND(404, "File or folder not found."),
//
// // Server
// INTERNAL_SERVER_ERROR(500, "Internal Server Error");
//
// private final int code;
// private final String message;
//
// DAOError(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoRowsAffectedDAOException.java
// public class NoRowsAffectedDAOException extends DAOException {
//
// private static final long serialVersionUID = 356684827372558709L;
//
// public NoRowsAffectedDAOException(DAOError error) {
// super(error);
// }
//
// public NoRowsAffectedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoRowsAffectedDAOException(String message) {
// super(message);
// }
//
// public NoRowsAffectedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoRowsAffectedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
| import static com.stacksync.syncservice.db.DAOUtil.prepareStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import com.stacksync.syncservice.db.DAOError;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.exceptions.dao.NoRowsAffectedDAOException; | package com.stacksync.syncservice.db.postgresql;
public class PostgresqlDAO {
private static final Logger logger = Logger.getLogger(PostgresqlDAO.class.getName());
protected Connection connection;
public PostgresqlDAO(Connection connection) {
this.connection = connection;
}
protected ResultSet executeQuery(String query, Object[] values) throws DAOException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
preparedStatement = prepareStatement(connection, query, false, values);
resultSet = preparedStatement.executeQuery();
} catch (SQLException e) {
logger.error(e); | // Path: src/main/java/com/stacksync/syncservice/db/DAOUtil.java
// public static PreparedStatement prepareStatement(Connection connection, String sql, boolean returnGeneratedKeys,
// Object... values) throws SQLException {
// PreparedStatement preparedStatement = connection.prepareStatement(sql,
// returnGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS);
// setValues(preparedStatement, values);
// return preparedStatement;
// }
//
// Path: src/main/java/com/stacksync/syncservice/db/DAOError.java
// public enum DAOError {
//
// // These errors codes correspond to HTTP codes
// // Users
// USER_NOT_FOUND(400, "User not found."), USER_NOT_AUTHORIZED(401,
// "The user is not authorized to access to this resource."),
//
// // Workspaces
// WORKSPACES_NOT_FOUND(410, "Workspaces not found."),
//
// // Files
// FILE_NOT_FOUND(404, "File or folder not found."),
//
// // Server
// INTERNAL_SERVER_ERROR(500, "Internal Server Error");
//
// private final int code;
// private final String message;
//
// DAOError(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoRowsAffectedDAOException.java
// public class NoRowsAffectedDAOException extends DAOException {
//
// private static final long serialVersionUID = 356684827372558709L;
//
// public NoRowsAffectedDAOException(DAOError error) {
// super(error);
// }
//
// public NoRowsAffectedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoRowsAffectedDAOException(String message) {
// super(message);
// }
//
// public NoRowsAffectedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoRowsAffectedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
// Path: src/main/java/com/stacksync/syncservice/db/postgresql/PostgresqlDAO.java
import static com.stacksync.syncservice.db.DAOUtil.prepareStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import com.stacksync.syncservice.db.DAOError;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.exceptions.dao.NoRowsAffectedDAOException;
package com.stacksync.syncservice.db.postgresql;
public class PostgresqlDAO {
private static final Logger logger = Logger.getLogger(PostgresqlDAO.class.getName());
protected Connection connection;
public PostgresqlDAO(Connection connection) {
this.connection = connection;
}
protected ResultSet executeQuery(String query, Object[] values) throws DAOException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
preparedStatement = prepareStatement(connection, query, false, values);
resultSet = preparedStatement.executeQuery();
} catch (SQLException e) {
logger.error(e); | throw new DAOException(e, DAOError.INTERNAL_SERVER_ERROR); |
stacksync/sync-service | src/main/java/com/stacksync/syncservice/db/postgresql/PostgresqlDAO.java | // Path: src/main/java/com/stacksync/syncservice/db/DAOUtil.java
// public static PreparedStatement prepareStatement(Connection connection, String sql, boolean returnGeneratedKeys,
// Object... values) throws SQLException {
// PreparedStatement preparedStatement = connection.prepareStatement(sql,
// returnGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS);
// setValues(preparedStatement, values);
// return preparedStatement;
// }
//
// Path: src/main/java/com/stacksync/syncservice/db/DAOError.java
// public enum DAOError {
//
// // These errors codes correspond to HTTP codes
// // Users
// USER_NOT_FOUND(400, "User not found."), USER_NOT_AUTHORIZED(401,
// "The user is not authorized to access to this resource."),
//
// // Workspaces
// WORKSPACES_NOT_FOUND(410, "Workspaces not found."),
//
// // Files
// FILE_NOT_FOUND(404, "File or folder not found."),
//
// // Server
// INTERNAL_SERVER_ERROR(500, "Internal Server Error");
//
// private final int code;
// private final String message;
//
// DAOError(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoRowsAffectedDAOException.java
// public class NoRowsAffectedDAOException extends DAOException {
//
// private static final long serialVersionUID = 356684827372558709L;
//
// public NoRowsAffectedDAOException(DAOError error) {
// super(error);
// }
//
// public NoRowsAffectedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoRowsAffectedDAOException(String message) {
// super(message);
// }
//
// public NoRowsAffectedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoRowsAffectedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
| import static com.stacksync.syncservice.db.DAOUtil.prepareStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import com.stacksync.syncservice.db.DAOError;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.exceptions.dao.NoRowsAffectedDAOException; | package com.stacksync.syncservice.db.postgresql;
public class PostgresqlDAO {
private static final Logger logger = Logger.getLogger(PostgresqlDAO.class.getName());
protected Connection connection;
public PostgresqlDAO(Connection connection) {
this.connection = connection;
}
protected ResultSet executeQuery(String query, Object[] values) throws DAOException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
preparedStatement = prepareStatement(connection, query, false, values);
resultSet = preparedStatement.executeQuery();
} catch (SQLException e) {
logger.error(e);
throw new DAOException(e, DAOError.INTERNAL_SERVER_ERROR);
}
return resultSet;
}
protected Object executeUpdate(String query, Object[] values) throws DAOException {
Object key = null;
PreparedStatement preparedStatement = null;
ResultSet generatedKeys = null;
try {
preparedStatement = prepareStatement(connection, query, true, values);
int affectedRows = preparedStatement.executeUpdate();
if (affectedRows == 0) { | // Path: src/main/java/com/stacksync/syncservice/db/DAOUtil.java
// public static PreparedStatement prepareStatement(Connection connection, String sql, boolean returnGeneratedKeys,
// Object... values) throws SQLException {
// PreparedStatement preparedStatement = connection.prepareStatement(sql,
// returnGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS);
// setValues(preparedStatement, values);
// return preparedStatement;
// }
//
// Path: src/main/java/com/stacksync/syncservice/db/DAOError.java
// public enum DAOError {
//
// // These errors codes correspond to HTTP codes
// // Users
// USER_NOT_FOUND(400, "User not found."), USER_NOT_AUTHORIZED(401,
// "The user is not authorized to access to this resource."),
//
// // Workspaces
// WORKSPACES_NOT_FOUND(410, "Workspaces not found."),
//
// // Files
// FILE_NOT_FOUND(404, "File or folder not found."),
//
// // Server
// INTERNAL_SERVER_ERROR(500, "Internal Server Error");
//
// private final int code;
// private final String message;
//
// DAOError(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoRowsAffectedDAOException.java
// public class NoRowsAffectedDAOException extends DAOException {
//
// private static final long serialVersionUID = 356684827372558709L;
//
// public NoRowsAffectedDAOException(DAOError error) {
// super(error);
// }
//
// public NoRowsAffectedDAOException(Exception e, DAOError error) {
// super(e, error);
// }
//
// public NoRowsAffectedDAOException(String message) {
// super(message);
// }
//
// public NoRowsAffectedDAOException(Throwable cause) {
// super(cause);
// }
//
// public NoRowsAffectedDAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
// Path: src/main/java/com/stacksync/syncservice/db/postgresql/PostgresqlDAO.java
import static com.stacksync.syncservice.db.DAOUtil.prepareStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import com.stacksync.syncservice.db.DAOError;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.exceptions.dao.NoRowsAffectedDAOException;
package com.stacksync.syncservice.db.postgresql;
public class PostgresqlDAO {
private static final Logger logger = Logger.getLogger(PostgresqlDAO.class.getName());
protected Connection connection;
public PostgresqlDAO(Connection connection) {
this.connection = connection;
}
protected ResultSet executeQuery(String query, Object[] values) throws DAOException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
preparedStatement = prepareStatement(connection, query, false, values);
resultSet = preparedStatement.executeQuery();
} catch (SQLException e) {
logger.error(e);
throw new DAOException(e, DAOError.INTERNAL_SERVER_ERROR);
}
return resultSet;
}
protected Object executeUpdate(String query, Object[] values) throws DAOException {
Object key = null;
PreparedStatement preparedStatement = null;
ResultSet generatedKeys = null;
try {
preparedStatement = prepareStatement(connection, query, true, values);
int affectedRows = preparedStatement.executeUpdate();
if (affectedRows == 0) { | throw new NoRowsAffectedDAOException("Execute update error: no rows affected."); |
stacksync/sync-service | src/test/java/com/stacksync/syncservice/test/benchmark/omq/TestGetWorkspaces.java | // Path: src/test/java/com/stacksync/syncservice/test/benchmark/Constants.java
// public class Constants {
// public static UUID USER = new UUID(1, 1);
// public static UUID WORKSPACE_ID = new UUID(1, 1);
// public static String REQUEST_ID = "Benchmark";
// public static UUID DEVICE_ID = new UUID(1, 1);
// public static Integer XMLRPC_PORT = com.stacksync.syncservice.util.Constants.XMLRPC_PORT;
// }
| import java.util.List;
import java.util.Properties;
import omq.common.broker.Broker;
import com.stacksync.commons.models.Workspace;
import com.stacksync.commons.omq.ISyncService;
import com.stacksync.commons.requests.GetWorkspacesRequest;
import com.stacksync.syncservice.test.benchmark.Constants; | package com.stacksync.syncservice.test.benchmark.omq;
public class TestGetWorkspaces {
public static void main(String[] args) throws Exception {
Properties env = RabbitConfig.getProperties();
Broker broker = new Broker(env);
ISyncService server = broker.lookup(ISyncService.class.getSimpleName(), ISyncService.class);
long startTotal = System.currentTimeMillis(); | // Path: src/test/java/com/stacksync/syncservice/test/benchmark/Constants.java
// public class Constants {
// public static UUID USER = new UUID(1, 1);
// public static UUID WORKSPACE_ID = new UUID(1, 1);
// public static String REQUEST_ID = "Benchmark";
// public static UUID DEVICE_ID = new UUID(1, 1);
// public static Integer XMLRPC_PORT = com.stacksync.syncservice.util.Constants.XMLRPC_PORT;
// }
// Path: src/test/java/com/stacksync/syncservice/test/benchmark/omq/TestGetWorkspaces.java
import java.util.List;
import java.util.Properties;
import omq.common.broker.Broker;
import com.stacksync.commons.models.Workspace;
import com.stacksync.commons.omq.ISyncService;
import com.stacksync.commons.requests.GetWorkspacesRequest;
import com.stacksync.syncservice.test.benchmark.Constants;
package com.stacksync.syncservice.test.benchmark.omq;
public class TestGetWorkspaces {
public static void main(String[] args) throws Exception {
Properties env = RabbitConfig.getProperties();
Broker broker = new Broker(env);
ISyncService server = broker.lookup(ISyncService.class.getSimpleName(), ISyncService.class);
long startTotal = System.currentTimeMillis(); | GetWorkspacesRequest request = new GetWorkspacesRequest(Constants.USER); |
stacksync/sync-service | src/test/java/com/stacksync/syncservice/test/benchmark/DBBenchmark.java | // Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/test/java/com/stacksync/syncservice/test/benchmark/db/DatabaseHelper.java
// public class DatabaseHelper {
// private ConnectionPool pool;
// private Connection connection;
// private WorkspaceDAO workspaceDAO;
// private UserDAO userDao;
// private DeviceDAO deviceDao;
// private ItemDAO objectDao;
// private ItemVersionDAO oversionDao;
//
// public DatabaseHelper() throws Exception {
// Config.loadProperties();
// Thread.sleep(100);
//
// String datasource = Config.getDatasource();
//
// pool = ConnectionPoolFactory.getConnectionPool(datasource);
// connection = pool.getConnection();
//
// DAOFactory factory = new DAOFactory(datasource);
//
// workspaceDAO = factory.getWorkspaceDao(connection);
// userDao = factory.getUserDao(connection);
// deviceDao = factory.getDeviceDAO(connection);
// objectDao = factory.getItemDAO(connection);
// oversionDao = factory.getItemVersionDAO(connection);
// }
//
// public void storeObjects(List<Item> objectsLevel) throws IllegalArgumentException, DAOException {
//
// long numChunk = 0, totalTimeChunk = 0;
// long numVersion = 0, totalTimeVersion = 0;
// long numObject = 0, totalTimeObject = 0;
//
// long startTotal = System.currentTimeMillis();
// for (Item object : objectsLevel) {
// // System.out.println("DatabaseHelper -- Put Object -> " + object);
// long startObjectTotal = System.currentTimeMillis();
//
// objectDao.put(object);
// for (ItemVersion version : object.getVersions()) {
//
// long startVersionTotal = System.currentTimeMillis();
// // System.out.println("DatabaseHelper -- Put Version -> " +
// // version);
// oversionDao.add(version);
//
// long startChunkTotal = System.currentTimeMillis();
//
// if (!version.getChunks().isEmpty()) {
// oversionDao.insertChunks(version.getChunks(), version.getId());
// }
//
// totalTimeChunk += System.currentTimeMillis() - startChunkTotal;
//
// totalTimeVersion += System.currentTimeMillis() - startVersionTotal;
// // System.out.println("---- Total Version time --> " +
// // totalVersionTime + " ms");
// numVersion++;
// }
//
// totalTimeObject += System.currentTimeMillis() - startObjectTotal;
// numObject++;
// }
//
// if (numChunk > 0) {
// System.out.println("-------- AVG avg Chunk(" + numChunk + ") time --> " + (totalTimeChunk / numChunk) + " ms");
// }
//
// if (numVersion > 0) {
// System.out.println("---- AVG Version(" + numVersion + ") time --> " + (totalTimeVersion / numVersion) + " ms");
// }
//
// if (numObject > 0) {
// System.out.println("AVG Object(" + numObject + ") time --> " + (totalTimeObject / numObject) + " ms");
// }
//
// long totalTime = System.currentTimeMillis() - startTotal;
//
// System.out.println("Total level time --> " + totalTime + " ms");
//
// }
//
// public void addUser(User user) throws IllegalArgumentException, DAOException {
// userDao.add(user);
// }
//
// public void addWorkspace(User user, Workspace workspace) throws IllegalArgumentException, DAOException {
// workspaceDAO.add(workspace);
// workspaceDAO.addUser(user, workspace);
// }
//
// public void addDevice(Device device) throws IllegalArgumentException, DAOException {
// deviceDao.add(device);
// }
//
// public void deleteUser(UUID id) throws DAOException {
// userDao.delete(id);
// }
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import com.stacksync.commons.models.Device;
import com.stacksync.commons.models.Item;
import com.stacksync.commons.models.User;
import com.stacksync.commons.models.Workspace;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.test.benchmark.db.DatabaseHelper; | package com.stacksync.syncservice.test.benchmark;
public class DBBenchmark extends Thread {
private static final int LEVELS = 3;
private static final int USERS = 30;
private String name;
private int numUser;
private int fsDepth;
private MetadataGenerator metadataGen; | // Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
// public class DAOException extends Exception {
//
// private static final long serialVersionUID = 1L;
// private DAOError error;
// /**
// * Constructs a DAOException with the given detail message.
// * @param message The detail message of the DAOException.
// */
// public DAOException(DAOError error) {
// super(error.getMessage());
// this.error = error;
// }
//
// public DAOException(Exception e, DAOError error) {
// super(e);
// this.error = error;
// }
//
// public DAOException(String message) {
// super(message);
// }
//
// public DAOError getError(){
// return this.error;
// }
// /**
// * Constructs a DAOException with the given root cause.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(Throwable cause) {
// super(cause);
// }
//
// /**
// * Constructs a DAOException with the given detail message and root cause.
// * @param message The detail message of the DAOException.
// * @param cause The root cause of the DAOException.
// */
// public DAOException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/test/java/com/stacksync/syncservice/test/benchmark/db/DatabaseHelper.java
// public class DatabaseHelper {
// private ConnectionPool pool;
// private Connection connection;
// private WorkspaceDAO workspaceDAO;
// private UserDAO userDao;
// private DeviceDAO deviceDao;
// private ItemDAO objectDao;
// private ItemVersionDAO oversionDao;
//
// public DatabaseHelper() throws Exception {
// Config.loadProperties();
// Thread.sleep(100);
//
// String datasource = Config.getDatasource();
//
// pool = ConnectionPoolFactory.getConnectionPool(datasource);
// connection = pool.getConnection();
//
// DAOFactory factory = new DAOFactory(datasource);
//
// workspaceDAO = factory.getWorkspaceDao(connection);
// userDao = factory.getUserDao(connection);
// deviceDao = factory.getDeviceDAO(connection);
// objectDao = factory.getItemDAO(connection);
// oversionDao = factory.getItemVersionDAO(connection);
// }
//
// public void storeObjects(List<Item> objectsLevel) throws IllegalArgumentException, DAOException {
//
// long numChunk = 0, totalTimeChunk = 0;
// long numVersion = 0, totalTimeVersion = 0;
// long numObject = 0, totalTimeObject = 0;
//
// long startTotal = System.currentTimeMillis();
// for (Item object : objectsLevel) {
// // System.out.println("DatabaseHelper -- Put Object -> " + object);
// long startObjectTotal = System.currentTimeMillis();
//
// objectDao.put(object);
// for (ItemVersion version : object.getVersions()) {
//
// long startVersionTotal = System.currentTimeMillis();
// // System.out.println("DatabaseHelper -- Put Version -> " +
// // version);
// oversionDao.add(version);
//
// long startChunkTotal = System.currentTimeMillis();
//
// if (!version.getChunks().isEmpty()) {
// oversionDao.insertChunks(version.getChunks(), version.getId());
// }
//
// totalTimeChunk += System.currentTimeMillis() - startChunkTotal;
//
// totalTimeVersion += System.currentTimeMillis() - startVersionTotal;
// // System.out.println("---- Total Version time --> " +
// // totalVersionTime + " ms");
// numVersion++;
// }
//
// totalTimeObject += System.currentTimeMillis() - startObjectTotal;
// numObject++;
// }
//
// if (numChunk > 0) {
// System.out.println("-------- AVG avg Chunk(" + numChunk + ") time --> " + (totalTimeChunk / numChunk) + " ms");
// }
//
// if (numVersion > 0) {
// System.out.println("---- AVG Version(" + numVersion + ") time --> " + (totalTimeVersion / numVersion) + " ms");
// }
//
// if (numObject > 0) {
// System.out.println("AVG Object(" + numObject + ") time --> " + (totalTimeObject / numObject) + " ms");
// }
//
// long totalTime = System.currentTimeMillis() - startTotal;
//
// System.out.println("Total level time --> " + totalTime + " ms");
//
// }
//
// public void addUser(User user) throws IllegalArgumentException, DAOException {
// userDao.add(user);
// }
//
// public void addWorkspace(User user, Workspace workspace) throws IllegalArgumentException, DAOException {
// workspaceDAO.add(workspace);
// workspaceDAO.addUser(user, workspace);
// }
//
// public void addDevice(Device device) throws IllegalArgumentException, DAOException {
// deviceDao.add(device);
// }
//
// public void deleteUser(UUID id) throws DAOException {
// userDao.delete(id);
// }
// }
// Path: src/test/java/com/stacksync/syncservice/test/benchmark/DBBenchmark.java
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import com.stacksync.commons.models.Device;
import com.stacksync.commons.models.Item;
import com.stacksync.commons.models.User;
import com.stacksync.commons.models.Workspace;
import com.stacksync.syncservice.exceptions.dao.DAOException;
import com.stacksync.syncservice.test.benchmark.db.DatabaseHelper;
package com.stacksync.syncservice.test.benchmark;
public class DBBenchmark extends Thread {
private static final int LEVELS = 3;
private static final int USERS = 30;
private String name;
private int numUser;
private int fsDepth;
private MetadataGenerator metadataGen; | private DatabaseHelper dbHelper; |
stacksync/sync-service | src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java | // Path: src/main/java/com/stacksync/syncservice/db/DAOError.java
// public enum DAOError {
//
// // These errors codes correspond to HTTP codes
// // Users
// USER_NOT_FOUND(400, "User not found."), USER_NOT_AUTHORIZED(401,
// "The user is not authorized to access to this resource."),
//
// // Workspaces
// WORKSPACES_NOT_FOUND(410, "Workspaces not found."),
//
// // Files
// FILE_NOT_FOUND(404, "File or folder not found."),
//
// // Server
// INTERNAL_SERVER_ERROR(500, "Internal Server Error");
//
// private final int code;
// private final String message;
//
// DAOError(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
// }
| import com.stacksync.syncservice.db.DAOError; | package com.stacksync.syncservice.exceptions.dao;
/**
* This class represents a generic DAO exception. It should wrap any exception on the database level
* , such as SQLExceptions.
*/
public class DAOException extends Exception {
private static final long serialVersionUID = 1L; | // Path: src/main/java/com/stacksync/syncservice/db/DAOError.java
// public enum DAOError {
//
// // These errors codes correspond to HTTP codes
// // Users
// USER_NOT_FOUND(400, "User not found."), USER_NOT_AUTHORIZED(401,
// "The user is not authorized to access to this resource."),
//
// // Workspaces
// WORKSPACES_NOT_FOUND(410, "Workspaces not found."),
//
// // Files
// FILE_NOT_FOUND(404, "File or folder not found."),
//
// // Server
// INTERNAL_SERVER_ERROR(500, "Internal Server Error");
//
// private final int code;
// private final String message;
//
// DAOError(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
// }
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/DAOException.java
import com.stacksync.syncservice.db.DAOError;
package com.stacksync.syncservice.exceptions.dao;
/**
* This class represents a generic DAO exception. It should wrap any exception on the database level
* , such as SQLExceptions.
*/
public class DAOException extends Exception {
private static final long serialVersionUID = 1L; | private DAOError error; |
stacksync/sync-service | src/main/java/com/stacksync/syncservice/exceptions/dao/NoResultReturnedDAOException.java | // Path: src/main/java/com/stacksync/syncservice/db/DAOError.java
// public enum DAOError {
//
// // These errors codes correspond to HTTP codes
// // Users
// USER_NOT_FOUND(400, "User not found."), USER_NOT_AUTHORIZED(401,
// "The user is not authorized to access to this resource."),
//
// // Workspaces
// WORKSPACES_NOT_FOUND(410, "Workspaces not found."),
//
// // Files
// FILE_NOT_FOUND(404, "File or folder not found."),
//
// // Server
// INTERNAL_SERVER_ERROR(500, "Internal Server Error");
//
// private final int code;
// private final String message;
//
// DAOError(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
// }
| import com.stacksync.syncservice.db.DAOError; | package com.stacksync.syncservice.exceptions.dao;
public class NoResultReturnedDAOException extends DAOException {
private static final long serialVersionUID = -1412276333572134887L;
| // Path: src/main/java/com/stacksync/syncservice/db/DAOError.java
// public enum DAOError {
//
// // These errors codes correspond to HTTP codes
// // Users
// USER_NOT_FOUND(400, "User not found."), USER_NOT_AUTHORIZED(401,
// "The user is not authorized to access to this resource."),
//
// // Workspaces
// WORKSPACES_NOT_FOUND(410, "Workspaces not found."),
//
// // Files
// FILE_NOT_FOUND(404, "File or folder not found."),
//
// // Server
// INTERNAL_SERVER_ERROR(500, "Internal Server Error");
//
// private final int code;
// private final String message;
//
// DAOError(int code, String message) {
// this.code = code;
// this.message = message;
// }
//
// public int getCode() {
// return code;
// }
//
// public String getMessage() {
// return message;
// }
// }
// Path: src/main/java/com/stacksync/syncservice/exceptions/dao/NoResultReturnedDAOException.java
import com.stacksync.syncservice.db.DAOError;
package com.stacksync.syncservice.exceptions.dao;
public class NoResultReturnedDAOException extends DAOException {
private static final long serialVersionUID = -1412276333572134887L;
| public NoResultReturnedDAOException(DAOError error) { |
dmanchester/playfop | library/src/main/java/com/dmanchester/playfop/japi/PlayFopComponents.java | // Path: library/src/main/java/com/dmanchester/playfop/jinternal/PlayFopImpl.java
// @Singleton
// public class PlayFopImpl implements PlayFop {
//
// private static final ProcessOptions DEFAULT_PROCESS_OPTIONS = new ProcessOptions.Builder().build();
//
// private com.dmanchester.playfop.sapi.PlayFop playFopScala = new com.dmanchester.playfop.sinternal.PlayFopImpl();
//
// @Override
// public byte[] processTwirlXml(Xml xslfo, String outputFormat) {
//
// return processTwirlXml(xslfo, outputFormat, DEFAULT_PROCESS_OPTIONS);
// }
//
// @Override
// public byte[] processTwirlXml(Xml xslfo, String outputFormat, ProcessOptions processOptions) {
//
// Function1<FOUserAgent, BoxedUnit> blockAsFunction = new BlockAsFunction(processOptions.getFoUserAgentBlock());
//
// return playFopScala.processTwirlXml(xslfo, outputFormat, processOptions.isAutoDetectFontsForPDF(), blockAsFunction);
// }
//
// @Override
// public byte[] processStringXml(String xslfo, String outputFormat) {
//
// return processStringXml(xslfo, outputFormat, DEFAULT_PROCESS_OPTIONS);
// }
//
// @Override
// public byte[] processStringXml(String xslfo, String outputFormat, ProcessOptions processOptions) {
//
// Function1<FOUserAgent, BoxedUnit> blockAsFunction = new BlockAsFunction(processOptions.getFoUserAgentBlock());
//
// return playFopScala.processStringXml(xslfo, outputFormat, processOptions.isAutoDetectFontsForPDF(), blockAsFunction);
// }
//
// @Override
// public Fop newFop(String outputFormat, OutputStream output) {
//
// return newFop(outputFormat, output, DEFAULT_PROCESS_OPTIONS);
// }
//
// @Override
// public Fop newFop(String outputFormat, OutputStream output, ProcessOptions processOptions) {
//
// Function1<FOUserAgent, BoxedUnit> blockAsFunction = new BlockAsFunction(processOptions.getFoUserAgentBlock());
//
// return playFopScala.newFop(outputFormat, output, processOptions.isAutoDetectFontsForPDF(), blockAsFunction);
// }
//
// private static class BlockAsFunction extends AbstractFunction1<FOUserAgent, BoxedUnit> {
//
// private FOUserAgentBlock block;
//
// public BlockAsFunction(FOUserAgentBlock block) {
// this.block = block;
// }
//
// @Override
// public BoxedUnit apply(FOUserAgent foUserAgent) {
// block.withFOUserAgent(foUserAgent);
// return BoxedUnit.UNIT;
// }
// }
// }
| import com.dmanchester.playfop.jinternal.PlayFopImpl; | package com.dmanchester.playfop.japi;
/**
* An interface for dependency-injecting PlayFOP into Java applications at
* compile time.
*/
public interface PlayFopComponents {
default PlayFop playFop() { | // Path: library/src/main/java/com/dmanchester/playfop/jinternal/PlayFopImpl.java
// @Singleton
// public class PlayFopImpl implements PlayFop {
//
// private static final ProcessOptions DEFAULT_PROCESS_OPTIONS = new ProcessOptions.Builder().build();
//
// private com.dmanchester.playfop.sapi.PlayFop playFopScala = new com.dmanchester.playfop.sinternal.PlayFopImpl();
//
// @Override
// public byte[] processTwirlXml(Xml xslfo, String outputFormat) {
//
// return processTwirlXml(xslfo, outputFormat, DEFAULT_PROCESS_OPTIONS);
// }
//
// @Override
// public byte[] processTwirlXml(Xml xslfo, String outputFormat, ProcessOptions processOptions) {
//
// Function1<FOUserAgent, BoxedUnit> blockAsFunction = new BlockAsFunction(processOptions.getFoUserAgentBlock());
//
// return playFopScala.processTwirlXml(xslfo, outputFormat, processOptions.isAutoDetectFontsForPDF(), blockAsFunction);
// }
//
// @Override
// public byte[] processStringXml(String xslfo, String outputFormat) {
//
// return processStringXml(xslfo, outputFormat, DEFAULT_PROCESS_OPTIONS);
// }
//
// @Override
// public byte[] processStringXml(String xslfo, String outputFormat, ProcessOptions processOptions) {
//
// Function1<FOUserAgent, BoxedUnit> blockAsFunction = new BlockAsFunction(processOptions.getFoUserAgentBlock());
//
// return playFopScala.processStringXml(xslfo, outputFormat, processOptions.isAutoDetectFontsForPDF(), blockAsFunction);
// }
//
// @Override
// public Fop newFop(String outputFormat, OutputStream output) {
//
// return newFop(outputFormat, output, DEFAULT_PROCESS_OPTIONS);
// }
//
// @Override
// public Fop newFop(String outputFormat, OutputStream output, ProcessOptions processOptions) {
//
// Function1<FOUserAgent, BoxedUnit> blockAsFunction = new BlockAsFunction(processOptions.getFoUserAgentBlock());
//
// return playFopScala.newFop(outputFormat, output, processOptions.isAutoDetectFontsForPDF(), blockAsFunction);
// }
//
// private static class BlockAsFunction extends AbstractFunction1<FOUserAgent, BoxedUnit> {
//
// private FOUserAgentBlock block;
//
// public BlockAsFunction(FOUserAgentBlock block) {
// this.block = block;
// }
//
// @Override
// public BoxedUnit apply(FOUserAgent foUserAgent) {
// block.withFOUserAgent(foUserAgent);
// return BoxedUnit.UNIT;
// }
// }
// }
// Path: library/src/main/java/com/dmanchester/playfop/japi/PlayFopComponents.java
import com.dmanchester.playfop.jinternal.PlayFopImpl;
package com.dmanchester.playfop.japi;
/**
* An interface for dependency-injecting PlayFOP into Java applications at
* compile time.
*/
public interface PlayFopComponents {
default PlayFop playFop() { | return new PlayFopImpl(); |
dmanchester/playfop | library/src/main/java/com/dmanchester/playfop/japi/PlayFopModule.java | // Path: library/src/main/java/com/dmanchester/playfop/jinternal/PlayFopImpl.java
// @Singleton
// public class PlayFopImpl implements PlayFop {
//
// private static final ProcessOptions DEFAULT_PROCESS_OPTIONS = new ProcessOptions.Builder().build();
//
// private com.dmanchester.playfop.sapi.PlayFop playFopScala = new com.dmanchester.playfop.sinternal.PlayFopImpl();
//
// @Override
// public byte[] processTwirlXml(Xml xslfo, String outputFormat) {
//
// return processTwirlXml(xslfo, outputFormat, DEFAULT_PROCESS_OPTIONS);
// }
//
// @Override
// public byte[] processTwirlXml(Xml xslfo, String outputFormat, ProcessOptions processOptions) {
//
// Function1<FOUserAgent, BoxedUnit> blockAsFunction = new BlockAsFunction(processOptions.getFoUserAgentBlock());
//
// return playFopScala.processTwirlXml(xslfo, outputFormat, processOptions.isAutoDetectFontsForPDF(), blockAsFunction);
// }
//
// @Override
// public byte[] processStringXml(String xslfo, String outputFormat) {
//
// return processStringXml(xslfo, outputFormat, DEFAULT_PROCESS_OPTIONS);
// }
//
// @Override
// public byte[] processStringXml(String xslfo, String outputFormat, ProcessOptions processOptions) {
//
// Function1<FOUserAgent, BoxedUnit> blockAsFunction = new BlockAsFunction(processOptions.getFoUserAgentBlock());
//
// return playFopScala.processStringXml(xslfo, outputFormat, processOptions.isAutoDetectFontsForPDF(), blockAsFunction);
// }
//
// @Override
// public Fop newFop(String outputFormat, OutputStream output) {
//
// return newFop(outputFormat, output, DEFAULT_PROCESS_OPTIONS);
// }
//
// @Override
// public Fop newFop(String outputFormat, OutputStream output, ProcessOptions processOptions) {
//
// Function1<FOUserAgent, BoxedUnit> blockAsFunction = new BlockAsFunction(processOptions.getFoUserAgentBlock());
//
// return playFopScala.newFop(outputFormat, output, processOptions.isAutoDetectFontsForPDF(), blockAsFunction);
// }
//
// private static class BlockAsFunction extends AbstractFunction1<FOUserAgent, BoxedUnit> {
//
// private FOUserAgentBlock block;
//
// public BlockAsFunction(FOUserAgentBlock block) {
// this.block = block;
// }
//
// @Override
// public BoxedUnit apply(FOUserAgent foUserAgent) {
// block.withFOUserAgent(foUserAgent);
// return BoxedUnit.UNIT;
// }
// }
// }
| import com.dmanchester.playfop.jinternal.PlayFopImpl;
import play.api.Configuration;
import play.api.Environment;
import play.api.inject.Binding;
import play.api.inject.Module;
import scala.collection.Seq; | package com.dmanchester.playfop.japi;
/**
* A Play <a href="https://playframework.com/documentation/2.6.x/api/scala/index.html#play.api.inject.Module"><code>Module</code></a>
* for dependency-injecting PlayFOP into Java applications at runtime.
*/
public class PlayFopModule extends Module {
@Override
public Seq<Binding<?>> bindings(Environment environment, Configuration configuration) {
return seq( | // Path: library/src/main/java/com/dmanchester/playfop/jinternal/PlayFopImpl.java
// @Singleton
// public class PlayFopImpl implements PlayFop {
//
// private static final ProcessOptions DEFAULT_PROCESS_OPTIONS = new ProcessOptions.Builder().build();
//
// private com.dmanchester.playfop.sapi.PlayFop playFopScala = new com.dmanchester.playfop.sinternal.PlayFopImpl();
//
// @Override
// public byte[] processTwirlXml(Xml xslfo, String outputFormat) {
//
// return processTwirlXml(xslfo, outputFormat, DEFAULT_PROCESS_OPTIONS);
// }
//
// @Override
// public byte[] processTwirlXml(Xml xslfo, String outputFormat, ProcessOptions processOptions) {
//
// Function1<FOUserAgent, BoxedUnit> blockAsFunction = new BlockAsFunction(processOptions.getFoUserAgentBlock());
//
// return playFopScala.processTwirlXml(xslfo, outputFormat, processOptions.isAutoDetectFontsForPDF(), blockAsFunction);
// }
//
// @Override
// public byte[] processStringXml(String xslfo, String outputFormat) {
//
// return processStringXml(xslfo, outputFormat, DEFAULT_PROCESS_OPTIONS);
// }
//
// @Override
// public byte[] processStringXml(String xslfo, String outputFormat, ProcessOptions processOptions) {
//
// Function1<FOUserAgent, BoxedUnit> blockAsFunction = new BlockAsFunction(processOptions.getFoUserAgentBlock());
//
// return playFopScala.processStringXml(xslfo, outputFormat, processOptions.isAutoDetectFontsForPDF(), blockAsFunction);
// }
//
// @Override
// public Fop newFop(String outputFormat, OutputStream output) {
//
// return newFop(outputFormat, output, DEFAULT_PROCESS_OPTIONS);
// }
//
// @Override
// public Fop newFop(String outputFormat, OutputStream output, ProcessOptions processOptions) {
//
// Function1<FOUserAgent, BoxedUnit> blockAsFunction = new BlockAsFunction(processOptions.getFoUserAgentBlock());
//
// return playFopScala.newFop(outputFormat, output, processOptions.isAutoDetectFontsForPDF(), blockAsFunction);
// }
//
// private static class BlockAsFunction extends AbstractFunction1<FOUserAgent, BoxedUnit> {
//
// private FOUserAgentBlock block;
//
// public BlockAsFunction(FOUserAgentBlock block) {
// this.block = block;
// }
//
// @Override
// public BoxedUnit apply(FOUserAgent foUserAgent) {
// block.withFOUserAgent(foUserAgent);
// return BoxedUnit.UNIT;
// }
// }
// }
// Path: library/src/main/java/com/dmanchester/playfop/japi/PlayFopModule.java
import com.dmanchester.playfop.jinternal.PlayFopImpl;
import play.api.Configuration;
import play.api.Environment;
import play.api.inject.Binding;
import play.api.inject.Module;
import scala.collection.Seq;
package com.dmanchester.playfop.japi;
/**
* A Play <a href="https://playframework.com/documentation/2.6.x/api/scala/index.html#play.api.inject.Module"><code>Module</code></a>
* for dependency-injecting PlayFOP into Java applications at runtime.
*/
public class PlayFopModule extends Module {
@Override
public Seq<Binding<?>> bindings(Environment environment, Configuration configuration) {
return seq( | bind(PlayFop.class).to(PlayFopImpl.class) |
johanneslerch/FlowTwist | FlowTwist/test/flow/twist/test/util/TestTaintPushOnStack.java | // Path: FlowTwist/src/flow/twist/trackable/Trackable.java
// public abstract class Trackable implements LinkedNode<Trackable> {
//
// public final Trackable predecessor;
// public final Unit sourceUnit;
// private final List<Trackable> neighbors;
// private final Set<Object> payload;
//
// protected Trackable() {
// this.predecessor = null;
// this.sourceUnit = null;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// }
//
// public Trackable(Unit sourceUnit, Trackable predecessor) {
// this.predecessor = predecessor;
// this.sourceUnit = sourceUnit;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// payload.addAll(predecessor.payload);
// }
//
// public void addPayload(Object payload) {
// this.payload.add(payload);
// }
//
// public void addNeighbor(Trackable trackable) {
// // trackable.neighbors.addAll(getSelfAndNeighbors());
// neighbors.add(trackable);
// }
//
// public Collection<Trackable> getSelfAndNeighbors() {
// LinkedList<Trackable> result = Lists.newLinkedList(neighbors);
// result.add(this);
// return result;
// }
//
// public boolean hasSelfOrNeighborAnPredecessor() {
// for (Trackable t : getSelfAndNeighbors())
// if (t.predecessor != null)
// return true;
// return false;
// }
//
// public abstract Trackable cloneWithoutNeighborsAndPayload();
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((payload == null) ? 0 : payload.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Trackable))
// return false;
// Trackable other = (Trackable) obj;
// if (payload == null) {
// if (other.payload != null)
// return false;
// } else if (!payload.equals(other.payload))
// return false;
// return true;
// }
//
// public String payloadString() {
// if (payload.size() == 0)
// return "";
// return "(" + Joiner.on(",").join(payload) + ")";
// }
//
// public abstract Trackable createAlias(Unit sourceUnits);
//
// public Collection<Object> getPayload() {
// return payload;
// }
// }
| import soot.Unit;
import flow.twist.trackable.PushOnStack;
import flow.twist.trackable.Trackable; | package flow.twist.test.util;
public class TestTaintPushOnStack extends TestTaint implements PushOnStack {
private Unit callSite;
| // Path: FlowTwist/src/flow/twist/trackable/Trackable.java
// public abstract class Trackable implements LinkedNode<Trackable> {
//
// public final Trackable predecessor;
// public final Unit sourceUnit;
// private final List<Trackable> neighbors;
// private final Set<Object> payload;
//
// protected Trackable() {
// this.predecessor = null;
// this.sourceUnit = null;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// }
//
// public Trackable(Unit sourceUnit, Trackable predecessor) {
// this.predecessor = predecessor;
// this.sourceUnit = sourceUnit;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// payload.addAll(predecessor.payload);
// }
//
// public void addPayload(Object payload) {
// this.payload.add(payload);
// }
//
// public void addNeighbor(Trackable trackable) {
// // trackable.neighbors.addAll(getSelfAndNeighbors());
// neighbors.add(trackable);
// }
//
// public Collection<Trackable> getSelfAndNeighbors() {
// LinkedList<Trackable> result = Lists.newLinkedList(neighbors);
// result.add(this);
// return result;
// }
//
// public boolean hasSelfOrNeighborAnPredecessor() {
// for (Trackable t : getSelfAndNeighbors())
// if (t.predecessor != null)
// return true;
// return false;
// }
//
// public abstract Trackable cloneWithoutNeighborsAndPayload();
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((payload == null) ? 0 : payload.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Trackable))
// return false;
// Trackable other = (Trackable) obj;
// if (payload == null) {
// if (other.payload != null)
// return false;
// } else if (!payload.equals(other.payload))
// return false;
// return true;
// }
//
// public String payloadString() {
// if (payload.size() == 0)
// return "";
// return "(" + Joiner.on(",").join(payload) + ")";
// }
//
// public abstract Trackable createAlias(Unit sourceUnits);
//
// public Collection<Object> getPayload() {
// return payload;
// }
// }
// Path: FlowTwist/test/flow/twist/test/util/TestTaintPushOnStack.java
import soot.Unit;
import flow.twist.trackable.PushOnStack;
import flow.twist.trackable.Trackable;
package flow.twist.test.util;
public class TestTaintPushOnStack extends TestTaint implements PushOnStack {
private Unit callSite;
| public TestTaintPushOnStack(Unit sourceUnit, Trackable predecessor, Unit callSite, String identifier) { |
johanneslerch/FlowTwist | FlowTwist/src/flow/twist/SolverFactory.java | // Path: FlowTwist/src/flow/twist/ifds/TabulationProblem.java
// public class TabulationProblem extends DefaultJimpleIFDSTabulationProblem<Trackable, BiDiInterproceduralCFG<Unit, SootMethod>> {
//
// private AnalysisContext context;
// private FlowFunctionFactory flowFunctionFactory;
//
// public TabulationProblem(AnalysisConfiguration config) {
// super(makeICFG(config.direction));
// this.context = new AnalysisContext(config, interproceduralCFG());
// flowFunctionFactory = new FlowFunctionFactory(this.context);
// }
//
// private static BiDiInterproceduralCFG<Unit, SootMethod> makeICFG(AnalysisDirection direction) {
// JimpleBasedInterproceduralCFG fwdIcfg = new JimpleBasedInterproceduralCFG();
// if (direction == AnalysisDirection.FORWARDS)
// return fwdIcfg;
// else
// return new BackwardsInterproceduralCFG(fwdIcfg);
// }
//
// @Override
// public Map<Unit, Set<Trackable>> initialSeeds() {
// return DefaultSeeds.make(context.seedFactory.initialSeeds(context), zeroValue());
// }
//
// public void startReturningDeferredTargets() {
// for (AnalysisTarget target : context.targets) {
// target.enableIfDeferred();
// }
// }
//
// @Override
// protected FlowFunctions<Unit, Trackable, SootMethod> createFlowFunctionsFactory() {
// return flowFunctionFactory;
// }
//
// @Override
// protected Trackable createZeroValue() {
// return Zero.ZERO;
// }
//
// @Override
// public boolean autoAddZero() {
// return false;
// }
//
// @Override
// public boolean followReturnsPastSeeds() {
// // unbalanced analysis problem
// return true;
// }
//
// @Override
// public boolean computeValues() {
// return false;
// }
//
// public AnalysisContext getContext() {
// return context;
// }
// }
//
// Path: FlowTwist/src/flow/twist/trackable/Trackable.java
// public abstract class Trackable implements LinkedNode<Trackable> {
//
// public final Trackable predecessor;
// public final Unit sourceUnit;
// private final List<Trackable> neighbors;
// private final Set<Object> payload;
//
// protected Trackable() {
// this.predecessor = null;
// this.sourceUnit = null;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// }
//
// public Trackable(Unit sourceUnit, Trackable predecessor) {
// this.predecessor = predecessor;
// this.sourceUnit = sourceUnit;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// payload.addAll(predecessor.payload);
// }
//
// public void addPayload(Object payload) {
// this.payload.add(payload);
// }
//
// public void addNeighbor(Trackable trackable) {
// // trackable.neighbors.addAll(getSelfAndNeighbors());
// neighbors.add(trackable);
// }
//
// public Collection<Trackable> getSelfAndNeighbors() {
// LinkedList<Trackable> result = Lists.newLinkedList(neighbors);
// result.add(this);
// return result;
// }
//
// public boolean hasSelfOrNeighborAnPredecessor() {
// for (Trackable t : getSelfAndNeighbors())
// if (t.predecessor != null)
// return true;
// return false;
// }
//
// public abstract Trackable cloneWithoutNeighborsAndPayload();
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((payload == null) ? 0 : payload.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Trackable))
// return false;
// Trackable other = (Trackable) obj;
// if (payload == null) {
// if (other.payload != null)
// return false;
// } else if (!payload.equals(other.payload))
// return false;
// return true;
// }
//
// public String payloadString() {
// if (payload.size() == 0)
// return "";
// return "(" + Joiner.on(",").join(payload) + ")";
// }
//
// public abstract Trackable createAlias(Unit sourceUnits);
//
// public Collection<Object> getPayload() {
// return payload;
// }
// }
| import static flow.twist.config.AnalysisDirection.BACKWARDS;
import static flow.twist.config.AnalysisDirection.FORWARDS;
import heros.solver.BiDiIFDSSolver;
import heros.solver.IFDSSolver;
import heros.solver.PathTrackingIFDSSolver;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.toolkits.ide.icfg.BiDiInterproceduralCFG;
import flow.twist.config.AnalysisConfigurationBuilder;
import flow.twist.config.AnalysisConfigurationBuilder.PropagationReporterDecorator;
import flow.twist.ifds.FlowFunctionFactory;
import flow.twist.ifds.TabulationProblem;
import flow.twist.reporter.DelayingReporter;
import flow.twist.reporter.IfdsReporter;
import flow.twist.trackable.Trackable;
import flow.twist.util.Pair; | package flow.twist;
public class SolverFactory {
public static void runOneDirectionSolver(AnalysisConfigurationBuilder configBuilder) {
Pair<IfdsReporter, AnalysisConfigurationBuilder> pair = configBuilder.decorateReporter(new PropagationReporterDecorator() {
@Override
public IfdsReporter decorate(IfdsReporter reporter) {
return new DelayingReporter(reporter);
}
});
| // Path: FlowTwist/src/flow/twist/ifds/TabulationProblem.java
// public class TabulationProblem extends DefaultJimpleIFDSTabulationProblem<Trackable, BiDiInterproceduralCFG<Unit, SootMethod>> {
//
// private AnalysisContext context;
// private FlowFunctionFactory flowFunctionFactory;
//
// public TabulationProblem(AnalysisConfiguration config) {
// super(makeICFG(config.direction));
// this.context = new AnalysisContext(config, interproceduralCFG());
// flowFunctionFactory = new FlowFunctionFactory(this.context);
// }
//
// private static BiDiInterproceduralCFG<Unit, SootMethod> makeICFG(AnalysisDirection direction) {
// JimpleBasedInterproceduralCFG fwdIcfg = new JimpleBasedInterproceduralCFG();
// if (direction == AnalysisDirection.FORWARDS)
// return fwdIcfg;
// else
// return new BackwardsInterproceduralCFG(fwdIcfg);
// }
//
// @Override
// public Map<Unit, Set<Trackable>> initialSeeds() {
// return DefaultSeeds.make(context.seedFactory.initialSeeds(context), zeroValue());
// }
//
// public void startReturningDeferredTargets() {
// for (AnalysisTarget target : context.targets) {
// target.enableIfDeferred();
// }
// }
//
// @Override
// protected FlowFunctions<Unit, Trackable, SootMethod> createFlowFunctionsFactory() {
// return flowFunctionFactory;
// }
//
// @Override
// protected Trackable createZeroValue() {
// return Zero.ZERO;
// }
//
// @Override
// public boolean autoAddZero() {
// return false;
// }
//
// @Override
// public boolean followReturnsPastSeeds() {
// // unbalanced analysis problem
// return true;
// }
//
// @Override
// public boolean computeValues() {
// return false;
// }
//
// public AnalysisContext getContext() {
// return context;
// }
// }
//
// Path: FlowTwist/src/flow/twist/trackable/Trackable.java
// public abstract class Trackable implements LinkedNode<Trackable> {
//
// public final Trackable predecessor;
// public final Unit sourceUnit;
// private final List<Trackable> neighbors;
// private final Set<Object> payload;
//
// protected Trackable() {
// this.predecessor = null;
// this.sourceUnit = null;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// }
//
// public Trackable(Unit sourceUnit, Trackable predecessor) {
// this.predecessor = predecessor;
// this.sourceUnit = sourceUnit;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// payload.addAll(predecessor.payload);
// }
//
// public void addPayload(Object payload) {
// this.payload.add(payload);
// }
//
// public void addNeighbor(Trackable trackable) {
// // trackable.neighbors.addAll(getSelfAndNeighbors());
// neighbors.add(trackable);
// }
//
// public Collection<Trackable> getSelfAndNeighbors() {
// LinkedList<Trackable> result = Lists.newLinkedList(neighbors);
// result.add(this);
// return result;
// }
//
// public boolean hasSelfOrNeighborAnPredecessor() {
// for (Trackable t : getSelfAndNeighbors())
// if (t.predecessor != null)
// return true;
// return false;
// }
//
// public abstract Trackable cloneWithoutNeighborsAndPayload();
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((payload == null) ? 0 : payload.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Trackable))
// return false;
// Trackable other = (Trackable) obj;
// if (payload == null) {
// if (other.payload != null)
// return false;
// } else if (!payload.equals(other.payload))
// return false;
// return true;
// }
//
// public String payloadString() {
// if (payload.size() == 0)
// return "";
// return "(" + Joiner.on(",").join(payload) + ")";
// }
//
// public abstract Trackable createAlias(Unit sourceUnits);
//
// public Collection<Object> getPayload() {
// return payload;
// }
// }
// Path: FlowTwist/src/flow/twist/SolverFactory.java
import static flow.twist.config.AnalysisDirection.BACKWARDS;
import static flow.twist.config.AnalysisDirection.FORWARDS;
import heros.solver.BiDiIFDSSolver;
import heros.solver.IFDSSolver;
import heros.solver.PathTrackingIFDSSolver;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.toolkits.ide.icfg.BiDiInterproceduralCFG;
import flow.twist.config.AnalysisConfigurationBuilder;
import flow.twist.config.AnalysisConfigurationBuilder.PropagationReporterDecorator;
import flow.twist.ifds.FlowFunctionFactory;
import flow.twist.ifds.TabulationProblem;
import flow.twist.reporter.DelayingReporter;
import flow.twist.reporter.IfdsReporter;
import flow.twist.trackable.Trackable;
import flow.twist.util.Pair;
package flow.twist;
public class SolverFactory {
public static void runOneDirectionSolver(AnalysisConfigurationBuilder configBuilder) {
Pair<IfdsReporter, AnalysisConfigurationBuilder> pair = configBuilder.decorateReporter(new PropagationReporterDecorator() {
@Override
public IfdsReporter decorate(IfdsReporter reporter) {
return new DelayingReporter(reporter);
}
});
| TabulationProblem problem = createTabulationProblem(pair.second); |
johanneslerch/FlowTwist | FlowTwist/src/flow/twist/SolverFactory.java | // Path: FlowTwist/src/flow/twist/ifds/TabulationProblem.java
// public class TabulationProblem extends DefaultJimpleIFDSTabulationProblem<Trackable, BiDiInterproceduralCFG<Unit, SootMethod>> {
//
// private AnalysisContext context;
// private FlowFunctionFactory flowFunctionFactory;
//
// public TabulationProblem(AnalysisConfiguration config) {
// super(makeICFG(config.direction));
// this.context = new AnalysisContext(config, interproceduralCFG());
// flowFunctionFactory = new FlowFunctionFactory(this.context);
// }
//
// private static BiDiInterproceduralCFG<Unit, SootMethod> makeICFG(AnalysisDirection direction) {
// JimpleBasedInterproceduralCFG fwdIcfg = new JimpleBasedInterproceduralCFG();
// if (direction == AnalysisDirection.FORWARDS)
// return fwdIcfg;
// else
// return new BackwardsInterproceduralCFG(fwdIcfg);
// }
//
// @Override
// public Map<Unit, Set<Trackable>> initialSeeds() {
// return DefaultSeeds.make(context.seedFactory.initialSeeds(context), zeroValue());
// }
//
// public void startReturningDeferredTargets() {
// for (AnalysisTarget target : context.targets) {
// target.enableIfDeferred();
// }
// }
//
// @Override
// protected FlowFunctions<Unit, Trackable, SootMethod> createFlowFunctionsFactory() {
// return flowFunctionFactory;
// }
//
// @Override
// protected Trackable createZeroValue() {
// return Zero.ZERO;
// }
//
// @Override
// public boolean autoAddZero() {
// return false;
// }
//
// @Override
// public boolean followReturnsPastSeeds() {
// // unbalanced analysis problem
// return true;
// }
//
// @Override
// public boolean computeValues() {
// return false;
// }
//
// public AnalysisContext getContext() {
// return context;
// }
// }
//
// Path: FlowTwist/src/flow/twist/trackable/Trackable.java
// public abstract class Trackable implements LinkedNode<Trackable> {
//
// public final Trackable predecessor;
// public final Unit sourceUnit;
// private final List<Trackable> neighbors;
// private final Set<Object> payload;
//
// protected Trackable() {
// this.predecessor = null;
// this.sourceUnit = null;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// }
//
// public Trackable(Unit sourceUnit, Trackable predecessor) {
// this.predecessor = predecessor;
// this.sourceUnit = sourceUnit;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// payload.addAll(predecessor.payload);
// }
//
// public void addPayload(Object payload) {
// this.payload.add(payload);
// }
//
// public void addNeighbor(Trackable trackable) {
// // trackable.neighbors.addAll(getSelfAndNeighbors());
// neighbors.add(trackable);
// }
//
// public Collection<Trackable> getSelfAndNeighbors() {
// LinkedList<Trackable> result = Lists.newLinkedList(neighbors);
// result.add(this);
// return result;
// }
//
// public boolean hasSelfOrNeighborAnPredecessor() {
// for (Trackable t : getSelfAndNeighbors())
// if (t.predecessor != null)
// return true;
// return false;
// }
//
// public abstract Trackable cloneWithoutNeighborsAndPayload();
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((payload == null) ? 0 : payload.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Trackable))
// return false;
// Trackable other = (Trackable) obj;
// if (payload == null) {
// if (other.payload != null)
// return false;
// } else if (!payload.equals(other.payload))
// return false;
// return true;
// }
//
// public String payloadString() {
// if (payload.size() == 0)
// return "";
// return "(" + Joiner.on(",").join(payload) + ")";
// }
//
// public abstract Trackable createAlias(Unit sourceUnits);
//
// public Collection<Object> getPayload() {
// return payload;
// }
// }
| import static flow.twist.config.AnalysisDirection.BACKWARDS;
import static flow.twist.config.AnalysisDirection.FORWARDS;
import heros.solver.BiDiIFDSSolver;
import heros.solver.IFDSSolver;
import heros.solver.PathTrackingIFDSSolver;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.toolkits.ide.icfg.BiDiInterproceduralCFG;
import flow.twist.config.AnalysisConfigurationBuilder;
import flow.twist.config.AnalysisConfigurationBuilder.PropagationReporterDecorator;
import flow.twist.ifds.FlowFunctionFactory;
import flow.twist.ifds.TabulationProblem;
import flow.twist.reporter.DelayingReporter;
import flow.twist.reporter.IfdsReporter;
import flow.twist.trackable.Trackable;
import flow.twist.util.Pair; | package flow.twist;
public class SolverFactory {
public static void runOneDirectionSolver(AnalysisConfigurationBuilder configBuilder) {
Pair<IfdsReporter, AnalysisConfigurationBuilder> pair = configBuilder.decorateReporter(new PropagationReporterDecorator() {
@Override
public IfdsReporter decorate(IfdsReporter reporter) {
return new DelayingReporter(reporter);
}
});
TabulationProblem problem = createTabulationProblem(pair.second); | // Path: FlowTwist/src/flow/twist/ifds/TabulationProblem.java
// public class TabulationProblem extends DefaultJimpleIFDSTabulationProblem<Trackable, BiDiInterproceduralCFG<Unit, SootMethod>> {
//
// private AnalysisContext context;
// private FlowFunctionFactory flowFunctionFactory;
//
// public TabulationProblem(AnalysisConfiguration config) {
// super(makeICFG(config.direction));
// this.context = new AnalysisContext(config, interproceduralCFG());
// flowFunctionFactory = new FlowFunctionFactory(this.context);
// }
//
// private static BiDiInterproceduralCFG<Unit, SootMethod> makeICFG(AnalysisDirection direction) {
// JimpleBasedInterproceduralCFG fwdIcfg = new JimpleBasedInterproceduralCFG();
// if (direction == AnalysisDirection.FORWARDS)
// return fwdIcfg;
// else
// return new BackwardsInterproceduralCFG(fwdIcfg);
// }
//
// @Override
// public Map<Unit, Set<Trackable>> initialSeeds() {
// return DefaultSeeds.make(context.seedFactory.initialSeeds(context), zeroValue());
// }
//
// public void startReturningDeferredTargets() {
// for (AnalysisTarget target : context.targets) {
// target.enableIfDeferred();
// }
// }
//
// @Override
// protected FlowFunctions<Unit, Trackable, SootMethod> createFlowFunctionsFactory() {
// return flowFunctionFactory;
// }
//
// @Override
// protected Trackable createZeroValue() {
// return Zero.ZERO;
// }
//
// @Override
// public boolean autoAddZero() {
// return false;
// }
//
// @Override
// public boolean followReturnsPastSeeds() {
// // unbalanced analysis problem
// return true;
// }
//
// @Override
// public boolean computeValues() {
// return false;
// }
//
// public AnalysisContext getContext() {
// return context;
// }
// }
//
// Path: FlowTwist/src/flow/twist/trackable/Trackable.java
// public abstract class Trackable implements LinkedNode<Trackable> {
//
// public final Trackable predecessor;
// public final Unit sourceUnit;
// private final List<Trackable> neighbors;
// private final Set<Object> payload;
//
// protected Trackable() {
// this.predecessor = null;
// this.sourceUnit = null;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// }
//
// public Trackable(Unit sourceUnit, Trackable predecessor) {
// this.predecessor = predecessor;
// this.sourceUnit = sourceUnit;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// payload.addAll(predecessor.payload);
// }
//
// public void addPayload(Object payload) {
// this.payload.add(payload);
// }
//
// public void addNeighbor(Trackable trackable) {
// // trackable.neighbors.addAll(getSelfAndNeighbors());
// neighbors.add(trackable);
// }
//
// public Collection<Trackable> getSelfAndNeighbors() {
// LinkedList<Trackable> result = Lists.newLinkedList(neighbors);
// result.add(this);
// return result;
// }
//
// public boolean hasSelfOrNeighborAnPredecessor() {
// for (Trackable t : getSelfAndNeighbors())
// if (t.predecessor != null)
// return true;
// return false;
// }
//
// public abstract Trackable cloneWithoutNeighborsAndPayload();
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((payload == null) ? 0 : payload.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Trackable))
// return false;
// Trackable other = (Trackable) obj;
// if (payload == null) {
// if (other.payload != null)
// return false;
// } else if (!payload.equals(other.payload))
// return false;
// return true;
// }
//
// public String payloadString() {
// if (payload.size() == 0)
// return "";
// return "(" + Joiner.on(",").join(payload) + ")";
// }
//
// public abstract Trackable createAlias(Unit sourceUnits);
//
// public Collection<Object> getPayload() {
// return payload;
// }
// }
// Path: FlowTwist/src/flow/twist/SolverFactory.java
import static flow.twist.config.AnalysisDirection.BACKWARDS;
import static flow.twist.config.AnalysisDirection.FORWARDS;
import heros.solver.BiDiIFDSSolver;
import heros.solver.IFDSSolver;
import heros.solver.PathTrackingIFDSSolver;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.toolkits.ide.icfg.BiDiInterproceduralCFG;
import flow.twist.config.AnalysisConfigurationBuilder;
import flow.twist.config.AnalysisConfigurationBuilder.PropagationReporterDecorator;
import flow.twist.ifds.FlowFunctionFactory;
import flow.twist.ifds.TabulationProblem;
import flow.twist.reporter.DelayingReporter;
import flow.twist.reporter.IfdsReporter;
import flow.twist.trackable.Trackable;
import flow.twist.util.Pair;
package flow.twist;
public class SolverFactory {
public static void runOneDirectionSolver(AnalysisConfigurationBuilder configBuilder) {
Pair<IfdsReporter, AnalysisConfigurationBuilder> pair = configBuilder.decorateReporter(new PropagationReporterDecorator() {
@Override
public IfdsReporter decorate(IfdsReporter reporter) {
return new DelayingReporter(reporter);
}
});
TabulationProblem problem = createTabulationProblem(pair.second); | IFDSSolver<Unit, Trackable, SootMethod, BiDiInterproceduralCFG<Unit, SootMethod>> solver = createSolver(problem); |
johanneslerch/FlowTwist | FlowTwist/test/flow/twist/test/util/selectors/TrackableSelectorFactory.java | // Path: FlowTwist/src/flow/twist/trackable/Taint.java
// public class Taint extends Trackable {
//
// public final Value value;
// public final Type type;
//
// public Taint(Unit sourceUnit, Trackable predecessor, Value value, Type type) {
// super(sourceUnit, predecessor);
//
// if (value instanceof Constant) {
// throw new IllegalArgumentException("Constant value has been tainted.");
// }
//
// this.value = value;
// this.type = type;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (!super.equals(obj))
// return false;
// if (!(obj instanceof Taint))
// return false;
// Taint other = (Taint) obj;
// if (type == null) {
// if (other.type != null)
// return false;
// } else if (!type.equals(other.type))
// return false;
// if (value == null) {
// if (other.value != null)
// return false;
// } else if (!value.equals(other.value))
// return false;
// return true;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = super.hashCode();
// result = prime * result + ((type == null) ? 0 : type.hashCode());
// result = prime * result + ((value == null) ? 0 : value.hashCode());
// return result;
// }
//
// @Override
// public String toString() {
// return "[Taint" + payloadString() + ": " + value + " Type: " + type + "]";
// // return "[Taint: " + value + "; " + System.identityHashCode(this) +
// // "; " + System.identityHashCode(value) + "; " + hashCode() + "]";
// }
//
// public Taint createAlias(Value value, Unit sourceUnit) {
// return new Taint(sourceUnit, this, value, type);
// }
//
// @Override
// public Trackable createAlias(Unit sourceUnit) {
// return new Taint(sourceUnit, this, value, type);
// }
//
// @Override
// public Taint cloneWithoutNeighborsAndPayload() {
// return new Taint(sourceUnit, predecessor, value, type);
// }
//
// }
//
// Path: FlowTwist/src/flow/twist/trackable/Trackable.java
// public abstract class Trackable implements LinkedNode<Trackable> {
//
// public final Trackable predecessor;
// public final Unit sourceUnit;
// private final List<Trackable> neighbors;
// private final Set<Object> payload;
//
// protected Trackable() {
// this.predecessor = null;
// this.sourceUnit = null;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// }
//
// public Trackable(Unit sourceUnit, Trackable predecessor) {
// this.predecessor = predecessor;
// this.sourceUnit = sourceUnit;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// payload.addAll(predecessor.payload);
// }
//
// public void addPayload(Object payload) {
// this.payload.add(payload);
// }
//
// public void addNeighbor(Trackable trackable) {
// // trackable.neighbors.addAll(getSelfAndNeighbors());
// neighbors.add(trackable);
// }
//
// public Collection<Trackable> getSelfAndNeighbors() {
// LinkedList<Trackable> result = Lists.newLinkedList(neighbors);
// result.add(this);
// return result;
// }
//
// public boolean hasSelfOrNeighborAnPredecessor() {
// for (Trackable t : getSelfAndNeighbors())
// if (t.predecessor != null)
// return true;
// return false;
// }
//
// public abstract Trackable cloneWithoutNeighborsAndPayload();
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((payload == null) ? 0 : payload.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Trackable))
// return false;
// Trackable other = (Trackable) obj;
// if (payload == null) {
// if (other.payload != null)
// return false;
// } else if (!payload.equals(other.payload))
// return false;
// return true;
// }
//
// public String payloadString() {
// if (payload.size() == 0)
// return "";
// return "(" + Joiner.on(",").join(payload) + ")";
// }
//
// public abstract Trackable createAlias(Unit sourceUnits);
//
// public Collection<Object> getPayload() {
// return payload;
// }
// }
| import flow.twist.trackable.Taint;
import flow.twist.trackable.Trackable; | package flow.twist.test.util.selectors;
public class TrackableSelectorFactory {
public static TrackableSelector taintContains(final String name) {
return new TrackableSelector() {
@Override | // Path: FlowTwist/src/flow/twist/trackable/Taint.java
// public class Taint extends Trackable {
//
// public final Value value;
// public final Type type;
//
// public Taint(Unit sourceUnit, Trackable predecessor, Value value, Type type) {
// super(sourceUnit, predecessor);
//
// if (value instanceof Constant) {
// throw new IllegalArgumentException("Constant value has been tainted.");
// }
//
// this.value = value;
// this.type = type;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (!super.equals(obj))
// return false;
// if (!(obj instanceof Taint))
// return false;
// Taint other = (Taint) obj;
// if (type == null) {
// if (other.type != null)
// return false;
// } else if (!type.equals(other.type))
// return false;
// if (value == null) {
// if (other.value != null)
// return false;
// } else if (!value.equals(other.value))
// return false;
// return true;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = super.hashCode();
// result = prime * result + ((type == null) ? 0 : type.hashCode());
// result = prime * result + ((value == null) ? 0 : value.hashCode());
// return result;
// }
//
// @Override
// public String toString() {
// return "[Taint" + payloadString() + ": " + value + " Type: " + type + "]";
// // return "[Taint: " + value + "; " + System.identityHashCode(this) +
// // "; " + System.identityHashCode(value) + "; " + hashCode() + "]";
// }
//
// public Taint createAlias(Value value, Unit sourceUnit) {
// return new Taint(sourceUnit, this, value, type);
// }
//
// @Override
// public Trackable createAlias(Unit sourceUnit) {
// return new Taint(sourceUnit, this, value, type);
// }
//
// @Override
// public Taint cloneWithoutNeighborsAndPayload() {
// return new Taint(sourceUnit, predecessor, value, type);
// }
//
// }
//
// Path: FlowTwist/src/flow/twist/trackable/Trackable.java
// public abstract class Trackable implements LinkedNode<Trackable> {
//
// public final Trackable predecessor;
// public final Unit sourceUnit;
// private final List<Trackable> neighbors;
// private final Set<Object> payload;
//
// protected Trackable() {
// this.predecessor = null;
// this.sourceUnit = null;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// }
//
// public Trackable(Unit sourceUnit, Trackable predecessor) {
// this.predecessor = predecessor;
// this.sourceUnit = sourceUnit;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// payload.addAll(predecessor.payload);
// }
//
// public void addPayload(Object payload) {
// this.payload.add(payload);
// }
//
// public void addNeighbor(Trackable trackable) {
// // trackable.neighbors.addAll(getSelfAndNeighbors());
// neighbors.add(trackable);
// }
//
// public Collection<Trackable> getSelfAndNeighbors() {
// LinkedList<Trackable> result = Lists.newLinkedList(neighbors);
// result.add(this);
// return result;
// }
//
// public boolean hasSelfOrNeighborAnPredecessor() {
// for (Trackable t : getSelfAndNeighbors())
// if (t.predecessor != null)
// return true;
// return false;
// }
//
// public abstract Trackable cloneWithoutNeighborsAndPayload();
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((payload == null) ? 0 : payload.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Trackable))
// return false;
// Trackable other = (Trackable) obj;
// if (payload == null) {
// if (other.payload != null)
// return false;
// } else if (!payload.equals(other.payload))
// return false;
// return true;
// }
//
// public String payloadString() {
// if (payload.size() == 0)
// return "";
// return "(" + Joiner.on(",").join(payload) + ")";
// }
//
// public abstract Trackable createAlias(Unit sourceUnits);
//
// public Collection<Object> getPayload() {
// return payload;
// }
// }
// Path: FlowTwist/test/flow/twist/test/util/selectors/TrackableSelectorFactory.java
import flow.twist.trackable.Taint;
import flow.twist.trackable.Trackable;
package flow.twist.test.util.selectors;
public class TrackableSelectorFactory {
public static TrackableSelector taintContains(final String name) {
return new TrackableSelector() {
@Override | public boolean matches(Trackable trackable) { |
johanneslerch/FlowTwist | FlowTwist/test/flow/twist/test/util/selectors/TrackableSelectorFactory.java | // Path: FlowTwist/src/flow/twist/trackable/Taint.java
// public class Taint extends Trackable {
//
// public final Value value;
// public final Type type;
//
// public Taint(Unit sourceUnit, Trackable predecessor, Value value, Type type) {
// super(sourceUnit, predecessor);
//
// if (value instanceof Constant) {
// throw new IllegalArgumentException("Constant value has been tainted.");
// }
//
// this.value = value;
// this.type = type;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (!super.equals(obj))
// return false;
// if (!(obj instanceof Taint))
// return false;
// Taint other = (Taint) obj;
// if (type == null) {
// if (other.type != null)
// return false;
// } else if (!type.equals(other.type))
// return false;
// if (value == null) {
// if (other.value != null)
// return false;
// } else if (!value.equals(other.value))
// return false;
// return true;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = super.hashCode();
// result = prime * result + ((type == null) ? 0 : type.hashCode());
// result = prime * result + ((value == null) ? 0 : value.hashCode());
// return result;
// }
//
// @Override
// public String toString() {
// return "[Taint" + payloadString() + ": " + value + " Type: " + type + "]";
// // return "[Taint: " + value + "; " + System.identityHashCode(this) +
// // "; " + System.identityHashCode(value) + "; " + hashCode() + "]";
// }
//
// public Taint createAlias(Value value, Unit sourceUnit) {
// return new Taint(sourceUnit, this, value, type);
// }
//
// @Override
// public Trackable createAlias(Unit sourceUnit) {
// return new Taint(sourceUnit, this, value, type);
// }
//
// @Override
// public Taint cloneWithoutNeighborsAndPayload() {
// return new Taint(sourceUnit, predecessor, value, type);
// }
//
// }
//
// Path: FlowTwist/src/flow/twist/trackable/Trackable.java
// public abstract class Trackable implements LinkedNode<Trackable> {
//
// public final Trackable predecessor;
// public final Unit sourceUnit;
// private final List<Trackable> neighbors;
// private final Set<Object> payload;
//
// protected Trackable() {
// this.predecessor = null;
// this.sourceUnit = null;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// }
//
// public Trackable(Unit sourceUnit, Trackable predecessor) {
// this.predecessor = predecessor;
// this.sourceUnit = sourceUnit;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// payload.addAll(predecessor.payload);
// }
//
// public void addPayload(Object payload) {
// this.payload.add(payload);
// }
//
// public void addNeighbor(Trackable trackable) {
// // trackable.neighbors.addAll(getSelfAndNeighbors());
// neighbors.add(trackable);
// }
//
// public Collection<Trackable> getSelfAndNeighbors() {
// LinkedList<Trackable> result = Lists.newLinkedList(neighbors);
// result.add(this);
// return result;
// }
//
// public boolean hasSelfOrNeighborAnPredecessor() {
// for (Trackable t : getSelfAndNeighbors())
// if (t.predecessor != null)
// return true;
// return false;
// }
//
// public abstract Trackable cloneWithoutNeighborsAndPayload();
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((payload == null) ? 0 : payload.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Trackable))
// return false;
// Trackable other = (Trackable) obj;
// if (payload == null) {
// if (other.payload != null)
// return false;
// } else if (!payload.equals(other.payload))
// return false;
// return true;
// }
//
// public String payloadString() {
// if (payload.size() == 0)
// return "";
// return "(" + Joiner.on(",").join(payload) + ")";
// }
//
// public abstract Trackable createAlias(Unit sourceUnits);
//
// public Collection<Object> getPayload() {
// return payload;
// }
// }
| import flow.twist.trackable.Taint;
import flow.twist.trackable.Trackable; | package flow.twist.test.util.selectors;
public class TrackableSelectorFactory {
public static TrackableSelector taintContains(final String name) {
return new TrackableSelector() {
@Override
public boolean matches(Trackable trackable) { | // Path: FlowTwist/src/flow/twist/trackable/Taint.java
// public class Taint extends Trackable {
//
// public final Value value;
// public final Type type;
//
// public Taint(Unit sourceUnit, Trackable predecessor, Value value, Type type) {
// super(sourceUnit, predecessor);
//
// if (value instanceof Constant) {
// throw new IllegalArgumentException("Constant value has been tainted.");
// }
//
// this.value = value;
// this.type = type;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (!super.equals(obj))
// return false;
// if (!(obj instanceof Taint))
// return false;
// Taint other = (Taint) obj;
// if (type == null) {
// if (other.type != null)
// return false;
// } else if (!type.equals(other.type))
// return false;
// if (value == null) {
// if (other.value != null)
// return false;
// } else if (!value.equals(other.value))
// return false;
// return true;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = super.hashCode();
// result = prime * result + ((type == null) ? 0 : type.hashCode());
// result = prime * result + ((value == null) ? 0 : value.hashCode());
// return result;
// }
//
// @Override
// public String toString() {
// return "[Taint" + payloadString() + ": " + value + " Type: " + type + "]";
// // return "[Taint: " + value + "; " + System.identityHashCode(this) +
// // "; " + System.identityHashCode(value) + "; " + hashCode() + "]";
// }
//
// public Taint createAlias(Value value, Unit sourceUnit) {
// return new Taint(sourceUnit, this, value, type);
// }
//
// @Override
// public Trackable createAlias(Unit sourceUnit) {
// return new Taint(sourceUnit, this, value, type);
// }
//
// @Override
// public Taint cloneWithoutNeighborsAndPayload() {
// return new Taint(sourceUnit, predecessor, value, type);
// }
//
// }
//
// Path: FlowTwist/src/flow/twist/trackable/Trackable.java
// public abstract class Trackable implements LinkedNode<Trackable> {
//
// public final Trackable predecessor;
// public final Unit sourceUnit;
// private final List<Trackable> neighbors;
// private final Set<Object> payload;
//
// protected Trackable() {
// this.predecessor = null;
// this.sourceUnit = null;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// }
//
// public Trackable(Unit sourceUnit, Trackable predecessor) {
// this.predecessor = predecessor;
// this.sourceUnit = sourceUnit;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// payload.addAll(predecessor.payload);
// }
//
// public void addPayload(Object payload) {
// this.payload.add(payload);
// }
//
// public void addNeighbor(Trackable trackable) {
// // trackable.neighbors.addAll(getSelfAndNeighbors());
// neighbors.add(trackable);
// }
//
// public Collection<Trackable> getSelfAndNeighbors() {
// LinkedList<Trackable> result = Lists.newLinkedList(neighbors);
// result.add(this);
// return result;
// }
//
// public boolean hasSelfOrNeighborAnPredecessor() {
// for (Trackable t : getSelfAndNeighbors())
// if (t.predecessor != null)
// return true;
// return false;
// }
//
// public abstract Trackable cloneWithoutNeighborsAndPayload();
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((payload == null) ? 0 : payload.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Trackable))
// return false;
// Trackable other = (Trackable) obj;
// if (payload == null) {
// if (other.payload != null)
// return false;
// } else if (!payload.equals(other.payload))
// return false;
// return true;
// }
//
// public String payloadString() {
// if (payload.size() == 0)
// return "";
// return "(" + Joiner.on(",").join(payload) + ")";
// }
//
// public abstract Trackable createAlias(Unit sourceUnits);
//
// public Collection<Object> getPayload() {
// return payload;
// }
// }
// Path: FlowTwist/test/flow/twist/test/util/selectors/TrackableSelectorFactory.java
import flow.twist.trackable.Taint;
import flow.twist.trackable.Trackable;
package flow.twist.test.util.selectors;
public class TrackableSelectorFactory {
public static TrackableSelector taintContains(final String name) {
return new TrackableSelector() {
@Override
public boolean matches(Trackable trackable) { | if (trackable instanceof Taint) { |
johanneslerch/FlowTwist | FlowTwist/test/flow/twist/test/util/AbstractPathTests.java | // Path: FlowTwist/test/flow/twist/test/util/selectors/UnitSelectorFactory.java
// public static UnitSelector anyUnit() {
// return new UnitSelector() {
//
// @Override
// public boolean matches(SootMethod method, Unit unit) {
// return true;
// }
//
// @Override
// public String toString() {
// return "any unit";
// }
// };
// }
//
// Path: FlowTwist/test/flow/twist/test/util/selectors/UnitSelectorFactory.java
// public static UnitSelector unitByLabel(final String label) {
// return new UnitSelector() {
// @Override
// public boolean matches(SootMethod method, Unit unit) {
// return unit.toString().contains(label);
// }
//
// @Override
// public String toString() {
// return label;
// }
// };
// }
//
// Path: FlowTwist/test/flow/twist/test/util/selectors/UnitSelectorFactory.java
// public static UnitSelector unitInMethod(final String methodString, final UnitSelector selector) {
// return new UnitSelector() {
// @Override
// public boolean matches(SootMethod method, Unit unit) {
// return method.toString().contains(methodString) && selector.matches(method, unit);
// }
//
// @Override
// public String toString() {
// return "'" + selector.toString() + "' in '" + methodString + "'";
// }
// };
// }
//
// Path: FlowTwist/test/flow/twist/test/util/selectors/UnitSelectorFactory.java
// public static UnitSelector unitWithoutLabel(final String label, final UnitSelector selector) {
// return new UnitSelector() {
// @Override
// public boolean matches(SootMethod method, Unit unit) {
// return !unit.toString().contains(label) && selector.matches(method, unit);
// }
//
// @Override
// public String toString() {
// return "'" + selector.toString() + "' without '" + label + "'";
// }
// };
// }
//
// Path: FlowTwist/test/flow/twist/test/util/PathVerifier.java
// public class PathSelector {
// private List<Path> paths;
//
// public PathSelector(List<Path> paths) {
// this.paths = paths;
// }
//
// public PathSelector endsAt(UnitSelector selector) {
// List<Path> matchingPaths = Lists.newLinkedList();
// for (Path path : paths) {
// Unit unit = path.getLast();
// if (selector.matches(path.context.icfg.getMethodOf(unit), unit)) {
// matchingPaths.add(path);
// }
// }
// return new PathSelector(matchingPaths);
// }
//
// public PathSelector contains(UnitSelector selector) {
// List<Path> matchingPaths = Lists.newLinkedList();
// for (Path path : paths) {
// if (pathContains(selector, path)) {
// matchingPaths.add(path);
// }
// }
// return new PathSelector(matchingPaths);
// }
//
// private boolean pathContains(UnitSelector selector, Path path) {
// for (PathElement element : path) {
// if (selector.matches(path.context.icfg.getMethodOf(element.to), element.to)) {
// return true;
// }
// }
//
// return false;
// }
//
// public PathSelector doesNotContain(UnitSelector selector) {
// List<Path> matchingPaths = Lists.newLinkedList();
// for (Path path : paths) {
// if (!pathContains(selector, path)) {
// matchingPaths.add(path);
// }
// }
// return new PathSelector(matchingPaths);
// }
//
// public void once() {
// Assert.assertEquals(1, paths.size());
// }
//
// public void never() {
// Assert.assertEquals(0, paths.size());
// }
//
// public void noOtherPaths() {
// Assert.assertEquals(paths.size(), PathVerifier.this.paths.size());
// }
//
// public void times(int i) {
// Assert.assertEquals(i, paths.size());
// }
//
// public void assertStack(Unit... callSites) {
// for (Path path : paths) {
// fj.data.List<Object> callStack = path.getCallStack();
// Assert.assertTrue(Iterables.elementsEqual(callStack, Lists.newArrayList(callSites)));
// }
// }
//
// }
| import static flow.twist.test.util.selectors.UnitSelectorFactory.anyUnit;
import static flow.twist.test.util.selectors.UnitSelectorFactory.unitByLabel;
import static flow.twist.test.util.selectors.UnitSelectorFactory.unitInMethod;
import static flow.twist.test.util.selectors.UnitSelectorFactory.unitWithoutLabel;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import flow.twist.test.util.PathVerifier.PathSelector;
import flow.twist.util.MultipleAnalysisPlotter; | package flow.twist.test.util;
public abstract class AbstractPathTests extends AbstractTaintAnalysisTest {
protected PathVerifier pathVerifier;
@Rule
public TestWatcher watcher = new TestWatcher() {
@Override
public void failed(Throwable e, Description description) {
StringBuilder builder = new StringBuilder();
builder.append("tmp/");
builder.append(AbstractPathTests.this.getClass().getSimpleName());
builder.append("_");
builder.append(description.getMethodName());
builder.append("_path");
MultipleAnalysisPlotter plotter = new MultipleAnalysisPlotter();
plotter.plotAnalysisResults(pathVerifier.getPaths(), "red");
plotter.writeFile(builder.toString());
}
};
@Test
public void aliasing() {
runTest("java.lang.Aliasing");
pathVerifier.totalPaths(3); | // Path: FlowTwist/test/flow/twist/test/util/selectors/UnitSelectorFactory.java
// public static UnitSelector anyUnit() {
// return new UnitSelector() {
//
// @Override
// public boolean matches(SootMethod method, Unit unit) {
// return true;
// }
//
// @Override
// public String toString() {
// return "any unit";
// }
// };
// }
//
// Path: FlowTwist/test/flow/twist/test/util/selectors/UnitSelectorFactory.java
// public static UnitSelector unitByLabel(final String label) {
// return new UnitSelector() {
// @Override
// public boolean matches(SootMethod method, Unit unit) {
// return unit.toString().contains(label);
// }
//
// @Override
// public String toString() {
// return label;
// }
// };
// }
//
// Path: FlowTwist/test/flow/twist/test/util/selectors/UnitSelectorFactory.java
// public static UnitSelector unitInMethod(final String methodString, final UnitSelector selector) {
// return new UnitSelector() {
// @Override
// public boolean matches(SootMethod method, Unit unit) {
// return method.toString().contains(methodString) && selector.matches(method, unit);
// }
//
// @Override
// public String toString() {
// return "'" + selector.toString() + "' in '" + methodString + "'";
// }
// };
// }
//
// Path: FlowTwist/test/flow/twist/test/util/selectors/UnitSelectorFactory.java
// public static UnitSelector unitWithoutLabel(final String label, final UnitSelector selector) {
// return new UnitSelector() {
// @Override
// public boolean matches(SootMethod method, Unit unit) {
// return !unit.toString().contains(label) && selector.matches(method, unit);
// }
//
// @Override
// public String toString() {
// return "'" + selector.toString() + "' without '" + label + "'";
// }
// };
// }
//
// Path: FlowTwist/test/flow/twist/test/util/PathVerifier.java
// public class PathSelector {
// private List<Path> paths;
//
// public PathSelector(List<Path> paths) {
// this.paths = paths;
// }
//
// public PathSelector endsAt(UnitSelector selector) {
// List<Path> matchingPaths = Lists.newLinkedList();
// for (Path path : paths) {
// Unit unit = path.getLast();
// if (selector.matches(path.context.icfg.getMethodOf(unit), unit)) {
// matchingPaths.add(path);
// }
// }
// return new PathSelector(matchingPaths);
// }
//
// public PathSelector contains(UnitSelector selector) {
// List<Path> matchingPaths = Lists.newLinkedList();
// for (Path path : paths) {
// if (pathContains(selector, path)) {
// matchingPaths.add(path);
// }
// }
// return new PathSelector(matchingPaths);
// }
//
// private boolean pathContains(UnitSelector selector, Path path) {
// for (PathElement element : path) {
// if (selector.matches(path.context.icfg.getMethodOf(element.to), element.to)) {
// return true;
// }
// }
//
// return false;
// }
//
// public PathSelector doesNotContain(UnitSelector selector) {
// List<Path> matchingPaths = Lists.newLinkedList();
// for (Path path : paths) {
// if (!pathContains(selector, path)) {
// matchingPaths.add(path);
// }
// }
// return new PathSelector(matchingPaths);
// }
//
// public void once() {
// Assert.assertEquals(1, paths.size());
// }
//
// public void never() {
// Assert.assertEquals(0, paths.size());
// }
//
// public void noOtherPaths() {
// Assert.assertEquals(paths.size(), PathVerifier.this.paths.size());
// }
//
// public void times(int i) {
// Assert.assertEquals(i, paths.size());
// }
//
// public void assertStack(Unit... callSites) {
// for (Path path : paths) {
// fj.data.List<Object> callStack = path.getCallStack();
// Assert.assertTrue(Iterables.elementsEqual(callStack, Lists.newArrayList(callSites)));
// }
// }
//
// }
// Path: FlowTwist/test/flow/twist/test/util/AbstractPathTests.java
import static flow.twist.test.util.selectors.UnitSelectorFactory.anyUnit;
import static flow.twist.test.util.selectors.UnitSelectorFactory.unitByLabel;
import static flow.twist.test.util.selectors.UnitSelectorFactory.unitInMethod;
import static flow.twist.test.util.selectors.UnitSelectorFactory.unitWithoutLabel;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import flow.twist.test.util.PathVerifier.PathSelector;
import flow.twist.util.MultipleAnalysisPlotter;
package flow.twist.test.util;
public abstract class AbstractPathTests extends AbstractTaintAnalysisTest {
protected PathVerifier pathVerifier;
@Rule
public TestWatcher watcher = new TestWatcher() {
@Override
public void failed(Throwable e, Description description) {
StringBuilder builder = new StringBuilder();
builder.append("tmp/");
builder.append(AbstractPathTests.this.getClass().getSimpleName());
builder.append("_");
builder.append(description.getMethodName());
builder.append("_path");
MultipleAnalysisPlotter plotter = new MultipleAnalysisPlotter();
plotter.plotAnalysisResults(pathVerifier.getPaths(), "red");
plotter.writeFile(builder.toString());
}
};
@Test
public void aliasing() {
runTest("java.lang.Aliasing");
pathVerifier.totalPaths(3); | pathVerifier.startsAt(unitInMethod("nameInput(", unitByLabel("@parameter0"))).endsAt(unitByLabel("return")).once(); |
johanneslerch/FlowTwist | FlowTwist/test/flow/twist/test/util/AbstractPathTests.java | // Path: FlowTwist/test/flow/twist/test/util/selectors/UnitSelectorFactory.java
// public static UnitSelector anyUnit() {
// return new UnitSelector() {
//
// @Override
// public boolean matches(SootMethod method, Unit unit) {
// return true;
// }
//
// @Override
// public String toString() {
// return "any unit";
// }
// };
// }
//
// Path: FlowTwist/test/flow/twist/test/util/selectors/UnitSelectorFactory.java
// public static UnitSelector unitByLabel(final String label) {
// return new UnitSelector() {
// @Override
// public boolean matches(SootMethod method, Unit unit) {
// return unit.toString().contains(label);
// }
//
// @Override
// public String toString() {
// return label;
// }
// };
// }
//
// Path: FlowTwist/test/flow/twist/test/util/selectors/UnitSelectorFactory.java
// public static UnitSelector unitInMethod(final String methodString, final UnitSelector selector) {
// return new UnitSelector() {
// @Override
// public boolean matches(SootMethod method, Unit unit) {
// return method.toString().contains(methodString) && selector.matches(method, unit);
// }
//
// @Override
// public String toString() {
// return "'" + selector.toString() + "' in '" + methodString + "'";
// }
// };
// }
//
// Path: FlowTwist/test/flow/twist/test/util/selectors/UnitSelectorFactory.java
// public static UnitSelector unitWithoutLabel(final String label, final UnitSelector selector) {
// return new UnitSelector() {
// @Override
// public boolean matches(SootMethod method, Unit unit) {
// return !unit.toString().contains(label) && selector.matches(method, unit);
// }
//
// @Override
// public String toString() {
// return "'" + selector.toString() + "' without '" + label + "'";
// }
// };
// }
//
// Path: FlowTwist/test/flow/twist/test/util/PathVerifier.java
// public class PathSelector {
// private List<Path> paths;
//
// public PathSelector(List<Path> paths) {
// this.paths = paths;
// }
//
// public PathSelector endsAt(UnitSelector selector) {
// List<Path> matchingPaths = Lists.newLinkedList();
// for (Path path : paths) {
// Unit unit = path.getLast();
// if (selector.matches(path.context.icfg.getMethodOf(unit), unit)) {
// matchingPaths.add(path);
// }
// }
// return new PathSelector(matchingPaths);
// }
//
// public PathSelector contains(UnitSelector selector) {
// List<Path> matchingPaths = Lists.newLinkedList();
// for (Path path : paths) {
// if (pathContains(selector, path)) {
// matchingPaths.add(path);
// }
// }
// return new PathSelector(matchingPaths);
// }
//
// private boolean pathContains(UnitSelector selector, Path path) {
// for (PathElement element : path) {
// if (selector.matches(path.context.icfg.getMethodOf(element.to), element.to)) {
// return true;
// }
// }
//
// return false;
// }
//
// public PathSelector doesNotContain(UnitSelector selector) {
// List<Path> matchingPaths = Lists.newLinkedList();
// for (Path path : paths) {
// if (!pathContains(selector, path)) {
// matchingPaths.add(path);
// }
// }
// return new PathSelector(matchingPaths);
// }
//
// public void once() {
// Assert.assertEquals(1, paths.size());
// }
//
// public void never() {
// Assert.assertEquals(0, paths.size());
// }
//
// public void noOtherPaths() {
// Assert.assertEquals(paths.size(), PathVerifier.this.paths.size());
// }
//
// public void times(int i) {
// Assert.assertEquals(i, paths.size());
// }
//
// public void assertStack(Unit... callSites) {
// for (Path path : paths) {
// fj.data.List<Object> callStack = path.getCallStack();
// Assert.assertTrue(Iterables.elementsEqual(callStack, Lists.newArrayList(callSites)));
// }
// }
//
// }
| import static flow.twist.test.util.selectors.UnitSelectorFactory.anyUnit;
import static flow.twist.test.util.selectors.UnitSelectorFactory.unitByLabel;
import static flow.twist.test.util.selectors.UnitSelectorFactory.unitInMethod;
import static flow.twist.test.util.selectors.UnitSelectorFactory.unitWithoutLabel;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import flow.twist.test.util.PathVerifier.PathSelector;
import flow.twist.util.MultipleAnalysisPlotter; | package flow.twist.test.util;
public abstract class AbstractPathTests extends AbstractTaintAnalysisTest {
protected PathVerifier pathVerifier;
@Rule
public TestWatcher watcher = new TestWatcher() {
@Override
public void failed(Throwable e, Description description) {
StringBuilder builder = new StringBuilder();
builder.append("tmp/");
builder.append(AbstractPathTests.this.getClass().getSimpleName());
builder.append("_");
builder.append(description.getMethodName());
builder.append("_path");
MultipleAnalysisPlotter plotter = new MultipleAnalysisPlotter();
plotter.plotAnalysisResults(pathVerifier.getPaths(), "red");
plotter.writeFile(builder.toString());
}
};
@Test
public void aliasing() {
runTest("java.lang.Aliasing");
pathVerifier.totalPaths(3); | // Path: FlowTwist/test/flow/twist/test/util/selectors/UnitSelectorFactory.java
// public static UnitSelector anyUnit() {
// return new UnitSelector() {
//
// @Override
// public boolean matches(SootMethod method, Unit unit) {
// return true;
// }
//
// @Override
// public String toString() {
// return "any unit";
// }
// };
// }
//
// Path: FlowTwist/test/flow/twist/test/util/selectors/UnitSelectorFactory.java
// public static UnitSelector unitByLabel(final String label) {
// return new UnitSelector() {
// @Override
// public boolean matches(SootMethod method, Unit unit) {
// return unit.toString().contains(label);
// }
//
// @Override
// public String toString() {
// return label;
// }
// };
// }
//
// Path: FlowTwist/test/flow/twist/test/util/selectors/UnitSelectorFactory.java
// public static UnitSelector unitInMethod(final String methodString, final UnitSelector selector) {
// return new UnitSelector() {
// @Override
// public boolean matches(SootMethod method, Unit unit) {
// return method.toString().contains(methodString) && selector.matches(method, unit);
// }
//
// @Override
// public String toString() {
// return "'" + selector.toString() + "' in '" + methodString + "'";
// }
// };
// }
//
// Path: FlowTwist/test/flow/twist/test/util/selectors/UnitSelectorFactory.java
// public static UnitSelector unitWithoutLabel(final String label, final UnitSelector selector) {
// return new UnitSelector() {
// @Override
// public boolean matches(SootMethod method, Unit unit) {
// return !unit.toString().contains(label) && selector.matches(method, unit);
// }
//
// @Override
// public String toString() {
// return "'" + selector.toString() + "' without '" + label + "'";
// }
// };
// }
//
// Path: FlowTwist/test/flow/twist/test/util/PathVerifier.java
// public class PathSelector {
// private List<Path> paths;
//
// public PathSelector(List<Path> paths) {
// this.paths = paths;
// }
//
// public PathSelector endsAt(UnitSelector selector) {
// List<Path> matchingPaths = Lists.newLinkedList();
// for (Path path : paths) {
// Unit unit = path.getLast();
// if (selector.matches(path.context.icfg.getMethodOf(unit), unit)) {
// matchingPaths.add(path);
// }
// }
// return new PathSelector(matchingPaths);
// }
//
// public PathSelector contains(UnitSelector selector) {
// List<Path> matchingPaths = Lists.newLinkedList();
// for (Path path : paths) {
// if (pathContains(selector, path)) {
// matchingPaths.add(path);
// }
// }
// return new PathSelector(matchingPaths);
// }
//
// private boolean pathContains(UnitSelector selector, Path path) {
// for (PathElement element : path) {
// if (selector.matches(path.context.icfg.getMethodOf(element.to), element.to)) {
// return true;
// }
// }
//
// return false;
// }
//
// public PathSelector doesNotContain(UnitSelector selector) {
// List<Path> matchingPaths = Lists.newLinkedList();
// for (Path path : paths) {
// if (!pathContains(selector, path)) {
// matchingPaths.add(path);
// }
// }
// return new PathSelector(matchingPaths);
// }
//
// public void once() {
// Assert.assertEquals(1, paths.size());
// }
//
// public void never() {
// Assert.assertEquals(0, paths.size());
// }
//
// public void noOtherPaths() {
// Assert.assertEquals(paths.size(), PathVerifier.this.paths.size());
// }
//
// public void times(int i) {
// Assert.assertEquals(i, paths.size());
// }
//
// public void assertStack(Unit... callSites) {
// for (Path path : paths) {
// fj.data.List<Object> callStack = path.getCallStack();
// Assert.assertTrue(Iterables.elementsEqual(callStack, Lists.newArrayList(callSites)));
// }
// }
//
// }
// Path: FlowTwist/test/flow/twist/test/util/AbstractPathTests.java
import static flow.twist.test.util.selectors.UnitSelectorFactory.anyUnit;
import static flow.twist.test.util.selectors.UnitSelectorFactory.unitByLabel;
import static flow.twist.test.util.selectors.UnitSelectorFactory.unitInMethod;
import static flow.twist.test.util.selectors.UnitSelectorFactory.unitWithoutLabel;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import flow.twist.test.util.PathVerifier.PathSelector;
import flow.twist.util.MultipleAnalysisPlotter;
package flow.twist.test.util;
public abstract class AbstractPathTests extends AbstractTaintAnalysisTest {
protected PathVerifier pathVerifier;
@Rule
public TestWatcher watcher = new TestWatcher() {
@Override
public void failed(Throwable e, Description description) {
StringBuilder builder = new StringBuilder();
builder.append("tmp/");
builder.append(AbstractPathTests.this.getClass().getSimpleName());
builder.append("_");
builder.append(description.getMethodName());
builder.append("_path");
MultipleAnalysisPlotter plotter = new MultipleAnalysisPlotter();
plotter.plotAnalysisResults(pathVerifier.getPaths(), "red");
plotter.writeFile(builder.toString());
}
};
@Test
public void aliasing() {
runTest("java.lang.Aliasing");
pathVerifier.totalPaths(3); | pathVerifier.startsAt(unitInMethod("nameInput(", unitByLabel("@parameter0"))).endsAt(unitByLabel("return")).once(); |
johanneslerch/FlowTwist | FlowTwist/test/flow/twist/test/util/AnalysisGraphVerifier.java | // Path: FlowTwist/test/flow/twist/test/util/selectors/TrackableSelector.java
// public interface TrackableSelector {
// boolean matches(Trackable trackable);
// }
//
// Path: FlowTwist/test/flow/twist/test/util/selectors/UnitSelector.java
// public interface UnitSelector {
// boolean matches(SootMethod method, Unit unit);
// }
//
// Path: FlowTwist/src/flow/twist/trackable/Trackable.java
// public abstract class Trackable implements LinkedNode<Trackable> {
//
// public final Trackable predecessor;
// public final Unit sourceUnit;
// private final List<Trackable> neighbors;
// private final Set<Object> payload;
//
// protected Trackable() {
// this.predecessor = null;
// this.sourceUnit = null;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// }
//
// public Trackable(Unit sourceUnit, Trackable predecessor) {
// this.predecessor = predecessor;
// this.sourceUnit = sourceUnit;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// payload.addAll(predecessor.payload);
// }
//
// public void addPayload(Object payload) {
// this.payload.add(payload);
// }
//
// public void addNeighbor(Trackable trackable) {
// // trackable.neighbors.addAll(getSelfAndNeighbors());
// neighbors.add(trackable);
// }
//
// public Collection<Trackable> getSelfAndNeighbors() {
// LinkedList<Trackable> result = Lists.newLinkedList(neighbors);
// result.add(this);
// return result;
// }
//
// public boolean hasSelfOrNeighborAnPredecessor() {
// for (Trackable t : getSelfAndNeighbors())
// if (t.predecessor != null)
// return true;
// return false;
// }
//
// public abstract Trackable cloneWithoutNeighborsAndPayload();
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((payload == null) ? 0 : payload.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Trackable))
// return false;
// Trackable other = (Trackable) obj;
// if (payload == null) {
// if (other.payload != null)
// return false;
// } else if (!payload.equals(other.payload))
// return false;
// return true;
// }
//
// public String payloadString() {
// if (payload.size() == 0)
// return "";
// return "(" + Joiner.on(",").join(payload) + ")";
// }
//
// public abstract Trackable createAlias(Unit sourceUnits);
//
// public Collection<Object> getPayload() {
// return payload;
// }
// }
| import static java.lang.String.format;
import heros.solver.Pair;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import junit.framework.AssertionFailedError;
import org.junit.Assert;
import soot.SootMethod;
import soot.Unit;
import soot.util.IdentityHashSet;
import com.google.common.base.Supplier;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
import flow.twist.config.AnalysisContext;
import flow.twist.reporter.IfdsReporter;
import flow.twist.reporter.Report;
import flow.twist.reporter.TrackableGraphPlotter;
import flow.twist.test.util.selectors.TrackableSelector;
import flow.twist.test.util.selectors.UnitSelector;
import flow.twist.trackable.Trackable; | package flow.twist.test.util;
public class AnalysisGraphVerifier implements IfdsReporter {
private TrackableGraphPlotter debugPlotter;
private Map<Unit, SootMethod> unit2Method = Maps.newHashMap(); | // Path: FlowTwist/test/flow/twist/test/util/selectors/TrackableSelector.java
// public interface TrackableSelector {
// boolean matches(Trackable trackable);
// }
//
// Path: FlowTwist/test/flow/twist/test/util/selectors/UnitSelector.java
// public interface UnitSelector {
// boolean matches(SootMethod method, Unit unit);
// }
//
// Path: FlowTwist/src/flow/twist/trackable/Trackable.java
// public abstract class Trackable implements LinkedNode<Trackable> {
//
// public final Trackable predecessor;
// public final Unit sourceUnit;
// private final List<Trackable> neighbors;
// private final Set<Object> payload;
//
// protected Trackable() {
// this.predecessor = null;
// this.sourceUnit = null;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// }
//
// public Trackable(Unit sourceUnit, Trackable predecessor) {
// this.predecessor = predecessor;
// this.sourceUnit = sourceUnit;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// payload.addAll(predecessor.payload);
// }
//
// public void addPayload(Object payload) {
// this.payload.add(payload);
// }
//
// public void addNeighbor(Trackable trackable) {
// // trackable.neighbors.addAll(getSelfAndNeighbors());
// neighbors.add(trackable);
// }
//
// public Collection<Trackable> getSelfAndNeighbors() {
// LinkedList<Trackable> result = Lists.newLinkedList(neighbors);
// result.add(this);
// return result;
// }
//
// public boolean hasSelfOrNeighborAnPredecessor() {
// for (Trackable t : getSelfAndNeighbors())
// if (t.predecessor != null)
// return true;
// return false;
// }
//
// public abstract Trackable cloneWithoutNeighborsAndPayload();
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((payload == null) ? 0 : payload.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Trackable))
// return false;
// Trackable other = (Trackable) obj;
// if (payload == null) {
// if (other.payload != null)
// return false;
// } else if (!payload.equals(other.payload))
// return false;
// return true;
// }
//
// public String payloadString() {
// if (payload.size() == 0)
// return "";
// return "(" + Joiner.on(",").join(payload) + ")";
// }
//
// public abstract Trackable createAlias(Unit sourceUnits);
//
// public Collection<Object> getPayload() {
// return payload;
// }
// }
// Path: FlowTwist/test/flow/twist/test/util/AnalysisGraphVerifier.java
import static java.lang.String.format;
import heros.solver.Pair;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import junit.framework.AssertionFailedError;
import org.junit.Assert;
import soot.SootMethod;
import soot.Unit;
import soot.util.IdentityHashSet;
import com.google.common.base.Supplier;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
import flow.twist.config.AnalysisContext;
import flow.twist.reporter.IfdsReporter;
import flow.twist.reporter.Report;
import flow.twist.reporter.TrackableGraphPlotter;
import flow.twist.test.util.selectors.TrackableSelector;
import flow.twist.test.util.selectors.UnitSelector;
import flow.twist.trackable.Trackable;
package flow.twist.test.util;
public class AnalysisGraphVerifier implements IfdsReporter {
private TrackableGraphPlotter debugPlotter;
private Map<Unit, SootMethod> unit2Method = Maps.newHashMap(); | private Multimap<Unit, Pair<Unit, Trackable>> successors = HashMultimap.create(); |
johanneslerch/FlowTwist | FlowTwist/test/flow/twist/test/util/AnalysisGraphVerifier.java | // Path: FlowTwist/test/flow/twist/test/util/selectors/TrackableSelector.java
// public interface TrackableSelector {
// boolean matches(Trackable trackable);
// }
//
// Path: FlowTwist/test/flow/twist/test/util/selectors/UnitSelector.java
// public interface UnitSelector {
// boolean matches(SootMethod method, Unit unit);
// }
//
// Path: FlowTwist/src/flow/twist/trackable/Trackable.java
// public abstract class Trackable implements LinkedNode<Trackable> {
//
// public final Trackable predecessor;
// public final Unit sourceUnit;
// private final List<Trackable> neighbors;
// private final Set<Object> payload;
//
// protected Trackable() {
// this.predecessor = null;
// this.sourceUnit = null;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// }
//
// public Trackable(Unit sourceUnit, Trackable predecessor) {
// this.predecessor = predecessor;
// this.sourceUnit = sourceUnit;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// payload.addAll(predecessor.payload);
// }
//
// public void addPayload(Object payload) {
// this.payload.add(payload);
// }
//
// public void addNeighbor(Trackable trackable) {
// // trackable.neighbors.addAll(getSelfAndNeighbors());
// neighbors.add(trackable);
// }
//
// public Collection<Trackable> getSelfAndNeighbors() {
// LinkedList<Trackable> result = Lists.newLinkedList(neighbors);
// result.add(this);
// return result;
// }
//
// public boolean hasSelfOrNeighborAnPredecessor() {
// for (Trackable t : getSelfAndNeighbors())
// if (t.predecessor != null)
// return true;
// return false;
// }
//
// public abstract Trackable cloneWithoutNeighborsAndPayload();
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((payload == null) ? 0 : payload.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Trackable))
// return false;
// Trackable other = (Trackable) obj;
// if (payload == null) {
// if (other.payload != null)
// return false;
// } else if (!payload.equals(other.payload))
// return false;
// return true;
// }
//
// public String payloadString() {
// if (payload.size() == 0)
// return "";
// return "(" + Joiner.on(",").join(payload) + ")";
// }
//
// public abstract Trackable createAlias(Unit sourceUnits);
//
// public Collection<Object> getPayload() {
// return payload;
// }
// }
| import static java.lang.String.format;
import heros.solver.Pair;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import junit.framework.AssertionFailedError;
import org.junit.Assert;
import soot.SootMethod;
import soot.Unit;
import soot.util.IdentityHashSet;
import com.google.common.base.Supplier;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
import flow.twist.config.AnalysisContext;
import flow.twist.reporter.IfdsReporter;
import flow.twist.reporter.Report;
import flow.twist.reporter.TrackableGraphPlotter;
import flow.twist.test.util.selectors.TrackableSelector;
import flow.twist.test.util.selectors.UnitSelector;
import flow.twist.trackable.Trackable; | }
@Override
public void reportTrackable(Report report) {
debugPlotter.reportTrackable(report);
createEdges(report.context, report.trackable, report.targetUnit);
}
private void createEdges(AnalysisContext context, Trackable trackable, Unit unit) {
unit2Method.put(unit, context.icfg.getMethodOf(unit));
for (Trackable neighbor : trackable.getSelfAndNeighbors()) {
trackablesAtUnit.put(unit, neighbor);
if (neighbor.sourceUnit == null)
continue;
if (successors.put(neighbor.sourceUnit, new Pair<Unit, Trackable>(unit, neighbor)))
createEdges(context, neighbor.predecessor, neighbor.sourceUnit);
}
}
@Override
public void analysisFinished() {
}
public void writeDebugFile(String fileName) {
System.out.println("Writing debug graph file for failed test: " + fileName);
debugPlotter.writeFile(fileName);
}
| // Path: FlowTwist/test/flow/twist/test/util/selectors/TrackableSelector.java
// public interface TrackableSelector {
// boolean matches(Trackable trackable);
// }
//
// Path: FlowTwist/test/flow/twist/test/util/selectors/UnitSelector.java
// public interface UnitSelector {
// boolean matches(SootMethod method, Unit unit);
// }
//
// Path: FlowTwist/src/flow/twist/trackable/Trackable.java
// public abstract class Trackable implements LinkedNode<Trackable> {
//
// public final Trackable predecessor;
// public final Unit sourceUnit;
// private final List<Trackable> neighbors;
// private final Set<Object> payload;
//
// protected Trackable() {
// this.predecessor = null;
// this.sourceUnit = null;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// }
//
// public Trackable(Unit sourceUnit, Trackable predecessor) {
// this.predecessor = predecessor;
// this.sourceUnit = sourceUnit;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// payload.addAll(predecessor.payload);
// }
//
// public void addPayload(Object payload) {
// this.payload.add(payload);
// }
//
// public void addNeighbor(Trackable trackable) {
// // trackable.neighbors.addAll(getSelfAndNeighbors());
// neighbors.add(trackable);
// }
//
// public Collection<Trackable> getSelfAndNeighbors() {
// LinkedList<Trackable> result = Lists.newLinkedList(neighbors);
// result.add(this);
// return result;
// }
//
// public boolean hasSelfOrNeighborAnPredecessor() {
// for (Trackable t : getSelfAndNeighbors())
// if (t.predecessor != null)
// return true;
// return false;
// }
//
// public abstract Trackable cloneWithoutNeighborsAndPayload();
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((payload == null) ? 0 : payload.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Trackable))
// return false;
// Trackable other = (Trackable) obj;
// if (payload == null) {
// if (other.payload != null)
// return false;
// } else if (!payload.equals(other.payload))
// return false;
// return true;
// }
//
// public String payloadString() {
// if (payload.size() == 0)
// return "";
// return "(" + Joiner.on(",").join(payload) + ")";
// }
//
// public abstract Trackable createAlias(Unit sourceUnits);
//
// public Collection<Object> getPayload() {
// return payload;
// }
// }
// Path: FlowTwist/test/flow/twist/test/util/AnalysisGraphVerifier.java
import static java.lang.String.format;
import heros.solver.Pair;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import junit.framework.AssertionFailedError;
import org.junit.Assert;
import soot.SootMethod;
import soot.Unit;
import soot.util.IdentityHashSet;
import com.google.common.base.Supplier;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
import flow.twist.config.AnalysisContext;
import flow.twist.reporter.IfdsReporter;
import flow.twist.reporter.Report;
import flow.twist.reporter.TrackableGraphPlotter;
import flow.twist.test.util.selectors.TrackableSelector;
import flow.twist.test.util.selectors.UnitSelector;
import flow.twist.trackable.Trackable;
}
@Override
public void reportTrackable(Report report) {
debugPlotter.reportTrackable(report);
createEdges(report.context, report.trackable, report.targetUnit);
}
private void createEdges(AnalysisContext context, Trackable trackable, Unit unit) {
unit2Method.put(unit, context.icfg.getMethodOf(unit));
for (Trackable neighbor : trackable.getSelfAndNeighbors()) {
trackablesAtUnit.put(unit, neighbor);
if (neighbor.sourceUnit == null)
continue;
if (successors.put(neighbor.sourceUnit, new Pair<Unit, Trackable>(unit, neighbor)))
createEdges(context, neighbor.predecessor, neighbor.sourceUnit);
}
}
@Override
public void analysisFinished() {
}
public void writeDebugFile(String fileName) {
System.out.println("Writing debug graph file for failed test: " + fileName);
debugPlotter.writeFile(fileName);
}
| public UnitNode find(UnitSelector selector) { |
johanneslerch/FlowTwist | FlowTwist/test/flow/twist/test/util/AnalysisGraphVerifier.java | // Path: FlowTwist/test/flow/twist/test/util/selectors/TrackableSelector.java
// public interface TrackableSelector {
// boolean matches(Trackable trackable);
// }
//
// Path: FlowTwist/test/flow/twist/test/util/selectors/UnitSelector.java
// public interface UnitSelector {
// boolean matches(SootMethod method, Unit unit);
// }
//
// Path: FlowTwist/src/flow/twist/trackable/Trackable.java
// public abstract class Trackable implements LinkedNode<Trackable> {
//
// public final Trackable predecessor;
// public final Unit sourceUnit;
// private final List<Trackable> neighbors;
// private final Set<Object> payload;
//
// protected Trackable() {
// this.predecessor = null;
// this.sourceUnit = null;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// }
//
// public Trackable(Unit sourceUnit, Trackable predecessor) {
// this.predecessor = predecessor;
// this.sourceUnit = sourceUnit;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// payload.addAll(predecessor.payload);
// }
//
// public void addPayload(Object payload) {
// this.payload.add(payload);
// }
//
// public void addNeighbor(Trackable trackable) {
// // trackable.neighbors.addAll(getSelfAndNeighbors());
// neighbors.add(trackable);
// }
//
// public Collection<Trackable> getSelfAndNeighbors() {
// LinkedList<Trackable> result = Lists.newLinkedList(neighbors);
// result.add(this);
// return result;
// }
//
// public boolean hasSelfOrNeighborAnPredecessor() {
// for (Trackable t : getSelfAndNeighbors())
// if (t.predecessor != null)
// return true;
// return false;
// }
//
// public abstract Trackable cloneWithoutNeighborsAndPayload();
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((payload == null) ? 0 : payload.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Trackable))
// return false;
// Trackable other = (Trackable) obj;
// if (payload == null) {
// if (other.payload != null)
// return false;
// } else if (!payload.equals(other.payload))
// return false;
// return true;
// }
//
// public String payloadString() {
// if (payload.size() == 0)
// return "";
// return "(" + Joiner.on(",").join(payload) + ")";
// }
//
// public abstract Trackable createAlias(Unit sourceUnits);
//
// public Collection<Object> getPayload() {
// return payload;
// }
// }
| import static java.lang.String.format;
import heros.solver.Pair;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import junit.framework.AssertionFailedError;
import org.junit.Assert;
import soot.SootMethod;
import soot.Unit;
import soot.util.IdentityHashSet;
import com.google.common.base.Supplier;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
import flow.twist.config.AnalysisContext;
import flow.twist.reporter.IfdsReporter;
import flow.twist.reporter.Report;
import flow.twist.reporter.TrackableGraphPlotter;
import flow.twist.test.util.selectors.TrackableSelector;
import flow.twist.test.util.selectors.UnitSelector;
import flow.twist.trackable.Trackable; | public void writeDebugFile(String fileName) {
System.out.println("Writing debug graph file for failed test: " + fileName);
debugPlotter.writeFile(fileName);
}
public UnitNode find(UnitSelector selector) {
for (Unit unit : unit2Method.keySet()) {
if (selector.matches(unit2Method.get(unit), unit)) {
return new UnitNode(unit);
}
}
throw new AssertionFailedError(format("Unit not found: %s", selector));
}
public void cannotFind(UnitSelector selector) {
for (Unit unit : unit2Method.keySet()) {
if (selector.matches(unit2Method.get(unit), unit)) {
throw new AssertionFailedError(format("Unit found: %s", selector));
}
}
}
public class UnitNode {
private final Unit unit;
public UnitNode(Unit unit) {
this.unit = unit;
}
| // Path: FlowTwist/test/flow/twist/test/util/selectors/TrackableSelector.java
// public interface TrackableSelector {
// boolean matches(Trackable trackable);
// }
//
// Path: FlowTwist/test/flow/twist/test/util/selectors/UnitSelector.java
// public interface UnitSelector {
// boolean matches(SootMethod method, Unit unit);
// }
//
// Path: FlowTwist/src/flow/twist/trackable/Trackable.java
// public abstract class Trackable implements LinkedNode<Trackable> {
//
// public final Trackable predecessor;
// public final Unit sourceUnit;
// private final List<Trackable> neighbors;
// private final Set<Object> payload;
//
// protected Trackable() {
// this.predecessor = null;
// this.sourceUnit = null;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// }
//
// public Trackable(Unit sourceUnit, Trackable predecessor) {
// this.predecessor = predecessor;
// this.sourceUnit = sourceUnit;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// payload.addAll(predecessor.payload);
// }
//
// public void addPayload(Object payload) {
// this.payload.add(payload);
// }
//
// public void addNeighbor(Trackable trackable) {
// // trackable.neighbors.addAll(getSelfAndNeighbors());
// neighbors.add(trackable);
// }
//
// public Collection<Trackable> getSelfAndNeighbors() {
// LinkedList<Trackable> result = Lists.newLinkedList(neighbors);
// result.add(this);
// return result;
// }
//
// public boolean hasSelfOrNeighborAnPredecessor() {
// for (Trackable t : getSelfAndNeighbors())
// if (t.predecessor != null)
// return true;
// return false;
// }
//
// public abstract Trackable cloneWithoutNeighborsAndPayload();
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((payload == null) ? 0 : payload.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Trackable))
// return false;
// Trackable other = (Trackable) obj;
// if (payload == null) {
// if (other.payload != null)
// return false;
// } else if (!payload.equals(other.payload))
// return false;
// return true;
// }
//
// public String payloadString() {
// if (payload.size() == 0)
// return "";
// return "(" + Joiner.on(",").join(payload) + ")";
// }
//
// public abstract Trackable createAlias(Unit sourceUnits);
//
// public Collection<Object> getPayload() {
// return payload;
// }
// }
// Path: FlowTwist/test/flow/twist/test/util/AnalysisGraphVerifier.java
import static java.lang.String.format;
import heros.solver.Pair;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import junit.framework.AssertionFailedError;
import org.junit.Assert;
import soot.SootMethod;
import soot.Unit;
import soot.util.IdentityHashSet;
import com.google.common.base.Supplier;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
import flow.twist.config.AnalysisContext;
import flow.twist.reporter.IfdsReporter;
import flow.twist.reporter.Report;
import flow.twist.reporter.TrackableGraphPlotter;
import flow.twist.test.util.selectors.TrackableSelector;
import flow.twist.test.util.selectors.UnitSelector;
import flow.twist.trackable.Trackable;
public void writeDebugFile(String fileName) {
System.out.println("Writing debug graph file for failed test: " + fileName);
debugPlotter.writeFile(fileName);
}
public UnitNode find(UnitSelector selector) {
for (Unit unit : unit2Method.keySet()) {
if (selector.matches(unit2Method.get(unit), unit)) {
return new UnitNode(unit);
}
}
throw new AssertionFailedError(format("Unit not found: %s", selector));
}
public void cannotFind(UnitSelector selector) {
for (Unit unit : unit2Method.keySet()) {
if (selector.matches(unit2Method.get(unit), unit)) {
throw new AssertionFailedError(format("Unit found: %s", selector));
}
}
}
public class UnitNode {
private final Unit unit;
public UnitNode(Unit unit) {
this.unit = unit;
}
| public UnitNode edge(TrackableSelector trackableSelector, UnitSelector unitSelector) { |
johanneslerch/FlowTwist | FlowTwist/src/flow/twist/ifds/TabulationProblem.java | // Path: FlowTwist/src/flow/twist/trackable/Trackable.java
// public abstract class Trackable implements LinkedNode<Trackable> {
//
// public final Trackable predecessor;
// public final Unit sourceUnit;
// private final List<Trackable> neighbors;
// private final Set<Object> payload;
//
// protected Trackable() {
// this.predecessor = null;
// this.sourceUnit = null;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// }
//
// public Trackable(Unit sourceUnit, Trackable predecessor) {
// this.predecessor = predecessor;
// this.sourceUnit = sourceUnit;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// payload.addAll(predecessor.payload);
// }
//
// public void addPayload(Object payload) {
// this.payload.add(payload);
// }
//
// public void addNeighbor(Trackable trackable) {
// // trackable.neighbors.addAll(getSelfAndNeighbors());
// neighbors.add(trackable);
// }
//
// public Collection<Trackable> getSelfAndNeighbors() {
// LinkedList<Trackable> result = Lists.newLinkedList(neighbors);
// result.add(this);
// return result;
// }
//
// public boolean hasSelfOrNeighborAnPredecessor() {
// for (Trackable t : getSelfAndNeighbors())
// if (t.predecessor != null)
// return true;
// return false;
// }
//
// public abstract Trackable cloneWithoutNeighborsAndPayload();
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((payload == null) ? 0 : payload.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Trackable))
// return false;
// Trackable other = (Trackable) obj;
// if (payload == null) {
// if (other.payload != null)
// return false;
// } else if (!payload.equals(other.payload))
// return false;
// return true;
// }
//
// public String payloadString() {
// if (payload.size() == 0)
// return "";
// return "(" + Joiner.on(",").join(payload) + ")";
// }
//
// public abstract Trackable createAlias(Unit sourceUnits);
//
// public Collection<Object> getPayload() {
// return payload;
// }
// }
//
// Path: FlowTwist/src/flow/twist/trackable/Zero.java
// public class Zero extends Trackable {
//
// private Zero() {
// super();
// }
//
// public static final Trackable ZERO = new Zero();
//
// @Override
// public String toString() {
// return "ZERO";
// }
//
// @Override
// public Trackable createAlias(Unit sourceUnits) {
// throw new IllegalStateException("Never propagate ZERO, thus don't create any alias.");
// }
//
// @Override
// public Trackable cloneWithoutNeighborsAndPayload() {
// return ZERO;
// }
//
// @Override
// public int hashCode() {
// return 23543865;
// }
//
// @Override
// public boolean equals(Object obj) {
// return this == obj;
// }
// }
| import heros.DefaultSeeds;
import heros.FlowFunctions;
import java.util.Map;
import java.util.Set;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.toolkits.ide.DefaultJimpleIFDSTabulationProblem;
import soot.jimple.toolkits.ide.icfg.BackwardsInterproceduralCFG;
import soot.jimple.toolkits.ide.icfg.BiDiInterproceduralCFG;
import soot.jimple.toolkits.ide.icfg.JimpleBasedInterproceduralCFG;
import flow.twist.config.AnalysisConfiguration;
import flow.twist.config.AnalysisContext;
import flow.twist.config.AnalysisDirection;
import flow.twist.targets.AnalysisTarget;
import flow.twist.trackable.Trackable;
import flow.twist.trackable.Zero; | this.context = new AnalysisContext(config, interproceduralCFG());
flowFunctionFactory = new FlowFunctionFactory(this.context);
}
private static BiDiInterproceduralCFG<Unit, SootMethod> makeICFG(AnalysisDirection direction) {
JimpleBasedInterproceduralCFG fwdIcfg = new JimpleBasedInterproceduralCFG();
if (direction == AnalysisDirection.FORWARDS)
return fwdIcfg;
else
return new BackwardsInterproceduralCFG(fwdIcfg);
}
@Override
public Map<Unit, Set<Trackable>> initialSeeds() {
return DefaultSeeds.make(context.seedFactory.initialSeeds(context), zeroValue());
}
public void startReturningDeferredTargets() {
for (AnalysisTarget target : context.targets) {
target.enableIfDeferred();
}
}
@Override
protected FlowFunctions<Unit, Trackable, SootMethod> createFlowFunctionsFactory() {
return flowFunctionFactory;
}
@Override
protected Trackable createZeroValue() { | // Path: FlowTwist/src/flow/twist/trackable/Trackable.java
// public abstract class Trackable implements LinkedNode<Trackable> {
//
// public final Trackable predecessor;
// public final Unit sourceUnit;
// private final List<Trackable> neighbors;
// private final Set<Object> payload;
//
// protected Trackable() {
// this.predecessor = null;
// this.sourceUnit = null;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// }
//
// public Trackable(Unit sourceUnit, Trackable predecessor) {
// this.predecessor = predecessor;
// this.sourceUnit = sourceUnit;
// payload = Sets.newHashSet();
// neighbors = Lists.newLinkedList();
// payload.addAll(predecessor.payload);
// }
//
// public void addPayload(Object payload) {
// this.payload.add(payload);
// }
//
// public void addNeighbor(Trackable trackable) {
// // trackable.neighbors.addAll(getSelfAndNeighbors());
// neighbors.add(trackable);
// }
//
// public Collection<Trackable> getSelfAndNeighbors() {
// LinkedList<Trackable> result = Lists.newLinkedList(neighbors);
// result.add(this);
// return result;
// }
//
// public boolean hasSelfOrNeighborAnPredecessor() {
// for (Trackable t : getSelfAndNeighbors())
// if (t.predecessor != null)
// return true;
// return false;
// }
//
// public abstract Trackable cloneWithoutNeighborsAndPayload();
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((payload == null) ? 0 : payload.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (!(obj instanceof Trackable))
// return false;
// Trackable other = (Trackable) obj;
// if (payload == null) {
// if (other.payload != null)
// return false;
// } else if (!payload.equals(other.payload))
// return false;
// return true;
// }
//
// public String payloadString() {
// if (payload.size() == 0)
// return "";
// return "(" + Joiner.on(",").join(payload) + ")";
// }
//
// public abstract Trackable createAlias(Unit sourceUnits);
//
// public Collection<Object> getPayload() {
// return payload;
// }
// }
//
// Path: FlowTwist/src/flow/twist/trackable/Zero.java
// public class Zero extends Trackable {
//
// private Zero() {
// super();
// }
//
// public static final Trackable ZERO = new Zero();
//
// @Override
// public String toString() {
// return "ZERO";
// }
//
// @Override
// public Trackable createAlias(Unit sourceUnits) {
// throw new IllegalStateException("Never propagate ZERO, thus don't create any alias.");
// }
//
// @Override
// public Trackable cloneWithoutNeighborsAndPayload() {
// return ZERO;
// }
//
// @Override
// public int hashCode() {
// return 23543865;
// }
//
// @Override
// public boolean equals(Object obj) {
// return this == obj;
// }
// }
// Path: FlowTwist/src/flow/twist/ifds/TabulationProblem.java
import heros.DefaultSeeds;
import heros.FlowFunctions;
import java.util.Map;
import java.util.Set;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.toolkits.ide.DefaultJimpleIFDSTabulationProblem;
import soot.jimple.toolkits.ide.icfg.BackwardsInterproceduralCFG;
import soot.jimple.toolkits.ide.icfg.BiDiInterproceduralCFG;
import soot.jimple.toolkits.ide.icfg.JimpleBasedInterproceduralCFG;
import flow.twist.config.AnalysisConfiguration;
import flow.twist.config.AnalysisContext;
import flow.twist.config.AnalysisDirection;
import flow.twist.targets.AnalysisTarget;
import flow.twist.trackable.Trackable;
import flow.twist.trackable.Zero;
this.context = new AnalysisContext(config, interproceduralCFG());
flowFunctionFactory = new FlowFunctionFactory(this.context);
}
private static BiDiInterproceduralCFG<Unit, SootMethod> makeICFG(AnalysisDirection direction) {
JimpleBasedInterproceduralCFG fwdIcfg = new JimpleBasedInterproceduralCFG();
if (direction == AnalysisDirection.FORWARDS)
return fwdIcfg;
else
return new BackwardsInterproceduralCFG(fwdIcfg);
}
@Override
public Map<Unit, Set<Trackable>> initialSeeds() {
return DefaultSeeds.make(context.seedFactory.initialSeeds(context), zeroValue());
}
public void startReturningDeferredTargets() {
for (AnalysisTarget target : context.targets) {
target.enableIfDeferred();
}
}
@Override
protected FlowFunctions<Unit, Trackable, SootMethod> createFlowFunctionsFactory() {
return flowFunctionFactory;
}
@Override
protected Trackable createZeroValue() { | return Zero.ZERO; |
johanneslerch/FlowTwist | FlowTwist/test/flow/twist/test/util/PathVerifier.java | // Path: FlowTwist/test/flow/twist/test/util/selectors/UnitSelector.java
// public interface UnitSelector {
// boolean matches(SootMethod method, Unit unit);
// }
| import java.util.List;
import java.util.Set;
import org.junit.Assert;
import soot.Unit;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import flow.twist.path.Path;
import flow.twist.path.PathElement;
import flow.twist.test.util.selectors.UnitSelector; | package flow.twist.test.util;
public class PathVerifier {
private Set<Path> paths;
public PathVerifier(Set<Path> paths) {
this.paths = paths;
}
public void totalPaths(int numberOfExpectedPaths) {
Assert.assertEquals(numberOfExpectedPaths, paths.size());
}
public Set<Path> getPaths() {
return paths;
}
| // Path: FlowTwist/test/flow/twist/test/util/selectors/UnitSelector.java
// public interface UnitSelector {
// boolean matches(SootMethod method, Unit unit);
// }
// Path: FlowTwist/test/flow/twist/test/util/PathVerifier.java
import java.util.List;
import java.util.Set;
import org.junit.Assert;
import soot.Unit;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import flow.twist.path.Path;
import flow.twist.path.PathElement;
import flow.twist.test.util.selectors.UnitSelector;
package flow.twist.test.util;
public class PathVerifier {
private Set<Path> paths;
public PathVerifier(Set<Path> paths) {
this.paths = paths;
}
public void totalPaths(int numberOfExpectedPaths) {
Assert.assertEquals(numberOfExpectedPaths, paths.size());
}
public Set<Path> getPaths() {
return paths;
}
| public PathSelector startsAt(UnitSelector selector) { |
johanneslerch/FlowTwist | FlowTwist/test/flow/twist/test/util/AbstractAnalysisTest.java | // Path: FlowTwist/src/flow/twist/AbstractAnalysis.java
// public abstract class AbstractAnalysis {
//
// public void execute() {
// ArrayList<String> argList = createArgs();
// AnalysisReporting.setSootArgs(argList);
// registerAnalysisTransformer();
// soot.Main.main(argList.toArray(new String[0]));
// }
//
// protected abstract ArrayList<String> createArgs();
//
// protected abstract void executeAnalysis();
//
// private static void insertNopStatements() {
// for (Iterator<MethodOrMethodContext> iter = Scene.v().getReachableMethods().listener(); iter.hasNext();) {
// SootMethod m = iter.next().method();
// if (m.hasActiveBody()) {
// Body b = m.getActiveBody();
// NopStmt newNopStmt = Jimple.v().newNopStmt();
// newNopStmt.addAllTagsOf(b.getUnits().getFirst());
// b.getUnits().addFirst(newNopStmt);
//
// ActiveBodyVerifier.markActive(m);
// } else
// ActiveBodyVerifier.markInactive(m);
// }
// }
//
// private void registerAnalysisTransformer() {
// PackManager.v().getPack("wjtp").add(new Transform("wjtp.permissionAnalysis", new SceneTransformer() {
// protected void internalTransform(String phaseName, @SuppressWarnings("rawtypes") Map options) {
// // Stats.print();
// insertNopStatements();
// executeAnalysis();
// }
// }));
// }
// }
| import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.After;
import org.junit.Before;
import soot.G;
import flow.twist.AbstractAnalysis;
import flow.twist.util.AnalysisUtil; | package flow.twist.test.util;
public abstract class AbstractAnalysisTest {
protected void runAnalysis(TestAnalysis analysis) {
analysis.execute();
}
@Before
public void setUp() throws Exception {
String jrePath = System.getProperty("java.home");
jrePath = jrePath.substring(0, jrePath.lastIndexOf(File.separator));
AnalysisUtil.initRestrictedPackages(jrePath);
}
@After
public void tearDown() throws Exception {
try {
} finally {
G.reset();
}
}
| // Path: FlowTwist/src/flow/twist/AbstractAnalysis.java
// public abstract class AbstractAnalysis {
//
// public void execute() {
// ArrayList<String> argList = createArgs();
// AnalysisReporting.setSootArgs(argList);
// registerAnalysisTransformer();
// soot.Main.main(argList.toArray(new String[0]));
// }
//
// protected abstract ArrayList<String> createArgs();
//
// protected abstract void executeAnalysis();
//
// private static void insertNopStatements() {
// for (Iterator<MethodOrMethodContext> iter = Scene.v().getReachableMethods().listener(); iter.hasNext();) {
// SootMethod m = iter.next().method();
// if (m.hasActiveBody()) {
// Body b = m.getActiveBody();
// NopStmt newNopStmt = Jimple.v().newNopStmt();
// newNopStmt.addAllTagsOf(b.getUnits().getFirst());
// b.getUnits().addFirst(newNopStmt);
//
// ActiveBodyVerifier.markActive(m);
// } else
// ActiveBodyVerifier.markInactive(m);
// }
// }
//
// private void registerAnalysisTransformer() {
// PackManager.v().getPack("wjtp").add(new Transform("wjtp.permissionAnalysis", new SceneTransformer() {
// protected void internalTransform(String phaseName, @SuppressWarnings("rawtypes") Map options) {
// // Stats.print();
// insertNopStatements();
// executeAnalysis();
// }
// }));
// }
// }
// Path: FlowTwist/test/flow/twist/test/util/AbstractAnalysisTest.java
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.After;
import org.junit.Before;
import soot.G;
import flow.twist.AbstractAnalysis;
import flow.twist.util.AnalysisUtil;
package flow.twist.test.util;
public abstract class AbstractAnalysisTest {
protected void runAnalysis(TestAnalysis analysis) {
analysis.execute();
}
@Before
public void setUp() throws Exception {
String jrePath = System.getProperty("java.home");
jrePath = jrePath.substring(0, jrePath.lastIndexOf(File.separator));
AnalysisUtil.initRestrictedPackages(jrePath);
}
@After
public void tearDown() throws Exception {
try {
} finally {
G.reset();
}
}
| public static abstract class TestAnalysis extends AbstractAnalysis { |
SpongeBobSun/Prodigal | app/src/main/java/bob/sun/bender/theme/ThemeManager.java | // Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public class AppConstants {
//
// public static final int RepeatAll = 0x233;
// public static final int RepeatOne = 0x234;
// public static final int RepeatNone = 0x235;
//
// //Theme
// public static final int ThemeShapeOval = 0;
// public static final int ThemeShapeRect = 1;
// public static final int ThemeShapePolygon = 2;
//
//
// public static final String pref_tag = "mpod_app_settings";
// public static final String kShuffle = "mpod_app_settings.key.shuffle";
// public static final String kRepeat = "mpod_app_settings.key.repeat";
//
// public static final String broadcastSongChange = "sun.bob.bender.songchanged";
// public static final String broadcastPermission = "sun.bob.bender.allow_broadcast";
//
// private static final String playlistfile = "/data/data/bob.sun.bender/playlistobject";
// private static final String packageFolder = "/data/data/bob.sun.bender/";
//
// public static final String themeFolder = "/data/Prodigal/Themes/";
//
// public static String getPlayistfile() {
// return Environment.getExternalStorageDirectory().getPath() + playlistfile;
// }
//
// public static String getExtFolder() {
// return Environment.getExternalStorageDirectory().getPath() + packageFolder;
// }
//
// }
//
// Path: app/src/main/java/bob/sun/bender/utils/UserDefaults.java
// public class UserDefaults {
// private static UserDefaults staticInstance;
// private SharedPreferences preferences;
// private String appVersion;
// private String kIntroShown = "kIntroShownFor:";
// private String kThemeName = "kThemeName";
//
// private UserDefaults(Context context){
// preferences = context.getSharedPreferences(pref_tag,0);
//
// appVersion = BuildConfig.VERSION_NAME;
// kIntroShown += appVersion;
//
// if (!preferences.contains(kRepeat)) {
// setRepeat(RepeatAll);
// }
// if (!preferences.contains(kShuffle)) {
// setShuffle(false);
// }
// if (!preferences.contains(kIntroShown)) {
// preferences.edit().putBoolean(kIntroShown, false).commit();
// }
// }
//
// public static UserDefaults getStaticInstance(Context context){
// if (staticInstance == null)
// staticInstance = new UserDefaults(context.getApplicationContext());
// return staticInstance;
// }
//
// public SharedPreferences getPreferences(){
// return preferences;
// }
//
// public int getRepeat() {
// return preferences.getInt(kRepeat, AppConstants.RepeatAll);
// }
//
// private void setRepeat(int mode) {
// preferences.edit().putInt(kRepeat, mode).commit();
// }
//
// public boolean isShuffle(){
// boolean ret = preferences.getBoolean(kShuffle, false);
// return ret;
// }
//
// private void setShuffle(boolean shuffle) {
// preferences.edit().putBoolean(kShuffle, shuffle).commit();
// }
//
// public void rollShuffle() {
// boolean current = isShuffle();
// setShuffle(!current);
// }
//
// public void rollRepeat() {
// int current = getRepeat();
// if (current == RepeatNone) {
// setRepeat(RepeatAll);
// } else {
// setRepeat(current + 1);
// }
// }
//
// public boolean shouldShowIntro() {
// return !preferences.getBoolean(kIntroShown, false);
// }
//
// public void introShown() {
// preferences.edit().putBoolean(kIntroShown, true).commit();
// }
//
// public void setTheme(String name) {
// preferences.edit().putString(kThemeName, name).commit();
// }
//
// public String getTheme() {
// return preferences.getString(kThemeName, "Default");
// }
// }
| import android.content.Context;
import android.content.res.AssetManager;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import bob.sun.bender.utils.AppConstants;
import bob.sun.bender.utils.UserDefaults; | package bob.sun.bender.theme;
/**
* Created by bob.sun on 17/05/2017.
*/
public class ThemeManager {
private static ThemeManager instance;
private volatile Theme currentTheme = null;
private Context context;
private Gson gson;
private ThemeManager(Context ctx) {
context = ctx;
gson = new Gson();
copyThemesIfNeeded();
}
public static ThemeManager getInstance(Context context) {
if (instance == null)
instance = new ThemeManager(context);
return instance;
}
private void copyThemesIfNeeded() {
String themeDirInExt = Environment.getExternalStorageDirectory().getAbsolutePath(); | // Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public class AppConstants {
//
// public static final int RepeatAll = 0x233;
// public static final int RepeatOne = 0x234;
// public static final int RepeatNone = 0x235;
//
// //Theme
// public static final int ThemeShapeOval = 0;
// public static final int ThemeShapeRect = 1;
// public static final int ThemeShapePolygon = 2;
//
//
// public static final String pref_tag = "mpod_app_settings";
// public static final String kShuffle = "mpod_app_settings.key.shuffle";
// public static final String kRepeat = "mpod_app_settings.key.repeat";
//
// public static final String broadcastSongChange = "sun.bob.bender.songchanged";
// public static final String broadcastPermission = "sun.bob.bender.allow_broadcast";
//
// private static final String playlistfile = "/data/data/bob.sun.bender/playlistobject";
// private static final String packageFolder = "/data/data/bob.sun.bender/";
//
// public static final String themeFolder = "/data/Prodigal/Themes/";
//
// public static String getPlayistfile() {
// return Environment.getExternalStorageDirectory().getPath() + playlistfile;
// }
//
// public static String getExtFolder() {
// return Environment.getExternalStorageDirectory().getPath() + packageFolder;
// }
//
// }
//
// Path: app/src/main/java/bob/sun/bender/utils/UserDefaults.java
// public class UserDefaults {
// private static UserDefaults staticInstance;
// private SharedPreferences preferences;
// private String appVersion;
// private String kIntroShown = "kIntroShownFor:";
// private String kThemeName = "kThemeName";
//
// private UserDefaults(Context context){
// preferences = context.getSharedPreferences(pref_tag,0);
//
// appVersion = BuildConfig.VERSION_NAME;
// kIntroShown += appVersion;
//
// if (!preferences.contains(kRepeat)) {
// setRepeat(RepeatAll);
// }
// if (!preferences.contains(kShuffle)) {
// setShuffle(false);
// }
// if (!preferences.contains(kIntroShown)) {
// preferences.edit().putBoolean(kIntroShown, false).commit();
// }
// }
//
// public static UserDefaults getStaticInstance(Context context){
// if (staticInstance == null)
// staticInstance = new UserDefaults(context.getApplicationContext());
// return staticInstance;
// }
//
// public SharedPreferences getPreferences(){
// return preferences;
// }
//
// public int getRepeat() {
// return preferences.getInt(kRepeat, AppConstants.RepeatAll);
// }
//
// private void setRepeat(int mode) {
// preferences.edit().putInt(kRepeat, mode).commit();
// }
//
// public boolean isShuffle(){
// boolean ret = preferences.getBoolean(kShuffle, false);
// return ret;
// }
//
// private void setShuffle(boolean shuffle) {
// preferences.edit().putBoolean(kShuffle, shuffle).commit();
// }
//
// public void rollShuffle() {
// boolean current = isShuffle();
// setShuffle(!current);
// }
//
// public void rollRepeat() {
// int current = getRepeat();
// if (current == RepeatNone) {
// setRepeat(RepeatAll);
// } else {
// setRepeat(current + 1);
// }
// }
//
// public boolean shouldShowIntro() {
// return !preferences.getBoolean(kIntroShown, false);
// }
//
// public void introShown() {
// preferences.edit().putBoolean(kIntroShown, true).commit();
// }
//
// public void setTheme(String name) {
// preferences.edit().putString(kThemeName, name).commit();
// }
//
// public String getTheme() {
// return preferences.getString(kThemeName, "Default");
// }
// }
// Path: app/src/main/java/bob/sun/bender/theme/ThemeManager.java
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import bob.sun.bender.utils.AppConstants;
import bob.sun.bender.utils.UserDefaults;
package bob.sun.bender.theme;
/**
* Created by bob.sun on 17/05/2017.
*/
public class ThemeManager {
private static ThemeManager instance;
private volatile Theme currentTheme = null;
private Context context;
private Gson gson;
private ThemeManager(Context ctx) {
context = ctx;
gson = new Gson();
copyThemesIfNeeded();
}
public static ThemeManager getInstance(Context context) {
if (instance == null)
instance = new ThemeManager(context);
return instance;
}
private void copyThemesIfNeeded() {
String themeDirInExt = Environment.getExternalStorageDirectory().getAbsolutePath(); | themeDirInExt += AppConstants.themeFolder; |
SpongeBobSun/Prodigal | app/src/main/java/bob/sun/bender/theme/ThemeManager.java | // Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public class AppConstants {
//
// public static final int RepeatAll = 0x233;
// public static final int RepeatOne = 0x234;
// public static final int RepeatNone = 0x235;
//
// //Theme
// public static final int ThemeShapeOval = 0;
// public static final int ThemeShapeRect = 1;
// public static final int ThemeShapePolygon = 2;
//
//
// public static final String pref_tag = "mpod_app_settings";
// public static final String kShuffle = "mpod_app_settings.key.shuffle";
// public static final String kRepeat = "mpod_app_settings.key.repeat";
//
// public static final String broadcastSongChange = "sun.bob.bender.songchanged";
// public static final String broadcastPermission = "sun.bob.bender.allow_broadcast";
//
// private static final String playlistfile = "/data/data/bob.sun.bender/playlistobject";
// private static final String packageFolder = "/data/data/bob.sun.bender/";
//
// public static final String themeFolder = "/data/Prodigal/Themes/";
//
// public static String getPlayistfile() {
// return Environment.getExternalStorageDirectory().getPath() + playlistfile;
// }
//
// public static String getExtFolder() {
// return Environment.getExternalStorageDirectory().getPath() + packageFolder;
// }
//
// }
//
// Path: app/src/main/java/bob/sun/bender/utils/UserDefaults.java
// public class UserDefaults {
// private static UserDefaults staticInstance;
// private SharedPreferences preferences;
// private String appVersion;
// private String kIntroShown = "kIntroShownFor:";
// private String kThemeName = "kThemeName";
//
// private UserDefaults(Context context){
// preferences = context.getSharedPreferences(pref_tag,0);
//
// appVersion = BuildConfig.VERSION_NAME;
// kIntroShown += appVersion;
//
// if (!preferences.contains(kRepeat)) {
// setRepeat(RepeatAll);
// }
// if (!preferences.contains(kShuffle)) {
// setShuffle(false);
// }
// if (!preferences.contains(kIntroShown)) {
// preferences.edit().putBoolean(kIntroShown, false).commit();
// }
// }
//
// public static UserDefaults getStaticInstance(Context context){
// if (staticInstance == null)
// staticInstance = new UserDefaults(context.getApplicationContext());
// return staticInstance;
// }
//
// public SharedPreferences getPreferences(){
// return preferences;
// }
//
// public int getRepeat() {
// return preferences.getInt(kRepeat, AppConstants.RepeatAll);
// }
//
// private void setRepeat(int mode) {
// preferences.edit().putInt(kRepeat, mode).commit();
// }
//
// public boolean isShuffle(){
// boolean ret = preferences.getBoolean(kShuffle, false);
// return ret;
// }
//
// private void setShuffle(boolean shuffle) {
// preferences.edit().putBoolean(kShuffle, shuffle).commit();
// }
//
// public void rollShuffle() {
// boolean current = isShuffle();
// setShuffle(!current);
// }
//
// public void rollRepeat() {
// int current = getRepeat();
// if (current == RepeatNone) {
// setRepeat(RepeatAll);
// } else {
// setRepeat(current + 1);
// }
// }
//
// public boolean shouldShowIntro() {
// return !preferences.getBoolean(kIntroShown, false);
// }
//
// public void introShown() {
// preferences.edit().putBoolean(kIntroShown, true).commit();
// }
//
// public void setTheme(String name) {
// preferences.edit().putString(kThemeName, name).commit();
// }
//
// public String getTheme() {
// return preferences.getString(kThemeName, "Default");
// }
// }
| import android.content.Context;
import android.content.res.AssetManager;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import bob.sun.bender.utils.AppConstants;
import bob.sun.bender.utils.UserDefaults; | File f = new File(folder + ze.getName());
if(!f.isDirectory()) {
f.mkdirs();
}
} else {
FileOutputStream fout = new FileOutputStream(folder + ze.getName());
BufferedOutputStream bufout = new BufferedOutputStream(fout);
byte[] buffer = new byte[1024];
int read = 0;
while ((read = zin.read(buffer)) != -1) {
bufout.write(buffer, 0, read);
}
bufout.close();
zin.closeEntry();
fout.close();
}
}
zin.close();
new File(zipFile).delete();
} catch(Exception e) {
e.printStackTrace();
}
}
public @NonNull Theme loadThemeNamed(@NonNull String name) {
if (name != null && "Default".equalsIgnoreCase(name)) {
return Theme.defaultTheme();
}
if (!validateByName(name)) { | // Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public class AppConstants {
//
// public static final int RepeatAll = 0x233;
// public static final int RepeatOne = 0x234;
// public static final int RepeatNone = 0x235;
//
// //Theme
// public static final int ThemeShapeOval = 0;
// public static final int ThemeShapeRect = 1;
// public static final int ThemeShapePolygon = 2;
//
//
// public static final String pref_tag = "mpod_app_settings";
// public static final String kShuffle = "mpod_app_settings.key.shuffle";
// public static final String kRepeat = "mpod_app_settings.key.repeat";
//
// public static final String broadcastSongChange = "sun.bob.bender.songchanged";
// public static final String broadcastPermission = "sun.bob.bender.allow_broadcast";
//
// private static final String playlistfile = "/data/data/bob.sun.bender/playlistobject";
// private static final String packageFolder = "/data/data/bob.sun.bender/";
//
// public static final String themeFolder = "/data/Prodigal/Themes/";
//
// public static String getPlayistfile() {
// return Environment.getExternalStorageDirectory().getPath() + playlistfile;
// }
//
// public static String getExtFolder() {
// return Environment.getExternalStorageDirectory().getPath() + packageFolder;
// }
//
// }
//
// Path: app/src/main/java/bob/sun/bender/utils/UserDefaults.java
// public class UserDefaults {
// private static UserDefaults staticInstance;
// private SharedPreferences preferences;
// private String appVersion;
// private String kIntroShown = "kIntroShownFor:";
// private String kThemeName = "kThemeName";
//
// private UserDefaults(Context context){
// preferences = context.getSharedPreferences(pref_tag,0);
//
// appVersion = BuildConfig.VERSION_NAME;
// kIntroShown += appVersion;
//
// if (!preferences.contains(kRepeat)) {
// setRepeat(RepeatAll);
// }
// if (!preferences.contains(kShuffle)) {
// setShuffle(false);
// }
// if (!preferences.contains(kIntroShown)) {
// preferences.edit().putBoolean(kIntroShown, false).commit();
// }
// }
//
// public static UserDefaults getStaticInstance(Context context){
// if (staticInstance == null)
// staticInstance = new UserDefaults(context.getApplicationContext());
// return staticInstance;
// }
//
// public SharedPreferences getPreferences(){
// return preferences;
// }
//
// public int getRepeat() {
// return preferences.getInt(kRepeat, AppConstants.RepeatAll);
// }
//
// private void setRepeat(int mode) {
// preferences.edit().putInt(kRepeat, mode).commit();
// }
//
// public boolean isShuffle(){
// boolean ret = preferences.getBoolean(kShuffle, false);
// return ret;
// }
//
// private void setShuffle(boolean shuffle) {
// preferences.edit().putBoolean(kShuffle, shuffle).commit();
// }
//
// public void rollShuffle() {
// boolean current = isShuffle();
// setShuffle(!current);
// }
//
// public void rollRepeat() {
// int current = getRepeat();
// if (current == RepeatNone) {
// setRepeat(RepeatAll);
// } else {
// setRepeat(current + 1);
// }
// }
//
// public boolean shouldShowIntro() {
// return !preferences.getBoolean(kIntroShown, false);
// }
//
// public void introShown() {
// preferences.edit().putBoolean(kIntroShown, true).commit();
// }
//
// public void setTheme(String name) {
// preferences.edit().putString(kThemeName, name).commit();
// }
//
// public String getTheme() {
// return preferences.getString(kThemeName, "Default");
// }
// }
// Path: app/src/main/java/bob/sun/bender/theme/ThemeManager.java
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import bob.sun.bender.utils.AppConstants;
import bob.sun.bender.utils.UserDefaults;
File f = new File(folder + ze.getName());
if(!f.isDirectory()) {
f.mkdirs();
}
} else {
FileOutputStream fout = new FileOutputStream(folder + ze.getName());
BufferedOutputStream bufout = new BufferedOutputStream(fout);
byte[] buffer = new byte[1024];
int read = 0;
while ((read = zin.read(buffer)) != -1) {
bufout.write(buffer, 0, read);
}
bufout.close();
zin.closeEntry();
fout.close();
}
}
zin.close();
new File(zipFile).delete();
} catch(Exception e) {
e.printStackTrace();
}
}
public @NonNull Theme loadThemeNamed(@NonNull String name) {
if (name != null && "Default".equalsIgnoreCase(name)) {
return Theme.defaultTheme();
}
if (!validateByName(name)) { | UserDefaults.getStaticInstance(context).setTheme("Default"); |
SpongeBobSun/Prodigal | app/src/main/java/bob/sun/bender/controller/OnTickListener.java | // Path: app/src/main/java/bob/sun/bender/model/SelectionDetail.java
// public class SelectionDetail {
//
// public static final int MENU_TPYE_MAIN = 1;
// public static final int MENU_TYPE_ARTIST = 2;
// public static final int MENU_TYPE_ALBUM = 3;
// public static final int MENU_TYPE_SONGS = 4;
// public static final int MENU_TYPE_GENRES = 5;
// public static final int MENU_TYPE_SETTING = 6;
// public static final int MENU_TYPE_THEMES = 7;
// public static final int MENU_TYPE_UNUSED = -1;
//
// public static final int DATA_TYPE_STRING = 1;
// public static final int DATA_TYPE_SONG = 2;
//
//
// private int menuType;
// private int dataType;
// private Object data;
// private int superType;
// private int subType;
// private ArrayList<SongBean> playlist;
// private int indexOfList;
//
// public int getMenuType() {
// return menuType;
// }
//
// public void setMenuType(int menuType) {
// this.menuType = menuType;
// }
//
// public int getDataType() {
// return dataType;
// }
//
// public void setDataType(int dataType) {
// this.dataType = dataType;
// }
//
// public Object getData() {
// return data;
// }
//
// public void setData(Object data) {
// this.data = data;
// }
//
// public int getSuperType() {
// return superType;
// }
//
// public void setSuperType(int superType) {
// this.superType = superType;
// }
//
// public int getSubType() {
// return subType;
// }
//
// public void setSubType(int subType) {
// this.subType = subType;
// }
//
// public ArrayList<SongBean> getPlaylist() {
// return playlist;
// }
//
// public void setPlaylist(ArrayList<SongBean> playlist) {
// this.playlist = playlist;
// }
//
// public int getIndexOfList() {
// return indexOfList;
// }
//
// public void setIndexOfList(int indexOfList) {
// this.indexOfList = indexOfList;
// }
// }
| import bob.sun.bender.model.SelectionDetail; | package bob.sun.bender.controller;
/**
* Created by sunkuan on 2015/4/23.
*/
public interface OnTickListener {
public void onNextTick();
public void onPreviousTick(); | // Path: app/src/main/java/bob/sun/bender/model/SelectionDetail.java
// public class SelectionDetail {
//
// public static final int MENU_TPYE_MAIN = 1;
// public static final int MENU_TYPE_ARTIST = 2;
// public static final int MENU_TYPE_ALBUM = 3;
// public static final int MENU_TYPE_SONGS = 4;
// public static final int MENU_TYPE_GENRES = 5;
// public static final int MENU_TYPE_SETTING = 6;
// public static final int MENU_TYPE_THEMES = 7;
// public static final int MENU_TYPE_UNUSED = -1;
//
// public static final int DATA_TYPE_STRING = 1;
// public static final int DATA_TYPE_SONG = 2;
//
//
// private int menuType;
// private int dataType;
// private Object data;
// private int superType;
// private int subType;
// private ArrayList<SongBean> playlist;
// private int indexOfList;
//
// public int getMenuType() {
// return menuType;
// }
//
// public void setMenuType(int menuType) {
// this.menuType = menuType;
// }
//
// public int getDataType() {
// return dataType;
// }
//
// public void setDataType(int dataType) {
// this.dataType = dataType;
// }
//
// public Object getData() {
// return data;
// }
//
// public void setData(Object data) {
// this.data = data;
// }
//
// public int getSuperType() {
// return superType;
// }
//
// public void setSuperType(int superType) {
// this.superType = superType;
// }
//
// public int getSubType() {
// return subType;
// }
//
// public void setSubType(int subType) {
// this.subType = subType;
// }
//
// public ArrayList<SongBean> getPlaylist() {
// return playlist;
// }
//
// public void setPlaylist(ArrayList<SongBean> playlist) {
// this.playlist = playlist;
// }
//
// public int getIndexOfList() {
// return indexOfList;
// }
//
// public void setIndexOfList(int indexOfList) {
// this.indexOfList = indexOfList;
// }
// }
// Path: app/src/main/java/bob/sun/bender/controller/OnTickListener.java
import bob.sun.bender.model.SelectionDetail;
package bob.sun.bender.controller;
/**
* Created by sunkuan on 2015/4/23.
*/
public interface OnTickListener {
public void onNextTick();
public void onPreviousTick(); | public SelectionDetail getCurrentSelection(); |
SpongeBobSun/Prodigal | app/src/main/java/bob/sun/bender/theme/Theme.java | // Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public class AppConstants {
//
// public static final int RepeatAll = 0x233;
// public static final int RepeatOne = 0x234;
// public static final int RepeatNone = 0x235;
//
// //Theme
// public static final int ThemeShapeOval = 0;
// public static final int ThemeShapeRect = 1;
// public static final int ThemeShapePolygon = 2;
//
//
// public static final String pref_tag = "mpod_app_settings";
// public static final String kShuffle = "mpod_app_settings.key.shuffle";
// public static final String kRepeat = "mpod_app_settings.key.repeat";
//
// public static final String broadcastSongChange = "sun.bob.bender.songchanged";
// public static final String broadcastPermission = "sun.bob.bender.allow_broadcast";
//
// private static final String playlistfile = "/data/data/bob.sun.bender/playlistobject";
// private static final String packageFolder = "/data/data/bob.sun.bender/";
//
// public static final String themeFolder = "/data/Prodigal/Themes/";
//
// public static String getPlayistfile() {
// return Environment.getExternalStorageDirectory().getPath() + playlistfile;
// }
//
// public static String getExtFolder() {
// return Environment.getExternalStorageDirectory().getPath() + packageFolder;
// }
//
// }
| import android.graphics.Color;
import android.os.Environment;
import android.support.annotation.NonNull;
import com.google.gson.annotations.SerializedName;
import bob.sun.bender.utils.AppConstants; | public String getMenuIcon() {
return themeFolder() + icons.icMenu;
}
public int getWheelColor() {
return Color.parseColor(wheelColor);
}
public int getButtonColor() {
return Color.parseColor(buttonColor);
}
public int getBackgroundColor() {
return Color.parseColor(backgroundColor);
}
public int getCardColor() {
return Color.parseColor(cardColor);
}
public int getItemColor() {
return Color.parseColor(itemColor);
}
public int getTextColor() {
return Color.parseColor(textColor);
}
public int getShape() {
if (wheelShape == null) { | // Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public class AppConstants {
//
// public static final int RepeatAll = 0x233;
// public static final int RepeatOne = 0x234;
// public static final int RepeatNone = 0x235;
//
// //Theme
// public static final int ThemeShapeOval = 0;
// public static final int ThemeShapeRect = 1;
// public static final int ThemeShapePolygon = 2;
//
//
// public static final String pref_tag = "mpod_app_settings";
// public static final String kShuffle = "mpod_app_settings.key.shuffle";
// public static final String kRepeat = "mpod_app_settings.key.repeat";
//
// public static final String broadcastSongChange = "sun.bob.bender.songchanged";
// public static final String broadcastPermission = "sun.bob.bender.allow_broadcast";
//
// private static final String playlistfile = "/data/data/bob.sun.bender/playlistobject";
// private static final String packageFolder = "/data/data/bob.sun.bender/";
//
// public static final String themeFolder = "/data/Prodigal/Themes/";
//
// public static String getPlayistfile() {
// return Environment.getExternalStorageDirectory().getPath() + playlistfile;
// }
//
// public static String getExtFolder() {
// return Environment.getExternalStorageDirectory().getPath() + packageFolder;
// }
//
// }
// Path: app/src/main/java/bob/sun/bender/theme/Theme.java
import android.graphics.Color;
import android.os.Environment;
import android.support.annotation.NonNull;
import com.google.gson.annotations.SerializedName;
import bob.sun.bender.utils.AppConstants;
public String getMenuIcon() {
return themeFolder() + icons.icMenu;
}
public int getWheelColor() {
return Color.parseColor(wheelColor);
}
public int getButtonColor() {
return Color.parseColor(buttonColor);
}
public int getBackgroundColor() {
return Color.parseColor(backgroundColor);
}
public int getCardColor() {
return Color.parseColor(cardColor);
}
public int getItemColor() {
return Color.parseColor(itemColor);
}
public int getTextColor() {
return Color.parseColor(textColor);
}
public int getShape() {
if (wheelShape == null) { | return AppConstants.ThemeShapeOval; |
SpongeBobSun/Prodigal | app/src/main/java/bob/sun/bender/utils/UserDefaults.java | // Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final int RepeatAll = 0x233;
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final int RepeatNone = 0x235;
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String kRepeat = "mpod_app_settings.key.repeat";
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String kShuffle = "mpod_app_settings.key.shuffle";
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String pref_tag = "mpod_app_settings";
| import android.content.Context;
import android.content.SharedPreferences;
import bob.sun.bender.BuildConfig;
import static bob.sun.bender.utils.AppConstants.RepeatAll;
import static bob.sun.bender.utils.AppConstants.RepeatNone;
import static bob.sun.bender.utils.AppConstants.kRepeat;
import static bob.sun.bender.utils.AppConstants.kShuffle;
import static bob.sun.bender.utils.AppConstants.pref_tag; | package bob.sun.bender.utils;
/**
* Created by sunkuan on 15/5/12.
*/
public class UserDefaults {
private static UserDefaults staticInstance;
private SharedPreferences preferences;
private String appVersion;
private String kIntroShown = "kIntroShownFor:";
private String kThemeName = "kThemeName";
private UserDefaults(Context context){ | // Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final int RepeatAll = 0x233;
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final int RepeatNone = 0x235;
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String kRepeat = "mpod_app_settings.key.repeat";
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String kShuffle = "mpod_app_settings.key.shuffle";
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String pref_tag = "mpod_app_settings";
// Path: app/src/main/java/bob/sun/bender/utils/UserDefaults.java
import android.content.Context;
import android.content.SharedPreferences;
import bob.sun.bender.BuildConfig;
import static bob.sun.bender.utils.AppConstants.RepeatAll;
import static bob.sun.bender.utils.AppConstants.RepeatNone;
import static bob.sun.bender.utils.AppConstants.kRepeat;
import static bob.sun.bender.utils.AppConstants.kShuffle;
import static bob.sun.bender.utils.AppConstants.pref_tag;
package bob.sun.bender.utils;
/**
* Created by sunkuan on 15/5/12.
*/
public class UserDefaults {
private static UserDefaults staticInstance;
private SharedPreferences preferences;
private String appVersion;
private String kIntroShown = "kIntroShownFor:";
private String kThemeName = "kThemeName";
private UserDefaults(Context context){ | preferences = context.getSharedPreferences(pref_tag,0); |
SpongeBobSun/Prodigal | app/src/main/java/bob/sun/bender/utils/UserDefaults.java | // Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final int RepeatAll = 0x233;
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final int RepeatNone = 0x235;
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String kRepeat = "mpod_app_settings.key.repeat";
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String kShuffle = "mpod_app_settings.key.shuffle";
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String pref_tag = "mpod_app_settings";
| import android.content.Context;
import android.content.SharedPreferences;
import bob.sun.bender.BuildConfig;
import static bob.sun.bender.utils.AppConstants.RepeatAll;
import static bob.sun.bender.utils.AppConstants.RepeatNone;
import static bob.sun.bender.utils.AppConstants.kRepeat;
import static bob.sun.bender.utils.AppConstants.kShuffle;
import static bob.sun.bender.utils.AppConstants.pref_tag; | package bob.sun.bender.utils;
/**
* Created by sunkuan on 15/5/12.
*/
public class UserDefaults {
private static UserDefaults staticInstance;
private SharedPreferences preferences;
private String appVersion;
private String kIntroShown = "kIntroShownFor:";
private String kThemeName = "kThemeName";
private UserDefaults(Context context){
preferences = context.getSharedPreferences(pref_tag,0);
appVersion = BuildConfig.VERSION_NAME;
kIntroShown += appVersion;
| // Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final int RepeatAll = 0x233;
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final int RepeatNone = 0x235;
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String kRepeat = "mpod_app_settings.key.repeat";
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String kShuffle = "mpod_app_settings.key.shuffle";
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String pref_tag = "mpod_app_settings";
// Path: app/src/main/java/bob/sun/bender/utils/UserDefaults.java
import android.content.Context;
import android.content.SharedPreferences;
import bob.sun.bender.BuildConfig;
import static bob.sun.bender.utils.AppConstants.RepeatAll;
import static bob.sun.bender.utils.AppConstants.RepeatNone;
import static bob.sun.bender.utils.AppConstants.kRepeat;
import static bob.sun.bender.utils.AppConstants.kShuffle;
import static bob.sun.bender.utils.AppConstants.pref_tag;
package bob.sun.bender.utils;
/**
* Created by sunkuan on 15/5/12.
*/
public class UserDefaults {
private static UserDefaults staticInstance;
private SharedPreferences preferences;
private String appVersion;
private String kIntroShown = "kIntroShownFor:";
private String kThemeName = "kThemeName";
private UserDefaults(Context context){
preferences = context.getSharedPreferences(pref_tag,0);
appVersion = BuildConfig.VERSION_NAME;
kIntroShown += appVersion;
| if (!preferences.contains(kRepeat)) { |
SpongeBobSun/Prodigal | app/src/main/java/bob/sun/bender/utils/UserDefaults.java | // Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final int RepeatAll = 0x233;
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final int RepeatNone = 0x235;
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String kRepeat = "mpod_app_settings.key.repeat";
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String kShuffle = "mpod_app_settings.key.shuffle";
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String pref_tag = "mpod_app_settings";
| import android.content.Context;
import android.content.SharedPreferences;
import bob.sun.bender.BuildConfig;
import static bob.sun.bender.utils.AppConstants.RepeatAll;
import static bob.sun.bender.utils.AppConstants.RepeatNone;
import static bob.sun.bender.utils.AppConstants.kRepeat;
import static bob.sun.bender.utils.AppConstants.kShuffle;
import static bob.sun.bender.utils.AppConstants.pref_tag; | package bob.sun.bender.utils;
/**
* Created by sunkuan on 15/5/12.
*/
public class UserDefaults {
private static UserDefaults staticInstance;
private SharedPreferences preferences;
private String appVersion;
private String kIntroShown = "kIntroShownFor:";
private String kThemeName = "kThemeName";
private UserDefaults(Context context){
preferences = context.getSharedPreferences(pref_tag,0);
appVersion = BuildConfig.VERSION_NAME;
kIntroShown += appVersion;
if (!preferences.contains(kRepeat)) { | // Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final int RepeatAll = 0x233;
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final int RepeatNone = 0x235;
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String kRepeat = "mpod_app_settings.key.repeat";
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String kShuffle = "mpod_app_settings.key.shuffle";
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String pref_tag = "mpod_app_settings";
// Path: app/src/main/java/bob/sun/bender/utils/UserDefaults.java
import android.content.Context;
import android.content.SharedPreferences;
import bob.sun.bender.BuildConfig;
import static bob.sun.bender.utils.AppConstants.RepeatAll;
import static bob.sun.bender.utils.AppConstants.RepeatNone;
import static bob.sun.bender.utils.AppConstants.kRepeat;
import static bob.sun.bender.utils.AppConstants.kShuffle;
import static bob.sun.bender.utils.AppConstants.pref_tag;
package bob.sun.bender.utils;
/**
* Created by sunkuan on 15/5/12.
*/
public class UserDefaults {
private static UserDefaults staticInstance;
private SharedPreferences preferences;
private String appVersion;
private String kIntroShown = "kIntroShownFor:";
private String kThemeName = "kThemeName";
private UserDefaults(Context context){
preferences = context.getSharedPreferences(pref_tag,0);
appVersion = BuildConfig.VERSION_NAME;
kIntroShown += appVersion;
if (!preferences.contains(kRepeat)) { | setRepeat(RepeatAll); |
SpongeBobSun/Prodigal | app/src/main/java/bob/sun/bender/utils/UserDefaults.java | // Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final int RepeatAll = 0x233;
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final int RepeatNone = 0x235;
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String kRepeat = "mpod_app_settings.key.repeat";
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String kShuffle = "mpod_app_settings.key.shuffle";
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String pref_tag = "mpod_app_settings";
| import android.content.Context;
import android.content.SharedPreferences;
import bob.sun.bender.BuildConfig;
import static bob.sun.bender.utils.AppConstants.RepeatAll;
import static bob.sun.bender.utils.AppConstants.RepeatNone;
import static bob.sun.bender.utils.AppConstants.kRepeat;
import static bob.sun.bender.utils.AppConstants.kShuffle;
import static bob.sun.bender.utils.AppConstants.pref_tag; | package bob.sun.bender.utils;
/**
* Created by sunkuan on 15/5/12.
*/
public class UserDefaults {
private static UserDefaults staticInstance;
private SharedPreferences preferences;
private String appVersion;
private String kIntroShown = "kIntroShownFor:";
private String kThemeName = "kThemeName";
private UserDefaults(Context context){
preferences = context.getSharedPreferences(pref_tag,0);
appVersion = BuildConfig.VERSION_NAME;
kIntroShown += appVersion;
if (!preferences.contains(kRepeat)) {
setRepeat(RepeatAll);
} | // Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final int RepeatAll = 0x233;
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final int RepeatNone = 0x235;
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String kRepeat = "mpod_app_settings.key.repeat";
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String kShuffle = "mpod_app_settings.key.shuffle";
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String pref_tag = "mpod_app_settings";
// Path: app/src/main/java/bob/sun/bender/utils/UserDefaults.java
import android.content.Context;
import android.content.SharedPreferences;
import bob.sun.bender.BuildConfig;
import static bob.sun.bender.utils.AppConstants.RepeatAll;
import static bob.sun.bender.utils.AppConstants.RepeatNone;
import static bob.sun.bender.utils.AppConstants.kRepeat;
import static bob.sun.bender.utils.AppConstants.kShuffle;
import static bob.sun.bender.utils.AppConstants.pref_tag;
package bob.sun.bender.utils;
/**
* Created by sunkuan on 15/5/12.
*/
public class UserDefaults {
private static UserDefaults staticInstance;
private SharedPreferences preferences;
private String appVersion;
private String kIntroShown = "kIntroShownFor:";
private String kThemeName = "kThemeName";
private UserDefaults(Context context){
preferences = context.getSharedPreferences(pref_tag,0);
appVersion = BuildConfig.VERSION_NAME;
kIntroShown += appVersion;
if (!preferences.contains(kRepeat)) {
setRepeat(RepeatAll);
} | if (!preferences.contains(kShuffle)) { |
SpongeBobSun/Prodigal | app/src/main/java/bob/sun/bender/utils/UserDefaults.java | // Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final int RepeatAll = 0x233;
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final int RepeatNone = 0x235;
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String kRepeat = "mpod_app_settings.key.repeat";
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String kShuffle = "mpod_app_settings.key.shuffle";
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String pref_tag = "mpod_app_settings";
| import android.content.Context;
import android.content.SharedPreferences;
import bob.sun.bender.BuildConfig;
import static bob.sun.bender.utils.AppConstants.RepeatAll;
import static bob.sun.bender.utils.AppConstants.RepeatNone;
import static bob.sun.bender.utils.AppConstants.kRepeat;
import static bob.sun.bender.utils.AppConstants.kShuffle;
import static bob.sun.bender.utils.AppConstants.pref_tag; | }
public SharedPreferences getPreferences(){
return preferences;
}
public int getRepeat() {
return preferences.getInt(kRepeat, AppConstants.RepeatAll);
}
private void setRepeat(int mode) {
preferences.edit().putInt(kRepeat, mode).commit();
}
public boolean isShuffle(){
boolean ret = preferences.getBoolean(kShuffle, false);
return ret;
}
private void setShuffle(boolean shuffle) {
preferences.edit().putBoolean(kShuffle, shuffle).commit();
}
public void rollShuffle() {
boolean current = isShuffle();
setShuffle(!current);
}
public void rollRepeat() {
int current = getRepeat(); | // Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final int RepeatAll = 0x233;
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final int RepeatNone = 0x235;
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String kRepeat = "mpod_app_settings.key.repeat";
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String kShuffle = "mpod_app_settings.key.shuffle";
//
// Path: app/src/main/java/bob/sun/bender/utils/AppConstants.java
// public static final String pref_tag = "mpod_app_settings";
// Path: app/src/main/java/bob/sun/bender/utils/UserDefaults.java
import android.content.Context;
import android.content.SharedPreferences;
import bob.sun.bender.BuildConfig;
import static bob.sun.bender.utils.AppConstants.RepeatAll;
import static bob.sun.bender.utils.AppConstants.RepeatNone;
import static bob.sun.bender.utils.AppConstants.kRepeat;
import static bob.sun.bender.utils.AppConstants.kShuffle;
import static bob.sun.bender.utils.AppConstants.pref_tag;
}
public SharedPreferences getPreferences(){
return preferences;
}
public int getRepeat() {
return preferences.getInt(kRepeat, AppConstants.RepeatAll);
}
private void setRepeat(int mode) {
preferences.edit().putInt(kRepeat, mode).commit();
}
public boolean isShuffle(){
boolean ret = preferences.getBoolean(kShuffle, false);
return ret;
}
private void setShuffle(boolean shuffle) {
preferences.edit().putBoolean(kShuffle, shuffle).commit();
}
public void rollShuffle() {
boolean current = isShuffle();
setShuffle(!current);
}
public void rollRepeat() {
int current = getRepeat(); | if (current == RepeatNone) { |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/v2/ClientLibraryDecoderTest.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/ConversionFailureException.java
// public class ConversionFailureException extends R2dbcNonTransientException {
//
// public ConversionFailureException(String message) {
// super(message);
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.params.provider.Arguments.arguments;
import com.google.cloud.ByteArray;
import com.google.cloud.Date;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.Struct;
import com.google.cloud.spanner.Type;
import com.google.cloud.spanner.Value;
import com.google.cloud.spanner.r2dbc.ConversionFailureException;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource; | /*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
/**
* Test for {@link ClientLibraryDecoder}.
*/
class ClientLibraryDecoderTest {
/**
* Prepare parameters for parametrized test.
*/
static Stream<Arguments> decodingWithConversion() {
return Stream.of(
arguments(Integer.class, 12345L, (Function<Object, Value>) (o) -> Value.int64((Long) o),
12345, null),
arguments(Integer.class, Integer.MAX_VALUE + 1L,
(Function<Object, Value>) (o) -> Value.int64((Long) o), null, | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/ConversionFailureException.java
// public class ConversionFailureException extends R2dbcNonTransientException {
//
// public ConversionFailureException(String message) {
// super(message);
// }
// }
// Path: cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/v2/ClientLibraryDecoderTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.params.provider.Arguments.arguments;
import com.google.cloud.ByteArray;
import com.google.cloud.Date;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.Struct;
import com.google.cloud.spanner.Type;
import com.google.cloud.spanner.Value;
import com.google.cloud.spanner.r2dbc.ConversionFailureException;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
/*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
/**
* Test for {@link ClientLibraryDecoder}.
*/
class ClientLibraryDecoderTest {
/**
* Prepare parameters for parametrized test.
*/
static Stream<Arguments> decodingWithConversion() {
return Stream.of(
arguments(Integer.class, 12345L, (Function<Object, Value>) (o) -> Value.int64((Long) o),
12345, null),
arguments(Integer.class, Integer.MAX_VALUE + 1L,
(Function<Object, Value>) (o) -> Value.int64((Long) o), null, | new ConversionFailureException("2147483648 is out of range for Integer")), |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/it/SpannerClientLibraryTestKit.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
| import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import static io.r2dbc.spi.test.TestKit.TestStatement.INSERT_TWO_COLUMNS;
import static io.r2dbc.spi.test.TestKit.TestStatement.SELECT_VALUE_TWO_COLUMNS;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import com.google.cloud.ServiceOptions;
import com.google.cloud.spanner.DatabaseAdminClient;
import com.google.cloud.spanner.DatabaseId;
import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import io.r2dbc.spi.Result;
import io.r2dbc.spi.Statement;
import io.r2dbc.spi.test.TestKit;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcOperations;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier; | /*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.it;
/**
* R2DBC TCK test implementation.
*/
@Disabled ("Until missing SPI v0.9 functionality is implemented")
public class SpannerClientLibraryTestKit implements TestKit<String> {
private static final String DISABLE_UNSUPPORTED_FUNCTIONALITY =
"Functionality not supported in Cloud Spanner";
private static final ConnectionFactory connectionFactory =
ConnectionFactories.get(
ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), ServiceOptions.getDefaultProjectId()) | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
// Path: cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/it/SpannerClientLibraryTestKit.java
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import static io.r2dbc.spi.test.TestKit.TestStatement.INSERT_TWO_COLUMNS;
import static io.r2dbc.spi.test.TestKit.TestStatement.SELECT_VALUE_TWO_COLUMNS;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import com.google.cloud.ServiceOptions;
import com.google.cloud.spanner.DatabaseAdminClient;
import com.google.cloud.spanner.DatabaseId;
import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import io.r2dbc.spi.Result;
import io.r2dbc.spi.Statement;
import io.r2dbc.spi.test.TestKit;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcOperations;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
/*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.it;
/**
* R2DBC TCK test implementation.
*/
@Disabled ("Until missing SPI v0.9 functionality is implemented")
public class SpannerClientLibraryTestKit implements TestKit<String> {
private static final String DISABLE_UNSUPPORTED_FUNCTIONALITY =
"Functionality not supported in Cloud Spanner";
private static final ConnectionFactory connectionFactory =
ConnectionFactories.get(
ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), ServiceOptions.getDefaultProjectId()) | .option(DRIVER, DRIVER_NAME) |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/it/SpannerClientLibraryTestKit.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
| import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import static io.r2dbc.spi.test.TestKit.TestStatement.INSERT_TWO_COLUMNS;
import static io.r2dbc.spi.test.TestKit.TestStatement.SELECT_VALUE_TWO_COLUMNS;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import com.google.cloud.ServiceOptions;
import com.google.cloud.spanner.DatabaseAdminClient;
import com.google.cloud.spanner.DatabaseId;
import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import io.r2dbc.spi.Result;
import io.r2dbc.spi.Statement;
import io.r2dbc.spi.test.TestKit;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcOperations;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier; | /*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.it;
/**
* R2DBC TCK test implementation.
*/
@Disabled ("Until missing SPI v0.9 functionality is implemented")
public class SpannerClientLibraryTestKit implements TestKit<String> {
private static final String DISABLE_UNSUPPORTED_FUNCTIONALITY =
"Functionality not supported in Cloud Spanner";
private static final ConnectionFactory connectionFactory =
ConnectionFactories.get(
ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), ServiceOptions.getDefaultProjectId())
.option(DRIVER, DRIVER_NAME) | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
// Path: cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/it/SpannerClientLibraryTestKit.java
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import static io.r2dbc.spi.test.TestKit.TestStatement.INSERT_TWO_COLUMNS;
import static io.r2dbc.spi.test.TestKit.TestStatement.SELECT_VALUE_TWO_COLUMNS;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import com.google.cloud.ServiceOptions;
import com.google.cloud.spanner.DatabaseAdminClient;
import com.google.cloud.spanner.DatabaseId;
import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import io.r2dbc.spi.Result;
import io.r2dbc.spi.Statement;
import io.r2dbc.spi.test.TestKit;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcOperations;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
/*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.it;
/**
* R2DBC TCK test implementation.
*/
@Disabled ("Until missing SPI v0.9 functionality is implemented")
public class SpannerClientLibraryTestKit implements TestKit<String> {
private static final String DISABLE_UNSUPPORTED_FUNCTIONALITY =
"Functionality not supported in Cloud Spanner";
private static final ConnectionFactory connectionFactory =
ConnectionFactories.get(
ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), ServiceOptions.getDefaultProjectId())
.option(DRIVER, DRIVER_NAME) | .option(INSTANCE, DatabaseProperties.INSTANCE) |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-spring-data-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/springdata/SpannerR2dbcDialectProvider.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryMetadata.java
// public class SpannerConnectionFactoryMetadata implements ConnectionFactoryMetadata {
//
// /**
// * The name of Cloud Spanner database product.
// */
// public static final String NAME = "Cloud Spanner";
//
// public static final SpannerConnectionFactoryMetadata INSTANCE
// = new SpannerConnectionFactoryMetadata();
//
// private SpannerConnectionFactoryMetadata() {
// }
//
// @Override
// public String getName() {
// return NAME;
// }
//
// }
| import com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryMetadata;
import io.r2dbc.spi.ConnectionFactory;
import java.util.Optional;
import org.springframework.data.r2dbc.dialect.DialectResolver.R2dbcDialectProvider;
import org.springframework.data.r2dbc.dialect.R2dbcDialect; | /*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.springdata;
/**
* Provides the {@link SpannerR2dbcDialect} for Spring Data.
*/
public class SpannerR2dbcDialectProvider implements R2dbcDialectProvider {
@Override
public Optional<R2dbcDialect> getDialect(ConnectionFactory connectionFactory) { | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryMetadata.java
// public class SpannerConnectionFactoryMetadata implements ConnectionFactoryMetadata {
//
// /**
// * The name of Cloud Spanner database product.
// */
// public static final String NAME = "Cloud Spanner";
//
// public static final SpannerConnectionFactoryMetadata INSTANCE
// = new SpannerConnectionFactoryMetadata();
//
// private SpannerConnectionFactoryMetadata() {
// }
//
// @Override
// public String getName() {
// return NAME;
// }
//
// }
// Path: cloud-spanner-spring-data-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/springdata/SpannerR2dbcDialectProvider.java
import com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryMetadata;
import io.r2dbc.spi.ConnectionFactory;
import java.util.Optional;
import org.springframework.data.r2dbc.dialect.DialectResolver.R2dbcDialectProvider;
import org.springframework.data.r2dbc.dialect.R2dbcDialect;
/*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.springdata;
/**
* Provides the {@link SpannerR2dbcDialect} for Spring Data.
*/
public class SpannerR2dbcDialectProvider implements R2dbcDialectProvider {
@Override
public Optional<R2dbcDialect> getDialect(ConnectionFactory connectionFactory) { | if (connectionFactory.getMetadata().getName().equals(SpannerConnectionFactoryMetadata.NAME)) { |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/util/SpannerExceptionUtilTest.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/util/SpannerExceptionUtil.java
// public static R2dbcException createR2dbcException(int errorCode, String message) {
// return createR2dbcException(errorCode, message, null);
// }
| import io.r2dbc.spi.R2dbcTransientResourceException;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import static com.google.cloud.spanner.r2dbc.util.SpannerExceptionUtil.createR2dbcException;
import static org.assertj.core.api.Assertions.assertThat;
import com.google.protobuf.Duration;
import com.google.rpc.Code;
import com.google.rpc.RetryInfo;
import io.grpc.Metadata;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.protobuf.ProtoUtils;
import io.r2dbc.spi.R2dbcDataIntegrityViolationException;
import io.r2dbc.spi.R2dbcException;
import io.r2dbc.spi.R2dbcNonTransientResourceException;
import io.r2dbc.spi.R2dbcPermissionDeniedException; | /*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.util;
class SpannerExceptionUtilTest {
@Test
void testCreateR2dbcException() { | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/util/SpannerExceptionUtil.java
// public static R2dbcException createR2dbcException(int errorCode, String message) {
// return createR2dbcException(errorCode, message, null);
// }
// Path: cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/util/SpannerExceptionUtilTest.java
import io.r2dbc.spi.R2dbcTransientResourceException;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import static com.google.cloud.spanner.r2dbc.util.SpannerExceptionUtil.createR2dbcException;
import static org.assertj.core.api.Assertions.assertThat;
import com.google.protobuf.Duration;
import com.google.rpc.Code;
import com.google.rpc.RetryInfo;
import io.grpc.Metadata;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.protobuf.ProtoUtils;
import io.r2dbc.spi.R2dbcDataIntegrityViolationException;
import io.r2dbc.spi.R2dbcException;
import io.r2dbc.spi.R2dbcNonTransientResourceException;
import io.r2dbc.spi.R2dbcPermissionDeniedException;
/*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.util;
class SpannerExceptionUtilTest {
@Test
void testCreateR2dbcException() { | R2dbcException exception = SpannerExceptionUtil.createR2dbcException( |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/SpannerClientLibraryResult.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/util/Assert.java
// public class Assert {
//
// private Assert() {
// // Prevent instantiation.
// }
//
// /**
// * Checks that a specified object reference is not {@code null} and throws a customized
// * {@link IllegalArgumentException} if it is.
// *
// * @param t the object reference to check for nullity
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// * @param <T> the type of object reference
// *
// * @return the original object {@code t}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static <T> T requireNonNull(@Nullable T t, String message) {
// if (t == null) {
// throw new IllegalArgumentException(message);
// }
//
// return t;
// }
//
// /**
// * Checks that a specified object reference is not {@code null} or an empty string, and throws a
// * customized {@link IllegalArgumentException} if it is.
// *
// * @param s string to check
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// *
// * @return the original string {@code s}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static ByteString requireNonEmpty(@Nullable ByteString s, String message) {
// if (s == null || s.isEmpty()) {
// throw new IllegalArgumentException(message);
// }
//
// return s;
// }
//
// /**
// * Checks that a specified object reference is not {@code null} or an empty string, and throws a
// * customized {@link IllegalArgumentException} if it is.
// *
// * @param s string to check
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// *
// * @return the original string {@code s}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static String requireNonEmpty(@Nullable String s, String message) {
// if (s == null || s.isEmpty()) {
// throw new IllegalArgumentException(message);
// }
//
// return s;
// }
//
// }
| import com.google.cloud.spanner.r2dbc.util.Assert;
import io.r2dbc.spi.Result;
import io.r2dbc.spi.Row;
import io.r2dbc.spi.RowMetadata;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono; | /*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class SpannerClientLibraryResult implements Result {
private final Flux<SpannerClientLibraryRow> resultRows;
private final int numRowsUpdated;
private RowMetadata rowMetadata;
public SpannerClientLibraryResult(
Flux<SpannerClientLibraryRow> resultRows, int numRowsUpdated) { | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/util/Assert.java
// public class Assert {
//
// private Assert() {
// // Prevent instantiation.
// }
//
// /**
// * Checks that a specified object reference is not {@code null} and throws a customized
// * {@link IllegalArgumentException} if it is.
// *
// * @param t the object reference to check for nullity
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// * @param <T> the type of object reference
// *
// * @return the original object {@code t}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static <T> T requireNonNull(@Nullable T t, String message) {
// if (t == null) {
// throw new IllegalArgumentException(message);
// }
//
// return t;
// }
//
// /**
// * Checks that a specified object reference is not {@code null} or an empty string, and throws a
// * customized {@link IllegalArgumentException} if it is.
// *
// * @param s string to check
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// *
// * @return the original string {@code s}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static ByteString requireNonEmpty(@Nullable ByteString s, String message) {
// if (s == null || s.isEmpty()) {
// throw new IllegalArgumentException(message);
// }
//
// return s;
// }
//
// /**
// * Checks that a specified object reference is not {@code null} or an empty string, and throws a
// * customized {@link IllegalArgumentException} if it is.
// *
// * @param s string to check
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// *
// * @return the original string {@code s}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static String requireNonEmpty(@Nullable String s, String message) {
// if (s == null || s.isEmpty()) {
// throw new IllegalArgumentException(message);
// }
//
// return s;
// }
//
// }
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/SpannerClientLibraryResult.java
import com.google.cloud.spanner.r2dbc.util.Assert;
import io.r2dbc.spi.Result;
import io.r2dbc.spi.Row;
import io.r2dbc.spi.RowMetadata;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class SpannerClientLibraryResult implements Result {
private final Flux<SpannerClientLibraryRow> resultRows;
private final int numRowsUpdated;
private RowMetadata rowMetadata;
public SpannerClientLibraryResult(
Flux<SpannerClientLibraryRow> resultRows, int numRowsUpdated) { | this.resultRows = Assert.requireNonNull(resultRows, "A non-null flux of rows is required."); |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/IterableBinder.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/BindingFailureException.java
// public class BindingFailureException extends R2dbcNonTransientException {
//
// public BindingFailureException(String message) {
// super(message);
// }
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerType.java
// public abstract class SpannerType implements io.r2dbc.spi.Type {
//
// private Type type;
//
// private static final Map<Code, Class<?>> SPANNER_TO_JAVA_TYPES = buildTypeMap();
// private static final Map<Code, IterableStatementBinder> ARRAY_BINDERS = buildArrayBinderMap();
//
// private SpannerType(Type type) {
// this.type = type;
// }
//
// public abstract boolean isArray();
//
// /**
// * Adds type-specific binding of provided value to statement.
// * Fails if the value or type are not compatiblie with Spanner arrays.
// *
// * @param binder a {@link ValueBinder} from a call to {@code Statement.Builder.bind(String)}
// * @param value {@link Iterable} value to bind
// */
// public void bindIterable(ValueBinder<Statement.Builder> binder, Iterable<?> value) {
// if (!this.isArray()) {
// throw new BindingFailureException("Iterable cannot be bound to a non-array Spanner type.");
// }
//
// IterableStatementBinder typedBinder =
// ARRAY_BINDERS.get(this.type.getArrayElementType().getCode());
// if (typedBinder == null) {
// throw new BindingFailureException("Array binder not found for type " + this.type);
// }
// typedBinder.bind(binder, value);
//
// }
//
// /**
// * Returns a `{@link SpannerType} corresponding to the provided Spanner client library type.
// *
// * @param type client library {@link Type}
// * @return `{@link SpannerType} wrapper for the provided client library type
// */
// public static SpannerType of(Type type) {
// return new SpannerType(type) {
// @Override
// public Class<?> getJavaType() {
// return SPANNER_TO_JAVA_TYPES.get(type.getCode());
// }
//
// @Override
// public String getName() {
// return type.toString();
// }
//
// @Override
// public boolean isArray() {
// return type.getCode() == Code.ARRAY;
// }
// };
// }
//
// private static Map<Code, Class<?>> buildTypeMap() {
// Map<Code, Class<?>> map = new EnumMap<>(Code.class);
// map.put(Code.BOOL, Boolean.class);
// map.put(Code.BYTES, ByteArray.class);
// map.put(Code.DATE, Date.class);
// map.put(Code.FLOAT64, Double.class);
// map.put(Code.NUMERIC, BigDecimal.class);
// map.put(Code.INT64, Long.class);
// map.put(Code.STRING, String.class);
// map.put(Code.STRUCT, Struct.class);
// map.put(Code.TIMESTAMP, Timestamp.class);
// map.put(Code.ARRAY, Iterable.class);
//
// return map;
// }
//
// private static Map<Code, IterableStatementBinder> buildArrayBinderMap() {
// Map<Code, IterableStatementBinder> map = new EnumMap<>(Code.class);
// map.put(Code.BOOL, (b, i) -> b.toBoolArray((Iterable<Boolean>) i));
// map.put(Code.INT64, (b, i) -> b.toInt64Array((Iterable<Long>) i));
// map.put(Code.NUMERIC, (b, i) -> b.toNumericArray((Iterable<BigDecimal>) i));
// map.put(Code.FLOAT64, (b, i) -> b.toFloat64Array((Iterable<Double>) i));
// map.put(Code.STRING, (b, i) -> b.toStringArray((Iterable<String>) i));
// map.put(Code.BYTES, (b, i) -> b.toBytesArray((Iterable<ByteArray>) i));
// map.put(Code.TIMESTAMP, (b, i) -> b.toTimestampArray((Iterable<Timestamp>) i));
// map.put(Code.DATE, (b, i) -> b.toDateArray((Iterable<Date>) i));
// // no JSON, ARRAY, STRUCT for now
//
// return map;
// }
//
// // More readable equivalent to BiConsumer<ValueBinder<Statement.Builder>, Iterable<?>>
// @FunctionalInterface
// private interface IterableStatementBinder {
// void bind(ValueBinder<Statement.Builder> binder, Iterable<?> value);
// }
// }
| import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.r2dbc.BindingFailureException;
import com.google.cloud.spanner.r2dbc.SpannerType; | /*
* Copyright 2022-2022 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
/**
* Binds {@link Iterable} values to statement parameters, using Spanner type information as a hint.
*/
class IterableBinder implements ClientLibraryTypeBinder {
@Override | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/BindingFailureException.java
// public class BindingFailureException extends R2dbcNonTransientException {
//
// public BindingFailureException(String message) {
// super(message);
// }
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerType.java
// public abstract class SpannerType implements io.r2dbc.spi.Type {
//
// private Type type;
//
// private static final Map<Code, Class<?>> SPANNER_TO_JAVA_TYPES = buildTypeMap();
// private static final Map<Code, IterableStatementBinder> ARRAY_BINDERS = buildArrayBinderMap();
//
// private SpannerType(Type type) {
// this.type = type;
// }
//
// public abstract boolean isArray();
//
// /**
// * Adds type-specific binding of provided value to statement.
// * Fails if the value or type are not compatiblie with Spanner arrays.
// *
// * @param binder a {@link ValueBinder} from a call to {@code Statement.Builder.bind(String)}
// * @param value {@link Iterable} value to bind
// */
// public void bindIterable(ValueBinder<Statement.Builder> binder, Iterable<?> value) {
// if (!this.isArray()) {
// throw new BindingFailureException("Iterable cannot be bound to a non-array Spanner type.");
// }
//
// IterableStatementBinder typedBinder =
// ARRAY_BINDERS.get(this.type.getArrayElementType().getCode());
// if (typedBinder == null) {
// throw new BindingFailureException("Array binder not found for type " + this.type);
// }
// typedBinder.bind(binder, value);
//
// }
//
// /**
// * Returns a `{@link SpannerType} corresponding to the provided Spanner client library type.
// *
// * @param type client library {@link Type}
// * @return `{@link SpannerType} wrapper for the provided client library type
// */
// public static SpannerType of(Type type) {
// return new SpannerType(type) {
// @Override
// public Class<?> getJavaType() {
// return SPANNER_TO_JAVA_TYPES.get(type.getCode());
// }
//
// @Override
// public String getName() {
// return type.toString();
// }
//
// @Override
// public boolean isArray() {
// return type.getCode() == Code.ARRAY;
// }
// };
// }
//
// private static Map<Code, Class<?>> buildTypeMap() {
// Map<Code, Class<?>> map = new EnumMap<>(Code.class);
// map.put(Code.BOOL, Boolean.class);
// map.put(Code.BYTES, ByteArray.class);
// map.put(Code.DATE, Date.class);
// map.put(Code.FLOAT64, Double.class);
// map.put(Code.NUMERIC, BigDecimal.class);
// map.put(Code.INT64, Long.class);
// map.put(Code.STRING, String.class);
// map.put(Code.STRUCT, Struct.class);
// map.put(Code.TIMESTAMP, Timestamp.class);
// map.put(Code.ARRAY, Iterable.class);
//
// return map;
// }
//
// private static Map<Code, IterableStatementBinder> buildArrayBinderMap() {
// Map<Code, IterableStatementBinder> map = new EnumMap<>(Code.class);
// map.put(Code.BOOL, (b, i) -> b.toBoolArray((Iterable<Boolean>) i));
// map.put(Code.INT64, (b, i) -> b.toInt64Array((Iterable<Long>) i));
// map.put(Code.NUMERIC, (b, i) -> b.toNumericArray((Iterable<BigDecimal>) i));
// map.put(Code.FLOAT64, (b, i) -> b.toFloat64Array((Iterable<Double>) i));
// map.put(Code.STRING, (b, i) -> b.toStringArray((Iterable<String>) i));
// map.put(Code.BYTES, (b, i) -> b.toBytesArray((Iterable<ByteArray>) i));
// map.put(Code.TIMESTAMP, (b, i) -> b.toTimestampArray((Iterable<Timestamp>) i));
// map.put(Code.DATE, (b, i) -> b.toDateArray((Iterable<Date>) i));
// // no JSON, ARRAY, STRUCT for now
//
// return map;
// }
//
// // More readable equivalent to BiConsumer<ValueBinder<Statement.Builder>, Iterable<?>>
// @FunctionalInterface
// private interface IterableStatementBinder {
// void bind(ValueBinder<Statement.Builder> binder, Iterable<?> value);
// }
// }
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/IterableBinder.java
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.r2dbc.BindingFailureException;
import com.google.cloud.spanner.r2dbc.SpannerType;
/*
* Copyright 2022-2022 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
/**
* Binds {@link Iterable} values to statement parameters, using Spanner type information as a hint.
*/
class IterableBinder implements ClientLibraryTypeBinder {
@Override | public boolean canBind(Class<?> type, SpannerType spannerType) { |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/IterableBinder.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/BindingFailureException.java
// public class BindingFailureException extends R2dbcNonTransientException {
//
// public BindingFailureException(String message) {
// super(message);
// }
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerType.java
// public abstract class SpannerType implements io.r2dbc.spi.Type {
//
// private Type type;
//
// private static final Map<Code, Class<?>> SPANNER_TO_JAVA_TYPES = buildTypeMap();
// private static final Map<Code, IterableStatementBinder> ARRAY_BINDERS = buildArrayBinderMap();
//
// private SpannerType(Type type) {
// this.type = type;
// }
//
// public abstract boolean isArray();
//
// /**
// * Adds type-specific binding of provided value to statement.
// * Fails if the value or type are not compatiblie with Spanner arrays.
// *
// * @param binder a {@link ValueBinder} from a call to {@code Statement.Builder.bind(String)}
// * @param value {@link Iterable} value to bind
// */
// public void bindIterable(ValueBinder<Statement.Builder> binder, Iterable<?> value) {
// if (!this.isArray()) {
// throw new BindingFailureException("Iterable cannot be bound to a non-array Spanner type.");
// }
//
// IterableStatementBinder typedBinder =
// ARRAY_BINDERS.get(this.type.getArrayElementType().getCode());
// if (typedBinder == null) {
// throw new BindingFailureException("Array binder not found for type " + this.type);
// }
// typedBinder.bind(binder, value);
//
// }
//
// /**
// * Returns a `{@link SpannerType} corresponding to the provided Spanner client library type.
// *
// * @param type client library {@link Type}
// * @return `{@link SpannerType} wrapper for the provided client library type
// */
// public static SpannerType of(Type type) {
// return new SpannerType(type) {
// @Override
// public Class<?> getJavaType() {
// return SPANNER_TO_JAVA_TYPES.get(type.getCode());
// }
//
// @Override
// public String getName() {
// return type.toString();
// }
//
// @Override
// public boolean isArray() {
// return type.getCode() == Code.ARRAY;
// }
// };
// }
//
// private static Map<Code, Class<?>> buildTypeMap() {
// Map<Code, Class<?>> map = new EnumMap<>(Code.class);
// map.put(Code.BOOL, Boolean.class);
// map.put(Code.BYTES, ByteArray.class);
// map.put(Code.DATE, Date.class);
// map.put(Code.FLOAT64, Double.class);
// map.put(Code.NUMERIC, BigDecimal.class);
// map.put(Code.INT64, Long.class);
// map.put(Code.STRING, String.class);
// map.put(Code.STRUCT, Struct.class);
// map.put(Code.TIMESTAMP, Timestamp.class);
// map.put(Code.ARRAY, Iterable.class);
//
// return map;
// }
//
// private static Map<Code, IterableStatementBinder> buildArrayBinderMap() {
// Map<Code, IterableStatementBinder> map = new EnumMap<>(Code.class);
// map.put(Code.BOOL, (b, i) -> b.toBoolArray((Iterable<Boolean>) i));
// map.put(Code.INT64, (b, i) -> b.toInt64Array((Iterable<Long>) i));
// map.put(Code.NUMERIC, (b, i) -> b.toNumericArray((Iterable<BigDecimal>) i));
// map.put(Code.FLOAT64, (b, i) -> b.toFloat64Array((Iterable<Double>) i));
// map.put(Code.STRING, (b, i) -> b.toStringArray((Iterable<String>) i));
// map.put(Code.BYTES, (b, i) -> b.toBytesArray((Iterable<ByteArray>) i));
// map.put(Code.TIMESTAMP, (b, i) -> b.toTimestampArray((Iterable<Timestamp>) i));
// map.put(Code.DATE, (b, i) -> b.toDateArray((Iterable<Date>) i));
// // no JSON, ARRAY, STRUCT for now
//
// return map;
// }
//
// // More readable equivalent to BiConsumer<ValueBinder<Statement.Builder>, Iterable<?>>
// @FunctionalInterface
// private interface IterableStatementBinder {
// void bind(ValueBinder<Statement.Builder> binder, Iterable<?> value);
// }
// }
| import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.r2dbc.BindingFailureException;
import com.google.cloud.spanner.r2dbc.SpannerType; | /*
* Copyright 2022-2022 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
/**
* Binds {@link Iterable} values to statement parameters, using Spanner type information as a hint.
*/
class IterableBinder implements ClientLibraryTypeBinder {
@Override
public boolean canBind(Class<?> type, SpannerType spannerType) {
// Handling all iterables regardless of SpannerType will allow more useful error messages.
return Iterable.class.isAssignableFrom(type);
}
@Override
public void bind(
Statement.Builder builder, String name, Object value, SpannerType spannerType) {
if (spannerType == null) { | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/BindingFailureException.java
// public class BindingFailureException extends R2dbcNonTransientException {
//
// public BindingFailureException(String message) {
// super(message);
// }
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerType.java
// public abstract class SpannerType implements io.r2dbc.spi.Type {
//
// private Type type;
//
// private static final Map<Code, Class<?>> SPANNER_TO_JAVA_TYPES = buildTypeMap();
// private static final Map<Code, IterableStatementBinder> ARRAY_BINDERS = buildArrayBinderMap();
//
// private SpannerType(Type type) {
// this.type = type;
// }
//
// public abstract boolean isArray();
//
// /**
// * Adds type-specific binding of provided value to statement.
// * Fails if the value or type are not compatiblie with Spanner arrays.
// *
// * @param binder a {@link ValueBinder} from a call to {@code Statement.Builder.bind(String)}
// * @param value {@link Iterable} value to bind
// */
// public void bindIterable(ValueBinder<Statement.Builder> binder, Iterable<?> value) {
// if (!this.isArray()) {
// throw new BindingFailureException("Iterable cannot be bound to a non-array Spanner type.");
// }
//
// IterableStatementBinder typedBinder =
// ARRAY_BINDERS.get(this.type.getArrayElementType().getCode());
// if (typedBinder == null) {
// throw new BindingFailureException("Array binder not found for type " + this.type);
// }
// typedBinder.bind(binder, value);
//
// }
//
// /**
// * Returns a `{@link SpannerType} corresponding to the provided Spanner client library type.
// *
// * @param type client library {@link Type}
// * @return `{@link SpannerType} wrapper for the provided client library type
// */
// public static SpannerType of(Type type) {
// return new SpannerType(type) {
// @Override
// public Class<?> getJavaType() {
// return SPANNER_TO_JAVA_TYPES.get(type.getCode());
// }
//
// @Override
// public String getName() {
// return type.toString();
// }
//
// @Override
// public boolean isArray() {
// return type.getCode() == Code.ARRAY;
// }
// };
// }
//
// private static Map<Code, Class<?>> buildTypeMap() {
// Map<Code, Class<?>> map = new EnumMap<>(Code.class);
// map.put(Code.BOOL, Boolean.class);
// map.put(Code.BYTES, ByteArray.class);
// map.put(Code.DATE, Date.class);
// map.put(Code.FLOAT64, Double.class);
// map.put(Code.NUMERIC, BigDecimal.class);
// map.put(Code.INT64, Long.class);
// map.put(Code.STRING, String.class);
// map.put(Code.STRUCT, Struct.class);
// map.put(Code.TIMESTAMP, Timestamp.class);
// map.put(Code.ARRAY, Iterable.class);
//
// return map;
// }
//
// private static Map<Code, IterableStatementBinder> buildArrayBinderMap() {
// Map<Code, IterableStatementBinder> map = new EnumMap<>(Code.class);
// map.put(Code.BOOL, (b, i) -> b.toBoolArray((Iterable<Boolean>) i));
// map.put(Code.INT64, (b, i) -> b.toInt64Array((Iterable<Long>) i));
// map.put(Code.NUMERIC, (b, i) -> b.toNumericArray((Iterable<BigDecimal>) i));
// map.put(Code.FLOAT64, (b, i) -> b.toFloat64Array((Iterable<Double>) i));
// map.put(Code.STRING, (b, i) -> b.toStringArray((Iterable<String>) i));
// map.put(Code.BYTES, (b, i) -> b.toBytesArray((Iterable<ByteArray>) i));
// map.put(Code.TIMESTAMP, (b, i) -> b.toTimestampArray((Iterable<Timestamp>) i));
// map.put(Code.DATE, (b, i) -> b.toDateArray((Iterable<Date>) i));
// // no JSON, ARRAY, STRUCT for now
//
// return map;
// }
//
// // More readable equivalent to BiConsumer<ValueBinder<Statement.Builder>, Iterable<?>>
// @FunctionalInterface
// private interface IterableStatementBinder {
// void bind(ValueBinder<Statement.Builder> binder, Iterable<?> value);
// }
// }
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/IterableBinder.java
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.r2dbc.BindingFailureException;
import com.google.cloud.spanner.r2dbc.SpannerType;
/*
* Copyright 2022-2022 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
/**
* Binds {@link Iterable} values to statement parameters, using Spanner type information as a hint.
*/
class IterableBinder implements ClientLibraryTypeBinder {
@Override
public boolean canBind(Class<?> type, SpannerType spannerType) {
// Handling all iterables regardless of SpannerType will allow more useful error messages.
return Iterable.class.isAssignableFrom(type);
}
@Override
public void bind(
Statement.Builder builder, String name, Object value, SpannerType spannerType) {
if (spannerType == null) { | throw new BindingFailureException( |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/StringToJsonConverter.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/ConversionFailureException.java
// public class ConversionFailureException extends R2dbcNonTransientException {
//
// public ConversionFailureException(String message) {
// super(message);
// }
// }
| import com.google.cloud.spanner.r2dbc.ConversionFailureException; | /*
* Copyright 2021-2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class StringToJsonConverter implements SpannerClientLibrariesConverter<JsonWrapper> {
@Override
public boolean canConvert(Class<?> inputClass, Class<?> resultClass) {
return inputClass == String.class && resultClass == JsonWrapper.class;
}
@Override
public JsonWrapper convert(Object input) {
if (!canConvert(input.getClass(), JsonWrapper.class)) { | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/ConversionFailureException.java
// public class ConversionFailureException extends R2dbcNonTransientException {
//
// public ConversionFailureException(String message) {
// super(message);
// }
// }
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/StringToJsonConverter.java
import com.google.cloud.spanner.r2dbc.ConversionFailureException;
/*
* Copyright 2021-2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class StringToJsonConverter implements SpannerClientLibrariesConverter<JsonWrapper> {
@Override
public boolean canConvert(Class<?> inputClass, Class<?> resultClass) {
return inputClass == String.class && resultClass == JsonWrapper.class;
}
@Override
public JsonWrapper convert(Object input) {
if (!canConvert(input.getClass(), JsonWrapper.class)) { | throw new ConversionFailureException( |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/SpannerClientLibraryRow.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/util/Assert.java
// public class Assert {
//
// private Assert() {
// // Prevent instantiation.
// }
//
// /**
// * Checks that a specified object reference is not {@code null} and throws a customized
// * {@link IllegalArgumentException} if it is.
// *
// * @param t the object reference to check for nullity
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// * @param <T> the type of object reference
// *
// * @return the original object {@code t}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static <T> T requireNonNull(@Nullable T t, String message) {
// if (t == null) {
// throw new IllegalArgumentException(message);
// }
//
// return t;
// }
//
// /**
// * Checks that a specified object reference is not {@code null} or an empty string, and throws a
// * customized {@link IllegalArgumentException} if it is.
// *
// * @param s string to check
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// *
// * @return the original string {@code s}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static ByteString requireNonEmpty(@Nullable ByteString s, String message) {
// if (s == null || s.isEmpty()) {
// throw new IllegalArgumentException(message);
// }
//
// return s;
// }
//
// /**
// * Checks that a specified object reference is not {@code null} or an empty string, and throws a
// * customized {@link IllegalArgumentException} if it is.
// *
// * @param s string to check
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// *
// * @return the original string {@code s}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static String requireNonEmpty(@Nullable String s, String message) {
// if (s == null || s.isEmpty()) {
// throw new IllegalArgumentException(message);
// }
//
// return s;
// }
//
// }
| import com.google.cloud.spanner.Struct;
import com.google.cloud.spanner.r2dbc.util.Assert;
import io.r2dbc.spi.Row;
import io.r2dbc.spi.RowMetadata; | /*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class SpannerClientLibraryRow implements Row {
private Struct rowFields;
public SpannerClientLibraryRow(Struct rowFields) { | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/util/Assert.java
// public class Assert {
//
// private Assert() {
// // Prevent instantiation.
// }
//
// /**
// * Checks that a specified object reference is not {@code null} and throws a customized
// * {@link IllegalArgumentException} if it is.
// *
// * @param t the object reference to check for nullity
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// * @param <T> the type of object reference
// *
// * @return the original object {@code t}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static <T> T requireNonNull(@Nullable T t, String message) {
// if (t == null) {
// throw new IllegalArgumentException(message);
// }
//
// return t;
// }
//
// /**
// * Checks that a specified object reference is not {@code null} or an empty string, and throws a
// * customized {@link IllegalArgumentException} if it is.
// *
// * @param s string to check
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// *
// * @return the original string {@code s}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static ByteString requireNonEmpty(@Nullable ByteString s, String message) {
// if (s == null || s.isEmpty()) {
// throw new IllegalArgumentException(message);
// }
//
// return s;
// }
//
// /**
// * Checks that a specified object reference is not {@code null} or an empty string, and throws a
// * customized {@link IllegalArgumentException} if it is.
// *
// * @param s string to check
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// *
// * @return the original string {@code s}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static String requireNonEmpty(@Nullable String s, String message) {
// if (s == null || s.isEmpty()) {
// throw new IllegalArgumentException(message);
// }
//
// return s;
// }
//
// }
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/SpannerClientLibraryRow.java
import com.google.cloud.spanner.Struct;
import com.google.cloud.spanner.r2dbc.util.Assert;
import io.r2dbc.spi.Row;
import io.r2dbc.spi.RowMetadata;
/*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class SpannerClientLibraryRow implements Row {
private Struct rowFields;
public SpannerClientLibraryRow(Struct rowFields) { | Assert.requireNonNull(rowFields, "rowFields must not be null"); |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-spring-data-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/springdata/SpannerR2dbcDialect.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/JsonWrapper.java
// public class JsonWrapper {
// private String jsonString;
//
// public JsonWrapper(String jsonString) {
// this.jsonString = jsonString;
// }
//
// protected Value getJsonVal() {
// return Value.json(this.jsonString);
// }
//
// public static JsonWrapper of(String jsonString) {
// return new JsonWrapper(jsonString);
// }
//
// @Override
// public String toString() {
// return this.jsonString;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// JsonWrapper that = (JsonWrapper) o;
// return Objects.equal(this.jsonString, that.jsonString);
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(this.jsonString);
// }
// }
| import com.google.cloud.spanner.r2dbc.v2.JsonWrapper;
import com.google.gson.Gson;
import java.util.Arrays;
import java.util.Collection;
import org.springframework.data.r2dbc.dialect.R2dbcDialect;
import org.springframework.data.relational.core.dialect.AbstractDialect;
import org.springframework.data.relational.core.dialect.ArrayColumns;
import org.springframework.data.relational.core.dialect.LimitClause;
import org.springframework.data.relational.core.dialect.LockClause;
import org.springframework.data.relational.core.sql.LockOptions;
import org.springframework.r2dbc.core.binding.BindMarkersFactory; | private static final LockClause LOCK_CLAUSE = new LockClause() {
@Override
public String getLock(LockOptions lockOptions) {
return "";
}
@Override
public Position getClausePosition() {
// It does not matter where to append an empty string.
return Position.AFTER_FROM_TABLE;
}
};
@Override
public BindMarkersFactory getBindMarkersFactory() {
return NAMED;
}
@Override
public LimitClause limit() {
return LIMIT_CLAUSE;
}
@Override
public LockClause lock() {
return LOCK_CLAUSE;
}
@Override
public Collection<? extends Class<?>> getSimpleTypes() { | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/JsonWrapper.java
// public class JsonWrapper {
// private String jsonString;
//
// public JsonWrapper(String jsonString) {
// this.jsonString = jsonString;
// }
//
// protected Value getJsonVal() {
// return Value.json(this.jsonString);
// }
//
// public static JsonWrapper of(String jsonString) {
// return new JsonWrapper(jsonString);
// }
//
// @Override
// public String toString() {
// return this.jsonString;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// JsonWrapper that = (JsonWrapper) o;
// return Objects.equal(this.jsonString, that.jsonString);
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(this.jsonString);
// }
// }
// Path: cloud-spanner-spring-data-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/springdata/SpannerR2dbcDialect.java
import com.google.cloud.spanner.r2dbc.v2.JsonWrapper;
import com.google.gson.Gson;
import java.util.Arrays;
import java.util.Collection;
import org.springframework.data.r2dbc.dialect.R2dbcDialect;
import org.springframework.data.relational.core.dialect.AbstractDialect;
import org.springframework.data.relational.core.dialect.ArrayColumns;
import org.springframework.data.relational.core.dialect.LimitClause;
import org.springframework.data.relational.core.dialect.LockClause;
import org.springframework.data.relational.core.sql.LockOptions;
import org.springframework.r2dbc.core.binding.BindMarkersFactory;
private static final LockClause LOCK_CLAUSE = new LockClause() {
@Override
public String getLock(LockOptions lockOptions) {
return "";
}
@Override
public Position getClausePosition() {
// It does not matter where to append an empty string.
return Position.AFTER_FROM_TABLE;
}
};
@Override
public BindMarkersFactory getBindMarkersFactory() {
return NAMED;
}
@Override
public LimitClause limit() {
return LIMIT_CLAUSE;
}
@Override
public LockClause lock() {
return LOCK_CLAUSE;
}
@Override
public Collection<? extends Class<?>> getSimpleTypes() { | return Arrays.asList(JsonWrapper.class); |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/it/SessionCleanupUtils.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/util/ObservableReactiveUtil.java
// public class ObservableReactiveUtil {
//
// /**
// * Invokes a lambda that in turn issues a remote call, directing the response to a {@link Mono}
// * stream.
// *
// * @param remoteCall lambda capable of invoking the correct remote call, making use of the
// * {@link Mono}-converting {@link StreamObserver} implementation.
// * @param <ResponseT> type of remote call response
// *
// * @return {@link Mono} containing the response of the unary call.
// */
// public static <ResponseT> Mono<ResponseT> unaryCall(
// Consumer<StreamObserver<ResponseT>> remoteCall) {
// return Mono.create(sink -> remoteCall.accept(new UnaryStreamObserver<>(sink)));
// }
//
// /**
// * Invokes a lambda that issues a streaming call and directs the response to a {@link Flux}
// * stream.
// *
// * @param remoteCall call to make
// * @param <RequestT> request type
// * @param <ResponseT> response type
// *
// * @return {@link Flux} of response objects resulting from the streaming call.
// */
// public static <RequestT, ResponseT> Flux<ResponseT> streamingCall(
// Consumer<StreamObserver<ResponseT>> remoteCall) {
//
// return Flux.create(sink -> {
// StreamingObserver<RequestT, ResponseT> observer = new StreamingObserver<>(sink);
// remoteCall.accept(observer);
// sink.onRequest(demand -> observer.request(demand));
// });
// }
//
// static class StreamingObserver<RequestT, ResponseT>
// implements ClientResponseObserver<RequestT, ResponseT> {
// ClientCallStreamObserver<RequestT> rsObserver;
// FluxSink<ResponseT> sink;
//
// public StreamingObserver(FluxSink<ResponseT> sink) {
// this.sink = sink;
// }
//
// @Override
// public void onNext(ResponseT value) {
// this.sink.next(value);
// }
//
// @Override
// public void onError(Throwable throwable) {
// this.sink.error(SpannerExceptionUtil.createR2dbcException(throwable));
// }
//
// @Override
// public void onCompleted() {
// this.sink.complete();
// }
//
// @Override
// public void beforeStart(ClientCallStreamObserver<RequestT> requestStream) {
// this.rsObserver = requestStream;
// requestStream.disableAutoInboundFlowControl();
// this.sink.onCancel(() -> requestStream.cancel("Flux requested cancel.", null));
// }
//
// public void request(long n) {
// this.rsObserver.request(n > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) n);
// }
// }
//
// /**
// * Forwards the result of a unary gRPC call to a {@link MonoSink}.
// *
// * <p>Unary gRPC calls expect a single response or an error, so completion of the call without an
// * emitted value is an error condition.
// *
// * @param <ResponseT> type of expected gRPC call response value.
// */
// private static class UnaryStreamObserver<ResponseT> implements StreamObserver<ResponseT> {
//
// private boolean terminalEventReceived;
//
// private final MonoSink<ResponseT> sink;
//
// public UnaryStreamObserver(MonoSink<ResponseT> sink) {
// this.sink = sink;
// }
//
// @Override
// public void onNext(ResponseT response) {
// this.terminalEventReceived = true;
// this.sink.success(response);
// }
//
// @Override
// public void onError(Throwable throwable) {
// this.terminalEventReceived = true;
// this.sink.error(SpannerExceptionUtil.createR2dbcException(throwable));
// }
//
// @Override
// public void onCompleted() {
// if (!this.terminalEventReceived) {
// this.sink.error(
// new RuntimeException("Unary gRPC call completed without yielding a value or an error"));
// }
// }
// }
// }
| import io.grpc.stub.StreamObserver;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.ServiceOptions;
import com.google.cloud.spanner.r2dbc.util.ObservableReactiveUtil;
import com.google.protobuf.Empty;
import com.google.spanner.v1.DatabaseName;
import com.google.spanner.v1.DeleteSessionRequest;
import com.google.spanner.v1.ListSessionsRequest;
import com.google.spanner.v1.ListSessionsResponse;
import com.google.spanner.v1.Session;
import com.google.spanner.v1.SpannerGrpc;
import com.google.spanner.v1.SpannerGrpc.SpannerStub;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.auth.MoreCallCredentials; | * Exceptions:
* - you are running in a CI environment and there are other tests running.
* - you want to verify session state after a test. In this case, make another method
* verifying the correct number of sessions (exactly 1, greater than 10 etc.)
*/
static void verifyNoLeftoverSessions() throws Exception {
List<String> activeSessions = getSessionNames();
if (activeSessions.isEmpty()) {
System.out.println("No leftover sessions, yay!");
} else {
throw new IllegalStateException("Expected no sessions, but found " + activeSessions.size());
}
}
private static List<String> getSessionNames() throws Exception {
String databaseName = DatabaseName.format(ServiceOptions.getDefaultProjectId(),
DatabaseProperties.INSTANCE, DatabaseProperties.DATABASE);
String nextPageToken = null;
List<String> sessionNames = new ArrayList<>();
do {
ListSessionsRequest.Builder requestBuilder =
ListSessionsRequest.newBuilder().setDatabase(databaseName);
if (nextPageToken != null) {
requestBuilder.setPageToken(nextPageToken);
}
ListSessionsResponse listSessionsResponse = | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/util/ObservableReactiveUtil.java
// public class ObservableReactiveUtil {
//
// /**
// * Invokes a lambda that in turn issues a remote call, directing the response to a {@link Mono}
// * stream.
// *
// * @param remoteCall lambda capable of invoking the correct remote call, making use of the
// * {@link Mono}-converting {@link StreamObserver} implementation.
// * @param <ResponseT> type of remote call response
// *
// * @return {@link Mono} containing the response of the unary call.
// */
// public static <ResponseT> Mono<ResponseT> unaryCall(
// Consumer<StreamObserver<ResponseT>> remoteCall) {
// return Mono.create(sink -> remoteCall.accept(new UnaryStreamObserver<>(sink)));
// }
//
// /**
// * Invokes a lambda that issues a streaming call and directs the response to a {@link Flux}
// * stream.
// *
// * @param remoteCall call to make
// * @param <RequestT> request type
// * @param <ResponseT> response type
// *
// * @return {@link Flux} of response objects resulting from the streaming call.
// */
// public static <RequestT, ResponseT> Flux<ResponseT> streamingCall(
// Consumer<StreamObserver<ResponseT>> remoteCall) {
//
// return Flux.create(sink -> {
// StreamingObserver<RequestT, ResponseT> observer = new StreamingObserver<>(sink);
// remoteCall.accept(observer);
// sink.onRequest(demand -> observer.request(demand));
// });
// }
//
// static class StreamingObserver<RequestT, ResponseT>
// implements ClientResponseObserver<RequestT, ResponseT> {
// ClientCallStreamObserver<RequestT> rsObserver;
// FluxSink<ResponseT> sink;
//
// public StreamingObserver(FluxSink<ResponseT> sink) {
// this.sink = sink;
// }
//
// @Override
// public void onNext(ResponseT value) {
// this.sink.next(value);
// }
//
// @Override
// public void onError(Throwable throwable) {
// this.sink.error(SpannerExceptionUtil.createR2dbcException(throwable));
// }
//
// @Override
// public void onCompleted() {
// this.sink.complete();
// }
//
// @Override
// public void beforeStart(ClientCallStreamObserver<RequestT> requestStream) {
// this.rsObserver = requestStream;
// requestStream.disableAutoInboundFlowControl();
// this.sink.onCancel(() -> requestStream.cancel("Flux requested cancel.", null));
// }
//
// public void request(long n) {
// this.rsObserver.request(n > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) n);
// }
// }
//
// /**
// * Forwards the result of a unary gRPC call to a {@link MonoSink}.
// *
// * <p>Unary gRPC calls expect a single response or an error, so completion of the call without an
// * emitted value is an error condition.
// *
// * @param <ResponseT> type of expected gRPC call response value.
// */
// private static class UnaryStreamObserver<ResponseT> implements StreamObserver<ResponseT> {
//
// private boolean terminalEventReceived;
//
// private final MonoSink<ResponseT> sink;
//
// public UnaryStreamObserver(MonoSink<ResponseT> sink) {
// this.sink = sink;
// }
//
// @Override
// public void onNext(ResponseT response) {
// this.terminalEventReceived = true;
// this.sink.success(response);
// }
//
// @Override
// public void onError(Throwable throwable) {
// this.terminalEventReceived = true;
// this.sink.error(SpannerExceptionUtil.createR2dbcException(throwable));
// }
//
// @Override
// public void onCompleted() {
// if (!this.terminalEventReceived) {
// this.sink.error(
// new RuntimeException("Unary gRPC call completed without yielding a value or an error"));
// }
// }
// }
// }
// Path: cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/it/SessionCleanupUtils.java
import io.grpc.stub.StreamObserver;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.ServiceOptions;
import com.google.cloud.spanner.r2dbc.util.ObservableReactiveUtil;
import com.google.protobuf.Empty;
import com.google.spanner.v1.DatabaseName;
import com.google.spanner.v1.DeleteSessionRequest;
import com.google.spanner.v1.ListSessionsRequest;
import com.google.spanner.v1.ListSessionsResponse;
import com.google.spanner.v1.Session;
import com.google.spanner.v1.SpannerGrpc;
import com.google.spanner.v1.SpannerGrpc.SpannerStub;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.auth.MoreCallCredentials;
* Exceptions:
* - you are running in a CI environment and there are other tests running.
* - you want to verify session state after a test. In this case, make another method
* verifying the correct number of sessions (exactly 1, greater than 10 etc.)
*/
static void verifyNoLeftoverSessions() throws Exception {
List<String> activeSessions = getSessionNames();
if (activeSessions.isEmpty()) {
System.out.println("No leftover sessions, yay!");
} else {
throw new IllegalStateException("Expected no sessions, but found " + activeSessions.size());
}
}
private static List<String> getSessionNames() throws Exception {
String databaseName = DatabaseName.format(ServiceOptions.getDefaultProjectId(),
DatabaseProperties.INSTANCE, DatabaseProperties.DATABASE);
String nextPageToken = null;
List<String> sessionNames = new ArrayList<>();
do {
ListSessionsRequest.Builder requestBuilder =
ListSessionsRequest.newBuilder().setDatabase(databaseName);
if (nextPageToken != null) {
requestBuilder.setPageToken(nextPageToken);
}
ListSessionsResponse listSessionsResponse = | ObservableReactiveUtil.<ListSessionsResponse>unaryCall( |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/LongIntegerConverter.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/ConversionFailureException.java
// public class ConversionFailureException extends R2dbcNonTransientException {
//
// public ConversionFailureException(String message) {
// super(message);
// }
// }
| import com.google.cloud.spanner.r2dbc.ConversionFailureException; | /*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class LongIntegerConverter implements SpannerClientLibrariesConverter<Integer> {
@Override
public boolean canConvert(Class<?> inputClass, Class<?> resultClass) {
return inputClass == Long.class && resultClass == Integer.class;
}
@Override
public Integer convert(Object input) {
if (!canConvert(input.getClass(), Integer.class)) { | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/ConversionFailureException.java
// public class ConversionFailureException extends R2dbcNonTransientException {
//
// public ConversionFailureException(String message) {
// super(message);
// }
// }
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/LongIntegerConverter.java
import com.google.cloud.spanner.r2dbc.ConversionFailureException;
/*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class LongIntegerConverter implements SpannerClientLibrariesConverter<Integer> {
@Override
public boolean canConvert(Class<?> inputClass, Class<?> resultClass) {
return inputClass == Long.class && resultClass == Integer.class;
}
@Override
public Integer convert(Object input) {
if (!canConvert(input.getClass(), Integer.class)) { | throw new ConversionFailureException( |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/AbstractSpannerClientLibraryStatement.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/TypedNull.java
// public class TypedNull {
//
// private final Class<?> type;
//
// public TypedNull(Class<?> type) {
// this.type = type;
// }
//
// public Class<?> getType() {
// return this.type;
// }
// }
| import com.google.cloud.spanner.r2dbc.statement.TypedNull;
import com.google.spanner.v1.ExecuteSqlRequest.QueryOptions;
import io.r2dbc.spi.Result;
import io.r2dbc.spi.Statement;
import java.util.ArrayList;
import java.util.List;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono; | return executeMultiple(this.statements);
}
return executeSingle(this.currentStatementBuilder.build());
}
protected abstract Mono<SpannerClientLibraryResult> executeSingle(
com.google.cloud.spanner.Statement statement);
protected abstract Flux<SpannerClientLibraryResult> executeMultiple(
List<com.google.cloud.spanner.Statement> statements);
@Override
public Statement bind(int index, Object value) {
throw new UnsupportedOperationException();
}
@Override
public Statement bind(String name, Object value) {
ClientLibraryBinder.bind(this.currentStatementBuilder, name, value);
this.startedBinding = true;
return this;
}
@Override
public Statement bindNull(int index, Class<?> type) {
throw new UnsupportedOperationException();
}
@Override
public Statement bindNull(String name, Class<?> type) { | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/TypedNull.java
// public class TypedNull {
//
// private final Class<?> type;
//
// public TypedNull(Class<?> type) {
// this.type = type;
// }
//
// public Class<?> getType() {
// return this.type;
// }
// }
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/AbstractSpannerClientLibraryStatement.java
import com.google.cloud.spanner.r2dbc.statement.TypedNull;
import com.google.spanner.v1.ExecuteSqlRequest.QueryOptions;
import io.r2dbc.spi.Result;
import io.r2dbc.spi.Statement;
import java.util.ArrayList;
import java.util.List;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
return executeMultiple(this.statements);
}
return executeSingle(this.currentStatementBuilder.build());
}
protected abstract Mono<SpannerClientLibraryResult> executeSingle(
com.google.cloud.spanner.Statement statement);
protected abstract Flux<SpannerClientLibraryResult> executeMultiple(
List<com.google.cloud.spanner.Statement> statements);
@Override
public Statement bind(int index, Object value) {
throw new UnsupportedOperationException();
}
@Override
public Statement bind(String name, Object value) {
ClientLibraryBinder.bind(this.currentStatementBuilder, name, value);
this.startedBinding = true;
return this;
}
@Override
public Statement bindNull(int index, Class<?> type) {
throw new UnsupportedOperationException();
}
@Override
public Statement bindNull(String name, Class<?> type) { | ClientLibraryBinder.bind(this.currentStatementBuilder, name, new TypedNull(type)); |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/SpannerClientLibraryConverters.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/ConversionFailureException.java
// public class ConversionFailureException extends R2dbcNonTransientException {
//
// public ConversionFailureException(String message) {
// super(message);
// }
// }
| import com.google.cloud.spanner.r2dbc.ConversionFailureException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional; | /*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class SpannerClientLibraryConverters {
private static final List<SpannerClientLibrariesConverter<?>> converters = createConverters();
private static List<SpannerClientLibrariesConverter<?>> createConverters() {
ArrayList<SpannerClientLibrariesConverter<?>> converters = new ArrayList<>();
converters.add(new LongIntegerConverter());
converters.add(new StringToJsonConverter());
return converters;
}
static <T> T convert(Object value, Class<T> type) {
Optional<SpannerClientLibrariesConverter<?>> converter = converters.stream()
.filter(candidate -> candidate.canConvert(value.getClass(), type))
.findFirst();
if (!converter.isPresent()) { | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/ConversionFailureException.java
// public class ConversionFailureException extends R2dbcNonTransientException {
//
// public ConversionFailureException(String message) {
// super(message);
// }
// }
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/SpannerClientLibraryConverters.java
import com.google.cloud.spanner.r2dbc.ConversionFailureException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class SpannerClientLibraryConverters {
private static final List<SpannerClientLibrariesConverter<?>> converters = createConverters();
private static List<SpannerClientLibrariesConverter<?>> createConverters() {
ArrayList<SpannerClientLibrariesConverter<?>> converters = new ArrayList<>();
converters.add(new LongIntegerConverter());
converters.add(new StringToJsonConverter());
return converters;
}
static <T> T convert(Object value, Class<T> type) {
Optional<SpannerClientLibrariesConverter<?>> converter = converters.stream()
.filter(candidate -> candidate.canConvert(value.getClass(), type))
.findFirst();
if (!converter.isPresent()) { | throw new ConversionFailureException( |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-spring-data-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/springdata/it/SpannerR2dbcDialectIntegrationTest.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
//
// Path: cloud-spanner-spring-data-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/springdata/it/entities/President.java
// public class President {
//
// @Column("NAME")
// private String name;
//
// @Column("START_YEAR")
// private long startYear;
//
// public President(String name, long startYear) {
// this.name = name;
// this.startYear = startYear;
// }
//
// public String getName() {
// return this.name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public long getStartYear() {
// return this.startYear;
// }
//
// public void setStartYear(long startYear) {
// this.startYear = startYear;
// }
//
// @Override
// public String toString() {
// return "President{"
// + "name='"
// + this.name + '\''
// + ", startYear="
// + this.startYear + '}';
// }
// }
| import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.ServiceOptions;
import com.google.cloud.spanner.r2dbc.springdata.it.entities.President;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.data.relational.core.query.Query;
import org.springframework.r2dbc.core.DatabaseClient;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier; | /*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.springdata.it;
/**
* Integration tests for the Spring Data R2DBC dialect.
*
* <p>By default, the test is configured to run tests in the `reactivetest` instance on the
* `testdb` database. This can be configured by overriding the `spanner.instance` and
* `spanner.database` system properties.
*/
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class SpannerR2dbcDialectIntegrationTest {
private static final Logger logger =
LoggerFactory.getLogger(SpannerR2dbcDialectIntegrationTest.class);
private static final String DRIVER_NAME = "spanner";
private static final String TEST_INSTANCE =
System.getProperty("spanner.instance", "reactivetest");
private static final String TEST_DATABASE =
System.getProperty("spanner.database", "testdb");
private static final ConnectionFactory connectionFactory =
ConnectionFactories.get(ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), ServiceOptions.getDefaultProjectId())
.option(DRIVER, DRIVER_NAME) | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
//
// Path: cloud-spanner-spring-data-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/springdata/it/entities/President.java
// public class President {
//
// @Column("NAME")
// private String name;
//
// @Column("START_YEAR")
// private long startYear;
//
// public President(String name, long startYear) {
// this.name = name;
// this.startYear = startYear;
// }
//
// public String getName() {
// return this.name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public long getStartYear() {
// return this.startYear;
// }
//
// public void setStartYear(long startYear) {
// this.startYear = startYear;
// }
//
// @Override
// public String toString() {
// return "President{"
// + "name='"
// + this.name + '\''
// + ", startYear="
// + this.startYear + '}';
// }
// }
// Path: cloud-spanner-spring-data-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/springdata/it/SpannerR2dbcDialectIntegrationTest.java
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.ServiceOptions;
import com.google.cloud.spanner.r2dbc.springdata.it.entities.President;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.data.relational.core.query.Query;
import org.springframework.r2dbc.core.DatabaseClient;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
/*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.springdata.it;
/**
* Integration tests for the Spring Data R2DBC dialect.
*
* <p>By default, the test is configured to run tests in the `reactivetest` instance on the
* `testdb` database. This can be configured by overriding the `spanner.instance` and
* `spanner.database` system properties.
*/
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class SpannerR2dbcDialectIntegrationTest {
private static final Logger logger =
LoggerFactory.getLogger(SpannerR2dbcDialectIntegrationTest.class);
private static final String DRIVER_NAME = "spanner";
private static final String TEST_INSTANCE =
System.getProperty("spanner.instance", "reactivetest");
private static final String TEST_DATABASE =
System.getProperty("spanner.database", "testdb");
private static final ConnectionFactory connectionFactory =
ConnectionFactories.get(ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), ServiceOptions.getDefaultProjectId())
.option(DRIVER, DRIVER_NAME) | .option(INSTANCE, TEST_INSTANCE) |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-spring-data-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/springdata/it/SpannerR2dbcDialectIntegrationTest.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
//
// Path: cloud-spanner-spring-data-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/springdata/it/entities/President.java
// public class President {
//
// @Column("NAME")
// private String name;
//
// @Column("START_YEAR")
// private long startYear;
//
// public President(String name, long startYear) {
// this.name = name;
// this.startYear = startYear;
// }
//
// public String getName() {
// return this.name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public long getStartYear() {
// return this.startYear;
// }
//
// public void setStartYear(long startYear) {
// this.startYear = startYear;
// }
//
// @Override
// public String toString() {
// return "President{"
// + "name='"
// + this.name + '\''
// + ", startYear="
// + this.startYear + '}';
// }
// }
| import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.ServiceOptions;
import com.google.cloud.spanner.r2dbc.springdata.it.entities.President;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.data.relational.core.query.Query;
import org.springframework.r2dbc.core.DatabaseClient;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier; | this.databaseClient = this.r2dbcEntityTemplate.getDatabaseClient();
if (SpannerTestUtils.tableExists(connection, "PRESIDENT")) {
this.databaseClient.sql("DROP TABLE PRESIDENT")
.fetch()
.rowsUpdated()
.block();
}
this.databaseClient.sql(
"CREATE TABLE PRESIDENT ("
+ " NAME STRING(256) NOT NULL,"
+ " START_YEAR INT64 NOT NULL"
+ ") PRIMARY KEY (NAME)")
.fetch()
.rowsUpdated()
.block();
}
@AfterEach
public void cleanupTableAfterTest() {
this.databaseClient
.sql("DELETE FROM PRESIDENT where NAME is not null")
.fetch()
.rowsUpdated()
.block();
}
@Test
void testReadWrite() { | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
//
// Path: cloud-spanner-spring-data-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/springdata/it/entities/President.java
// public class President {
//
// @Column("NAME")
// private String name;
//
// @Column("START_YEAR")
// private long startYear;
//
// public President(String name, long startYear) {
// this.name = name;
// this.startYear = startYear;
// }
//
// public String getName() {
// return this.name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public long getStartYear() {
// return this.startYear;
// }
//
// public void setStartYear(long startYear) {
// this.startYear = startYear;
// }
//
// @Override
// public String toString() {
// return "President{"
// + "name='"
// + this.name + '\''
// + ", startYear="
// + this.startYear + '}';
// }
// }
// Path: cloud-spanner-spring-data-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/springdata/it/SpannerR2dbcDialectIntegrationTest.java
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.ServiceOptions;
import com.google.cloud.spanner.r2dbc.springdata.it.entities.President;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.data.relational.core.query.Query;
import org.springframework.r2dbc.core.DatabaseClient;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
this.databaseClient = this.r2dbcEntityTemplate.getDatabaseClient();
if (SpannerTestUtils.tableExists(connection, "PRESIDENT")) {
this.databaseClient.sql("DROP TABLE PRESIDENT")
.fetch()
.rowsUpdated()
.block();
}
this.databaseClient.sql(
"CREATE TABLE PRESIDENT ("
+ " NAME STRING(256) NOT NULL,"
+ " START_YEAR INT64 NOT NULL"
+ ") PRIMARY KEY (NAME)")
.fetch()
.rowsUpdated()
.block();
}
@AfterEach
public void cleanupTableAfterTest() {
this.databaseClient
.sql("DELETE FROM PRESIDENT where NAME is not null")
.fetch()
.rowsUpdated()
.block();
}
@Test
void testReadWrite() { | insertPresident(new President("Bill Clinton", 1992)); |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/SpannerBatch.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/StatementParser.java
// public class StatementParser {
//
// private static com.google.cloud.spanner.connection.AbstractStatementParser clientLibraryParser =
// com.google.cloud.spanner.connection.AbstractStatementParser.getInstance(
// Dialect.GOOGLE_STANDARD_SQL);
//
// private StatementParser() {
// // Prevent instantiation.
// }
//
// /**
// * Returns the statement type of a given SQL string.
// *
// * @param sql the input SQL string.
// *
// * @return the type of statement of the SQL string.
// */
// public static StatementType getStatementType(String sql) {
// if (clientLibraryParser.isQuery(sql)) {
// return StatementType.SELECT;
// } else if (clientLibraryParser.isDdlStatement(sql)) {
// return StatementType.DDL;
// } else if (clientLibraryParser.isUpdateStatement(sql)) {
// return StatementType.DML;
// } else {
// return StatementType.UNKNOWN;
// }
// }
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/StatementType.java
// public enum StatementType {
// SELECT,
// DDL,
// DML,
// UNKNOWN;
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/util/Assert.java
// public class Assert {
//
// private Assert() {
// // Prevent instantiation.
// }
//
// /**
// * Checks that a specified object reference is not {@code null} and throws a customized
// * {@link IllegalArgumentException} if it is.
// *
// * @param t the object reference to check for nullity
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// * @param <T> the type of object reference
// *
// * @return the original object {@code t}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static <T> T requireNonNull(@Nullable T t, String message) {
// if (t == null) {
// throw new IllegalArgumentException(message);
// }
//
// return t;
// }
//
// /**
// * Checks that a specified object reference is not {@code null} or an empty string, and throws a
// * customized {@link IllegalArgumentException} if it is.
// *
// * @param s string to check
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// *
// * @return the original string {@code s}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static ByteString requireNonEmpty(@Nullable ByteString s, String message) {
// if (s == null || s.isEmpty()) {
// throw new IllegalArgumentException(message);
// }
//
// return s;
// }
//
// /**
// * Checks that a specified object reference is not {@code null} or an empty string, and throws a
// * customized {@link IllegalArgumentException} if it is.
// *
// * @param s string to check
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// *
// * @return the original string {@code s}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static String requireNonEmpty(@Nullable String s, String message) {
// if (s == null || s.isEmpty()) {
// throw new IllegalArgumentException(message);
// }
//
// return s;
// }
//
// }
| import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.r2dbc.statement.StatementParser;
import com.google.cloud.spanner.r2dbc.statement.StatementType;
import com.google.cloud.spanner.r2dbc.util.Assert;
import io.r2dbc.spi.Batch;
import io.r2dbc.spi.Result;
import java.util.ArrayList;
import java.util.List;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono; | /*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class SpannerBatch implements Batch {
private DatabaseClientReactiveAdapter clientLibraryAdapter;
private List<Statement> statements = new ArrayList<>();
SpannerBatch(DatabaseClientReactiveAdapter clientLibraryAdapter) {
this.clientLibraryAdapter = clientLibraryAdapter;
}
@Override
public Batch add(String sql) { | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/StatementParser.java
// public class StatementParser {
//
// private static com.google.cloud.spanner.connection.AbstractStatementParser clientLibraryParser =
// com.google.cloud.spanner.connection.AbstractStatementParser.getInstance(
// Dialect.GOOGLE_STANDARD_SQL);
//
// private StatementParser() {
// // Prevent instantiation.
// }
//
// /**
// * Returns the statement type of a given SQL string.
// *
// * @param sql the input SQL string.
// *
// * @return the type of statement of the SQL string.
// */
// public static StatementType getStatementType(String sql) {
// if (clientLibraryParser.isQuery(sql)) {
// return StatementType.SELECT;
// } else if (clientLibraryParser.isDdlStatement(sql)) {
// return StatementType.DDL;
// } else if (clientLibraryParser.isUpdateStatement(sql)) {
// return StatementType.DML;
// } else {
// return StatementType.UNKNOWN;
// }
// }
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/StatementType.java
// public enum StatementType {
// SELECT,
// DDL,
// DML,
// UNKNOWN;
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/util/Assert.java
// public class Assert {
//
// private Assert() {
// // Prevent instantiation.
// }
//
// /**
// * Checks that a specified object reference is not {@code null} and throws a customized
// * {@link IllegalArgumentException} if it is.
// *
// * @param t the object reference to check for nullity
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// * @param <T> the type of object reference
// *
// * @return the original object {@code t}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static <T> T requireNonNull(@Nullable T t, String message) {
// if (t == null) {
// throw new IllegalArgumentException(message);
// }
//
// return t;
// }
//
// /**
// * Checks that a specified object reference is not {@code null} or an empty string, and throws a
// * customized {@link IllegalArgumentException} if it is.
// *
// * @param s string to check
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// *
// * @return the original string {@code s}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static ByteString requireNonEmpty(@Nullable ByteString s, String message) {
// if (s == null || s.isEmpty()) {
// throw new IllegalArgumentException(message);
// }
//
// return s;
// }
//
// /**
// * Checks that a specified object reference is not {@code null} or an empty string, and throws a
// * customized {@link IllegalArgumentException} if it is.
// *
// * @param s string to check
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// *
// * @return the original string {@code s}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static String requireNonEmpty(@Nullable String s, String message) {
// if (s == null || s.isEmpty()) {
// throw new IllegalArgumentException(message);
// }
//
// return s;
// }
//
// }
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/SpannerBatch.java
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.r2dbc.statement.StatementParser;
import com.google.cloud.spanner.r2dbc.statement.StatementType;
import com.google.cloud.spanner.r2dbc.util.Assert;
import io.r2dbc.spi.Batch;
import io.r2dbc.spi.Result;
import java.util.ArrayList;
import java.util.List;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono;
/*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class SpannerBatch implements Batch {
private DatabaseClientReactiveAdapter clientLibraryAdapter;
private List<Statement> statements = new ArrayList<>();
SpannerBatch(DatabaseClientReactiveAdapter clientLibraryAdapter) {
this.clientLibraryAdapter = clientLibraryAdapter;
}
@Override
public Batch add(String sql) { | Assert.requireNonNull(sql, "SQL must not be null."); |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/SpannerBatch.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/StatementParser.java
// public class StatementParser {
//
// private static com.google.cloud.spanner.connection.AbstractStatementParser clientLibraryParser =
// com.google.cloud.spanner.connection.AbstractStatementParser.getInstance(
// Dialect.GOOGLE_STANDARD_SQL);
//
// private StatementParser() {
// // Prevent instantiation.
// }
//
// /**
// * Returns the statement type of a given SQL string.
// *
// * @param sql the input SQL string.
// *
// * @return the type of statement of the SQL string.
// */
// public static StatementType getStatementType(String sql) {
// if (clientLibraryParser.isQuery(sql)) {
// return StatementType.SELECT;
// } else if (clientLibraryParser.isDdlStatement(sql)) {
// return StatementType.DDL;
// } else if (clientLibraryParser.isUpdateStatement(sql)) {
// return StatementType.DML;
// } else {
// return StatementType.UNKNOWN;
// }
// }
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/StatementType.java
// public enum StatementType {
// SELECT,
// DDL,
// DML,
// UNKNOWN;
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/util/Assert.java
// public class Assert {
//
// private Assert() {
// // Prevent instantiation.
// }
//
// /**
// * Checks that a specified object reference is not {@code null} and throws a customized
// * {@link IllegalArgumentException} if it is.
// *
// * @param t the object reference to check for nullity
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// * @param <T> the type of object reference
// *
// * @return the original object {@code t}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static <T> T requireNonNull(@Nullable T t, String message) {
// if (t == null) {
// throw new IllegalArgumentException(message);
// }
//
// return t;
// }
//
// /**
// * Checks that a specified object reference is not {@code null} or an empty string, and throws a
// * customized {@link IllegalArgumentException} if it is.
// *
// * @param s string to check
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// *
// * @return the original string {@code s}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static ByteString requireNonEmpty(@Nullable ByteString s, String message) {
// if (s == null || s.isEmpty()) {
// throw new IllegalArgumentException(message);
// }
//
// return s;
// }
//
// /**
// * Checks that a specified object reference is not {@code null} or an empty string, and throws a
// * customized {@link IllegalArgumentException} if it is.
// *
// * @param s string to check
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// *
// * @return the original string {@code s}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static String requireNonEmpty(@Nullable String s, String message) {
// if (s == null || s.isEmpty()) {
// throw new IllegalArgumentException(message);
// }
//
// return s;
// }
//
// }
| import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.r2dbc.statement.StatementParser;
import com.google.cloud.spanner.r2dbc.statement.StatementType;
import com.google.cloud.spanner.r2dbc.util.Assert;
import io.r2dbc.spi.Batch;
import io.r2dbc.spi.Result;
import java.util.ArrayList;
import java.util.List;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono; | /*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class SpannerBatch implements Batch {
private DatabaseClientReactiveAdapter clientLibraryAdapter;
private List<Statement> statements = new ArrayList<>();
SpannerBatch(DatabaseClientReactiveAdapter clientLibraryAdapter) {
this.clientLibraryAdapter = clientLibraryAdapter;
}
@Override
public Batch add(String sql) {
Assert.requireNonNull(sql, "SQL must not be null."); | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/StatementParser.java
// public class StatementParser {
//
// private static com.google.cloud.spanner.connection.AbstractStatementParser clientLibraryParser =
// com.google.cloud.spanner.connection.AbstractStatementParser.getInstance(
// Dialect.GOOGLE_STANDARD_SQL);
//
// private StatementParser() {
// // Prevent instantiation.
// }
//
// /**
// * Returns the statement type of a given SQL string.
// *
// * @param sql the input SQL string.
// *
// * @return the type of statement of the SQL string.
// */
// public static StatementType getStatementType(String sql) {
// if (clientLibraryParser.isQuery(sql)) {
// return StatementType.SELECT;
// } else if (clientLibraryParser.isDdlStatement(sql)) {
// return StatementType.DDL;
// } else if (clientLibraryParser.isUpdateStatement(sql)) {
// return StatementType.DML;
// } else {
// return StatementType.UNKNOWN;
// }
// }
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/StatementType.java
// public enum StatementType {
// SELECT,
// DDL,
// DML,
// UNKNOWN;
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/util/Assert.java
// public class Assert {
//
// private Assert() {
// // Prevent instantiation.
// }
//
// /**
// * Checks that a specified object reference is not {@code null} and throws a customized
// * {@link IllegalArgumentException} if it is.
// *
// * @param t the object reference to check for nullity
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// * @param <T> the type of object reference
// *
// * @return the original object {@code t}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static <T> T requireNonNull(@Nullable T t, String message) {
// if (t == null) {
// throw new IllegalArgumentException(message);
// }
//
// return t;
// }
//
// /**
// * Checks that a specified object reference is not {@code null} or an empty string, and throws a
// * customized {@link IllegalArgumentException} if it is.
// *
// * @param s string to check
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// *
// * @return the original string {@code s}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static ByteString requireNonEmpty(@Nullable ByteString s, String message) {
// if (s == null || s.isEmpty()) {
// throw new IllegalArgumentException(message);
// }
//
// return s;
// }
//
// /**
// * Checks that a specified object reference is not {@code null} or an empty string, and throws a
// * customized {@link IllegalArgumentException} if it is.
// *
// * @param s string to check
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// *
// * @return the original string {@code s}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static String requireNonEmpty(@Nullable String s, String message) {
// if (s == null || s.isEmpty()) {
// throw new IllegalArgumentException(message);
// }
//
// return s;
// }
//
// }
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/SpannerBatch.java
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.r2dbc.statement.StatementParser;
import com.google.cloud.spanner.r2dbc.statement.StatementType;
import com.google.cloud.spanner.r2dbc.util.Assert;
import io.r2dbc.spi.Batch;
import io.r2dbc.spi.Result;
import java.util.ArrayList;
import java.util.List;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono;
/*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class SpannerBatch implements Batch {
private DatabaseClientReactiveAdapter clientLibraryAdapter;
private List<Statement> statements = new ArrayList<>();
SpannerBatch(DatabaseClientReactiveAdapter clientLibraryAdapter) {
this.clientLibraryAdapter = clientLibraryAdapter;
}
@Override
public Batch add(String sql) {
Assert.requireNonNull(sql, "SQL must not be null."); | if (StatementParser.getStatementType(sql) != StatementType.DML) { |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/SpannerBatch.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/StatementParser.java
// public class StatementParser {
//
// private static com.google.cloud.spanner.connection.AbstractStatementParser clientLibraryParser =
// com.google.cloud.spanner.connection.AbstractStatementParser.getInstance(
// Dialect.GOOGLE_STANDARD_SQL);
//
// private StatementParser() {
// // Prevent instantiation.
// }
//
// /**
// * Returns the statement type of a given SQL string.
// *
// * @param sql the input SQL string.
// *
// * @return the type of statement of the SQL string.
// */
// public static StatementType getStatementType(String sql) {
// if (clientLibraryParser.isQuery(sql)) {
// return StatementType.SELECT;
// } else if (clientLibraryParser.isDdlStatement(sql)) {
// return StatementType.DDL;
// } else if (clientLibraryParser.isUpdateStatement(sql)) {
// return StatementType.DML;
// } else {
// return StatementType.UNKNOWN;
// }
// }
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/StatementType.java
// public enum StatementType {
// SELECT,
// DDL,
// DML,
// UNKNOWN;
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/util/Assert.java
// public class Assert {
//
// private Assert() {
// // Prevent instantiation.
// }
//
// /**
// * Checks that a specified object reference is not {@code null} and throws a customized
// * {@link IllegalArgumentException} if it is.
// *
// * @param t the object reference to check for nullity
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// * @param <T> the type of object reference
// *
// * @return the original object {@code t}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static <T> T requireNonNull(@Nullable T t, String message) {
// if (t == null) {
// throw new IllegalArgumentException(message);
// }
//
// return t;
// }
//
// /**
// * Checks that a specified object reference is not {@code null} or an empty string, and throws a
// * customized {@link IllegalArgumentException} if it is.
// *
// * @param s string to check
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// *
// * @return the original string {@code s}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static ByteString requireNonEmpty(@Nullable ByteString s, String message) {
// if (s == null || s.isEmpty()) {
// throw new IllegalArgumentException(message);
// }
//
// return s;
// }
//
// /**
// * Checks that a specified object reference is not {@code null} or an empty string, and throws a
// * customized {@link IllegalArgumentException} if it is.
// *
// * @param s string to check
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// *
// * @return the original string {@code s}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static String requireNonEmpty(@Nullable String s, String message) {
// if (s == null || s.isEmpty()) {
// throw new IllegalArgumentException(message);
// }
//
// return s;
// }
//
// }
| import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.r2dbc.statement.StatementParser;
import com.google.cloud.spanner.r2dbc.statement.StatementType;
import com.google.cloud.spanner.r2dbc.util.Assert;
import io.r2dbc.spi.Batch;
import io.r2dbc.spi.Result;
import java.util.ArrayList;
import java.util.List;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono; | /*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class SpannerBatch implements Batch {
private DatabaseClientReactiveAdapter clientLibraryAdapter;
private List<Statement> statements = new ArrayList<>();
SpannerBatch(DatabaseClientReactiveAdapter clientLibraryAdapter) {
this.clientLibraryAdapter = clientLibraryAdapter;
}
@Override
public Batch add(String sql) {
Assert.requireNonNull(sql, "SQL must not be null."); | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/StatementParser.java
// public class StatementParser {
//
// private static com.google.cloud.spanner.connection.AbstractStatementParser clientLibraryParser =
// com.google.cloud.spanner.connection.AbstractStatementParser.getInstance(
// Dialect.GOOGLE_STANDARD_SQL);
//
// private StatementParser() {
// // Prevent instantiation.
// }
//
// /**
// * Returns the statement type of a given SQL string.
// *
// * @param sql the input SQL string.
// *
// * @return the type of statement of the SQL string.
// */
// public static StatementType getStatementType(String sql) {
// if (clientLibraryParser.isQuery(sql)) {
// return StatementType.SELECT;
// } else if (clientLibraryParser.isDdlStatement(sql)) {
// return StatementType.DDL;
// } else if (clientLibraryParser.isUpdateStatement(sql)) {
// return StatementType.DML;
// } else {
// return StatementType.UNKNOWN;
// }
// }
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/StatementType.java
// public enum StatementType {
// SELECT,
// DDL,
// DML,
// UNKNOWN;
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/util/Assert.java
// public class Assert {
//
// private Assert() {
// // Prevent instantiation.
// }
//
// /**
// * Checks that a specified object reference is not {@code null} and throws a customized
// * {@link IllegalArgumentException} if it is.
// *
// * @param t the object reference to check for nullity
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// * @param <T> the type of object reference
// *
// * @return the original object {@code t}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static <T> T requireNonNull(@Nullable T t, String message) {
// if (t == null) {
// throw new IllegalArgumentException(message);
// }
//
// return t;
// }
//
// /**
// * Checks that a specified object reference is not {@code null} or an empty string, and throws a
// * customized {@link IllegalArgumentException} if it is.
// *
// * @param s string to check
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// *
// * @return the original string {@code s}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static ByteString requireNonEmpty(@Nullable ByteString s, String message) {
// if (s == null || s.isEmpty()) {
// throw new IllegalArgumentException(message);
// }
//
// return s;
// }
//
// /**
// * Checks that a specified object reference is not {@code null} or an empty string, and throws a
// * customized {@link IllegalArgumentException} if it is.
// *
// * @param s string to check
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// *
// * @return the original string {@code s}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static String requireNonEmpty(@Nullable String s, String message) {
// if (s == null || s.isEmpty()) {
// throw new IllegalArgumentException(message);
// }
//
// return s;
// }
//
// }
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/SpannerBatch.java
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.r2dbc.statement.StatementParser;
import com.google.cloud.spanner.r2dbc.statement.StatementType;
import com.google.cloud.spanner.r2dbc.util.Assert;
import io.r2dbc.spi.Batch;
import io.r2dbc.spi.Result;
import java.util.ArrayList;
import java.util.List;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono;
/*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class SpannerBatch implements Batch {
private DatabaseClientReactiveAdapter clientLibraryAdapter;
private List<Statement> statements = new ArrayList<>();
SpannerBatch(DatabaseClientReactiveAdapter clientLibraryAdapter) {
this.clientLibraryAdapter = clientLibraryAdapter;
}
@Override
public Batch add(String sql) {
Assert.requireNonNull(sql, "SQL must not be null."); | if (StatementParser.getStatementType(sql) != StatementType.DML) { |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/it/SpannerDmlReactiveStreamVerification.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
| import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.ServiceOptions;
import io.r2dbc.spi.Closeable;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import org.reactivestreams.Publisher;
import org.reactivestreams.tck.PublisherVerification;
import org.reactivestreams.tck.TestEnvironment; | /*
* Copyright 2021-2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.it;
class SpannerDmlReactiveStreamVerification extends
PublisherVerification<Integer> {
private static ConnectionFactory connectionFactory;
private static TestDatabaseHelper dbHelper;
@BeforeSuite
static void createConnectionFactory() {
connectionFactory = ConnectionFactories.get(
ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), ServiceOptions.getDefaultProjectId()) | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
// Path: cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/it/SpannerDmlReactiveStreamVerification.java
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.ServiceOptions;
import io.r2dbc.spi.Closeable;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import org.reactivestreams.Publisher;
import org.reactivestreams.tck.PublisherVerification;
import org.reactivestreams.tck.TestEnvironment;
/*
* Copyright 2021-2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.it;
class SpannerDmlReactiveStreamVerification extends
PublisherVerification<Integer> {
private static ConnectionFactory connectionFactory;
private static TestDatabaseHelper dbHelper;
@BeforeSuite
static void createConnectionFactory() {
connectionFactory = ConnectionFactories.get(
ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), ServiceOptions.getDefaultProjectId()) | .option(DRIVER, DRIVER_NAME) |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/it/SpannerDmlReactiveStreamVerification.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
| import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.ServiceOptions;
import io.r2dbc.spi.Closeable;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import org.reactivestreams.Publisher;
import org.reactivestreams.tck.PublisherVerification;
import org.reactivestreams.tck.TestEnvironment; | /*
* Copyright 2021-2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.it;
class SpannerDmlReactiveStreamVerification extends
PublisherVerification<Integer> {
private static ConnectionFactory connectionFactory;
private static TestDatabaseHelper dbHelper;
@BeforeSuite
static void createConnectionFactory() {
connectionFactory = ConnectionFactories.get(
ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), ServiceOptions.getDefaultProjectId())
.option(DRIVER, DRIVER_NAME) | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
// Path: cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/it/SpannerDmlReactiveStreamVerification.java
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.ServiceOptions;
import io.r2dbc.spi.Closeable;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import org.reactivestreams.Publisher;
import org.reactivestreams.tck.PublisherVerification;
import org.reactivestreams.tck.TestEnvironment;
/*
* Copyright 2021-2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.it;
class SpannerDmlReactiveStreamVerification extends
PublisherVerification<Integer> {
private static ConnectionFactory connectionFactory;
private static TestDatabaseHelper dbHelper;
@BeforeSuite
static void createConnectionFactory() {
connectionFactory = ConnectionFactories.get(
ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), ServiceOptions.getDefaultProjectId())
.option(DRIVER, DRIVER_NAME) | .option(INSTANCE, DatabaseProperties.INSTANCE) |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/it/SpannerSelectReactiveStreamVerification.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
| import org.reactivestreams.tck.TestEnvironment;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.ServiceOptions;
import io.r2dbc.spi.Closeable;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import io.r2dbc.spi.Row;
import org.reactivestreams.Publisher;
import org.reactivestreams.tck.PublisherVerification; | /*
* Copyright 2021-2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.it;
class SpannerSelectReactiveStreamVerification extends
PublisherVerification<Row> {
private static ConnectionFactory connectionFactory;
private static TestDatabaseHelper dbHelper;
@BeforeSuite
static void createConnectionFactory() {
connectionFactory = ConnectionFactories.get(
ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), ServiceOptions.getDefaultProjectId()) | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
// Path: cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/it/SpannerSelectReactiveStreamVerification.java
import org.reactivestreams.tck.TestEnvironment;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.ServiceOptions;
import io.r2dbc.spi.Closeable;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import io.r2dbc.spi.Row;
import org.reactivestreams.Publisher;
import org.reactivestreams.tck.PublisherVerification;
/*
* Copyright 2021-2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.it;
class SpannerSelectReactiveStreamVerification extends
PublisherVerification<Row> {
private static ConnectionFactory connectionFactory;
private static TestDatabaseHelper dbHelper;
@BeforeSuite
static void createConnectionFactory() {
connectionFactory = ConnectionFactories.get(
ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), ServiceOptions.getDefaultProjectId()) | .option(DRIVER, DRIVER_NAME) |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/it/SpannerSelectReactiveStreamVerification.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
| import org.reactivestreams.tck.TestEnvironment;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.ServiceOptions;
import io.r2dbc.spi.Closeable;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import io.r2dbc.spi.Row;
import org.reactivestreams.Publisher;
import org.reactivestreams.tck.PublisherVerification; | /*
* Copyright 2021-2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.it;
class SpannerSelectReactiveStreamVerification extends
PublisherVerification<Row> {
private static ConnectionFactory connectionFactory;
private static TestDatabaseHelper dbHelper;
@BeforeSuite
static void createConnectionFactory() {
connectionFactory = ConnectionFactories.get(
ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), ServiceOptions.getDefaultProjectId())
.option(DRIVER, DRIVER_NAME) | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
// Path: cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/it/SpannerSelectReactiveStreamVerification.java
import org.reactivestreams.tck.TestEnvironment;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.ServiceOptions;
import io.r2dbc.spi.Closeable;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import io.r2dbc.spi.Row;
import org.reactivestreams.Publisher;
import org.reactivestreams.tck.PublisherVerification;
/*
* Copyright 2021-2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.it;
class SpannerSelectReactiveStreamVerification extends
PublisherVerification<Row> {
private static ConnectionFactory connectionFactory;
private static TestDatabaseHelper dbHelper;
@BeforeSuite
static void createConnectionFactory() {
connectionFactory = ConnectionFactories.get(
ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), ServiceOptions.getDefaultProjectId())
.option(DRIVER, DRIVER_NAME) | .option(INSTANCE, DatabaseProperties.INSTANCE) |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/v2/ClientLibraryTypeBindersTest.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/BindingFailureException.java
// public class BindingFailureException extends R2dbcNonTransientException {
//
// public BindingFailureException(String message) {
// super(message);
// }
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/TypedNull.java
// public class TypedNull {
//
// private final Class<?> type;
//
// public TypedNull(Class<?> type) {
// this.type = type;
// }
//
// public Class<?> getType() {
// return this.type;
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.withPrecision;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import com.google.cloud.ByteArray;
import com.google.cloud.Date;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.Statement.Builder;
import com.google.cloud.spanner.Value;
import com.google.cloud.spanner.ValueBinder;
import com.google.cloud.spanner.r2dbc.BindingFailureException;
import com.google.cloud.spanner.r2dbc.statement.TypedNull;
import io.r2dbc.spi.Parameters;
import io.r2dbc.spi.R2dbcType;
import java.math.BigDecimal;
import java.util.Random;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito; | /*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class ClientLibraryTypeBindersTest {
ValueBinder valueBinder;
ValueBinder nullBinder;
Builder statementBuilder;
@BeforeEach
public void setUp() {
this.valueBinder = Mockito.mock(ValueBinder.class);
this.nullBinder = Mockito.mock(ValueBinder.class);
this.statementBuilder = Mockito.mock(Builder.class);
when(this.statementBuilder.bind("valueColumn")).thenReturn(this.valueBinder);
when(this.statementBuilder.bind("nullColumn")).thenReturn(this.nullBinder);
}
@Test
void unsupportedTypeThrowsException() {
Random rand = new Random();
assertThatThrownBy(() -> ClientLibraryBinder.bind(this.statementBuilder, "valueColumn", rand)) | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/BindingFailureException.java
// public class BindingFailureException extends R2dbcNonTransientException {
//
// public BindingFailureException(String message) {
// super(message);
// }
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/TypedNull.java
// public class TypedNull {
//
// private final Class<?> type;
//
// public TypedNull(Class<?> type) {
// this.type = type;
// }
//
// public Class<?> getType() {
// return this.type;
// }
// }
// Path: cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/v2/ClientLibraryTypeBindersTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.withPrecision;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import com.google.cloud.ByteArray;
import com.google.cloud.Date;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.Statement.Builder;
import com.google.cloud.spanner.Value;
import com.google.cloud.spanner.ValueBinder;
import com.google.cloud.spanner.r2dbc.BindingFailureException;
import com.google.cloud.spanner.r2dbc.statement.TypedNull;
import io.r2dbc.spi.Parameters;
import io.r2dbc.spi.R2dbcType;
import java.math.BigDecimal;
import java.util.Random;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
/*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class ClientLibraryTypeBindersTest {
ValueBinder valueBinder;
ValueBinder nullBinder;
Builder statementBuilder;
@BeforeEach
public void setUp() {
this.valueBinder = Mockito.mock(ValueBinder.class);
this.nullBinder = Mockito.mock(ValueBinder.class);
this.statementBuilder = Mockito.mock(Builder.class);
when(this.statementBuilder.bind("valueColumn")).thenReturn(this.valueBinder);
when(this.statementBuilder.bind("nullColumn")).thenReturn(this.nullBinder);
}
@Test
void unsupportedTypeThrowsException() {
Random rand = new Random();
assertThatThrownBy(() -> ClientLibraryBinder.bind(this.statementBuilder, "valueColumn", rand)) | .isInstanceOf(BindingFailureException.class) |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/v2/ClientLibraryTypeBindersTest.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/BindingFailureException.java
// public class BindingFailureException extends R2dbcNonTransientException {
//
// public BindingFailureException(String message) {
// super(message);
// }
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/TypedNull.java
// public class TypedNull {
//
// private final Class<?> type;
//
// public TypedNull(Class<?> type) {
// this.type = type;
// }
//
// public Class<?> getType() {
// return this.type;
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.withPrecision;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import com.google.cloud.ByteArray;
import com.google.cloud.Date;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.Statement.Builder;
import com.google.cloud.spanner.Value;
import com.google.cloud.spanner.ValueBinder;
import com.google.cloud.spanner.r2dbc.BindingFailureException;
import com.google.cloud.spanner.r2dbc.statement.TypedNull;
import io.r2dbc.spi.Parameters;
import io.r2dbc.spi.R2dbcType;
import java.math.BigDecimal;
import java.util.Random;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito; | /*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class ClientLibraryTypeBindersTest {
ValueBinder valueBinder;
ValueBinder nullBinder;
Builder statementBuilder;
@BeforeEach
public void setUp() {
this.valueBinder = Mockito.mock(ValueBinder.class);
this.nullBinder = Mockito.mock(ValueBinder.class);
this.statementBuilder = Mockito.mock(Builder.class);
when(this.statementBuilder.bind("valueColumn")).thenReturn(this.valueBinder);
when(this.statementBuilder.bind("nullColumn")).thenReturn(this.nullBinder);
}
@Test
void unsupportedTypeThrowsException() {
Random rand = new Random();
assertThatThrownBy(() -> ClientLibraryBinder.bind(this.statementBuilder, "valueColumn", rand))
.isInstanceOf(BindingFailureException.class)
.hasMessageContaining("Can't find a binder for type: class java.util.Random");
| // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/BindingFailureException.java
// public class BindingFailureException extends R2dbcNonTransientException {
//
// public BindingFailureException(String message) {
// super(message);
// }
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/TypedNull.java
// public class TypedNull {
//
// private final Class<?> type;
//
// public TypedNull(Class<?> type) {
// this.type = type;
// }
//
// public Class<?> getType() {
// return this.type;
// }
// }
// Path: cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/v2/ClientLibraryTypeBindersTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.withPrecision;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import com.google.cloud.ByteArray;
import com.google.cloud.Date;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.Statement.Builder;
import com.google.cloud.spanner.Value;
import com.google.cloud.spanner.ValueBinder;
import com.google.cloud.spanner.r2dbc.BindingFailureException;
import com.google.cloud.spanner.r2dbc.statement.TypedNull;
import io.r2dbc.spi.Parameters;
import io.r2dbc.spi.R2dbcType;
import java.math.BigDecimal;
import java.util.Random;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
/*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class ClientLibraryTypeBindersTest {
ValueBinder valueBinder;
ValueBinder nullBinder;
Builder statementBuilder;
@BeforeEach
public void setUp() {
this.valueBinder = Mockito.mock(ValueBinder.class);
this.nullBinder = Mockito.mock(ValueBinder.class);
this.statementBuilder = Mockito.mock(Builder.class);
when(this.statementBuilder.bind("valueColumn")).thenReturn(this.valueBinder);
when(this.statementBuilder.bind("nullColumn")).thenReturn(this.nullBinder);
}
@Test
void unsupportedTypeThrowsException() {
Random rand = new Random();
assertThatThrownBy(() -> ClientLibraryBinder.bind(this.statementBuilder, "valueColumn", rand))
.isInstanceOf(BindingFailureException.class)
.hasMessageContaining("Can't find a binder for type: class java.util.Random");
| TypedNull randNull = new TypedNull(Random.class); |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-spring-data-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/springdata/SpannerR2dbcDialectTest.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/JsonWrapper.java
// public class JsonWrapper {
// private String jsonString;
//
// public JsonWrapper(String jsonString) {
// this.jsonString = jsonString;
// }
//
// protected Value getJsonVal() {
// return Value.json(this.jsonString);
// }
//
// public static JsonWrapper of(String jsonString) {
// return new JsonWrapper(jsonString);
// }
//
// @Override
// public String toString() {
// return this.jsonString;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// JsonWrapper that = (JsonWrapper) o;
// return Objects.equal(this.jsonString, that.jsonString);
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(this.jsonString);
// }
// }
| import org.springframework.data.relational.core.sql.Table;
import org.springframework.r2dbc.core.binding.BindMarkers;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.cloud.spanner.r2dbc.v2.JsonWrapper;
import java.util.Collection;
import org.junit.jupiter.api.Test;
import org.springframework.data.mapping.model.SimpleTypeHolder;
import org.springframework.data.relational.core.dialect.LimitClause;
import org.springframework.data.relational.core.dialect.LockClause;
import org.springframework.data.relational.core.sql.LockMode;
import org.springframework.data.relational.core.sql.LockOptions;
import org.springframework.data.relational.core.sql.SQL;
import org.springframework.data.relational.core.sql.Select; |
@Test
void testBindMarkersFactory() {
SpannerR2dbcDialect dialect = new SpannerR2dbcDialect();
BindMarkers bindMarkers = dialect.getBindMarkersFactory().create();
assertThat(bindMarkers).isNotNull();
assertThat(bindMarkers.next().getPlaceholder()).isEqualTo("@val0");
assertThat(bindMarkers.next().getPlaceholder()).isEqualTo("@val1");
}
@Test
void lockStringAlwaysEmpty() {
SpannerR2dbcDialect dialect = new SpannerR2dbcDialect();
Table table = SQL.table("aTable");
Select sql = Select.builder().select(table.column("aColumn"))
.from(table)
.build();
LockOptions lockOptions = new LockOptions(LockMode.PESSIMISTIC_READ, sql.getFrom());
LockClause lock = dialect.lock();
assertNotNull(lock);
assertThat(lock.getLock(lockOptions)).isEmpty();
assertThat(lock.getClausePosition()).isSameAs(LockClause.Position.AFTER_FROM_TABLE);
}
@Test
void testSimpleType() {
SpannerR2dbcDialect dialect = new SpannerR2dbcDialect();
SimpleTypeHolder simpleTypeHolder = dialect.getSimpleTypeHolder(); | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/JsonWrapper.java
// public class JsonWrapper {
// private String jsonString;
//
// public JsonWrapper(String jsonString) {
// this.jsonString = jsonString;
// }
//
// protected Value getJsonVal() {
// return Value.json(this.jsonString);
// }
//
// public static JsonWrapper of(String jsonString) {
// return new JsonWrapper(jsonString);
// }
//
// @Override
// public String toString() {
// return this.jsonString;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// JsonWrapper that = (JsonWrapper) o;
// return Objects.equal(this.jsonString, that.jsonString);
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(this.jsonString);
// }
// }
// Path: cloud-spanner-spring-data-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/springdata/SpannerR2dbcDialectTest.java
import org.springframework.data.relational.core.sql.Table;
import org.springframework.r2dbc.core.binding.BindMarkers;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.cloud.spanner.r2dbc.v2.JsonWrapper;
import java.util.Collection;
import org.junit.jupiter.api.Test;
import org.springframework.data.mapping.model.SimpleTypeHolder;
import org.springframework.data.relational.core.dialect.LimitClause;
import org.springframework.data.relational.core.dialect.LockClause;
import org.springframework.data.relational.core.sql.LockMode;
import org.springframework.data.relational.core.sql.LockOptions;
import org.springframework.data.relational.core.sql.SQL;
import org.springframework.data.relational.core.sql.Select;
@Test
void testBindMarkersFactory() {
SpannerR2dbcDialect dialect = new SpannerR2dbcDialect();
BindMarkers bindMarkers = dialect.getBindMarkersFactory().create();
assertThat(bindMarkers).isNotNull();
assertThat(bindMarkers.next().getPlaceholder()).isEqualTo("@val0");
assertThat(bindMarkers.next().getPlaceholder()).isEqualTo("@val1");
}
@Test
void lockStringAlwaysEmpty() {
SpannerR2dbcDialect dialect = new SpannerR2dbcDialect();
Table table = SQL.table("aTable");
Select sql = Select.builder().select(table.column("aColumn"))
.from(table)
.build();
LockOptions lockOptions = new LockOptions(LockMode.PESSIMISTIC_READ, sql.getFrom());
LockClause lock = dialect.lock();
assertNotNull(lock);
assertThat(lock.getLock(lockOptions)).isEmpty();
assertThat(lock.getClausePosition()).isSameAs(LockClause.Position.AFTER_FROM_TABLE);
}
@Test
void testSimpleType() {
SpannerR2dbcDialect dialect = new SpannerR2dbcDialect();
SimpleTypeHolder simpleTypeHolder = dialect.getSimpleTypeHolder(); | assertThat(simpleTypeHolder.isSimpleType(JsonWrapper.class)).isTrue(); |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/v2/SpannerClientLibraryConvertersTest.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/ConversionFailureException.java
// public class ConversionFailureException extends R2dbcNonTransientException {
//
// public ConversionFailureException(String message) {
// super(message);
// }
// }
| import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import com.google.cloud.spanner.r2dbc.ConversionFailureException;
import org.junit.jupiter.api.Test; | /*
* Copyright 2021-2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class SpannerClientLibraryConvertersTest {
@Test
void convertTest() {
assertThat(
SpannerClientLibraryConverters.convert(
"{\"rating\":9,\"open\":true}", JsonWrapper.class))
.isInstanceOf(JsonWrapper.class)
.isEqualTo(JsonWrapper.of("{\"rating\":9,\"open\":true}"));
assertThatThrownBy(() -> SpannerClientLibraryConverters.convert(1234L, JsonWrapper.class)) | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/ConversionFailureException.java
// public class ConversionFailureException extends R2dbcNonTransientException {
//
// public ConversionFailureException(String message) {
// super(message);
// }
// }
// Path: cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/v2/SpannerClientLibraryConvertersTest.java
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import com.google.cloud.spanner.r2dbc.ConversionFailureException;
import org.junit.jupiter.api.Test;
/*
* Copyright 2021-2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class SpannerClientLibraryConvertersTest {
@Test
void convertTest() {
assertThat(
SpannerClientLibraryConverters.convert(
"{\"rating\":9,\"open\":true}", JsonWrapper.class))
.isInstanceOf(JsonWrapper.class)
.isEqualTo(JsonWrapper.of("{\"rating\":9,\"open\":true}"));
assertThatThrownBy(() -> SpannerClientLibraryConverters.convert(1234L, JsonWrapper.class)) | .isInstanceOf(ConversionFailureException.class) |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/v2/StringToJsonConverterTest.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/ConversionFailureException.java
// public class ConversionFailureException extends R2dbcNonTransientException {
//
// public ConversionFailureException(String message) {
// super(message);
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import com.google.cloud.spanner.r2dbc.ConversionFailureException;
import org.assertj.core.api.AssertionsForClassTypes;
import org.junit.jupiter.api.Test; | /*
* Copyright 2021-2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class StringToJsonConverterTest {
@Test
void canConvert() {
StringToJsonConverter converter = new StringToJsonConverter();
assertThat(converter.canConvert(Long.class, JsonWrapper.class)).isFalse();
assertThat(converter.canConvert(String.class, Long.class)).isFalse();
assertThat(converter.canConvert(String.class, JsonWrapper.class)).isTrue();
}
@Test
void convert() {
StringToJsonConverter converter = new StringToJsonConverter();
AssertionsForClassTypes.assertThat(
converter.convert(
"{\"rating\":9,\"open\":true}"))
.isInstanceOf(JsonWrapper.class)
.isEqualTo(JsonWrapper.of("{\"rating\":9,\"open\":true}"));
assertThatThrownBy(() -> converter.convert(1234L)) | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/ConversionFailureException.java
// public class ConversionFailureException extends R2dbcNonTransientException {
//
// public ConversionFailureException(String message) {
// super(message);
// }
// }
// Path: cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/v2/StringToJsonConverterTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import com.google.cloud.spanner.r2dbc.ConversionFailureException;
import org.assertj.core.api.AssertionsForClassTypes;
import org.junit.jupiter.api.Test;
/*
* Copyright 2021-2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class StringToJsonConverterTest {
@Test
void canConvert() {
StringToJsonConverter converter = new StringToJsonConverter();
assertThat(converter.canConvert(Long.class, JsonWrapper.class)).isFalse();
assertThat(converter.canConvert(String.class, Long.class)).isFalse();
assertThat(converter.canConvert(String.class, JsonWrapper.class)).isTrue();
}
@Test
void convert() {
StringToJsonConverter converter = new StringToJsonConverter();
AssertionsForClassTypes.assertThat(
converter.convert(
"{\"rating\":9,\"open\":true}"))
.isInstanceOf(JsonWrapper.class)
.isEqualTo(JsonWrapper.of("{\"rating\":9,\"open\":true}"));
assertThatThrownBy(() -> converter.convert(1234L)) | .isInstanceOf(ConversionFailureException.class) |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionConfiguration.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/util/Assert.java
// public class Assert {
//
// private Assert() {
// // Prevent instantiation.
// }
//
// /**
// * Checks that a specified object reference is not {@code null} and throws a customized
// * {@link IllegalArgumentException} if it is.
// *
// * @param t the object reference to check for nullity
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// * @param <T> the type of object reference
// *
// * @return the original object {@code t}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static <T> T requireNonNull(@Nullable T t, String message) {
// if (t == null) {
// throw new IllegalArgumentException(message);
// }
//
// return t;
// }
//
// /**
// * Checks that a specified object reference is not {@code null} or an empty string, and throws a
// * customized {@link IllegalArgumentException} if it is.
// *
// * @param s string to check
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// *
// * @return the original string {@code s}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static ByteString requireNonEmpty(@Nullable ByteString s, String message) {
// if (s == null || s.isEmpty()) {
// throw new IllegalArgumentException(message);
// }
//
// return s;
// }
//
// /**
// * Checks that a specified object reference is not {@code null} or an empty string, and throws a
// * customized {@link IllegalArgumentException} if it is.
// *
// * @param s string to check
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// *
// * @return the original string {@code s}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static String requireNonEmpty(@Nullable String s, String message) {
// if (s == null || s.isEmpty()) {
// throw new IllegalArgumentException(message);
// }
//
// return s;
// }
//
// }
| import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.OAuth2Credentials;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.r2dbc.util.Assert;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.R2dbcNonTransientResourceException;
import java.io.IOException;
import java.time.Duration;
import java.util.Collections;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | /*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc;
/**
* Configurable properties for Cloud Spanner.
*/
public class SpannerConnectionConfiguration {
public static final String FQDN_PATTERN_GENERATE =
"projects/%s/instances/%s/databases/%s";
/** Pattern used to validate that the user input database string is in the right format. */
public static final Pattern FQDN_PATTERN_PARSE = Pattern.compile(
"projects\\/([\\w\\-]+)\\/instances\\/([\\w\\-]+)\\/databases\\/([\\w\\-]+)$");
private static final String USER_AGENT_LIBRARY_NAME = "cloud-spanner-r2dbc";
private static final String PACKAGE_VERSION =
SpannerConnectionConfiguration.class.getPackage().getImplementationVersion();
private static final String USER_AGENT_KEY = "user-agent";
// TODO: check how to handle full URL (it gets parsed by SPI, we only get pieces)
private final String fullyQualifiedDbName;
private String projectId;
private String instanceName;
private String databaseName;
private final OAuth2Credentials credentials;
private int partialResultSetFetchSize;
private Duration ddlOperationTimeout;
private Duration ddlOperationPollInterval;
private boolean usePlainText;
private String optimizerVersion;
private boolean readonly;
private boolean autocommit;
/**
* Basic property initializing constructor.
*
* @param projectId GCP project that contains the database.
* @param instanceName instance to connect to
* @param databaseName database to connect to.
* @param credentials GCP credentials to authenticate service calls with.
*/
private SpannerConnectionConfiguration(
String projectId,
String instanceName,
String databaseName,
OAuth2Credentials credentials) {
| // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/util/Assert.java
// public class Assert {
//
// private Assert() {
// // Prevent instantiation.
// }
//
// /**
// * Checks that a specified object reference is not {@code null} and throws a customized
// * {@link IllegalArgumentException} if it is.
// *
// * @param t the object reference to check for nullity
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// * @param <T> the type of object reference
// *
// * @return the original object {@code t}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static <T> T requireNonNull(@Nullable T t, String message) {
// if (t == null) {
// throw new IllegalArgumentException(message);
// }
//
// return t;
// }
//
// /**
// * Checks that a specified object reference is not {@code null} or an empty string, and throws a
// * customized {@link IllegalArgumentException} if it is.
// *
// * @param s string to check
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// *
// * @return the original string {@code s}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static ByteString requireNonEmpty(@Nullable ByteString s, String message) {
// if (s == null || s.isEmpty()) {
// throw new IllegalArgumentException(message);
// }
//
// return s;
// }
//
// /**
// * Checks that a specified object reference is not {@code null} or an empty string, and throws a
// * customized {@link IllegalArgumentException} if it is.
// *
// * @param s string to check
// * @param message informative message to be used in the event that an
// * {@link IllegalArgumentException} is thrown
// *
// * @return the original string {@code s}
// *
// * @throws IllegalArgumentException if {@code o} is {@code null}
// */
// public static String requireNonEmpty(@Nullable String s, String message) {
// if (s == null || s.isEmpty()) {
// throw new IllegalArgumentException(message);
// }
//
// return s;
// }
//
// }
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionConfiguration.java
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.OAuth2Credentials;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.r2dbc.util.Assert;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.R2dbcNonTransientResourceException;
import java.io.IOException;
import java.time.Duration;
import java.util.Collections;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc;
/**
* Configurable properties for Cloud Spanner.
*/
public class SpannerConnectionConfiguration {
public static final String FQDN_PATTERN_GENERATE =
"projects/%s/instances/%s/databases/%s";
/** Pattern used to validate that the user input database string is in the right format. */
public static final Pattern FQDN_PATTERN_PARSE = Pattern.compile(
"projects\\/([\\w\\-]+)\\/instances\\/([\\w\\-]+)\\/databases\\/([\\w\\-]+)$");
private static final String USER_AGENT_LIBRARY_NAME = "cloud-spanner-r2dbc";
private static final String PACKAGE_VERSION =
SpannerConnectionConfiguration.class.getPackage().getImplementationVersion();
private static final String USER_AGENT_KEY = "user-agent";
// TODO: check how to handle full URL (it gets parsed by SPI, we only get pieces)
private final String fullyQualifiedDbName;
private String projectId;
private String instanceName;
private String databaseName;
private final OAuth2Credentials credentials;
private int partialResultSetFetchSize;
private Duration ddlOperationTimeout;
private Duration ddlOperationPollInterval;
private boolean usePlainText;
private String optimizerVersion;
private boolean readonly;
private boolean autocommit;
/**
* Basic property initializing constructor.
*
* @param projectId GCP project that contains the database.
* @param instanceName instance to connect to
* @param databaseName database to connect to.
* @param credentials GCP credentials to authenticate service calls with.
*/
private SpannerConnectionConfiguration(
String projectId,
String instanceName,
String databaseName,
OAuth2Credentials credentials) {
| Assert.requireNonNull(projectId, "projectId must not be null"); |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc-samples/cloud-spanner-spring-data-r2dbc-sample/src/main/java/com/example/SpringDataR2dbcApp.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
| import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import java.net.URI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories;
import org.springframework.r2dbc.core.DatabaseClient;
import org.springframework.util.Assert;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Hooks; | /*
* Copyright 2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example;
/**
* Driver application showing Cloud Spanner R2DBC use with Spring Data.
*/
@SpringBootApplication
@EnableR2dbcRepositories
public class SpringDataR2dbcApp {
private static final Logger LOGGER = LoggerFactory.getLogger(SpringDataR2dbcApp.class);
private static final String SPANNER_INSTANCE = System.getProperty("spanner.instance");
private static final String SPANNER_DATABASE = System.getProperty("spanner.database");
private static final String GCP_PROJECT = System.getProperty("gcp.project");
@Autowired
private DatabaseClient r2dbcClient;
public static void main(String[] args) {
Hooks.onOperatorDebug(); | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
// Path: cloud-spanner-r2dbc-samples/cloud-spanner-spring-data-r2dbc-sample/src/main/java/com/example/SpringDataR2dbcApp.java
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
import java.net.URI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories;
import org.springframework.r2dbc.core.DatabaseClient;
import org.springframework.util.Assert;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Hooks;
/*
* Copyright 2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example;
/**
* Driver application showing Cloud Spanner R2DBC use with Spring Data.
*/
@SpringBootApplication
@EnableR2dbcRepositories
public class SpringDataR2dbcApp {
private static final Logger LOGGER = LoggerFactory.getLogger(SpringDataR2dbcApp.class);
private static final String SPANNER_INSTANCE = System.getProperty("spanner.instance");
private static final String SPANNER_DATABASE = System.getProperty("spanner.database");
private static final String GCP_PROJECT = System.getProperty("gcp.project");
@Autowired
private DatabaseClient r2dbcClient;
public static void main(String[] args) {
Hooks.onOperatorDebug(); | Assert.notNull(INSTANCE, "Please provide spanner.instance property"); |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-spring-data-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/springdata/SpannerBindMarkerFactoryProvider.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryMetadata.java
// public class SpannerConnectionFactoryMetadata implements ConnectionFactoryMetadata {
//
// /**
// * The name of Cloud Spanner database product.
// */
// public static final String NAME = "Cloud Spanner";
//
// public static final SpannerConnectionFactoryMetadata INSTANCE
// = new SpannerConnectionFactoryMetadata();
//
// private SpannerConnectionFactoryMetadata() {
// }
//
// @Override
// public String getName() {
// return NAME;
// }
//
// }
| import com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryMetadata;
import io.r2dbc.spi.ConnectionFactory;
import org.springframework.r2dbc.core.binding.BindMarkersFactory;
import org.springframework.r2dbc.core.binding.BindMarkersFactoryResolver.BindMarkerFactoryProvider; | /*
* Copyright 2021-2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.springdata;
/**
* Provides the named bind marker strategy for Cloud Spanner.
*/
public class SpannerBindMarkerFactoryProvider implements BindMarkerFactoryProvider {
@Override
public BindMarkersFactory getBindMarkers(ConnectionFactory connectionFactory) { | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryMetadata.java
// public class SpannerConnectionFactoryMetadata implements ConnectionFactoryMetadata {
//
// /**
// * The name of Cloud Spanner database product.
// */
// public static final String NAME = "Cloud Spanner";
//
// public static final SpannerConnectionFactoryMetadata INSTANCE
// = new SpannerConnectionFactoryMetadata();
//
// private SpannerConnectionFactoryMetadata() {
// }
//
// @Override
// public String getName() {
// return NAME;
// }
//
// }
// Path: cloud-spanner-spring-data-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/springdata/SpannerBindMarkerFactoryProvider.java
import com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryMetadata;
import io.r2dbc.spi.ConnectionFactory;
import org.springframework.r2dbc.core.binding.BindMarkersFactory;
import org.springframework.r2dbc.core.binding.BindMarkersFactoryResolver.BindMarkerFactoryProvider;
/*
* Copyright 2021-2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.springdata;
/**
* Provides the named bind marker strategy for Cloud Spanner.
*/
public class SpannerBindMarkerFactoryProvider implements BindMarkerFactoryProvider {
@Override
public BindMarkersFactory getBindMarkers(ConnectionFactory connectionFactory) { | if (SpannerConnectionFactoryMetadata.INSTANCE.equals(connectionFactory.getMetadata())) { |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc-samples/cloud-spanner-spring-data-r2dbc-sample/src/main/java/com/example/CustomConfiguration.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/JsonWrapper.java
// public class JsonWrapper {
// private String jsonString;
//
// public JsonWrapper(String jsonString) {
// this.jsonString = jsonString;
// }
//
// protected Value getJsonVal() {
// return Value.json(this.jsonString);
// }
//
// public static JsonWrapper of(String jsonString) {
// return new JsonWrapper(jsonString);
// }
//
// @Override
// public String toString() {
// return this.jsonString;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// JsonWrapper that = (JsonWrapper) o;
// return Objects.equal(this.jsonString, that.jsonString);
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(this.jsonString);
// }
// }
| import java.util.ArrayList;
import java.util.List;
import com.google.cloud.spanner.r2dbc.v2.JsonWrapper;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import io.r2dbc.spi.ConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.convert.ReadingConverter;
import org.springframework.data.convert.WritingConverter;
import org.springframework.data.r2dbc.config.AbstractR2dbcConfiguration;
import org.springframework.data.r2dbc.convert.R2dbcCustomConversions;
import org.springframework.stereotype.Component; | /*
* Copyright 2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example;
@Configuration
public class CustomConfiguration extends AbstractR2dbcConfiguration {
@Autowired
ApplicationContext applicationContext;
@Override
public ConnectionFactory connectionFactory() {
return null;
}
@Bean
@Override
public R2dbcCustomConversions r2dbcCustomConversions() {
List<Converter<?, ?>> converters = new ArrayList<>();
converters.add(this.applicationContext.getBean(JsonToReviewsConverter.class));
converters.add(this.applicationContext.getBean(ReviewsToJsonConverter.class));
return new R2dbcCustomConversions(getStoreConversions(), converters);
}
@Component
@ReadingConverter | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/JsonWrapper.java
// public class JsonWrapper {
// private String jsonString;
//
// public JsonWrapper(String jsonString) {
// this.jsonString = jsonString;
// }
//
// protected Value getJsonVal() {
// return Value.json(this.jsonString);
// }
//
// public static JsonWrapper of(String jsonString) {
// return new JsonWrapper(jsonString);
// }
//
// @Override
// public String toString() {
// return this.jsonString;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// JsonWrapper that = (JsonWrapper) o;
// return Objects.equal(this.jsonString, that.jsonString);
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(this.jsonString);
// }
// }
// Path: cloud-spanner-r2dbc-samples/cloud-spanner-spring-data-r2dbc-sample/src/main/java/com/example/CustomConfiguration.java
import java.util.ArrayList;
import java.util.List;
import com.google.cloud.spanner.r2dbc.v2.JsonWrapper;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import io.r2dbc.spi.ConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.convert.ReadingConverter;
import org.springframework.data.convert.WritingConverter;
import org.springframework.data.r2dbc.config.AbstractR2dbcConfiguration;
import org.springframework.data.r2dbc.convert.R2dbcCustomConversions;
import org.springframework.stereotype.Component;
/*
* Copyright 2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example;
@Configuration
public class CustomConfiguration extends AbstractR2dbcConfiguration {
@Autowired
ApplicationContext applicationContext;
@Override
public ConnectionFactory connectionFactory() {
return null;
}
@Bean
@Override
public R2dbcCustomConversions r2dbcCustomConversions() {
List<Converter<?, ?>> converters = new ArrayList<>();
converters.add(this.applicationContext.getBean(JsonToReviewsConverter.class));
converters.add(this.applicationContext.getBean(ReviewsToJsonConverter.class));
return new R2dbcCustomConversions(getStoreConversions(), converters);
}
@Component
@ReadingConverter | public class JsonToReviewsConverter implements Converter<JsonWrapper, Review> { |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/SpannerClientLibraryConnection.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/api/SpannerConnection.java
// public interface SpannerConnection {
// /**
// * Allows starting a readonly Cloud Spanner transaction with given staleness settings.
// *
// * @param timestampBound staleness settings
// *
// * @return {@link Mono} signaling readonly transaction is ready for use
// */
// Mono<Void> beginReadonlyTransaction(TimestampBound timestampBound);
//
// /**
// * Allows starting a readonly Cloud Spanner transaction with strong consistency.
// *
// * @return {@link Mono} signaling readonly transaction is ready for use
// */
// Mono<Void> beginReadonlyTransaction();
//
// boolean isInReadonlyTransaction();
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/StatementParser.java
// public class StatementParser {
//
// private static com.google.cloud.spanner.connection.AbstractStatementParser clientLibraryParser =
// com.google.cloud.spanner.connection.AbstractStatementParser.getInstance(
// Dialect.GOOGLE_STANDARD_SQL);
//
// private StatementParser() {
// // Prevent instantiation.
// }
//
// /**
// * Returns the statement type of a given SQL string.
// *
// * @param sql the input SQL string.
// *
// * @return the type of statement of the SQL string.
// */
// public static StatementType getStatementType(String sql) {
// if (clientLibraryParser.isQuery(sql)) {
// return StatementType.SELECT;
// } else if (clientLibraryParser.isDdlStatement(sql)) {
// return StatementType.DDL;
// } else if (clientLibraryParser.isUpdateStatement(sql)) {
// return StatementType.DML;
// } else {
// return StatementType.UNKNOWN;
// }
// }
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/StatementType.java
// public enum StatementType {
// SELECT,
// DDL,
// DML,
// UNKNOWN;
// }
| import com.google.cloud.spanner.TimestampBound;
import com.google.cloud.spanner.r2dbc.api.SpannerConnection;
import com.google.cloud.spanner.r2dbc.statement.StatementParser;
import com.google.cloud.spanner.r2dbc.statement.StatementType;
import io.r2dbc.spi.Batch;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionMetadata;
import io.r2dbc.spi.IsolationLevel;
import io.r2dbc.spi.Statement;
import io.r2dbc.spi.TransactionDefinition;
import io.r2dbc.spi.ValidationDepth;
import java.time.Duration;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono; | @Override
public Mono<Void> beginReadonlyTransaction(TimestampBound timestampBound) {
return this.clientLibraryAdapter.beginReadonlyTransaction(timestampBound);
}
@Override
public Mono<Void> beginReadonlyTransaction() {
return this.clientLibraryAdapter.beginReadonlyTransaction(TimestampBound.strong());
}
@Override
public Publisher<Void> commitTransaction() {
return this.clientLibraryAdapter.commitTransaction();
}
@Override
public Batch createBatch() {
return new SpannerBatch(this.clientLibraryAdapter);
}
@Override
public Publisher<Void> createSavepoint(String name) {
throw new UnsupportedOperationException();
}
@Override
public Statement createStatement(String query) {
if (query == null) {
throw new IllegalArgumentException("Invalid null query.");
} | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/api/SpannerConnection.java
// public interface SpannerConnection {
// /**
// * Allows starting a readonly Cloud Spanner transaction with given staleness settings.
// *
// * @param timestampBound staleness settings
// *
// * @return {@link Mono} signaling readonly transaction is ready for use
// */
// Mono<Void> beginReadonlyTransaction(TimestampBound timestampBound);
//
// /**
// * Allows starting a readonly Cloud Spanner transaction with strong consistency.
// *
// * @return {@link Mono} signaling readonly transaction is ready for use
// */
// Mono<Void> beginReadonlyTransaction();
//
// boolean isInReadonlyTransaction();
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/StatementParser.java
// public class StatementParser {
//
// private static com.google.cloud.spanner.connection.AbstractStatementParser clientLibraryParser =
// com.google.cloud.spanner.connection.AbstractStatementParser.getInstance(
// Dialect.GOOGLE_STANDARD_SQL);
//
// private StatementParser() {
// // Prevent instantiation.
// }
//
// /**
// * Returns the statement type of a given SQL string.
// *
// * @param sql the input SQL string.
// *
// * @return the type of statement of the SQL string.
// */
// public static StatementType getStatementType(String sql) {
// if (clientLibraryParser.isQuery(sql)) {
// return StatementType.SELECT;
// } else if (clientLibraryParser.isDdlStatement(sql)) {
// return StatementType.DDL;
// } else if (clientLibraryParser.isUpdateStatement(sql)) {
// return StatementType.DML;
// } else {
// return StatementType.UNKNOWN;
// }
// }
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/StatementType.java
// public enum StatementType {
// SELECT,
// DDL,
// DML,
// UNKNOWN;
// }
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/SpannerClientLibraryConnection.java
import com.google.cloud.spanner.TimestampBound;
import com.google.cloud.spanner.r2dbc.api.SpannerConnection;
import com.google.cloud.spanner.r2dbc.statement.StatementParser;
import com.google.cloud.spanner.r2dbc.statement.StatementType;
import io.r2dbc.spi.Batch;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionMetadata;
import io.r2dbc.spi.IsolationLevel;
import io.r2dbc.spi.Statement;
import io.r2dbc.spi.TransactionDefinition;
import io.r2dbc.spi.ValidationDepth;
import java.time.Duration;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono;
@Override
public Mono<Void> beginReadonlyTransaction(TimestampBound timestampBound) {
return this.clientLibraryAdapter.beginReadonlyTransaction(timestampBound);
}
@Override
public Mono<Void> beginReadonlyTransaction() {
return this.clientLibraryAdapter.beginReadonlyTransaction(TimestampBound.strong());
}
@Override
public Publisher<Void> commitTransaction() {
return this.clientLibraryAdapter.commitTransaction();
}
@Override
public Batch createBatch() {
return new SpannerBatch(this.clientLibraryAdapter);
}
@Override
public Publisher<Void> createSavepoint(String name) {
throw new UnsupportedOperationException();
}
@Override
public Statement createStatement(String query) {
if (query == null) {
throw new IllegalArgumentException("Invalid null query.");
} | StatementType type = StatementParser.getStatementType(query); |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/SpannerClientLibraryConnection.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/api/SpannerConnection.java
// public interface SpannerConnection {
// /**
// * Allows starting a readonly Cloud Spanner transaction with given staleness settings.
// *
// * @param timestampBound staleness settings
// *
// * @return {@link Mono} signaling readonly transaction is ready for use
// */
// Mono<Void> beginReadonlyTransaction(TimestampBound timestampBound);
//
// /**
// * Allows starting a readonly Cloud Spanner transaction with strong consistency.
// *
// * @return {@link Mono} signaling readonly transaction is ready for use
// */
// Mono<Void> beginReadonlyTransaction();
//
// boolean isInReadonlyTransaction();
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/StatementParser.java
// public class StatementParser {
//
// private static com.google.cloud.spanner.connection.AbstractStatementParser clientLibraryParser =
// com.google.cloud.spanner.connection.AbstractStatementParser.getInstance(
// Dialect.GOOGLE_STANDARD_SQL);
//
// private StatementParser() {
// // Prevent instantiation.
// }
//
// /**
// * Returns the statement type of a given SQL string.
// *
// * @param sql the input SQL string.
// *
// * @return the type of statement of the SQL string.
// */
// public static StatementType getStatementType(String sql) {
// if (clientLibraryParser.isQuery(sql)) {
// return StatementType.SELECT;
// } else if (clientLibraryParser.isDdlStatement(sql)) {
// return StatementType.DDL;
// } else if (clientLibraryParser.isUpdateStatement(sql)) {
// return StatementType.DML;
// } else {
// return StatementType.UNKNOWN;
// }
// }
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/StatementType.java
// public enum StatementType {
// SELECT,
// DDL,
// DML,
// UNKNOWN;
// }
| import com.google.cloud.spanner.TimestampBound;
import com.google.cloud.spanner.r2dbc.api.SpannerConnection;
import com.google.cloud.spanner.r2dbc.statement.StatementParser;
import com.google.cloud.spanner.r2dbc.statement.StatementType;
import io.r2dbc.spi.Batch;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionMetadata;
import io.r2dbc.spi.IsolationLevel;
import io.r2dbc.spi.Statement;
import io.r2dbc.spi.TransactionDefinition;
import io.r2dbc.spi.ValidationDepth;
import java.time.Duration;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono; | @Override
public Mono<Void> beginReadonlyTransaction(TimestampBound timestampBound) {
return this.clientLibraryAdapter.beginReadonlyTransaction(timestampBound);
}
@Override
public Mono<Void> beginReadonlyTransaction() {
return this.clientLibraryAdapter.beginReadonlyTransaction(TimestampBound.strong());
}
@Override
public Publisher<Void> commitTransaction() {
return this.clientLibraryAdapter.commitTransaction();
}
@Override
public Batch createBatch() {
return new SpannerBatch(this.clientLibraryAdapter);
}
@Override
public Publisher<Void> createSavepoint(String name) {
throw new UnsupportedOperationException();
}
@Override
public Statement createStatement(String query) {
if (query == null) {
throw new IllegalArgumentException("Invalid null query.");
} | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/api/SpannerConnection.java
// public interface SpannerConnection {
// /**
// * Allows starting a readonly Cloud Spanner transaction with given staleness settings.
// *
// * @param timestampBound staleness settings
// *
// * @return {@link Mono} signaling readonly transaction is ready for use
// */
// Mono<Void> beginReadonlyTransaction(TimestampBound timestampBound);
//
// /**
// * Allows starting a readonly Cloud Spanner transaction with strong consistency.
// *
// * @return {@link Mono} signaling readonly transaction is ready for use
// */
// Mono<Void> beginReadonlyTransaction();
//
// boolean isInReadonlyTransaction();
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/StatementParser.java
// public class StatementParser {
//
// private static com.google.cloud.spanner.connection.AbstractStatementParser clientLibraryParser =
// com.google.cloud.spanner.connection.AbstractStatementParser.getInstance(
// Dialect.GOOGLE_STANDARD_SQL);
//
// private StatementParser() {
// // Prevent instantiation.
// }
//
// /**
// * Returns the statement type of a given SQL string.
// *
// * @param sql the input SQL string.
// *
// * @return the type of statement of the SQL string.
// */
// public static StatementType getStatementType(String sql) {
// if (clientLibraryParser.isQuery(sql)) {
// return StatementType.SELECT;
// } else if (clientLibraryParser.isDdlStatement(sql)) {
// return StatementType.DDL;
// } else if (clientLibraryParser.isUpdateStatement(sql)) {
// return StatementType.DML;
// } else {
// return StatementType.UNKNOWN;
// }
// }
// }
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/statement/StatementType.java
// public enum StatementType {
// SELECT,
// DDL,
// DML,
// UNKNOWN;
// }
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/SpannerClientLibraryConnection.java
import com.google.cloud.spanner.TimestampBound;
import com.google.cloud.spanner.r2dbc.api.SpannerConnection;
import com.google.cloud.spanner.r2dbc.statement.StatementParser;
import com.google.cloud.spanner.r2dbc.statement.StatementType;
import io.r2dbc.spi.Batch;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionMetadata;
import io.r2dbc.spi.IsolationLevel;
import io.r2dbc.spi.Statement;
import io.r2dbc.spi.TransactionDefinition;
import io.r2dbc.spi.ValidationDepth;
import java.time.Duration;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono;
@Override
public Mono<Void> beginReadonlyTransaction(TimestampBound timestampBound) {
return this.clientLibraryAdapter.beginReadonlyTransaction(timestampBound);
}
@Override
public Mono<Void> beginReadonlyTransaction() {
return this.clientLibraryAdapter.beginReadonlyTransaction(TimestampBound.strong());
}
@Override
public Publisher<Void> commitTransaction() {
return this.clientLibraryAdapter.commitTransaction();
}
@Override
public Batch createBatch() {
return new SpannerBatch(this.clientLibraryAdapter);
}
@Override
public Publisher<Void> createSavepoint(String name) {
throw new UnsupportedOperationException();
}
@Override
public Statement createStatement(String query) {
if (query == null) {
throw new IllegalArgumentException("Invalid null query.");
} | StatementType type = StatementParser.getStatementType(query); |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/DatabaseClientTransactionManager.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/DatabaseClientReactiveAdapter.java
// public static final Executor REACTOR_EXECUTOR =
// runnable -> Schedulers.parallel().schedule(runnable);
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/TransactionInProgressException.java
// public class TransactionInProgressException extends R2dbcNonTransientException {
//
// public static final String MSG_READONLY =
// "Cannot begin a new transaction because a readonly transaction is already in progress.";
// public static final String MSG_READWRITE =
// "Cannot begin a new transaction because a read/write transaction is already in progress.";
//
// public TransactionInProgressException(boolean isReadwrite) {
// super(isReadwrite ? MSG_READWRITE : MSG_READONLY);
// }
//
// }
| import java.util.function.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.cloud.spanner.r2dbc.v2.DatabaseClientReactiveAdapter.REACTOR_EXECUTOR;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutures;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.AsyncTransactionManager;
import com.google.cloud.spanner.AsyncTransactionManager.AsyncTransactionStep;
import com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture;
import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.ReadContext;
import com.google.cloud.spanner.ReadOnlyTransaction;
import com.google.cloud.spanner.TimestampBound;
import com.google.cloud.spanner.TransactionContext;
import com.google.cloud.spanner.r2dbc.TransactionInProgressException; | /*
* Copyright 2020-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
/**
* Helper class encapsulating read/write and readonly transaction management for client library
* based interaction with Cloud Spanner.
* Partitioned DML is out of scope for transaction handling, as they are not atomic.
*/
class DatabaseClientTransactionManager {
private static final Logger LOGGER =
LoggerFactory.getLogger(DatabaseClientTransactionManager.class);
private final DatabaseClient dbClient;
private AsyncTransactionManager transactionManager;
private TransactionContextFuture txnContextFuture;
private ReadOnlyTransaction readOnlyTransaction;
private AsyncTransactionStep<?, ? extends Object> lastStep;
public DatabaseClientTransactionManager(DatabaseClient dbClient) {
this.dbClient = dbClient;
}
boolean isInReadWriteTransaction() {
return this.txnContextFuture != null;
}
boolean isInReadonlyTransaction() {
return this.readOnlyTransaction != null;
}
boolean isInTransaction() {
return isInReadWriteTransaction() || isInReadonlyTransaction();
}
/**
* Starts a Cloud Spanner Read/Write transaction.
*
* @return chainable {@link TransactionContextFuture} for the current transaction.
*/
TransactionContextFuture beginTransaction() {
if (this.isInTransaction()) { | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/DatabaseClientReactiveAdapter.java
// public static final Executor REACTOR_EXECUTOR =
// runnable -> Schedulers.parallel().schedule(runnable);
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/TransactionInProgressException.java
// public class TransactionInProgressException extends R2dbcNonTransientException {
//
// public static final String MSG_READONLY =
// "Cannot begin a new transaction because a readonly transaction is already in progress.";
// public static final String MSG_READWRITE =
// "Cannot begin a new transaction because a read/write transaction is already in progress.";
//
// public TransactionInProgressException(boolean isReadwrite) {
// super(isReadwrite ? MSG_READWRITE : MSG_READONLY);
// }
//
// }
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/DatabaseClientTransactionManager.java
import java.util.function.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.cloud.spanner.r2dbc.v2.DatabaseClientReactiveAdapter.REACTOR_EXECUTOR;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutures;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.AsyncTransactionManager;
import com.google.cloud.spanner.AsyncTransactionManager.AsyncTransactionStep;
import com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture;
import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.ReadContext;
import com.google.cloud.spanner.ReadOnlyTransaction;
import com.google.cloud.spanner.TimestampBound;
import com.google.cloud.spanner.TransactionContext;
import com.google.cloud.spanner.r2dbc.TransactionInProgressException;
/*
* Copyright 2020-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
/**
* Helper class encapsulating read/write and readonly transaction management for client library
* based interaction with Cloud Spanner.
* Partitioned DML is out of scope for transaction handling, as they are not atomic.
*/
class DatabaseClientTransactionManager {
private static final Logger LOGGER =
LoggerFactory.getLogger(DatabaseClientTransactionManager.class);
private final DatabaseClient dbClient;
private AsyncTransactionManager transactionManager;
private TransactionContextFuture txnContextFuture;
private ReadOnlyTransaction readOnlyTransaction;
private AsyncTransactionStep<?, ? extends Object> lastStep;
public DatabaseClientTransactionManager(DatabaseClient dbClient) {
this.dbClient = dbClient;
}
boolean isInReadWriteTransaction() {
return this.txnContextFuture != null;
}
boolean isInReadonlyTransaction() {
return this.readOnlyTransaction != null;
}
boolean isInTransaction() {
return isInReadWriteTransaction() || isInReadonlyTransaction();
}
/**
* Starts a Cloud Spanner Read/Write transaction.
*
* @return chainable {@link TransactionContextFuture} for the current transaction.
*/
TransactionContextFuture beginTransaction() {
if (this.isInTransaction()) { | throw new TransactionInProgressException(this.isInReadWriteTransaction()); |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/DatabaseClientTransactionManager.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/DatabaseClientReactiveAdapter.java
// public static final Executor REACTOR_EXECUTOR =
// runnable -> Schedulers.parallel().schedule(runnable);
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/TransactionInProgressException.java
// public class TransactionInProgressException extends R2dbcNonTransientException {
//
// public static final String MSG_READONLY =
// "Cannot begin a new transaction because a readonly transaction is already in progress.";
// public static final String MSG_READWRITE =
// "Cannot begin a new transaction because a read/write transaction is already in progress.";
//
// public TransactionInProgressException(boolean isReadwrite) {
// super(isReadwrite ? MSG_READWRITE : MSG_READONLY);
// }
//
// }
| import java.util.function.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.cloud.spanner.r2dbc.v2.DatabaseClientReactiveAdapter.REACTOR_EXECUTOR;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutures;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.AsyncTransactionManager;
import com.google.cloud.spanner.AsyncTransactionManager.AsyncTransactionStep;
import com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture;
import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.ReadContext;
import com.google.cloud.spanner.ReadOnlyTransaction;
import com.google.cloud.spanner.TimestampBound;
import com.google.cloud.spanner.TransactionContext;
import com.google.cloud.spanner.r2dbc.TransactionInProgressException; | */
ApiFuture<Void> rollbackTransaction() {
if (isInReadWriteTransaction()) {
if (this.lastStep == null) {
LOGGER.warn("Read/Write transaction rolling back without any statements.");
}
return this.transactionManager.rollbackAsync();
}
LOGGER.warn("Rollback called outside of an active read/write transaction.");
return ApiFutures.immediateFuture(null);
}
/**
* Runs provided operation, managing the client library transactional future chaining.
*
* @param operation a function executing either streaming SQL or DML.
* The function accepts ReadContext for SELECT queries, and TransactionContext for DML.
* @param <T> Type of object wrapped by the {@link ApiFuture} returned by the operation
*
* @return {@link ApiFuture} result of the provided operation
*/
<T> ApiFuture<T> runInTransaction(Function<? super TransactionContext, ApiFuture<T>> operation) {
// The first statement in a transaction has no input, hence Void input type.
// The subsequent statements take the previous statements' return (affected row count)
// as input.
AsyncTransactionStep<? extends Object, T> updateStatementFuture =
this.lastStep == null
? this.txnContextFuture.then( | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/DatabaseClientReactiveAdapter.java
// public static final Executor REACTOR_EXECUTOR =
// runnable -> Schedulers.parallel().schedule(runnable);
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/TransactionInProgressException.java
// public class TransactionInProgressException extends R2dbcNonTransientException {
//
// public static final String MSG_READONLY =
// "Cannot begin a new transaction because a readonly transaction is already in progress.";
// public static final String MSG_READWRITE =
// "Cannot begin a new transaction because a read/write transaction is already in progress.";
//
// public TransactionInProgressException(boolean isReadwrite) {
// super(isReadwrite ? MSG_READWRITE : MSG_READONLY);
// }
//
// }
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/DatabaseClientTransactionManager.java
import java.util.function.Function;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.cloud.spanner.r2dbc.v2.DatabaseClientReactiveAdapter.REACTOR_EXECUTOR;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutures;
import com.google.cloud.Timestamp;
import com.google.cloud.spanner.AsyncTransactionManager;
import com.google.cloud.spanner.AsyncTransactionManager.AsyncTransactionStep;
import com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture;
import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.ReadContext;
import com.google.cloud.spanner.ReadOnlyTransaction;
import com.google.cloud.spanner.TimestampBound;
import com.google.cloud.spanner.TransactionContext;
import com.google.cloud.spanner.r2dbc.TransactionInProgressException;
*/
ApiFuture<Void> rollbackTransaction() {
if (isInReadWriteTransaction()) {
if (this.lastStep == null) {
LOGGER.warn("Read/Write transaction rolling back without any statements.");
}
return this.transactionManager.rollbackAsync();
}
LOGGER.warn("Rollback called outside of an active read/write transaction.");
return ApiFutures.immediateFuture(null);
}
/**
* Runs provided operation, managing the client library transactional future chaining.
*
* @param operation a function executing either streaming SQL or DML.
* The function accepts ReadContext for SELECT queries, and TransactionContext for DML.
* @param <T> Type of object wrapped by the {@link ApiFuture} returned by the operation
*
* @return {@link ApiFuture} result of the provided operation
*/
<T> ApiFuture<T> runInTransaction(Function<? super TransactionContext, ApiFuture<T>> operation) {
// The first statement in a transaction has no input, hence Void input type.
// The subsequent statements take the previous statements' return (affected row count)
// as input.
AsyncTransactionStep<? extends Object, T> updateStatementFuture =
this.lastStep == null
? this.txnContextFuture.then( | (ctx, unusedVoid) -> operation.apply(ctx), REACTOR_EXECUTOR) |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/it/ClientLibraryDdlIntegrationTest.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
| import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.ServiceOptions;
import io.r2dbc.spi.Closeable;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import io.r2dbc.spi.Result;
import java.util.Random;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Hooks;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier; | /*
* Copyright 2021-2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.it;
class ClientLibraryDdlIntegrationTest {
private static final ConnectionFactory connectionFactory =
ConnectionFactories.get(
ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), ServiceOptions.getDefaultProjectId()) | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
// Path: cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/it/ClientLibraryDdlIntegrationTest.java
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.ServiceOptions;
import io.r2dbc.spi.Closeable;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import io.r2dbc.spi.Result;
import java.util.Random;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Hooks;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
/*
* Copyright 2021-2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.it;
class ClientLibraryDdlIntegrationTest {
private static final ConnectionFactory connectionFactory =
ConnectionFactories.get(
ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), ServiceOptions.getDefaultProjectId()) | .option(DRIVER, DRIVER_NAME) |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/it/ClientLibraryDdlIntegrationTest.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
| import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.ServiceOptions;
import io.r2dbc.spi.Closeable;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import io.r2dbc.spi.Result;
import java.util.Random;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Hooks;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier; | /*
* Copyright 2021-2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.it;
class ClientLibraryDdlIntegrationTest {
private static final ConnectionFactory connectionFactory =
ConnectionFactories.get(
ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), ServiceOptions.getDefaultProjectId())
.option(DRIVER, DRIVER_NAME) | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
// Path: cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/it/ClientLibraryDdlIntegrationTest.java
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.ServiceOptions;
import io.r2dbc.spi.Closeable;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import io.r2dbc.spi.Result;
import java.util.Random;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Hooks;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
/*
* Copyright 2021-2021 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.it;
class ClientLibraryDdlIntegrationTest {
private static final ConnectionFactory connectionFactory =
ConnectionFactories.get(
ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), ServiceOptions.getDefaultProjectId())
.option(DRIVER, DRIVER_NAME) | .option(INSTANCE, DatabaseProperties.INSTANCE) |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/it/TestDatabaseHelper.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
| import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.ServiceOptions;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | public void addTestData(String title, int category) {
int suffix = Math.abs(this.random.nextInt());
Mono.from(
this.connection
.createStatement(INSERT_DATA_QUERY)
.bind("uuid", "autoinserted-" + suffix)
.bind("title", title)
.bind("category", category)
.execute())
.flatMapMany(rs -> rs.getRowsUpdated())
.blockLast();
}
public void clearTestData() {
Mono.from(
this.connection.createStatement("DELETE FROM BOOKS WHERE true").execute())
.flatMap(rs -> Mono.from(rs.getRowsUpdated()))
.block();
}
public void close() {
Mono.from(this.connection.close()).block();
}
public static void main(String[] args) {
ConnectionFactory cf =
ConnectionFactories.get(
ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), ServiceOptions.getDefaultProjectId()) | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
// Path: cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/it/TestDatabaseHelper.java
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.ServiceOptions;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public void addTestData(String title, int category) {
int suffix = Math.abs(this.random.nextInt());
Mono.from(
this.connection
.createStatement(INSERT_DATA_QUERY)
.bind("uuid", "autoinserted-" + suffix)
.bind("title", title)
.bind("category", category)
.execute())
.flatMapMany(rs -> rs.getRowsUpdated())
.blockLast();
}
public void clearTestData() {
Mono.from(
this.connection.createStatement("DELETE FROM BOOKS WHERE true").execute())
.flatMap(rs -> Mono.from(rs.getRowsUpdated()))
.block();
}
public void close() {
Mono.from(this.connection.close()).block();
}
public static void main(String[] args) {
ConnectionFactory cf =
ConnectionFactories.get(
ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), ServiceOptions.getDefaultProjectId()) | .option(DRIVER, DRIVER_NAME) |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/it/TestDatabaseHelper.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
| import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.ServiceOptions;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | int suffix = Math.abs(this.random.nextInt());
Mono.from(
this.connection
.createStatement(INSERT_DATA_QUERY)
.bind("uuid", "autoinserted-" + suffix)
.bind("title", title)
.bind("category", category)
.execute())
.flatMapMany(rs -> rs.getRowsUpdated())
.blockLast();
}
public void clearTestData() {
Mono.from(
this.connection.createStatement("DELETE FROM BOOKS WHERE true").execute())
.flatMap(rs -> Mono.from(rs.getRowsUpdated()))
.block();
}
public void close() {
Mono.from(this.connection.close()).block();
}
public static void main(String[] args) {
ConnectionFactory cf =
ConnectionFactories.get(
ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), ServiceOptions.getDefaultProjectId())
.option(DRIVER, DRIVER_NAME) | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
// Path: cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/it/TestDatabaseHelper.java
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.ServiceOptions;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import java.util.Random;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
int suffix = Math.abs(this.random.nextInt());
Mono.from(
this.connection
.createStatement(INSERT_DATA_QUERY)
.bind("uuid", "autoinserted-" + suffix)
.bind("title", title)
.bind("category", category)
.execute())
.flatMapMany(rs -> rs.getRowsUpdated())
.blockLast();
}
public void clearTestData() {
Mono.from(
this.connection.createStatement("DELETE FROM BOOKS WHERE true").execute())
.flatMap(rs -> Mono.from(rs.getRowsUpdated()))
.block();
}
public void close() {
Mono.from(this.connection.close()).block();
}
public static void main(String[] args) {
ConnectionFactory cf =
ConnectionFactories.get(
ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), ServiceOptions.getDefaultProjectId())
.option(DRIVER, DRIVER_NAME) | .option(INSTANCE, DatabaseProperties.INSTANCE) |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/v2/DatabaseClientTransactionManagerTest.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/TransactionInProgressException.java
// public class TransactionInProgressException extends R2dbcNonTransientException {
//
// public static final String MSG_READONLY =
// "Cannot begin a new transaction because a readonly transaction is already in progress.";
// public static final String MSG_READWRITE =
// "Cannot begin a new transaction because a read/write transaction is already in progress.";
//
// public TransactionInProgressException(boolean isReadwrite) {
// super(isReadwrite ? MSG_READWRITE : MSG_READONLY);
// }
//
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import com.google.api.core.ApiFutures;
import com.google.cloud.spanner.AsyncTransactionManager;
import com.google.cloud.spanner.AsyncTransactionManager.AsyncTransactionFunction;
import com.google.cloud.spanner.AsyncTransactionManager.AsyncTransactionStep;
import com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture;
import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.ReadOnlyTransaction;
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.TimestampBound;
import com.google.cloud.spanner.TransactionContext;
import com.google.cloud.spanner.r2dbc.TransactionInProgressException;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | /*
* Copyright 2020-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class DatabaseClientTransactionManagerTest {
DatabaseClientTransactionManager transactionManager;
DatabaseClient mockDbClient;
AsyncTransactionManager mockClientLibraryTransactionManager;
TransactionContextFuture mockTransactionFuture;
TransactionContext mockTransactionContext;
ReadOnlyTransaction mockReadOnlyTransaction;
AsyncTransactionStep mockAsyncTransactionStep;
private static PrintStream systemErr;
private static ByteArrayOutputStream redirectedOutput = new ByteArrayOutputStream();
@BeforeAll
public static void redirectOutput() {
systemErr = System.out;
System.setErr(new PrintStream(redirectedOutput));
}
@AfterAll
public static void restoreOutput() {
System.setErr(systemErr);
}
/** Sets up mocks. */
@BeforeEach
public void setUp() {
this.mockDbClient = mock(DatabaseClient.class);
this.mockClientLibraryTransactionManager = mock(AsyncTransactionManager.class);
this.mockTransactionFuture = mock(TransactionContextFuture.class);
this.mockTransactionContext = mock(TransactionContext.class);
this.mockReadOnlyTransaction = mock(ReadOnlyTransaction.class);
this.mockAsyncTransactionStep = mock(AsyncTransactionStep.class);
when(this.mockDbClient.transactionManagerAsync())
.thenReturn(this.mockClientLibraryTransactionManager);
when(this.mockClientLibraryTransactionManager.beginAsync())
.thenReturn(this.mockTransactionFuture);
when(this.mockTransactionFuture.then(any(), any())).thenAnswer(invocation -> {
((AsyncTransactionFunction) invocation.getArgument(0))
.apply(this.mockTransactionContext, null);
return this.mockAsyncTransactionStep;
});
when(this.mockTransactionContext.executeUpdateAsync(any()))
.thenReturn(ApiFutures.immediateFuture(42L));
when(this.mockClientLibraryTransactionManager.closeAsync())
.thenReturn(ApiFutures.immediateFuture(null));
when(this.mockDbClient.readOnlyTransaction(TimestampBound.strong()))
.thenReturn(this.mockReadOnlyTransaction);
this.transactionManager = new DatabaseClientTransactionManager(this.mockDbClient);
}
@Test
void testReadonlyTransactionStartedWhileReadWriteInProgressFails() {
this.transactionManager.beginTransaction();
TimestampBound strongBound = TimestampBound.strong();
assertThatThrownBy(() ->
this.transactionManager.beginReadonlyTransaction(strongBound) | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/TransactionInProgressException.java
// public class TransactionInProgressException extends R2dbcNonTransientException {
//
// public static final String MSG_READONLY =
// "Cannot begin a new transaction because a readonly transaction is already in progress.";
// public static final String MSG_READWRITE =
// "Cannot begin a new transaction because a read/write transaction is already in progress.";
//
// public TransactionInProgressException(boolean isReadwrite) {
// super(isReadwrite ? MSG_READWRITE : MSG_READONLY);
// }
//
// }
// Path: cloud-spanner-r2dbc/src/test/java/com/google/cloud/spanner/r2dbc/v2/DatabaseClientTransactionManagerTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import com.google.api.core.ApiFutures;
import com.google.cloud.spanner.AsyncTransactionManager;
import com.google.cloud.spanner.AsyncTransactionManager.AsyncTransactionFunction;
import com.google.cloud.spanner.AsyncTransactionManager.AsyncTransactionStep;
import com.google.cloud.spanner.AsyncTransactionManager.TransactionContextFuture;
import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.ReadOnlyTransaction;
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.TimestampBound;
import com.google.cloud.spanner.TransactionContext;
import com.google.cloud.spanner.r2dbc.TransactionInProgressException;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/*
* Copyright 2020-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.spanner.r2dbc.v2;
class DatabaseClientTransactionManagerTest {
DatabaseClientTransactionManager transactionManager;
DatabaseClient mockDbClient;
AsyncTransactionManager mockClientLibraryTransactionManager;
TransactionContextFuture mockTransactionFuture;
TransactionContext mockTransactionContext;
ReadOnlyTransaction mockReadOnlyTransaction;
AsyncTransactionStep mockAsyncTransactionStep;
private static PrintStream systemErr;
private static ByteArrayOutputStream redirectedOutput = new ByteArrayOutputStream();
@BeforeAll
public static void redirectOutput() {
systemErr = System.out;
System.setErr(new PrintStream(redirectedOutput));
}
@AfterAll
public static void restoreOutput() {
System.setErr(systemErr);
}
/** Sets up mocks. */
@BeforeEach
public void setUp() {
this.mockDbClient = mock(DatabaseClient.class);
this.mockClientLibraryTransactionManager = mock(AsyncTransactionManager.class);
this.mockTransactionFuture = mock(TransactionContextFuture.class);
this.mockTransactionContext = mock(TransactionContext.class);
this.mockReadOnlyTransaction = mock(ReadOnlyTransaction.class);
this.mockAsyncTransactionStep = mock(AsyncTransactionStep.class);
when(this.mockDbClient.transactionManagerAsync())
.thenReturn(this.mockClientLibraryTransactionManager);
when(this.mockClientLibraryTransactionManager.beginAsync())
.thenReturn(this.mockTransactionFuture);
when(this.mockTransactionFuture.then(any(), any())).thenAnswer(invocation -> {
((AsyncTransactionFunction) invocation.getArgument(0))
.apply(this.mockTransactionContext, null);
return this.mockAsyncTransactionStep;
});
when(this.mockTransactionContext.executeUpdateAsync(any()))
.thenReturn(ApiFutures.immediateFuture(42L));
when(this.mockClientLibraryTransactionManager.closeAsync())
.thenReturn(ApiFutures.immediateFuture(null));
when(this.mockDbClient.readOnlyTransaction(TimestampBound.strong()))
.thenReturn(this.mockReadOnlyTransaction);
this.transactionManager = new DatabaseClientTransactionManager(this.mockDbClient);
}
@Test
void testReadonlyTransactionStartedWhileReadWriteInProgressFails() {
this.transactionManager.beginTransaction();
TimestampBound strongBound = TimestampBound.strong();
assertThatThrownBy(() ->
this.transactionManager.beginReadonlyTransaction(strongBound) | ).isInstanceOf(TransactionInProgressException.class) |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc-samples/cloud-spanner-r2dbc-sample/src/main/java/com/example/BookExampleApp.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/JsonWrapper.java
// public class JsonWrapper {
// private String jsonString;
//
// public JsonWrapper(String jsonString) {
// this.jsonString = jsonString;
// }
//
// protected Value getJsonVal() {
// return Value.json(this.jsonString);
// }
//
// public static JsonWrapper of(String jsonString) {
// return new JsonWrapper(jsonString);
// }
//
// @Override
// public String toString() {
// return this.jsonString;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// JsonWrapper that = (JsonWrapper) o;
// return Objects.equal(this.jsonString, that.jsonString);
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(this.jsonString);
// }
// }
| import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.spanner.r2dbc.v2.JsonWrapper;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import io.r2dbc.spi.Row;
import io.r2dbc.spi.RowMetadata;
import io.r2dbc.spi.Statement; | /*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example;
/**
* The main class for the functions of the sample application.
*/
public class BookExampleApp {
private final ConnectionFactory connectionFactory;
private final Connection connection;
/**
* Constructor.
*
* @param sampleInstance the sample instance to use.
* @param sampleDatabase the sample database to use.
* @param sampleProjectId the sample project to use.
*/
public BookExampleApp(String sampleInstance, String sampleDatabase,
String sampleProjectId) {
this.connectionFactory = ConnectionFactories.get(ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), sampleProjectId) | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/JsonWrapper.java
// public class JsonWrapper {
// private String jsonString;
//
// public JsonWrapper(String jsonString) {
// this.jsonString = jsonString;
// }
//
// protected Value getJsonVal() {
// return Value.json(this.jsonString);
// }
//
// public static JsonWrapper of(String jsonString) {
// return new JsonWrapper(jsonString);
// }
//
// @Override
// public String toString() {
// return this.jsonString;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// JsonWrapper that = (JsonWrapper) o;
// return Objects.equal(this.jsonString, that.jsonString);
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(this.jsonString);
// }
// }
// Path: cloud-spanner-r2dbc-samples/cloud-spanner-r2dbc-sample/src/main/java/com/example/BookExampleApp.java
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.spanner.r2dbc.v2.JsonWrapper;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import io.r2dbc.spi.Row;
import io.r2dbc.spi.RowMetadata;
import io.r2dbc.spi.Statement;
/*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example;
/**
* The main class for the functions of the sample application.
*/
public class BookExampleApp {
private final ConnectionFactory connectionFactory;
private final Connection connection;
/**
* Constructor.
*
* @param sampleInstance the sample instance to use.
* @param sampleDatabase the sample database to use.
* @param sampleProjectId the sample project to use.
*/
public BookExampleApp(String sampleInstance, String sampleDatabase,
String sampleProjectId) {
this.connectionFactory = ConnectionFactories.get(ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), sampleProjectId) | .option(DRIVER, DRIVER_NAME) |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc-samples/cloud-spanner-r2dbc-sample/src/main/java/com/example/BookExampleApp.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/JsonWrapper.java
// public class JsonWrapper {
// private String jsonString;
//
// public JsonWrapper(String jsonString) {
// this.jsonString = jsonString;
// }
//
// protected Value getJsonVal() {
// return Value.json(this.jsonString);
// }
//
// public static JsonWrapper of(String jsonString) {
// return new JsonWrapper(jsonString);
// }
//
// @Override
// public String toString() {
// return this.jsonString;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// JsonWrapper that = (JsonWrapper) o;
// return Objects.equal(this.jsonString, that.jsonString);
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(this.jsonString);
// }
// }
| import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.spanner.r2dbc.v2.JsonWrapper;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import io.r2dbc.spi.Row;
import io.r2dbc.spi.RowMetadata;
import io.r2dbc.spi.Statement; | /*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example;
/**
* The main class for the functions of the sample application.
*/
public class BookExampleApp {
private final ConnectionFactory connectionFactory;
private final Connection connection;
/**
* Constructor.
*
* @param sampleInstance the sample instance to use.
* @param sampleDatabase the sample database to use.
* @param sampleProjectId the sample project to use.
*/
public BookExampleApp(String sampleInstance, String sampleDatabase,
String sampleProjectId) {
this.connectionFactory = ConnectionFactories.get(ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), sampleProjectId)
.option(DRIVER, DRIVER_NAME) | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/JsonWrapper.java
// public class JsonWrapper {
// private String jsonString;
//
// public JsonWrapper(String jsonString) {
// this.jsonString = jsonString;
// }
//
// protected Value getJsonVal() {
// return Value.json(this.jsonString);
// }
//
// public static JsonWrapper of(String jsonString) {
// return new JsonWrapper(jsonString);
// }
//
// @Override
// public String toString() {
// return this.jsonString;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// JsonWrapper that = (JsonWrapper) o;
// return Objects.equal(this.jsonString, that.jsonString);
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(this.jsonString);
// }
// }
// Path: cloud-spanner-r2dbc-samples/cloud-spanner-r2dbc-sample/src/main/java/com/example/BookExampleApp.java
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.spanner.r2dbc.v2.JsonWrapper;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import io.r2dbc.spi.Row;
import io.r2dbc.spi.RowMetadata;
import io.r2dbc.spi.Statement;
/*
* Copyright 2019-2020 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example;
/**
* The main class for the functions of the sample application.
*/
public class BookExampleApp {
private final ConnectionFactory connectionFactory;
private final Connection connection;
/**
* Constructor.
*
* @param sampleInstance the sample instance to use.
* @param sampleDatabase the sample database to use.
* @param sampleProjectId the sample project to use.
*/
public BookExampleApp(String sampleInstance, String sampleDatabase,
String sampleProjectId) {
this.connectionFactory = ConnectionFactories.get(ConnectionFactoryOptions.builder()
.option(Option.valueOf("project"), sampleProjectId)
.option(DRIVER, DRIVER_NAME) | .option(INSTANCE, sampleInstance) |
GoogleCloudPlatform/cloud-spanner-r2dbc | cloud-spanner-r2dbc-samples/cloud-spanner-r2dbc-sample/src/main/java/com/example/BookExampleApp.java | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/JsonWrapper.java
// public class JsonWrapper {
// private String jsonString;
//
// public JsonWrapper(String jsonString) {
// this.jsonString = jsonString;
// }
//
// protected Value getJsonVal() {
// return Value.json(this.jsonString);
// }
//
// public static JsonWrapper of(String jsonString) {
// return new JsonWrapper(jsonString);
// }
//
// @Override
// public String toString() {
// return this.jsonString;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// JsonWrapper that = (JsonWrapper) o;
// return Objects.equal(this.jsonString, that.jsonString);
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(this.jsonString);
// }
// }
| import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.spanner.r2dbc.v2.JsonWrapper;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import io.r2dbc.spi.Row;
import io.r2dbc.spi.RowMetadata;
import io.r2dbc.spi.Statement; | + " TITLE STRING(MAX) NOT NULL,"
+ " EXTRADETAILS JSON"
+ ") PRIMARY KEY (ID)").execute())
.doOnSuccess(x -> System.out.println("Table creation completed."))
.block();
}
/**
* Saves two books.
*/
public void saveBooks() {
Statement statement = this.connection.createStatement(
"INSERT BOOKS "
+ "(ID, TITLE)"
+ " VALUES "
+ "(@id, @title)")
.bind("id", "book1")
.bind("title", "Book One")
.add()
.bind("id", "book2")
.bind("title", "Book Two");
Statement statement2 = this.connection.createStatement(
"INSERT BOOKS "
+ "(ID, TITLE, EXTRADETAILS)"
+ " VALUES "
+ "(@id, @title, @extradetails)")
.bind("id", "book3")
.bind("title", "Book Three") | // Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final String DRIVER_NAME = "cloudspanner";
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/SpannerConnectionFactoryProvider.java
// public static final Option<String> INSTANCE = Option.valueOf("instance");
//
// Path: cloud-spanner-r2dbc/src/main/java/com/google/cloud/spanner/r2dbc/v2/JsonWrapper.java
// public class JsonWrapper {
// private String jsonString;
//
// public JsonWrapper(String jsonString) {
// this.jsonString = jsonString;
// }
//
// protected Value getJsonVal() {
// return Value.json(this.jsonString);
// }
//
// public static JsonWrapper of(String jsonString) {
// return new JsonWrapper(jsonString);
// }
//
// @Override
// public String toString() {
// return this.jsonString;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// JsonWrapper that = (JsonWrapper) o;
// return Objects.equal(this.jsonString, that.jsonString);
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(this.jsonString);
// }
// }
// Path: cloud-spanner-r2dbc-samples/cloud-spanner-r2dbc-sample/src/main/java/com/example/BookExampleApp.java
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.DRIVER_NAME;
import static com.google.cloud.spanner.r2dbc.SpannerConnectionFactoryProvider.INSTANCE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE;
import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER;
import com.google.cloud.spanner.r2dbc.v2.JsonWrapper;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.Option;
import io.r2dbc.spi.Row;
import io.r2dbc.spi.RowMetadata;
import io.r2dbc.spi.Statement;
+ " TITLE STRING(MAX) NOT NULL,"
+ " EXTRADETAILS JSON"
+ ") PRIMARY KEY (ID)").execute())
.doOnSuccess(x -> System.out.println("Table creation completed."))
.block();
}
/**
* Saves two books.
*/
public void saveBooks() {
Statement statement = this.connection.createStatement(
"INSERT BOOKS "
+ "(ID, TITLE)"
+ " VALUES "
+ "(@id, @title)")
.bind("id", "book1")
.bind("title", "Book One")
.add()
.bind("id", "book2")
.bind("title", "Book Two");
Statement statement2 = this.connection.createStatement(
"INSERT BOOKS "
+ "(ID, TITLE, EXTRADETAILS)"
+ " VALUES "
+ "(@id, @title, @extradetails)")
.bind("id", "book3")
.bind("title", "Book Three") | .bind("extradetails", new JsonWrapper("{\"rating\":9,\"series\":true}")); |
elphinkuo/lightDroid | framework/util/jsonparser/ParserData.java | // Path: framework/util/http/exception/AuthorizationException.java
// public class AuthorizationException extends XmlParserException {
// private static final long serialVersionUID = 1L;
//
// public AuthorizationException(String message) {
// super(message);
// }
//
// }
//
// Path: framework/util/http/exception/XmlParserException.java
// public class XmlParserException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 3789211073927189813L;
// private String mExtra;
//
// public XmlParserException(String errorMessage) {
// super(errorMessage);
// }
//
// public XmlParserException(String errorMessage, String extra) {
// super(errorMessage);
// mExtra = extra;
// }
//
// public String getExtra() {
// return mExtra;
// }
// }
//
// Path: framework/util/http/exception/XmlParserParseException.java
// public class XmlParserParseException extends XmlParserException {
//
// /**
// *
// */
// private static final long serialVersionUID = 3857089504256300868L;
//
// public XmlParserParseException(String errorMessage) {
// super(errorMessage);
// }
// }
| import com.elphin.framework.util.http.exception.AuthorizationException;
import com.elphin.framework.util.http.exception.XmlParserException;
import com.elphin.framework.util.http.exception.XmlParserParseException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream; | package com.elphin.framework.util.jsonparser;
public class ParserData {
public static BaseObject analysisHttpResponseToObject(InputStream is,
Parser<? extends BaseObject> parser, String encodeing) | // Path: framework/util/http/exception/AuthorizationException.java
// public class AuthorizationException extends XmlParserException {
// private static final long serialVersionUID = 1L;
//
// public AuthorizationException(String message) {
// super(message);
// }
//
// }
//
// Path: framework/util/http/exception/XmlParserException.java
// public class XmlParserException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 3789211073927189813L;
// private String mExtra;
//
// public XmlParserException(String errorMessage) {
// super(errorMessage);
// }
//
// public XmlParserException(String errorMessage, String extra) {
// super(errorMessage);
// mExtra = extra;
// }
//
// public String getExtra() {
// return mExtra;
// }
// }
//
// Path: framework/util/http/exception/XmlParserParseException.java
// public class XmlParserParseException extends XmlParserException {
//
// /**
// *
// */
// private static final long serialVersionUID = 3857089504256300868L;
//
// public XmlParserParseException(String errorMessage) {
// super(errorMessage);
// }
// }
// Path: framework/util/jsonparser/ParserData.java
import com.elphin.framework.util.http.exception.AuthorizationException;
import com.elphin.framework.util.http.exception.XmlParserException;
import com.elphin.framework.util.http.exception.XmlParserParseException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
package com.elphin.framework.util.jsonparser;
public class ParserData {
public static BaseObject analysisHttpResponseToObject(InputStream is,
Parser<? extends BaseObject> parser, String encodeing) | throws AuthorizationException, XmlParserParseException, |
elphinkuo/lightDroid | framework/util/jsonparser/ParserData.java | // Path: framework/util/http/exception/AuthorizationException.java
// public class AuthorizationException extends XmlParserException {
// private static final long serialVersionUID = 1L;
//
// public AuthorizationException(String message) {
// super(message);
// }
//
// }
//
// Path: framework/util/http/exception/XmlParserException.java
// public class XmlParserException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 3789211073927189813L;
// private String mExtra;
//
// public XmlParserException(String errorMessage) {
// super(errorMessage);
// }
//
// public XmlParserException(String errorMessage, String extra) {
// super(errorMessage);
// mExtra = extra;
// }
//
// public String getExtra() {
// return mExtra;
// }
// }
//
// Path: framework/util/http/exception/XmlParserParseException.java
// public class XmlParserParseException extends XmlParserException {
//
// /**
// *
// */
// private static final long serialVersionUID = 3857089504256300868L;
//
// public XmlParserParseException(String errorMessage) {
// super(errorMessage);
// }
// }
| import com.elphin.framework.util.http.exception.AuthorizationException;
import com.elphin.framework.util.http.exception.XmlParserException;
import com.elphin.framework.util.http.exception.XmlParserParseException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream; | package com.elphin.framework.util.jsonparser;
public class ParserData {
public static BaseObject analysisHttpResponseToObject(InputStream is,
Parser<? extends BaseObject> parser, String encodeing) | // Path: framework/util/http/exception/AuthorizationException.java
// public class AuthorizationException extends XmlParserException {
// private static final long serialVersionUID = 1L;
//
// public AuthorizationException(String message) {
// super(message);
// }
//
// }
//
// Path: framework/util/http/exception/XmlParserException.java
// public class XmlParserException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 3789211073927189813L;
// private String mExtra;
//
// public XmlParserException(String errorMessage) {
// super(errorMessage);
// }
//
// public XmlParserException(String errorMessage, String extra) {
// super(errorMessage);
// mExtra = extra;
// }
//
// public String getExtra() {
// return mExtra;
// }
// }
//
// Path: framework/util/http/exception/XmlParserParseException.java
// public class XmlParserParseException extends XmlParserException {
//
// /**
// *
// */
// private static final long serialVersionUID = 3857089504256300868L;
//
// public XmlParserParseException(String errorMessage) {
// super(errorMessage);
// }
// }
// Path: framework/util/jsonparser/ParserData.java
import com.elphin.framework.util.http.exception.AuthorizationException;
import com.elphin.framework.util.http.exception.XmlParserException;
import com.elphin.framework.util.http.exception.XmlParserParseException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
package com.elphin.framework.util.jsonparser;
public class ParserData {
public static BaseObject analysisHttpResponseToObject(InputStream is,
Parser<? extends BaseObject> parser, String encodeing) | throws AuthorizationException, XmlParserParseException, |
elphinkuo/lightDroid | framework/util/jsonparser/ParserData.java | // Path: framework/util/http/exception/AuthorizationException.java
// public class AuthorizationException extends XmlParserException {
// private static final long serialVersionUID = 1L;
//
// public AuthorizationException(String message) {
// super(message);
// }
//
// }
//
// Path: framework/util/http/exception/XmlParserException.java
// public class XmlParserException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 3789211073927189813L;
// private String mExtra;
//
// public XmlParserException(String errorMessage) {
// super(errorMessage);
// }
//
// public XmlParserException(String errorMessage, String extra) {
// super(errorMessage);
// mExtra = extra;
// }
//
// public String getExtra() {
// return mExtra;
// }
// }
//
// Path: framework/util/http/exception/XmlParserParseException.java
// public class XmlParserParseException extends XmlParserException {
//
// /**
// *
// */
// private static final long serialVersionUID = 3857089504256300868L;
//
// public XmlParserParseException(String errorMessage) {
// super(errorMessage);
// }
// }
| import com.elphin.framework.util.http.exception.AuthorizationException;
import com.elphin.framework.util.http.exception.XmlParserException;
import com.elphin.framework.util.http.exception.XmlParserParseException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream; | package com.elphin.framework.util.jsonparser;
public class ParserData {
public static BaseObject analysisHttpResponseToObject(InputStream is,
Parser<? extends BaseObject> parser, String encodeing)
throws AuthorizationException, XmlParserParseException, | // Path: framework/util/http/exception/AuthorizationException.java
// public class AuthorizationException extends XmlParserException {
// private static final long serialVersionUID = 1L;
//
// public AuthorizationException(String message) {
// super(message);
// }
//
// }
//
// Path: framework/util/http/exception/XmlParserException.java
// public class XmlParserException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 3789211073927189813L;
// private String mExtra;
//
// public XmlParserException(String errorMessage) {
// super(errorMessage);
// }
//
// public XmlParserException(String errorMessage, String extra) {
// super(errorMessage);
// mExtra = extra;
// }
//
// public String getExtra() {
// return mExtra;
// }
// }
//
// Path: framework/util/http/exception/XmlParserParseException.java
// public class XmlParserParseException extends XmlParserException {
//
// /**
// *
// */
// private static final long serialVersionUID = 3857089504256300868L;
//
// public XmlParserParseException(String errorMessage) {
// super(errorMessage);
// }
// }
// Path: framework/util/jsonparser/ParserData.java
import com.elphin.framework.util.http.exception.AuthorizationException;
import com.elphin.framework.util.http.exception.XmlParserException;
import com.elphin.framework.util.http.exception.XmlParserParseException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
package com.elphin.framework.util.jsonparser;
public class ParserData {
public static BaseObject analysisHttpResponseToObject(InputStream is,
Parser<? extends BaseObject> parser, String encodeing)
throws AuthorizationException, XmlParserParseException, | XmlParserException, IOException { |
elphinkuo/lightDroid | framework/util/http/AbstractHttpApi.java | // Path: framework/util/http/exception/AuthorizationException.java
// public class AuthorizationException extends XmlParserException {
// private static final long serialVersionUID = 1L;
//
// public AuthorizationException(String message) {
// super(message);
// }
//
// }
//
// Path: framework/util/http/exception/XmlParserException.java
// public class XmlParserException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 3789211073927189813L;
// private String mExtra;
//
// public XmlParserException(String errorMessage) {
// super(errorMessage);
// }
//
// public XmlParserException(String errorMessage, String extra) {
// super(errorMessage);
// mExtra = extra;
// }
//
// public String getExtra() {
// return mExtra;
// }
// }
//
// Path: framework/util/http/exception/XmlParserParseException.java
// public class XmlParserParseException extends XmlParserException {
//
// /**
// *
// */
// private static final long serialVersionUID = 3857089504256300868L;
//
// public XmlParserParseException(String errorMessage) {
// super(errorMessage);
// }
// }
| import android.content.Context;
import com.elphin.framework.util.http.exception.AuthorizationException;
import com.elphin.framework.util.http.exception.XmlParserException;
import com.elphin.framework.util.http.exception.XmlParserParseException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List; |
package com.elphin.framework.util.http;
/**
* @author elphin
*
*/
abstract public class AbstractHttpApi implements HttpApi {
// protected static final boolean DEBUG = Config.DEBUG;
private static final String DEFAULT_CLIENT_VERSION = "com.baidu.android";
private static final String CLIENT_VERSION_HEADER = "User-Agent";
private static final int TIMEOUT = 60;
private final DefaultHttpClient mHttpClient;
private final String mClientVersion;
public AbstractHttpApi(DefaultHttpClient httpClient, String clientVersion) {
mHttpClient = httpClient;
if (clientVersion != null) {
mClientVersion = clientVersion;
} else {
mClientVersion = DEFAULT_CLIENT_VERSION;
}
}
/**
* 执行post
*/
public String doHttpPost(String url, NameValuePair... nameValuePairs) | // Path: framework/util/http/exception/AuthorizationException.java
// public class AuthorizationException extends XmlParserException {
// private static final long serialVersionUID = 1L;
//
// public AuthorizationException(String message) {
// super(message);
// }
//
// }
//
// Path: framework/util/http/exception/XmlParserException.java
// public class XmlParserException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 3789211073927189813L;
// private String mExtra;
//
// public XmlParserException(String errorMessage) {
// super(errorMessage);
// }
//
// public XmlParserException(String errorMessage, String extra) {
// super(errorMessage);
// mExtra = extra;
// }
//
// public String getExtra() {
// return mExtra;
// }
// }
//
// Path: framework/util/http/exception/XmlParserParseException.java
// public class XmlParserParseException extends XmlParserException {
//
// /**
// *
// */
// private static final long serialVersionUID = 3857089504256300868L;
//
// public XmlParserParseException(String errorMessage) {
// super(errorMessage);
// }
// }
// Path: framework/util/http/AbstractHttpApi.java
import android.content.Context;
import com.elphin.framework.util.http.exception.AuthorizationException;
import com.elphin.framework.util.http.exception.XmlParserException;
import com.elphin.framework.util.http.exception.XmlParserParseException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
package com.elphin.framework.util.http;
/**
* @author elphin
*
*/
abstract public class AbstractHttpApi implements HttpApi {
// protected static final boolean DEBUG = Config.DEBUG;
private static final String DEFAULT_CLIENT_VERSION = "com.baidu.android";
private static final String CLIENT_VERSION_HEADER = "User-Agent";
private static final int TIMEOUT = 60;
private final DefaultHttpClient mHttpClient;
private final String mClientVersion;
public AbstractHttpApi(DefaultHttpClient httpClient, String clientVersion) {
mHttpClient = httpClient;
if (clientVersion != null) {
mClientVersion = clientVersion;
} else {
mClientVersion = DEFAULT_CLIENT_VERSION;
}
}
/**
* 执行post
*/
public String doHttpPost(String url, NameValuePair... nameValuePairs) | throws AuthorizationException, XmlParserParseException, XmlParserException, IOException { |
elphinkuo/lightDroid | framework/util/http/AbstractHttpApi.java | // Path: framework/util/http/exception/AuthorizationException.java
// public class AuthorizationException extends XmlParserException {
// private static final long serialVersionUID = 1L;
//
// public AuthorizationException(String message) {
// super(message);
// }
//
// }
//
// Path: framework/util/http/exception/XmlParserException.java
// public class XmlParserException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 3789211073927189813L;
// private String mExtra;
//
// public XmlParserException(String errorMessage) {
// super(errorMessage);
// }
//
// public XmlParserException(String errorMessage, String extra) {
// super(errorMessage);
// mExtra = extra;
// }
//
// public String getExtra() {
// return mExtra;
// }
// }
//
// Path: framework/util/http/exception/XmlParserParseException.java
// public class XmlParserParseException extends XmlParserException {
//
// /**
// *
// */
// private static final long serialVersionUID = 3857089504256300868L;
//
// public XmlParserParseException(String errorMessage) {
// super(errorMessage);
// }
// }
| import android.content.Context;
import com.elphin.framework.util.http.exception.AuthorizationException;
import com.elphin.framework.util.http.exception.XmlParserException;
import com.elphin.framework.util.http.exception.XmlParserParseException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List; |
package com.elphin.framework.util.http;
/**
* @author elphin
*
*/
abstract public class AbstractHttpApi implements HttpApi {
// protected static final boolean DEBUG = Config.DEBUG;
private static final String DEFAULT_CLIENT_VERSION = "com.baidu.android";
private static final String CLIENT_VERSION_HEADER = "User-Agent";
private static final int TIMEOUT = 60;
private final DefaultHttpClient mHttpClient;
private final String mClientVersion;
public AbstractHttpApi(DefaultHttpClient httpClient, String clientVersion) {
mHttpClient = httpClient;
if (clientVersion != null) {
mClientVersion = clientVersion;
} else {
mClientVersion = DEFAULT_CLIENT_VERSION;
}
}
/**
* 执行post
*/
public String doHttpPost(String url, NameValuePair... nameValuePairs) | // Path: framework/util/http/exception/AuthorizationException.java
// public class AuthorizationException extends XmlParserException {
// private static final long serialVersionUID = 1L;
//
// public AuthorizationException(String message) {
// super(message);
// }
//
// }
//
// Path: framework/util/http/exception/XmlParserException.java
// public class XmlParserException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 3789211073927189813L;
// private String mExtra;
//
// public XmlParserException(String errorMessage) {
// super(errorMessage);
// }
//
// public XmlParserException(String errorMessage, String extra) {
// super(errorMessage);
// mExtra = extra;
// }
//
// public String getExtra() {
// return mExtra;
// }
// }
//
// Path: framework/util/http/exception/XmlParserParseException.java
// public class XmlParserParseException extends XmlParserException {
//
// /**
// *
// */
// private static final long serialVersionUID = 3857089504256300868L;
//
// public XmlParserParseException(String errorMessage) {
// super(errorMessage);
// }
// }
// Path: framework/util/http/AbstractHttpApi.java
import android.content.Context;
import com.elphin.framework.util.http.exception.AuthorizationException;
import com.elphin.framework.util.http.exception.XmlParserException;
import com.elphin.framework.util.http.exception.XmlParserParseException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
package com.elphin.framework.util.http;
/**
* @author elphin
*
*/
abstract public class AbstractHttpApi implements HttpApi {
// protected static final boolean DEBUG = Config.DEBUG;
private static final String DEFAULT_CLIENT_VERSION = "com.baidu.android";
private static final String CLIENT_VERSION_HEADER = "User-Agent";
private static final int TIMEOUT = 60;
private final DefaultHttpClient mHttpClient;
private final String mClientVersion;
public AbstractHttpApi(DefaultHttpClient httpClient, String clientVersion) {
mHttpClient = httpClient;
if (clientVersion != null) {
mClientVersion = clientVersion;
} else {
mClientVersion = DEFAULT_CLIENT_VERSION;
}
}
/**
* 执行post
*/
public String doHttpPost(String url, NameValuePair... nameValuePairs) | throws AuthorizationException, XmlParserParseException, XmlParserException, IOException { |
elphinkuo/lightDroid | framework/util/http/AbstractHttpApi.java | // Path: framework/util/http/exception/AuthorizationException.java
// public class AuthorizationException extends XmlParserException {
// private static final long serialVersionUID = 1L;
//
// public AuthorizationException(String message) {
// super(message);
// }
//
// }
//
// Path: framework/util/http/exception/XmlParserException.java
// public class XmlParserException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 3789211073927189813L;
// private String mExtra;
//
// public XmlParserException(String errorMessage) {
// super(errorMessage);
// }
//
// public XmlParserException(String errorMessage, String extra) {
// super(errorMessage);
// mExtra = extra;
// }
//
// public String getExtra() {
// return mExtra;
// }
// }
//
// Path: framework/util/http/exception/XmlParserParseException.java
// public class XmlParserParseException extends XmlParserException {
//
// /**
// *
// */
// private static final long serialVersionUID = 3857089504256300868L;
//
// public XmlParserParseException(String errorMessage) {
// super(errorMessage);
// }
// }
| import android.content.Context;
import com.elphin.framework.util.http.exception.AuthorizationException;
import com.elphin.framework.util.http.exception.XmlParserException;
import com.elphin.framework.util.http.exception.XmlParserParseException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List; |
package com.elphin.framework.util.http;
/**
* @author elphin
*
*/
abstract public class AbstractHttpApi implements HttpApi {
// protected static final boolean DEBUG = Config.DEBUG;
private static final String DEFAULT_CLIENT_VERSION = "com.baidu.android";
private static final String CLIENT_VERSION_HEADER = "User-Agent";
private static final int TIMEOUT = 60;
private final DefaultHttpClient mHttpClient;
private final String mClientVersion;
public AbstractHttpApi(DefaultHttpClient httpClient, String clientVersion) {
mHttpClient = httpClient;
if (clientVersion != null) {
mClientVersion = clientVersion;
} else {
mClientVersion = DEFAULT_CLIENT_VERSION;
}
}
/**
* 执行post
*/
public String doHttpPost(String url, NameValuePair... nameValuePairs) | // Path: framework/util/http/exception/AuthorizationException.java
// public class AuthorizationException extends XmlParserException {
// private static final long serialVersionUID = 1L;
//
// public AuthorizationException(String message) {
// super(message);
// }
//
// }
//
// Path: framework/util/http/exception/XmlParserException.java
// public class XmlParserException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 3789211073927189813L;
// private String mExtra;
//
// public XmlParserException(String errorMessage) {
// super(errorMessage);
// }
//
// public XmlParserException(String errorMessage, String extra) {
// super(errorMessage);
// mExtra = extra;
// }
//
// public String getExtra() {
// return mExtra;
// }
// }
//
// Path: framework/util/http/exception/XmlParserParseException.java
// public class XmlParserParseException extends XmlParserException {
//
// /**
// *
// */
// private static final long serialVersionUID = 3857089504256300868L;
//
// public XmlParserParseException(String errorMessage) {
// super(errorMessage);
// }
// }
// Path: framework/util/http/AbstractHttpApi.java
import android.content.Context;
import com.elphin.framework.util.http.exception.AuthorizationException;
import com.elphin.framework.util.http.exception.XmlParserException;
import com.elphin.framework.util.http.exception.XmlParserParseException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
package com.elphin.framework.util.http;
/**
* @author elphin
*
*/
abstract public class AbstractHttpApi implements HttpApi {
// protected static final boolean DEBUG = Config.DEBUG;
private static final String DEFAULT_CLIENT_VERSION = "com.baidu.android";
private static final String CLIENT_VERSION_HEADER = "User-Agent";
private static final int TIMEOUT = 60;
private final DefaultHttpClient mHttpClient;
private final String mClientVersion;
public AbstractHttpApi(DefaultHttpClient httpClient, String clientVersion) {
mHttpClient = httpClient;
if (clientVersion != null) {
mClientVersion = clientVersion;
} else {
mClientVersion = DEFAULT_CLIENT_VERSION;
}
}
/**
* 执行post
*/
public String doHttpPost(String url, NameValuePair... nameValuePairs) | throws AuthorizationException, XmlParserParseException, XmlParserException, IOException { |
elphinkuo/lightDroid | framework/app/fpstack/TaskManagerImpl.java | // Path: framework/exception/BMException.java
// public class BMException extends Exception {
// public BMException(String message) {
// super(message);
// }
//
// public BMException() {
// super();
// }
//
// public BMException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public BMException(Throwable cause) {
// super(cause);
// }
// }
| import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import com.elphin.framework.exception.BMException;
import de.greenrobot.event.EventBus;
import java.lang.ref.SoftReference;
import java.net.URI;
import java.util.*; | if (mPageMap.containsKey(taskClsName)) {
ArrayList<String> pageList = mPageMap.get(taskClsName);
if (pageList == null) {
pageList = new ArrayList<String>();
return pageList.add(pageClsName) && (mPageMap.put(taskClsName, pageList) != null);
} else {
return !pageList.contains(pageClsName) && pageList.add(pageClsName);
}
} else {
ArrayList<String> pageList = new ArrayList<String>();
return pageList.add(pageClsName) && (mPageMap.put(taskClsName, pageList) == null);
}
}
/**
* 指定页面Tag跳转页面,附加页面参数
* </p>
* 为跳转的页面添加标签,构造多实例页面
*
* @param ctx Context
* @param pageCategory 目标页面类型,区分Map还是组件
* @param pageClsName 目标页面的类名(全限定名)
* @param pageTagString 目标页面标签
* @param pageArgs 页面参数
*/
public void navigateTo(Context ctx, PageCategory pageCategory, String pageClsName, String pageTagString, Bundle pageArgs) {
if(DEBUG)
Log.d(TAG,"== TaskMgr navigateTo == " + pageClsName);
if (ctx == null) {
try { | // Path: framework/exception/BMException.java
// public class BMException extends Exception {
// public BMException(String message) {
// super(message);
// }
//
// public BMException() {
// super();
// }
//
// public BMException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public BMException(Throwable cause) {
// super(cause);
// }
// }
// Path: framework/app/fpstack/TaskManagerImpl.java
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import com.elphin.framework.exception.BMException;
import de.greenrobot.event.EventBus;
import java.lang.ref.SoftReference;
import java.net.URI;
import java.util.*;
if (mPageMap.containsKey(taskClsName)) {
ArrayList<String> pageList = mPageMap.get(taskClsName);
if (pageList == null) {
pageList = new ArrayList<String>();
return pageList.add(pageClsName) && (mPageMap.put(taskClsName, pageList) != null);
} else {
return !pageList.contains(pageClsName) && pageList.add(pageClsName);
}
} else {
ArrayList<String> pageList = new ArrayList<String>();
return pageList.add(pageClsName) && (mPageMap.put(taskClsName, pageList) == null);
}
}
/**
* 指定页面Tag跳转页面,附加页面参数
* </p>
* 为跳转的页面添加标签,构造多实例页面
*
* @param ctx Context
* @param pageCategory 目标页面类型,区分Map还是组件
* @param pageClsName 目标页面的类名(全限定名)
* @param pageTagString 目标页面标签
* @param pageArgs 页面参数
*/
public void navigateTo(Context ctx, PageCategory pageCategory, String pageClsName, String pageTagString, Bundle pageArgs) {
if(DEBUG)
Log.d(TAG,"== TaskMgr navigateTo == " + pageClsName);
if (ctx == null) {
try { | throw new BMException("The Context is Null!!"); |
elphinkuo/lightDroid | framework/util/http/HttpApi.java | // Path: framework/util/http/exception/AuthorizationException.java
// public class AuthorizationException extends XmlParserException {
// private static final long serialVersionUID = 1L;
//
// public AuthorizationException(String message) {
// super(message);
// }
//
// }
//
// Path: framework/util/http/exception/XmlParserException.java
// public class XmlParserException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 3789211073927189813L;
// private String mExtra;
//
// public XmlParserException(String errorMessage) {
// super(errorMessage);
// }
//
// public XmlParserException(String errorMessage, String extra) {
// super(errorMessage);
// mExtra = extra;
// }
//
// public String getExtra() {
// return mExtra;
// }
// }
//
// Path: framework/util/http/exception/XmlParserParseException.java
// public class XmlParserParseException extends XmlParserException {
//
// /**
// *
// */
// private static final long serialVersionUID = 3857089504256300868L;
//
// public XmlParserParseException(String errorMessage) {
// super(errorMessage);
// }
// }
| import com.elphin.framework.util.http.exception.AuthorizationException;
import com.elphin.framework.util.http.exception.XmlParserException;
import com.elphin.framework.util.http.exception.XmlParserParseException;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL; | package com.elphin.framework.util.http;
public interface HttpApi {
abstract public String doHttpPost(String url,
NameValuePair... nameValuePairs) | // Path: framework/util/http/exception/AuthorizationException.java
// public class AuthorizationException extends XmlParserException {
// private static final long serialVersionUID = 1L;
//
// public AuthorizationException(String message) {
// super(message);
// }
//
// }
//
// Path: framework/util/http/exception/XmlParserException.java
// public class XmlParserException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 3789211073927189813L;
// private String mExtra;
//
// public XmlParserException(String errorMessage) {
// super(errorMessage);
// }
//
// public XmlParserException(String errorMessage, String extra) {
// super(errorMessage);
// mExtra = extra;
// }
//
// public String getExtra() {
// return mExtra;
// }
// }
//
// Path: framework/util/http/exception/XmlParserParseException.java
// public class XmlParserParseException extends XmlParserException {
//
// /**
// *
// */
// private static final long serialVersionUID = 3857089504256300868L;
//
// public XmlParserParseException(String errorMessage) {
// super(errorMessage);
// }
// }
// Path: framework/util/http/HttpApi.java
import com.elphin.framework.util.http.exception.AuthorizationException;
import com.elphin.framework.util.http.exception.XmlParserException;
import com.elphin.framework.util.http.exception.XmlParserParseException;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
package com.elphin.framework.util.http;
public interface HttpApi {
abstract public String doHttpPost(String url,
NameValuePair... nameValuePairs) | throws AuthorizationException, XmlParserParseException, |
elphinkuo/lightDroid | framework/util/http/HttpApi.java | // Path: framework/util/http/exception/AuthorizationException.java
// public class AuthorizationException extends XmlParserException {
// private static final long serialVersionUID = 1L;
//
// public AuthorizationException(String message) {
// super(message);
// }
//
// }
//
// Path: framework/util/http/exception/XmlParserException.java
// public class XmlParserException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 3789211073927189813L;
// private String mExtra;
//
// public XmlParserException(String errorMessage) {
// super(errorMessage);
// }
//
// public XmlParserException(String errorMessage, String extra) {
// super(errorMessage);
// mExtra = extra;
// }
//
// public String getExtra() {
// return mExtra;
// }
// }
//
// Path: framework/util/http/exception/XmlParserParseException.java
// public class XmlParserParseException extends XmlParserException {
//
// /**
// *
// */
// private static final long serialVersionUID = 3857089504256300868L;
//
// public XmlParserParseException(String errorMessage) {
// super(errorMessage);
// }
// }
| import com.elphin.framework.util.http.exception.AuthorizationException;
import com.elphin.framework.util.http.exception.XmlParserException;
import com.elphin.framework.util.http.exception.XmlParserParseException;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL; | package com.elphin.framework.util.http;
public interface HttpApi {
abstract public String doHttpPost(String url,
NameValuePair... nameValuePairs) | // Path: framework/util/http/exception/AuthorizationException.java
// public class AuthorizationException extends XmlParserException {
// private static final long serialVersionUID = 1L;
//
// public AuthorizationException(String message) {
// super(message);
// }
//
// }
//
// Path: framework/util/http/exception/XmlParserException.java
// public class XmlParserException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 3789211073927189813L;
// private String mExtra;
//
// public XmlParserException(String errorMessage) {
// super(errorMessage);
// }
//
// public XmlParserException(String errorMessage, String extra) {
// super(errorMessage);
// mExtra = extra;
// }
//
// public String getExtra() {
// return mExtra;
// }
// }
//
// Path: framework/util/http/exception/XmlParserParseException.java
// public class XmlParserParseException extends XmlParserException {
//
// /**
// *
// */
// private static final long serialVersionUID = 3857089504256300868L;
//
// public XmlParserParseException(String errorMessage) {
// super(errorMessage);
// }
// }
// Path: framework/util/http/HttpApi.java
import com.elphin.framework.util.http.exception.AuthorizationException;
import com.elphin.framework.util.http.exception.XmlParserException;
import com.elphin.framework.util.http.exception.XmlParserParseException;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
package com.elphin.framework.util.http;
public interface HttpApi {
abstract public String doHttpPost(String url,
NameValuePair... nameValuePairs) | throws AuthorizationException, XmlParserParseException, |
elphinkuo/lightDroid | framework/util/http/HttpApi.java | // Path: framework/util/http/exception/AuthorizationException.java
// public class AuthorizationException extends XmlParserException {
// private static final long serialVersionUID = 1L;
//
// public AuthorizationException(String message) {
// super(message);
// }
//
// }
//
// Path: framework/util/http/exception/XmlParserException.java
// public class XmlParserException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 3789211073927189813L;
// private String mExtra;
//
// public XmlParserException(String errorMessage) {
// super(errorMessage);
// }
//
// public XmlParserException(String errorMessage, String extra) {
// super(errorMessage);
// mExtra = extra;
// }
//
// public String getExtra() {
// return mExtra;
// }
// }
//
// Path: framework/util/http/exception/XmlParserParseException.java
// public class XmlParserParseException extends XmlParserException {
//
// /**
// *
// */
// private static final long serialVersionUID = 3857089504256300868L;
//
// public XmlParserParseException(String errorMessage) {
// super(errorMessage);
// }
// }
| import com.elphin.framework.util.http.exception.AuthorizationException;
import com.elphin.framework.util.http.exception.XmlParserException;
import com.elphin.framework.util.http.exception.XmlParserParseException;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL; | package com.elphin.framework.util.http;
public interface HttpApi {
abstract public String doHttpPost(String url,
NameValuePair... nameValuePairs)
throws AuthorizationException, XmlParserParseException, | // Path: framework/util/http/exception/AuthorizationException.java
// public class AuthorizationException extends XmlParserException {
// private static final long serialVersionUID = 1L;
//
// public AuthorizationException(String message) {
// super(message);
// }
//
// }
//
// Path: framework/util/http/exception/XmlParserException.java
// public class XmlParserException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 3789211073927189813L;
// private String mExtra;
//
// public XmlParserException(String errorMessage) {
// super(errorMessage);
// }
//
// public XmlParserException(String errorMessage, String extra) {
// super(errorMessage);
// mExtra = extra;
// }
//
// public String getExtra() {
// return mExtra;
// }
// }
//
// Path: framework/util/http/exception/XmlParserParseException.java
// public class XmlParserParseException extends XmlParserException {
//
// /**
// *
// */
// private static final long serialVersionUID = 3857089504256300868L;
//
// public XmlParserParseException(String errorMessage) {
// super(errorMessage);
// }
// }
// Path: framework/util/http/HttpApi.java
import com.elphin.framework.util.http.exception.AuthorizationException;
import com.elphin.framework.util.http.exception.XmlParserException;
import com.elphin.framework.util.http.exception.XmlParserParseException;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
package com.elphin.framework.util.http;
public interface HttpApi {
abstract public String doHttpPost(String url,
NameValuePair... nameValuePairs)
throws AuthorizationException, XmlParserParseException, | XmlParserException, IOException; |
elphinkuo/lightDroid | framework/util/jsonparser/JsonParserHttpApi.java | // Path: framework/util/http/HttpApiWithBasicAuth.java
// public class HttpApiWithBasicAuth extends AbstractHttpApi {
//
// private HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
//
// @Override
// public void process(final HttpRequest request, final HttpContext context)
// throws HttpException, IOException {
//
// AuthState authState = (AuthState) context
// .getAttribute(ClientContext.TARGET_AUTH_STATE);
// CredentialsProvider credsProvider = (CredentialsProvider) context
// .getAttribute(ClientContext.CREDS_PROVIDER);
// HttpHost targetHost = (HttpHost) context
// .getAttribute(ExecutionContext.HTTP_TARGET_HOST);
//
// // If not auth scheme has been initialized yet
// if (authState.getAuthScheme() == null) {
// AuthScope authScope = new AuthScope(targetHost.getHostName(),
// targetHost.getPort());
// // Obtain credentials matching the target host
// org.apache.http.auth.Credentials creds = credsProvider
// .getCredentials(authScope);
// // If found, generate BasicScheme preemptively
// if (creds != null) {
// authState.setAuthScheme(new BasicScheme());
// authState.setCredentials(creds);
// }
// }
// }
//
// };
//
// public HttpApiWithBasicAuth(DefaultHttpClient httpClient,
// String clientVersion) {
// super(httpClient, clientVersion);
// httpClient.addRequestInterceptor(preemptiveAuth, 0);
// }
// }
//
// Path: framework/util/http/exception/AuthorizationException.java
// public class AuthorizationException extends XmlParserException {
// private static final long serialVersionUID = 1L;
//
// public AuthorizationException(String message) {
// super(message);
// }
//
// }
//
// Path: framework/util/http/exception/XmlParserException.java
// public class XmlParserException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 3789211073927189813L;
// private String mExtra;
//
// public XmlParserException(String errorMessage) {
// super(errorMessage);
// }
//
// public XmlParserException(String errorMessage, String extra) {
// super(errorMessage);
// mExtra = extra;
// }
//
// public String getExtra() {
// return mExtra;
// }
// }
//
// Path: framework/util/http/exception/XmlParserParseException.java
// public class XmlParserParseException extends XmlParserException {
//
// /**
// *
// */
// private static final long serialVersionUID = 3857089504256300868L;
//
// public XmlParserParseException(String errorMessage) {
// super(errorMessage);
// }
// }
| import com.elphin.framework.util.http.HttpApiWithBasicAuth;
import com.elphin.framework.util.http.exception.AuthorizationException;
import com.elphin.framework.util.http.exception.XmlParserException;
import com.elphin.framework.util.http.exception.XmlParserParseException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream; | package com.elphin.framework.util.jsonparser;
public class JsonParserHttpApi extends HttpApiWithBasicAuth {
public JsonParserHttpApi(DefaultHttpClient httpClient, String clientVersion) {
super(httpClient, clientVersion);
}
public BaseObject analysisInputStreamToObject(InputStream inputStream, Parser<? extends BaseObject> parser,
String encodeing) throws JSONException, IOException, Exception {
return parser.parse(BaseParser.createJSONParser(inputStream, encodeing));
}
public BaseObject analysisHttpResponseToObject(HttpResponse response, Parser<? extends BaseObject> parser, | // Path: framework/util/http/HttpApiWithBasicAuth.java
// public class HttpApiWithBasicAuth extends AbstractHttpApi {
//
// private HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
//
// @Override
// public void process(final HttpRequest request, final HttpContext context)
// throws HttpException, IOException {
//
// AuthState authState = (AuthState) context
// .getAttribute(ClientContext.TARGET_AUTH_STATE);
// CredentialsProvider credsProvider = (CredentialsProvider) context
// .getAttribute(ClientContext.CREDS_PROVIDER);
// HttpHost targetHost = (HttpHost) context
// .getAttribute(ExecutionContext.HTTP_TARGET_HOST);
//
// // If not auth scheme has been initialized yet
// if (authState.getAuthScheme() == null) {
// AuthScope authScope = new AuthScope(targetHost.getHostName(),
// targetHost.getPort());
// // Obtain credentials matching the target host
// org.apache.http.auth.Credentials creds = credsProvider
// .getCredentials(authScope);
// // If found, generate BasicScheme preemptively
// if (creds != null) {
// authState.setAuthScheme(new BasicScheme());
// authState.setCredentials(creds);
// }
// }
// }
//
// };
//
// public HttpApiWithBasicAuth(DefaultHttpClient httpClient,
// String clientVersion) {
// super(httpClient, clientVersion);
// httpClient.addRequestInterceptor(preemptiveAuth, 0);
// }
// }
//
// Path: framework/util/http/exception/AuthorizationException.java
// public class AuthorizationException extends XmlParserException {
// private static final long serialVersionUID = 1L;
//
// public AuthorizationException(String message) {
// super(message);
// }
//
// }
//
// Path: framework/util/http/exception/XmlParserException.java
// public class XmlParserException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 3789211073927189813L;
// private String mExtra;
//
// public XmlParserException(String errorMessage) {
// super(errorMessage);
// }
//
// public XmlParserException(String errorMessage, String extra) {
// super(errorMessage);
// mExtra = extra;
// }
//
// public String getExtra() {
// return mExtra;
// }
// }
//
// Path: framework/util/http/exception/XmlParserParseException.java
// public class XmlParserParseException extends XmlParserException {
//
// /**
// *
// */
// private static final long serialVersionUID = 3857089504256300868L;
//
// public XmlParserParseException(String errorMessage) {
// super(errorMessage);
// }
// }
// Path: framework/util/jsonparser/JsonParserHttpApi.java
import com.elphin.framework.util.http.HttpApiWithBasicAuth;
import com.elphin.framework.util.http.exception.AuthorizationException;
import com.elphin.framework.util.http.exception.XmlParserException;
import com.elphin.framework.util.http.exception.XmlParserParseException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
package com.elphin.framework.util.jsonparser;
public class JsonParserHttpApi extends HttpApiWithBasicAuth {
public JsonParserHttpApi(DefaultHttpClient httpClient, String clientVersion) {
super(httpClient, clientVersion);
}
public BaseObject analysisInputStreamToObject(InputStream inputStream, Parser<? extends BaseObject> parser,
String encodeing) throws JSONException, IOException, Exception {
return parser.parse(BaseParser.createJSONParser(inputStream, encodeing));
}
public BaseObject analysisHttpResponseToObject(HttpResponse response, Parser<? extends BaseObject> parser, | String encodeing) throws AuthorizationException, XmlParserParseException, XmlParserException, IOException { |
elphinkuo/lightDroid | framework/util/jsonparser/JsonParserHttpApi.java | // Path: framework/util/http/HttpApiWithBasicAuth.java
// public class HttpApiWithBasicAuth extends AbstractHttpApi {
//
// private HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
//
// @Override
// public void process(final HttpRequest request, final HttpContext context)
// throws HttpException, IOException {
//
// AuthState authState = (AuthState) context
// .getAttribute(ClientContext.TARGET_AUTH_STATE);
// CredentialsProvider credsProvider = (CredentialsProvider) context
// .getAttribute(ClientContext.CREDS_PROVIDER);
// HttpHost targetHost = (HttpHost) context
// .getAttribute(ExecutionContext.HTTP_TARGET_HOST);
//
// // If not auth scheme has been initialized yet
// if (authState.getAuthScheme() == null) {
// AuthScope authScope = new AuthScope(targetHost.getHostName(),
// targetHost.getPort());
// // Obtain credentials matching the target host
// org.apache.http.auth.Credentials creds = credsProvider
// .getCredentials(authScope);
// // If found, generate BasicScheme preemptively
// if (creds != null) {
// authState.setAuthScheme(new BasicScheme());
// authState.setCredentials(creds);
// }
// }
// }
//
// };
//
// public HttpApiWithBasicAuth(DefaultHttpClient httpClient,
// String clientVersion) {
// super(httpClient, clientVersion);
// httpClient.addRequestInterceptor(preemptiveAuth, 0);
// }
// }
//
// Path: framework/util/http/exception/AuthorizationException.java
// public class AuthorizationException extends XmlParserException {
// private static final long serialVersionUID = 1L;
//
// public AuthorizationException(String message) {
// super(message);
// }
//
// }
//
// Path: framework/util/http/exception/XmlParserException.java
// public class XmlParserException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 3789211073927189813L;
// private String mExtra;
//
// public XmlParserException(String errorMessage) {
// super(errorMessage);
// }
//
// public XmlParserException(String errorMessage, String extra) {
// super(errorMessage);
// mExtra = extra;
// }
//
// public String getExtra() {
// return mExtra;
// }
// }
//
// Path: framework/util/http/exception/XmlParserParseException.java
// public class XmlParserParseException extends XmlParserException {
//
// /**
// *
// */
// private static final long serialVersionUID = 3857089504256300868L;
//
// public XmlParserParseException(String errorMessage) {
// super(errorMessage);
// }
// }
| import com.elphin.framework.util.http.HttpApiWithBasicAuth;
import com.elphin.framework.util.http.exception.AuthorizationException;
import com.elphin.framework.util.http.exception.XmlParserException;
import com.elphin.framework.util.http.exception.XmlParserParseException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream; | package com.elphin.framework.util.jsonparser;
public class JsonParserHttpApi extends HttpApiWithBasicAuth {
public JsonParserHttpApi(DefaultHttpClient httpClient, String clientVersion) {
super(httpClient, clientVersion);
}
public BaseObject analysisInputStreamToObject(InputStream inputStream, Parser<? extends BaseObject> parser,
String encodeing) throws JSONException, IOException, Exception {
return parser.parse(BaseParser.createJSONParser(inputStream, encodeing));
}
public BaseObject analysisHttpResponseToObject(HttpResponse response, Parser<? extends BaseObject> parser, | // Path: framework/util/http/HttpApiWithBasicAuth.java
// public class HttpApiWithBasicAuth extends AbstractHttpApi {
//
// private HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
//
// @Override
// public void process(final HttpRequest request, final HttpContext context)
// throws HttpException, IOException {
//
// AuthState authState = (AuthState) context
// .getAttribute(ClientContext.TARGET_AUTH_STATE);
// CredentialsProvider credsProvider = (CredentialsProvider) context
// .getAttribute(ClientContext.CREDS_PROVIDER);
// HttpHost targetHost = (HttpHost) context
// .getAttribute(ExecutionContext.HTTP_TARGET_HOST);
//
// // If not auth scheme has been initialized yet
// if (authState.getAuthScheme() == null) {
// AuthScope authScope = new AuthScope(targetHost.getHostName(),
// targetHost.getPort());
// // Obtain credentials matching the target host
// org.apache.http.auth.Credentials creds = credsProvider
// .getCredentials(authScope);
// // If found, generate BasicScheme preemptively
// if (creds != null) {
// authState.setAuthScheme(new BasicScheme());
// authState.setCredentials(creds);
// }
// }
// }
//
// };
//
// public HttpApiWithBasicAuth(DefaultHttpClient httpClient,
// String clientVersion) {
// super(httpClient, clientVersion);
// httpClient.addRequestInterceptor(preemptiveAuth, 0);
// }
// }
//
// Path: framework/util/http/exception/AuthorizationException.java
// public class AuthorizationException extends XmlParserException {
// private static final long serialVersionUID = 1L;
//
// public AuthorizationException(String message) {
// super(message);
// }
//
// }
//
// Path: framework/util/http/exception/XmlParserException.java
// public class XmlParserException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 3789211073927189813L;
// private String mExtra;
//
// public XmlParserException(String errorMessage) {
// super(errorMessage);
// }
//
// public XmlParserException(String errorMessage, String extra) {
// super(errorMessage);
// mExtra = extra;
// }
//
// public String getExtra() {
// return mExtra;
// }
// }
//
// Path: framework/util/http/exception/XmlParserParseException.java
// public class XmlParserParseException extends XmlParserException {
//
// /**
// *
// */
// private static final long serialVersionUID = 3857089504256300868L;
//
// public XmlParserParseException(String errorMessage) {
// super(errorMessage);
// }
// }
// Path: framework/util/jsonparser/JsonParserHttpApi.java
import com.elphin.framework.util.http.HttpApiWithBasicAuth;
import com.elphin.framework.util.http.exception.AuthorizationException;
import com.elphin.framework.util.http.exception.XmlParserException;
import com.elphin.framework.util.http.exception.XmlParserParseException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
package com.elphin.framework.util.jsonparser;
public class JsonParserHttpApi extends HttpApiWithBasicAuth {
public JsonParserHttpApi(DefaultHttpClient httpClient, String clientVersion) {
super(httpClient, clientVersion);
}
public BaseObject analysisInputStreamToObject(InputStream inputStream, Parser<? extends BaseObject> parser,
String encodeing) throws JSONException, IOException, Exception {
return parser.parse(BaseParser.createJSONParser(inputStream, encodeing));
}
public BaseObject analysisHttpResponseToObject(HttpResponse response, Parser<? extends BaseObject> parser, | String encodeing) throws AuthorizationException, XmlParserParseException, XmlParserException, IOException { |
elphinkuo/lightDroid | framework/util/jsonparser/JsonParserHttpApi.java | // Path: framework/util/http/HttpApiWithBasicAuth.java
// public class HttpApiWithBasicAuth extends AbstractHttpApi {
//
// private HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
//
// @Override
// public void process(final HttpRequest request, final HttpContext context)
// throws HttpException, IOException {
//
// AuthState authState = (AuthState) context
// .getAttribute(ClientContext.TARGET_AUTH_STATE);
// CredentialsProvider credsProvider = (CredentialsProvider) context
// .getAttribute(ClientContext.CREDS_PROVIDER);
// HttpHost targetHost = (HttpHost) context
// .getAttribute(ExecutionContext.HTTP_TARGET_HOST);
//
// // If not auth scheme has been initialized yet
// if (authState.getAuthScheme() == null) {
// AuthScope authScope = new AuthScope(targetHost.getHostName(),
// targetHost.getPort());
// // Obtain credentials matching the target host
// org.apache.http.auth.Credentials creds = credsProvider
// .getCredentials(authScope);
// // If found, generate BasicScheme preemptively
// if (creds != null) {
// authState.setAuthScheme(new BasicScheme());
// authState.setCredentials(creds);
// }
// }
// }
//
// };
//
// public HttpApiWithBasicAuth(DefaultHttpClient httpClient,
// String clientVersion) {
// super(httpClient, clientVersion);
// httpClient.addRequestInterceptor(preemptiveAuth, 0);
// }
// }
//
// Path: framework/util/http/exception/AuthorizationException.java
// public class AuthorizationException extends XmlParserException {
// private static final long serialVersionUID = 1L;
//
// public AuthorizationException(String message) {
// super(message);
// }
//
// }
//
// Path: framework/util/http/exception/XmlParserException.java
// public class XmlParserException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 3789211073927189813L;
// private String mExtra;
//
// public XmlParserException(String errorMessage) {
// super(errorMessage);
// }
//
// public XmlParserException(String errorMessage, String extra) {
// super(errorMessage);
// mExtra = extra;
// }
//
// public String getExtra() {
// return mExtra;
// }
// }
//
// Path: framework/util/http/exception/XmlParserParseException.java
// public class XmlParserParseException extends XmlParserException {
//
// /**
// *
// */
// private static final long serialVersionUID = 3857089504256300868L;
//
// public XmlParserParseException(String errorMessage) {
// super(errorMessage);
// }
// }
| import com.elphin.framework.util.http.HttpApiWithBasicAuth;
import com.elphin.framework.util.http.exception.AuthorizationException;
import com.elphin.framework.util.http.exception.XmlParserException;
import com.elphin.framework.util.http.exception.XmlParserParseException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream; | package com.elphin.framework.util.jsonparser;
public class JsonParserHttpApi extends HttpApiWithBasicAuth {
public JsonParserHttpApi(DefaultHttpClient httpClient, String clientVersion) {
super(httpClient, clientVersion);
}
public BaseObject analysisInputStreamToObject(InputStream inputStream, Parser<? extends BaseObject> parser,
String encodeing) throws JSONException, IOException, Exception {
return parser.parse(BaseParser.createJSONParser(inputStream, encodeing));
}
public BaseObject analysisHttpResponseToObject(HttpResponse response, Parser<? extends BaseObject> parser, | // Path: framework/util/http/HttpApiWithBasicAuth.java
// public class HttpApiWithBasicAuth extends AbstractHttpApi {
//
// private HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
//
// @Override
// public void process(final HttpRequest request, final HttpContext context)
// throws HttpException, IOException {
//
// AuthState authState = (AuthState) context
// .getAttribute(ClientContext.TARGET_AUTH_STATE);
// CredentialsProvider credsProvider = (CredentialsProvider) context
// .getAttribute(ClientContext.CREDS_PROVIDER);
// HttpHost targetHost = (HttpHost) context
// .getAttribute(ExecutionContext.HTTP_TARGET_HOST);
//
// // If not auth scheme has been initialized yet
// if (authState.getAuthScheme() == null) {
// AuthScope authScope = new AuthScope(targetHost.getHostName(),
// targetHost.getPort());
// // Obtain credentials matching the target host
// org.apache.http.auth.Credentials creds = credsProvider
// .getCredentials(authScope);
// // If found, generate BasicScheme preemptively
// if (creds != null) {
// authState.setAuthScheme(new BasicScheme());
// authState.setCredentials(creds);
// }
// }
// }
//
// };
//
// public HttpApiWithBasicAuth(DefaultHttpClient httpClient,
// String clientVersion) {
// super(httpClient, clientVersion);
// httpClient.addRequestInterceptor(preemptiveAuth, 0);
// }
// }
//
// Path: framework/util/http/exception/AuthorizationException.java
// public class AuthorizationException extends XmlParserException {
// private static final long serialVersionUID = 1L;
//
// public AuthorizationException(String message) {
// super(message);
// }
//
// }
//
// Path: framework/util/http/exception/XmlParserException.java
// public class XmlParserException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 3789211073927189813L;
// private String mExtra;
//
// public XmlParserException(String errorMessage) {
// super(errorMessage);
// }
//
// public XmlParserException(String errorMessage, String extra) {
// super(errorMessage);
// mExtra = extra;
// }
//
// public String getExtra() {
// return mExtra;
// }
// }
//
// Path: framework/util/http/exception/XmlParserParseException.java
// public class XmlParserParseException extends XmlParserException {
//
// /**
// *
// */
// private static final long serialVersionUID = 3857089504256300868L;
//
// public XmlParserParseException(String errorMessage) {
// super(errorMessage);
// }
// }
// Path: framework/util/jsonparser/JsonParserHttpApi.java
import com.elphin.framework.util.http.HttpApiWithBasicAuth;
import com.elphin.framework.util.http.exception.AuthorizationException;
import com.elphin.framework.util.http.exception.XmlParserException;
import com.elphin.framework.util.http.exception.XmlParserParseException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
package com.elphin.framework.util.jsonparser;
public class JsonParserHttpApi extends HttpApiWithBasicAuth {
public JsonParserHttpApi(DefaultHttpClient httpClient, String clientVersion) {
super(httpClient, clientVersion);
}
public BaseObject analysisInputStreamToObject(InputStream inputStream, Parser<? extends BaseObject> parser,
String encodeing) throws JSONException, IOException, Exception {
return parser.parse(BaseParser.createJSONParser(inputStream, encodeing));
}
public BaseObject analysisHttpResponseToObject(HttpResponse response, Parser<? extends BaseObject> parser, | String encodeing) throws AuthorizationException, XmlParserParseException, XmlParserException, IOException { |
elphinkuo/lightDroid | framework/app/fpstack/BaseTask.java | // Path: framework/app/ActivityLifecycleCallbacks.java
// public interface ActivityLifecycleCallbacks {
// abstract void onActivityCreated(Activity activity, Bundle savedInstanceState);
// abstract void onActivityDestroyed(Activity activity);
// abstract void onActivityPaused(Activity activity);
// abstract void onActivityResumed(Activity activity);
// abstract void onActivitySaveInstanceState(Activity activity, Bundle outState);
// abstract void onActivityStarted(Activity activity);
// abstract void onActivityStopped(Activity activity);
// }
| import android.app.ActivityManager;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.Window;
import com.baidu.BaiduMap.R;
import com.elphin.framework.app.ActivityLifecycleCallbacks;
import de.greenrobot.event.EventBus;
import java.util.ArrayList;
import java.util.Stack; | package com.elphin.framework.app.fpstack;
/**
* Task的基类实现,以FragmentActivity作为载体,子页面用Fragment实现
* </p>
*
* @version 1.0
* @author elphinkuo
* @date 13-5-26 下午3:53
*/
public abstract class BaseTask extends FragmentActivity implements Task {
private static final boolean DEBUG = false;
private static final String TAG = BaseTask.class.getSimpleName();
private String taskTag; | // Path: framework/app/ActivityLifecycleCallbacks.java
// public interface ActivityLifecycleCallbacks {
// abstract void onActivityCreated(Activity activity, Bundle savedInstanceState);
// abstract void onActivityDestroyed(Activity activity);
// abstract void onActivityPaused(Activity activity);
// abstract void onActivityResumed(Activity activity);
// abstract void onActivitySaveInstanceState(Activity activity, Bundle outState);
// abstract void onActivityStarted(Activity activity);
// abstract void onActivityStopped(Activity activity);
// }
// Path: framework/app/fpstack/BaseTask.java
import android.app.ActivityManager;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.Window;
import com.baidu.BaiduMap.R;
import com.elphin.framework.app.ActivityLifecycleCallbacks;
import de.greenrobot.event.EventBus;
import java.util.ArrayList;
import java.util.Stack;
package com.elphin.framework.app.fpstack;
/**
* Task的基类实现,以FragmentActivity作为载体,子页面用Fragment实现
* </p>
*
* @version 1.0
* @author elphinkuo
* @date 13-5-26 下午3:53
*/
public abstract class BaseTask extends FragmentActivity implements Task {
private static final boolean DEBUG = false;
private static final String TAG = BaseTask.class.getSimpleName();
private String taskTag; | protected ActivityLifecycleCallbacks activityLifecycleCallbacks; |
Nulltilus/Appmatic-Android | app/src/main/java/com/appmatic/baseapp/main/MainView.java | // Path: app/src/main/java/com/appmatic/baseapp/api/models/AppContent.java
// public class AppContent {
// private int content_id;
// private ArrayList<Content> contents;
// private String icon_id;
// private String name;
// private int position;
//
// public AppContent(int content_id) {
// this.content_id = content_id;
// }
//
// public AppContent(int content_id, int position, String name, String icon_id, ArrayList<Content> contents) {
// this.content_id = content_id;
// this.position = position;
// this.name = name;
// this.icon_id = icon_id;
// this.contents = contents;
// }
//
// public int getContent_id() {
// return this.content_id;
// }
//
// public void setContent_id(int content_id) {
// this.content_id = content_id;
// }
//
// public int getPosition() {
// return this.position;
// }
//
// public void setPosition(int position) {
// this.position = position;
// }
//
// public String getName() {
// return this.name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getIcon_id() {
// return this.icon_id;
// }
//
// public void setIcon_id(String icon_id) {
// this.icon_id = icon_id;
// }
//
// public ArrayList<Content> getContents() {
// return this.contents;
// }
//
// public void setContents(ArrayList<Content> contents) {
// this.contents = contents;
// }
//
// public boolean equals(Object o) {
// return !(o == null || !(o instanceof AppContent)) && ((AppContent) o).getContent_id() == getContent_id();
// }
// }
//
// Path: app/src/main/java/com/appmatic/baseapp/api/models/ExtraInfo.java
// public class ExtraInfo {
// public static final String TYPE_CONTACT_ITEM = "TYPE_CONTACT_ITEM";
// public static final String TYPE_GALLERY_ITEM = "TYPE_GALLERY_ITEM";
//
// private boolean navigation_bar_colored;
// private String android_drawer_header_color;
// private String android_drawer_header_main_text;
// private String android_drawer_header_sub_text;
// private ArrayList<String> extra_items;
//
// public ExtraInfo() {
// }
//
// public ExtraInfo(boolean navigation_bar_colored, String android_drawer_header_color,
// String android_drawer_header_main_text, String android_drawer_header_sub_text, ArrayList<String> extra_items) {
// this.navigation_bar_colored = navigation_bar_colored;
// this.android_drawer_header_color = android_drawer_header_color;
// this.android_drawer_header_main_text = android_drawer_header_main_text;
// this.android_drawer_header_sub_text = android_drawer_header_sub_text;
// this.extra_items = extra_items;
// }
//
// public static String getTagByItemName(String itemName) {
// switch (itemName) {
// case TYPE_CONTACT_ITEM:
// return ContactFragment.class.toString();
// default:
// return "";
// }
// }
//
// public ArrayList<String> getExtra_items() {
// return extra_items;
// }
//
// public void setExtra_items(ArrayList<String> extra_items) {
// this.extra_items = extra_items;
// }
//
// public boolean isNavigation_bar_colored() {
// return navigation_bar_colored;
// }
//
// public void setNavigation_bar_colored(boolean navigation_bar_colored) {
// this.navigation_bar_colored = navigation_bar_colored;
// }
//
// public String getAndroid_drawer_header_color() {
// return android_drawer_header_color;
// }
//
// public void setAndroid_drawer_header_color(String android_drawer_header_color) {
// this.android_drawer_header_color = android_drawer_header_color;
// }
//
// public String getAndroid_drawer_header_main_text() {
// return android_drawer_header_main_text;
// }
//
// public void setAndroid_drawer_header_main_text(String android_drawer_header_main_text) {
// this.android_drawer_header_main_text = android_drawer_header_main_text;
// }
//
// public String getAndroid_drawer_header_sub_text() {
// return android_drawer_header_sub_text;
// }
//
// public void setAndroid_drawer_header_sub_text(String android_drawer_header_sub_text) {
// this.android_drawer_header_sub_text = android_drawer_header_sub_text;
// }
// }
| import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import com.afollestad.materialdialogs.MaterialDialog;
import com.appmatic.baseapp.api.models.AppContent;
import com.appmatic.baseapp.api.models.ExtraInfo;
import java.util.ArrayList; | package com.appmatic.baseapp.main;
/**
* Appmatic
* Copyright (C) 2016 - Nulltilus
*
* This file is part of Appmatic.
*
* Appmatic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>.
*/
interface MainView {
void showProgress(String title, String message);
void hideProgress();
void handleInternetError(@Nullable MaterialDialog.SingleButtonCallback onPositiveCallback);
void hideErrorDialog();
| // Path: app/src/main/java/com/appmatic/baseapp/api/models/AppContent.java
// public class AppContent {
// private int content_id;
// private ArrayList<Content> contents;
// private String icon_id;
// private String name;
// private int position;
//
// public AppContent(int content_id) {
// this.content_id = content_id;
// }
//
// public AppContent(int content_id, int position, String name, String icon_id, ArrayList<Content> contents) {
// this.content_id = content_id;
// this.position = position;
// this.name = name;
// this.icon_id = icon_id;
// this.contents = contents;
// }
//
// public int getContent_id() {
// return this.content_id;
// }
//
// public void setContent_id(int content_id) {
// this.content_id = content_id;
// }
//
// public int getPosition() {
// return this.position;
// }
//
// public void setPosition(int position) {
// this.position = position;
// }
//
// public String getName() {
// return this.name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getIcon_id() {
// return this.icon_id;
// }
//
// public void setIcon_id(String icon_id) {
// this.icon_id = icon_id;
// }
//
// public ArrayList<Content> getContents() {
// return this.contents;
// }
//
// public void setContents(ArrayList<Content> contents) {
// this.contents = contents;
// }
//
// public boolean equals(Object o) {
// return !(o == null || !(o instanceof AppContent)) && ((AppContent) o).getContent_id() == getContent_id();
// }
// }
//
// Path: app/src/main/java/com/appmatic/baseapp/api/models/ExtraInfo.java
// public class ExtraInfo {
// public static final String TYPE_CONTACT_ITEM = "TYPE_CONTACT_ITEM";
// public static final String TYPE_GALLERY_ITEM = "TYPE_GALLERY_ITEM";
//
// private boolean navigation_bar_colored;
// private String android_drawer_header_color;
// private String android_drawer_header_main_text;
// private String android_drawer_header_sub_text;
// private ArrayList<String> extra_items;
//
// public ExtraInfo() {
// }
//
// public ExtraInfo(boolean navigation_bar_colored, String android_drawer_header_color,
// String android_drawer_header_main_text, String android_drawer_header_sub_text, ArrayList<String> extra_items) {
// this.navigation_bar_colored = navigation_bar_colored;
// this.android_drawer_header_color = android_drawer_header_color;
// this.android_drawer_header_main_text = android_drawer_header_main_text;
// this.android_drawer_header_sub_text = android_drawer_header_sub_text;
// this.extra_items = extra_items;
// }
//
// public static String getTagByItemName(String itemName) {
// switch (itemName) {
// case TYPE_CONTACT_ITEM:
// return ContactFragment.class.toString();
// default:
// return "";
// }
// }
//
// public ArrayList<String> getExtra_items() {
// return extra_items;
// }
//
// public void setExtra_items(ArrayList<String> extra_items) {
// this.extra_items = extra_items;
// }
//
// public boolean isNavigation_bar_colored() {
// return navigation_bar_colored;
// }
//
// public void setNavigation_bar_colored(boolean navigation_bar_colored) {
// this.navigation_bar_colored = navigation_bar_colored;
// }
//
// public String getAndroid_drawer_header_color() {
// return android_drawer_header_color;
// }
//
// public void setAndroid_drawer_header_color(String android_drawer_header_color) {
// this.android_drawer_header_color = android_drawer_header_color;
// }
//
// public String getAndroid_drawer_header_main_text() {
// return android_drawer_header_main_text;
// }
//
// public void setAndroid_drawer_header_main_text(String android_drawer_header_main_text) {
// this.android_drawer_header_main_text = android_drawer_header_main_text;
// }
//
// public String getAndroid_drawer_header_sub_text() {
// return android_drawer_header_sub_text;
// }
//
// public void setAndroid_drawer_header_sub_text(String android_drawer_header_sub_text) {
// this.android_drawer_header_sub_text = android_drawer_header_sub_text;
// }
// }
// Path: app/src/main/java/com/appmatic/baseapp/main/MainView.java
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import com.afollestad.materialdialogs.MaterialDialog;
import com.appmatic.baseapp.api.models.AppContent;
import com.appmatic.baseapp.api.models.ExtraInfo;
import java.util.ArrayList;
package com.appmatic.baseapp.main;
/**
* Appmatic
* Copyright (C) 2016 - Nulltilus
*
* This file is part of Appmatic.
*
* Appmatic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>.
*/
interface MainView {
void showProgress(String title, String message);
void hideProgress();
void handleInternetError(@Nullable MaterialDialog.SingleButtonCallback onPositiveCallback);
void hideErrorDialog();
| void updateAllContent(ArrayList<AppContent> appContents); |
Nulltilus/Appmatic-Android | app/src/main/java/com/appmatic/baseapp/main/MainView.java | // Path: app/src/main/java/com/appmatic/baseapp/api/models/AppContent.java
// public class AppContent {
// private int content_id;
// private ArrayList<Content> contents;
// private String icon_id;
// private String name;
// private int position;
//
// public AppContent(int content_id) {
// this.content_id = content_id;
// }
//
// public AppContent(int content_id, int position, String name, String icon_id, ArrayList<Content> contents) {
// this.content_id = content_id;
// this.position = position;
// this.name = name;
// this.icon_id = icon_id;
// this.contents = contents;
// }
//
// public int getContent_id() {
// return this.content_id;
// }
//
// public void setContent_id(int content_id) {
// this.content_id = content_id;
// }
//
// public int getPosition() {
// return this.position;
// }
//
// public void setPosition(int position) {
// this.position = position;
// }
//
// public String getName() {
// return this.name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getIcon_id() {
// return this.icon_id;
// }
//
// public void setIcon_id(String icon_id) {
// this.icon_id = icon_id;
// }
//
// public ArrayList<Content> getContents() {
// return this.contents;
// }
//
// public void setContents(ArrayList<Content> contents) {
// this.contents = contents;
// }
//
// public boolean equals(Object o) {
// return !(o == null || !(o instanceof AppContent)) && ((AppContent) o).getContent_id() == getContent_id();
// }
// }
//
// Path: app/src/main/java/com/appmatic/baseapp/api/models/ExtraInfo.java
// public class ExtraInfo {
// public static final String TYPE_CONTACT_ITEM = "TYPE_CONTACT_ITEM";
// public static final String TYPE_GALLERY_ITEM = "TYPE_GALLERY_ITEM";
//
// private boolean navigation_bar_colored;
// private String android_drawer_header_color;
// private String android_drawer_header_main_text;
// private String android_drawer_header_sub_text;
// private ArrayList<String> extra_items;
//
// public ExtraInfo() {
// }
//
// public ExtraInfo(boolean navigation_bar_colored, String android_drawer_header_color,
// String android_drawer_header_main_text, String android_drawer_header_sub_text, ArrayList<String> extra_items) {
// this.navigation_bar_colored = navigation_bar_colored;
// this.android_drawer_header_color = android_drawer_header_color;
// this.android_drawer_header_main_text = android_drawer_header_main_text;
// this.android_drawer_header_sub_text = android_drawer_header_sub_text;
// this.extra_items = extra_items;
// }
//
// public static String getTagByItemName(String itemName) {
// switch (itemName) {
// case TYPE_CONTACT_ITEM:
// return ContactFragment.class.toString();
// default:
// return "";
// }
// }
//
// public ArrayList<String> getExtra_items() {
// return extra_items;
// }
//
// public void setExtra_items(ArrayList<String> extra_items) {
// this.extra_items = extra_items;
// }
//
// public boolean isNavigation_bar_colored() {
// return navigation_bar_colored;
// }
//
// public void setNavigation_bar_colored(boolean navigation_bar_colored) {
// this.navigation_bar_colored = navigation_bar_colored;
// }
//
// public String getAndroid_drawer_header_color() {
// return android_drawer_header_color;
// }
//
// public void setAndroid_drawer_header_color(String android_drawer_header_color) {
// this.android_drawer_header_color = android_drawer_header_color;
// }
//
// public String getAndroid_drawer_header_main_text() {
// return android_drawer_header_main_text;
// }
//
// public void setAndroid_drawer_header_main_text(String android_drawer_header_main_text) {
// this.android_drawer_header_main_text = android_drawer_header_main_text;
// }
//
// public String getAndroid_drawer_header_sub_text() {
// return android_drawer_header_sub_text;
// }
//
// public void setAndroid_drawer_header_sub_text(String android_drawer_header_sub_text) {
// this.android_drawer_header_sub_text = android_drawer_header_sub_text;
// }
// }
| import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import com.afollestad.materialdialogs.MaterialDialog;
import com.appmatic.baseapp.api.models.AppContent;
import com.appmatic.baseapp.api.models.ExtraInfo;
import java.util.ArrayList; | package com.appmatic.baseapp.main;
/**
* Appmatic
* Copyright (C) 2016 - Nulltilus
*
* This file is part of Appmatic.
*
* Appmatic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>.
*/
interface MainView {
void showProgress(String title, String message);
void hideProgress();
void handleInternetError(@Nullable MaterialDialog.SingleButtonCallback onPositiveCallback);
void hideErrorDialog();
void updateAllContent(ArrayList<AppContent> appContents);
void handleFirstContentState(ArrayList<String> extraItems);
void restoreContent();
| // Path: app/src/main/java/com/appmatic/baseapp/api/models/AppContent.java
// public class AppContent {
// private int content_id;
// private ArrayList<Content> contents;
// private String icon_id;
// private String name;
// private int position;
//
// public AppContent(int content_id) {
// this.content_id = content_id;
// }
//
// public AppContent(int content_id, int position, String name, String icon_id, ArrayList<Content> contents) {
// this.content_id = content_id;
// this.position = position;
// this.name = name;
// this.icon_id = icon_id;
// this.contents = contents;
// }
//
// public int getContent_id() {
// return this.content_id;
// }
//
// public void setContent_id(int content_id) {
// this.content_id = content_id;
// }
//
// public int getPosition() {
// return this.position;
// }
//
// public void setPosition(int position) {
// this.position = position;
// }
//
// public String getName() {
// return this.name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getIcon_id() {
// return this.icon_id;
// }
//
// public void setIcon_id(String icon_id) {
// this.icon_id = icon_id;
// }
//
// public ArrayList<Content> getContents() {
// return this.contents;
// }
//
// public void setContents(ArrayList<Content> contents) {
// this.contents = contents;
// }
//
// public boolean equals(Object o) {
// return !(o == null || !(o instanceof AppContent)) && ((AppContent) o).getContent_id() == getContent_id();
// }
// }
//
// Path: app/src/main/java/com/appmatic/baseapp/api/models/ExtraInfo.java
// public class ExtraInfo {
// public static final String TYPE_CONTACT_ITEM = "TYPE_CONTACT_ITEM";
// public static final String TYPE_GALLERY_ITEM = "TYPE_GALLERY_ITEM";
//
// private boolean navigation_bar_colored;
// private String android_drawer_header_color;
// private String android_drawer_header_main_text;
// private String android_drawer_header_sub_text;
// private ArrayList<String> extra_items;
//
// public ExtraInfo() {
// }
//
// public ExtraInfo(boolean navigation_bar_colored, String android_drawer_header_color,
// String android_drawer_header_main_text, String android_drawer_header_sub_text, ArrayList<String> extra_items) {
// this.navigation_bar_colored = navigation_bar_colored;
// this.android_drawer_header_color = android_drawer_header_color;
// this.android_drawer_header_main_text = android_drawer_header_main_text;
// this.android_drawer_header_sub_text = android_drawer_header_sub_text;
// this.extra_items = extra_items;
// }
//
// public static String getTagByItemName(String itemName) {
// switch (itemName) {
// case TYPE_CONTACT_ITEM:
// return ContactFragment.class.toString();
// default:
// return "";
// }
// }
//
// public ArrayList<String> getExtra_items() {
// return extra_items;
// }
//
// public void setExtra_items(ArrayList<String> extra_items) {
// this.extra_items = extra_items;
// }
//
// public boolean isNavigation_bar_colored() {
// return navigation_bar_colored;
// }
//
// public void setNavigation_bar_colored(boolean navigation_bar_colored) {
// this.navigation_bar_colored = navigation_bar_colored;
// }
//
// public String getAndroid_drawer_header_color() {
// return android_drawer_header_color;
// }
//
// public void setAndroid_drawer_header_color(String android_drawer_header_color) {
// this.android_drawer_header_color = android_drawer_header_color;
// }
//
// public String getAndroid_drawer_header_main_text() {
// return android_drawer_header_main_text;
// }
//
// public void setAndroid_drawer_header_main_text(String android_drawer_header_main_text) {
// this.android_drawer_header_main_text = android_drawer_header_main_text;
// }
//
// public String getAndroid_drawer_header_sub_text() {
// return android_drawer_header_sub_text;
// }
//
// public void setAndroid_drawer_header_sub_text(String android_drawer_header_sub_text) {
// this.android_drawer_header_sub_text = android_drawer_header_sub_text;
// }
// }
// Path: app/src/main/java/com/appmatic/baseapp/main/MainView.java
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import com.afollestad.materialdialogs.MaterialDialog;
import com.appmatic.baseapp.api.models.AppContent;
import com.appmatic.baseapp.api.models.ExtraInfo;
import java.util.ArrayList;
package com.appmatic.baseapp.main;
/**
* Appmatic
* Copyright (C) 2016 - Nulltilus
*
* This file is part of Appmatic.
*
* Appmatic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>.
*/
interface MainView {
void showProgress(String title, String message);
void hideProgress();
void handleInternetError(@Nullable MaterialDialog.SingleButtonCallback onPositiveCallback);
void hideErrorDialog();
void updateAllContent(ArrayList<AppContent> appContents);
void handleFirstContentState(ArrayList<String> extraItems);
void restoreContent();
| void setUpRemainingContent(ExtraInfo extraInfo); |
Nulltilus/Appmatic-Android | app/src/main/java/com/appmatic/baseapp/gallery/GalleryInteractor.java | // Path: app/src/main/java/com/appmatic/baseapp/api/models/GalleryGroup.java
// public class GalleryGroup {
// private String title;
// private ArrayList<Image> images;
//
// public GalleryGroup() {
// }
//
// public GalleryGroup(String title, ArrayList<Image> images) {
// this.title = title;
// this.images = images;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public ArrayList<Image> getImages() {
// return images;
// }
//
// public void setImages(ArrayList<Image> images) {
// this.images = images;
// }
//
// public static class Image implements Parcelable {
// public static final Creator<Image> CREATOR = new Creator<Image>() {
// @Override
// public Image createFromParcel(Parcel in) {
// return new Image(in);
// }
//
// @Override
// public Image[] newArray(int size) {
// return new Image[size];
// }
// };
// private String url;
//
// public Image() {
// }
//
// public Image(String url) {
// this.url = url;
// }
//
// protected Image(Parcel in) {
// url = in.readString();
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel parcel, int i) {
// parcel.writeString(url);
// }
// }
// }
| import android.content.Context;
import android.support.annotation.NonNull;
import com.appmatic.baseapp.api.models.GalleryGroup;
import java.util.ArrayList; | package com.appmatic.baseapp.gallery;
/**
* Appmatic
* Copyright (C) 2016 - Nulltilus
*
* This file is part of Appmatic.
*
* Appmatic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>.
*/
interface GalleryInteractor {
void retrieveImages(@NonNull Context context, OnImagesReceivedListener onImagesReceivedListener);
interface OnImagesReceivedListener { | // Path: app/src/main/java/com/appmatic/baseapp/api/models/GalleryGroup.java
// public class GalleryGroup {
// private String title;
// private ArrayList<Image> images;
//
// public GalleryGroup() {
// }
//
// public GalleryGroup(String title, ArrayList<Image> images) {
// this.title = title;
// this.images = images;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public ArrayList<Image> getImages() {
// return images;
// }
//
// public void setImages(ArrayList<Image> images) {
// this.images = images;
// }
//
// public static class Image implements Parcelable {
// public static final Creator<Image> CREATOR = new Creator<Image>() {
// @Override
// public Image createFromParcel(Parcel in) {
// return new Image(in);
// }
//
// @Override
// public Image[] newArray(int size) {
// return new Image[size];
// }
// };
// private String url;
//
// public Image() {
// }
//
// public Image(String url) {
// this.url = url;
// }
//
// protected Image(Parcel in) {
// url = in.readString();
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel parcel, int i) {
// parcel.writeString(url);
// }
// }
// }
// Path: app/src/main/java/com/appmatic/baseapp/gallery/GalleryInteractor.java
import android.content.Context;
import android.support.annotation.NonNull;
import com.appmatic.baseapp.api.models.GalleryGroup;
import java.util.ArrayList;
package com.appmatic.baseapp.gallery;
/**
* Appmatic
* Copyright (C) 2016 - Nulltilus
*
* This file is part of Appmatic.
*
* Appmatic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>.
*/
interface GalleryInteractor {
void retrieveImages(@NonNull Context context, OnImagesReceivedListener onImagesReceivedListener);
interface OnImagesReceivedListener { | void onImagesReceived(ArrayList<GalleryGroup> groups); |
Nulltilus/Appmatic-Android | app/src/main/java/com/appmatic/baseapp/main/MainInteractor.java | // Path: app/src/main/java/com/appmatic/baseapp/api/models/AppContent.java
// public class AppContent {
// private int content_id;
// private ArrayList<Content> contents;
// private String icon_id;
// private String name;
// private int position;
//
// public AppContent(int content_id) {
// this.content_id = content_id;
// }
//
// public AppContent(int content_id, int position, String name, String icon_id, ArrayList<Content> contents) {
// this.content_id = content_id;
// this.position = position;
// this.name = name;
// this.icon_id = icon_id;
// this.contents = contents;
// }
//
// public int getContent_id() {
// return this.content_id;
// }
//
// public void setContent_id(int content_id) {
// this.content_id = content_id;
// }
//
// public int getPosition() {
// return this.position;
// }
//
// public void setPosition(int position) {
// this.position = position;
// }
//
// public String getName() {
// return this.name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getIcon_id() {
// return this.icon_id;
// }
//
// public void setIcon_id(String icon_id) {
// this.icon_id = icon_id;
// }
//
// public ArrayList<Content> getContents() {
// return this.contents;
// }
//
// public void setContents(ArrayList<Content> contents) {
// this.contents = contents;
// }
//
// public boolean equals(Object o) {
// return !(o == null || !(o instanceof AppContent)) && ((AppContent) o).getContent_id() == getContent_id();
// }
// }
//
// Path: app/src/main/java/com/appmatic/baseapp/api/models/ExtraInfo.java
// public class ExtraInfo {
// public static final String TYPE_CONTACT_ITEM = "TYPE_CONTACT_ITEM";
// public static final String TYPE_GALLERY_ITEM = "TYPE_GALLERY_ITEM";
//
// private boolean navigation_bar_colored;
// private String android_drawer_header_color;
// private String android_drawer_header_main_text;
// private String android_drawer_header_sub_text;
// private ArrayList<String> extra_items;
//
// public ExtraInfo() {
// }
//
// public ExtraInfo(boolean navigation_bar_colored, String android_drawer_header_color,
// String android_drawer_header_main_text, String android_drawer_header_sub_text, ArrayList<String> extra_items) {
// this.navigation_bar_colored = navigation_bar_colored;
// this.android_drawer_header_color = android_drawer_header_color;
// this.android_drawer_header_main_text = android_drawer_header_main_text;
// this.android_drawer_header_sub_text = android_drawer_header_sub_text;
// this.extra_items = extra_items;
// }
//
// public static String getTagByItemName(String itemName) {
// switch (itemName) {
// case TYPE_CONTACT_ITEM:
// return ContactFragment.class.toString();
// default:
// return "";
// }
// }
//
// public ArrayList<String> getExtra_items() {
// return extra_items;
// }
//
// public void setExtra_items(ArrayList<String> extra_items) {
// this.extra_items = extra_items;
// }
//
// public boolean isNavigation_bar_colored() {
// return navigation_bar_colored;
// }
//
// public void setNavigation_bar_colored(boolean navigation_bar_colored) {
// this.navigation_bar_colored = navigation_bar_colored;
// }
//
// public String getAndroid_drawer_header_color() {
// return android_drawer_header_color;
// }
//
// public void setAndroid_drawer_header_color(String android_drawer_header_color) {
// this.android_drawer_header_color = android_drawer_header_color;
// }
//
// public String getAndroid_drawer_header_main_text() {
// return android_drawer_header_main_text;
// }
//
// public void setAndroid_drawer_header_main_text(String android_drawer_header_main_text) {
// this.android_drawer_header_main_text = android_drawer_header_main_text;
// }
//
// public String getAndroid_drawer_header_sub_text() {
// return android_drawer_header_sub_text;
// }
//
// public void setAndroid_drawer_header_sub_text(String android_drawer_header_sub_text) {
// this.android_drawer_header_sub_text = android_drawer_header_sub_text;
// }
// }
| import android.content.Context;
import android.support.annotation.NonNull;
import com.appmatic.baseapp.api.models.AppContent;
import com.appmatic.baseapp.api.models.ExtraInfo;
import java.util.ArrayList; | package com.appmatic.baseapp.main;
/**
* Appmatic
* Copyright (C) 2016 - Nulltilus
*
* This file is part of Appmatic.
*
* Appmatic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>.
*/
interface MainInteractor {
void getData(@NonNull Context context, OnDataRetrievedListener dataListener);
void getExtraInfo(@NonNull Context context, OnExtraInfoListener extraItemsListener);
interface OnDataRetrievedListener { | // Path: app/src/main/java/com/appmatic/baseapp/api/models/AppContent.java
// public class AppContent {
// private int content_id;
// private ArrayList<Content> contents;
// private String icon_id;
// private String name;
// private int position;
//
// public AppContent(int content_id) {
// this.content_id = content_id;
// }
//
// public AppContent(int content_id, int position, String name, String icon_id, ArrayList<Content> contents) {
// this.content_id = content_id;
// this.position = position;
// this.name = name;
// this.icon_id = icon_id;
// this.contents = contents;
// }
//
// public int getContent_id() {
// return this.content_id;
// }
//
// public void setContent_id(int content_id) {
// this.content_id = content_id;
// }
//
// public int getPosition() {
// return this.position;
// }
//
// public void setPosition(int position) {
// this.position = position;
// }
//
// public String getName() {
// return this.name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getIcon_id() {
// return this.icon_id;
// }
//
// public void setIcon_id(String icon_id) {
// this.icon_id = icon_id;
// }
//
// public ArrayList<Content> getContents() {
// return this.contents;
// }
//
// public void setContents(ArrayList<Content> contents) {
// this.contents = contents;
// }
//
// public boolean equals(Object o) {
// return !(o == null || !(o instanceof AppContent)) && ((AppContent) o).getContent_id() == getContent_id();
// }
// }
//
// Path: app/src/main/java/com/appmatic/baseapp/api/models/ExtraInfo.java
// public class ExtraInfo {
// public static final String TYPE_CONTACT_ITEM = "TYPE_CONTACT_ITEM";
// public static final String TYPE_GALLERY_ITEM = "TYPE_GALLERY_ITEM";
//
// private boolean navigation_bar_colored;
// private String android_drawer_header_color;
// private String android_drawer_header_main_text;
// private String android_drawer_header_sub_text;
// private ArrayList<String> extra_items;
//
// public ExtraInfo() {
// }
//
// public ExtraInfo(boolean navigation_bar_colored, String android_drawer_header_color,
// String android_drawer_header_main_text, String android_drawer_header_sub_text, ArrayList<String> extra_items) {
// this.navigation_bar_colored = navigation_bar_colored;
// this.android_drawer_header_color = android_drawer_header_color;
// this.android_drawer_header_main_text = android_drawer_header_main_text;
// this.android_drawer_header_sub_text = android_drawer_header_sub_text;
// this.extra_items = extra_items;
// }
//
// public static String getTagByItemName(String itemName) {
// switch (itemName) {
// case TYPE_CONTACT_ITEM:
// return ContactFragment.class.toString();
// default:
// return "";
// }
// }
//
// public ArrayList<String> getExtra_items() {
// return extra_items;
// }
//
// public void setExtra_items(ArrayList<String> extra_items) {
// this.extra_items = extra_items;
// }
//
// public boolean isNavigation_bar_colored() {
// return navigation_bar_colored;
// }
//
// public void setNavigation_bar_colored(boolean navigation_bar_colored) {
// this.navigation_bar_colored = navigation_bar_colored;
// }
//
// public String getAndroid_drawer_header_color() {
// return android_drawer_header_color;
// }
//
// public void setAndroid_drawer_header_color(String android_drawer_header_color) {
// this.android_drawer_header_color = android_drawer_header_color;
// }
//
// public String getAndroid_drawer_header_main_text() {
// return android_drawer_header_main_text;
// }
//
// public void setAndroid_drawer_header_main_text(String android_drawer_header_main_text) {
// this.android_drawer_header_main_text = android_drawer_header_main_text;
// }
//
// public String getAndroid_drawer_header_sub_text() {
// return android_drawer_header_sub_text;
// }
//
// public void setAndroid_drawer_header_sub_text(String android_drawer_header_sub_text) {
// this.android_drawer_header_sub_text = android_drawer_header_sub_text;
// }
// }
// Path: app/src/main/java/com/appmatic/baseapp/main/MainInteractor.java
import android.content.Context;
import android.support.annotation.NonNull;
import com.appmatic.baseapp.api.models.AppContent;
import com.appmatic.baseapp.api.models.ExtraInfo;
import java.util.ArrayList;
package com.appmatic.baseapp.main;
/**
* Appmatic
* Copyright (C) 2016 - Nulltilus
*
* This file is part of Appmatic.
*
* Appmatic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>.
*/
interface MainInteractor {
void getData(@NonNull Context context, OnDataRetrievedListener dataListener);
void getExtraInfo(@NonNull Context context, OnExtraInfoListener extraItemsListener);
interface OnDataRetrievedListener { | void onDataReceived(ArrayList<AppContent> appContents); |
Nulltilus/Appmatic-Android | app/src/main/java/com/appmatic/baseapp/main/MainInteractor.java | // Path: app/src/main/java/com/appmatic/baseapp/api/models/AppContent.java
// public class AppContent {
// private int content_id;
// private ArrayList<Content> contents;
// private String icon_id;
// private String name;
// private int position;
//
// public AppContent(int content_id) {
// this.content_id = content_id;
// }
//
// public AppContent(int content_id, int position, String name, String icon_id, ArrayList<Content> contents) {
// this.content_id = content_id;
// this.position = position;
// this.name = name;
// this.icon_id = icon_id;
// this.contents = contents;
// }
//
// public int getContent_id() {
// return this.content_id;
// }
//
// public void setContent_id(int content_id) {
// this.content_id = content_id;
// }
//
// public int getPosition() {
// return this.position;
// }
//
// public void setPosition(int position) {
// this.position = position;
// }
//
// public String getName() {
// return this.name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getIcon_id() {
// return this.icon_id;
// }
//
// public void setIcon_id(String icon_id) {
// this.icon_id = icon_id;
// }
//
// public ArrayList<Content> getContents() {
// return this.contents;
// }
//
// public void setContents(ArrayList<Content> contents) {
// this.contents = contents;
// }
//
// public boolean equals(Object o) {
// return !(o == null || !(o instanceof AppContent)) && ((AppContent) o).getContent_id() == getContent_id();
// }
// }
//
// Path: app/src/main/java/com/appmatic/baseapp/api/models/ExtraInfo.java
// public class ExtraInfo {
// public static final String TYPE_CONTACT_ITEM = "TYPE_CONTACT_ITEM";
// public static final String TYPE_GALLERY_ITEM = "TYPE_GALLERY_ITEM";
//
// private boolean navigation_bar_colored;
// private String android_drawer_header_color;
// private String android_drawer_header_main_text;
// private String android_drawer_header_sub_text;
// private ArrayList<String> extra_items;
//
// public ExtraInfo() {
// }
//
// public ExtraInfo(boolean navigation_bar_colored, String android_drawer_header_color,
// String android_drawer_header_main_text, String android_drawer_header_sub_text, ArrayList<String> extra_items) {
// this.navigation_bar_colored = navigation_bar_colored;
// this.android_drawer_header_color = android_drawer_header_color;
// this.android_drawer_header_main_text = android_drawer_header_main_text;
// this.android_drawer_header_sub_text = android_drawer_header_sub_text;
// this.extra_items = extra_items;
// }
//
// public static String getTagByItemName(String itemName) {
// switch (itemName) {
// case TYPE_CONTACT_ITEM:
// return ContactFragment.class.toString();
// default:
// return "";
// }
// }
//
// public ArrayList<String> getExtra_items() {
// return extra_items;
// }
//
// public void setExtra_items(ArrayList<String> extra_items) {
// this.extra_items = extra_items;
// }
//
// public boolean isNavigation_bar_colored() {
// return navigation_bar_colored;
// }
//
// public void setNavigation_bar_colored(boolean navigation_bar_colored) {
// this.navigation_bar_colored = navigation_bar_colored;
// }
//
// public String getAndroid_drawer_header_color() {
// return android_drawer_header_color;
// }
//
// public void setAndroid_drawer_header_color(String android_drawer_header_color) {
// this.android_drawer_header_color = android_drawer_header_color;
// }
//
// public String getAndroid_drawer_header_main_text() {
// return android_drawer_header_main_text;
// }
//
// public void setAndroid_drawer_header_main_text(String android_drawer_header_main_text) {
// this.android_drawer_header_main_text = android_drawer_header_main_text;
// }
//
// public String getAndroid_drawer_header_sub_text() {
// return android_drawer_header_sub_text;
// }
//
// public void setAndroid_drawer_header_sub_text(String android_drawer_header_sub_text) {
// this.android_drawer_header_sub_text = android_drawer_header_sub_text;
// }
// }
| import android.content.Context;
import android.support.annotation.NonNull;
import com.appmatic.baseapp.api.models.AppContent;
import com.appmatic.baseapp.api.models.ExtraInfo;
import java.util.ArrayList; | package com.appmatic.baseapp.main;
/**
* Appmatic
* Copyright (C) 2016 - Nulltilus
*
* This file is part of Appmatic.
*
* Appmatic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>.
*/
interface MainInteractor {
void getData(@NonNull Context context, OnDataRetrievedListener dataListener);
void getExtraInfo(@NonNull Context context, OnExtraInfoListener extraItemsListener);
interface OnDataRetrievedListener {
void onDataReceived(ArrayList<AppContent> appContents);
void onDataReceivedError();
}
interface OnExtraInfoListener { | // Path: app/src/main/java/com/appmatic/baseapp/api/models/AppContent.java
// public class AppContent {
// private int content_id;
// private ArrayList<Content> contents;
// private String icon_id;
// private String name;
// private int position;
//
// public AppContent(int content_id) {
// this.content_id = content_id;
// }
//
// public AppContent(int content_id, int position, String name, String icon_id, ArrayList<Content> contents) {
// this.content_id = content_id;
// this.position = position;
// this.name = name;
// this.icon_id = icon_id;
// this.contents = contents;
// }
//
// public int getContent_id() {
// return this.content_id;
// }
//
// public void setContent_id(int content_id) {
// this.content_id = content_id;
// }
//
// public int getPosition() {
// return this.position;
// }
//
// public void setPosition(int position) {
// this.position = position;
// }
//
// public String getName() {
// return this.name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getIcon_id() {
// return this.icon_id;
// }
//
// public void setIcon_id(String icon_id) {
// this.icon_id = icon_id;
// }
//
// public ArrayList<Content> getContents() {
// return this.contents;
// }
//
// public void setContents(ArrayList<Content> contents) {
// this.contents = contents;
// }
//
// public boolean equals(Object o) {
// return !(o == null || !(o instanceof AppContent)) && ((AppContent) o).getContent_id() == getContent_id();
// }
// }
//
// Path: app/src/main/java/com/appmatic/baseapp/api/models/ExtraInfo.java
// public class ExtraInfo {
// public static final String TYPE_CONTACT_ITEM = "TYPE_CONTACT_ITEM";
// public static final String TYPE_GALLERY_ITEM = "TYPE_GALLERY_ITEM";
//
// private boolean navigation_bar_colored;
// private String android_drawer_header_color;
// private String android_drawer_header_main_text;
// private String android_drawer_header_sub_text;
// private ArrayList<String> extra_items;
//
// public ExtraInfo() {
// }
//
// public ExtraInfo(boolean navigation_bar_colored, String android_drawer_header_color,
// String android_drawer_header_main_text, String android_drawer_header_sub_text, ArrayList<String> extra_items) {
// this.navigation_bar_colored = navigation_bar_colored;
// this.android_drawer_header_color = android_drawer_header_color;
// this.android_drawer_header_main_text = android_drawer_header_main_text;
// this.android_drawer_header_sub_text = android_drawer_header_sub_text;
// this.extra_items = extra_items;
// }
//
// public static String getTagByItemName(String itemName) {
// switch (itemName) {
// case TYPE_CONTACT_ITEM:
// return ContactFragment.class.toString();
// default:
// return "";
// }
// }
//
// public ArrayList<String> getExtra_items() {
// return extra_items;
// }
//
// public void setExtra_items(ArrayList<String> extra_items) {
// this.extra_items = extra_items;
// }
//
// public boolean isNavigation_bar_colored() {
// return navigation_bar_colored;
// }
//
// public void setNavigation_bar_colored(boolean navigation_bar_colored) {
// this.navigation_bar_colored = navigation_bar_colored;
// }
//
// public String getAndroid_drawer_header_color() {
// return android_drawer_header_color;
// }
//
// public void setAndroid_drawer_header_color(String android_drawer_header_color) {
// this.android_drawer_header_color = android_drawer_header_color;
// }
//
// public String getAndroid_drawer_header_main_text() {
// return android_drawer_header_main_text;
// }
//
// public void setAndroid_drawer_header_main_text(String android_drawer_header_main_text) {
// this.android_drawer_header_main_text = android_drawer_header_main_text;
// }
//
// public String getAndroid_drawer_header_sub_text() {
// return android_drawer_header_sub_text;
// }
//
// public void setAndroid_drawer_header_sub_text(String android_drawer_header_sub_text) {
// this.android_drawer_header_sub_text = android_drawer_header_sub_text;
// }
// }
// Path: app/src/main/java/com/appmatic/baseapp/main/MainInteractor.java
import android.content.Context;
import android.support.annotation.NonNull;
import com.appmatic.baseapp.api.models.AppContent;
import com.appmatic.baseapp.api.models.ExtraInfo;
import java.util.ArrayList;
package com.appmatic.baseapp.main;
/**
* Appmatic
* Copyright (C) 2016 - Nulltilus
*
* This file is part of Appmatic.
*
* Appmatic is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* Appmatic 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 Appmatic. If not, see <http://www.gnu.org/licenses/>.
*/
interface MainInteractor {
void getData(@NonNull Context context, OnDataRetrievedListener dataListener);
void getExtraInfo(@NonNull Context context, OnExtraInfoListener extraItemsListener);
interface OnDataRetrievedListener {
void onDataReceived(ArrayList<AppContent> appContents);
void onDataReceivedError();
}
interface OnExtraInfoListener { | void onExtraInfoReceived(ExtraInfo extraInfo); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.