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 |
|---|---|---|---|---|---|---|
robotman3000/iCloud-Linux | iCloud Client/src/icloud/EventHandler.java | // Path: iCloud Client/src/icloud/event/CloudEvent.java
// public abstract class CloudEvent {
//
// }
//
// Path: iCloud Client/src/icloud/handler/CloudEventHandler.java
// public interface CloudEventHandler {
//
// public abstract void onEvent(CloudEvent evt);
// }
| import icloud.event.CloudEvent;
import icloud.handler.CloudEventHandler; | package icloud;
public interface EventHandler {
public void addEventHandler(CloudEventHandler evt);
| // Path: iCloud Client/src/icloud/event/CloudEvent.java
// public abstract class CloudEvent {
//
// }
//
// Path: iCloud Client/src/icloud/handler/CloudEventHandler.java
// public interface CloudEventHandler {
//
// public abstract void onEvent(CloudEvent evt);
// }
// Path: iCloud Client/src/icloud/EventHandler.java
import icloud.event.CloudEvent;
import icloud.handler.CloudEventHandler;
package icloud;
public interface EventHandler {
public void addEventHandler(CloudEventHandler evt);
| public void handleCloudEvent(CloudEvent evt); |
dsx-tech/blockchain-benchmarking | post-processing/src/main/java/uk/dsxt/bb/processing/CSVParser.java | // Path: post-processing/src/main/java/uk/dsxt/bb/model/BlockInfo.java
// @Data
// public class BlockInfo {
//
// private long blockId;
// private List<TransactionInfo> transactions;
// private long parentBlockId;
// private List<DistributionTime> distributionTimes;
// private long distributionTime95;
// private long distributionTime100;
// private long verificationTime;
// private int size;
// private long creationTime;
//
//
// public BlockInfo(long blockId, List<DistributionTime> distributionTimes) {
// this.blockId = blockId;
// this.distributionTimes = distributionTimes;
// this.transactions = new ArrayList<>();
// }
//
// public void calculateMaxTime() {
// List<Long> times = new ArrayList<>();
// for (DistributionTime distributionTime : distributionTimes) {
// times.add(distributionTime.getTime());
// }
// times.sort(Long::compareTo);
// distributionTime100 = times.get(times.size() - 1);
// distributionTime95 = times.get((int) (times.size() * 0.95 - 1));
// }
//
// public void addTransaction(TransactionInfo transaction) {
// transactions.add(transaction);
// }
//
// @Data
// public static class DistributionTime {
// private int nodeId;
// private long time;
//
// public DistributionTime(int nodeId, long time) {
// this.nodeId = nodeId;
// this.time = time;
// }
// }
// }
//
// Path: post-processing/src/main/java/uk/dsxt/bb/model/BlockchainInfo.java
// @Data
// public class BlockchainInfo {
//
// private Map<Long, BlockInfo> blocks;
// private Map<Long, TransactionInfo> transactions;
// private List<NodeInfo> nodes;
// private Map<Long, Integer> timeToIntensities;
// private Map<Long, Integer> timeToUnverifiedTransactions;
// private Map<Long, Integer> timeToNumNodes;
// private NavigableMap<Long, NavigableMap<Integer, TimeInfo>> timeInfos;
//
// public BlockchainInfo(Map<Long, BlockInfo> blocks, Map<Long, TransactionInfo> transactions, List<NodeInfo> nodes) {
// this.blocks = blocks;
// this.transactions = transactions;
// this.nodes = nodes;
// this.timeToIntensities = new HashMap<>();
// timeToUnverifiedTransactions = new HashMap<>();
// timeToNumNodes = new HashMap<>();
// timeInfos = new TreeMap<>();
// }
//
// public BlockInfo getChildBlockById(long id) {
// for (BlockInfo block : blocks.values()) {
// if (block.getParentBlockId() == id) {
// return block;
// }
// }
// return null;
// }
//
// // public TimeInfo getTimeInfoByTimeAndSize(long time, int size) {
// // for (TimeInfo timeInfo : timeInfos) {
// //
// // }
// // return null;
// // }
// }
//
// Path: post-processing/src/main/java/uk/dsxt/bb/model/NodeInfo.java
// @Data
// public class NodeInfo {
//
// private int nodeId;
// private List<TimeSpan> workTimes;
// private List<Long> startTimes;
// private List<Long> stopTimes;
//
// public NodeInfo(int nodeId) {
// this.nodeId = nodeId;
// this.startTimes = new ArrayList<>();
// this.stopTimes = new ArrayList<>();
// this.workTimes = new ArrayList<>();
// }
//
// public void addStartTime(Long time) {
// startTimes.add(time);
// }
//
// public void addStopTime(Long time) {
// stopTimes.add(time);
// }
//
// public void addWorkTime(TimeSpan time) {
// workTimes.add(time);
// }
//
// @Data
// public static class TimeSpan {
// private long startTime;
// private long endTime;
//
// public TimeSpan(long startTime, long endTime) {
// this.startTime = startTime;
// this.endTime = endTime;
// }
// }
// }
//
// Path: post-processing/src/main/java/uk/dsxt/bb/model/TransactionInfo.java
// @Data
// public class TransactionInfo {
//
// private long time;
// private long transactionId;
// private int transactionSize;
// private int nodeId;
// private int responseCode;
// private String responseMessage;
// private long blockId;
//
// public TransactionInfo(long time, long transactionId, int transactionSize,
// int nodeId, int responseCode, String responseMessage) {
// this.time = time;
// this.transactionId = transactionId;
// this.transactionSize = transactionSize;
// this.nodeId = nodeId;
// this.responseCode = responseCode;
// this.responseMessage = responseMessage;
// }
// }
| import au.com.bytecode.opencsv.CSVReader;
import lombok.extern.log4j.Log4j2;
import uk.dsxt.bb.model.BlockInfo;
import uk.dsxt.bb.model.BlockchainInfo;
import uk.dsxt.bb.model.NodeInfo;
import uk.dsxt.bb.model.TransactionInfo;
import java.io.FileReader;
import java.io.IOException;
import java.util.*; | /******************************************************************************
* Blockchain benchmarking framework *
* Copyright (C) 2017 DSX Technologies Limited. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************/
package uk.dsxt.bb.processing;
@Log4j2
public class CSVParser {
//input files
private static final String PATH = "post-processing/src/main/resources/";
private static final String LOAD_GENERATOR_FILE = "loadGeneratorOutput.csv";
private static final String BLOCK_DISTRIBUTION_FILE = "blockDistribution.csv";
private static final String NODES_FILE = "nodes.csv";
private static final String BLOCKCHAIN_INFO_FILE = "blockchainInfo.csv"; | // Path: post-processing/src/main/java/uk/dsxt/bb/model/BlockInfo.java
// @Data
// public class BlockInfo {
//
// private long blockId;
// private List<TransactionInfo> transactions;
// private long parentBlockId;
// private List<DistributionTime> distributionTimes;
// private long distributionTime95;
// private long distributionTime100;
// private long verificationTime;
// private int size;
// private long creationTime;
//
//
// public BlockInfo(long blockId, List<DistributionTime> distributionTimes) {
// this.blockId = blockId;
// this.distributionTimes = distributionTimes;
// this.transactions = new ArrayList<>();
// }
//
// public void calculateMaxTime() {
// List<Long> times = new ArrayList<>();
// for (DistributionTime distributionTime : distributionTimes) {
// times.add(distributionTime.getTime());
// }
// times.sort(Long::compareTo);
// distributionTime100 = times.get(times.size() - 1);
// distributionTime95 = times.get((int) (times.size() * 0.95 - 1));
// }
//
// public void addTransaction(TransactionInfo transaction) {
// transactions.add(transaction);
// }
//
// @Data
// public static class DistributionTime {
// private int nodeId;
// private long time;
//
// public DistributionTime(int nodeId, long time) {
// this.nodeId = nodeId;
// this.time = time;
// }
// }
// }
//
// Path: post-processing/src/main/java/uk/dsxt/bb/model/BlockchainInfo.java
// @Data
// public class BlockchainInfo {
//
// private Map<Long, BlockInfo> blocks;
// private Map<Long, TransactionInfo> transactions;
// private List<NodeInfo> nodes;
// private Map<Long, Integer> timeToIntensities;
// private Map<Long, Integer> timeToUnverifiedTransactions;
// private Map<Long, Integer> timeToNumNodes;
// private NavigableMap<Long, NavigableMap<Integer, TimeInfo>> timeInfos;
//
// public BlockchainInfo(Map<Long, BlockInfo> blocks, Map<Long, TransactionInfo> transactions, List<NodeInfo> nodes) {
// this.blocks = blocks;
// this.transactions = transactions;
// this.nodes = nodes;
// this.timeToIntensities = new HashMap<>();
// timeToUnverifiedTransactions = new HashMap<>();
// timeToNumNodes = new HashMap<>();
// timeInfos = new TreeMap<>();
// }
//
// public BlockInfo getChildBlockById(long id) {
// for (BlockInfo block : blocks.values()) {
// if (block.getParentBlockId() == id) {
// return block;
// }
// }
// return null;
// }
//
// // public TimeInfo getTimeInfoByTimeAndSize(long time, int size) {
// // for (TimeInfo timeInfo : timeInfos) {
// //
// // }
// // return null;
// // }
// }
//
// Path: post-processing/src/main/java/uk/dsxt/bb/model/NodeInfo.java
// @Data
// public class NodeInfo {
//
// private int nodeId;
// private List<TimeSpan> workTimes;
// private List<Long> startTimes;
// private List<Long> stopTimes;
//
// public NodeInfo(int nodeId) {
// this.nodeId = nodeId;
// this.startTimes = new ArrayList<>();
// this.stopTimes = new ArrayList<>();
// this.workTimes = new ArrayList<>();
// }
//
// public void addStartTime(Long time) {
// startTimes.add(time);
// }
//
// public void addStopTime(Long time) {
// stopTimes.add(time);
// }
//
// public void addWorkTime(TimeSpan time) {
// workTimes.add(time);
// }
//
// @Data
// public static class TimeSpan {
// private long startTime;
// private long endTime;
//
// public TimeSpan(long startTime, long endTime) {
// this.startTime = startTime;
// this.endTime = endTime;
// }
// }
// }
//
// Path: post-processing/src/main/java/uk/dsxt/bb/model/TransactionInfo.java
// @Data
// public class TransactionInfo {
//
// private long time;
// private long transactionId;
// private int transactionSize;
// private int nodeId;
// private int responseCode;
// private String responseMessage;
// private long blockId;
//
// public TransactionInfo(long time, long transactionId, int transactionSize,
// int nodeId, int responseCode, String responseMessage) {
// this.time = time;
// this.transactionId = transactionId;
// this.transactionSize = transactionSize;
// this.nodeId = nodeId;
// this.responseCode = responseCode;
// this.responseMessage = responseMessage;
// }
// }
// Path: post-processing/src/main/java/uk/dsxt/bb/processing/CSVParser.java
import au.com.bytecode.opencsv.CSVReader;
import lombok.extern.log4j.Log4j2;
import uk.dsxt.bb.model.BlockInfo;
import uk.dsxt.bb.model.BlockchainInfo;
import uk.dsxt.bb.model.NodeInfo;
import uk.dsxt.bb.model.TransactionInfo;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
/******************************************************************************
* Blockchain benchmarking framework *
* Copyright (C) 2017 DSX Technologies Limited. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************/
package uk.dsxt.bb.processing;
@Log4j2
public class CSVParser {
//input files
private static final String PATH = "post-processing/src/main/resources/";
private static final String LOAD_GENERATOR_FILE = "loadGeneratorOutput.csv";
private static final String BLOCK_DISTRIBUTION_FILE = "blockDistribution.csv";
private static final String NODES_FILE = "nodes.csv";
private static final String BLOCKCHAIN_INFO_FILE = "blockchainInfo.csv"; | private BlockchainInfo blockchainInfo; |
dsx-tech/blockchain-benchmarking | load-generator/src/main/java/uk/dsxt/bb/loadgenerator/LoadGeneratorMain.java | // Path: load-generator/src/main/java/uk/dsxt/bb/loadgenerator/data/Credential.java
// @Data
// public class Credential {
// private final String account;
// private final String password;
// }
//
// Path: test-manager/src/main/java/uk/dsxt/bb/remote/instance/WorkFinishedTO.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public class WorkFinishedTO {
// private String ip;
// }
| import uk.dsxt.bb.remote.instance.WorkFinishedTO;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import lombok.extern.log4j.Log4j2;
import uk.dsxt.bb.loadgenerator.data.Credential; | /*
******************************************************************************
* Blockchain benchmarking framework *
* Copyright (C) 2016 DSX Technologies Limited. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************
*/
package uk.dsxt.bb.loadgenerator;
/**
* @author phd
*/
@Log4j2
public class LoadGeneratorMain {
public static void main(String[] args) throws IOException {
try {
if (args.length < 8) {
log.error("Incorrect arguments count in LoadGeneratorMain.main(). Need min 10. Actual args: {}", Arrays.toString(args));
return;
}
int amountOfTransactions = Integer.parseInt(args[0]);
int amountOfThreadsPerTarget = Integer.parseInt(args[1]);
int minLength = Integer.parseInt(args[2]);
int maxLength = Integer.parseInt(args[3]);
int delay = Integer.parseInt(args[4]);
String ip = args[5];
String masterHost = args[6];
String credentialsPath = args[7];
String blockchainType = args[8];
String blockchainPort = args[9];
List<String> targets = new ArrayList<>();
targets.addAll(Arrays.asList(args).subList(10, args.length));
| // Path: load-generator/src/main/java/uk/dsxt/bb/loadgenerator/data/Credential.java
// @Data
// public class Credential {
// private final String account;
// private final String password;
// }
//
// Path: test-manager/src/main/java/uk/dsxt/bb/remote/instance/WorkFinishedTO.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public class WorkFinishedTO {
// private String ip;
// }
// Path: load-generator/src/main/java/uk/dsxt/bb/loadgenerator/LoadGeneratorMain.java
import uk.dsxt.bb.remote.instance.WorkFinishedTO;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import lombok.extern.log4j.Log4j2;
import uk.dsxt.bb.loadgenerator.data.Credential;
/*
******************************************************************************
* Blockchain benchmarking framework *
* Copyright (C) 2016 DSX Technologies Limited. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************
*/
package uk.dsxt.bb.loadgenerator;
/**
* @author phd
*/
@Log4j2
public class LoadGeneratorMain {
public static void main(String[] args) throws IOException {
try {
if (args.length < 8) {
log.error("Incorrect arguments count in LoadGeneratorMain.main(). Need min 10. Actual args: {}", Arrays.toString(args));
return;
}
int amountOfTransactions = Integer.parseInt(args[0]);
int amountOfThreadsPerTarget = Integer.parseInt(args[1]);
int minLength = Integer.parseInt(args[2]);
int maxLength = Integer.parseInt(args[3]);
int delay = Integer.parseInt(args[4]);
String ip = args[5];
String masterHost = args[6];
String credentialsPath = args[7];
String blockchainType = args[8];
String blockchainPort = args[9];
List<String> targets = new ArrayList<>();
targets.addAll(Arrays.asList(args).subList(10, args.length));
| List<Credential> accounts = new ArrayList<>(); |
dsx-tech/blockchain-benchmarking | load-generator/src/main/java/uk/dsxt/bb/loadgenerator/LoadGeneratorMain.java | // Path: load-generator/src/main/java/uk/dsxt/bb/loadgenerator/data/Credential.java
// @Data
// public class Credential {
// private final String account;
// private final String password;
// }
//
// Path: test-manager/src/main/java/uk/dsxt/bb/remote/instance/WorkFinishedTO.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public class WorkFinishedTO {
// private String ip;
// }
| import uk.dsxt.bb.remote.instance.WorkFinishedTO;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import lombok.extern.log4j.Log4j2;
import uk.dsxt.bb.loadgenerator.data.Credential; | int minLength = Integer.parseInt(args[2]);
int maxLength = Integer.parseInt(args[3]);
int delay = Integer.parseInt(args[4]);
String ip = args[5];
String masterHost = args[6];
String credentialsPath = args[7];
String blockchainType = args[8];
String blockchainPort = args[9];
List<String> targets = new ArrayList<>();
targets.addAll(Arrays.asList(args).subList(10, args.length));
List<Credential> accounts = new ArrayList<>();
if (Paths.get(credentialsPath).toFile().exists()) {
Files.readAllLines(Paths.get(credentialsPath)).forEach(line -> {
String[] credential = line.split(" ");
if (credential.length != 2) {
log.error("Invalid credential: " + line);
return;
}
accounts.add(new Credential(credential[0], credential[1]));
}
);
}
LoadManager loadManager = new LoadManager(targets, accounts, amountOfTransactions, amountOfThreadsPerTarget, minLength, maxLength, delay, blockchainType, blockchainPort);
loadManager.start();
loadManager.waitCompletion();
log.info("Load generation finished, sending info to master node " + "http://" + masterHost + "/loadGenerator/state"); | // Path: load-generator/src/main/java/uk/dsxt/bb/loadgenerator/data/Credential.java
// @Data
// public class Credential {
// private final String account;
// private final String password;
// }
//
// Path: test-manager/src/main/java/uk/dsxt/bb/remote/instance/WorkFinishedTO.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public class WorkFinishedTO {
// private String ip;
// }
// Path: load-generator/src/main/java/uk/dsxt/bb/loadgenerator/LoadGeneratorMain.java
import uk.dsxt.bb.remote.instance.WorkFinishedTO;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import lombok.extern.log4j.Log4j2;
import uk.dsxt.bb.loadgenerator.data.Credential;
int minLength = Integer.parseInt(args[2]);
int maxLength = Integer.parseInt(args[3]);
int delay = Integer.parseInt(args[4]);
String ip = args[5];
String masterHost = args[6];
String credentialsPath = args[7];
String blockchainType = args[8];
String blockchainPort = args[9];
List<String> targets = new ArrayList<>();
targets.addAll(Arrays.asList(args).subList(10, args.length));
List<Credential> accounts = new ArrayList<>();
if (Paths.get(credentialsPath).toFile().exists()) {
Files.readAllLines(Paths.get(credentialsPath)).forEach(line -> {
String[] credential = line.split(" ");
if (credential.length != 2) {
log.error("Invalid credential: " + line);
return;
}
accounts.add(new Credential(credential[0], credential[1]));
}
);
}
LoadManager loadManager = new LoadManager(targets, accounts, amountOfTransactions, amountOfThreadsPerTarget, minLength, maxLength, delay, blockchainType, blockchainPort);
loadManager.start();
loadManager.waitCompletion();
log.info("Load generation finished, sending info to master node " + "http://" + masterHost + "/loadGenerator/state"); | WorkFinishedTO remoteInstanceStateTO = new WorkFinishedTO(ip); |
dsx-tech/blockchain-benchmarking | blockchain-api/src/main/java/uk/dsxt/bb/bitcoin/BitcoinManager.java | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Manager.java
// public interface Manager {
//
// String sendTransaction(String to, String from, long amount);
//
// String sendMessage(byte[] body);
// String sendMessage(String from, String to, String message);
//
// List<Message> getNewMessages();
//
// BlockchainBlock getBlock(long id) throws IOException;
//
// BlockchainPeer[] getPeers() throws IOException;
//
// BlockchainChainInfo getChain() throws IOException;
//
// void authorize(String user, String password);
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Message.java
// @Value
// public class Message {
//
// String id;
//
// String body;
//
// boolean isCommitted;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/utils/InternalLogicException.java
// public class InternalLogicException extends Exception {
//
// @Getter
// private final Object returnValue; // Unfortunately, generic class can not inherit Exception, so returnValue has not concrete type.
//
// public InternalLogicException(String message) {
// this(null, message);
// }
//
// public InternalLogicException(Object returnValue, String message) {
// super(message);
// this.returnValue = returnValue;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/utils/JSONRPCHelper.java
// @Log4j2
// public class JSONRPCHelper {
//
// public static AtomicInteger id = new AtomicInteger();
// public static HttpHelper httpHelper = new HttpHelper(120000, 120000);
//
// public static String post(String url, String method, Object... parameters) throws InternalLogicException {
// try {
//
// Gson gson = new Gson();
//
// JsonObject req = new JsonObject();
// req.addProperty("id", id);
// req.addProperty("method", method);
//
// JsonArray params = new JsonArray();
// if (parameters != null) {
// for (Object o : parameters) {
// params.add(gson.toJsonTree(o));
// }
// }
//
// req.add("params", params);
//
// String requestData = req.toString();
//
// String request = httpHelper.request(url, requestData, RequestType.POST);
// JsonParser parser = new JsonParser();
// JsonObject resp = (JsonObject) parser.parse(new StringReader(request));
// JsonElement result = resp.get("result");
// id.getAndIncrement();
// return result.toString();
// } catch (Exception e) {
// log.error("post method failed", e);
// }
// return null;
// }
//
// public static <T> T post(String url, String method, Class<T> tClass, Object... args) throws IOException {
// String post = null;
// try {
// post = JSONRPCHelper.post(url, method, args);
// } catch (InternalLogicException e) {
// log.error("Cannot post request to bitcoin node", e);
// }
// return new Gson().fromJson(post, (Type) tClass);
// }
//
// public static String postToSendTransactionEthereum(String url, String sender, String receiver, String amount)
// throws IOException {
//
// try {
// String params = String.format("{\"jsonrpc\":\"2.0\"," +
// "\"method\":\"eth_sendTransaction\",\"params\":[{\"from\":\"%s\",\"to\":\"%s\"," +
// "\"value\":\"%s\"}],\"id\":%s}",
// sender, receiver, amount, id);
// String responseString = httpHelper.request(url, params, RequestType.POST);
// ObjectMapper mapper = new ObjectMapper();
// JsonNode responseJson = mapper.readTree(responseString);
// return responseJson.get("result").textValue();
// } catch (Exception e) {
// log.error("Cannot run post method for sending transactions in Ethereum", e);
// }
//
// return Strings.EMPTY;
// }
//
// public static String postToSendMessageEthereum(String url, String sender, String receiver, String message, String amount)
// throws IOException {
// try {
// String params = String.format("{\"jsonrpc\":\"2.0\"," +
// "\"method\":\"eth_sendTransaction\",\"params\":[{\"from\":\"%s\",\"to\":\"%s\"," +
// "\"value\":\"%s\", \"data\":\"%s\"}],\"id\":%s}",
// sender, receiver, amount, "0x" + Hex.encodeHexString(message.getBytes()), id);
//
// String responseString = httpHelper.request(url, params, RequestType.POST);
// ObjectMapper mapper = new ObjectMapper();
// JsonNode responseJson = mapper.readTree(responseString);
// return responseJson.get("result").textValue();
// } catch (Exception e) {
// log.error("Cannot run post method for sending transactions in Ethereum", e);
// }
//
// return Strings.EMPTY;
// }
// }
| import uk.dsxt.bb.utils.JSONRPCHelper;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.logging.log4j.util.Strings;
import uk.dsxt.bb.blockchain.Manager;
import uk.dsxt.bb.blockchain.Message;
import uk.dsxt.bb.datamodel.bitcoin.*;
import uk.dsxt.bb.utils.InternalLogicException; | }
return null;
}
@Override
public String sendMessage(byte[] body) {
try {
return sendMessage(BITCOIN_WALLET_ADDRESS, body);
} catch (IOException e) {
log.error("Error while sending message", e);
}
return null;
}
@Override
public String sendMessage(String from, String to, String message) {
return null;
}
private String sendMessage(String address, byte[] body) throws IOException {
try {
return JSONRPCHelper.post(url, BitcoinMethods.SENDTOADDRESS.name().toLowerCase(),
address, BitcoinManager.toBigDecimal(body));
} catch (InternalLogicException e) {
log.error("Cannot send transaction", e);
}
return Strings.EMPTY;
}
@Override | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Manager.java
// public interface Manager {
//
// String sendTransaction(String to, String from, long amount);
//
// String sendMessage(byte[] body);
// String sendMessage(String from, String to, String message);
//
// List<Message> getNewMessages();
//
// BlockchainBlock getBlock(long id) throws IOException;
//
// BlockchainPeer[] getPeers() throws IOException;
//
// BlockchainChainInfo getChain() throws IOException;
//
// void authorize(String user, String password);
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Message.java
// @Value
// public class Message {
//
// String id;
//
// String body;
//
// boolean isCommitted;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/utils/InternalLogicException.java
// public class InternalLogicException extends Exception {
//
// @Getter
// private final Object returnValue; // Unfortunately, generic class can not inherit Exception, so returnValue has not concrete type.
//
// public InternalLogicException(String message) {
// this(null, message);
// }
//
// public InternalLogicException(Object returnValue, String message) {
// super(message);
// this.returnValue = returnValue;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/utils/JSONRPCHelper.java
// @Log4j2
// public class JSONRPCHelper {
//
// public static AtomicInteger id = new AtomicInteger();
// public static HttpHelper httpHelper = new HttpHelper(120000, 120000);
//
// public static String post(String url, String method, Object... parameters) throws InternalLogicException {
// try {
//
// Gson gson = new Gson();
//
// JsonObject req = new JsonObject();
// req.addProperty("id", id);
// req.addProperty("method", method);
//
// JsonArray params = new JsonArray();
// if (parameters != null) {
// for (Object o : parameters) {
// params.add(gson.toJsonTree(o));
// }
// }
//
// req.add("params", params);
//
// String requestData = req.toString();
//
// String request = httpHelper.request(url, requestData, RequestType.POST);
// JsonParser parser = new JsonParser();
// JsonObject resp = (JsonObject) parser.parse(new StringReader(request));
// JsonElement result = resp.get("result");
// id.getAndIncrement();
// return result.toString();
// } catch (Exception e) {
// log.error("post method failed", e);
// }
// return null;
// }
//
// public static <T> T post(String url, String method, Class<T> tClass, Object... args) throws IOException {
// String post = null;
// try {
// post = JSONRPCHelper.post(url, method, args);
// } catch (InternalLogicException e) {
// log.error("Cannot post request to bitcoin node", e);
// }
// return new Gson().fromJson(post, (Type) tClass);
// }
//
// public static String postToSendTransactionEthereum(String url, String sender, String receiver, String amount)
// throws IOException {
//
// try {
// String params = String.format("{\"jsonrpc\":\"2.0\"," +
// "\"method\":\"eth_sendTransaction\",\"params\":[{\"from\":\"%s\",\"to\":\"%s\"," +
// "\"value\":\"%s\"}],\"id\":%s}",
// sender, receiver, amount, id);
// String responseString = httpHelper.request(url, params, RequestType.POST);
// ObjectMapper mapper = new ObjectMapper();
// JsonNode responseJson = mapper.readTree(responseString);
// return responseJson.get("result").textValue();
// } catch (Exception e) {
// log.error("Cannot run post method for sending transactions in Ethereum", e);
// }
//
// return Strings.EMPTY;
// }
//
// public static String postToSendMessageEthereum(String url, String sender, String receiver, String message, String amount)
// throws IOException {
// try {
// String params = String.format("{\"jsonrpc\":\"2.0\"," +
// "\"method\":\"eth_sendTransaction\",\"params\":[{\"from\":\"%s\",\"to\":\"%s\"," +
// "\"value\":\"%s\", \"data\":\"%s\"}],\"id\":%s}",
// sender, receiver, amount, "0x" + Hex.encodeHexString(message.getBytes()), id);
//
// String responseString = httpHelper.request(url, params, RequestType.POST);
// ObjectMapper mapper = new ObjectMapper();
// JsonNode responseJson = mapper.readTree(responseString);
// return responseJson.get("result").textValue();
// } catch (Exception e) {
// log.error("Cannot run post method for sending transactions in Ethereum", e);
// }
//
// return Strings.EMPTY;
// }
// }
// Path: blockchain-api/src/main/java/uk/dsxt/bb/bitcoin/BitcoinManager.java
import uk.dsxt.bb.utils.JSONRPCHelper;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.logging.log4j.util.Strings;
import uk.dsxt.bb.blockchain.Manager;
import uk.dsxt.bb.blockchain.Message;
import uk.dsxt.bb.datamodel.bitcoin.*;
import uk.dsxt.bb.utils.InternalLogicException;
}
return null;
}
@Override
public String sendMessage(byte[] body) {
try {
return sendMessage(BITCOIN_WALLET_ADDRESS, body);
} catch (IOException e) {
log.error("Error while sending message", e);
}
return null;
}
@Override
public String sendMessage(String from, String to, String message) {
return null;
}
private String sendMessage(String address, byte[] body) throws IOException {
try {
return JSONRPCHelper.post(url, BitcoinMethods.SENDTOADDRESS.name().toLowerCase(),
address, BitcoinManager.toBigDecimal(body));
} catch (InternalLogicException e) {
log.error("Cannot send transaction", e);
}
return Strings.EMPTY;
}
@Override | public List<Message> getNewMessages() { |
dsx-tech/blockchain-benchmarking | blockchain-api/src/main/java/uk/dsxt/bb/eris/ErisManager.java | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Manager.java
// public interface Manager {
//
// String sendTransaction(String to, String from, long amount);
//
// String sendMessage(byte[] body);
// String sendMessage(String from, String to, String message);
//
// List<Message> getNewMessages();
//
// BlockchainBlock getBlock(long id) throws IOException;
//
// BlockchainPeer[] getPeers() throws IOException;
//
// BlockchainChainInfo getChain() throws IOException;
//
// void authorize(String user, String password);
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Message.java
// @Value
// public class Message {
//
// String id;
//
// String body;
//
// boolean isCommitted;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainPeer.java
// public interface BlockchainPeer {
// String id = Strings.EMPTY;
// String address = Strings.EMPTY;
//
// default String getId() {
// return id;
// }
//
// default String getAddress() {
// return address;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/eris/ErisBlock.java
// @Value
// public class ErisBlock implements BlockchainBlock {
// int min_height;
// int max_height;
// private List<ErisBlockMeta> block_metas = null;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/eris/ErisChainInfo.java
// @Value
// public class ErisChainInfo implements BlockchainChainInfo {
// String chain_id;
// String genesis_hash;
// long latest_block_height;
//
// @Override
// public long getLastBlockNumber() {
// return latest_block_height;
// }
// }
| import com.google.gson.Gson;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import uk.dsxt.bb.blockchain.Manager;
import uk.dsxt.bb.blockchain.Message;
import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo;
import uk.dsxt.bb.datamodel.blockchain.BlockchainPeer;
import uk.dsxt.bb.datamodel.eris.ErisBlock;
import uk.dsxt.bb.datamodel.eris.ErisChainInfo;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List; | connection.setDoOutput(true);
connection.setRequestProperty("Content-Length", String.valueOf(data.length()));
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(data);
wr.flush();
wr.close();
}
int responseCode = connection.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
public String sendMessage(String from, String to, String message) {
return null;
}
@Override | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Manager.java
// public interface Manager {
//
// String sendTransaction(String to, String from, long amount);
//
// String sendMessage(byte[] body);
// String sendMessage(String from, String to, String message);
//
// List<Message> getNewMessages();
//
// BlockchainBlock getBlock(long id) throws IOException;
//
// BlockchainPeer[] getPeers() throws IOException;
//
// BlockchainChainInfo getChain() throws IOException;
//
// void authorize(String user, String password);
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Message.java
// @Value
// public class Message {
//
// String id;
//
// String body;
//
// boolean isCommitted;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainPeer.java
// public interface BlockchainPeer {
// String id = Strings.EMPTY;
// String address = Strings.EMPTY;
//
// default String getId() {
// return id;
// }
//
// default String getAddress() {
// return address;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/eris/ErisBlock.java
// @Value
// public class ErisBlock implements BlockchainBlock {
// int min_height;
// int max_height;
// private List<ErisBlockMeta> block_metas = null;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/eris/ErisChainInfo.java
// @Value
// public class ErisChainInfo implements BlockchainChainInfo {
// String chain_id;
// String genesis_hash;
// long latest_block_height;
//
// @Override
// public long getLastBlockNumber() {
// return latest_block_height;
// }
// }
// Path: blockchain-api/src/main/java/uk/dsxt/bb/eris/ErisManager.java
import com.google.gson.Gson;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import uk.dsxt.bb.blockchain.Manager;
import uk.dsxt.bb.blockchain.Message;
import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo;
import uk.dsxt.bb.datamodel.blockchain.BlockchainPeer;
import uk.dsxt.bb.datamodel.eris.ErisBlock;
import uk.dsxt.bb.datamodel.eris.ErisChainInfo;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
connection.setDoOutput(true);
connection.setRequestProperty("Content-Length", String.valueOf(data.length()));
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(data);
wr.flush();
wr.close();
}
int responseCode = connection.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
public String sendMessage(String from, String to, String message) {
return null;
}
@Override | public List<Message> getNewMessages() { |
dsx-tech/blockchain-benchmarking | blockchain-api/src/main/java/uk/dsxt/bb/eris/ErisManager.java | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Manager.java
// public interface Manager {
//
// String sendTransaction(String to, String from, long amount);
//
// String sendMessage(byte[] body);
// String sendMessage(String from, String to, String message);
//
// List<Message> getNewMessages();
//
// BlockchainBlock getBlock(long id) throws IOException;
//
// BlockchainPeer[] getPeers() throws IOException;
//
// BlockchainChainInfo getChain() throws IOException;
//
// void authorize(String user, String password);
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Message.java
// @Value
// public class Message {
//
// String id;
//
// String body;
//
// boolean isCommitted;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainPeer.java
// public interface BlockchainPeer {
// String id = Strings.EMPTY;
// String address = Strings.EMPTY;
//
// default String getId() {
// return id;
// }
//
// default String getAddress() {
// return address;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/eris/ErisBlock.java
// @Value
// public class ErisBlock implements BlockchainBlock {
// int min_height;
// int max_height;
// private List<ErisBlockMeta> block_metas = null;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/eris/ErisChainInfo.java
// @Value
// public class ErisChainInfo implements BlockchainChainInfo {
// String chain_id;
// String genesis_hash;
// long latest_block_height;
//
// @Override
// public long getLastBlockNumber() {
// return latest_block_height;
// }
// }
| import com.google.gson.Gson;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import uk.dsxt.bb.blockchain.Manager;
import uk.dsxt.bb.blockchain.Message;
import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo;
import uk.dsxt.bb.datamodel.blockchain.BlockchainPeer;
import uk.dsxt.bb.datamodel.eris.ErisBlock;
import uk.dsxt.bb.datamodel.eris.ErisChainInfo;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List; | wr.close();
}
int responseCode = connection.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
public String sendMessage(String from, String to, String message) {
return null;
}
@Override
public List<Message> getNewMessages() {
return null;
}
@Override | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Manager.java
// public interface Manager {
//
// String sendTransaction(String to, String from, long amount);
//
// String sendMessage(byte[] body);
// String sendMessage(String from, String to, String message);
//
// List<Message> getNewMessages();
//
// BlockchainBlock getBlock(long id) throws IOException;
//
// BlockchainPeer[] getPeers() throws IOException;
//
// BlockchainChainInfo getChain() throws IOException;
//
// void authorize(String user, String password);
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Message.java
// @Value
// public class Message {
//
// String id;
//
// String body;
//
// boolean isCommitted;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainPeer.java
// public interface BlockchainPeer {
// String id = Strings.EMPTY;
// String address = Strings.EMPTY;
//
// default String getId() {
// return id;
// }
//
// default String getAddress() {
// return address;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/eris/ErisBlock.java
// @Value
// public class ErisBlock implements BlockchainBlock {
// int min_height;
// int max_height;
// private List<ErisBlockMeta> block_metas = null;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/eris/ErisChainInfo.java
// @Value
// public class ErisChainInfo implements BlockchainChainInfo {
// String chain_id;
// String genesis_hash;
// long latest_block_height;
//
// @Override
// public long getLastBlockNumber() {
// return latest_block_height;
// }
// }
// Path: blockchain-api/src/main/java/uk/dsxt/bb/eris/ErisManager.java
import com.google.gson.Gson;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import uk.dsxt.bb.blockchain.Manager;
import uk.dsxt.bb.blockchain.Message;
import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo;
import uk.dsxt.bb.datamodel.blockchain.BlockchainPeer;
import uk.dsxt.bb.datamodel.eris.ErisBlock;
import uk.dsxt.bb.datamodel.eris.ErisChainInfo;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
wr.close();
}
int responseCode = connection.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
public String sendMessage(String from, String to, String message) {
return null;
}
@Override
public List<Message> getNewMessages() {
return null;
}
@Override | public BlockchainBlock getBlock(long id) throws IOException { |
dsx-tech/blockchain-benchmarking | blockchain-api/src/main/java/uk/dsxt/bb/eris/ErisManager.java | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Manager.java
// public interface Manager {
//
// String sendTransaction(String to, String from, long amount);
//
// String sendMessage(byte[] body);
// String sendMessage(String from, String to, String message);
//
// List<Message> getNewMessages();
//
// BlockchainBlock getBlock(long id) throws IOException;
//
// BlockchainPeer[] getPeers() throws IOException;
//
// BlockchainChainInfo getChain() throws IOException;
//
// void authorize(String user, String password);
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Message.java
// @Value
// public class Message {
//
// String id;
//
// String body;
//
// boolean isCommitted;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainPeer.java
// public interface BlockchainPeer {
// String id = Strings.EMPTY;
// String address = Strings.EMPTY;
//
// default String getId() {
// return id;
// }
//
// default String getAddress() {
// return address;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/eris/ErisBlock.java
// @Value
// public class ErisBlock implements BlockchainBlock {
// int min_height;
// int max_height;
// private List<ErisBlockMeta> block_metas = null;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/eris/ErisChainInfo.java
// @Value
// public class ErisChainInfo implements BlockchainChainInfo {
// String chain_id;
// String genesis_hash;
// long latest_block_height;
//
// @Override
// public long getLastBlockNumber() {
// return latest_block_height;
// }
// }
| import com.google.gson.Gson;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import uk.dsxt.bb.blockchain.Manager;
import uk.dsxt.bb.blockchain.Message;
import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo;
import uk.dsxt.bb.datamodel.blockchain.BlockchainPeer;
import uk.dsxt.bb.datamodel.eris.ErisBlock;
import uk.dsxt.bb.datamodel.eris.ErisChainInfo;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List; | BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
public String sendMessage(String from, String to, String message) {
return null;
}
@Override
public List<Message> getNewMessages() {
return null;
}
@Override
public BlockchainBlock getBlock(long id) throws IOException {
try {
String block = Request.Get(url+String.format("/blockchain/blocks?q=height:%d", id)).execute().returnContent().asString();
System.out.println(block); | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Manager.java
// public interface Manager {
//
// String sendTransaction(String to, String from, long amount);
//
// String sendMessage(byte[] body);
// String sendMessage(String from, String to, String message);
//
// List<Message> getNewMessages();
//
// BlockchainBlock getBlock(long id) throws IOException;
//
// BlockchainPeer[] getPeers() throws IOException;
//
// BlockchainChainInfo getChain() throws IOException;
//
// void authorize(String user, String password);
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Message.java
// @Value
// public class Message {
//
// String id;
//
// String body;
//
// boolean isCommitted;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainPeer.java
// public interface BlockchainPeer {
// String id = Strings.EMPTY;
// String address = Strings.EMPTY;
//
// default String getId() {
// return id;
// }
//
// default String getAddress() {
// return address;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/eris/ErisBlock.java
// @Value
// public class ErisBlock implements BlockchainBlock {
// int min_height;
// int max_height;
// private List<ErisBlockMeta> block_metas = null;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/eris/ErisChainInfo.java
// @Value
// public class ErisChainInfo implements BlockchainChainInfo {
// String chain_id;
// String genesis_hash;
// long latest_block_height;
//
// @Override
// public long getLastBlockNumber() {
// return latest_block_height;
// }
// }
// Path: blockchain-api/src/main/java/uk/dsxt/bb/eris/ErisManager.java
import com.google.gson.Gson;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import uk.dsxt.bb.blockchain.Manager;
import uk.dsxt.bb.blockchain.Message;
import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo;
import uk.dsxt.bb.datamodel.blockchain.BlockchainPeer;
import uk.dsxt.bb.datamodel.eris.ErisBlock;
import uk.dsxt.bb.datamodel.eris.ErisChainInfo;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
public String sendMessage(String from, String to, String message) {
return null;
}
@Override
public List<Message> getNewMessages() {
return null;
}
@Override
public BlockchainBlock getBlock(long id) throws IOException {
try {
String block = Request.Get(url+String.format("/blockchain/blocks?q=height:%d", id)).execute().returnContent().asString();
System.out.println(block); | return new Gson().fromJson(block, ErisBlock.class); |
dsx-tech/blockchain-benchmarking | blockchain-api/src/main/java/uk/dsxt/bb/eris/ErisManager.java | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Manager.java
// public interface Manager {
//
// String sendTransaction(String to, String from, long amount);
//
// String sendMessage(byte[] body);
// String sendMessage(String from, String to, String message);
//
// List<Message> getNewMessages();
//
// BlockchainBlock getBlock(long id) throws IOException;
//
// BlockchainPeer[] getPeers() throws IOException;
//
// BlockchainChainInfo getChain() throws IOException;
//
// void authorize(String user, String password);
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Message.java
// @Value
// public class Message {
//
// String id;
//
// String body;
//
// boolean isCommitted;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainPeer.java
// public interface BlockchainPeer {
// String id = Strings.EMPTY;
// String address = Strings.EMPTY;
//
// default String getId() {
// return id;
// }
//
// default String getAddress() {
// return address;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/eris/ErisBlock.java
// @Value
// public class ErisBlock implements BlockchainBlock {
// int min_height;
// int max_height;
// private List<ErisBlockMeta> block_metas = null;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/eris/ErisChainInfo.java
// @Value
// public class ErisChainInfo implements BlockchainChainInfo {
// String chain_id;
// String genesis_hash;
// long latest_block_height;
//
// @Override
// public long getLastBlockNumber() {
// return latest_block_height;
// }
// }
| import com.google.gson.Gson;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import uk.dsxt.bb.blockchain.Manager;
import uk.dsxt.bb.blockchain.Message;
import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo;
import uk.dsxt.bb.datamodel.blockchain.BlockchainPeer;
import uk.dsxt.bb.datamodel.eris.ErisBlock;
import uk.dsxt.bb.datamodel.eris.ErisChainInfo;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List; | } catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
public String sendMessage(String from, String to, String message) {
return null;
}
@Override
public List<Message> getNewMessages() {
return null;
}
@Override
public BlockchainBlock getBlock(long id) throws IOException {
try {
String block = Request.Get(url+String.format("/blockchain/blocks?q=height:%d", id)).execute().returnContent().asString();
System.out.println(block);
return new Gson().fromJson(block, ErisBlock.class);
} catch (Exception e) {
log.error("Exc", e);
}
return null;
}
@Override | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Manager.java
// public interface Manager {
//
// String sendTransaction(String to, String from, long amount);
//
// String sendMessage(byte[] body);
// String sendMessage(String from, String to, String message);
//
// List<Message> getNewMessages();
//
// BlockchainBlock getBlock(long id) throws IOException;
//
// BlockchainPeer[] getPeers() throws IOException;
//
// BlockchainChainInfo getChain() throws IOException;
//
// void authorize(String user, String password);
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Message.java
// @Value
// public class Message {
//
// String id;
//
// String body;
//
// boolean isCommitted;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainPeer.java
// public interface BlockchainPeer {
// String id = Strings.EMPTY;
// String address = Strings.EMPTY;
//
// default String getId() {
// return id;
// }
//
// default String getAddress() {
// return address;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/eris/ErisBlock.java
// @Value
// public class ErisBlock implements BlockchainBlock {
// int min_height;
// int max_height;
// private List<ErisBlockMeta> block_metas = null;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/eris/ErisChainInfo.java
// @Value
// public class ErisChainInfo implements BlockchainChainInfo {
// String chain_id;
// String genesis_hash;
// long latest_block_height;
//
// @Override
// public long getLastBlockNumber() {
// return latest_block_height;
// }
// }
// Path: blockchain-api/src/main/java/uk/dsxt/bb/eris/ErisManager.java
import com.google.gson.Gson;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import uk.dsxt.bb.blockchain.Manager;
import uk.dsxt.bb.blockchain.Message;
import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo;
import uk.dsxt.bb.datamodel.blockchain.BlockchainPeer;
import uk.dsxt.bb.datamodel.eris.ErisBlock;
import uk.dsxt.bb.datamodel.eris.ErisChainInfo;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
public String sendMessage(String from, String to, String message) {
return null;
}
@Override
public List<Message> getNewMessages() {
return null;
}
@Override
public BlockchainBlock getBlock(long id) throws IOException {
try {
String block = Request.Get(url+String.format("/blockchain/blocks?q=height:%d", id)).execute().returnContent().asString();
System.out.println(block);
return new Gson().fromJson(block, ErisBlock.class);
} catch (Exception e) {
log.error("Exc", e);
}
return null;
}
@Override | public BlockchainPeer[] getPeers() throws IOException { |
dsx-tech/blockchain-benchmarking | blockchain-api/src/main/java/uk/dsxt/bb/eris/ErisManager.java | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Manager.java
// public interface Manager {
//
// String sendTransaction(String to, String from, long amount);
//
// String sendMessage(byte[] body);
// String sendMessage(String from, String to, String message);
//
// List<Message> getNewMessages();
//
// BlockchainBlock getBlock(long id) throws IOException;
//
// BlockchainPeer[] getPeers() throws IOException;
//
// BlockchainChainInfo getChain() throws IOException;
//
// void authorize(String user, String password);
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Message.java
// @Value
// public class Message {
//
// String id;
//
// String body;
//
// boolean isCommitted;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainPeer.java
// public interface BlockchainPeer {
// String id = Strings.EMPTY;
// String address = Strings.EMPTY;
//
// default String getId() {
// return id;
// }
//
// default String getAddress() {
// return address;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/eris/ErisBlock.java
// @Value
// public class ErisBlock implements BlockchainBlock {
// int min_height;
// int max_height;
// private List<ErisBlockMeta> block_metas = null;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/eris/ErisChainInfo.java
// @Value
// public class ErisChainInfo implements BlockchainChainInfo {
// String chain_id;
// String genesis_hash;
// long latest_block_height;
//
// @Override
// public long getLastBlockNumber() {
// return latest_block_height;
// }
// }
| import com.google.gson.Gson;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import uk.dsxt.bb.blockchain.Manager;
import uk.dsxt.bb.blockchain.Message;
import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo;
import uk.dsxt.bb.datamodel.blockchain.BlockchainPeer;
import uk.dsxt.bb.datamodel.eris.ErisBlock;
import uk.dsxt.bb.datamodel.eris.ErisChainInfo;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List; |
@Override
public String sendMessage(String from, String to, String message) {
return null;
}
@Override
public List<Message> getNewMessages() {
return null;
}
@Override
public BlockchainBlock getBlock(long id) throws IOException {
try {
String block = Request.Get(url+String.format("/blockchain/blocks?q=height:%d", id)).execute().returnContent().asString();
System.out.println(block);
return new Gson().fromJson(block, ErisBlock.class);
} catch (Exception e) {
log.error("Exc", e);
}
return null;
}
@Override
public BlockchainPeer[] getPeers() throws IOException {
return new BlockchainPeer[0];
}
@Override | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Manager.java
// public interface Manager {
//
// String sendTransaction(String to, String from, long amount);
//
// String sendMessage(byte[] body);
// String sendMessage(String from, String to, String message);
//
// List<Message> getNewMessages();
//
// BlockchainBlock getBlock(long id) throws IOException;
//
// BlockchainPeer[] getPeers() throws IOException;
//
// BlockchainChainInfo getChain() throws IOException;
//
// void authorize(String user, String password);
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Message.java
// @Value
// public class Message {
//
// String id;
//
// String body;
//
// boolean isCommitted;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainPeer.java
// public interface BlockchainPeer {
// String id = Strings.EMPTY;
// String address = Strings.EMPTY;
//
// default String getId() {
// return id;
// }
//
// default String getAddress() {
// return address;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/eris/ErisBlock.java
// @Value
// public class ErisBlock implements BlockchainBlock {
// int min_height;
// int max_height;
// private List<ErisBlockMeta> block_metas = null;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/eris/ErisChainInfo.java
// @Value
// public class ErisChainInfo implements BlockchainChainInfo {
// String chain_id;
// String genesis_hash;
// long latest_block_height;
//
// @Override
// public long getLastBlockNumber() {
// return latest_block_height;
// }
// }
// Path: blockchain-api/src/main/java/uk/dsxt/bb/eris/ErisManager.java
import com.google.gson.Gson;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import uk.dsxt.bb.blockchain.Manager;
import uk.dsxt.bb.blockchain.Message;
import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo;
import uk.dsxt.bb.datamodel.blockchain.BlockchainPeer;
import uk.dsxt.bb.datamodel.eris.ErisBlock;
import uk.dsxt.bb.datamodel.eris.ErisChainInfo;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
@Override
public String sendMessage(String from, String to, String message) {
return null;
}
@Override
public List<Message> getNewMessages() {
return null;
}
@Override
public BlockchainBlock getBlock(long id) throws IOException {
try {
String block = Request.Get(url+String.format("/blockchain/blocks?q=height:%d", id)).execute().returnContent().asString();
System.out.println(block);
return new Gson().fromJson(block, ErisBlock.class);
} catch (Exception e) {
log.error("Exc", e);
}
return null;
}
@Override
public BlockchainPeer[] getPeers() throws IOException {
return new BlockchainPeer[0];
}
@Override | public BlockchainChainInfo getChain() throws IOException { |
dsx-tech/blockchain-benchmarking | blockchain-api/src/main/java/uk/dsxt/bb/eris/ErisManager.java | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Manager.java
// public interface Manager {
//
// String sendTransaction(String to, String from, long amount);
//
// String sendMessage(byte[] body);
// String sendMessage(String from, String to, String message);
//
// List<Message> getNewMessages();
//
// BlockchainBlock getBlock(long id) throws IOException;
//
// BlockchainPeer[] getPeers() throws IOException;
//
// BlockchainChainInfo getChain() throws IOException;
//
// void authorize(String user, String password);
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Message.java
// @Value
// public class Message {
//
// String id;
//
// String body;
//
// boolean isCommitted;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainPeer.java
// public interface BlockchainPeer {
// String id = Strings.EMPTY;
// String address = Strings.EMPTY;
//
// default String getId() {
// return id;
// }
//
// default String getAddress() {
// return address;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/eris/ErisBlock.java
// @Value
// public class ErisBlock implements BlockchainBlock {
// int min_height;
// int max_height;
// private List<ErisBlockMeta> block_metas = null;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/eris/ErisChainInfo.java
// @Value
// public class ErisChainInfo implements BlockchainChainInfo {
// String chain_id;
// String genesis_hash;
// long latest_block_height;
//
// @Override
// public long getLastBlockNumber() {
// return latest_block_height;
// }
// }
| import com.google.gson.Gson;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import uk.dsxt.bb.blockchain.Manager;
import uk.dsxt.bb.blockchain.Message;
import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo;
import uk.dsxt.bb.datamodel.blockchain.BlockchainPeer;
import uk.dsxt.bb.datamodel.eris.ErisBlock;
import uk.dsxt.bb.datamodel.eris.ErisChainInfo;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List; | }
@Override
public List<Message> getNewMessages() {
return null;
}
@Override
public BlockchainBlock getBlock(long id) throws IOException {
try {
String block = Request.Get(url+String.format("/blockchain/blocks?q=height:%d", id)).execute().returnContent().asString();
System.out.println(block);
return new Gson().fromJson(block, ErisBlock.class);
} catch (Exception e) {
log.error("Exc", e);
}
return null;
}
@Override
public BlockchainPeer[] getPeers() throws IOException {
return new BlockchainPeer[0];
}
@Override
public BlockchainChainInfo getChain() throws IOException {
try {
String chain = Request.Get(url+"/blockchain").execute().returnContent().asString();
System.out.println(chain); | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Manager.java
// public interface Manager {
//
// String sendTransaction(String to, String from, long amount);
//
// String sendMessage(byte[] body);
// String sendMessage(String from, String to, String message);
//
// List<Message> getNewMessages();
//
// BlockchainBlock getBlock(long id) throws IOException;
//
// BlockchainPeer[] getPeers() throws IOException;
//
// BlockchainChainInfo getChain() throws IOException;
//
// void authorize(String user, String password);
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Message.java
// @Value
// public class Message {
//
// String id;
//
// String body;
//
// boolean isCommitted;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainPeer.java
// public interface BlockchainPeer {
// String id = Strings.EMPTY;
// String address = Strings.EMPTY;
//
// default String getId() {
// return id;
// }
//
// default String getAddress() {
// return address;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/eris/ErisBlock.java
// @Value
// public class ErisBlock implements BlockchainBlock {
// int min_height;
// int max_height;
// private List<ErisBlockMeta> block_metas = null;
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/eris/ErisChainInfo.java
// @Value
// public class ErisChainInfo implements BlockchainChainInfo {
// String chain_id;
// String genesis_hash;
// long latest_block_height;
//
// @Override
// public long getLastBlockNumber() {
// return latest_block_height;
// }
// }
// Path: blockchain-api/src/main/java/uk/dsxt/bb/eris/ErisManager.java
import com.google.gson.Gson;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import uk.dsxt.bb.blockchain.Manager;
import uk.dsxt.bb.blockchain.Message;
import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo;
import uk.dsxt.bb.datamodel.blockchain.BlockchainPeer;
import uk.dsxt.bb.datamodel.eris.ErisBlock;
import uk.dsxt.bb.datamodel.eris.ErisChainInfo;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
}
@Override
public List<Message> getNewMessages() {
return null;
}
@Override
public BlockchainBlock getBlock(long id) throws IOException {
try {
String block = Request.Get(url+String.format("/blockchain/blocks?q=height:%d", id)).execute().returnContent().asString();
System.out.println(block);
return new Gson().fromJson(block, ErisBlock.class);
} catch (Exception e) {
log.error("Exc", e);
}
return null;
}
@Override
public BlockchainPeer[] getPeers() throws IOException {
return new BlockchainPeer[0];
}
@Override
public BlockchainChainInfo getChain() throws IOException {
try {
String chain = Request.Get(url+"/blockchain").execute().returnContent().asString();
System.out.println(chain); | return new Gson().fromJson(chain, ErisChainInfo.class); |
dsx-tech/blockchain-benchmarking | blockchain-api/src/main/java/uk/dsxt/bb/fabric/FabricLogger.java | // Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricBlock.java
// @Getter
// public class FabricBlock implements BlockchainBlock {
// List<FabricTransaction> transactions;
// String stateHash;
// String previousBlockHash;
// String consensusMetadata;
// FabricNonHashData nonHashData;
//
// @Override
// public String getHash() {
// return stateHash;
// }
//
// @Override
// public String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// @Override
// public FabricTransaction[] getTransactions() {
// return transactions == null ? new FabricTransaction[0] : transactions.toArray(new FabricTransaction[transactions.size()]);
// }
//
// @Override
// public long getTime() {
// return nonHashData.getLocalLedgerCommitTimestamp().getSeconds();
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricChain.java
// @Getter
// public class FabricChain implements BlockchainChainInfo {
// long height;
// String currentBlockHash;
// String previousBlockHash;
//
// @Override
// public long getLastBlockNumber() {
// return height - 1;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricPeer.java
// @Getter
// public class FabricPeer implements BlockchainPeer {
// FabricPeerID ID;
// String address;
// String type;
//
// @Override
// public String getId() {
// return ID.getName();
// }
//
// @Override
// public String getAddress() {
// return address;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricTimestamp.java
// @Data
// public class FabricTimestamp {
// long seconds;
// long nanos;
// }
| import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import uk.dsxt.bb.datamodel.fabric.FabricBlock;
import uk.dsxt.bb.datamodel.fabric.FabricChain;
import uk.dsxt.bb.datamodel.fabric.FabricPeer;
import uk.dsxt.bb.datamodel.fabric.FabricTimestamp; | /*
******************************************************************************
* Blockchain benchmarking framework *
* Copyright (C) 2016 DSX Technologies Limited. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************
*/
package uk.dsxt.bb.fabric;
public class FabricLogger {
private long counterForHeight = 0;
private static final Logger log = LogManager.getLogger(FabricLogger.class.getName());
| // Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricBlock.java
// @Getter
// public class FabricBlock implements BlockchainBlock {
// List<FabricTransaction> transactions;
// String stateHash;
// String previousBlockHash;
// String consensusMetadata;
// FabricNonHashData nonHashData;
//
// @Override
// public String getHash() {
// return stateHash;
// }
//
// @Override
// public String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// @Override
// public FabricTransaction[] getTransactions() {
// return transactions == null ? new FabricTransaction[0] : transactions.toArray(new FabricTransaction[transactions.size()]);
// }
//
// @Override
// public long getTime() {
// return nonHashData.getLocalLedgerCommitTimestamp().getSeconds();
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricChain.java
// @Getter
// public class FabricChain implements BlockchainChainInfo {
// long height;
// String currentBlockHash;
// String previousBlockHash;
//
// @Override
// public long getLastBlockNumber() {
// return height - 1;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricPeer.java
// @Getter
// public class FabricPeer implements BlockchainPeer {
// FabricPeerID ID;
// String address;
// String type;
//
// @Override
// public String getId() {
// return ID.getName();
// }
//
// @Override
// public String getAddress() {
// return address;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricTimestamp.java
// @Data
// public class FabricTimestamp {
// long seconds;
// long nanos;
// }
// Path: blockchain-api/src/main/java/uk/dsxt/bb/fabric/FabricLogger.java
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import uk.dsxt.bb.datamodel.fabric.FabricBlock;
import uk.dsxt.bb.datamodel.fabric.FabricChain;
import uk.dsxt.bb.datamodel.fabric.FabricPeer;
import uk.dsxt.bb.datamodel.fabric.FabricTimestamp;
/*
******************************************************************************
* Blockchain benchmarking framework *
* Copyright (C) 2016 DSX Technologies Limited. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************
*/
package uk.dsxt.bb.fabric;
public class FabricLogger {
private long counterForHeight = 0;
private static final Logger log = LogManager.getLogger(FabricLogger.class.getName());
| private FabricTimestamp getTimestampDiff(FabricBlock fb1, FabricBlock fb2) { |
dsx-tech/blockchain-benchmarking | blockchain-api/src/main/java/uk/dsxt/bb/fabric/FabricLogger.java | // Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricBlock.java
// @Getter
// public class FabricBlock implements BlockchainBlock {
// List<FabricTransaction> transactions;
// String stateHash;
// String previousBlockHash;
// String consensusMetadata;
// FabricNonHashData nonHashData;
//
// @Override
// public String getHash() {
// return stateHash;
// }
//
// @Override
// public String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// @Override
// public FabricTransaction[] getTransactions() {
// return transactions == null ? new FabricTransaction[0] : transactions.toArray(new FabricTransaction[transactions.size()]);
// }
//
// @Override
// public long getTime() {
// return nonHashData.getLocalLedgerCommitTimestamp().getSeconds();
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricChain.java
// @Getter
// public class FabricChain implements BlockchainChainInfo {
// long height;
// String currentBlockHash;
// String previousBlockHash;
//
// @Override
// public long getLastBlockNumber() {
// return height - 1;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricPeer.java
// @Getter
// public class FabricPeer implements BlockchainPeer {
// FabricPeerID ID;
// String address;
// String type;
//
// @Override
// public String getId() {
// return ID.getName();
// }
//
// @Override
// public String getAddress() {
// return address;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricTimestamp.java
// @Data
// public class FabricTimestamp {
// long seconds;
// long nanos;
// }
| import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import uk.dsxt.bb.datamodel.fabric.FabricBlock;
import uk.dsxt.bb.datamodel.fabric.FabricChain;
import uk.dsxt.bb.datamodel.fabric.FabricPeer;
import uk.dsxt.bb.datamodel.fabric.FabricTimestamp; | /*
******************************************************************************
* Blockchain benchmarking framework *
* Copyright (C) 2016 DSX Technologies Limited. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************
*/
package uk.dsxt.bb.fabric;
public class FabricLogger {
private long counterForHeight = 0;
private static final Logger log = LogManager.getLogger(FabricLogger.class.getName());
| // Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricBlock.java
// @Getter
// public class FabricBlock implements BlockchainBlock {
// List<FabricTransaction> transactions;
// String stateHash;
// String previousBlockHash;
// String consensusMetadata;
// FabricNonHashData nonHashData;
//
// @Override
// public String getHash() {
// return stateHash;
// }
//
// @Override
// public String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// @Override
// public FabricTransaction[] getTransactions() {
// return transactions == null ? new FabricTransaction[0] : transactions.toArray(new FabricTransaction[transactions.size()]);
// }
//
// @Override
// public long getTime() {
// return nonHashData.getLocalLedgerCommitTimestamp().getSeconds();
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricChain.java
// @Getter
// public class FabricChain implements BlockchainChainInfo {
// long height;
// String currentBlockHash;
// String previousBlockHash;
//
// @Override
// public long getLastBlockNumber() {
// return height - 1;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricPeer.java
// @Getter
// public class FabricPeer implements BlockchainPeer {
// FabricPeerID ID;
// String address;
// String type;
//
// @Override
// public String getId() {
// return ID.getName();
// }
//
// @Override
// public String getAddress() {
// return address;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricTimestamp.java
// @Data
// public class FabricTimestamp {
// long seconds;
// long nanos;
// }
// Path: blockchain-api/src/main/java/uk/dsxt/bb/fabric/FabricLogger.java
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import uk.dsxt.bb.datamodel.fabric.FabricBlock;
import uk.dsxt.bb.datamodel.fabric.FabricChain;
import uk.dsxt.bb.datamodel.fabric.FabricPeer;
import uk.dsxt.bb.datamodel.fabric.FabricTimestamp;
/*
******************************************************************************
* Blockchain benchmarking framework *
* Copyright (C) 2016 DSX Technologies Limited. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************
*/
package uk.dsxt.bb.fabric;
public class FabricLogger {
private long counterForHeight = 0;
private static final Logger log = LogManager.getLogger(FabricLogger.class.getName());
| private FabricTimestamp getTimestampDiff(FabricBlock fb1, FabricBlock fb2) { |
dsx-tech/blockchain-benchmarking | blockchain-api/src/main/java/uk/dsxt/bb/fabric/FabricLogger.java | // Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricBlock.java
// @Getter
// public class FabricBlock implements BlockchainBlock {
// List<FabricTransaction> transactions;
// String stateHash;
// String previousBlockHash;
// String consensusMetadata;
// FabricNonHashData nonHashData;
//
// @Override
// public String getHash() {
// return stateHash;
// }
//
// @Override
// public String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// @Override
// public FabricTransaction[] getTransactions() {
// return transactions == null ? new FabricTransaction[0] : transactions.toArray(new FabricTransaction[transactions.size()]);
// }
//
// @Override
// public long getTime() {
// return nonHashData.getLocalLedgerCommitTimestamp().getSeconds();
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricChain.java
// @Getter
// public class FabricChain implements BlockchainChainInfo {
// long height;
// String currentBlockHash;
// String previousBlockHash;
//
// @Override
// public long getLastBlockNumber() {
// return height - 1;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricPeer.java
// @Getter
// public class FabricPeer implements BlockchainPeer {
// FabricPeerID ID;
// String address;
// String type;
//
// @Override
// public String getId() {
// return ID.getName();
// }
//
// @Override
// public String getAddress() {
// return address;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricTimestamp.java
// @Data
// public class FabricTimestamp {
// long seconds;
// long nanos;
// }
| import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import uk.dsxt.bb.datamodel.fabric.FabricBlock;
import uk.dsxt.bb.datamodel.fabric.FabricChain;
import uk.dsxt.bb.datamodel.fabric.FabricPeer;
import uk.dsxt.bb.datamodel.fabric.FabricTimestamp; | /*
******************************************************************************
* Blockchain benchmarking framework *
* Copyright (C) 2016 DSX Technologies Limited. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************
*/
package uk.dsxt.bb.fabric;
public class FabricLogger {
private long counterForHeight = 0;
private static final Logger log = LogManager.getLogger(FabricLogger.class.getName());
private FabricTimestamp getTimestampDiff(FabricBlock fb1, FabricBlock fb2) {
FabricTimestamp timestamp1 = fb1.getNonHashData().getLocalLedgerCommitTimestamp();
FabricTimestamp timestamp2 = fb2.getNonHashData().getLocalLedgerCommitTimestamp();
FabricTimestamp diffTimestamp = new FabricTimestamp();
diffTimestamp.setNanos(Math.abs(timestamp2.getNanos() - timestamp1.getNanos()));
diffTimestamp.setSeconds(Math.abs(timestamp2.getSeconds() - timestamp1.getSeconds()));
return diffTimestamp;
}
public void log(FabricManager fabricManager) throws IOException { | // Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricBlock.java
// @Getter
// public class FabricBlock implements BlockchainBlock {
// List<FabricTransaction> transactions;
// String stateHash;
// String previousBlockHash;
// String consensusMetadata;
// FabricNonHashData nonHashData;
//
// @Override
// public String getHash() {
// return stateHash;
// }
//
// @Override
// public String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// @Override
// public FabricTransaction[] getTransactions() {
// return transactions == null ? new FabricTransaction[0] : transactions.toArray(new FabricTransaction[transactions.size()]);
// }
//
// @Override
// public long getTime() {
// return nonHashData.getLocalLedgerCommitTimestamp().getSeconds();
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricChain.java
// @Getter
// public class FabricChain implements BlockchainChainInfo {
// long height;
// String currentBlockHash;
// String previousBlockHash;
//
// @Override
// public long getLastBlockNumber() {
// return height - 1;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricPeer.java
// @Getter
// public class FabricPeer implements BlockchainPeer {
// FabricPeerID ID;
// String address;
// String type;
//
// @Override
// public String getId() {
// return ID.getName();
// }
//
// @Override
// public String getAddress() {
// return address;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricTimestamp.java
// @Data
// public class FabricTimestamp {
// long seconds;
// long nanos;
// }
// Path: blockchain-api/src/main/java/uk/dsxt/bb/fabric/FabricLogger.java
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import uk.dsxt.bb.datamodel.fabric.FabricBlock;
import uk.dsxt.bb.datamodel.fabric.FabricChain;
import uk.dsxt.bb.datamodel.fabric.FabricPeer;
import uk.dsxt.bb.datamodel.fabric.FabricTimestamp;
/*
******************************************************************************
* Blockchain benchmarking framework *
* Copyright (C) 2016 DSX Technologies Limited. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************
*/
package uk.dsxt.bb.fabric;
public class FabricLogger {
private long counterForHeight = 0;
private static final Logger log = LogManager.getLogger(FabricLogger.class.getName());
private FabricTimestamp getTimestampDiff(FabricBlock fb1, FabricBlock fb2) {
FabricTimestamp timestamp1 = fb1.getNonHashData().getLocalLedgerCommitTimestamp();
FabricTimestamp timestamp2 = fb2.getNonHashData().getLocalLedgerCommitTimestamp();
FabricTimestamp diffTimestamp = new FabricTimestamp();
diffTimestamp.setNanos(Math.abs(timestamp2.getNanos() - timestamp1.getNanos()));
diffTimestamp.setSeconds(Math.abs(timestamp2.getSeconds() - timestamp1.getSeconds()));
return diffTimestamp;
}
public void log(FabricManager fabricManager) throws IOException { | FabricChain fabricChain = fabricManager.getChain(); |
dsx-tech/blockchain-benchmarking | blockchain-api/src/main/java/uk/dsxt/bb/fabric/FabricLogger.java | // Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricBlock.java
// @Getter
// public class FabricBlock implements BlockchainBlock {
// List<FabricTransaction> transactions;
// String stateHash;
// String previousBlockHash;
// String consensusMetadata;
// FabricNonHashData nonHashData;
//
// @Override
// public String getHash() {
// return stateHash;
// }
//
// @Override
// public String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// @Override
// public FabricTransaction[] getTransactions() {
// return transactions == null ? new FabricTransaction[0] : transactions.toArray(new FabricTransaction[transactions.size()]);
// }
//
// @Override
// public long getTime() {
// return nonHashData.getLocalLedgerCommitTimestamp().getSeconds();
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricChain.java
// @Getter
// public class FabricChain implements BlockchainChainInfo {
// long height;
// String currentBlockHash;
// String previousBlockHash;
//
// @Override
// public long getLastBlockNumber() {
// return height - 1;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricPeer.java
// @Getter
// public class FabricPeer implements BlockchainPeer {
// FabricPeerID ID;
// String address;
// String type;
//
// @Override
// public String getId() {
// return ID.getName();
// }
//
// @Override
// public String getAddress() {
// return address;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricTimestamp.java
// @Data
// public class FabricTimestamp {
// long seconds;
// long nanos;
// }
| import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import uk.dsxt.bb.datamodel.fabric.FabricBlock;
import uk.dsxt.bb.datamodel.fabric.FabricChain;
import uk.dsxt.bb.datamodel.fabric.FabricPeer;
import uk.dsxt.bb.datamodel.fabric.FabricTimestamp; | /*
******************************************************************************
* Blockchain benchmarking framework *
* Copyright (C) 2016 DSX Technologies Limited. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************
*/
package uk.dsxt.bb.fabric;
public class FabricLogger {
private long counterForHeight = 0;
private static final Logger log = LogManager.getLogger(FabricLogger.class.getName());
private FabricTimestamp getTimestampDiff(FabricBlock fb1, FabricBlock fb2) {
FabricTimestamp timestamp1 = fb1.getNonHashData().getLocalLedgerCommitTimestamp();
FabricTimestamp timestamp2 = fb2.getNonHashData().getLocalLedgerCommitTimestamp();
FabricTimestamp diffTimestamp = new FabricTimestamp();
diffTimestamp.setNanos(Math.abs(timestamp2.getNanos() - timestamp1.getNanos()));
diffTimestamp.setSeconds(Math.abs(timestamp2.getSeconds() - timestamp1.getSeconds()));
return diffTimestamp;
}
public void log(FabricManager fabricManager) throws IOException {
FabricChain fabricChain = fabricManager.getChain();
List<FabricTimestamp> timestamps = new LinkedList<>();
if (fabricChain.getHeight() - 1 > counterForHeight) {
| // Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricBlock.java
// @Getter
// public class FabricBlock implements BlockchainBlock {
// List<FabricTransaction> transactions;
// String stateHash;
// String previousBlockHash;
// String consensusMetadata;
// FabricNonHashData nonHashData;
//
// @Override
// public String getHash() {
// return stateHash;
// }
//
// @Override
// public String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// @Override
// public FabricTransaction[] getTransactions() {
// return transactions == null ? new FabricTransaction[0] : transactions.toArray(new FabricTransaction[transactions.size()]);
// }
//
// @Override
// public long getTime() {
// return nonHashData.getLocalLedgerCommitTimestamp().getSeconds();
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricChain.java
// @Getter
// public class FabricChain implements BlockchainChainInfo {
// long height;
// String currentBlockHash;
// String previousBlockHash;
//
// @Override
// public long getLastBlockNumber() {
// return height - 1;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricPeer.java
// @Getter
// public class FabricPeer implements BlockchainPeer {
// FabricPeerID ID;
// String address;
// String type;
//
// @Override
// public String getId() {
// return ID.getName();
// }
//
// @Override
// public String getAddress() {
// return address;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/fabric/FabricTimestamp.java
// @Data
// public class FabricTimestamp {
// long seconds;
// long nanos;
// }
// Path: blockchain-api/src/main/java/uk/dsxt/bb/fabric/FabricLogger.java
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import uk.dsxt.bb.datamodel.fabric.FabricBlock;
import uk.dsxt.bb.datamodel.fabric.FabricChain;
import uk.dsxt.bb.datamodel.fabric.FabricPeer;
import uk.dsxt.bb.datamodel.fabric.FabricTimestamp;
/*
******************************************************************************
* Blockchain benchmarking framework *
* Copyright (C) 2016 DSX Technologies Limited. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************
*/
package uk.dsxt.bb.fabric;
public class FabricLogger {
private long counterForHeight = 0;
private static final Logger log = LogManager.getLogger(FabricLogger.class.getName());
private FabricTimestamp getTimestampDiff(FabricBlock fb1, FabricBlock fb2) {
FabricTimestamp timestamp1 = fb1.getNonHashData().getLocalLedgerCommitTimestamp();
FabricTimestamp timestamp2 = fb2.getNonHashData().getLocalLedgerCommitTimestamp();
FabricTimestamp diffTimestamp = new FabricTimestamp();
diffTimestamp.setNanos(Math.abs(timestamp2.getNanos() - timestamp1.getNanos()));
diffTimestamp.setSeconds(Math.abs(timestamp2.getSeconds() - timestamp1.getSeconds()));
return diffTimestamp;
}
public void log(FabricManager fabricManager) throws IOException {
FabricChain fabricChain = fabricManager.getChain();
List<FabricTimestamp> timestamps = new LinkedList<>();
if (fabricChain.getHeight() - 1 > counterForHeight) {
| FabricPeer[] fabricPeers = fabricManager.getPeers(); |
dsx-tech/blockchain-benchmarking | blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Manager.java | // Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainPeer.java
// public interface BlockchainPeer {
// String id = Strings.EMPTY;
// String address = Strings.EMPTY;
//
// default String getId() {
// return id;
// }
//
// default String getAddress() {
// return address;
// }
// }
| import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo;
import uk.dsxt.bb.datamodel.blockchain.BlockchainPeer;
import java.io.IOException;
import java.util.List; | /*
******************************************************************************
* Blockchain benchmarking framework *
* Copyright (C) 2016 DSX Technologies Limited. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************
*/
package uk.dsxt.bb.blockchain;
public interface Manager {
String sendTransaction(String to, String from, long amount);
String sendMessage(byte[] body);
String sendMessage(String from, String to, String message);
List<Message> getNewMessages();
| // Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainPeer.java
// public interface BlockchainPeer {
// String id = Strings.EMPTY;
// String address = Strings.EMPTY;
//
// default String getId() {
// return id;
// }
//
// default String getAddress() {
// return address;
// }
// }
// Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Manager.java
import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo;
import uk.dsxt.bb.datamodel.blockchain.BlockchainPeer;
import java.io.IOException;
import java.util.List;
/*
******************************************************************************
* Blockchain benchmarking framework *
* Copyright (C) 2016 DSX Technologies Limited. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************
*/
package uk.dsxt.bb.blockchain;
public interface Manager {
String sendTransaction(String to, String from, long amount);
String sendMessage(byte[] body);
String sendMessage(String from, String to, String message);
List<Message> getNewMessages();
| BlockchainBlock getBlock(long id) throws IOException; |
dsx-tech/blockchain-benchmarking | blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Manager.java | // Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainPeer.java
// public interface BlockchainPeer {
// String id = Strings.EMPTY;
// String address = Strings.EMPTY;
//
// default String getId() {
// return id;
// }
//
// default String getAddress() {
// return address;
// }
// }
| import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo;
import uk.dsxt.bb.datamodel.blockchain.BlockchainPeer;
import java.io.IOException;
import java.util.List; | /*
******************************************************************************
* Blockchain benchmarking framework *
* Copyright (C) 2016 DSX Technologies Limited. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************
*/
package uk.dsxt.bb.blockchain;
public interface Manager {
String sendTransaction(String to, String from, long amount);
String sendMessage(byte[] body);
String sendMessage(String from, String to, String message);
List<Message> getNewMessages();
BlockchainBlock getBlock(long id) throws IOException;
| // Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainPeer.java
// public interface BlockchainPeer {
// String id = Strings.EMPTY;
// String address = Strings.EMPTY;
//
// default String getId() {
// return id;
// }
//
// default String getAddress() {
// return address;
// }
// }
// Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Manager.java
import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo;
import uk.dsxt.bb.datamodel.blockchain.BlockchainPeer;
import java.io.IOException;
import java.util.List;
/*
******************************************************************************
* Blockchain benchmarking framework *
* Copyright (C) 2016 DSX Technologies Limited. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************
*/
package uk.dsxt.bb.blockchain;
public interface Manager {
String sendTransaction(String to, String from, long amount);
String sendMessage(byte[] body);
String sendMessage(String from, String to, String message);
List<Message> getNewMessages();
BlockchainBlock getBlock(long id) throws IOException;
| BlockchainPeer[] getPeers() throws IOException; |
dsx-tech/blockchain-benchmarking | blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Manager.java | // Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainPeer.java
// public interface BlockchainPeer {
// String id = Strings.EMPTY;
// String address = Strings.EMPTY;
//
// default String getId() {
// return id;
// }
//
// default String getAddress() {
// return address;
// }
// }
| import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo;
import uk.dsxt.bb.datamodel.blockchain.BlockchainPeer;
import java.io.IOException;
import java.util.List; | /*
******************************************************************************
* Blockchain benchmarking framework *
* Copyright (C) 2016 DSX Technologies Limited. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************
*/
package uk.dsxt.bb.blockchain;
public interface Manager {
String sendTransaction(String to, String from, long amount);
String sendMessage(byte[] body);
String sendMessage(String from, String to, String message);
List<Message> getNewMessages();
BlockchainBlock getBlock(long id) throws IOException;
BlockchainPeer[] getPeers() throws IOException;
| // Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainPeer.java
// public interface BlockchainPeer {
// String id = Strings.EMPTY;
// String address = Strings.EMPTY;
//
// default String getId() {
// return id;
// }
//
// default String getAddress() {
// return address;
// }
// }
// Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/Manager.java
import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo;
import uk.dsxt.bb.datamodel.blockchain.BlockchainPeer;
import java.io.IOException;
import java.util.List;
/*
******************************************************************************
* Blockchain benchmarking framework *
* Copyright (C) 2016 DSX Technologies Limited. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************
*/
package uk.dsxt.bb.blockchain;
public interface Manager {
String sendTransaction(String to, String from, long amount);
String sendMessage(byte[] body);
String sendMessage(String from, String to, String message);
List<Message> getNewMessages();
BlockchainBlock getBlock(long id) throws IOException;
BlockchainPeer[] getPeers() throws IOException;
| BlockchainChainInfo getChain() throws IOException; |
dsx-tech/blockchain-benchmarking | load-generator/src/main/java/uk/dsxt/bb/loadgenerator/LoadManager.java | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/BlockchainManager.java
// @Log4j2
// public class BlockchainManager implements Manager {
//
// private String blockchainType;
// private String url;
//
// private Manager manager;
//
// public BlockchainManager(String blockchainType, String url) {
// this.blockchainType = blockchainType;
// this.url = url;
// switch (blockchainType) {
// case "fabric":
// manager = new FabricManager(url);
// break;
// case "bitcoin":
// manager = new BitcoinManager(url);
// break;
// case "ethereum":
// manager = new EthereumManager(url);
// break;
// case "multichain":
// manager = new MultichainManager(url);
// break;
// default:
// log.error(String.format("%s blockchain currently not supported or not exist. Currently supported: " +
// "fabric, bitcoin, ethereum, multichain", blockchainType));
// break;
// }
// }
//
// @Override
// public String sendTransaction(String to, String from, long amount) {
// if (manager != null) {
// return manager.sendTransaction(to, from, amount);
// }
//
// return null;
// }
// @Override
// public String sendMessage(String from, String to, String message) {
// if (manager != null) {
// return manager.sendMessage(from, to, message);
// }
// return null;
// }
//
//
// @Override
// public String sendMessage(byte[] body) {
// if (manager != null)
// return manager.sendMessage(body);
//
// return null;
// }
//
// @Override
// public List<Message> getNewMessages() {
// if (manager != null)
// return manager.getNewMessages();
//
// return null;
// }
//
// @Override
// public BlockchainBlock getBlock(long id) throws IOException {
// if (manager != null)
// return manager.getBlock(id);
//
// return null;
// }
//
// @Override
// public BlockchainPeer[] getPeers() throws IOException {
// if (manager != null)
// return manager.getPeers();
//
// return null;
// }
//
// @Override
// public BlockchainChainInfo getChain() throws IOException {
// if (manager != null)
// return manager.getChain();
//
// return null;
// }
//
// @Override
// public void authorize(String user, String password) {
// if (manager != null)
// manager.authorize(user, password);
// }
//
// public static void main(String[] args) throws IOException {
// BlockchainManager manager = new BlockchainManager("bitcoin", "http://127.0.0.1:6290");
// manager.authorize("multichainrpc", "3NPieLHgUEfEsdJeQpQstPDmHX1yasatPAw3SYGtY2Jr");
// System.out.println(manager.getBlock(0));
// }
// }
//
// Path: load-generator/src/main/java/uk/dsxt/bb/loadgenerator/data/Credential.java
// @Data
// public class Credential {
// private final String account;
// private final String password;
// }
| import java.util.List;
import java.util.Random;
import java.util.StringJoiner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import lombok.extern.log4j.Log4j2;
import uk.dsxt.bb.blockchain.BlockchainManager;
import uk.dsxt.bb.loadgenerator.data.Credential;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList; | /*
******************************************************************************
* Blockchain benchmarking framework *
* Copyright (C) 2016 DSX Technologies Limited. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************
*/
package uk.dsxt.bb.loadgenerator;
/**
* @author phd
*/
@Log4j2
class LoadManager {
private static final int BATCH_SIZE = 100;
private static final char[] symbols;
static {
StringBuilder tmp = new StringBuilder();
for (char ch = '0'; ch <= '9'; ++ch)
tmp.append(ch);
for (char ch = 'a'; ch <= 'z'; ++ch)
tmp.append(ch);
symbols = tmp.toString().toCharArray();
}
private final int minLength;
private final int maxLength;
private final int delay;
private List<String> targets; | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/BlockchainManager.java
// @Log4j2
// public class BlockchainManager implements Manager {
//
// private String blockchainType;
// private String url;
//
// private Manager manager;
//
// public BlockchainManager(String blockchainType, String url) {
// this.blockchainType = blockchainType;
// this.url = url;
// switch (blockchainType) {
// case "fabric":
// manager = new FabricManager(url);
// break;
// case "bitcoin":
// manager = new BitcoinManager(url);
// break;
// case "ethereum":
// manager = new EthereumManager(url);
// break;
// case "multichain":
// manager = new MultichainManager(url);
// break;
// default:
// log.error(String.format("%s blockchain currently not supported or not exist. Currently supported: " +
// "fabric, bitcoin, ethereum, multichain", blockchainType));
// break;
// }
// }
//
// @Override
// public String sendTransaction(String to, String from, long amount) {
// if (manager != null) {
// return manager.sendTransaction(to, from, amount);
// }
//
// return null;
// }
// @Override
// public String sendMessage(String from, String to, String message) {
// if (manager != null) {
// return manager.sendMessage(from, to, message);
// }
// return null;
// }
//
//
// @Override
// public String sendMessage(byte[] body) {
// if (manager != null)
// return manager.sendMessage(body);
//
// return null;
// }
//
// @Override
// public List<Message> getNewMessages() {
// if (manager != null)
// return manager.getNewMessages();
//
// return null;
// }
//
// @Override
// public BlockchainBlock getBlock(long id) throws IOException {
// if (manager != null)
// return manager.getBlock(id);
//
// return null;
// }
//
// @Override
// public BlockchainPeer[] getPeers() throws IOException {
// if (manager != null)
// return manager.getPeers();
//
// return null;
// }
//
// @Override
// public BlockchainChainInfo getChain() throws IOException {
// if (manager != null)
// return manager.getChain();
//
// return null;
// }
//
// @Override
// public void authorize(String user, String password) {
// if (manager != null)
// manager.authorize(user, password);
// }
//
// public static void main(String[] args) throws IOException {
// BlockchainManager manager = new BlockchainManager("bitcoin", "http://127.0.0.1:6290");
// manager.authorize("multichainrpc", "3NPieLHgUEfEsdJeQpQstPDmHX1yasatPAw3SYGtY2Jr");
// System.out.println(manager.getBlock(0));
// }
// }
//
// Path: load-generator/src/main/java/uk/dsxt/bb/loadgenerator/data/Credential.java
// @Data
// public class Credential {
// private final String account;
// private final String password;
// }
// Path: load-generator/src/main/java/uk/dsxt/bb/loadgenerator/LoadManager.java
import java.util.List;
import java.util.Random;
import java.util.StringJoiner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import lombok.extern.log4j.Log4j2;
import uk.dsxt.bb.blockchain.BlockchainManager;
import uk.dsxt.bb.loadgenerator.data.Credential;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
/*
******************************************************************************
* Blockchain benchmarking framework *
* Copyright (C) 2016 DSX Technologies Limited. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************
*/
package uk.dsxt.bb.loadgenerator;
/**
* @author phd
*/
@Log4j2
class LoadManager {
private static final int BATCH_SIZE = 100;
private static final char[] symbols;
static {
StringBuilder tmp = new StringBuilder();
for (char ch = '0'; ch <= '9'; ++ch)
tmp.append(ch);
for (char ch = 'a'; ch <= 'z'; ++ch)
tmp.append(ch);
symbols = tmp.toString().toCharArray();
}
private final int minLength;
private final int maxLength;
private final int delay;
private List<String> targets; | private List<Credential> credentials; |
dsx-tech/blockchain-benchmarking | load-generator/src/main/java/uk/dsxt/bb/loadgenerator/LoadManager.java | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/BlockchainManager.java
// @Log4j2
// public class BlockchainManager implements Manager {
//
// private String blockchainType;
// private String url;
//
// private Manager manager;
//
// public BlockchainManager(String blockchainType, String url) {
// this.blockchainType = blockchainType;
// this.url = url;
// switch (blockchainType) {
// case "fabric":
// manager = new FabricManager(url);
// break;
// case "bitcoin":
// manager = new BitcoinManager(url);
// break;
// case "ethereum":
// manager = new EthereumManager(url);
// break;
// case "multichain":
// manager = new MultichainManager(url);
// break;
// default:
// log.error(String.format("%s blockchain currently not supported or not exist. Currently supported: " +
// "fabric, bitcoin, ethereum, multichain", blockchainType));
// break;
// }
// }
//
// @Override
// public String sendTransaction(String to, String from, long amount) {
// if (manager != null) {
// return manager.sendTransaction(to, from, amount);
// }
//
// return null;
// }
// @Override
// public String sendMessage(String from, String to, String message) {
// if (manager != null) {
// return manager.sendMessage(from, to, message);
// }
// return null;
// }
//
//
// @Override
// public String sendMessage(byte[] body) {
// if (manager != null)
// return manager.sendMessage(body);
//
// return null;
// }
//
// @Override
// public List<Message> getNewMessages() {
// if (manager != null)
// return manager.getNewMessages();
//
// return null;
// }
//
// @Override
// public BlockchainBlock getBlock(long id) throws IOException {
// if (manager != null)
// return manager.getBlock(id);
//
// return null;
// }
//
// @Override
// public BlockchainPeer[] getPeers() throws IOException {
// if (manager != null)
// return manager.getPeers();
//
// return null;
// }
//
// @Override
// public BlockchainChainInfo getChain() throws IOException {
// if (manager != null)
// return manager.getChain();
//
// return null;
// }
//
// @Override
// public void authorize(String user, String password) {
// if (manager != null)
// manager.authorize(user, password);
// }
//
// public static void main(String[] args) throws IOException {
// BlockchainManager manager = new BlockchainManager("bitcoin", "http://127.0.0.1:6290");
// manager.authorize("multichainrpc", "3NPieLHgUEfEsdJeQpQstPDmHX1yasatPAw3SYGtY2Jr");
// System.out.println(manager.getBlock(0));
// }
// }
//
// Path: load-generator/src/main/java/uk/dsxt/bb/loadgenerator/data/Credential.java
// @Data
// public class Credential {
// private final String account;
// private final String password;
// }
| import java.util.List;
import java.util.Random;
import java.util.StringJoiner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import lombok.extern.log4j.Log4j2;
import uk.dsxt.bb.blockchain.BlockchainManager;
import uk.dsxt.bb.loadgenerator.data.Credential;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList; | this.maxLength = maxLength;
this.delay = delay;
this.loggers = new ArrayList<>();
this.blockchainType = blockchainType;
this.blockchainPort = blockchainPort;
executorService = Executors.newFixedThreadPool(amountOfThreadsPerTarget * targets.size());
}
private static String generateMessage(Random random, int minLength, int maxLength) {
StringBuilder tmp = new StringBuilder();
int length = minLength + random.nextInt(maxLength - minLength);
for (int i = 0; i < minLength + length; ++i) {
tmp.append(symbols[random.nextInt(symbols.length)]);
}
return tmp.toString();
}
private static int getRandomIntExcept(Random random, int bound, int except) {
int candidate = random.nextInt(bound);
while (candidate == except) {
candidate = random.nextInt(bound);
}
return candidate;
}
void start() throws IOException {
for (int targetIndex = 0; targetIndex < targets.size(); ++targetIndex) {
String t = targets.get(targetIndex);
Logger logger = new Logger(Paths.get("load_logs", t + "_load.log"));
loggers.add(logger); | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/BlockchainManager.java
// @Log4j2
// public class BlockchainManager implements Manager {
//
// private String blockchainType;
// private String url;
//
// private Manager manager;
//
// public BlockchainManager(String blockchainType, String url) {
// this.blockchainType = blockchainType;
// this.url = url;
// switch (blockchainType) {
// case "fabric":
// manager = new FabricManager(url);
// break;
// case "bitcoin":
// manager = new BitcoinManager(url);
// break;
// case "ethereum":
// manager = new EthereumManager(url);
// break;
// case "multichain":
// manager = new MultichainManager(url);
// break;
// default:
// log.error(String.format("%s blockchain currently not supported or not exist. Currently supported: " +
// "fabric, bitcoin, ethereum, multichain", blockchainType));
// break;
// }
// }
//
// @Override
// public String sendTransaction(String to, String from, long amount) {
// if (manager != null) {
// return manager.sendTransaction(to, from, amount);
// }
//
// return null;
// }
// @Override
// public String sendMessage(String from, String to, String message) {
// if (manager != null) {
// return manager.sendMessage(from, to, message);
// }
// return null;
// }
//
//
// @Override
// public String sendMessage(byte[] body) {
// if (manager != null)
// return manager.sendMessage(body);
//
// return null;
// }
//
// @Override
// public List<Message> getNewMessages() {
// if (manager != null)
// return manager.getNewMessages();
//
// return null;
// }
//
// @Override
// public BlockchainBlock getBlock(long id) throws IOException {
// if (manager != null)
// return manager.getBlock(id);
//
// return null;
// }
//
// @Override
// public BlockchainPeer[] getPeers() throws IOException {
// if (manager != null)
// return manager.getPeers();
//
// return null;
// }
//
// @Override
// public BlockchainChainInfo getChain() throws IOException {
// if (manager != null)
// return manager.getChain();
//
// return null;
// }
//
// @Override
// public void authorize(String user, String password) {
// if (manager != null)
// manager.authorize(user, password);
// }
//
// public static void main(String[] args) throws IOException {
// BlockchainManager manager = new BlockchainManager("bitcoin", "http://127.0.0.1:6290");
// manager.authorize("multichainrpc", "3NPieLHgUEfEsdJeQpQstPDmHX1yasatPAw3SYGtY2Jr");
// System.out.println(manager.getBlock(0));
// }
// }
//
// Path: load-generator/src/main/java/uk/dsxt/bb/loadgenerator/data/Credential.java
// @Data
// public class Credential {
// private final String account;
// private final String password;
// }
// Path: load-generator/src/main/java/uk/dsxt/bb/loadgenerator/LoadManager.java
import java.util.List;
import java.util.Random;
import java.util.StringJoiner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import lombok.extern.log4j.Log4j2;
import uk.dsxt.bb.blockchain.BlockchainManager;
import uk.dsxt.bb.loadgenerator.data.Credential;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
this.maxLength = maxLength;
this.delay = delay;
this.loggers = new ArrayList<>();
this.blockchainType = blockchainType;
this.blockchainPort = blockchainPort;
executorService = Executors.newFixedThreadPool(amountOfThreadsPerTarget * targets.size());
}
private static String generateMessage(Random random, int minLength, int maxLength) {
StringBuilder tmp = new StringBuilder();
int length = minLength + random.nextInt(maxLength - minLength);
for (int i = 0; i < minLength + length; ++i) {
tmp.append(symbols[random.nextInt(symbols.length)]);
}
return tmp.toString();
}
private static int getRandomIntExcept(Random random, int bound, int except) {
int candidate = random.nextInt(bound);
while (candidate == except) {
candidate = random.nextInt(bound);
}
return candidate;
}
void start() throws IOException {
for (int targetIndex = 0; targetIndex < targets.size(); ++targetIndex) {
String t = targets.get(targetIndex);
Logger logger = new Logger(Paths.get("load_logs", t + "_load.log"));
loggers.add(logger); | BlockchainManager manager = new BlockchainManager(blockchainType, "http://" + t + ":" + blockchainPort); |
dsx-tech/blockchain-benchmarking | test-manager/src/main/java/uk/dsxt/bb/test_manager/TestManager.java | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/BlockchainManager.java
// @Log4j2
// public class BlockchainManager implements Manager {
//
// private String blockchainType;
// private String url;
//
// private Manager manager;
//
// public BlockchainManager(String blockchainType, String url) {
// this.blockchainType = blockchainType;
// this.url = url;
// switch (blockchainType) {
// case "fabric":
// manager = new FabricManager(url);
// break;
// case "bitcoin":
// manager = new BitcoinManager(url);
// break;
// case "ethereum":
// manager = new EthereumManager(url);
// break;
// case "multichain":
// manager = new MultichainManager(url);
// break;
// default:
// log.error(String.format("%s blockchain currently not supported or not exist. Currently supported: " +
// "fabric, bitcoin, ethereum, multichain", blockchainType));
// break;
// }
// }
//
// @Override
// public String sendTransaction(String to, String from, long amount) {
// if (manager != null) {
// return manager.sendTransaction(to, from, amount);
// }
//
// return null;
// }
// @Override
// public String sendMessage(String from, String to, String message) {
// if (manager != null) {
// return manager.sendMessage(from, to, message);
// }
// return null;
// }
//
//
// @Override
// public String sendMessage(byte[] body) {
// if (manager != null)
// return manager.sendMessage(body);
//
// return null;
// }
//
// @Override
// public List<Message> getNewMessages() {
// if (manager != null)
// return manager.getNewMessages();
//
// return null;
// }
//
// @Override
// public BlockchainBlock getBlock(long id) throws IOException {
// if (manager != null)
// return manager.getBlock(id);
//
// return null;
// }
//
// @Override
// public BlockchainPeer[] getPeers() throws IOException {
// if (manager != null)
// return manager.getPeers();
//
// return null;
// }
//
// @Override
// public BlockchainChainInfo getChain() throws IOException {
// if (manager != null)
// return manager.getChain();
//
// return null;
// }
//
// @Override
// public void authorize(String user, String password) {
// if (manager != null)
// manager.authorize(user, password);
// }
//
// public static void main(String[] args) throws IOException {
// BlockchainManager manager = new BlockchainManager("bitcoin", "http://127.0.0.1:6290");
// manager.authorize("multichainrpc", "3NPieLHgUEfEsdJeQpQstPDmHX1yasatPAw3SYGtY2Jr");
// System.out.println(manager.getBlock(0));
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainTransaction.java
// public interface BlockchainTransaction {
// String txId = Strings.EMPTY;
//
// default String getTxId() {
// return txId;
// }
// }
| import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j2;
import spark.Spark;
import uk.dsxt.bb.blockchain.BlockchainManager;
import uk.dsxt.bb.datamodel.blockchain.BlockchainTransaction;
import uk.dsxt.bb.remote.instance.*;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import static java.lang.Thread.sleep;
import static java.net.HttpURLConnection.*;
import static java.util.Collections.singletonList; | }
private boolean safeExecute(Runnable action) {
try {
action.run();
return true;
}
catch (Exception e) {
log.error(e);
}
return false;
}
private void getResourceMonitorsLogs() {
log.info("Getting logs from resource-monitors");
if (isResourceMonitorsLogsLoaded.compareAndSet(false, true)) {
resourceMonitorsInstancesManager.getAllInstances().forEach(monitor ->
monitor.downloadFiles(
singletonList("resource_usage.csv"),
resourceMonitorsLog.resolve(monitor.getHost() + "_res_usage.csv"))
);
}
}
private void getTransactionsForBlocks() {
log.info("Extracting transactions from blockchain...");
try (FileWriter fw = new FileWriter(
getEmptyFolder(Paths.get(properties.getResultLogsPath(), "transactionsPerBlock"))
.resolve("transactionsPerBlock").toFile())) {
fw.write("blockID, transactionID\n"); | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/BlockchainManager.java
// @Log4j2
// public class BlockchainManager implements Manager {
//
// private String blockchainType;
// private String url;
//
// private Manager manager;
//
// public BlockchainManager(String blockchainType, String url) {
// this.blockchainType = blockchainType;
// this.url = url;
// switch (blockchainType) {
// case "fabric":
// manager = new FabricManager(url);
// break;
// case "bitcoin":
// manager = new BitcoinManager(url);
// break;
// case "ethereum":
// manager = new EthereumManager(url);
// break;
// case "multichain":
// manager = new MultichainManager(url);
// break;
// default:
// log.error(String.format("%s blockchain currently not supported or not exist. Currently supported: " +
// "fabric, bitcoin, ethereum, multichain", blockchainType));
// break;
// }
// }
//
// @Override
// public String sendTransaction(String to, String from, long amount) {
// if (manager != null) {
// return manager.sendTransaction(to, from, amount);
// }
//
// return null;
// }
// @Override
// public String sendMessage(String from, String to, String message) {
// if (manager != null) {
// return manager.sendMessage(from, to, message);
// }
// return null;
// }
//
//
// @Override
// public String sendMessage(byte[] body) {
// if (manager != null)
// return manager.sendMessage(body);
//
// return null;
// }
//
// @Override
// public List<Message> getNewMessages() {
// if (manager != null)
// return manager.getNewMessages();
//
// return null;
// }
//
// @Override
// public BlockchainBlock getBlock(long id) throws IOException {
// if (manager != null)
// return manager.getBlock(id);
//
// return null;
// }
//
// @Override
// public BlockchainPeer[] getPeers() throws IOException {
// if (manager != null)
// return manager.getPeers();
//
// return null;
// }
//
// @Override
// public BlockchainChainInfo getChain() throws IOException {
// if (manager != null)
// return manager.getChain();
//
// return null;
// }
//
// @Override
// public void authorize(String user, String password) {
// if (manager != null)
// manager.authorize(user, password);
// }
//
// public static void main(String[] args) throws IOException {
// BlockchainManager manager = new BlockchainManager("bitcoin", "http://127.0.0.1:6290");
// manager.authorize("multichainrpc", "3NPieLHgUEfEsdJeQpQstPDmHX1yasatPAw3SYGtY2Jr");
// System.out.println(manager.getBlock(0));
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainTransaction.java
// public interface BlockchainTransaction {
// String txId = Strings.EMPTY;
//
// default String getTxId() {
// return txId;
// }
// }
// Path: test-manager/src/main/java/uk/dsxt/bb/test_manager/TestManager.java
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j2;
import spark.Spark;
import uk.dsxt.bb.blockchain.BlockchainManager;
import uk.dsxt.bb.datamodel.blockchain.BlockchainTransaction;
import uk.dsxt.bb.remote.instance.*;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import static java.lang.Thread.sleep;
import static java.net.HttpURLConnection.*;
import static java.util.Collections.singletonList;
}
private boolean safeExecute(Runnable action) {
try {
action.run();
return true;
}
catch (Exception e) {
log.error(e);
}
return false;
}
private void getResourceMonitorsLogs() {
log.info("Getting logs from resource-monitors");
if (isResourceMonitorsLogsLoaded.compareAndSet(false, true)) {
resourceMonitorsInstancesManager.getAllInstances().forEach(monitor ->
monitor.downloadFiles(
singletonList("resource_usage.csv"),
resourceMonitorsLog.resolve(monitor.getHost() + "_res_usage.csv"))
);
}
}
private void getTransactionsForBlocks() {
log.info("Extracting transactions from blockchain...");
try (FileWriter fw = new FileWriter(
getEmptyFolder(Paths.get(properties.getResultLogsPath(), "transactionsPerBlock"))
.resolve("transactionsPerBlock").toFile())) {
fw.write("blockID, transactionID\n"); | BlockchainManager blockchainManager = new BlockchainManager(properties.getBlockchainType(), |
dsx-tech/blockchain-benchmarking | test-manager/src/main/java/uk/dsxt/bb/test_manager/TestManager.java | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/BlockchainManager.java
// @Log4j2
// public class BlockchainManager implements Manager {
//
// private String blockchainType;
// private String url;
//
// private Manager manager;
//
// public BlockchainManager(String blockchainType, String url) {
// this.blockchainType = blockchainType;
// this.url = url;
// switch (blockchainType) {
// case "fabric":
// manager = new FabricManager(url);
// break;
// case "bitcoin":
// manager = new BitcoinManager(url);
// break;
// case "ethereum":
// manager = new EthereumManager(url);
// break;
// case "multichain":
// manager = new MultichainManager(url);
// break;
// default:
// log.error(String.format("%s blockchain currently not supported or not exist. Currently supported: " +
// "fabric, bitcoin, ethereum, multichain", blockchainType));
// break;
// }
// }
//
// @Override
// public String sendTransaction(String to, String from, long amount) {
// if (manager != null) {
// return manager.sendTransaction(to, from, amount);
// }
//
// return null;
// }
// @Override
// public String sendMessage(String from, String to, String message) {
// if (manager != null) {
// return manager.sendMessage(from, to, message);
// }
// return null;
// }
//
//
// @Override
// public String sendMessage(byte[] body) {
// if (manager != null)
// return manager.sendMessage(body);
//
// return null;
// }
//
// @Override
// public List<Message> getNewMessages() {
// if (manager != null)
// return manager.getNewMessages();
//
// return null;
// }
//
// @Override
// public BlockchainBlock getBlock(long id) throws IOException {
// if (manager != null)
// return manager.getBlock(id);
//
// return null;
// }
//
// @Override
// public BlockchainPeer[] getPeers() throws IOException {
// if (manager != null)
// return manager.getPeers();
//
// return null;
// }
//
// @Override
// public BlockchainChainInfo getChain() throws IOException {
// if (manager != null)
// return manager.getChain();
//
// return null;
// }
//
// @Override
// public void authorize(String user, String password) {
// if (manager != null)
// manager.authorize(user, password);
// }
//
// public static void main(String[] args) throws IOException {
// BlockchainManager manager = new BlockchainManager("bitcoin", "http://127.0.0.1:6290");
// manager.authorize("multichainrpc", "3NPieLHgUEfEsdJeQpQstPDmHX1yasatPAw3SYGtY2Jr");
// System.out.println(manager.getBlock(0));
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainTransaction.java
// public interface BlockchainTransaction {
// String txId = Strings.EMPTY;
//
// default String getTxId() {
// return txId;
// }
// }
| import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j2;
import spark.Spark;
import uk.dsxt.bb.blockchain.BlockchainManager;
import uk.dsxt.bb.datamodel.blockchain.BlockchainTransaction;
import uk.dsxt.bb.remote.instance.*;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import static java.lang.Thread.sleep;
import static java.net.HttpURLConnection.*;
import static java.util.Collections.singletonList; | action.run();
return true;
}
catch (Exception e) {
log.error(e);
}
return false;
}
private void getResourceMonitorsLogs() {
log.info("Getting logs from resource-monitors");
if (isResourceMonitorsLogsLoaded.compareAndSet(false, true)) {
resourceMonitorsInstancesManager.getAllInstances().forEach(monitor ->
monitor.downloadFiles(
singletonList("resource_usage.csv"),
resourceMonitorsLog.resolve(monitor.getHost() + "_res_usage.csv"))
);
}
}
private void getTransactionsForBlocks() {
log.info("Extracting transactions from blockchain...");
try (FileWriter fw = new FileWriter(
getEmptyFolder(Paths.get(properties.getResultLogsPath(), "transactionsPerBlock"))
.resolve("transactionsPerBlock").toFile())) {
fw.write("blockID, transactionID\n");
BlockchainManager blockchainManager = new BlockchainManager(properties.getBlockchainType(),
"http://" +blockchainInstancesManager.getRootInstance().getHost() + ":" + properties.getBlockchainPort());
long lastBlock = blockchainManager.getChain().getLastBlockNumber();
for (int i = 0; i <= lastBlock; ++i) { | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/BlockchainManager.java
// @Log4j2
// public class BlockchainManager implements Manager {
//
// private String blockchainType;
// private String url;
//
// private Manager manager;
//
// public BlockchainManager(String blockchainType, String url) {
// this.blockchainType = blockchainType;
// this.url = url;
// switch (blockchainType) {
// case "fabric":
// manager = new FabricManager(url);
// break;
// case "bitcoin":
// manager = new BitcoinManager(url);
// break;
// case "ethereum":
// manager = new EthereumManager(url);
// break;
// case "multichain":
// manager = new MultichainManager(url);
// break;
// default:
// log.error(String.format("%s blockchain currently not supported or not exist. Currently supported: " +
// "fabric, bitcoin, ethereum, multichain", blockchainType));
// break;
// }
// }
//
// @Override
// public String sendTransaction(String to, String from, long amount) {
// if (manager != null) {
// return manager.sendTransaction(to, from, amount);
// }
//
// return null;
// }
// @Override
// public String sendMessage(String from, String to, String message) {
// if (manager != null) {
// return manager.sendMessage(from, to, message);
// }
// return null;
// }
//
//
// @Override
// public String sendMessage(byte[] body) {
// if (manager != null)
// return manager.sendMessage(body);
//
// return null;
// }
//
// @Override
// public List<Message> getNewMessages() {
// if (manager != null)
// return manager.getNewMessages();
//
// return null;
// }
//
// @Override
// public BlockchainBlock getBlock(long id) throws IOException {
// if (manager != null)
// return manager.getBlock(id);
//
// return null;
// }
//
// @Override
// public BlockchainPeer[] getPeers() throws IOException {
// if (manager != null)
// return manager.getPeers();
//
// return null;
// }
//
// @Override
// public BlockchainChainInfo getChain() throws IOException {
// if (manager != null)
// return manager.getChain();
//
// return null;
// }
//
// @Override
// public void authorize(String user, String password) {
// if (manager != null)
// manager.authorize(user, password);
// }
//
// public static void main(String[] args) throws IOException {
// BlockchainManager manager = new BlockchainManager("bitcoin", "http://127.0.0.1:6290");
// manager.authorize("multichainrpc", "3NPieLHgUEfEsdJeQpQstPDmHX1yasatPAw3SYGtY2Jr");
// System.out.println(manager.getBlock(0));
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainTransaction.java
// public interface BlockchainTransaction {
// String txId = Strings.EMPTY;
//
// default String getTxId() {
// return txId;
// }
// }
// Path: test-manager/src/main/java/uk/dsxt/bb/test_manager/TestManager.java
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j2;
import spark.Spark;
import uk.dsxt.bb.blockchain.BlockchainManager;
import uk.dsxt.bb.datamodel.blockchain.BlockchainTransaction;
import uk.dsxt.bb.remote.instance.*;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import static java.lang.Thread.sleep;
import static java.net.HttpURLConnection.*;
import static java.util.Collections.singletonList;
action.run();
return true;
}
catch (Exception e) {
log.error(e);
}
return false;
}
private void getResourceMonitorsLogs() {
log.info("Getting logs from resource-monitors");
if (isResourceMonitorsLogsLoaded.compareAndSet(false, true)) {
resourceMonitorsInstancesManager.getAllInstances().forEach(monitor ->
monitor.downloadFiles(
singletonList("resource_usage.csv"),
resourceMonitorsLog.resolve(monitor.getHost() + "_res_usage.csv"))
);
}
}
private void getTransactionsForBlocks() {
log.info("Extracting transactions from blockchain...");
try (FileWriter fw = new FileWriter(
getEmptyFolder(Paths.get(properties.getResultLogsPath(), "transactionsPerBlock"))
.resolve("transactionsPerBlock").toFile())) {
fw.write("blockID, transactionID\n");
BlockchainManager blockchainManager = new BlockchainManager(properties.getBlockchainType(),
"http://" +blockchainInstancesManager.getRootInstance().getHost() + ":" + properties.getBlockchainPort());
long lastBlock = blockchainManager.getChain().getLastBlockNumber();
for (int i = 0; i <= lastBlock; ++i) { | for (BlockchainTransaction blockchainTransaction: blockchainManager.getBlock(i).getTransactions()) { |
dsx-tech/blockchain-benchmarking | blockchain-logger/src/main/java/uk/dsxt/bb/logger/BlockchainLogger.java | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/BlockchainManager.java
// @Log4j2
// public class BlockchainManager implements Manager {
//
// private String blockchainType;
// private String url;
//
// private Manager manager;
//
// public BlockchainManager(String blockchainType, String url) {
// this.blockchainType = blockchainType;
// this.url = url;
// switch (blockchainType) {
// case "fabric":
// manager = new FabricManager(url);
// break;
// case "bitcoin":
// manager = new BitcoinManager(url);
// break;
// case "ethereum":
// manager = new EthereumManager(url);
// break;
// case "multichain":
// manager = new MultichainManager(url);
// break;
// default:
// log.error(String.format("%s blockchain currently not supported or not exist. Currently supported: " +
// "fabric, bitcoin, ethereum, multichain", blockchainType));
// break;
// }
// }
//
// @Override
// public String sendTransaction(String to, String from, long amount) {
// if (manager != null) {
// return manager.sendTransaction(to, from, amount);
// }
//
// return null;
// }
// @Override
// public String sendMessage(String from, String to, String message) {
// if (manager != null) {
// return manager.sendMessage(from, to, message);
// }
// return null;
// }
//
//
// @Override
// public String sendMessage(byte[] body) {
// if (manager != null)
// return manager.sendMessage(body);
//
// return null;
// }
//
// @Override
// public List<Message> getNewMessages() {
// if (manager != null)
// return manager.getNewMessages();
//
// return null;
// }
//
// @Override
// public BlockchainBlock getBlock(long id) throws IOException {
// if (manager != null)
// return manager.getBlock(id);
//
// return null;
// }
//
// @Override
// public BlockchainPeer[] getPeers() throws IOException {
// if (manager != null)
// return manager.getPeers();
//
// return null;
// }
//
// @Override
// public BlockchainChainInfo getChain() throws IOException {
// if (manager != null)
// return manager.getChain();
//
// return null;
// }
//
// @Override
// public void authorize(String user, String password) {
// if (manager != null)
// manager.authorize(user, password);
// }
//
// public static void main(String[] args) throws IOException {
// BlockchainManager manager = new BlockchainManager("bitcoin", "http://127.0.0.1:6290");
// manager.authorize("multichainrpc", "3NPieLHgUEfEsdJeQpQstPDmHX1yasatPAw3SYGtY2Jr");
// System.out.println(manager.getBlock(0));
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: test-manager/src/main/java/uk/dsxt/bb/remote/instance/WorkFinishedTO.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public class WorkFinishedTO {
// private String ip;
// }
| import uk.dsxt.bb.remote.instance.WorkFinishedTO;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;
import java.util.stream.LongStream;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import lombok.extern.log4j.Log4j2;
import uk.dsxt.bb.blockchain.BlockchainManager;
import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo; | /*
******************************************************************************
* Blockchain benchmarking framework *
* Copyright (C) 2016 DSX Technologies Limited. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************
*/
package uk.dsxt.bb.logger;
@Log4j2
public class BlockchainLogger {
| // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/BlockchainManager.java
// @Log4j2
// public class BlockchainManager implements Manager {
//
// private String blockchainType;
// private String url;
//
// private Manager manager;
//
// public BlockchainManager(String blockchainType, String url) {
// this.blockchainType = blockchainType;
// this.url = url;
// switch (blockchainType) {
// case "fabric":
// manager = new FabricManager(url);
// break;
// case "bitcoin":
// manager = new BitcoinManager(url);
// break;
// case "ethereum":
// manager = new EthereumManager(url);
// break;
// case "multichain":
// manager = new MultichainManager(url);
// break;
// default:
// log.error(String.format("%s blockchain currently not supported or not exist. Currently supported: " +
// "fabric, bitcoin, ethereum, multichain", blockchainType));
// break;
// }
// }
//
// @Override
// public String sendTransaction(String to, String from, long amount) {
// if (manager != null) {
// return manager.sendTransaction(to, from, amount);
// }
//
// return null;
// }
// @Override
// public String sendMessage(String from, String to, String message) {
// if (manager != null) {
// return manager.sendMessage(from, to, message);
// }
// return null;
// }
//
//
// @Override
// public String sendMessage(byte[] body) {
// if (manager != null)
// return manager.sendMessage(body);
//
// return null;
// }
//
// @Override
// public List<Message> getNewMessages() {
// if (manager != null)
// return manager.getNewMessages();
//
// return null;
// }
//
// @Override
// public BlockchainBlock getBlock(long id) throws IOException {
// if (manager != null)
// return manager.getBlock(id);
//
// return null;
// }
//
// @Override
// public BlockchainPeer[] getPeers() throws IOException {
// if (manager != null)
// return manager.getPeers();
//
// return null;
// }
//
// @Override
// public BlockchainChainInfo getChain() throws IOException {
// if (manager != null)
// return manager.getChain();
//
// return null;
// }
//
// @Override
// public void authorize(String user, String password) {
// if (manager != null)
// manager.authorize(user, password);
// }
//
// public static void main(String[] args) throws IOException {
// BlockchainManager manager = new BlockchainManager("bitcoin", "http://127.0.0.1:6290");
// manager.authorize("multichainrpc", "3NPieLHgUEfEsdJeQpQstPDmHX1yasatPAw3SYGtY2Jr");
// System.out.println(manager.getBlock(0));
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: test-manager/src/main/java/uk/dsxt/bb/remote/instance/WorkFinishedTO.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public class WorkFinishedTO {
// private String ip;
// }
// Path: blockchain-logger/src/main/java/uk/dsxt/bb/logger/BlockchainLogger.java
import uk.dsxt.bb.remote.instance.WorkFinishedTO;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;
import java.util.stream.LongStream;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import lombok.extern.log4j.Log4j2;
import uk.dsxt.bb.blockchain.BlockchainManager;
import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo;
/*
******************************************************************************
* Blockchain benchmarking framework *
* Copyright (C) 2016 DSX Technologies Limited. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************
*/
package uk.dsxt.bb.logger;
@Log4j2
public class BlockchainLogger {
| private BlockchainManager blockchainManager; |
dsx-tech/blockchain-benchmarking | blockchain-logger/src/main/java/uk/dsxt/bb/logger/BlockchainLogger.java | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/BlockchainManager.java
// @Log4j2
// public class BlockchainManager implements Manager {
//
// private String blockchainType;
// private String url;
//
// private Manager manager;
//
// public BlockchainManager(String blockchainType, String url) {
// this.blockchainType = blockchainType;
// this.url = url;
// switch (blockchainType) {
// case "fabric":
// manager = new FabricManager(url);
// break;
// case "bitcoin":
// manager = new BitcoinManager(url);
// break;
// case "ethereum":
// manager = new EthereumManager(url);
// break;
// case "multichain":
// manager = new MultichainManager(url);
// break;
// default:
// log.error(String.format("%s blockchain currently not supported or not exist. Currently supported: " +
// "fabric, bitcoin, ethereum, multichain", blockchainType));
// break;
// }
// }
//
// @Override
// public String sendTransaction(String to, String from, long amount) {
// if (manager != null) {
// return manager.sendTransaction(to, from, amount);
// }
//
// return null;
// }
// @Override
// public String sendMessage(String from, String to, String message) {
// if (manager != null) {
// return manager.sendMessage(from, to, message);
// }
// return null;
// }
//
//
// @Override
// public String sendMessage(byte[] body) {
// if (manager != null)
// return manager.sendMessage(body);
//
// return null;
// }
//
// @Override
// public List<Message> getNewMessages() {
// if (manager != null)
// return manager.getNewMessages();
//
// return null;
// }
//
// @Override
// public BlockchainBlock getBlock(long id) throws IOException {
// if (manager != null)
// return manager.getBlock(id);
//
// return null;
// }
//
// @Override
// public BlockchainPeer[] getPeers() throws IOException {
// if (manager != null)
// return manager.getPeers();
//
// return null;
// }
//
// @Override
// public BlockchainChainInfo getChain() throws IOException {
// if (manager != null)
// return manager.getChain();
//
// return null;
// }
//
// @Override
// public void authorize(String user, String password) {
// if (manager != null)
// manager.authorize(user, password);
// }
//
// public static void main(String[] args) throws IOException {
// BlockchainManager manager = new BlockchainManager("bitcoin", "http://127.0.0.1:6290");
// manager.authorize("multichainrpc", "3NPieLHgUEfEsdJeQpQstPDmHX1yasatPAw3SYGtY2Jr");
// System.out.println(manager.getBlock(0));
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: test-manager/src/main/java/uk/dsxt/bb/remote/instance/WorkFinishedTO.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public class WorkFinishedTO {
// private String ip;
// }
| import uk.dsxt.bb.remote.instance.WorkFinishedTO;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;
import java.util.stream.LongStream;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import lombok.extern.log4j.Log4j2;
import uk.dsxt.bb.blockchain.BlockchainManager;
import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo; | } catch (Exception e) {
log.error("Couldn't start Blockchain Logger.", e);
}
}
private void log(long lastLoggedBlockId, long currentBlockId, long time) throws IOException {
for (long i = lastLoggedBlockId + 1; i <= currentBlockId; ++i) {
StringJoiner stringJoiner = new StringJoiner(",");
stringJoiner.add(String.valueOf(i));
stringJoiner.add(String.valueOf(time));
fw.write(stringJoiner.toString() + '\n');
}
fw.flush();
}
private boolean isBlocksInRangeHasTransactions(long start, long end) {
return LongStream.rangeClosed(start + 1, end)
.parallel()
.anyMatch(i -> {
try {
return blockchainManager.getBlock(i).getTransactions().length > 0;
} catch (IOException e) {
log.error(e);
return false;
}
});
}
public void logInLoop() {
try {
if (blockchainManager != null) { | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/BlockchainManager.java
// @Log4j2
// public class BlockchainManager implements Manager {
//
// private String blockchainType;
// private String url;
//
// private Manager manager;
//
// public BlockchainManager(String blockchainType, String url) {
// this.blockchainType = blockchainType;
// this.url = url;
// switch (blockchainType) {
// case "fabric":
// manager = new FabricManager(url);
// break;
// case "bitcoin":
// manager = new BitcoinManager(url);
// break;
// case "ethereum":
// manager = new EthereumManager(url);
// break;
// case "multichain":
// manager = new MultichainManager(url);
// break;
// default:
// log.error(String.format("%s blockchain currently not supported or not exist. Currently supported: " +
// "fabric, bitcoin, ethereum, multichain", blockchainType));
// break;
// }
// }
//
// @Override
// public String sendTransaction(String to, String from, long amount) {
// if (manager != null) {
// return manager.sendTransaction(to, from, amount);
// }
//
// return null;
// }
// @Override
// public String sendMessage(String from, String to, String message) {
// if (manager != null) {
// return manager.sendMessage(from, to, message);
// }
// return null;
// }
//
//
// @Override
// public String sendMessage(byte[] body) {
// if (manager != null)
// return manager.sendMessage(body);
//
// return null;
// }
//
// @Override
// public List<Message> getNewMessages() {
// if (manager != null)
// return manager.getNewMessages();
//
// return null;
// }
//
// @Override
// public BlockchainBlock getBlock(long id) throws IOException {
// if (manager != null)
// return manager.getBlock(id);
//
// return null;
// }
//
// @Override
// public BlockchainPeer[] getPeers() throws IOException {
// if (manager != null)
// return manager.getPeers();
//
// return null;
// }
//
// @Override
// public BlockchainChainInfo getChain() throws IOException {
// if (manager != null)
// return manager.getChain();
//
// return null;
// }
//
// @Override
// public void authorize(String user, String password) {
// if (manager != null)
// manager.authorize(user, password);
// }
//
// public static void main(String[] args) throws IOException {
// BlockchainManager manager = new BlockchainManager("bitcoin", "http://127.0.0.1:6290");
// manager.authorize("multichainrpc", "3NPieLHgUEfEsdJeQpQstPDmHX1yasatPAw3SYGtY2Jr");
// System.out.println(manager.getBlock(0));
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: test-manager/src/main/java/uk/dsxt/bb/remote/instance/WorkFinishedTO.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public class WorkFinishedTO {
// private String ip;
// }
// Path: blockchain-logger/src/main/java/uk/dsxt/bb/logger/BlockchainLogger.java
import uk.dsxt.bb.remote.instance.WorkFinishedTO;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;
import java.util.stream.LongStream;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import lombok.extern.log4j.Log4j2;
import uk.dsxt.bb.blockchain.BlockchainManager;
import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo;
} catch (Exception e) {
log.error("Couldn't start Blockchain Logger.", e);
}
}
private void log(long lastLoggedBlockId, long currentBlockId, long time) throws IOException {
for (long i = lastLoggedBlockId + 1; i <= currentBlockId; ++i) {
StringJoiner stringJoiner = new StringJoiner(",");
stringJoiner.add(String.valueOf(i));
stringJoiner.add(String.valueOf(time));
fw.write(stringJoiner.toString() + '\n');
}
fw.flush();
}
private boolean isBlocksInRangeHasTransactions(long start, long end) {
return LongStream.rangeClosed(start + 1, end)
.parallel()
.anyMatch(i -> {
try {
return blockchainManager.getBlock(i).getTransactions().length > 0;
} catch (IOException e) {
log.error(e);
return false;
}
});
}
public void logInLoop() {
try {
if (blockchainManager != null) { | BlockchainChainInfo info = blockchainManager.getChain(); |
dsx-tech/blockchain-benchmarking | blockchain-logger/src/main/java/uk/dsxt/bb/logger/BlockchainLogger.java | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/BlockchainManager.java
// @Log4j2
// public class BlockchainManager implements Manager {
//
// private String blockchainType;
// private String url;
//
// private Manager manager;
//
// public BlockchainManager(String blockchainType, String url) {
// this.blockchainType = blockchainType;
// this.url = url;
// switch (blockchainType) {
// case "fabric":
// manager = new FabricManager(url);
// break;
// case "bitcoin":
// manager = new BitcoinManager(url);
// break;
// case "ethereum":
// manager = new EthereumManager(url);
// break;
// case "multichain":
// manager = new MultichainManager(url);
// break;
// default:
// log.error(String.format("%s blockchain currently not supported or not exist. Currently supported: " +
// "fabric, bitcoin, ethereum, multichain", blockchainType));
// break;
// }
// }
//
// @Override
// public String sendTransaction(String to, String from, long amount) {
// if (manager != null) {
// return manager.sendTransaction(to, from, amount);
// }
//
// return null;
// }
// @Override
// public String sendMessage(String from, String to, String message) {
// if (manager != null) {
// return manager.sendMessage(from, to, message);
// }
// return null;
// }
//
//
// @Override
// public String sendMessage(byte[] body) {
// if (manager != null)
// return manager.sendMessage(body);
//
// return null;
// }
//
// @Override
// public List<Message> getNewMessages() {
// if (manager != null)
// return manager.getNewMessages();
//
// return null;
// }
//
// @Override
// public BlockchainBlock getBlock(long id) throws IOException {
// if (manager != null)
// return manager.getBlock(id);
//
// return null;
// }
//
// @Override
// public BlockchainPeer[] getPeers() throws IOException {
// if (manager != null)
// return manager.getPeers();
//
// return null;
// }
//
// @Override
// public BlockchainChainInfo getChain() throws IOException {
// if (manager != null)
// return manager.getChain();
//
// return null;
// }
//
// @Override
// public void authorize(String user, String password) {
// if (manager != null)
// manager.authorize(user, password);
// }
//
// public static void main(String[] args) throws IOException {
// BlockchainManager manager = new BlockchainManager("bitcoin", "http://127.0.0.1:6290");
// manager.authorize("multichainrpc", "3NPieLHgUEfEsdJeQpQstPDmHX1yasatPAw3SYGtY2Jr");
// System.out.println(manager.getBlock(0));
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: test-manager/src/main/java/uk/dsxt/bb/remote/instance/WorkFinishedTO.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public class WorkFinishedTO {
// private String ip;
// }
| import uk.dsxt.bb.remote.instance.WorkFinishedTO;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;
import java.util.stream.LongStream;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import lombok.extern.log4j.Log4j2;
import uk.dsxt.bb.blockchain.BlockchainManager;
import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo; | });
}
public void logInLoop() {
try {
if (blockchainManager != null) {
BlockchainChainInfo info = blockchainManager.getChain();
if (info != null) {
StringJoiner stringJoiner = new StringJoiner(",");
stringJoiner.add("id");
stringJoiner.add("Appeared time");
fw.write(stringJoiner.toString() + '\n');
fw.flush();
long currentBlockId;
long previousBlockId = -1;
long lastNonEmptyBlockId = -1;
long lastNonEmptyBlockTime = System.currentTimeMillis();
while (true) {
long startLoopTime = System.currentTimeMillis();
currentBlockId = blockchainManager.getChain().getLastBlockNumber();
long currentBlockTime = System.currentTimeMillis();
if (currentBlockId > previousBlockId) {
log(previousBlockId, currentBlockId, currentBlockTime);
}
if ((startLoopTime - lastNonEmptyBlockTime > 10 * 60 * 1000) && !isBlocksInRangeHasTransactions(previousBlockId, currentBlockId)) {
ObjectMapper mapper = new ObjectMapper(); | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/BlockchainManager.java
// @Log4j2
// public class BlockchainManager implements Manager {
//
// private String blockchainType;
// private String url;
//
// private Manager manager;
//
// public BlockchainManager(String blockchainType, String url) {
// this.blockchainType = blockchainType;
// this.url = url;
// switch (blockchainType) {
// case "fabric":
// manager = new FabricManager(url);
// break;
// case "bitcoin":
// manager = new BitcoinManager(url);
// break;
// case "ethereum":
// manager = new EthereumManager(url);
// break;
// case "multichain":
// manager = new MultichainManager(url);
// break;
// default:
// log.error(String.format("%s blockchain currently not supported or not exist. Currently supported: " +
// "fabric, bitcoin, ethereum, multichain", blockchainType));
// break;
// }
// }
//
// @Override
// public String sendTransaction(String to, String from, long amount) {
// if (manager != null) {
// return manager.sendTransaction(to, from, amount);
// }
//
// return null;
// }
// @Override
// public String sendMessage(String from, String to, String message) {
// if (manager != null) {
// return manager.sendMessage(from, to, message);
// }
// return null;
// }
//
//
// @Override
// public String sendMessage(byte[] body) {
// if (manager != null)
// return manager.sendMessage(body);
//
// return null;
// }
//
// @Override
// public List<Message> getNewMessages() {
// if (manager != null)
// return manager.getNewMessages();
//
// return null;
// }
//
// @Override
// public BlockchainBlock getBlock(long id) throws IOException {
// if (manager != null)
// return manager.getBlock(id);
//
// return null;
// }
//
// @Override
// public BlockchainPeer[] getPeers() throws IOException {
// if (manager != null)
// return manager.getPeers();
//
// return null;
// }
//
// @Override
// public BlockchainChainInfo getChain() throws IOException {
// if (manager != null)
// return manager.getChain();
//
// return null;
// }
//
// @Override
// public void authorize(String user, String password) {
// if (manager != null)
// manager.authorize(user, password);
// }
//
// public static void main(String[] args) throws IOException {
// BlockchainManager manager = new BlockchainManager("bitcoin", "http://127.0.0.1:6290");
// manager.authorize("multichainrpc", "3NPieLHgUEfEsdJeQpQstPDmHX1yasatPAw3SYGtY2Jr");
// System.out.println(manager.getBlock(0));
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: test-manager/src/main/java/uk/dsxt/bb/remote/instance/WorkFinishedTO.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public class WorkFinishedTO {
// private String ip;
// }
// Path: blockchain-logger/src/main/java/uk/dsxt/bb/logger/BlockchainLogger.java
import uk.dsxt.bb.remote.instance.WorkFinishedTO;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;
import java.util.stream.LongStream;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import lombok.extern.log4j.Log4j2;
import uk.dsxt.bb.blockchain.BlockchainManager;
import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo;
});
}
public void logInLoop() {
try {
if (blockchainManager != null) {
BlockchainChainInfo info = blockchainManager.getChain();
if (info != null) {
StringJoiner stringJoiner = new StringJoiner(",");
stringJoiner.add("id");
stringJoiner.add("Appeared time");
fw.write(stringJoiner.toString() + '\n');
fw.flush();
long currentBlockId;
long previousBlockId = -1;
long lastNonEmptyBlockId = -1;
long lastNonEmptyBlockTime = System.currentTimeMillis();
while (true) {
long startLoopTime = System.currentTimeMillis();
currentBlockId = blockchainManager.getChain().getLastBlockNumber();
long currentBlockTime = System.currentTimeMillis();
if (currentBlockId > previousBlockId) {
log(previousBlockId, currentBlockId, currentBlockTime);
}
if ((startLoopTime - lastNonEmptyBlockTime > 10 * 60 * 1000) && !isBlocksInRangeHasTransactions(previousBlockId, currentBlockId)) {
ObjectMapper mapper = new ObjectMapper(); | WorkFinishedTO remoteInstanceStateTO = new WorkFinishedTO(ip); |
dsx-tech/blockchain-benchmarking | blockchain-logger/src/main/java/uk/dsxt/bb/logger/BlockchainLogger.java | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/BlockchainManager.java
// @Log4j2
// public class BlockchainManager implements Manager {
//
// private String blockchainType;
// private String url;
//
// private Manager manager;
//
// public BlockchainManager(String blockchainType, String url) {
// this.blockchainType = blockchainType;
// this.url = url;
// switch (blockchainType) {
// case "fabric":
// manager = new FabricManager(url);
// break;
// case "bitcoin":
// manager = new BitcoinManager(url);
// break;
// case "ethereum":
// manager = new EthereumManager(url);
// break;
// case "multichain":
// manager = new MultichainManager(url);
// break;
// default:
// log.error(String.format("%s blockchain currently not supported or not exist. Currently supported: " +
// "fabric, bitcoin, ethereum, multichain", blockchainType));
// break;
// }
// }
//
// @Override
// public String sendTransaction(String to, String from, long amount) {
// if (manager != null) {
// return manager.sendTransaction(to, from, amount);
// }
//
// return null;
// }
// @Override
// public String sendMessage(String from, String to, String message) {
// if (manager != null) {
// return manager.sendMessage(from, to, message);
// }
// return null;
// }
//
//
// @Override
// public String sendMessage(byte[] body) {
// if (manager != null)
// return manager.sendMessage(body);
//
// return null;
// }
//
// @Override
// public List<Message> getNewMessages() {
// if (manager != null)
// return manager.getNewMessages();
//
// return null;
// }
//
// @Override
// public BlockchainBlock getBlock(long id) throws IOException {
// if (manager != null)
// return manager.getBlock(id);
//
// return null;
// }
//
// @Override
// public BlockchainPeer[] getPeers() throws IOException {
// if (manager != null)
// return manager.getPeers();
//
// return null;
// }
//
// @Override
// public BlockchainChainInfo getChain() throws IOException {
// if (manager != null)
// return manager.getChain();
//
// return null;
// }
//
// @Override
// public void authorize(String user, String password) {
// if (manager != null)
// manager.authorize(user, password);
// }
//
// public static void main(String[] args) throws IOException {
// BlockchainManager manager = new BlockchainManager("bitcoin", "http://127.0.0.1:6290");
// manager.authorize("multichainrpc", "3NPieLHgUEfEsdJeQpQstPDmHX1yasatPAw3SYGtY2Jr");
// System.out.println(manager.getBlock(0));
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: test-manager/src/main/java/uk/dsxt/bb/remote/instance/WorkFinishedTO.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public class WorkFinishedTO {
// private String ip;
// }
| import uk.dsxt.bb.remote.instance.WorkFinishedTO;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;
import java.util.stream.LongStream;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import lombok.extern.log4j.Log4j2;
import uk.dsxt.bb.blockchain.BlockchainManager;
import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo; | stringJoiner.add("id");
stringJoiner.add("Appeared time");
fw.write(stringJoiner.toString() + '\n');
fw.flush();
long currentBlockId;
long previousBlockId = -1;
long lastNonEmptyBlockId = -1;
long lastNonEmptyBlockTime = System.currentTimeMillis();
while (true) {
long startLoopTime = System.currentTimeMillis();
currentBlockId = blockchainManager.getChain().getLastBlockNumber();
long currentBlockTime = System.currentTimeMillis();
if (currentBlockId > previousBlockId) {
log(previousBlockId, currentBlockId, currentBlockTime);
}
if ((startLoopTime - lastNonEmptyBlockTime > 10 * 60 * 1000) && !isBlocksInRangeHasTransactions(previousBlockId, currentBlockId)) {
ObjectMapper mapper = new ObjectMapper();
WorkFinishedTO remoteInstanceStateTO = new WorkFinishedTO(ip);
Unirest.post("http://" + masterHost + "/logger/state")
.body(mapper.writeValueAsString(remoteInstanceStateTO)).asJson();
break;
}
if (currentBlockId > previousBlockId) { | // Path: blockchain-api/src/main/java/uk/dsxt/bb/blockchain/BlockchainManager.java
// @Log4j2
// public class BlockchainManager implements Manager {
//
// private String blockchainType;
// private String url;
//
// private Manager manager;
//
// public BlockchainManager(String blockchainType, String url) {
// this.blockchainType = blockchainType;
// this.url = url;
// switch (blockchainType) {
// case "fabric":
// manager = new FabricManager(url);
// break;
// case "bitcoin":
// manager = new BitcoinManager(url);
// break;
// case "ethereum":
// manager = new EthereumManager(url);
// break;
// case "multichain":
// manager = new MultichainManager(url);
// break;
// default:
// log.error(String.format("%s blockchain currently not supported or not exist. Currently supported: " +
// "fabric, bitcoin, ethereum, multichain", blockchainType));
// break;
// }
// }
//
// @Override
// public String sendTransaction(String to, String from, long amount) {
// if (manager != null) {
// return manager.sendTransaction(to, from, amount);
// }
//
// return null;
// }
// @Override
// public String sendMessage(String from, String to, String message) {
// if (manager != null) {
// return manager.sendMessage(from, to, message);
// }
// return null;
// }
//
//
// @Override
// public String sendMessage(byte[] body) {
// if (manager != null)
// return manager.sendMessage(body);
//
// return null;
// }
//
// @Override
// public List<Message> getNewMessages() {
// if (manager != null)
// return manager.getNewMessages();
//
// return null;
// }
//
// @Override
// public BlockchainBlock getBlock(long id) throws IOException {
// if (manager != null)
// return manager.getBlock(id);
//
// return null;
// }
//
// @Override
// public BlockchainPeer[] getPeers() throws IOException {
// if (manager != null)
// return manager.getPeers();
//
// return null;
// }
//
// @Override
// public BlockchainChainInfo getChain() throws IOException {
// if (manager != null)
// return manager.getChain();
//
// return null;
// }
//
// @Override
// public void authorize(String user, String password) {
// if (manager != null)
// manager.authorize(user, password);
// }
//
// public static void main(String[] args) throws IOException {
// BlockchainManager manager = new BlockchainManager("bitcoin", "http://127.0.0.1:6290");
// manager.authorize("multichainrpc", "3NPieLHgUEfEsdJeQpQstPDmHX1yasatPAw3SYGtY2Jr");
// System.out.println(manager.getBlock(0));
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainBlock.java
// public interface BlockchainBlock {
// String hash = Strings.EMPTY;
// String previousBlockHash = Strings.EMPTY;
// BlockchainTransaction[] transactions = new BlockchainTransaction[0];
// long time = 0L;
//
// default String getHash() {
// return hash;
// }
//
// default String getPreviousBlockHash() {
// return previousBlockHash;
// }
//
// default BlockchainTransaction[] getTransactions() {
// return transactions;
// }
//
// default long getTime() {
// return time;
// }
// }
//
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
//
// Path: test-manager/src/main/java/uk/dsxt/bb/remote/instance/WorkFinishedTO.java
// @Data
// @NoArgsConstructor
// @AllArgsConstructor
// public class WorkFinishedTO {
// private String ip;
// }
// Path: blockchain-logger/src/main/java/uk/dsxt/bb/logger/BlockchainLogger.java
import uk.dsxt.bb.remote.instance.WorkFinishedTO;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;
import java.util.stream.LongStream;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import lombok.extern.log4j.Log4j2;
import uk.dsxt.bb.blockchain.BlockchainManager;
import uk.dsxt.bb.datamodel.blockchain.BlockchainBlock;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo;
stringJoiner.add("id");
stringJoiner.add("Appeared time");
fw.write(stringJoiner.toString() + '\n');
fw.flush();
long currentBlockId;
long previousBlockId = -1;
long lastNonEmptyBlockId = -1;
long lastNonEmptyBlockTime = System.currentTimeMillis();
while (true) {
long startLoopTime = System.currentTimeMillis();
currentBlockId = blockchainManager.getChain().getLastBlockNumber();
long currentBlockTime = System.currentTimeMillis();
if (currentBlockId > previousBlockId) {
log(previousBlockId, currentBlockId, currentBlockTime);
}
if ((startLoopTime - lastNonEmptyBlockTime > 10 * 60 * 1000) && !isBlocksInRangeHasTransactions(previousBlockId, currentBlockId)) {
ObjectMapper mapper = new ObjectMapper();
WorkFinishedTO remoteInstanceStateTO = new WorkFinishedTO(ip);
Unirest.post("http://" + masterHost + "/logger/state")
.body(mapper.writeValueAsString(remoteInstanceStateTO)).asJson();
break;
}
if (currentBlockId > previousBlockId) { | BlockchainBlock currentBlock = blockchainManager.getBlock(currentBlockId); |
dsx-tech/blockchain-benchmarking | blockchain-api/src/main/java/uk/dsxt/bb/datamodel/ethereum/EthereumInfo.java | // Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
| import lombok.AllArgsConstructor;
import lombok.Data;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo; | /*
******************************************************************************
* Blockchain benchmarking framework *
* Copyright (C) 2016 DSX Technologies Limited. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************
*/
package uk.dsxt.bb.datamodel.ethereum;
@Data
@AllArgsConstructor | // Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/blockchain/BlockchainChainInfo.java
// public interface BlockchainChainInfo {
// long lastBlockNumber = 0L;
//
// default long getLastBlockNumber() {
// return lastBlockNumber;
// }
// }
// Path: blockchain-api/src/main/java/uk/dsxt/bb/datamodel/ethereum/EthereumInfo.java
import lombok.AllArgsConstructor;
import lombok.Data;
import uk.dsxt.bb.datamodel.blockchain.BlockchainChainInfo;
/*
******************************************************************************
* Blockchain benchmarking framework *
* Copyright (C) 2016 DSX Technologies Limited. *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************
*/
package uk.dsxt.bb.datamodel.ethereum;
@Data
@AllArgsConstructor | public class EthereumInfo implements BlockchainChainInfo { |
lp895876294/genericdao | src/test/java/com/dao/genericdao/dao/TmpUserDao.java | // Path: src/test/java/com/dao/genericdao/entity/TmpUser.java
// @Entity
// @Table(name="user")
// @Getter
// @Setter
// public class TmpUser extends JPABaseEntity {
// private static final long serialVersionUID = 1L;
//
// /**
// * 用户名称
// */
// @Column(name="username")
// private String username ;
//
// @DateTimeFormat(pattern="yyyy-MM-dd")
// @Column(name="birthday")
// private Date birthday ;
//
// /**
// * 手机号
// */
// @Column(name="mobile")
// private String mobile ;
//
// @Column(name="avatarpath" , length=500)
// private String photo ;
//
// /**
// * 当前用户的状态
// */
// @Enumerated(EnumType.ORDINAL)
// @Column(name="activestate")
// private UserStatus userStatus = UserStatus.VALID ;
//
// @Temporal(TemporalType.TIMESTAMP)
// @Column(name="last_login_time")
// private Date lastloginTime ;
//
// /**
// * 登陆次数
// */
// @Column(name="login_count")
// private Long loginCount ;
//
// @Column(name="password")
// private String password ;
//
// /**
// * 所属部门
// */
// @Column
// private String department ;
//
// }
//
// Path: src/main/java/com/dao/genericdao/jpa/GenericJpaRepository.java
// @NoRepositoryBean
// public interface GenericJpaRepository<T, ID extends Serializable> extends JpaRepository<T, ID>,
// JpaSpecificationExecutor<T> , BaseDataRepository<T,ID> {
// /**
// * 统计加和运算
// * @param spec 查询条件
// * @param fieldName 字段名称
// * @param resultType 返回值类型
// * @return
// */
// public <S extends Number> S sum(String fieldName, Class<S> resultType, Specification<T> spec) ;
//
// /**
// * 查询多个字段
// * @param fields 查询字段数组
// * @param spec 查询条件
// * @return 返回list,每个元素为一个map对象,存储字段名称和字段值的映射
// */
// public List<Map<String, Object>> queryMultiFields(String[] fields, Specification<T> spec) ;
//
// /**
// * 查询单个字段
// * @param field
// * @param spec
// * @return 返回待查询字段的list对象
// */
// public List<String> querySingleFields(String field, Specification<T> spec) ;
//
// /**
// * 获取当前dao对应的实体管理器
// * @return
// */
// public EntityManager getEntityManager() ;
// }
//
// Path: src/main/java/com/dao/genericdao/mybatis/plugins/page/MybatisPage.java
// public interface MybatisPage<T> extends Page<T>, List<T> {
//
// }
| import com.dao.genericdao.annotation.MybatisQuery;
import com.dao.genericdao.entity.TmpUser;
import com.dao.genericdao.jpa.GenericJpaRepository;
import com.dao.genericdao.mybatis.plugins.page.MybatisPage;
import org.apache.ibatis.annotations.Param;
import org.springframework.data.domain.Pageable;
import java.util.List;
import java.util.Map; | package com.dao.genericdao.dao;
/**
* Created by liupeng on 2016-6-15.
*/
public interface TmpUserDao extends GenericJpaRepository<TmpUser,String> {
@MybatisQuery
List<TmpUser> findAll(@Param("param") Map<String,Object> searchParam) ;
@MybatisQuery | // Path: src/test/java/com/dao/genericdao/entity/TmpUser.java
// @Entity
// @Table(name="user")
// @Getter
// @Setter
// public class TmpUser extends JPABaseEntity {
// private static final long serialVersionUID = 1L;
//
// /**
// * 用户名称
// */
// @Column(name="username")
// private String username ;
//
// @DateTimeFormat(pattern="yyyy-MM-dd")
// @Column(name="birthday")
// private Date birthday ;
//
// /**
// * 手机号
// */
// @Column(name="mobile")
// private String mobile ;
//
// @Column(name="avatarpath" , length=500)
// private String photo ;
//
// /**
// * 当前用户的状态
// */
// @Enumerated(EnumType.ORDINAL)
// @Column(name="activestate")
// private UserStatus userStatus = UserStatus.VALID ;
//
// @Temporal(TemporalType.TIMESTAMP)
// @Column(name="last_login_time")
// private Date lastloginTime ;
//
// /**
// * 登陆次数
// */
// @Column(name="login_count")
// private Long loginCount ;
//
// @Column(name="password")
// private String password ;
//
// /**
// * 所属部门
// */
// @Column
// private String department ;
//
// }
//
// Path: src/main/java/com/dao/genericdao/jpa/GenericJpaRepository.java
// @NoRepositoryBean
// public interface GenericJpaRepository<T, ID extends Serializable> extends JpaRepository<T, ID>,
// JpaSpecificationExecutor<T> , BaseDataRepository<T,ID> {
// /**
// * 统计加和运算
// * @param spec 查询条件
// * @param fieldName 字段名称
// * @param resultType 返回值类型
// * @return
// */
// public <S extends Number> S sum(String fieldName, Class<S> resultType, Specification<T> spec) ;
//
// /**
// * 查询多个字段
// * @param fields 查询字段数组
// * @param spec 查询条件
// * @return 返回list,每个元素为一个map对象,存储字段名称和字段值的映射
// */
// public List<Map<String, Object>> queryMultiFields(String[] fields, Specification<T> spec) ;
//
// /**
// * 查询单个字段
// * @param field
// * @param spec
// * @return 返回待查询字段的list对象
// */
// public List<String> querySingleFields(String field, Specification<T> spec) ;
//
// /**
// * 获取当前dao对应的实体管理器
// * @return
// */
// public EntityManager getEntityManager() ;
// }
//
// Path: src/main/java/com/dao/genericdao/mybatis/plugins/page/MybatisPage.java
// public interface MybatisPage<T> extends Page<T>, List<T> {
//
// }
// Path: src/test/java/com/dao/genericdao/dao/TmpUserDao.java
import com.dao.genericdao.annotation.MybatisQuery;
import com.dao.genericdao.entity.TmpUser;
import com.dao.genericdao.jpa.GenericJpaRepository;
import com.dao.genericdao.mybatis.plugins.page.MybatisPage;
import org.apache.ibatis.annotations.Param;
import org.springframework.data.domain.Pageable;
import java.util.List;
import java.util.Map;
package com.dao.genericdao.dao;
/**
* Created by liupeng on 2016-6-15.
*/
public interface TmpUserDao extends GenericJpaRepository<TmpUser,String> {
@MybatisQuery
List<TmpUser> findAll(@Param("param") Map<String,Object> searchParam) ;
@MybatisQuery | MybatisPage<TmpUser> findAll(@Param("param") Map<String,Object> searchParam , Pageable pageable) ; |
lp895876294/genericdao | src/main/java/com/dao/genericdao/mybatis/plugins/page/MybatisPageRequest.java | // Path: src/main/java/com/dao/genericdao/mybatis/plugins/page/support/PageInterceptor.java
// @SuppressWarnings({"rawtypes", "unchecked"})
// @Intercepts(@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}))
// public class PageInterceptor implements Interceptor {
// //sql工具类
// private SqlUtil sqlUtil;
//
// /**
// * 开始分页
// *
// * @param pageNum 页码
// * @param pageSize 每页显示数量
// */
// public static PageHelper startPage(int pageNum, int pageSize) {
// return startPage(pageNum, pageSize, true);
// }
//
// /**
// * 开始分页
// *
// * @param pageNum 页码
// * @param pageSize 每页显示数量
// * @param orderBy 针对sqlserver - 建议在sql中直接包含order by
// */
// public static PageHelper startPage(int pageNum, int pageSize, String orderBy) {
// return startPage(pageNum, pageSize, true).orderBy(orderBy);
// }
//
// /**
// * 开始分页
// *
// * @param pageNum 页码
// * @param pageSize 每页显示数量
// * @param count 是否进行count查询
// */
// public static PageHelper startPage(int pageNum, int pageSize, boolean count) {
// return startPage(pageNum, pageSize, count, null);
// }
//
// /**
// * 开始分页
// *
// * @param pageNum 页码
// * @param pageSize 每页显示数量
// * @param count 是否进行count查询
// * @param reasonable 分页合理化,null时用默认配置
// */
// public static PageHelper startPage(int pageNum, int pageSize, boolean count, Boolean reasonable) {
// return startPage(pageNum, pageSize, count, reasonable, null);
// }
//
// /**
// * 开始分页
// *
// * @param pageNum 页码
// * @param pageSize 每页显示数量
// * @param count 是否进行count查询
// * @param reasonable 分页合理化,null时用默认配置
// * @param pageSizeZero true且pageSize=0时返回全部结果,false时分页,null时用默认配置
// */
// public static PageHelper startPage(int pageNum, int pageSize, boolean count, Boolean reasonable, Boolean pageSizeZero) {
// PageHelper page = new PageHelper(pageNum, pageSize, count);
// page.setReasonable(reasonable);
// page.setPageSizeZero(pageSizeZero);
// SqlUtil.setLocalPage(page);
// return page;
// }
//
// /**
// * 开始分页
// *
// * @param params
// */
// public static PageHelper startPage(Object params) {
// PageHelper page = SqlUtil.getPageFromObject(params);
// SqlUtil.setLocalPage(page);
// return page;
// }
//
//
// /**
// * Mybatis拦截器方法
// *
// * @param invocation 拦截器入参
// * @return 返回执行结果
// * @throws Throwable 抛出异常
// */
// public Object intercept(Invocation invocation) throws Throwable {
// return sqlUtil.processPage(invocation);
// }
//
// /**
// * 只拦截Executor
// *
// * @param target
// * @return
// */
// public Object plugin(Object target) {
// if (target instanceof Executor) {
// return Plugin.wrap(target, this);
// } else {
// return target;
// }
// }
//
// /**
// * 设置属性值
// *
// * @param p 属性值
// */
// public void setProperties(Properties p) {
// //数据库方言
// String dialect = p.getProperty("dialect");
// sqlUtil = new SqlUtil(dialect);
// sqlUtil.setProperties(p);
// }
// }
| import com.dao.genericdao.mybatis.plugins.page.support.PageInterceptor;
import org.springframework.data.domain.PageRequest; | package com.dao.genericdao.mybatis.plugins.page;
/**
* mybatis分页请求,分页号由0开始
* 通过通用的接口PageRequest将分页号等参数暂存起来。
* 在后续的mybatis接口中并没有直接使用PageRequest类
*/
public class MybatisPageRequest extends PageRequest {
private static final long serialVersionUID = 1L;
/**
* 创建mybatis分页请求,分页号(pageNum)由0开始
* @param pageNum
* @param pageSize
*/
public MybatisPageRequest(int pageNum, int pageSize) {
super(pageNum, pageSize);
//设置分页信息 | // Path: src/main/java/com/dao/genericdao/mybatis/plugins/page/support/PageInterceptor.java
// @SuppressWarnings({"rawtypes", "unchecked"})
// @Intercepts(@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}))
// public class PageInterceptor implements Interceptor {
// //sql工具类
// private SqlUtil sqlUtil;
//
// /**
// * 开始分页
// *
// * @param pageNum 页码
// * @param pageSize 每页显示数量
// */
// public static PageHelper startPage(int pageNum, int pageSize) {
// return startPage(pageNum, pageSize, true);
// }
//
// /**
// * 开始分页
// *
// * @param pageNum 页码
// * @param pageSize 每页显示数量
// * @param orderBy 针对sqlserver - 建议在sql中直接包含order by
// */
// public static PageHelper startPage(int pageNum, int pageSize, String orderBy) {
// return startPage(pageNum, pageSize, true).orderBy(orderBy);
// }
//
// /**
// * 开始分页
// *
// * @param pageNum 页码
// * @param pageSize 每页显示数量
// * @param count 是否进行count查询
// */
// public static PageHelper startPage(int pageNum, int pageSize, boolean count) {
// return startPage(pageNum, pageSize, count, null);
// }
//
// /**
// * 开始分页
// *
// * @param pageNum 页码
// * @param pageSize 每页显示数量
// * @param count 是否进行count查询
// * @param reasonable 分页合理化,null时用默认配置
// */
// public static PageHelper startPage(int pageNum, int pageSize, boolean count, Boolean reasonable) {
// return startPage(pageNum, pageSize, count, reasonable, null);
// }
//
// /**
// * 开始分页
// *
// * @param pageNum 页码
// * @param pageSize 每页显示数量
// * @param count 是否进行count查询
// * @param reasonable 分页合理化,null时用默认配置
// * @param pageSizeZero true且pageSize=0时返回全部结果,false时分页,null时用默认配置
// */
// public static PageHelper startPage(int pageNum, int pageSize, boolean count, Boolean reasonable, Boolean pageSizeZero) {
// PageHelper page = new PageHelper(pageNum, pageSize, count);
// page.setReasonable(reasonable);
// page.setPageSizeZero(pageSizeZero);
// SqlUtil.setLocalPage(page);
// return page;
// }
//
// /**
// * 开始分页
// *
// * @param params
// */
// public static PageHelper startPage(Object params) {
// PageHelper page = SqlUtil.getPageFromObject(params);
// SqlUtil.setLocalPage(page);
// return page;
// }
//
//
// /**
// * Mybatis拦截器方法
// *
// * @param invocation 拦截器入参
// * @return 返回执行结果
// * @throws Throwable 抛出异常
// */
// public Object intercept(Invocation invocation) throws Throwable {
// return sqlUtil.processPage(invocation);
// }
//
// /**
// * 只拦截Executor
// *
// * @param target
// * @return
// */
// public Object plugin(Object target) {
// if (target instanceof Executor) {
// return Plugin.wrap(target, this);
// } else {
// return target;
// }
// }
//
// /**
// * 设置属性值
// *
// * @param p 属性值
// */
// public void setProperties(Properties p) {
// //数据库方言
// String dialect = p.getProperty("dialect");
// sqlUtil = new SqlUtil(dialect);
// sqlUtil.setProperties(p);
// }
// }
// Path: src/main/java/com/dao/genericdao/mybatis/plugins/page/MybatisPageRequest.java
import com.dao.genericdao.mybatis.plugins.page.support.PageInterceptor;
import org.springframework.data.domain.PageRequest;
package com.dao.genericdao.mybatis.plugins.page;
/**
* mybatis分页请求,分页号由0开始
* 通过通用的接口PageRequest将分页号等参数暂存起来。
* 在后续的mybatis接口中并没有直接使用PageRequest类
*/
public class MybatisPageRequest extends PageRequest {
private static final long serialVersionUID = 1L;
/**
* 创建mybatis分页请求,分页号(pageNum)由0开始
* @param pageNum
* @param pageSize
*/
public MybatisPageRequest(int pageNum, int pageSize) {
super(pageNum, pageSize);
//设置分页信息 | PageInterceptor.startPage(pageNum+1, pageSize) ; |
lp895876294/genericdao | src/test/java/com/dao/genericdao/test/TestTmpUserDao.java | // Path: src/test/java/com/dao/genericdao/base/BaseTest.java
// @RunWith(SpringJUnit4ClassRunner.class)
// @ContextConfiguration(classes = BaseConfig.class)
// @Rollback(value = false)
// @Transactional
// public class BaseTest {
// }
//
// Path: src/test/java/com/dao/genericdao/dao/TmpUserDao.java
// public interface TmpUserDao extends GenericJpaRepository<TmpUser,String> {
//
// @MybatisQuery
// List<TmpUser> findAll(@Param("param") Map<String,Object> searchParam) ;
//
// @MybatisQuery
// MybatisPage<TmpUser> findAll(@Param("param") Map<String,Object> searchParam , Pageable pageable) ;
//
// }
//
// Path: src/test/java/com/dao/genericdao/entity/TmpUser.java
// @Entity
// @Table(name="user")
// @Getter
// @Setter
// public class TmpUser extends JPABaseEntity {
// private static final long serialVersionUID = 1L;
//
// /**
// * 用户名称
// */
// @Column(name="username")
// private String username ;
//
// @DateTimeFormat(pattern="yyyy-MM-dd")
// @Column(name="birthday")
// private Date birthday ;
//
// /**
// * 手机号
// */
// @Column(name="mobile")
// private String mobile ;
//
// @Column(name="avatarpath" , length=500)
// private String photo ;
//
// /**
// * 当前用户的状态
// */
// @Enumerated(EnumType.ORDINAL)
// @Column(name="activestate")
// private UserStatus userStatus = UserStatus.VALID ;
//
// @Temporal(TemporalType.TIMESTAMP)
// @Column(name="last_login_time")
// private Date lastloginTime ;
//
// /**
// * 登陆次数
// */
// @Column(name="login_count")
// private Long loginCount ;
//
// @Column(name="password")
// private String password ;
//
// /**
// * 所属部门
// */
// @Column
// private String department ;
//
// }
//
// Path: src/main/java/com/dao/genericdao/mybatis/plugins/page/MybatisPageRequest.java
// public class MybatisPageRequest extends PageRequest {
// private static final long serialVersionUID = 1L;
// /**
// * 创建mybatis分页请求,分页号(pageNum)由0开始
// * @param pageNum
// * @param pageSize
// */
// public MybatisPageRequest(int pageNum, int pageSize) {
// super(pageNum, pageSize);
// //设置分页信息
// PageInterceptor.startPage(pageNum+1, pageSize) ;
// }
//
// public MybatisPageRequest() {
// super(0, 1);
// }
// }
| import com.alibaba.fastjson.JSON;
import com.dao.genericdao.base.BaseTest;
import com.dao.genericdao.dao.TmpUserDao;
import com.dao.genericdao.entity.TmpUser;
import com.dao.genericdao.mybatis.plugins.page.MybatisPageRequest;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import java.util.Map;
import java.util.UUID; | package com.dao.genericdao.test;
@Slf4j
public class TestTmpUserDao extends BaseTest {
@Autowired | // Path: src/test/java/com/dao/genericdao/base/BaseTest.java
// @RunWith(SpringJUnit4ClassRunner.class)
// @ContextConfiguration(classes = BaseConfig.class)
// @Rollback(value = false)
// @Transactional
// public class BaseTest {
// }
//
// Path: src/test/java/com/dao/genericdao/dao/TmpUserDao.java
// public interface TmpUserDao extends GenericJpaRepository<TmpUser,String> {
//
// @MybatisQuery
// List<TmpUser> findAll(@Param("param") Map<String,Object> searchParam) ;
//
// @MybatisQuery
// MybatisPage<TmpUser> findAll(@Param("param") Map<String,Object> searchParam , Pageable pageable) ;
//
// }
//
// Path: src/test/java/com/dao/genericdao/entity/TmpUser.java
// @Entity
// @Table(name="user")
// @Getter
// @Setter
// public class TmpUser extends JPABaseEntity {
// private static final long serialVersionUID = 1L;
//
// /**
// * 用户名称
// */
// @Column(name="username")
// private String username ;
//
// @DateTimeFormat(pattern="yyyy-MM-dd")
// @Column(name="birthday")
// private Date birthday ;
//
// /**
// * 手机号
// */
// @Column(name="mobile")
// private String mobile ;
//
// @Column(name="avatarpath" , length=500)
// private String photo ;
//
// /**
// * 当前用户的状态
// */
// @Enumerated(EnumType.ORDINAL)
// @Column(name="activestate")
// private UserStatus userStatus = UserStatus.VALID ;
//
// @Temporal(TemporalType.TIMESTAMP)
// @Column(name="last_login_time")
// private Date lastloginTime ;
//
// /**
// * 登陆次数
// */
// @Column(name="login_count")
// private Long loginCount ;
//
// @Column(name="password")
// private String password ;
//
// /**
// * 所属部门
// */
// @Column
// private String department ;
//
// }
//
// Path: src/main/java/com/dao/genericdao/mybatis/plugins/page/MybatisPageRequest.java
// public class MybatisPageRequest extends PageRequest {
// private static final long serialVersionUID = 1L;
// /**
// * 创建mybatis分页请求,分页号(pageNum)由0开始
// * @param pageNum
// * @param pageSize
// */
// public MybatisPageRequest(int pageNum, int pageSize) {
// super(pageNum, pageSize);
// //设置分页信息
// PageInterceptor.startPage(pageNum+1, pageSize) ;
// }
//
// public MybatisPageRequest() {
// super(0, 1);
// }
// }
// Path: src/test/java/com/dao/genericdao/test/TestTmpUserDao.java
import com.alibaba.fastjson.JSON;
import com.dao.genericdao.base.BaseTest;
import com.dao.genericdao.dao.TmpUserDao;
import com.dao.genericdao.entity.TmpUser;
import com.dao.genericdao.mybatis.plugins.page.MybatisPageRequest;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import java.util.Map;
import java.util.UUID;
package com.dao.genericdao.test;
@Slf4j
public class TestTmpUserDao extends BaseTest {
@Autowired | private TmpUserDao tmpUserDao ; |
lp895876294/genericdao | src/test/java/com/dao/genericdao/test/TestTmpUserDao.java | // Path: src/test/java/com/dao/genericdao/base/BaseTest.java
// @RunWith(SpringJUnit4ClassRunner.class)
// @ContextConfiguration(classes = BaseConfig.class)
// @Rollback(value = false)
// @Transactional
// public class BaseTest {
// }
//
// Path: src/test/java/com/dao/genericdao/dao/TmpUserDao.java
// public interface TmpUserDao extends GenericJpaRepository<TmpUser,String> {
//
// @MybatisQuery
// List<TmpUser> findAll(@Param("param") Map<String,Object> searchParam) ;
//
// @MybatisQuery
// MybatisPage<TmpUser> findAll(@Param("param") Map<String,Object> searchParam , Pageable pageable) ;
//
// }
//
// Path: src/test/java/com/dao/genericdao/entity/TmpUser.java
// @Entity
// @Table(name="user")
// @Getter
// @Setter
// public class TmpUser extends JPABaseEntity {
// private static final long serialVersionUID = 1L;
//
// /**
// * 用户名称
// */
// @Column(name="username")
// private String username ;
//
// @DateTimeFormat(pattern="yyyy-MM-dd")
// @Column(name="birthday")
// private Date birthday ;
//
// /**
// * 手机号
// */
// @Column(name="mobile")
// private String mobile ;
//
// @Column(name="avatarpath" , length=500)
// private String photo ;
//
// /**
// * 当前用户的状态
// */
// @Enumerated(EnumType.ORDINAL)
// @Column(name="activestate")
// private UserStatus userStatus = UserStatus.VALID ;
//
// @Temporal(TemporalType.TIMESTAMP)
// @Column(name="last_login_time")
// private Date lastloginTime ;
//
// /**
// * 登陆次数
// */
// @Column(name="login_count")
// private Long loginCount ;
//
// @Column(name="password")
// private String password ;
//
// /**
// * 所属部门
// */
// @Column
// private String department ;
//
// }
//
// Path: src/main/java/com/dao/genericdao/mybatis/plugins/page/MybatisPageRequest.java
// public class MybatisPageRequest extends PageRequest {
// private static final long serialVersionUID = 1L;
// /**
// * 创建mybatis分页请求,分页号(pageNum)由0开始
// * @param pageNum
// * @param pageSize
// */
// public MybatisPageRequest(int pageNum, int pageSize) {
// super(pageNum, pageSize);
// //设置分页信息
// PageInterceptor.startPage(pageNum+1, pageSize) ;
// }
//
// public MybatisPageRequest() {
// super(0, 1);
// }
// }
| import com.alibaba.fastjson.JSON;
import com.dao.genericdao.base.BaseTest;
import com.dao.genericdao.dao.TmpUserDao;
import com.dao.genericdao.entity.TmpUser;
import com.dao.genericdao.mybatis.plugins.page.MybatisPageRequest;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import java.util.Map;
import java.util.UUID; | package com.dao.genericdao.test;
@Slf4j
public class TestTmpUserDao extends BaseTest {
@Autowired
private TmpUserDao tmpUserDao ;
public void testSave(){ | // Path: src/test/java/com/dao/genericdao/base/BaseTest.java
// @RunWith(SpringJUnit4ClassRunner.class)
// @ContextConfiguration(classes = BaseConfig.class)
// @Rollback(value = false)
// @Transactional
// public class BaseTest {
// }
//
// Path: src/test/java/com/dao/genericdao/dao/TmpUserDao.java
// public interface TmpUserDao extends GenericJpaRepository<TmpUser,String> {
//
// @MybatisQuery
// List<TmpUser> findAll(@Param("param") Map<String,Object> searchParam) ;
//
// @MybatisQuery
// MybatisPage<TmpUser> findAll(@Param("param") Map<String,Object> searchParam , Pageable pageable) ;
//
// }
//
// Path: src/test/java/com/dao/genericdao/entity/TmpUser.java
// @Entity
// @Table(name="user")
// @Getter
// @Setter
// public class TmpUser extends JPABaseEntity {
// private static final long serialVersionUID = 1L;
//
// /**
// * 用户名称
// */
// @Column(name="username")
// private String username ;
//
// @DateTimeFormat(pattern="yyyy-MM-dd")
// @Column(name="birthday")
// private Date birthday ;
//
// /**
// * 手机号
// */
// @Column(name="mobile")
// private String mobile ;
//
// @Column(name="avatarpath" , length=500)
// private String photo ;
//
// /**
// * 当前用户的状态
// */
// @Enumerated(EnumType.ORDINAL)
// @Column(name="activestate")
// private UserStatus userStatus = UserStatus.VALID ;
//
// @Temporal(TemporalType.TIMESTAMP)
// @Column(name="last_login_time")
// private Date lastloginTime ;
//
// /**
// * 登陆次数
// */
// @Column(name="login_count")
// private Long loginCount ;
//
// @Column(name="password")
// private String password ;
//
// /**
// * 所属部门
// */
// @Column
// private String department ;
//
// }
//
// Path: src/main/java/com/dao/genericdao/mybatis/plugins/page/MybatisPageRequest.java
// public class MybatisPageRequest extends PageRequest {
// private static final long serialVersionUID = 1L;
// /**
// * 创建mybatis分页请求,分页号(pageNum)由0开始
// * @param pageNum
// * @param pageSize
// */
// public MybatisPageRequest(int pageNum, int pageSize) {
// super(pageNum, pageSize);
// //设置分页信息
// PageInterceptor.startPage(pageNum+1, pageSize) ;
// }
//
// public MybatisPageRequest() {
// super(0, 1);
// }
// }
// Path: src/test/java/com/dao/genericdao/test/TestTmpUserDao.java
import com.alibaba.fastjson.JSON;
import com.dao.genericdao.base.BaseTest;
import com.dao.genericdao.dao.TmpUserDao;
import com.dao.genericdao.entity.TmpUser;
import com.dao.genericdao.mybatis.plugins.page.MybatisPageRequest;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import java.util.Map;
import java.util.UUID;
package com.dao.genericdao.test;
@Slf4j
public class TestTmpUserDao extends BaseTest {
@Autowired
private TmpUserDao tmpUserDao ;
public void testSave(){ | TmpUser tmpUser = new TmpUser() ; |
lp895876294/genericdao | src/test/java/com/dao/genericdao/test/TestTmpUserDao.java | // Path: src/test/java/com/dao/genericdao/base/BaseTest.java
// @RunWith(SpringJUnit4ClassRunner.class)
// @ContextConfiguration(classes = BaseConfig.class)
// @Rollback(value = false)
// @Transactional
// public class BaseTest {
// }
//
// Path: src/test/java/com/dao/genericdao/dao/TmpUserDao.java
// public interface TmpUserDao extends GenericJpaRepository<TmpUser,String> {
//
// @MybatisQuery
// List<TmpUser> findAll(@Param("param") Map<String,Object> searchParam) ;
//
// @MybatisQuery
// MybatisPage<TmpUser> findAll(@Param("param") Map<String,Object> searchParam , Pageable pageable) ;
//
// }
//
// Path: src/test/java/com/dao/genericdao/entity/TmpUser.java
// @Entity
// @Table(name="user")
// @Getter
// @Setter
// public class TmpUser extends JPABaseEntity {
// private static final long serialVersionUID = 1L;
//
// /**
// * 用户名称
// */
// @Column(name="username")
// private String username ;
//
// @DateTimeFormat(pattern="yyyy-MM-dd")
// @Column(name="birthday")
// private Date birthday ;
//
// /**
// * 手机号
// */
// @Column(name="mobile")
// private String mobile ;
//
// @Column(name="avatarpath" , length=500)
// private String photo ;
//
// /**
// * 当前用户的状态
// */
// @Enumerated(EnumType.ORDINAL)
// @Column(name="activestate")
// private UserStatus userStatus = UserStatus.VALID ;
//
// @Temporal(TemporalType.TIMESTAMP)
// @Column(name="last_login_time")
// private Date lastloginTime ;
//
// /**
// * 登陆次数
// */
// @Column(name="login_count")
// private Long loginCount ;
//
// @Column(name="password")
// private String password ;
//
// /**
// * 所属部门
// */
// @Column
// private String department ;
//
// }
//
// Path: src/main/java/com/dao/genericdao/mybatis/plugins/page/MybatisPageRequest.java
// public class MybatisPageRequest extends PageRequest {
// private static final long serialVersionUID = 1L;
// /**
// * 创建mybatis分页请求,分页号(pageNum)由0开始
// * @param pageNum
// * @param pageSize
// */
// public MybatisPageRequest(int pageNum, int pageSize) {
// super(pageNum, pageSize);
// //设置分页信息
// PageInterceptor.startPage(pageNum+1, pageSize) ;
// }
//
// public MybatisPageRequest() {
// super(0, 1);
// }
// }
| import com.alibaba.fastjson.JSON;
import com.dao.genericdao.base.BaseTest;
import com.dao.genericdao.dao.TmpUserDao;
import com.dao.genericdao.entity.TmpUser;
import com.dao.genericdao.mybatis.plugins.page.MybatisPageRequest;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import java.util.Map;
import java.util.UUID; | package com.dao.genericdao.test;
@Slf4j
public class TestTmpUserDao extends BaseTest {
@Autowired
private TmpUserDao tmpUserDao ;
public void testSave(){
TmpUser tmpUser = new TmpUser() ;
tmpUser.setUsername("lp,"+ UUID.randomUUID().toString()) ;
tmpUser.setPhoto("my photo path") ;
tmpUserDao.save(tmpUser) ;
}
@Test
public void queryAll(){
Map<String,Object> searchParam = Maps.newHashMap() ;
| // Path: src/test/java/com/dao/genericdao/base/BaseTest.java
// @RunWith(SpringJUnit4ClassRunner.class)
// @ContextConfiguration(classes = BaseConfig.class)
// @Rollback(value = false)
// @Transactional
// public class BaseTest {
// }
//
// Path: src/test/java/com/dao/genericdao/dao/TmpUserDao.java
// public interface TmpUserDao extends GenericJpaRepository<TmpUser,String> {
//
// @MybatisQuery
// List<TmpUser> findAll(@Param("param") Map<String,Object> searchParam) ;
//
// @MybatisQuery
// MybatisPage<TmpUser> findAll(@Param("param") Map<String,Object> searchParam , Pageable pageable) ;
//
// }
//
// Path: src/test/java/com/dao/genericdao/entity/TmpUser.java
// @Entity
// @Table(name="user")
// @Getter
// @Setter
// public class TmpUser extends JPABaseEntity {
// private static final long serialVersionUID = 1L;
//
// /**
// * 用户名称
// */
// @Column(name="username")
// private String username ;
//
// @DateTimeFormat(pattern="yyyy-MM-dd")
// @Column(name="birthday")
// private Date birthday ;
//
// /**
// * 手机号
// */
// @Column(name="mobile")
// private String mobile ;
//
// @Column(name="avatarpath" , length=500)
// private String photo ;
//
// /**
// * 当前用户的状态
// */
// @Enumerated(EnumType.ORDINAL)
// @Column(name="activestate")
// private UserStatus userStatus = UserStatus.VALID ;
//
// @Temporal(TemporalType.TIMESTAMP)
// @Column(name="last_login_time")
// private Date lastloginTime ;
//
// /**
// * 登陆次数
// */
// @Column(name="login_count")
// private Long loginCount ;
//
// @Column(name="password")
// private String password ;
//
// /**
// * 所属部门
// */
// @Column
// private String department ;
//
// }
//
// Path: src/main/java/com/dao/genericdao/mybatis/plugins/page/MybatisPageRequest.java
// public class MybatisPageRequest extends PageRequest {
// private static final long serialVersionUID = 1L;
// /**
// * 创建mybatis分页请求,分页号(pageNum)由0开始
// * @param pageNum
// * @param pageSize
// */
// public MybatisPageRequest(int pageNum, int pageSize) {
// super(pageNum, pageSize);
// //设置分页信息
// PageInterceptor.startPage(pageNum+1, pageSize) ;
// }
//
// public MybatisPageRequest() {
// super(0, 1);
// }
// }
// Path: src/test/java/com/dao/genericdao/test/TestTmpUserDao.java
import com.alibaba.fastjson.JSON;
import com.dao.genericdao.base.BaseTest;
import com.dao.genericdao.dao.TmpUserDao;
import com.dao.genericdao.entity.TmpUser;
import com.dao.genericdao.mybatis.plugins.page.MybatisPageRequest;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import java.util.Map;
import java.util.UUID;
package com.dao.genericdao.test;
@Slf4j
public class TestTmpUserDao extends BaseTest {
@Autowired
private TmpUserDao tmpUserDao ;
public void testSave(){
TmpUser tmpUser = new TmpUser() ;
tmpUser.setUsername("lp,"+ UUID.randomUUID().toString()) ;
tmpUser.setPhoto("my photo path") ;
tmpUserDao.save(tmpUser) ;
}
@Test
public void queryAll(){
Map<String,Object> searchParam = Maps.newHashMap() ;
| Page<TmpUser> result = tmpUserDao.findAll(searchParam , new MybatisPageRequest(0,1)) ; |
lp895876294/genericdao | src/main/java/com/dao/genericdao/mybatis/plugins/page/support/SqlUtil.java | // Path: src/main/java/com/dao/genericdao/mybatis/plugins/page/MybatisPageImpl.java
// public class MybatisPageImpl<T> extends ArrayList<T> implements MybatisPage<T> {
//
// private PageHelper page ;
//
// public MybatisPageImpl(){
//
// }
//
// public MybatisPageImpl(PageHelper page){
// super(page.getPageSize()) ;
//
// this.page = page ;
//
// this.addAll(page) ;
// }
//
// @Override
// public int getNumber() {
// return page.getPageNum() ;
// }
//
// @Override
// public int getSize() {
// return page.getPageSize() ;
// }
//
// @Override
// public int getNumberOfElements() {
// return this.size();
// }
//
// @Override
// public List<T> getContent() {
// return this;
// }
//
// @Override
// public boolean hasContent() {
// return !this.isEmpty();
// }
//
// @Override
// public Sort getSort() {
// return null;
// }
//
// @Override
// public boolean isFirst() {
// return page.getPageNum()==1;
// }
//
// @Override
// public boolean isLast() {
// return page.getPageNum() == page.getPages() ;
// }
//
// @Override
// public boolean hasNext() {
// return page.getPages()>page.getPageNum();
// }
//
// @Override
// public boolean hasPrevious() {
// return page.getPageNum()>1;
// }
//
// @Override
// public Pageable nextPageable() {
// return this.hasNext() ? new PageRequest(page.getPageNum()+1, page.getPageSize()) : null ;
// }
//
// @Override
// public Pageable previousPageable() {
// return this.hasPrevious() ? new PageRequest(page.getPageNum()-1, page.getPageSize()) : null ;
// }
//
// @Override
// public int getTotalPages() {
// return page.getPages();
// }
//
// @Override
// public long getTotalElements() {
// return page.getTotal();
// }
//
// @Override
// public <S> Page<S> map(Converter<? super T, ? extends S> converter) {
// return null;
// }
//
// }
| import com.dao.genericdao.mybatis.plugins.page.MybatisPageImpl;
import org.apache.ibatis.builder.SqlSourceBuilder;
import org.apache.ibatis.builder.StaticSqlSource;
import org.apache.ibatis.builder.annotation.ProviderSqlSource;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.scripting.xmltags.DynamicContext;
import org.apache.ibatis.scripting.xmltags.DynamicSqlSource;
import org.apache.ibatis.scripting.xmltags.MixedSqlNode;
import org.apache.ibatis.scripting.xmltags.SqlNode;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.RowBounds;
import java.lang.reflect.Method;
import java.util.*; | * @param required
* @return
*/
public static Object getParamValue(MetaObject paramsObject, String paramName, boolean required) {
Object value = null;
if (paramsObject.hasGetter(PARAMS.get(paramName))) {
value = paramsObject.getValue(PARAMS.get(paramName));
}
if (required && value == null) {
throw new RuntimeException("分页查询缺少必要的参数:" + PARAMS.get(paramName));
}
return value;
}
/**
* Mybatis拦截器方法
*
* @param invocation 拦截器入参
* @return 返回执行结果
* @throws Throwable 抛出异常
*/
public Object processPage(Invocation invocation) throws Throwable {
try{
Object result = _processPage(invocation);
clearLocalPage();
//扩展当前分页对象,使用spring的分页对象
if(result instanceof PageHelper){
// MybatisPage page = (MybatisPage) result ;
// Page resultPage = new PageImpl(page , new PageRequest(page.getPageNum(), page.getPageSize()), page.getTotal()) ;
// return resultPage ; | // Path: src/main/java/com/dao/genericdao/mybatis/plugins/page/MybatisPageImpl.java
// public class MybatisPageImpl<T> extends ArrayList<T> implements MybatisPage<T> {
//
// private PageHelper page ;
//
// public MybatisPageImpl(){
//
// }
//
// public MybatisPageImpl(PageHelper page){
// super(page.getPageSize()) ;
//
// this.page = page ;
//
// this.addAll(page) ;
// }
//
// @Override
// public int getNumber() {
// return page.getPageNum() ;
// }
//
// @Override
// public int getSize() {
// return page.getPageSize() ;
// }
//
// @Override
// public int getNumberOfElements() {
// return this.size();
// }
//
// @Override
// public List<T> getContent() {
// return this;
// }
//
// @Override
// public boolean hasContent() {
// return !this.isEmpty();
// }
//
// @Override
// public Sort getSort() {
// return null;
// }
//
// @Override
// public boolean isFirst() {
// return page.getPageNum()==1;
// }
//
// @Override
// public boolean isLast() {
// return page.getPageNum() == page.getPages() ;
// }
//
// @Override
// public boolean hasNext() {
// return page.getPages()>page.getPageNum();
// }
//
// @Override
// public boolean hasPrevious() {
// return page.getPageNum()>1;
// }
//
// @Override
// public Pageable nextPageable() {
// return this.hasNext() ? new PageRequest(page.getPageNum()+1, page.getPageSize()) : null ;
// }
//
// @Override
// public Pageable previousPageable() {
// return this.hasPrevious() ? new PageRequest(page.getPageNum()-1, page.getPageSize()) : null ;
// }
//
// @Override
// public int getTotalPages() {
// return page.getPages();
// }
//
// @Override
// public long getTotalElements() {
// return page.getTotal();
// }
//
// @Override
// public <S> Page<S> map(Converter<? super T, ? extends S> converter) {
// return null;
// }
//
// }
// Path: src/main/java/com/dao/genericdao/mybatis/plugins/page/support/SqlUtil.java
import com.dao.genericdao.mybatis.plugins.page.MybatisPageImpl;
import org.apache.ibatis.builder.SqlSourceBuilder;
import org.apache.ibatis.builder.StaticSqlSource;
import org.apache.ibatis.builder.annotation.ProviderSqlSource;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.scripting.xmltags.DynamicContext;
import org.apache.ibatis.scripting.xmltags.DynamicSqlSource;
import org.apache.ibatis.scripting.xmltags.MixedSqlNode;
import org.apache.ibatis.scripting.xmltags.SqlNode;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.RowBounds;
import java.lang.reflect.Method;
import java.util.*;
* @param required
* @return
*/
public static Object getParamValue(MetaObject paramsObject, String paramName, boolean required) {
Object value = null;
if (paramsObject.hasGetter(PARAMS.get(paramName))) {
value = paramsObject.getValue(PARAMS.get(paramName));
}
if (required && value == null) {
throw new RuntimeException("分页查询缺少必要的参数:" + PARAMS.get(paramName));
}
return value;
}
/**
* Mybatis拦截器方法
*
* @param invocation 拦截器入参
* @return 返回执行结果
* @throws Throwable 抛出异常
*/
public Object processPage(Invocation invocation) throws Throwable {
try{
Object result = _processPage(invocation);
clearLocalPage();
//扩展当前分页对象,使用spring的分页对象
if(result instanceof PageHelper){
// MybatisPage page = (MybatisPage) result ;
// Page resultPage = new PageImpl(page , new PageRequest(page.getPageNum(), page.getPageSize()), page.getTotal()) ;
// return resultPage ; | return new MybatisPageImpl((PageHelper) result) ; |
lp895876294/genericdao | src/test/java/com/dao/genericdao/entity/TmpUser.java | // Path: src/test/java/com/dao/genericdao/entity/support/UserStatus.java
// public enum UserStatus {
// DELETED , INVALID , VALID , REJECT , TEST , FREEZE , TEMP
// }
| import com.dao.genericdao.entity.support.UserStatus;
import lombok.Getter;
import lombok.Setter;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import java.util.Date; | package com.dao.genericdao.entity;
@Entity
@Table(name="user")
@Getter
@Setter
public class TmpUser extends JPABaseEntity {
private static final long serialVersionUID = 1L;
/**
* 用户名称
*/
@Column(name="username")
private String username ;
@DateTimeFormat(pattern="yyyy-MM-dd")
@Column(name="birthday")
private Date birthday ;
/**
* 手机号
*/
@Column(name="mobile")
private String mobile ;
@Column(name="avatarpath" , length=500)
private String photo ;
/**
* 当前用户的状态
*/
@Enumerated(EnumType.ORDINAL)
@Column(name="activestate") | // Path: src/test/java/com/dao/genericdao/entity/support/UserStatus.java
// public enum UserStatus {
// DELETED , INVALID , VALID , REJECT , TEST , FREEZE , TEMP
// }
// Path: src/test/java/com/dao/genericdao/entity/TmpUser.java
import com.dao.genericdao.entity.support.UserStatus;
import lombok.Getter;
import lombok.Setter;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import java.util.Date;
package com.dao.genericdao.entity;
@Entity
@Table(name="user")
@Getter
@Setter
public class TmpUser extends JPABaseEntity {
private static final long serialVersionUID = 1L;
/**
* 用户名称
*/
@Column(name="username")
private String username ;
@DateTimeFormat(pattern="yyyy-MM-dd")
@Column(name="birthday")
private Date birthday ;
/**
* 手机号
*/
@Column(name="mobile")
private String mobile ;
@Column(name="avatarpath" , length=500)
private String photo ;
/**
* 当前用户的状态
*/
@Enumerated(EnumType.ORDINAL)
@Column(name="activestate") | private UserStatus userStatus = UserStatus.VALID ; |
lp895876294/genericdao | src/main/java/com/dao/genericdao/jpa/lookup/GenericQueryLookupStrategy.java | // Path: src/main/java/com/dao/genericdao/jpa/repository/MybatisRepositoryQuery.java
// public class MybatisRepositoryQuery implements RepositoryQuery {
//
// private static Logger log = LoggerFactory.getLogger(MybatisRepositoryQuery.class) ;
//
// /**
// * 存储dao接口和mybatis中mapper代理的映射
// */
// private static Map<String,Object> mybatisMapperMap = Maps.newHashMap() ;
//
// private static Map<String,ResultMap> entityResultMap = Maps.newHashMap() ;
//
// private Method method ;
//
// private RepositoryMetadata repositoryMetadata ;
//
// private SqlSessionTemplate sqlSessionTemplate ;
//
// public MybatisRepositoryQuery(SqlSessionTemplate sqlSessionTemplate ,
// Method method, RepositoryMetadata repositoryMetadata){
// this.sqlSessionTemplate = sqlSessionTemplate ;
// this.method = method ;
// this.repositoryMetadata = repositoryMetadata ;
//
// log.info("{}的领域类{}",repositoryMetadata.getRepositoryInterface().getName() , repositoryMetadata.getDomainType() );
//
// if(!mybatisMapperMap.containsKey(getMapperKey())){
// Object mapper = sqlSessionTemplate.getMapper(repositoryMetadata.getRepositoryInterface()) ;
// mybatisMapperMap.put(getMapperKey() , mapper) ;
// }
//
// }
//
// @Override
// public Object execute(Object[] parameters) {
//
// log.info("执行{}.{},参数为{}" , repositoryMetadata.getRepositoryInterface().getName() ,
// method.getName() , parameters!=null?Arrays.toString(parameters):"") ;
//
// Object result = null ;
// try {
// Object mapper = mybatisMapperMap.get(getMapperKey()) ;
// Assert.isTrue(mapper!=null , repositoryMetadata.getRepositoryInterface().getName()+"对应的Mapper为null");
// if(mapper!=null){
// result = method.invoke(mapper , parameters) ;
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// return result ;
// }
//
// @Override
// public QueryMethod getQueryMethod() {
// return new QueryMethod(method , repositoryMetadata) ;
// }
//
// /**
// * 获取mybatis中mapper的key
// * @return
// */
// public String getMapperKey(){
// return repositoryMetadata.getRepositoryInterface().getName() ;
// }
//
// public Method getMethod() {
// return method;
// }
//
// public RepositoryMetadata getRepositoryMetadata() {
// return repositoryMetadata;
// }
//
// public SqlSessionTemplate getSqlSessionTemplate() {
// return sqlSessionTemplate;
// }
//
// }
| import com.dao.genericdao.annotation.MybatisQuery;
import com.dao.genericdao.jpa.repository.MybatisRepositoryQuery;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.jpa.provider.QueryExtractor;
import org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy;
import org.springframework.data.repository.core.NamedQueries;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.query.EvaluationContextProvider;
import org.springframework.data.repository.query.QueryLookupStrategy;
import org.springframework.data.repository.query.RepositoryQuery;
import javax.persistence.EntityManager;
import java.lang.reflect.Method; | package com.dao.genericdao.jpa.lookup;
/**
* 方法查询策略。主要检测mybatis查询方法
*/
public class GenericQueryLookupStrategy implements QueryLookupStrategy {
private static Logger log = LoggerFactory.getLogger(GenericQueryLookupStrategy.class) ;
private final EntityManager entityManager;
private final SqlSessionTemplate sqlSessionTemplate ;
private QueryLookupStrategy jpaQueryLookupStrategy;
private QueryExtractor extractor;
public GenericQueryLookupStrategy(EntityManager entityManager, SqlSessionTemplate sqlSessionTemplate ,
Key key, QueryExtractor extractor, EvaluationContextProvider evaluationContextProvider) {
this.jpaQueryLookupStrategy = JpaQueryLookupStrategy.create(entityManager, key, extractor, evaluationContextProvider);
this.extractor = extractor;
this.entityManager = entityManager;
this.sqlSessionTemplate = sqlSessionTemplate ;
}
public static QueryLookupStrategy create(EntityManager entityManager, SqlSessionTemplate sqlSessionTemplate ,
Key key, QueryExtractor extractor, EvaluationContextProvider evaluationContextProvider) {
return new GenericQueryLookupStrategy(entityManager , sqlSessionTemplate ,
key , extractor , evaluationContextProvider);
}
@Override
public RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, NamedQueries namedQueries) {
if (method.getAnnotation(MybatisQuery.class) != null) {
log.info(metadata.getRepositoryInterface().getName()+"."+method.getName()+" 为mybatis方法。 "); | // Path: src/main/java/com/dao/genericdao/jpa/repository/MybatisRepositoryQuery.java
// public class MybatisRepositoryQuery implements RepositoryQuery {
//
// private static Logger log = LoggerFactory.getLogger(MybatisRepositoryQuery.class) ;
//
// /**
// * 存储dao接口和mybatis中mapper代理的映射
// */
// private static Map<String,Object> mybatisMapperMap = Maps.newHashMap() ;
//
// private static Map<String,ResultMap> entityResultMap = Maps.newHashMap() ;
//
// private Method method ;
//
// private RepositoryMetadata repositoryMetadata ;
//
// private SqlSessionTemplate sqlSessionTemplate ;
//
// public MybatisRepositoryQuery(SqlSessionTemplate sqlSessionTemplate ,
// Method method, RepositoryMetadata repositoryMetadata){
// this.sqlSessionTemplate = sqlSessionTemplate ;
// this.method = method ;
// this.repositoryMetadata = repositoryMetadata ;
//
// log.info("{}的领域类{}",repositoryMetadata.getRepositoryInterface().getName() , repositoryMetadata.getDomainType() );
//
// if(!mybatisMapperMap.containsKey(getMapperKey())){
// Object mapper = sqlSessionTemplate.getMapper(repositoryMetadata.getRepositoryInterface()) ;
// mybatisMapperMap.put(getMapperKey() , mapper) ;
// }
//
// }
//
// @Override
// public Object execute(Object[] parameters) {
//
// log.info("执行{}.{},参数为{}" , repositoryMetadata.getRepositoryInterface().getName() ,
// method.getName() , parameters!=null?Arrays.toString(parameters):"") ;
//
// Object result = null ;
// try {
// Object mapper = mybatisMapperMap.get(getMapperKey()) ;
// Assert.isTrue(mapper!=null , repositoryMetadata.getRepositoryInterface().getName()+"对应的Mapper为null");
// if(mapper!=null){
// result = method.invoke(mapper , parameters) ;
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// return result ;
// }
//
// @Override
// public QueryMethod getQueryMethod() {
// return new QueryMethod(method , repositoryMetadata) ;
// }
//
// /**
// * 获取mybatis中mapper的key
// * @return
// */
// public String getMapperKey(){
// return repositoryMetadata.getRepositoryInterface().getName() ;
// }
//
// public Method getMethod() {
// return method;
// }
//
// public RepositoryMetadata getRepositoryMetadata() {
// return repositoryMetadata;
// }
//
// public SqlSessionTemplate getSqlSessionTemplate() {
// return sqlSessionTemplate;
// }
//
// }
// Path: src/main/java/com/dao/genericdao/jpa/lookup/GenericQueryLookupStrategy.java
import com.dao.genericdao.annotation.MybatisQuery;
import com.dao.genericdao.jpa.repository.MybatisRepositoryQuery;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.jpa.provider.QueryExtractor;
import org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy;
import org.springframework.data.repository.core.NamedQueries;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.query.EvaluationContextProvider;
import org.springframework.data.repository.query.QueryLookupStrategy;
import org.springframework.data.repository.query.RepositoryQuery;
import javax.persistence.EntityManager;
import java.lang.reflect.Method;
package com.dao.genericdao.jpa.lookup;
/**
* 方法查询策略。主要检测mybatis查询方法
*/
public class GenericQueryLookupStrategy implements QueryLookupStrategy {
private static Logger log = LoggerFactory.getLogger(GenericQueryLookupStrategy.class) ;
private final EntityManager entityManager;
private final SqlSessionTemplate sqlSessionTemplate ;
private QueryLookupStrategy jpaQueryLookupStrategy;
private QueryExtractor extractor;
public GenericQueryLookupStrategy(EntityManager entityManager, SqlSessionTemplate sqlSessionTemplate ,
Key key, QueryExtractor extractor, EvaluationContextProvider evaluationContextProvider) {
this.jpaQueryLookupStrategy = JpaQueryLookupStrategy.create(entityManager, key, extractor, evaluationContextProvider);
this.extractor = extractor;
this.entityManager = entityManager;
this.sqlSessionTemplate = sqlSessionTemplate ;
}
public static QueryLookupStrategy create(EntityManager entityManager, SqlSessionTemplate sqlSessionTemplate ,
Key key, QueryExtractor extractor, EvaluationContextProvider evaluationContextProvider) {
return new GenericQueryLookupStrategy(entityManager , sqlSessionTemplate ,
key , extractor , evaluationContextProvider);
}
@Override
public RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, NamedQueries namedQueries) {
if (method.getAnnotation(MybatisQuery.class) != null) {
log.info(metadata.getRepositoryInterface().getName()+"."+method.getName()+" 为mybatis方法。 "); | return new MybatisRepositoryQuery(sqlSessionTemplate , method , metadata) ; |
lp895876294/genericdao | src/main/java/com/dao/genericdao/jpa/GenericJpaRepository.java | // Path: src/main/java/com/dao/genericdao/dao/BaseDataRepository.java
// @NoRepositoryBean
// public interface BaseDataRepository<T, ID extends Serializable> extends PagingAndSortingRepository<T,ID> {
// /**
// * 更新实体对象
// * @param entity 实体
// * @param updateFieldsName 更新字段名称
// */
// public T update(T entity , Collection<String> updateFieldsName) ;
//
// /**
// * 更新实体对象,更新所有的属性
// * @param entity 实体
// */
// public T update(T entity) ;
//
// /**
// * 批量更新实体对象
// * @param entityList 实体集合
// * @param updateFieldsName 更新字段名称
// */
// public List<T> update(List<T> entityList , Collection<String> updateFieldsName) ;
//
// /**
// * 批量更新实体对象
// * @param entityList 实体
// */
// public List<T> update(List<T> entityList) ;
//
// /**
// * 获取进行操作的领域类
// */
// public Class<T> getDomainClass() ;
//
// }
| import com.dao.genericdao.dao.BaseDataRepository;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.NoRepositoryBean;
import javax.persistence.EntityManager;
import java.io.Serializable;
import java.util.List;
import java.util.Map; | package com.dao.genericdao.jpa;
/**
* 扩展JpaRepository,添加对update的支持
*/
@NoRepositoryBean
public interface GenericJpaRepository<T, ID extends Serializable> extends JpaRepository<T, ID>, | // Path: src/main/java/com/dao/genericdao/dao/BaseDataRepository.java
// @NoRepositoryBean
// public interface BaseDataRepository<T, ID extends Serializable> extends PagingAndSortingRepository<T,ID> {
// /**
// * 更新实体对象
// * @param entity 实体
// * @param updateFieldsName 更新字段名称
// */
// public T update(T entity , Collection<String> updateFieldsName) ;
//
// /**
// * 更新实体对象,更新所有的属性
// * @param entity 实体
// */
// public T update(T entity) ;
//
// /**
// * 批量更新实体对象
// * @param entityList 实体集合
// * @param updateFieldsName 更新字段名称
// */
// public List<T> update(List<T> entityList , Collection<String> updateFieldsName) ;
//
// /**
// * 批量更新实体对象
// * @param entityList 实体
// */
// public List<T> update(List<T> entityList) ;
//
// /**
// * 获取进行操作的领域类
// */
// public Class<T> getDomainClass() ;
//
// }
// Path: src/main/java/com/dao/genericdao/jpa/GenericJpaRepository.java
import com.dao.genericdao.dao.BaseDataRepository;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.NoRepositoryBean;
import javax.persistence.EntityManager;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
package com.dao.genericdao.jpa;
/**
* 扩展JpaRepository,添加对update的支持
*/
@NoRepositoryBean
public interface GenericJpaRepository<T, ID extends Serializable> extends JpaRepository<T, ID>, | JpaSpecificationExecutor<T> , BaseDataRepository<T,ID> { |
lp895876294/genericdao | src/main/java/com/dao/genericdao/util/JPAUtil.java | // Path: src/main/java/com/dao/genericdao/dialect/MySQLDialectWithoutFK.java
// public class MySQLDialectWithoutFK extends MySQL5InnoDBDialect{
// @Override
// public String getAddForeignKeyConstraintString(
// String constraintName,
// String[] foreignKey,
// String referencedTable,
// String[] primaryKey,
// boolean referencesPrimaryKey) {
// final String cols = StringHelper.join( ", ", foreignKey );
// // 设置foreignkey对应的列值可以为空
// return " ALTER "+ cols +" SET DEFAULT NULL " ;
// }
// }
//
// Path: src/main/java/com/dao/genericdao/dialect/Oracle10gDialectWithoutFK.java
// public class Oracle10gDialectWithoutFK extends Oracle10gDialect {
// @Override
// public String getAddForeignKeyConstraintString(
// String constraintName,
// String[] foreignKey,
// String referencedTable,
// String[] primaryKey,
// boolean referencesPrimaryKey) {
// // 通过修改外键列的默认值,而不是添加外键,避免生成外键
// return " modify "+ foreignKey[0] +" default null " ;
// }
// }
//
// Path: src/main/java/com/dao/genericdao/dialect/PostgreSQL9DialectWithoutFK.java
// public class PostgreSQL9DialectWithoutFK extends PostgreSQL9Dialect {
// @Override
// public String getAddForeignKeyConstraintString(
// String constraintName,
// String[] foreignKey,
// String referencedTable,
// String[] primaryKey,
// boolean referencesPrimaryKey) {
// // 设置foreignkey对应的列值可以为空
// return " alter "+ foreignKey[0] +" set default null " ;
// }
// }
| import com.dao.genericdao.dialect.MySQLDialectWithoutFK;
import com.dao.genericdao.dialect.Oracle10gDialectWithoutFK;
import com.dao.genericdao.dialect.PostgreSQL9DialectWithoutFK;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.dialect.SQLServer2008Dialect;
import org.reflections.ReflectionUtils;
import org.springframework.orm.jpa.vendor.Database;
import javax.sql.DataSource;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*; | return flag ;
}
/**
* 获取数据库类型
*/
public static Database getDBType(DataSource dataSource){
String jdbcUrl = getJdbcUrlFromDataSource(dataSource);
if (StringUtils.contains(jdbcUrl, ":h2:")) {
return Database.H2 ;
} else if (StringUtils.contains(jdbcUrl, ":mysql:")) {
return Database.MYSQL ;
} else if (StringUtils.contains(jdbcUrl, ":oracle:")) {
return Database.ORACLE ;
} else if (StringUtils.contains(jdbcUrl, ":postgresql:")) {
return Database.POSTGRESQL ;
} else if (StringUtils.contains(jdbcUrl, ":sqlserver:")) {
return Database.SQL_SERVER ;
}
throw new IllegalArgumentException("Unknown Database of " + jdbcUrl);
}
/**
* 从DataSoure中取出connection, 根据connection的metadata中的jdbcUrl判断Dialect类型.
* 仅支持Oracle 10, H2, MySql, PostgreSql, SQLServer,如需更多数据库类型,请仿照此类自行编写。
*/
public static String getDialect(DataSource dataSource) {
switch (getDBType(dataSource)) {
case H2:
return H2Dialect.class.getName();
case MYSQL: | // Path: src/main/java/com/dao/genericdao/dialect/MySQLDialectWithoutFK.java
// public class MySQLDialectWithoutFK extends MySQL5InnoDBDialect{
// @Override
// public String getAddForeignKeyConstraintString(
// String constraintName,
// String[] foreignKey,
// String referencedTable,
// String[] primaryKey,
// boolean referencesPrimaryKey) {
// final String cols = StringHelper.join( ", ", foreignKey );
// // 设置foreignkey对应的列值可以为空
// return " ALTER "+ cols +" SET DEFAULT NULL " ;
// }
// }
//
// Path: src/main/java/com/dao/genericdao/dialect/Oracle10gDialectWithoutFK.java
// public class Oracle10gDialectWithoutFK extends Oracle10gDialect {
// @Override
// public String getAddForeignKeyConstraintString(
// String constraintName,
// String[] foreignKey,
// String referencedTable,
// String[] primaryKey,
// boolean referencesPrimaryKey) {
// // 通过修改外键列的默认值,而不是添加外键,避免生成外键
// return " modify "+ foreignKey[0] +" default null " ;
// }
// }
//
// Path: src/main/java/com/dao/genericdao/dialect/PostgreSQL9DialectWithoutFK.java
// public class PostgreSQL9DialectWithoutFK extends PostgreSQL9Dialect {
// @Override
// public String getAddForeignKeyConstraintString(
// String constraintName,
// String[] foreignKey,
// String referencedTable,
// String[] primaryKey,
// boolean referencesPrimaryKey) {
// // 设置foreignkey对应的列值可以为空
// return " alter "+ foreignKey[0] +" set default null " ;
// }
// }
// Path: src/main/java/com/dao/genericdao/util/JPAUtil.java
import com.dao.genericdao.dialect.MySQLDialectWithoutFK;
import com.dao.genericdao.dialect.Oracle10gDialectWithoutFK;
import com.dao.genericdao.dialect.PostgreSQL9DialectWithoutFK;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.dialect.SQLServer2008Dialect;
import org.reflections.ReflectionUtils;
import org.springframework.orm.jpa.vendor.Database;
import javax.sql.DataSource;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
return flag ;
}
/**
* 获取数据库类型
*/
public static Database getDBType(DataSource dataSource){
String jdbcUrl = getJdbcUrlFromDataSource(dataSource);
if (StringUtils.contains(jdbcUrl, ":h2:")) {
return Database.H2 ;
} else if (StringUtils.contains(jdbcUrl, ":mysql:")) {
return Database.MYSQL ;
} else if (StringUtils.contains(jdbcUrl, ":oracle:")) {
return Database.ORACLE ;
} else if (StringUtils.contains(jdbcUrl, ":postgresql:")) {
return Database.POSTGRESQL ;
} else if (StringUtils.contains(jdbcUrl, ":sqlserver:")) {
return Database.SQL_SERVER ;
}
throw new IllegalArgumentException("Unknown Database of " + jdbcUrl);
}
/**
* 从DataSoure中取出connection, 根据connection的metadata中的jdbcUrl判断Dialect类型.
* 仅支持Oracle 10, H2, MySql, PostgreSql, SQLServer,如需更多数据库类型,请仿照此类自行编写。
*/
public static String getDialect(DataSource dataSource) {
switch (getDBType(dataSource)) {
case H2:
return H2Dialect.class.getName();
case MYSQL: | return MySQLDialectWithoutFK.class.getName(); |
lp895876294/genericdao | src/main/java/com/dao/genericdao/util/JPAUtil.java | // Path: src/main/java/com/dao/genericdao/dialect/MySQLDialectWithoutFK.java
// public class MySQLDialectWithoutFK extends MySQL5InnoDBDialect{
// @Override
// public String getAddForeignKeyConstraintString(
// String constraintName,
// String[] foreignKey,
// String referencedTable,
// String[] primaryKey,
// boolean referencesPrimaryKey) {
// final String cols = StringHelper.join( ", ", foreignKey );
// // 设置foreignkey对应的列值可以为空
// return " ALTER "+ cols +" SET DEFAULT NULL " ;
// }
// }
//
// Path: src/main/java/com/dao/genericdao/dialect/Oracle10gDialectWithoutFK.java
// public class Oracle10gDialectWithoutFK extends Oracle10gDialect {
// @Override
// public String getAddForeignKeyConstraintString(
// String constraintName,
// String[] foreignKey,
// String referencedTable,
// String[] primaryKey,
// boolean referencesPrimaryKey) {
// // 通过修改外键列的默认值,而不是添加外键,避免生成外键
// return " modify "+ foreignKey[0] +" default null " ;
// }
// }
//
// Path: src/main/java/com/dao/genericdao/dialect/PostgreSQL9DialectWithoutFK.java
// public class PostgreSQL9DialectWithoutFK extends PostgreSQL9Dialect {
// @Override
// public String getAddForeignKeyConstraintString(
// String constraintName,
// String[] foreignKey,
// String referencedTable,
// String[] primaryKey,
// boolean referencesPrimaryKey) {
// // 设置foreignkey对应的列值可以为空
// return " alter "+ foreignKey[0] +" set default null " ;
// }
// }
| import com.dao.genericdao.dialect.MySQLDialectWithoutFK;
import com.dao.genericdao.dialect.Oracle10gDialectWithoutFK;
import com.dao.genericdao.dialect.PostgreSQL9DialectWithoutFK;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.dialect.SQLServer2008Dialect;
import org.reflections.ReflectionUtils;
import org.springframework.orm.jpa.vendor.Database;
import javax.sql.DataSource;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*; | /**
* 获取数据库类型
*/
public static Database getDBType(DataSource dataSource){
String jdbcUrl = getJdbcUrlFromDataSource(dataSource);
if (StringUtils.contains(jdbcUrl, ":h2:")) {
return Database.H2 ;
} else if (StringUtils.contains(jdbcUrl, ":mysql:")) {
return Database.MYSQL ;
} else if (StringUtils.contains(jdbcUrl, ":oracle:")) {
return Database.ORACLE ;
} else if (StringUtils.contains(jdbcUrl, ":postgresql:")) {
return Database.POSTGRESQL ;
} else if (StringUtils.contains(jdbcUrl, ":sqlserver:")) {
return Database.SQL_SERVER ;
}
throw new IllegalArgumentException("Unknown Database of " + jdbcUrl);
}
/**
* 从DataSoure中取出connection, 根据connection的metadata中的jdbcUrl判断Dialect类型.
* 仅支持Oracle 10, H2, MySql, PostgreSql, SQLServer,如需更多数据库类型,请仿照此类自行编写。
*/
public static String getDialect(DataSource dataSource) {
switch (getDBType(dataSource)) {
case H2:
return H2Dialect.class.getName();
case MYSQL:
return MySQLDialectWithoutFK.class.getName();
case ORACLE: | // Path: src/main/java/com/dao/genericdao/dialect/MySQLDialectWithoutFK.java
// public class MySQLDialectWithoutFK extends MySQL5InnoDBDialect{
// @Override
// public String getAddForeignKeyConstraintString(
// String constraintName,
// String[] foreignKey,
// String referencedTable,
// String[] primaryKey,
// boolean referencesPrimaryKey) {
// final String cols = StringHelper.join( ", ", foreignKey );
// // 设置foreignkey对应的列值可以为空
// return " ALTER "+ cols +" SET DEFAULT NULL " ;
// }
// }
//
// Path: src/main/java/com/dao/genericdao/dialect/Oracle10gDialectWithoutFK.java
// public class Oracle10gDialectWithoutFK extends Oracle10gDialect {
// @Override
// public String getAddForeignKeyConstraintString(
// String constraintName,
// String[] foreignKey,
// String referencedTable,
// String[] primaryKey,
// boolean referencesPrimaryKey) {
// // 通过修改外键列的默认值,而不是添加外键,避免生成外键
// return " modify "+ foreignKey[0] +" default null " ;
// }
// }
//
// Path: src/main/java/com/dao/genericdao/dialect/PostgreSQL9DialectWithoutFK.java
// public class PostgreSQL9DialectWithoutFK extends PostgreSQL9Dialect {
// @Override
// public String getAddForeignKeyConstraintString(
// String constraintName,
// String[] foreignKey,
// String referencedTable,
// String[] primaryKey,
// boolean referencesPrimaryKey) {
// // 设置foreignkey对应的列值可以为空
// return " alter "+ foreignKey[0] +" set default null " ;
// }
// }
// Path: src/main/java/com/dao/genericdao/util/JPAUtil.java
import com.dao.genericdao.dialect.MySQLDialectWithoutFK;
import com.dao.genericdao.dialect.Oracle10gDialectWithoutFK;
import com.dao.genericdao.dialect.PostgreSQL9DialectWithoutFK;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.dialect.SQLServer2008Dialect;
import org.reflections.ReflectionUtils;
import org.springframework.orm.jpa.vendor.Database;
import javax.sql.DataSource;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
/**
* 获取数据库类型
*/
public static Database getDBType(DataSource dataSource){
String jdbcUrl = getJdbcUrlFromDataSource(dataSource);
if (StringUtils.contains(jdbcUrl, ":h2:")) {
return Database.H2 ;
} else if (StringUtils.contains(jdbcUrl, ":mysql:")) {
return Database.MYSQL ;
} else if (StringUtils.contains(jdbcUrl, ":oracle:")) {
return Database.ORACLE ;
} else if (StringUtils.contains(jdbcUrl, ":postgresql:")) {
return Database.POSTGRESQL ;
} else if (StringUtils.contains(jdbcUrl, ":sqlserver:")) {
return Database.SQL_SERVER ;
}
throw new IllegalArgumentException("Unknown Database of " + jdbcUrl);
}
/**
* 从DataSoure中取出connection, 根据connection的metadata中的jdbcUrl判断Dialect类型.
* 仅支持Oracle 10, H2, MySql, PostgreSql, SQLServer,如需更多数据库类型,请仿照此类自行编写。
*/
public static String getDialect(DataSource dataSource) {
switch (getDBType(dataSource)) {
case H2:
return H2Dialect.class.getName();
case MYSQL:
return MySQLDialectWithoutFK.class.getName();
case ORACLE: | return Oracle10gDialectWithoutFK.class.getName() ; |
lp895876294/genericdao | src/main/java/com/dao/genericdao/util/JPAUtil.java | // Path: src/main/java/com/dao/genericdao/dialect/MySQLDialectWithoutFK.java
// public class MySQLDialectWithoutFK extends MySQL5InnoDBDialect{
// @Override
// public String getAddForeignKeyConstraintString(
// String constraintName,
// String[] foreignKey,
// String referencedTable,
// String[] primaryKey,
// boolean referencesPrimaryKey) {
// final String cols = StringHelper.join( ", ", foreignKey );
// // 设置foreignkey对应的列值可以为空
// return " ALTER "+ cols +" SET DEFAULT NULL " ;
// }
// }
//
// Path: src/main/java/com/dao/genericdao/dialect/Oracle10gDialectWithoutFK.java
// public class Oracle10gDialectWithoutFK extends Oracle10gDialect {
// @Override
// public String getAddForeignKeyConstraintString(
// String constraintName,
// String[] foreignKey,
// String referencedTable,
// String[] primaryKey,
// boolean referencesPrimaryKey) {
// // 通过修改外键列的默认值,而不是添加外键,避免生成外键
// return " modify "+ foreignKey[0] +" default null " ;
// }
// }
//
// Path: src/main/java/com/dao/genericdao/dialect/PostgreSQL9DialectWithoutFK.java
// public class PostgreSQL9DialectWithoutFK extends PostgreSQL9Dialect {
// @Override
// public String getAddForeignKeyConstraintString(
// String constraintName,
// String[] foreignKey,
// String referencedTable,
// String[] primaryKey,
// boolean referencesPrimaryKey) {
// // 设置foreignkey对应的列值可以为空
// return " alter "+ foreignKey[0] +" set default null " ;
// }
// }
| import com.dao.genericdao.dialect.MySQLDialectWithoutFK;
import com.dao.genericdao.dialect.Oracle10gDialectWithoutFK;
import com.dao.genericdao.dialect.PostgreSQL9DialectWithoutFK;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.dialect.SQLServer2008Dialect;
import org.reflections.ReflectionUtils;
import org.springframework.orm.jpa.vendor.Database;
import javax.sql.DataSource;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*; | */
public static Database getDBType(DataSource dataSource){
String jdbcUrl = getJdbcUrlFromDataSource(dataSource);
if (StringUtils.contains(jdbcUrl, ":h2:")) {
return Database.H2 ;
} else if (StringUtils.contains(jdbcUrl, ":mysql:")) {
return Database.MYSQL ;
} else if (StringUtils.contains(jdbcUrl, ":oracle:")) {
return Database.ORACLE ;
} else if (StringUtils.contains(jdbcUrl, ":postgresql:")) {
return Database.POSTGRESQL ;
} else if (StringUtils.contains(jdbcUrl, ":sqlserver:")) {
return Database.SQL_SERVER ;
}
throw new IllegalArgumentException("Unknown Database of " + jdbcUrl);
}
/**
* 从DataSoure中取出connection, 根据connection的metadata中的jdbcUrl判断Dialect类型.
* 仅支持Oracle 10, H2, MySql, PostgreSql, SQLServer,如需更多数据库类型,请仿照此类自行编写。
*/
public static String getDialect(DataSource dataSource) {
switch (getDBType(dataSource)) {
case H2:
return H2Dialect.class.getName();
case MYSQL:
return MySQLDialectWithoutFK.class.getName();
case ORACLE:
return Oracle10gDialectWithoutFK.class.getName() ;
case POSTGRESQL: | // Path: src/main/java/com/dao/genericdao/dialect/MySQLDialectWithoutFK.java
// public class MySQLDialectWithoutFK extends MySQL5InnoDBDialect{
// @Override
// public String getAddForeignKeyConstraintString(
// String constraintName,
// String[] foreignKey,
// String referencedTable,
// String[] primaryKey,
// boolean referencesPrimaryKey) {
// final String cols = StringHelper.join( ", ", foreignKey );
// // 设置foreignkey对应的列值可以为空
// return " ALTER "+ cols +" SET DEFAULT NULL " ;
// }
// }
//
// Path: src/main/java/com/dao/genericdao/dialect/Oracle10gDialectWithoutFK.java
// public class Oracle10gDialectWithoutFK extends Oracle10gDialect {
// @Override
// public String getAddForeignKeyConstraintString(
// String constraintName,
// String[] foreignKey,
// String referencedTable,
// String[] primaryKey,
// boolean referencesPrimaryKey) {
// // 通过修改外键列的默认值,而不是添加外键,避免生成外键
// return " modify "+ foreignKey[0] +" default null " ;
// }
// }
//
// Path: src/main/java/com/dao/genericdao/dialect/PostgreSQL9DialectWithoutFK.java
// public class PostgreSQL9DialectWithoutFK extends PostgreSQL9Dialect {
// @Override
// public String getAddForeignKeyConstraintString(
// String constraintName,
// String[] foreignKey,
// String referencedTable,
// String[] primaryKey,
// boolean referencesPrimaryKey) {
// // 设置foreignkey对应的列值可以为空
// return " alter "+ foreignKey[0] +" set default null " ;
// }
// }
// Path: src/main/java/com/dao/genericdao/util/JPAUtil.java
import com.dao.genericdao.dialect.MySQLDialectWithoutFK;
import com.dao.genericdao.dialect.Oracle10gDialectWithoutFK;
import com.dao.genericdao.dialect.PostgreSQL9DialectWithoutFK;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.dialect.SQLServer2008Dialect;
import org.reflections.ReflectionUtils;
import org.springframework.orm.jpa.vendor.Database;
import javax.sql.DataSource;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;
*/
public static Database getDBType(DataSource dataSource){
String jdbcUrl = getJdbcUrlFromDataSource(dataSource);
if (StringUtils.contains(jdbcUrl, ":h2:")) {
return Database.H2 ;
} else if (StringUtils.contains(jdbcUrl, ":mysql:")) {
return Database.MYSQL ;
} else if (StringUtils.contains(jdbcUrl, ":oracle:")) {
return Database.ORACLE ;
} else if (StringUtils.contains(jdbcUrl, ":postgresql:")) {
return Database.POSTGRESQL ;
} else if (StringUtils.contains(jdbcUrl, ":sqlserver:")) {
return Database.SQL_SERVER ;
}
throw new IllegalArgumentException("Unknown Database of " + jdbcUrl);
}
/**
* 从DataSoure中取出connection, 根据connection的metadata中的jdbcUrl判断Dialect类型.
* 仅支持Oracle 10, H2, MySql, PostgreSql, SQLServer,如需更多数据库类型,请仿照此类自行编写。
*/
public static String getDialect(DataSource dataSource) {
switch (getDBType(dataSource)) {
case H2:
return H2Dialect.class.getName();
case MYSQL:
return MySQLDialectWithoutFK.class.getName();
case ORACLE:
return Oracle10gDialectWithoutFK.class.getName() ;
case POSTGRESQL: | return PostgreSQL9DialectWithoutFK.class.getName() ; |
pevdh/telegram-bots-java-api | api/src/main/java/co/vandenham/telegram/botapi/ChatContext.java | // Path: api/src/main/java/co/vandenham/telegram/botapi/requests/OptionalArgs.java
// public class OptionalArgs {
//
// private boolean disableWebPagePreview = false;
// private int replyToMessageId = -1;
// private ReplyMarkup replyMarkup = null;
// private int offset = -1;
// private int limit = -1;
// private int timeout = -1;
// private int duration = -1;
// private String caption = null;
// private String performer = null;
// private String title = null;
//
// private Map<String, String> options;
//
// public Map<String, String> options() {
// options = new HashMap<>();
//
// if (disableWebPagePreview)
// putBoolean("disable_web_page_preview", true);
//
// if (replyToMessageId != -1)
// putInt("reply_to_message_id", replyToMessageId);
//
// if (offset != -1)
// putInt("offset", offset);
//
// if (limit != -1)
// putInt("limit", limit);
//
// if (timeout != -1)
// putInt("timeout", timeout);
//
// if (duration != -1)
// putInt("duration", duration);
//
// if (replyMarkup != null)
// options.put("reply_markup", replyMarkup.serialize());
//
// if (caption != null)
// options.put("caption", caption);
//
// if (performer != null)
// options.put("performer", performer);
//
// if (title != null)
// options.put("title", title);
//
// return options;
// }
//
// private void putBoolean(String key, boolean b) {
// options.put(key, String.valueOf(b));
// }
//
// private void putInt(String key, int i) {
// options.put(key, String.valueOf(i));
// }
//
// public OptionalArgs disableWebPagePreview() {
// this.disableWebPagePreview = true;
// return this;
// }
//
// public OptionalArgs replyToMessageId(int replyToMessageId) {
// this.replyToMessageId = replyToMessageId;
// return this;
// }
//
// public OptionalArgs replyMarkup(ReplyMarkup replyMarkup) {
// this.replyMarkup = replyMarkup;
// return this;
// }
//
// public OptionalArgs offset(int offset) {
// this.offset = offset;
// return this;
// }
//
// public OptionalArgs limit(int limit) {
// this.limit = limit;
// return this;
// }
//
// public OptionalArgs timeout(int timeout) {
// this.timeout = timeout;
// return this;
// }
//
// public OptionalArgs duration(int duration) {
// this.duration = duration;
// return this;
// }
//
// public OptionalArgs caption(String caption) {
// this.caption = caption;
// return this;
// }
//
// public OptionalArgs performer(String performer) {
// this.performer = performer;
// return this;
// }
//
// public OptionalArgs title(String title) {
// this.title = title;
// return this;
// }
// }
| import co.vandenham.telegram.botapi.requests.ApiResponse;
import co.vandenham.telegram.botapi.requests.ChatAction;
import co.vandenham.telegram.botapi.requests.OptionalArgs;
import co.vandenham.telegram.botapi.types.Message;
import co.vandenham.telegram.botapi.types.User;
import co.vandenham.telegram.botapi.types.UserProfilePhotos;
import java.io.File; | throw new IllegalArgumentException("A Message was passed to the wrong ChatContext.");
onMessage(message);
handlerNotifier.notifyHandlers(message);
}
public void onStart() {
}
public void onStop() {
}
protected void onMessage(Message message) {
}
public ApiResponse<Message> forwardMessage(int fromChatId, int toChatId, int messageId) {
return bot.forwardMessage(toChatId, fromChatId, messageId);
}
public ApiResponse<User> getMe() {
return bot.getMe();
}
public ApiResponse<UserProfilePhotos> getUserProfilePhotos(int userId) {
return bot.getUserProfilePhotos(userId);
}
| // Path: api/src/main/java/co/vandenham/telegram/botapi/requests/OptionalArgs.java
// public class OptionalArgs {
//
// private boolean disableWebPagePreview = false;
// private int replyToMessageId = -1;
// private ReplyMarkup replyMarkup = null;
// private int offset = -1;
// private int limit = -1;
// private int timeout = -1;
// private int duration = -1;
// private String caption = null;
// private String performer = null;
// private String title = null;
//
// private Map<String, String> options;
//
// public Map<String, String> options() {
// options = new HashMap<>();
//
// if (disableWebPagePreview)
// putBoolean("disable_web_page_preview", true);
//
// if (replyToMessageId != -1)
// putInt("reply_to_message_id", replyToMessageId);
//
// if (offset != -1)
// putInt("offset", offset);
//
// if (limit != -1)
// putInt("limit", limit);
//
// if (timeout != -1)
// putInt("timeout", timeout);
//
// if (duration != -1)
// putInt("duration", duration);
//
// if (replyMarkup != null)
// options.put("reply_markup", replyMarkup.serialize());
//
// if (caption != null)
// options.put("caption", caption);
//
// if (performer != null)
// options.put("performer", performer);
//
// if (title != null)
// options.put("title", title);
//
// return options;
// }
//
// private void putBoolean(String key, boolean b) {
// options.put(key, String.valueOf(b));
// }
//
// private void putInt(String key, int i) {
// options.put(key, String.valueOf(i));
// }
//
// public OptionalArgs disableWebPagePreview() {
// this.disableWebPagePreview = true;
// return this;
// }
//
// public OptionalArgs replyToMessageId(int replyToMessageId) {
// this.replyToMessageId = replyToMessageId;
// return this;
// }
//
// public OptionalArgs replyMarkup(ReplyMarkup replyMarkup) {
// this.replyMarkup = replyMarkup;
// return this;
// }
//
// public OptionalArgs offset(int offset) {
// this.offset = offset;
// return this;
// }
//
// public OptionalArgs limit(int limit) {
// this.limit = limit;
// return this;
// }
//
// public OptionalArgs timeout(int timeout) {
// this.timeout = timeout;
// return this;
// }
//
// public OptionalArgs duration(int duration) {
// this.duration = duration;
// return this;
// }
//
// public OptionalArgs caption(String caption) {
// this.caption = caption;
// return this;
// }
//
// public OptionalArgs performer(String performer) {
// this.performer = performer;
// return this;
// }
//
// public OptionalArgs title(String title) {
// this.title = title;
// return this;
// }
// }
// Path: api/src/main/java/co/vandenham/telegram/botapi/ChatContext.java
import co.vandenham.telegram.botapi.requests.ApiResponse;
import co.vandenham.telegram.botapi.requests.ChatAction;
import co.vandenham.telegram.botapi.requests.OptionalArgs;
import co.vandenham.telegram.botapi.types.Message;
import co.vandenham.telegram.botapi.types.User;
import co.vandenham.telegram.botapi.types.UserProfilePhotos;
import java.io.File;
throw new IllegalArgumentException("A Message was passed to the wrong ChatContext.");
onMessage(message);
handlerNotifier.notifyHandlers(message);
}
public void onStart() {
}
public void onStop() {
}
protected void onMessage(Message message) {
}
public ApiResponse<Message> forwardMessage(int fromChatId, int toChatId, int messageId) {
return bot.forwardMessage(toChatId, fromChatId, messageId);
}
public ApiResponse<User> getMe() {
return bot.getMe();
}
public ApiResponse<UserProfilePhotos> getUserProfilePhotos(int userId) {
return bot.getUserProfilePhotos(userId);
}
| public ApiResponse<UserProfilePhotos> getUserProfilePhotos(int userId, OptionalArgs optionalArgs) { |
alkacon/alkacon-oamp | com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/CmsForm.java | // Path: com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/CmsFormContentUtil.java
// public static String getContentStringValue(CmsXmlContent content, CmsObject cms, String path, Locale locale) {
//
// return content.getStringValue(cms, getNestedPathPrefix(content, NODE_NESTED_FORM, locale) + path, locale);
// }
//
// Path: com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/CmsFormContentUtil.java
// public static I_CmsXmlContentValue getContentValue(CmsXmlContent content, String path, Locale locale) {
//
// return content.getValue(getNestedPathPrefix(content, NODE_NESTED_FORM, locale) + path, locale);
// }
//
// Path: com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/CmsFormContentUtil.java
// public static List<I_CmsXmlContentValue> getContentValues(CmsXmlContent content, String path, Locale locale) {
//
// return content.getValues(getNestedPathPrefix(content, NODE_NESTED_FORM, locale) + path, locale);
// }
| import static com.alkacon.opencms.v8.formgenerator.CmsFormContentUtil.getContentStringValue;
import static com.alkacon.opencms.v8.formgenerator.CmsFormContentUtil.getContentValue;
import static com.alkacon.opencms.v8.formgenerator.CmsFormContentUtil.getContentValues;
import org.opencms.configuration.CmsConfigurationException;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.i18n.CmsMessages;
import org.opencms.jsp.CmsJspActionElement;
import org.opencms.main.OpenCms;
import org.opencms.util.CmsMacroResolver;
import org.opencms.util.CmsStringUtil;
import org.opencms.workplace.CmsWorkplace;
import org.opencms.xml.content.CmsXmlContent;
import org.opencms.xml.content.CmsXmlContentFactory;
import org.opencms.xml.types.CmsXmlHtmlValue;
import org.opencms.xml.types.I_CmsXmlContentValue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import org.apache.commons.fileupload.FileItem;
| * @return the parameter value
*/
protected String getParameter(String parameter) {
try {
return (m_parameterMap.get(parameter))[0];
} catch (NullPointerException e) {
return "";
}
}
/**
* Initializes the optional captcha field.<p>
*
* @param jsp the initialized CmsJspActionElement to access the OpenCms API
* @param content the XML configuration content
* @param locale the currently active Locale
* @param initial if true, field values are filled with values specified in the XML configuration, otherwise values are read from the request
*/
protected void initCaptchaField(CmsJspActionElement jsp, CmsXmlContent content, Locale locale, boolean initial) {
boolean captchaFieldIsOnInputPage = captchaFieldIsOnInputPage();
boolean displayCheckPage = captchaFieldIsOnCheckPage() && isInputFormSubmitted();
boolean submittedCheckPage = captchaFieldIsOnCheckPage() && isCheckPageSubmitted();
// Todo: read the captcha settings here, don't provide xmlcontent with form!!!
if (captchaFieldIsOnInputPage || displayCheckPage || submittedCheckPage) {
CmsObject cms = jsp.getCmsObject();
| // Path: com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/CmsFormContentUtil.java
// public static String getContentStringValue(CmsXmlContent content, CmsObject cms, String path, Locale locale) {
//
// return content.getStringValue(cms, getNestedPathPrefix(content, NODE_NESTED_FORM, locale) + path, locale);
// }
//
// Path: com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/CmsFormContentUtil.java
// public static I_CmsXmlContentValue getContentValue(CmsXmlContent content, String path, Locale locale) {
//
// return content.getValue(getNestedPathPrefix(content, NODE_NESTED_FORM, locale) + path, locale);
// }
//
// Path: com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/CmsFormContentUtil.java
// public static List<I_CmsXmlContentValue> getContentValues(CmsXmlContent content, String path, Locale locale) {
//
// return content.getValues(getNestedPathPrefix(content, NODE_NESTED_FORM, locale) + path, locale);
// }
// Path: com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/CmsForm.java
import static com.alkacon.opencms.v8.formgenerator.CmsFormContentUtil.getContentStringValue;
import static com.alkacon.opencms.v8.formgenerator.CmsFormContentUtil.getContentValue;
import static com.alkacon.opencms.v8.formgenerator.CmsFormContentUtil.getContentValues;
import org.opencms.configuration.CmsConfigurationException;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.i18n.CmsMessages;
import org.opencms.jsp.CmsJspActionElement;
import org.opencms.main.OpenCms;
import org.opencms.util.CmsMacroResolver;
import org.opencms.util.CmsStringUtil;
import org.opencms.workplace.CmsWorkplace;
import org.opencms.xml.content.CmsXmlContent;
import org.opencms.xml.content.CmsXmlContentFactory;
import org.opencms.xml.types.CmsXmlHtmlValue;
import org.opencms.xml.types.I_CmsXmlContentValue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import org.apache.commons.fileupload.FileItem;
* @return the parameter value
*/
protected String getParameter(String parameter) {
try {
return (m_parameterMap.get(parameter))[0];
} catch (NullPointerException e) {
return "";
}
}
/**
* Initializes the optional captcha field.<p>
*
* @param jsp the initialized CmsJspActionElement to access the OpenCms API
* @param content the XML configuration content
* @param locale the currently active Locale
* @param initial if true, field values are filled with values specified in the XML configuration, otherwise values are read from the request
*/
protected void initCaptchaField(CmsJspActionElement jsp, CmsXmlContent content, Locale locale, boolean initial) {
boolean captchaFieldIsOnInputPage = captchaFieldIsOnInputPage();
boolean displayCheckPage = captchaFieldIsOnCheckPage() && isInputFormSubmitted();
boolean submittedCheckPage = captchaFieldIsOnCheckPage() && isCheckPageSubmitted();
// Todo: read the captcha settings here, don't provide xmlcontent with form!!!
if (captchaFieldIsOnInputPage || displayCheckPage || submittedCheckPage) {
CmsObject cms = jsp.getCmsObject();
| I_CmsXmlContentValue xmlValueCaptcha = CmsFormContentUtil.getContentValue(content, NODE_CAPTCHA, locale);
|
alkacon/alkacon-oamp | com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/CmsForm.java | // Path: com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/CmsFormContentUtil.java
// public static String getContentStringValue(CmsXmlContent content, CmsObject cms, String path, Locale locale) {
//
// return content.getStringValue(cms, getNestedPathPrefix(content, NODE_NESTED_FORM, locale) + path, locale);
// }
//
// Path: com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/CmsFormContentUtil.java
// public static I_CmsXmlContentValue getContentValue(CmsXmlContent content, String path, Locale locale) {
//
// return content.getValue(getNestedPathPrefix(content, NODE_NESTED_FORM, locale) + path, locale);
// }
//
// Path: com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/CmsFormContentUtil.java
// public static List<I_CmsXmlContentValue> getContentValues(CmsXmlContent content, String path, Locale locale) {
//
// return content.getValues(getNestedPathPrefix(content, NODE_NESTED_FORM, locale) + path, locale);
// }
| import static com.alkacon.opencms.v8.formgenerator.CmsFormContentUtil.getContentStringValue;
import static com.alkacon.opencms.v8.formgenerator.CmsFormContentUtil.getContentValue;
import static com.alkacon.opencms.v8.formgenerator.CmsFormContentUtil.getContentValues;
import org.opencms.configuration.CmsConfigurationException;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.i18n.CmsMessages;
import org.opencms.jsp.CmsJspActionElement;
import org.opencms.main.OpenCms;
import org.opencms.util.CmsMacroResolver;
import org.opencms.util.CmsStringUtil;
import org.opencms.workplace.CmsWorkplace;
import org.opencms.xml.content.CmsXmlContent;
import org.opencms.xml.content.CmsXmlContentFactory;
import org.opencms.xml.types.CmsXmlHtmlValue;
import org.opencms.xml.types.I_CmsXmlContentValue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import org.apache.commons.fileupload.FileItem;
| initFormGlobalConfiguration(content, cms, locale, messages, null);
}
/**
* Initializes the general online form settings.<p>
*
* @param content the XML configuration content
* @param cms the CmsObject to access the content values
* @param locale the currently active Locale
* @param messages the localized messages
* @param dynamicConfig map of configurations that can overwrite the configuration from the configuration file
*
* @throws Exception if initializing the form settings fails
*
*/
protected void initFormGlobalConfiguration(
CmsXmlContent content,
CmsObject cms,
Locale locale,
CmsMessages messages,
Map<String, String> dynamicConfig) throws Exception {
// create a macro resolver with the cms object
CmsMacroResolver resolver = CmsMacroResolver.newInstance().setCmsObject(cms).setKeepEmptyMacros(true);
String stringValue;
// get the form text
stringValue = getValueFromDynamicConfig(dynamicConfig, NODE_FORMTEXT);
if (stringValue == null) {
| // Path: com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/CmsFormContentUtil.java
// public static String getContentStringValue(CmsXmlContent content, CmsObject cms, String path, Locale locale) {
//
// return content.getStringValue(cms, getNestedPathPrefix(content, NODE_NESTED_FORM, locale) + path, locale);
// }
//
// Path: com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/CmsFormContentUtil.java
// public static I_CmsXmlContentValue getContentValue(CmsXmlContent content, String path, Locale locale) {
//
// return content.getValue(getNestedPathPrefix(content, NODE_NESTED_FORM, locale) + path, locale);
// }
//
// Path: com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/CmsFormContentUtil.java
// public static List<I_CmsXmlContentValue> getContentValues(CmsXmlContent content, String path, Locale locale) {
//
// return content.getValues(getNestedPathPrefix(content, NODE_NESTED_FORM, locale) + path, locale);
// }
// Path: com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/CmsForm.java
import static com.alkacon.opencms.v8.formgenerator.CmsFormContentUtil.getContentStringValue;
import static com.alkacon.opencms.v8.formgenerator.CmsFormContentUtil.getContentValue;
import static com.alkacon.opencms.v8.formgenerator.CmsFormContentUtil.getContentValues;
import org.opencms.configuration.CmsConfigurationException;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.i18n.CmsMessages;
import org.opencms.jsp.CmsJspActionElement;
import org.opencms.main.OpenCms;
import org.opencms.util.CmsMacroResolver;
import org.opencms.util.CmsStringUtil;
import org.opencms.workplace.CmsWorkplace;
import org.opencms.xml.content.CmsXmlContent;
import org.opencms.xml.content.CmsXmlContentFactory;
import org.opencms.xml.types.CmsXmlHtmlValue;
import org.opencms.xml.types.I_CmsXmlContentValue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import org.apache.commons.fileupload.FileItem;
initFormGlobalConfiguration(content, cms, locale, messages, null);
}
/**
* Initializes the general online form settings.<p>
*
* @param content the XML configuration content
* @param cms the CmsObject to access the content values
* @param locale the currently active Locale
* @param messages the localized messages
* @param dynamicConfig map of configurations that can overwrite the configuration from the configuration file
*
* @throws Exception if initializing the form settings fails
*
*/
protected void initFormGlobalConfiguration(
CmsXmlContent content,
CmsObject cms,
Locale locale,
CmsMessages messages,
Map<String, String> dynamicConfig) throws Exception {
// create a macro resolver with the cms object
CmsMacroResolver resolver = CmsMacroResolver.newInstance().setCmsObject(cms).setKeepEmptyMacros(true);
String stringValue;
// get the form text
stringValue = getValueFromDynamicConfig(dynamicConfig, NODE_FORMTEXT);
if (stringValue == null) {
| stringValue = getContentStringValue(content, cms, NODE_FORMTEXT, locale);
|
alkacon/alkacon-oamp | com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/CmsForm.java | // Path: com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/CmsFormContentUtil.java
// public static String getContentStringValue(CmsXmlContent content, CmsObject cms, String path, Locale locale) {
//
// return content.getStringValue(cms, getNestedPathPrefix(content, NODE_NESTED_FORM, locale) + path, locale);
// }
//
// Path: com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/CmsFormContentUtil.java
// public static I_CmsXmlContentValue getContentValue(CmsXmlContent content, String path, Locale locale) {
//
// return content.getValue(getNestedPathPrefix(content, NODE_NESTED_FORM, locale) + path, locale);
// }
//
// Path: com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/CmsFormContentUtil.java
// public static List<I_CmsXmlContentValue> getContentValues(CmsXmlContent content, String path, Locale locale) {
//
// return content.getValues(getNestedPathPrefix(content, NODE_NESTED_FORM, locale) + path, locale);
// }
| import static com.alkacon.opencms.v8.formgenerator.CmsFormContentUtil.getContentStringValue;
import static com.alkacon.opencms.v8.formgenerator.CmsFormContentUtil.getContentValue;
import static com.alkacon.opencms.v8.formgenerator.CmsFormContentUtil.getContentValues;
import org.opencms.configuration.CmsConfigurationException;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.i18n.CmsMessages;
import org.opencms.jsp.CmsJspActionElement;
import org.opencms.main.OpenCms;
import org.opencms.util.CmsMacroResolver;
import org.opencms.util.CmsStringUtil;
import org.opencms.workplace.CmsWorkplace;
import org.opencms.xml.content.CmsXmlContent;
import org.opencms.xml.content.CmsXmlContentFactory;
import org.opencms.xml.types.CmsXmlHtmlValue;
import org.opencms.xml.types.I_CmsXmlContentValue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import org.apache.commons.fileupload.FileItem;
| // no valid release date defined, ignore setting
}
}
stringValue = getValueFromDynamicConfig(dynamicConfig, pathPrefix + NODE_TEXT);
if (stringValue != null) {
setMaximumSubmissionsText(getConfigurationValue(stringValue, ""));
}
}
}
/**
* Initializes the field objects of the form.<p>
*
* @param content the XML configuration content
* @param jsp the initialized CmsJspActionElement to access the OpenCms API
* @param locale the currently active Locale
* @param messages the localized messages
* @param initial if true, field values are filled with values specified in the XML configuration, otherwise values are read from the request
* @throws CmsConfigurationException if parsing the configuration fails
*/
protected void initInputFields(
CmsXmlContent content,
CmsJspActionElement jsp,
Locale locale,
CmsMessages messages,
boolean initial) throws CmsConfigurationException {
// initialize the optional field texts
Map<String, CmsFieldText> fieldTexts = new HashMap<String, CmsFieldText>();
| // Path: com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/CmsFormContentUtil.java
// public static String getContentStringValue(CmsXmlContent content, CmsObject cms, String path, Locale locale) {
//
// return content.getStringValue(cms, getNestedPathPrefix(content, NODE_NESTED_FORM, locale) + path, locale);
// }
//
// Path: com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/CmsFormContentUtil.java
// public static I_CmsXmlContentValue getContentValue(CmsXmlContent content, String path, Locale locale) {
//
// return content.getValue(getNestedPathPrefix(content, NODE_NESTED_FORM, locale) + path, locale);
// }
//
// Path: com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/CmsFormContentUtil.java
// public static List<I_CmsXmlContentValue> getContentValues(CmsXmlContent content, String path, Locale locale) {
//
// return content.getValues(getNestedPathPrefix(content, NODE_NESTED_FORM, locale) + path, locale);
// }
// Path: com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/CmsForm.java
import static com.alkacon.opencms.v8.formgenerator.CmsFormContentUtil.getContentStringValue;
import static com.alkacon.opencms.v8.formgenerator.CmsFormContentUtil.getContentValue;
import static com.alkacon.opencms.v8.formgenerator.CmsFormContentUtil.getContentValues;
import org.opencms.configuration.CmsConfigurationException;
import org.opencms.file.CmsFile;
import org.opencms.file.CmsObject;
import org.opencms.i18n.CmsMessages;
import org.opencms.jsp.CmsJspActionElement;
import org.opencms.main.OpenCms;
import org.opencms.util.CmsMacroResolver;
import org.opencms.util.CmsStringUtil;
import org.opencms.workplace.CmsWorkplace;
import org.opencms.xml.content.CmsXmlContent;
import org.opencms.xml.content.CmsXmlContentFactory;
import org.opencms.xml.types.CmsXmlHtmlValue;
import org.opencms.xml.types.I_CmsXmlContentValue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import org.apache.commons.fileupload.FileItem;
// no valid release date defined, ignore setting
}
}
stringValue = getValueFromDynamicConfig(dynamicConfig, pathPrefix + NODE_TEXT);
if (stringValue != null) {
setMaximumSubmissionsText(getConfigurationValue(stringValue, ""));
}
}
}
/**
* Initializes the field objects of the form.<p>
*
* @param content the XML configuration content
* @param jsp the initialized CmsJspActionElement to access the OpenCms API
* @param locale the currently active Locale
* @param messages the localized messages
* @param initial if true, field values are filled with values specified in the XML configuration, otherwise values are read from the request
* @throws CmsConfigurationException if parsing the configuration fails
*/
protected void initInputFields(
CmsXmlContent content,
CmsJspActionElement jsp,
Locale locale,
CmsMessages messages,
boolean initial) throws CmsConfigurationException {
// initialize the optional field texts
Map<String, CmsFieldText> fieldTexts = new HashMap<String, CmsFieldText>();
| List<I_CmsXmlContentValue> textValues = getContentValues(content, NODE_OPTIONALFIELDTEXT, locale);
|
alkacon/alkacon-oamp | com.alkacon.opencms.v8.calendar/src/com/alkacon/opencms/v8/calendar/test/AllTests.java | // Path: com.alkacon.opencms.v8.calendar/src/com/alkacon/opencms/v8/calendar/CmsCalendar.java
// public class CmsCalendar {
//
// /** Contains the configured calendar entries. */
// private List m_entries;
//
// /**
// * Default constructor, creates an empty calendar without entries.<p>
// */
// public CmsCalendar() {
//
// m_entries = new ArrayList();
// }
//
// /**
// * Constructor with parameter, creates a calendar with provided list of entries.<p>
// *
// * @param entries the list of entries for the calendar day
// */
// public CmsCalendar(List entries) {
//
// m_entries = entries;
// }
//
// /**
// * Adds a calendar entry to the list of entries for the day.<p>
// *
// * @param entry the calendar entry to add
// */
// public void addEntry(CmsCalendarEntry entry) {
//
// m_entries.add(entry);
// }
//
// /**
// * Returns all calendar entries.<p>
// *
// * @return all calendar entries
// */
// public List getEntries() {
//
// return m_entries;
// }
//
// /**
// * Returns the entries for the given calendar view, sorted by the view's sort method.<p>
// *
// * @param calendarView the given calendar view
// *
// * @return the matching entries for the calendar view
// */
// public List getEntries(I_CmsCalendarView calendarView) {
//
// List result = new ArrayList();
//
// for (int i = 0; i < m_entries.size(); i++) {
// CmsCalendarEntry entry = (CmsCalendarEntry)m_entries.get(i);
// List matchedEntries = entry.matchCalendarView(calendarView);
// if (matchedEntries.size() > 0) {
// // add matching entries to result list
// result.addAll(matchedEntries);
// }
// }
//
// // sort the result using the view's sort method
// calendarView.sort(result);
//
// return result;
// }
//
// /**
// * Sets the sorted list of entries for the calendar day.<p>
// *
// * The list has to be created using {@link CmsCalendarEntry} objects.<p>
// *
// * @param entries the list of entries for the calendar day
// */
// public void setEntries(List entries) {
//
// m_entries = entries;
// }
//
// }
| import com.alkacon.opencms.v8.calendar.CmsCalendar;
import org.opencms.test.OpenCmsTestProperties;
import junit.framework.Test;
import junit.framework.TestSuite; | /*
* File : $Source: /alkacon/cvs/alkacon/com.alkacon.opencms.v8.calendar/src/com/alkacon/opencms/v8/calendar/test/AllTests.java,v $
* Date : $Date: 2008/04/25 14:50:41 $
* Version: $Revision: 1.1 $
*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) 2002 - 2007 Alkacon Software GmbH (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software GmbH, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.alkacon.opencms.v8.calendar.test;
/**
* Main test suite for the package <code>{@link com.alkacon.opencms.v8.calendar}</code>.<p>
*
* @author Andreas Zahner
*
* @version $Revision: 1.1 $
*
* @since 6.0.1
*/
public final class AllTests {
/**
* Hide constructor to prevent generation of class instances.<p>
*/
private AllTests() {
// empty
}
/**
* Returns the JUnit test suite for this package.<p>
*
* @return the JUnit test suite for this package
*/
public static Test suite() {
| // Path: com.alkacon.opencms.v8.calendar/src/com/alkacon/opencms/v8/calendar/CmsCalendar.java
// public class CmsCalendar {
//
// /** Contains the configured calendar entries. */
// private List m_entries;
//
// /**
// * Default constructor, creates an empty calendar without entries.<p>
// */
// public CmsCalendar() {
//
// m_entries = new ArrayList();
// }
//
// /**
// * Constructor with parameter, creates a calendar with provided list of entries.<p>
// *
// * @param entries the list of entries for the calendar day
// */
// public CmsCalendar(List entries) {
//
// m_entries = entries;
// }
//
// /**
// * Adds a calendar entry to the list of entries for the day.<p>
// *
// * @param entry the calendar entry to add
// */
// public void addEntry(CmsCalendarEntry entry) {
//
// m_entries.add(entry);
// }
//
// /**
// * Returns all calendar entries.<p>
// *
// * @return all calendar entries
// */
// public List getEntries() {
//
// return m_entries;
// }
//
// /**
// * Returns the entries for the given calendar view, sorted by the view's sort method.<p>
// *
// * @param calendarView the given calendar view
// *
// * @return the matching entries for the calendar view
// */
// public List getEntries(I_CmsCalendarView calendarView) {
//
// List result = new ArrayList();
//
// for (int i = 0; i < m_entries.size(); i++) {
// CmsCalendarEntry entry = (CmsCalendarEntry)m_entries.get(i);
// List matchedEntries = entry.matchCalendarView(calendarView);
// if (matchedEntries.size() > 0) {
// // add matching entries to result list
// result.addAll(matchedEntries);
// }
// }
//
// // sort the result using the view's sort method
// calendarView.sort(result);
//
// return result;
// }
//
// /**
// * Sets the sorted list of entries for the calendar day.<p>
// *
// * The list has to be created using {@link CmsCalendarEntry} objects.<p>
// *
// * @param entries the list of entries for the calendar day
// */
// public void setEntries(List entries) {
//
// m_entries = entries;
// }
//
// }
// Path: com.alkacon.opencms.v8.calendar/src/com/alkacon/opencms/v8/calendar/test/AllTests.java
import com.alkacon.opencms.v8.calendar.CmsCalendar;
import org.opencms.test.OpenCmsTestProperties;
import junit.framework.Test;
import junit.framework.TestSuite;
/*
* File : $Source: /alkacon/cvs/alkacon/com.alkacon.opencms.v8.calendar/src/com/alkacon/opencms/v8/calendar/test/AllTests.java,v $
* Date : $Date: 2008/04/25 14:50:41 $
* Version: $Revision: 1.1 $
*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) 2002 - 2007 Alkacon Software GmbH (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* For further information about Alkacon Software GmbH, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.alkacon.opencms.v8.calendar.test;
/**
* Main test suite for the package <code>{@link com.alkacon.opencms.v8.calendar}</code>.<p>
*
* @author Andreas Zahner
*
* @version $Revision: 1.1 $
*
* @since 6.0.1
*/
public final class AllTests {
/**
* Hide constructor to prevent generation of class instances.<p>
*/
private AllTests() {
// empty
}
/**
* Returns the JUnit test suite for this package.<p>
*
* @return the JUnit test suite for this package
*/
public static Test suite() {
| TestSuite suite = new TestSuite("Tests for package " + CmsCalendar.class.getPackage().getName()); |
killme2008/Metamorphosis | metamorphosis-server-wrapper/src/main/java/com/taobao/metamorphosis/http/processor/MetamorphosisOnJettyProcessor.java | // Path: metamorphosis-server/src/main/java/com/taobao/metamorphosis/server/network/PutCallback.java
// public interface PutCallback {
//
// public void putComplete(ResponseCommand resp);
// }
| import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import com.taobao.gecko.core.command.ResponseCommand;
import com.taobao.metamorphosis.network.BooleanCommand;
import com.taobao.metamorphosis.network.DataCommand;
import com.taobao.metamorphosis.network.GetCommand;
import com.taobao.metamorphosis.network.HttpStatus;
import com.taobao.metamorphosis.network.OffsetCommand;
import com.taobao.metamorphosis.network.PutCommand;
import com.taobao.metamorphosis.server.CommandProcessor;
import com.taobao.metamorphosis.server.assembly.MetaMorphosisBroker;
import com.taobao.metamorphosis.server.network.PutCallback; | response.setStatus(((BooleanCommand) responseCommand).getCode());
response.getWriter().write(((BooleanCommand) responseCommand).getErrorMsg());
}
catch (final Throwable e) {
logger.error("Could not get message from position " + offset, e);
response.setStatus(HttpStatus.InternalServerError);
response.getWriter().write(e.getMessage());
}
}
private void putMessage(final Request jettyRequest, final HttpServletResponse response) throws IOException {
final String topic = jettyRequest.getParameter("topic");
try {
// Validation should be done on client side already
final int partition = Integer.parseInt(jettyRequest.getParameter("partition"));
final int flag = Integer.parseInt(jettyRequest.getParameter("flag"));
int checkSum = -1;
if (StringUtils.isNotBlank(jettyRequest.getParameter("checksum"))) {
checkSum = Integer.parseInt(jettyRequest.getParameter("checksum"));
}
// This stream should be handle by Jetty server and therefore it is
// out of scope here without care close
final InputStream inputStream = jettyRequest.getInputStream();
final int dataLength = Integer.parseInt(jettyRequest.getParameter("length"));
final byte[] data = new byte[dataLength];
inputStream.read(data);
this.doResponseHeaders(response, "text/plain");
final PutCommand putCommand = this.convert2PutCommand(topic, partition, data, flag, checkSum); | // Path: metamorphosis-server/src/main/java/com/taobao/metamorphosis/server/network/PutCallback.java
// public interface PutCallback {
//
// public void putComplete(ResponseCommand resp);
// }
// Path: metamorphosis-server-wrapper/src/main/java/com/taobao/metamorphosis/http/processor/MetamorphosisOnJettyProcessor.java
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import com.taobao.gecko.core.command.ResponseCommand;
import com.taobao.metamorphosis.network.BooleanCommand;
import com.taobao.metamorphosis.network.DataCommand;
import com.taobao.metamorphosis.network.GetCommand;
import com.taobao.metamorphosis.network.HttpStatus;
import com.taobao.metamorphosis.network.OffsetCommand;
import com.taobao.metamorphosis.network.PutCommand;
import com.taobao.metamorphosis.server.CommandProcessor;
import com.taobao.metamorphosis.server.assembly.MetaMorphosisBroker;
import com.taobao.metamorphosis.server.network.PutCallback;
response.setStatus(((BooleanCommand) responseCommand).getCode());
response.getWriter().write(((BooleanCommand) responseCommand).getErrorMsg());
}
catch (final Throwable e) {
logger.error("Could not get message from position " + offset, e);
response.setStatus(HttpStatus.InternalServerError);
response.getWriter().write(e.getMessage());
}
}
private void putMessage(final Request jettyRequest, final HttpServletResponse response) throws IOException {
final String topic = jettyRequest.getParameter("topic");
try {
// Validation should be done on client side already
final int partition = Integer.parseInt(jettyRequest.getParameter("partition"));
final int flag = Integer.parseInt(jettyRequest.getParameter("flag"));
int checkSum = -1;
if (StringUtils.isNotBlank(jettyRequest.getParameter("checksum"))) {
checkSum = Integer.parseInt(jettyRequest.getParameter("checksum"));
}
// This stream should be handle by Jetty server and therefore it is
// out of scope here without care close
final InputStream inputStream = jettyRequest.getInputStream();
final int dataLength = Integer.parseInt(jettyRequest.getParameter("length"));
final byte[] data = new byte[dataLength];
inputStream.read(data);
this.doResponseHeaders(response, "text/plain");
final PutCommand putCommand = this.convert2PutCommand(topic, partition, data, flag, checkSum); | this.commandProcessor.processPutCommand(putCommand, null, new PutCallback() { |
smitchell/garmin-fit-geojson | src/test/java/com/exploringspatial/service/GarminFitListnerTest.java | // Path: src/main/java/com/exploringspatial/domain/FitActivity.java
// public class FitActivity {
// private Long activityId;
// private String name;
// private String description;
// /**
// * Timestamp formatted to ISO 8601
// * http://www.w3.org/TR/NOTE-datetime
// * See Apache commons-lang3 have useful constants, for example: DateFormatUtils.ISO_DATETIME_FORMAT:
// * DateFormatUtils.format(new Date(), "yyyy-MM-dd'T'HH:mm'Z'", TimeZone.getTimeZone("UTC"))
// * // e.g. 2012-04-23T18:25:43.511Z
// */
// private String startTime;
// private String sport;
// private Double totalMeters;
// private Double totalSeconds;
// private List<Coordinate> polyline = new ArrayList<Coordinate>();
//
// public Long getActivityId() {
// return activityId;
// }
//
// public void setActivityId(final Long activityId) {
// this.activityId = activityId;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(final String description) {
// this.description = description;
// }
//
// public String getStartTime() {
// return startTime;
// }
//
// public void setStartTime(final String startTime) {
// this.startTime = startTime;
// }
//
// public String getSport() {
// return sport;
// }
//
// public void setSport(String sport) {
// this.sport = sport;
// }
//
// public Double getTotalMeters() {
// return totalMeters;
// }
//
// public void setTotalMeters(Double totalMeters) {
// this.totalMeters = totalMeters;
// }
//
// public Double getTotalSeconds() {
// return totalSeconds;
// }
//
// public void setTotalSeconds(Double totalSeconds) {
// this.totalSeconds = totalSeconds;
// }
//
// public List<Coordinate> getPolyline() {
// return polyline;
// }
//
// public void setPolyline(final List<Coordinate> polyline) {
// this.polyline = polyline;
// }
//
// public void addCoordinate(final Coordinate coordinate) {
// if (this.polyline == null) {
// this.polyline = new ArrayList<Coordinate>(1);
// }
// this.polyline.add(coordinate);
// }
// }
| import com.exploringspatial.domain.FitActivity;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import org.junit.Test;
import org.opengis.referencing.FactoryException;
import java.io.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue; | package com.exploringspatial.service;
/**
* Created by Steve on 1/3/15.
*/
public class GarminFitListnerTest {
private final String fileName = "/155155867.fit";
@Test
public void testExtractFitPolyline() throws IOException {
final InputStream in = this.getClass().getResourceAsStream(fileName);
final GarminFitService garminFitService = new GarminFitService(); | // Path: src/main/java/com/exploringspatial/domain/FitActivity.java
// public class FitActivity {
// private Long activityId;
// private String name;
// private String description;
// /**
// * Timestamp formatted to ISO 8601
// * http://www.w3.org/TR/NOTE-datetime
// * See Apache commons-lang3 have useful constants, for example: DateFormatUtils.ISO_DATETIME_FORMAT:
// * DateFormatUtils.format(new Date(), "yyyy-MM-dd'T'HH:mm'Z'", TimeZone.getTimeZone("UTC"))
// * // e.g. 2012-04-23T18:25:43.511Z
// */
// private String startTime;
// private String sport;
// private Double totalMeters;
// private Double totalSeconds;
// private List<Coordinate> polyline = new ArrayList<Coordinate>();
//
// public Long getActivityId() {
// return activityId;
// }
//
// public void setActivityId(final Long activityId) {
// this.activityId = activityId;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(final String description) {
// this.description = description;
// }
//
// public String getStartTime() {
// return startTime;
// }
//
// public void setStartTime(final String startTime) {
// this.startTime = startTime;
// }
//
// public String getSport() {
// return sport;
// }
//
// public void setSport(String sport) {
// this.sport = sport;
// }
//
// public Double getTotalMeters() {
// return totalMeters;
// }
//
// public void setTotalMeters(Double totalMeters) {
// this.totalMeters = totalMeters;
// }
//
// public Double getTotalSeconds() {
// return totalSeconds;
// }
//
// public void setTotalSeconds(Double totalSeconds) {
// this.totalSeconds = totalSeconds;
// }
//
// public List<Coordinate> getPolyline() {
// return polyline;
// }
//
// public void setPolyline(final List<Coordinate> polyline) {
// this.polyline = polyline;
// }
//
// public void addCoordinate(final Coordinate coordinate) {
// if (this.polyline == null) {
// this.polyline = new ArrayList<Coordinate>(1);
// }
// this.polyline.add(coordinate);
// }
// }
// Path: src/test/java/com/exploringspatial/service/GarminFitListnerTest.java
import com.exploringspatial.domain.FitActivity;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import org.junit.Test;
import org.opengis.referencing.FactoryException;
import java.io.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
package com.exploringspatial.service;
/**
* Created by Steve on 1/3/15.
*/
public class GarminFitListnerTest {
private final String fileName = "/155155867.fit";
@Test
public void testExtractFitPolyline() throws IOException {
final InputStream in = this.getClass().getResourceAsStream(fileName);
final GarminFitService garminFitService = new GarminFitService(); | final FitActivity fitActivity = garminFitService.decodeFitFile(in); |
smitchell/garmin-fit-geojson | src/main/java/com/exploringspatial/tcx/TcxParser.java | // Path: src/main/java/com/exploringspatial/domain/FitActivity.java
// public class FitActivity {
// private Long activityId;
// private String name;
// private String description;
// /**
// * Timestamp formatted to ISO 8601
// * http://www.w3.org/TR/NOTE-datetime
// * See Apache commons-lang3 have useful constants, for example: DateFormatUtils.ISO_DATETIME_FORMAT:
// * DateFormatUtils.format(new Date(), "yyyy-MM-dd'T'HH:mm'Z'", TimeZone.getTimeZone("UTC"))
// * // e.g. 2012-04-23T18:25:43.511Z
// */
// private String startTime;
// private String sport;
// private Double totalMeters;
// private Double totalSeconds;
// private List<Coordinate> polyline = new ArrayList<Coordinate>();
//
// public Long getActivityId() {
// return activityId;
// }
//
// public void setActivityId(final Long activityId) {
// this.activityId = activityId;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(final String description) {
// this.description = description;
// }
//
// public String getStartTime() {
// return startTime;
// }
//
// public void setStartTime(final String startTime) {
// this.startTime = startTime;
// }
//
// public String getSport() {
// return sport;
// }
//
// public void setSport(String sport) {
// this.sport = sport;
// }
//
// public Double getTotalMeters() {
// return totalMeters;
// }
//
// public void setTotalMeters(Double totalMeters) {
// this.totalMeters = totalMeters;
// }
//
// public Double getTotalSeconds() {
// return totalSeconds;
// }
//
// public void setTotalSeconds(Double totalSeconds) {
// this.totalSeconds = totalSeconds;
// }
//
// public List<Coordinate> getPolyline() {
// return polyline;
// }
//
// public void setPolyline(final List<Coordinate> polyline) {
// this.polyline = polyline;
// }
//
// public void addCoordinate(final Coordinate coordinate) {
// if (this.polyline == null) {
// this.polyline = new ArrayList<Coordinate>(1);
// }
// this.polyline.add(coordinate);
// }
// }
| import com.exploringspatial.domain.FitActivity;
import com.garmin.trainingcenter.*;
import com.vividsolutions.jts.geom.Coordinate;
import org.apache.log4j.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List; | package com.exploringspatial.tcx;
/**
* Created by mitchellst on 1/7/15.
*/
public class TcxParser {
private final Logger log = Logger.getLogger(TcxParser.class);
private Unmarshaller unmarshaller;
public TcxParser() {
super();
init();
}
private void init() {
try {
JAXBContext jaxbContext = JAXBContext.newInstance("com.garmin.trainingcenter");
unmarshaller = jaxbContext.createUnmarshaller();
} catch (JAXBException e) {
e.printStackTrace();
}
}
| // Path: src/main/java/com/exploringspatial/domain/FitActivity.java
// public class FitActivity {
// private Long activityId;
// private String name;
// private String description;
// /**
// * Timestamp formatted to ISO 8601
// * http://www.w3.org/TR/NOTE-datetime
// * See Apache commons-lang3 have useful constants, for example: DateFormatUtils.ISO_DATETIME_FORMAT:
// * DateFormatUtils.format(new Date(), "yyyy-MM-dd'T'HH:mm'Z'", TimeZone.getTimeZone("UTC"))
// * // e.g. 2012-04-23T18:25:43.511Z
// */
// private String startTime;
// private String sport;
// private Double totalMeters;
// private Double totalSeconds;
// private List<Coordinate> polyline = new ArrayList<Coordinate>();
//
// public Long getActivityId() {
// return activityId;
// }
//
// public void setActivityId(final Long activityId) {
// this.activityId = activityId;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(final String description) {
// this.description = description;
// }
//
// public String getStartTime() {
// return startTime;
// }
//
// public void setStartTime(final String startTime) {
// this.startTime = startTime;
// }
//
// public String getSport() {
// return sport;
// }
//
// public void setSport(String sport) {
// this.sport = sport;
// }
//
// public Double getTotalMeters() {
// return totalMeters;
// }
//
// public void setTotalMeters(Double totalMeters) {
// this.totalMeters = totalMeters;
// }
//
// public Double getTotalSeconds() {
// return totalSeconds;
// }
//
// public void setTotalSeconds(Double totalSeconds) {
// this.totalSeconds = totalSeconds;
// }
//
// public List<Coordinate> getPolyline() {
// return polyline;
// }
//
// public void setPolyline(final List<Coordinate> polyline) {
// this.polyline = polyline;
// }
//
// public void addCoordinate(final Coordinate coordinate) {
// if (this.polyline == null) {
// this.polyline = new ArrayList<Coordinate>(1);
// }
// this.polyline.add(coordinate);
// }
// }
// Path: src/main/java/com/exploringspatial/tcx/TcxParser.java
import com.exploringspatial.domain.FitActivity;
import com.garmin.trainingcenter.*;
import com.vividsolutions.jts.geom.Coordinate;
import org.apache.log4j.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
package com.exploringspatial.tcx;
/**
* Created by mitchellst on 1/7/15.
*/
public class TcxParser {
private final Logger log = Logger.getLogger(TcxParser.class);
private Unmarshaller unmarshaller;
public TcxParser() {
super();
init();
}
private void init() {
try {
JAXBContext jaxbContext = JAXBContext.newInstance("com.garmin.trainingcenter");
unmarshaller = jaxbContext.createUnmarshaller();
} catch (JAXBException e) {
e.printStackTrace();
}
}
| public List<FitActivity> parseTcxFile(final InputStream inputStream) { |
magnusmickelsson/pokeraidbot | src/main/java/pokeraidbot/domain/raid/RaidBossCounters.java | // Path: src/main/java/pokeraidbot/domain/pokemon/Pokemon.java
// public class Pokemon {
//
// private String name;
// private PokemonTypes types;
// private Set<String> weaknesses;
// private Set<String> resistant;
// private Integer number;
// private String about;
// private String buddyDistance;
//
// public Pokemon(Integer number, String name, String about, PokemonTypes types, String buddyDistance,
// Set<String> weaknesses, Set<String> resistantTo) {
// Validate.notNull(number, "Number is null!");
// Validate.notNull(types, "Types is null!");
// Validate.notEmpty(name, "Name is empty!");
// if (types != PokemonTypes.NONE) {
// Validate.notEmpty(weaknesses, "Weaknesses is empty!");
// Validate.notEmpty(resistantTo, "ResistantTo is empty!");
// }
//
// this.number = number;
// this.name = name;
// this.about = about;
// this.types = types;
// this.buddyDistance = buddyDistance;
// this.weaknesses = weaknesses;
// resistant = resistantTo;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof Pokemon)) return false;
//
// Pokemon pokemon = (Pokemon) o;
//
// if (name != null ? !name.equals(pokemon.name) : pokemon.name != null) return false;
// if (types != null ? !types.equals(pokemon.types) : pokemon.types != null) return false;
// if (weaknesses != null ? !weaknesses.equals(pokemon.weaknesses) : pokemon.weaknesses != null) return false;
// if (resistant != null ? !resistant.equals(pokemon.resistant) : pokemon.resistant != null) return false;
// if (number != null ? !number.equals(pokemon.number) : pokemon.number != null) return false;
// if (about != null ? !about.equals(pokemon.about) : pokemon.about != null) return false;
// return buddyDistance != null ? buddyDistance.equals(pokemon.buddyDistance) : pokemon.buddyDistance == null;
// }
//
// @Override
// public int hashCode() {
// int result = name != null ? name.hashCode() : 0;
// result = 31 * result + (types != null ? types.hashCode() : 0);
// result = 31 * result + (weaknesses != null ? weaknesses.hashCode() : 0);
// result = 31 * result + (resistant != null ? resistant.hashCode() : 0);
// result = 31 * result + (number != null ? number.hashCode() : 0);
// result = 31 * result + (about != null ? about.hashCode() : 0);
// result = 31 * result + (buddyDistance != null ? buddyDistance.hashCode() : 0);
// return result;
// }
//
// public PokemonTypes getTypes() {
// return types;
// }
//
// public Set<String> getWeaknesses() {
// return weaknesses;
// }
//
// public Set<String> getResistant() {
// return resistant;
// }
//
// public Integer getNumber() {
// return number;
// }
//
// public String getAbout() {
// return about;
// }
//
// public String getBuddyDistance() {
// return buddyDistance;
// }
//
// @Override
// public String toString() {
// return name + (types.getTypeSet().size() > 0 ? " (" + types + ")" : "");
// }
//
// public String getName() {
// return name;
// }
//
// public boolean isEgg() {
// return StringUtils.containsIgnoreCase(name, "egg") && name.matches("[Ee][Gg][Gg][1-6]");
// }
// }
//
// Path: src/main/java/pokeraidbot/infrastructure/CounterPokemon.java
// public class CounterPokemon {
// private final String counterPokemonName;
// private final Set<String> moves;
//
// public CounterPokemon(String counterPokemonName, Set<String> moves) {
// this.counterPokemonName = counterPokemonName;
// this.moves = moves;
// }
//
// public String getCounterPokemonName() {
// return counterPokemonName;
// }
//
// public Set<String> getMoves() {
// return moves;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof CounterPokemon)) return false;
//
// CounterPokemon that = (CounterPokemon) o;
//
// if (counterPokemonName != null ? !counterPokemonName.equals(that.counterPokemonName) : that.counterPokemonName != null)
// return false;
// return moves != null ? moves.equals(that.moves) : that.moves == null;
// }
//
// @Override
// public int hashCode() {
// int result = counterPokemonName != null ? counterPokemonName.hashCode() : 0;
// result = 31 * result + (moves != null ? moves.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return counterPokemonName;
// }
// }
| import pokeraidbot.domain.pokemon.Pokemon;
import pokeraidbot.infrastructure.CounterPokemon;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set; | package pokeraidbot.domain.raid;
public class RaidBossCounters {
private Pokemon pokemon; | // Path: src/main/java/pokeraidbot/domain/pokemon/Pokemon.java
// public class Pokemon {
//
// private String name;
// private PokemonTypes types;
// private Set<String> weaknesses;
// private Set<String> resistant;
// private Integer number;
// private String about;
// private String buddyDistance;
//
// public Pokemon(Integer number, String name, String about, PokemonTypes types, String buddyDistance,
// Set<String> weaknesses, Set<String> resistantTo) {
// Validate.notNull(number, "Number is null!");
// Validate.notNull(types, "Types is null!");
// Validate.notEmpty(name, "Name is empty!");
// if (types != PokemonTypes.NONE) {
// Validate.notEmpty(weaknesses, "Weaknesses is empty!");
// Validate.notEmpty(resistantTo, "ResistantTo is empty!");
// }
//
// this.number = number;
// this.name = name;
// this.about = about;
// this.types = types;
// this.buddyDistance = buddyDistance;
// this.weaknesses = weaknesses;
// resistant = resistantTo;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof Pokemon)) return false;
//
// Pokemon pokemon = (Pokemon) o;
//
// if (name != null ? !name.equals(pokemon.name) : pokemon.name != null) return false;
// if (types != null ? !types.equals(pokemon.types) : pokemon.types != null) return false;
// if (weaknesses != null ? !weaknesses.equals(pokemon.weaknesses) : pokemon.weaknesses != null) return false;
// if (resistant != null ? !resistant.equals(pokemon.resistant) : pokemon.resistant != null) return false;
// if (number != null ? !number.equals(pokemon.number) : pokemon.number != null) return false;
// if (about != null ? !about.equals(pokemon.about) : pokemon.about != null) return false;
// return buddyDistance != null ? buddyDistance.equals(pokemon.buddyDistance) : pokemon.buddyDistance == null;
// }
//
// @Override
// public int hashCode() {
// int result = name != null ? name.hashCode() : 0;
// result = 31 * result + (types != null ? types.hashCode() : 0);
// result = 31 * result + (weaknesses != null ? weaknesses.hashCode() : 0);
// result = 31 * result + (resistant != null ? resistant.hashCode() : 0);
// result = 31 * result + (number != null ? number.hashCode() : 0);
// result = 31 * result + (about != null ? about.hashCode() : 0);
// result = 31 * result + (buddyDistance != null ? buddyDistance.hashCode() : 0);
// return result;
// }
//
// public PokemonTypes getTypes() {
// return types;
// }
//
// public Set<String> getWeaknesses() {
// return weaknesses;
// }
//
// public Set<String> getResistant() {
// return resistant;
// }
//
// public Integer getNumber() {
// return number;
// }
//
// public String getAbout() {
// return about;
// }
//
// public String getBuddyDistance() {
// return buddyDistance;
// }
//
// @Override
// public String toString() {
// return name + (types.getTypeSet().size() > 0 ? " (" + types + ")" : "");
// }
//
// public String getName() {
// return name;
// }
//
// public boolean isEgg() {
// return StringUtils.containsIgnoreCase(name, "egg") && name.matches("[Ee][Gg][Gg][1-6]");
// }
// }
//
// Path: src/main/java/pokeraidbot/infrastructure/CounterPokemon.java
// public class CounterPokemon {
// private final String counterPokemonName;
// private final Set<String> moves;
//
// public CounterPokemon(String counterPokemonName, Set<String> moves) {
// this.counterPokemonName = counterPokemonName;
// this.moves = moves;
// }
//
// public String getCounterPokemonName() {
// return counterPokemonName;
// }
//
// public Set<String> getMoves() {
// return moves;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof CounterPokemon)) return false;
//
// CounterPokemon that = (CounterPokemon) o;
//
// if (counterPokemonName != null ? !counterPokemonName.equals(that.counterPokemonName) : that.counterPokemonName != null)
// return false;
// return moves != null ? moves.equals(that.moves) : that.moves == null;
// }
//
// @Override
// public int hashCode() {
// int result = counterPokemonName != null ? counterPokemonName.hashCode() : 0;
// result = 31 * result + (moves != null ? moves.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return counterPokemonName;
// }
// }
// Path: src/main/java/pokeraidbot/domain/raid/RaidBossCounters.java
import pokeraidbot.domain.pokemon.Pokemon;
import pokeraidbot.infrastructure.CounterPokemon;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
package pokeraidbot.domain.raid;
public class RaidBossCounters {
private Pokemon pokemon; | private Set<CounterPokemon> supremeCounters = new LinkedHashSet<>(); |
marcohc/android-clean-architecture | bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/presentation/mvp/BaseBusMvpActivity.java | // Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/common/BusProvider.java
// public final class BusProvider {
//
// private static final EventBus BUS = EventBus.getDefault();
//
// private static EventBus getInstance() {
// return BUS;
// }
//
// public static void register(Object subscriber) {
// try {
// getInstance().register(subscriber);
// } catch (EventBusException e) {
// Timber.i("register: %s", e.getMessage());
// getInstance().unregister(subscriber);
// getInstance().register(subscriber);
// }
// }
//
// public static void unregister(Object subscriber) {
// getInstance().unregister(subscriber);
// }
//
// public static void post(Object busEvent) {
// if (busEvent != null) {
// log(busEvent);
// getInstance().post(busEvent);
// }
// }
//
// public static void cancelEventDelivery(BusEvent busEvent) {
// getInstance().cancelEventDelivery(busEvent);
// }
//
// public static void postSticky(Object busEvent) {
// if (busEvent != null) {
// log(busEvent);
// getInstance().postSticky(busEvent);
// }
// }
//
// public static <T> boolean containsStickyEvent(Class<T> clazz) {
// return getInstance().getStickyEvent(clazz) != null;
// }
//
// public static <T> T getStickyEvent(Class<T> busEventClass) {
// return getInstance().getStickyEvent(busEventClass);
// }
//
// public static void removeStickyEvent(BusEvent busEvent) {
// getInstance().removeStickyEvent(busEvent);
// }
//
// public static void removeAllStickyEvents() {
// getInstance().removeAllStickyEvents();
// }
//
// private static void log(Object busEvent) {
// String name = busEvent.getClass().getSimpleName();
// if (name.contains("Event")) {
// Timber.v("Event: %s", name);
// } else if (name.contains("Request")) {
// Timber.v("Request: %s", name);
// } else if (name.contains("DataResponse")) {
// Timber.v("DataResponse: %s", name);
// } else if (name.contains("DomainResponse")) {
// Timber.v("DomainResponse: %s", name);
// } else {
// Timber.v("Posting to bus: %s", name);
// }
// }
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpView.java
// public interface BaseMvpView extends MvpView {
//
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpActivity.java
// public abstract class BaseMvpActivity<V extends BaseMvpView, P extends MvpPresenter<V>> extends MvpActivity<V, P> implements BaseMvpView {
//
// /**
// * Used by Calligraphy.
// */
// @Override
// protected void attachBaseContext(Context newBase) {
// super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
// }
//
// /**
// * @return The layout id that will be used on {@link AppCompatActivity#setContentView(int)}
// */
// @LayoutRes
// protected abstract int getLayoutId();
//
// @CallSuper
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(getLayoutId());
// ButterKnife.bind(this);
// onViewCreated(savedInstanceState);
// }
//
// /**
// * When content is changed, ButterKnife will bind the view so is not needed to call from outside.
// */
// @Override
// @CallSuper
// public void onContentChanged() {
// super.onContentChanged();
// ButterKnife.bind(this);
// }
//
// /**
// * Called from {@link AppCompatActivity#onCreate(Bundle)}
// * after {@link AppCompatActivity#setContentView(int)} and {@link ButterKnife#bind(Activity)} was called.
// * <p>
// * This method can be used for initialize {@link android.view.View}
// *
// * @param savedInstanceState If non-null, this activity is being re-constructed from a previous saved state as given here.
// */
// protected abstract void onViewCreated(@Nullable final Bundle savedInstanceState);
// }
| import com.hannesdorfmann.mosby.mvp.MvpPresenter;
import com.marcohc.architecture.aca.presentation.bus.common.BusProvider;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpView;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpActivity; | package com.marcohc.architecture.aca.presentation.bus.presentation.mvp;
/**
* Base bus activity which automatically register into the event bus.
* <p>
* Override it for specific common methods in activities.
*
* @param <V> the BaseMvpView type the superclass is implementing
* @param <P> the type of MvpPresenter which will handle the logic of the class
* @author Marco Hernaiz
* @since 08/08/16
*/
public abstract class BaseBusMvpActivity<V extends BaseMvpView, P extends MvpPresenter<V>> extends BaseMvpActivity<V, P> implements BaseMvpView {
@Override
public void onStart() {
super.onStart(); | // Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/common/BusProvider.java
// public final class BusProvider {
//
// private static final EventBus BUS = EventBus.getDefault();
//
// private static EventBus getInstance() {
// return BUS;
// }
//
// public static void register(Object subscriber) {
// try {
// getInstance().register(subscriber);
// } catch (EventBusException e) {
// Timber.i("register: %s", e.getMessage());
// getInstance().unregister(subscriber);
// getInstance().register(subscriber);
// }
// }
//
// public static void unregister(Object subscriber) {
// getInstance().unregister(subscriber);
// }
//
// public static void post(Object busEvent) {
// if (busEvent != null) {
// log(busEvent);
// getInstance().post(busEvent);
// }
// }
//
// public static void cancelEventDelivery(BusEvent busEvent) {
// getInstance().cancelEventDelivery(busEvent);
// }
//
// public static void postSticky(Object busEvent) {
// if (busEvent != null) {
// log(busEvent);
// getInstance().postSticky(busEvent);
// }
// }
//
// public static <T> boolean containsStickyEvent(Class<T> clazz) {
// return getInstance().getStickyEvent(clazz) != null;
// }
//
// public static <T> T getStickyEvent(Class<T> busEventClass) {
// return getInstance().getStickyEvent(busEventClass);
// }
//
// public static void removeStickyEvent(BusEvent busEvent) {
// getInstance().removeStickyEvent(busEvent);
// }
//
// public static void removeAllStickyEvents() {
// getInstance().removeAllStickyEvents();
// }
//
// private static void log(Object busEvent) {
// String name = busEvent.getClass().getSimpleName();
// if (name.contains("Event")) {
// Timber.v("Event: %s", name);
// } else if (name.contains("Request")) {
// Timber.v("Request: %s", name);
// } else if (name.contains("DataResponse")) {
// Timber.v("DataResponse: %s", name);
// } else if (name.contains("DomainResponse")) {
// Timber.v("DomainResponse: %s", name);
// } else {
// Timber.v("Posting to bus: %s", name);
// }
// }
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpView.java
// public interface BaseMvpView extends MvpView {
//
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpActivity.java
// public abstract class BaseMvpActivity<V extends BaseMvpView, P extends MvpPresenter<V>> extends MvpActivity<V, P> implements BaseMvpView {
//
// /**
// * Used by Calligraphy.
// */
// @Override
// protected void attachBaseContext(Context newBase) {
// super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
// }
//
// /**
// * @return The layout id that will be used on {@link AppCompatActivity#setContentView(int)}
// */
// @LayoutRes
// protected abstract int getLayoutId();
//
// @CallSuper
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(getLayoutId());
// ButterKnife.bind(this);
// onViewCreated(savedInstanceState);
// }
//
// /**
// * When content is changed, ButterKnife will bind the view so is not needed to call from outside.
// */
// @Override
// @CallSuper
// public void onContentChanged() {
// super.onContentChanged();
// ButterKnife.bind(this);
// }
//
// /**
// * Called from {@link AppCompatActivity#onCreate(Bundle)}
// * after {@link AppCompatActivity#setContentView(int)} and {@link ButterKnife#bind(Activity)} was called.
// * <p>
// * This method can be used for initialize {@link android.view.View}
// *
// * @param savedInstanceState If non-null, this activity is being re-constructed from a previous saved state as given here.
// */
// protected abstract void onViewCreated(@Nullable final Bundle savedInstanceState);
// }
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/presentation/mvp/BaseBusMvpActivity.java
import com.hannesdorfmann.mosby.mvp.MvpPresenter;
import com.marcohc.architecture.aca.presentation.bus.common.BusProvider;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpView;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpActivity;
package com.marcohc.architecture.aca.presentation.bus.presentation.mvp;
/**
* Base bus activity which automatically register into the event bus.
* <p>
* Override it for specific common methods in activities.
*
* @param <V> the BaseMvpView type the superclass is implementing
* @param <P> the type of MvpPresenter which will handle the logic of the class
* @author Marco Hernaiz
* @since 08/08/16
*/
public abstract class BaseBusMvpActivity<V extends BaseMvpView, P extends MvpPresenter<V>> extends BaseMvpActivity<V, P> implements BaseMvpView {
@Override
public void onStart() {
super.onStart(); | BusProvider.register(presenter); |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/presentation/navigation/Navigator.java | // Path: app/src/main/java/com/marcohc/architecture/app/domain/model/UserModel.java
// public class UserModel implements Model {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserModel() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/story/user/userdetail/view/UserDetailActivity.java
// public class UserDetailActivity extends BaseMvpActivity<UserDetailView, UserDetailPresenter> implements UserDetailView {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @BindView(R.id.toolbar)
// Toolbar mToolbar;
//
// @BindView(R.id.userImageView)
// ImageView mUserImageView;
//
// @BindView(R.id.usernameTextView)
// TextView mUsernameTextView;
//
// @BindView(R.id.emailTextView)
// TextView mEmailTextView;
//
// // ************************************************************************************************************************************************************************
// // * Initialization methods
// // ************************************************************************************************************************************************************************
//
// @NonNull
// @Override
// public UserDetailPresenter createPresenter() {
// return new UserDetailPresenterImpl();
// }
//
// @Override
// protected int getLayoutId() {
// return R.layout.activity_user_detail;
// }
//
// @Override
// protected void onViewCreated(@Nullable Bundle savedInstanceState) {
// setUpActionBar();
// setUpUserData();
// }
//
// private void setUpActionBar() {
// setSupportActionBar(mToolbar);
// ActionBar actionBar = getSupportActionBar();
// if (actionBar != null) {
// actionBar.setTitle(R.string.user_detail);
// actionBar.setDisplayHomeAsUpEnabled(true);
// actionBar.setHomeButtonEnabled(true);
// }
// }
//
// private void setUpUserData() {
// presenter.onViewCreated(this);
// }
//
// // ************************************************************************************************************************************************************************
// // * Event handler methods
// // ************************************************************************************************************************************************************************
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// onBackPressed();
// return true;
// }
//
// @OnClick(R.id.userImageView)
// protected void onUserImageClick() {
// }
//
// // ************************************************************************************************************************************************************************
// // * View interface methods
// // ************************************************************************************************************************************************************************
//
// @Override
// public void renderModel(@NonNull UserModel model) {
// String image = model.getPictureUrl();
// if (!StringUtils.isBlank(image)) {
// Glide.with(this).load(image).error(R.drawable.im_user_place_holder).into(mUserImageView);
// } else {
// mUserImageView.setImageResource(R.drawable.im_user_place_holder);
// }
// mUsernameTextView.setText(model.getName());
// mEmailTextView.setText(model.getEmail());
// }
//
// // ************************************************************************************************************************************************************************
// // * UI methods
// // ************************************************************************************************************************************************************************
//
//
// }
| import android.content.Context;
import android.content.Intent;
import com.marcohc.architecture.app.domain.model.UserModel;
import com.marcohc.architecture.app.presentation.story.user.userdetail.view.UserDetailActivity; | package com.marcohc.architecture.app.presentation.navigation;
/**
* Manages the navigation between activities.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public final class Navigator {
// ************************************************************************************************************************************************************************
// * Constants
// ************************************************************************************************************************************************************************
public static final String USER = "user";
// ************************************************************************************************************************************************************************
// * Constructors
// ************************************************************************************************************************************************************************
private Navigator() {
}
// ************************************************************************************************************************************************************************
// * Navigation methods
// ************************************************************************************************************************************************************************
/**
* Go to {@link UserDetailActivity}.
*
* @param context the context
* @param model the UserModel to be displayed in the details
*/ | // Path: app/src/main/java/com/marcohc/architecture/app/domain/model/UserModel.java
// public class UserModel implements Model {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserModel() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/story/user/userdetail/view/UserDetailActivity.java
// public class UserDetailActivity extends BaseMvpActivity<UserDetailView, UserDetailPresenter> implements UserDetailView {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @BindView(R.id.toolbar)
// Toolbar mToolbar;
//
// @BindView(R.id.userImageView)
// ImageView mUserImageView;
//
// @BindView(R.id.usernameTextView)
// TextView mUsernameTextView;
//
// @BindView(R.id.emailTextView)
// TextView mEmailTextView;
//
// // ************************************************************************************************************************************************************************
// // * Initialization methods
// // ************************************************************************************************************************************************************************
//
// @NonNull
// @Override
// public UserDetailPresenter createPresenter() {
// return new UserDetailPresenterImpl();
// }
//
// @Override
// protected int getLayoutId() {
// return R.layout.activity_user_detail;
// }
//
// @Override
// protected void onViewCreated(@Nullable Bundle savedInstanceState) {
// setUpActionBar();
// setUpUserData();
// }
//
// private void setUpActionBar() {
// setSupportActionBar(mToolbar);
// ActionBar actionBar = getSupportActionBar();
// if (actionBar != null) {
// actionBar.setTitle(R.string.user_detail);
// actionBar.setDisplayHomeAsUpEnabled(true);
// actionBar.setHomeButtonEnabled(true);
// }
// }
//
// private void setUpUserData() {
// presenter.onViewCreated(this);
// }
//
// // ************************************************************************************************************************************************************************
// // * Event handler methods
// // ************************************************************************************************************************************************************************
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// onBackPressed();
// return true;
// }
//
// @OnClick(R.id.userImageView)
// protected void onUserImageClick() {
// }
//
// // ************************************************************************************************************************************************************************
// // * View interface methods
// // ************************************************************************************************************************************************************************
//
// @Override
// public void renderModel(@NonNull UserModel model) {
// String image = model.getPictureUrl();
// if (!StringUtils.isBlank(image)) {
// Glide.with(this).load(image).error(R.drawable.im_user_place_holder).into(mUserImageView);
// } else {
// mUserImageView.setImageResource(R.drawable.im_user_place_holder);
// }
// mUsernameTextView.setText(model.getName());
// mEmailTextView.setText(model.getEmail());
// }
//
// // ************************************************************************************************************************************************************************
// // * UI methods
// // ************************************************************************************************************************************************************************
//
//
// }
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/navigation/Navigator.java
import android.content.Context;
import android.content.Intent;
import com.marcohc.architecture.app.domain.model.UserModel;
import com.marcohc.architecture.app.presentation.story.user.userdetail.view.UserDetailActivity;
package com.marcohc.architecture.app.presentation.navigation;
/**
* Manages the navigation between activities.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public final class Navigator {
// ************************************************************************************************************************************************************************
// * Constants
// ************************************************************************************************************************************************************************
public static final String USER = "user";
// ************************************************************************************************************************************************************************
// * Constructors
// ************************************************************************************************************************************************************************
private Navigator() {
}
// ************************************************************************************************************************************************************************
// * Navigation methods
// ************************************************************************************************************************************************************************
/**
* Go to {@link UserDetailActivity}.
*
* @param context the context
* @param model the UserModel to be displayed in the details
*/ | public static void goToUserDetail(Context context, UserModel model) { |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/presentation/navigation/Navigator.java | // Path: app/src/main/java/com/marcohc/architecture/app/domain/model/UserModel.java
// public class UserModel implements Model {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserModel() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/story/user/userdetail/view/UserDetailActivity.java
// public class UserDetailActivity extends BaseMvpActivity<UserDetailView, UserDetailPresenter> implements UserDetailView {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @BindView(R.id.toolbar)
// Toolbar mToolbar;
//
// @BindView(R.id.userImageView)
// ImageView mUserImageView;
//
// @BindView(R.id.usernameTextView)
// TextView mUsernameTextView;
//
// @BindView(R.id.emailTextView)
// TextView mEmailTextView;
//
// // ************************************************************************************************************************************************************************
// // * Initialization methods
// // ************************************************************************************************************************************************************************
//
// @NonNull
// @Override
// public UserDetailPresenter createPresenter() {
// return new UserDetailPresenterImpl();
// }
//
// @Override
// protected int getLayoutId() {
// return R.layout.activity_user_detail;
// }
//
// @Override
// protected void onViewCreated(@Nullable Bundle savedInstanceState) {
// setUpActionBar();
// setUpUserData();
// }
//
// private void setUpActionBar() {
// setSupportActionBar(mToolbar);
// ActionBar actionBar = getSupportActionBar();
// if (actionBar != null) {
// actionBar.setTitle(R.string.user_detail);
// actionBar.setDisplayHomeAsUpEnabled(true);
// actionBar.setHomeButtonEnabled(true);
// }
// }
//
// private void setUpUserData() {
// presenter.onViewCreated(this);
// }
//
// // ************************************************************************************************************************************************************************
// // * Event handler methods
// // ************************************************************************************************************************************************************************
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// onBackPressed();
// return true;
// }
//
// @OnClick(R.id.userImageView)
// protected void onUserImageClick() {
// }
//
// // ************************************************************************************************************************************************************************
// // * View interface methods
// // ************************************************************************************************************************************************************************
//
// @Override
// public void renderModel(@NonNull UserModel model) {
// String image = model.getPictureUrl();
// if (!StringUtils.isBlank(image)) {
// Glide.with(this).load(image).error(R.drawable.im_user_place_holder).into(mUserImageView);
// } else {
// mUserImageView.setImageResource(R.drawable.im_user_place_holder);
// }
// mUsernameTextView.setText(model.getName());
// mEmailTextView.setText(model.getEmail());
// }
//
// // ************************************************************************************************************************************************************************
// // * UI methods
// // ************************************************************************************************************************************************************************
//
//
// }
| import android.content.Context;
import android.content.Intent;
import com.marcohc.architecture.app.domain.model.UserModel;
import com.marcohc.architecture.app.presentation.story.user.userdetail.view.UserDetailActivity; | package com.marcohc.architecture.app.presentation.navigation;
/**
* Manages the navigation between activities.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public final class Navigator {
// ************************************************************************************************************************************************************************
// * Constants
// ************************************************************************************************************************************************************************
public static final String USER = "user";
// ************************************************************************************************************************************************************************
// * Constructors
// ************************************************************************************************************************************************************************
private Navigator() {
}
// ************************************************************************************************************************************************************************
// * Navigation methods
// ************************************************************************************************************************************************************************
/**
* Go to {@link UserDetailActivity}.
*
* @param context the context
* @param model the UserModel to be displayed in the details
*/
public static void goToUserDetail(Context context, UserModel model) {
if (context != null && model != null) { | // Path: app/src/main/java/com/marcohc/architecture/app/domain/model/UserModel.java
// public class UserModel implements Model {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserModel() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/story/user/userdetail/view/UserDetailActivity.java
// public class UserDetailActivity extends BaseMvpActivity<UserDetailView, UserDetailPresenter> implements UserDetailView {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @BindView(R.id.toolbar)
// Toolbar mToolbar;
//
// @BindView(R.id.userImageView)
// ImageView mUserImageView;
//
// @BindView(R.id.usernameTextView)
// TextView mUsernameTextView;
//
// @BindView(R.id.emailTextView)
// TextView mEmailTextView;
//
// // ************************************************************************************************************************************************************************
// // * Initialization methods
// // ************************************************************************************************************************************************************************
//
// @NonNull
// @Override
// public UserDetailPresenter createPresenter() {
// return new UserDetailPresenterImpl();
// }
//
// @Override
// protected int getLayoutId() {
// return R.layout.activity_user_detail;
// }
//
// @Override
// protected void onViewCreated(@Nullable Bundle savedInstanceState) {
// setUpActionBar();
// setUpUserData();
// }
//
// private void setUpActionBar() {
// setSupportActionBar(mToolbar);
// ActionBar actionBar = getSupportActionBar();
// if (actionBar != null) {
// actionBar.setTitle(R.string.user_detail);
// actionBar.setDisplayHomeAsUpEnabled(true);
// actionBar.setHomeButtonEnabled(true);
// }
// }
//
// private void setUpUserData() {
// presenter.onViewCreated(this);
// }
//
// // ************************************************************************************************************************************************************************
// // * Event handler methods
// // ************************************************************************************************************************************************************************
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// onBackPressed();
// return true;
// }
//
// @OnClick(R.id.userImageView)
// protected void onUserImageClick() {
// }
//
// // ************************************************************************************************************************************************************************
// // * View interface methods
// // ************************************************************************************************************************************************************************
//
// @Override
// public void renderModel(@NonNull UserModel model) {
// String image = model.getPictureUrl();
// if (!StringUtils.isBlank(image)) {
// Glide.with(this).load(image).error(R.drawable.im_user_place_holder).into(mUserImageView);
// } else {
// mUserImageView.setImageResource(R.drawable.im_user_place_holder);
// }
// mUsernameTextView.setText(model.getName());
// mEmailTextView.setText(model.getEmail());
// }
//
// // ************************************************************************************************************************************************************************
// // * UI methods
// // ************************************************************************************************************************************************************************
//
//
// }
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/navigation/Navigator.java
import android.content.Context;
import android.content.Intent;
import com.marcohc.architecture.app.domain.model.UserModel;
import com.marcohc.architecture.app.presentation.story.user.userdetail.view.UserDetailActivity;
package com.marcohc.architecture.app.presentation.navigation;
/**
* Manages the navigation between activities.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public final class Navigator {
// ************************************************************************************************************************************************************************
// * Constants
// ************************************************************************************************************************************************************************
public static final String USER = "user";
// ************************************************************************************************************************************************************************
// * Constructors
// ************************************************************************************************************************************************************************
private Navigator() {
}
// ************************************************************************************************************************************************************************
// * Navigation methods
// ************************************************************************************************************************************************************************
/**
* Go to {@link UserDetailActivity}.
*
* @param context the context
* @param model the UserModel to be displayed in the details
*/
public static void goToUserDetail(Context context, UserModel model) {
if (context != null && model != null) { | Intent intent = new Intent(context, UserDetailActivity.class); |
marcohc/android-clean-architecture | common/src/main/java/com/marcohc/architecture/common/util/helper/StringUtils.java | // Path: common/src/main/java/com/marcohc/architecture/common/util/utils/Preconditions.java
// public final class Preconditions {
//
// private Preconditions() {
// // no-op
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @param name the variable name
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference, String name) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException(name + " must not be null.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @param name the variable name
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression, @Nullable String name) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be false.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures not blank in parameters.
// *
// * @param value the value to check
// * @param name the name you want to display in the logs
// * @param <T> the type of the value
// * @return the value you want to check
// */
// @NonNull
// public static <T extends CharSequence> T nonBlank(@Nullable T value, String name) {
// if (StringUtils.isBlank(value)) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be blank.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return value;
// }
//
// @NonNull
// private static StackTraceElement[] getStackTrace(@NonNull Exception exception) {
// final StackTraceElement[] sourceStack = exception.getStackTrace();
//
// final StackTraceElement[] updatedStack = new StackTraceElement[sourceStack.length - 1];
// System.arraycopy(sourceStack, 1, updatedStack, 0, updatedStack.length);
//
// return updatedStack;
// }
// }
| import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.marcohc.architecture.common.util.utils.Preconditions;
import java.util.regex.Pattern; | package com.marcohc.architecture.common.util.helper;
public final class StringUtils {
private static final String EMAIL_PATTERN = "^[\\w!#$%&'*+/=?`{|}~^-]+(?:\\.[\\w!#$%&'*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$";
private static Pattern pattern;
private StringUtils() {
}
/**
* Validate hex with regular expression
*
* @param email hex for validation
* @return true valid hex, false invalid hex
*/
public static boolean isEmailValid(@NonNull final String email) { | // Path: common/src/main/java/com/marcohc/architecture/common/util/utils/Preconditions.java
// public final class Preconditions {
//
// private Preconditions() {
// // no-op
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @param name the variable name
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference, String name) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException(name + " must not be null.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @param name the variable name
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression, @Nullable String name) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be false.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures not blank in parameters.
// *
// * @param value the value to check
// * @param name the name you want to display in the logs
// * @param <T> the type of the value
// * @return the value you want to check
// */
// @NonNull
// public static <T extends CharSequence> T nonBlank(@Nullable T value, String name) {
// if (StringUtils.isBlank(value)) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be blank.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return value;
// }
//
// @NonNull
// private static StackTraceElement[] getStackTrace(@NonNull Exception exception) {
// final StackTraceElement[] sourceStack = exception.getStackTrace();
//
// final StackTraceElement[] updatedStack = new StackTraceElement[sourceStack.length - 1];
// System.arraycopy(sourceStack, 1, updatedStack, 0, updatedStack.length);
//
// return updatedStack;
// }
// }
// Path: common/src/main/java/com/marcohc/architecture/common/util/helper/StringUtils.java
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.marcohc.architecture.common.util.utils.Preconditions;
import java.util.regex.Pattern;
package com.marcohc.architecture.common.util.helper;
public final class StringUtils {
private static final String EMAIL_PATTERN = "^[\\w!#$%&'*+/=?`{|}~^-]+(?:\\.[\\w!#$%&'*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$";
private static Pattern pattern;
private StringUtils() {
}
/**
* Validate hex with regular expression
*
* @param email hex for validation
* @return true valid hex, false invalid hex
*/
public static boolean isEmailValid(@NonNull final String email) { | Preconditions.checkNotNull(email, "email"); |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/internal/di/ApplicationComponent.java | // Path: app/src/main/java/com/marcohc/architecture/app/data/cache/UserCache.java
// public final class UserCache implements DataCache<List<UserEntity>> {
//
// private static final long CACHE_EXPIRATION_TIME = 3600 * 1000;
// private static final String CACHE_NAME = UserCache.class.getSimpleName() + BuildConfig.VERSION_NAME;
// private static final int TEST_APP_VERSION = BuildConfig.VERSION_CODE;
// private static final int RAM_MAX_SIZE = 1024 * 1024 * 512;
// private static UserCache sInstance;
// private final DualCache<String> mCache;
//
// private UserCache() {
// ApplicationInjector.getApplicationComponent().inject(this);
// CacheSerializer<String> jsonSerializer = new JsonSerializer<>(String.class);
// mCache = new Builder<String>(CACHE_NAME, TEST_APP_VERSION)
// .useSerializerInRam(RAM_MAX_SIZE, jsonSerializer)
// .useSerializerInDisk(RAM_MAX_SIZE, true, jsonSerializer, ApplicationInjector.getApplicationComponent().provideContext())
// .build();
// }
//
// /**
// * Get singleton instance.
// *
// * @return UserCache
// */
// public synchronized static UserCache getInstance() {
// if (sInstance == null) {
// sInstance = new UserCache();
// }
// return sInstance;
// }
//
// @Override
// public void clear() {
// mCache.invalidate();
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public List<UserEntity> get(String key) {
// String jsonStored = mCache.get(key);
// return Parser.parseCollection(jsonStored, new GenericCollection<>(List.class, UserEntity.class));
// }
//
// @Override
// public boolean isCached(String key) {
//
// if (StringUtils.isBlank(key)) {
// Timber.e("isCached: key is null!");
// return false;
// }
//
// if (mCache.get(key) != null) {
// Timber.v("isCached: true");
// return true;
// } else {
// Timber.v("isCached: false");
// return false;
// }
// }
//
// @Override
// public boolean isValid(String key) {
//
// if (StringUtils.isBlank(key)) {
// Timber.e("isValid: key is null!");
// return false;
// }
//
// String jsonStored = mCache.get(key);
// Long timeStored = null;
// try {
// timeStored = Long.valueOf(mCache.get(getTimeToken(key)));
// } catch (NumberFormatException e) {
// Timber.e("isValid: timeStored is not a Long!");
// }
//
// boolean isValid = false;
// if (jsonStored != null && timeStored != null) {
// Timber.v("isValid: is stored");
//
// if (((System.currentTimeMillis() - timeStored) < CACHE_EXPIRATION_TIME)) {
// Timber.v("isValid: true");
// isValid = true;
// } else {
// Timber.v("isValid: is expired");
// }
// } else {
// Timber.v("isValid: false");
// }
//
// Timber.v("isValid: %s", isValid);
// return isValid;
// }
//
// @Override
// public void put(String key, List<UserEntity> item) {
//
// if (StringUtils.isBlank(key)) {
// Timber.e("put: key is null!");
// return;
// }
//
// mCache.put(key, Parser.toJsonString(item));
// mCache.put(getTimeToken(key), String.valueOf(System.currentTimeMillis()));
// }
//
// @Override
// public void remove(String key) {
//
// if (StringUtils.isBlank(key)) {
// Timber.e("remove: key is null!");
// return;
// }
//
// mCache.delete(key);
// mCache.delete(getTimeToken(key));
// }
//
// private String getTimeToken(String key) {
// return key + "_timestamp";
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/repository/user/UserRepository.java
// public interface UserRepository {
//
// /**
// * Get all users with picture based on parameters.
// *
// * @param useCache use the cache
// * @return the Observable with a list of users
// */
// Observable<List<UserEntity>> getAllWithPicture(boolean useCache);
//
// /**
// * Get all users without picture based on parameters.
// *
// * @param useCache use the cache
// * @return the Observable with a list of users
// */
// Observable<List<UserEntity>> getAllWithoutPicture(boolean useCache);
//
// }
| import android.content.Context;
import com.marcohc.architecture.app.data.cache.UserCache;
import com.marcohc.architecture.app.data.repository.user.UserRepository;
import javax.inject.Singleton;
import dagger.Component; | package com.marcohc.architecture.app.internal.di;
/**
* Dagger component.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
@Singleton
@PerApplication
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
/**
* Injects the cache.
*
* @param cache
*/ | // Path: app/src/main/java/com/marcohc/architecture/app/data/cache/UserCache.java
// public final class UserCache implements DataCache<List<UserEntity>> {
//
// private static final long CACHE_EXPIRATION_TIME = 3600 * 1000;
// private static final String CACHE_NAME = UserCache.class.getSimpleName() + BuildConfig.VERSION_NAME;
// private static final int TEST_APP_VERSION = BuildConfig.VERSION_CODE;
// private static final int RAM_MAX_SIZE = 1024 * 1024 * 512;
// private static UserCache sInstance;
// private final DualCache<String> mCache;
//
// private UserCache() {
// ApplicationInjector.getApplicationComponent().inject(this);
// CacheSerializer<String> jsonSerializer = new JsonSerializer<>(String.class);
// mCache = new Builder<String>(CACHE_NAME, TEST_APP_VERSION)
// .useSerializerInRam(RAM_MAX_SIZE, jsonSerializer)
// .useSerializerInDisk(RAM_MAX_SIZE, true, jsonSerializer, ApplicationInjector.getApplicationComponent().provideContext())
// .build();
// }
//
// /**
// * Get singleton instance.
// *
// * @return UserCache
// */
// public synchronized static UserCache getInstance() {
// if (sInstance == null) {
// sInstance = new UserCache();
// }
// return sInstance;
// }
//
// @Override
// public void clear() {
// mCache.invalidate();
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public List<UserEntity> get(String key) {
// String jsonStored = mCache.get(key);
// return Parser.parseCollection(jsonStored, new GenericCollection<>(List.class, UserEntity.class));
// }
//
// @Override
// public boolean isCached(String key) {
//
// if (StringUtils.isBlank(key)) {
// Timber.e("isCached: key is null!");
// return false;
// }
//
// if (mCache.get(key) != null) {
// Timber.v("isCached: true");
// return true;
// } else {
// Timber.v("isCached: false");
// return false;
// }
// }
//
// @Override
// public boolean isValid(String key) {
//
// if (StringUtils.isBlank(key)) {
// Timber.e("isValid: key is null!");
// return false;
// }
//
// String jsonStored = mCache.get(key);
// Long timeStored = null;
// try {
// timeStored = Long.valueOf(mCache.get(getTimeToken(key)));
// } catch (NumberFormatException e) {
// Timber.e("isValid: timeStored is not a Long!");
// }
//
// boolean isValid = false;
// if (jsonStored != null && timeStored != null) {
// Timber.v("isValid: is stored");
//
// if (((System.currentTimeMillis() - timeStored) < CACHE_EXPIRATION_TIME)) {
// Timber.v("isValid: true");
// isValid = true;
// } else {
// Timber.v("isValid: is expired");
// }
// } else {
// Timber.v("isValid: false");
// }
//
// Timber.v("isValid: %s", isValid);
// return isValid;
// }
//
// @Override
// public void put(String key, List<UserEntity> item) {
//
// if (StringUtils.isBlank(key)) {
// Timber.e("put: key is null!");
// return;
// }
//
// mCache.put(key, Parser.toJsonString(item));
// mCache.put(getTimeToken(key), String.valueOf(System.currentTimeMillis()));
// }
//
// @Override
// public void remove(String key) {
//
// if (StringUtils.isBlank(key)) {
// Timber.e("remove: key is null!");
// return;
// }
//
// mCache.delete(key);
// mCache.delete(getTimeToken(key));
// }
//
// private String getTimeToken(String key) {
// return key + "_timestamp";
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/repository/user/UserRepository.java
// public interface UserRepository {
//
// /**
// * Get all users with picture based on parameters.
// *
// * @param useCache use the cache
// * @return the Observable with a list of users
// */
// Observable<List<UserEntity>> getAllWithPicture(boolean useCache);
//
// /**
// * Get all users without picture based on parameters.
// *
// * @param useCache use the cache
// * @return the Observable with a list of users
// */
// Observable<List<UserEntity>> getAllWithoutPicture(boolean useCache);
//
// }
// Path: app/src/main/java/com/marcohc/architecture/app/internal/di/ApplicationComponent.java
import android.content.Context;
import com.marcohc.architecture.app.data.cache.UserCache;
import com.marcohc.architecture.app.data.repository.user.UserRepository;
import javax.inject.Singleton;
import dagger.Component;
package com.marcohc.architecture.app.internal.di;
/**
* Dagger component.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
@Singleton
@PerApplication
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
/**
* Injects the cache.
*
* @param cache
*/ | void inject(UserCache cache); |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/internal/di/ApplicationComponent.java | // Path: app/src/main/java/com/marcohc/architecture/app/data/cache/UserCache.java
// public final class UserCache implements DataCache<List<UserEntity>> {
//
// private static final long CACHE_EXPIRATION_TIME = 3600 * 1000;
// private static final String CACHE_NAME = UserCache.class.getSimpleName() + BuildConfig.VERSION_NAME;
// private static final int TEST_APP_VERSION = BuildConfig.VERSION_CODE;
// private static final int RAM_MAX_SIZE = 1024 * 1024 * 512;
// private static UserCache sInstance;
// private final DualCache<String> mCache;
//
// private UserCache() {
// ApplicationInjector.getApplicationComponent().inject(this);
// CacheSerializer<String> jsonSerializer = new JsonSerializer<>(String.class);
// mCache = new Builder<String>(CACHE_NAME, TEST_APP_VERSION)
// .useSerializerInRam(RAM_MAX_SIZE, jsonSerializer)
// .useSerializerInDisk(RAM_MAX_SIZE, true, jsonSerializer, ApplicationInjector.getApplicationComponent().provideContext())
// .build();
// }
//
// /**
// * Get singleton instance.
// *
// * @return UserCache
// */
// public synchronized static UserCache getInstance() {
// if (sInstance == null) {
// sInstance = new UserCache();
// }
// return sInstance;
// }
//
// @Override
// public void clear() {
// mCache.invalidate();
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public List<UserEntity> get(String key) {
// String jsonStored = mCache.get(key);
// return Parser.parseCollection(jsonStored, new GenericCollection<>(List.class, UserEntity.class));
// }
//
// @Override
// public boolean isCached(String key) {
//
// if (StringUtils.isBlank(key)) {
// Timber.e("isCached: key is null!");
// return false;
// }
//
// if (mCache.get(key) != null) {
// Timber.v("isCached: true");
// return true;
// } else {
// Timber.v("isCached: false");
// return false;
// }
// }
//
// @Override
// public boolean isValid(String key) {
//
// if (StringUtils.isBlank(key)) {
// Timber.e("isValid: key is null!");
// return false;
// }
//
// String jsonStored = mCache.get(key);
// Long timeStored = null;
// try {
// timeStored = Long.valueOf(mCache.get(getTimeToken(key)));
// } catch (NumberFormatException e) {
// Timber.e("isValid: timeStored is not a Long!");
// }
//
// boolean isValid = false;
// if (jsonStored != null && timeStored != null) {
// Timber.v("isValid: is stored");
//
// if (((System.currentTimeMillis() - timeStored) < CACHE_EXPIRATION_TIME)) {
// Timber.v("isValid: true");
// isValid = true;
// } else {
// Timber.v("isValid: is expired");
// }
// } else {
// Timber.v("isValid: false");
// }
//
// Timber.v("isValid: %s", isValid);
// return isValid;
// }
//
// @Override
// public void put(String key, List<UserEntity> item) {
//
// if (StringUtils.isBlank(key)) {
// Timber.e("put: key is null!");
// return;
// }
//
// mCache.put(key, Parser.toJsonString(item));
// mCache.put(getTimeToken(key), String.valueOf(System.currentTimeMillis()));
// }
//
// @Override
// public void remove(String key) {
//
// if (StringUtils.isBlank(key)) {
// Timber.e("remove: key is null!");
// return;
// }
//
// mCache.delete(key);
// mCache.delete(getTimeToken(key));
// }
//
// private String getTimeToken(String key) {
// return key + "_timestamp";
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/repository/user/UserRepository.java
// public interface UserRepository {
//
// /**
// * Get all users with picture based on parameters.
// *
// * @param useCache use the cache
// * @return the Observable with a list of users
// */
// Observable<List<UserEntity>> getAllWithPicture(boolean useCache);
//
// /**
// * Get all users without picture based on parameters.
// *
// * @param useCache use the cache
// * @return the Observable with a list of users
// */
// Observable<List<UserEntity>> getAllWithoutPicture(boolean useCache);
//
// }
| import android.content.Context;
import com.marcohc.architecture.app.data.cache.UserCache;
import com.marcohc.architecture.app.data.repository.user.UserRepository;
import javax.inject.Singleton;
import dagger.Component; | package com.marcohc.architecture.app.internal.di;
/**
* Dagger component.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
@Singleton
@PerApplication
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
/**
* Injects the cache.
*
* @param cache
*/
void inject(UserCache cache);
// void inject(GetUsersUseCase useCase);
/**
* Provides the context.
* @return Context
*/
Context provideContext();
/**
* Provides the repository.
* @return UserRepository
*/ | // Path: app/src/main/java/com/marcohc/architecture/app/data/cache/UserCache.java
// public final class UserCache implements DataCache<List<UserEntity>> {
//
// private static final long CACHE_EXPIRATION_TIME = 3600 * 1000;
// private static final String CACHE_NAME = UserCache.class.getSimpleName() + BuildConfig.VERSION_NAME;
// private static final int TEST_APP_VERSION = BuildConfig.VERSION_CODE;
// private static final int RAM_MAX_SIZE = 1024 * 1024 * 512;
// private static UserCache sInstance;
// private final DualCache<String> mCache;
//
// private UserCache() {
// ApplicationInjector.getApplicationComponent().inject(this);
// CacheSerializer<String> jsonSerializer = new JsonSerializer<>(String.class);
// mCache = new Builder<String>(CACHE_NAME, TEST_APP_VERSION)
// .useSerializerInRam(RAM_MAX_SIZE, jsonSerializer)
// .useSerializerInDisk(RAM_MAX_SIZE, true, jsonSerializer, ApplicationInjector.getApplicationComponent().provideContext())
// .build();
// }
//
// /**
// * Get singleton instance.
// *
// * @return UserCache
// */
// public synchronized static UserCache getInstance() {
// if (sInstance == null) {
// sInstance = new UserCache();
// }
// return sInstance;
// }
//
// @Override
// public void clear() {
// mCache.invalidate();
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public List<UserEntity> get(String key) {
// String jsonStored = mCache.get(key);
// return Parser.parseCollection(jsonStored, new GenericCollection<>(List.class, UserEntity.class));
// }
//
// @Override
// public boolean isCached(String key) {
//
// if (StringUtils.isBlank(key)) {
// Timber.e("isCached: key is null!");
// return false;
// }
//
// if (mCache.get(key) != null) {
// Timber.v("isCached: true");
// return true;
// } else {
// Timber.v("isCached: false");
// return false;
// }
// }
//
// @Override
// public boolean isValid(String key) {
//
// if (StringUtils.isBlank(key)) {
// Timber.e("isValid: key is null!");
// return false;
// }
//
// String jsonStored = mCache.get(key);
// Long timeStored = null;
// try {
// timeStored = Long.valueOf(mCache.get(getTimeToken(key)));
// } catch (NumberFormatException e) {
// Timber.e("isValid: timeStored is not a Long!");
// }
//
// boolean isValid = false;
// if (jsonStored != null && timeStored != null) {
// Timber.v("isValid: is stored");
//
// if (((System.currentTimeMillis() - timeStored) < CACHE_EXPIRATION_TIME)) {
// Timber.v("isValid: true");
// isValid = true;
// } else {
// Timber.v("isValid: is expired");
// }
// } else {
// Timber.v("isValid: false");
// }
//
// Timber.v("isValid: %s", isValid);
// return isValid;
// }
//
// @Override
// public void put(String key, List<UserEntity> item) {
//
// if (StringUtils.isBlank(key)) {
// Timber.e("put: key is null!");
// return;
// }
//
// mCache.put(key, Parser.toJsonString(item));
// mCache.put(getTimeToken(key), String.valueOf(System.currentTimeMillis()));
// }
//
// @Override
// public void remove(String key) {
//
// if (StringUtils.isBlank(key)) {
// Timber.e("remove: key is null!");
// return;
// }
//
// mCache.delete(key);
// mCache.delete(getTimeToken(key));
// }
//
// private String getTimeToken(String key) {
// return key + "_timestamp";
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/repository/user/UserRepository.java
// public interface UserRepository {
//
// /**
// * Get all users with picture based on parameters.
// *
// * @param useCache use the cache
// * @return the Observable with a list of users
// */
// Observable<List<UserEntity>> getAllWithPicture(boolean useCache);
//
// /**
// * Get all users without picture based on parameters.
// *
// * @param useCache use the cache
// * @return the Observable with a list of users
// */
// Observable<List<UserEntity>> getAllWithoutPicture(boolean useCache);
//
// }
// Path: app/src/main/java/com/marcohc/architecture/app/internal/di/ApplicationComponent.java
import android.content.Context;
import com.marcohc.architecture.app.data.cache.UserCache;
import com.marcohc.architecture.app.data.repository.user.UserRepository;
import javax.inject.Singleton;
import dagger.Component;
package com.marcohc.architecture.app.internal.di;
/**
* Dagger component.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
@Singleton
@PerApplication
@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
/**
* Injects the cache.
*
* @param cache
*/
void inject(UserCache cache);
// void inject(GetUsersUseCase useCase);
/**
* Provides the context.
* @return Context
*/
Context provideContext();
/**
* Provides the repository.
* @return UserRepository
*/ | UserRepository provideRepository(); |
marcohc/android-clean-architecture | util/src/main/java/com/marcohc/architecture/common/util/ImageUtils.java | // Path: common/src/main/java/com/marcohc/architecture/common/util/utils/Preconditions.java
// public final class Preconditions {
//
// private Preconditions() {
// // no-op
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @param name the variable name
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference, String name) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException(name + " must not be null.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @param name the variable name
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression, @Nullable String name) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be false.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures not blank in parameters.
// *
// * @param value the value to check
// * @param name the name you want to display in the logs
// * @param <T> the type of the value
// * @return the value you want to check
// */
// @NonNull
// public static <T extends CharSequence> T nonBlank(@Nullable T value, String name) {
// if (StringUtils.isBlank(value)) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be blank.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return value;
// }
//
// @NonNull
// private static StackTraceElement[] getStackTrace(@NonNull Exception exception) {
// final StackTraceElement[] sourceStack = exception.getStackTrace();
//
// final StackTraceElement[] updatedStack = new StackTraceElement[sourceStack.length - 1];
// System.arraycopy(sourceStack, 1, updatedStack, 0, updatedStack.length);
//
// return updatedStack;
// }
// }
| import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Base64;
import com.marcohc.architecture.common.util.utils.Preconditions;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import timber.log.Timber; | /*
* Copyright (C) 2015 Marco Hernaiz Cao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marcohc.architecture.common.util;
public class ImageUtils {
public static final int SELECT_PICTURE_FROM_GALLERY_REQUEST = 10;
public static final int CAMERA_REQUEST = 20;
public static final int NINETEEN = 19;
public static int IMAGE_MAX_WIDTH = 1080;
public static int IMAGE_MAX_HEIGHT = 720;
public static void showPickUpPictureDialog(@NonNull final Activity activity, @NonNull final Uri fileUri) { | // Path: common/src/main/java/com/marcohc/architecture/common/util/utils/Preconditions.java
// public final class Preconditions {
//
// private Preconditions() {
// // no-op
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @param name the variable name
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference, String name) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException(name + " must not be null.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @param name the variable name
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression, @Nullable String name) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be false.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures not blank in parameters.
// *
// * @param value the value to check
// * @param name the name you want to display in the logs
// * @param <T> the type of the value
// * @return the value you want to check
// */
// @NonNull
// public static <T extends CharSequence> T nonBlank(@Nullable T value, String name) {
// if (StringUtils.isBlank(value)) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be blank.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return value;
// }
//
// @NonNull
// private static StackTraceElement[] getStackTrace(@NonNull Exception exception) {
// final StackTraceElement[] sourceStack = exception.getStackTrace();
//
// final StackTraceElement[] updatedStack = new StackTraceElement[sourceStack.length - 1];
// System.arraycopy(sourceStack, 1, updatedStack, 0, updatedStack.length);
//
// return updatedStack;
// }
// }
// Path: util/src/main/java/com/marcohc/architecture/common/util/ImageUtils.java
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Base64;
import com.marcohc.architecture.common.util.utils.Preconditions;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import timber.log.Timber;
/*
* Copyright (C) 2015 Marco Hernaiz Cao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marcohc.architecture.common.util;
public class ImageUtils {
public static final int SELECT_PICTURE_FROM_GALLERY_REQUEST = 10;
public static final int CAMERA_REQUEST = 20;
public static final int NINETEEN = 19;
public static int IMAGE_MAX_WIDTH = 1080;
public static int IMAGE_MAX_HEIGHT = 720;
public static void showPickUpPictureDialog(@NonNull final Activity activity, @NonNull final Uri fileUri) { | Preconditions.checkNotNull(activity); |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/MainApplication.java | // Path: app/src/main/java/com/marcohc/architecture/app/internal/di/ApplicationInjector.java
// public final class ApplicationInjector {
//
// private static ApplicationComponent sApplicationComponent;
//
// private ApplicationInjector() {
// }
//
// /**
// * Inject the context.
// *
// * @param context
// */
// public static void inject(Context context) {
// sApplicationComponent = DaggerApplicationComponent.builder()
// .applicationModule(new ApplicationModule(context))
// .build();
// }
//
// public static ApplicationComponent getApplicationComponent() {
// return sApplicationComponent;
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/util/BuildConfigUtils.java
// public class BuildConfigUtils extends BaseBuildConfigUtils {
//
// private static BuildConfigUtils instance;
//
// private BuildConfigUtils(String buildType) {
// super(buildType);
// }
//
// public static BuildConfigUtils getInstance() {
// if (instance == null) {
// instance = new BuildConfigUtils(BuildConfig.BUILD_TYPE);
// }
// return instance;
// }
// }
//
// Path: util/src/main/java/com/marcohc/architecture/common/util/TimerUtils.java
// public class TimerUtils {
//
// private long stepTime;
// private long totalTime;
// private int stepNumber;
// private String tag;
//
// public static TimerUtils getInstance(String tag) {
// return new TimerUtils(tag);
// }
//
// private TimerUtils(String tag) {
// this.tag = tag;
// stepNumber = 1;
// stepTime = System.currentTimeMillis();
// totalTime = System.currentTimeMillis();
// }
//
// /**
// * Prints a log with the step time.
// *
// * @return the step time
// */
// public Long logStep() {
// Long difference = System.currentTimeMillis() - stepTime;
// Timber.d("%s - Step %d: %d", tag, stepNumber++, difference);
// stepTime = System.currentTimeMillis();
// return difference;
// }
//
// /**
// * Prints a log with the step time.
// *
// * @param subTag sub tag used in the log
// * @return the step time
// */
// public Long logStep(String subTag) {
// Long difference = System.currentTimeMillis() - stepTime;
// Timber.d("%s (%s) - Step %d: %d", android.R.attr.tag, subTag, stepNumber++, difference);
// stepTime = System.currentTimeMillis();
// return difference;
// }
//
// /**
// * Prints a log with the total time.
// *
// * @return the total time
// */
// public Long logTotal() {
// Long difference = System.currentTimeMillis() - totalTime;
// Timber.d("%s - TOTAL: %d", tag, difference);
// return difference;
// }
// }
| import android.annotation.SuppressLint;
import android.os.StrictMode;
import com.marcohc.architecture.app.internal.di.ApplicationInjector;
import com.marcohc.architecture.app.presentation.util.BuildConfigUtils;
import com.marcohc.architecture.common.util.TimerUtils;
import com.squareup.leakcanary.LeakCanary;
import cat.ereza.customactivityoncrash.CustomActivityOnCrash;
import timber.log.Timber;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig; | package com.marcohc.architecture.app;
@SuppressLint({ "SimpleDateFormat", "DefaultLocale" })
public class MainApplication extends android.app.Application {
@Override
public void onCreate() {
super.onCreate();
| // Path: app/src/main/java/com/marcohc/architecture/app/internal/di/ApplicationInjector.java
// public final class ApplicationInjector {
//
// private static ApplicationComponent sApplicationComponent;
//
// private ApplicationInjector() {
// }
//
// /**
// * Inject the context.
// *
// * @param context
// */
// public static void inject(Context context) {
// sApplicationComponent = DaggerApplicationComponent.builder()
// .applicationModule(new ApplicationModule(context))
// .build();
// }
//
// public static ApplicationComponent getApplicationComponent() {
// return sApplicationComponent;
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/util/BuildConfigUtils.java
// public class BuildConfigUtils extends BaseBuildConfigUtils {
//
// private static BuildConfigUtils instance;
//
// private BuildConfigUtils(String buildType) {
// super(buildType);
// }
//
// public static BuildConfigUtils getInstance() {
// if (instance == null) {
// instance = new BuildConfigUtils(BuildConfig.BUILD_TYPE);
// }
// return instance;
// }
// }
//
// Path: util/src/main/java/com/marcohc/architecture/common/util/TimerUtils.java
// public class TimerUtils {
//
// private long stepTime;
// private long totalTime;
// private int stepNumber;
// private String tag;
//
// public static TimerUtils getInstance(String tag) {
// return new TimerUtils(tag);
// }
//
// private TimerUtils(String tag) {
// this.tag = tag;
// stepNumber = 1;
// stepTime = System.currentTimeMillis();
// totalTime = System.currentTimeMillis();
// }
//
// /**
// * Prints a log with the step time.
// *
// * @return the step time
// */
// public Long logStep() {
// Long difference = System.currentTimeMillis() - stepTime;
// Timber.d("%s - Step %d: %d", tag, stepNumber++, difference);
// stepTime = System.currentTimeMillis();
// return difference;
// }
//
// /**
// * Prints a log with the step time.
// *
// * @param subTag sub tag used in the log
// * @return the step time
// */
// public Long logStep(String subTag) {
// Long difference = System.currentTimeMillis() - stepTime;
// Timber.d("%s (%s) - Step %d: %d", android.R.attr.tag, subTag, stepNumber++, difference);
// stepTime = System.currentTimeMillis();
// return difference;
// }
//
// /**
// * Prints a log with the total time.
// *
// * @return the total time
// */
// public Long logTotal() {
// Long difference = System.currentTimeMillis() - totalTime;
// Timber.d("%s - TOTAL: %d", tag, difference);
// return difference;
// }
// }
// Path: app/src/main/java/com/marcohc/architecture/app/MainApplication.java
import android.annotation.SuppressLint;
import android.os.StrictMode;
import com.marcohc.architecture.app.internal.di.ApplicationInjector;
import com.marcohc.architecture.app.presentation.util.BuildConfigUtils;
import com.marcohc.architecture.common.util.TimerUtils;
import com.squareup.leakcanary.LeakCanary;
import cat.ereza.customactivityoncrash.CustomActivityOnCrash;
import timber.log.Timber;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
package com.marcohc.architecture.app;
@SuppressLint({ "SimpleDateFormat", "DefaultLocale" })
public class MainApplication extends android.app.Application {
@Override
public void onCreate() {
super.onCreate();
| if (BuildConfigUtils.getInstance().isDevelopment()) { |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/MainApplication.java | // Path: app/src/main/java/com/marcohc/architecture/app/internal/di/ApplicationInjector.java
// public final class ApplicationInjector {
//
// private static ApplicationComponent sApplicationComponent;
//
// private ApplicationInjector() {
// }
//
// /**
// * Inject the context.
// *
// * @param context
// */
// public static void inject(Context context) {
// sApplicationComponent = DaggerApplicationComponent.builder()
// .applicationModule(new ApplicationModule(context))
// .build();
// }
//
// public static ApplicationComponent getApplicationComponent() {
// return sApplicationComponent;
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/util/BuildConfigUtils.java
// public class BuildConfigUtils extends BaseBuildConfigUtils {
//
// private static BuildConfigUtils instance;
//
// private BuildConfigUtils(String buildType) {
// super(buildType);
// }
//
// public static BuildConfigUtils getInstance() {
// if (instance == null) {
// instance = new BuildConfigUtils(BuildConfig.BUILD_TYPE);
// }
// return instance;
// }
// }
//
// Path: util/src/main/java/com/marcohc/architecture/common/util/TimerUtils.java
// public class TimerUtils {
//
// private long stepTime;
// private long totalTime;
// private int stepNumber;
// private String tag;
//
// public static TimerUtils getInstance(String tag) {
// return new TimerUtils(tag);
// }
//
// private TimerUtils(String tag) {
// this.tag = tag;
// stepNumber = 1;
// stepTime = System.currentTimeMillis();
// totalTime = System.currentTimeMillis();
// }
//
// /**
// * Prints a log with the step time.
// *
// * @return the step time
// */
// public Long logStep() {
// Long difference = System.currentTimeMillis() - stepTime;
// Timber.d("%s - Step %d: %d", tag, stepNumber++, difference);
// stepTime = System.currentTimeMillis();
// return difference;
// }
//
// /**
// * Prints a log with the step time.
// *
// * @param subTag sub tag used in the log
// * @return the step time
// */
// public Long logStep(String subTag) {
// Long difference = System.currentTimeMillis() - stepTime;
// Timber.d("%s (%s) - Step %d: %d", android.R.attr.tag, subTag, stepNumber++, difference);
// stepTime = System.currentTimeMillis();
// return difference;
// }
//
// /**
// * Prints a log with the total time.
// *
// * @return the total time
// */
// public Long logTotal() {
// Long difference = System.currentTimeMillis() - totalTime;
// Timber.d("%s - TOTAL: %d", tag, difference);
// return difference;
// }
// }
| import android.annotation.SuppressLint;
import android.os.StrictMode;
import com.marcohc.architecture.app.internal.di.ApplicationInjector;
import com.marcohc.architecture.app.presentation.util.BuildConfigUtils;
import com.marcohc.architecture.common.util.TimerUtils;
import com.squareup.leakcanary.LeakCanary;
import cat.ereza.customactivityoncrash.CustomActivityOnCrash;
import timber.log.Timber;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig; | package com.marcohc.architecture.app;
@SuppressLint({ "SimpleDateFormat", "DefaultLocale" })
public class MainApplication extends android.app.Application {
@Override
public void onCreate() {
super.onCreate();
if (BuildConfigUtils.getInstance().isDevelopment()) {
setUpStrictMode();
setUpLeakCanary();
}
setUpTimber();
| // Path: app/src/main/java/com/marcohc/architecture/app/internal/di/ApplicationInjector.java
// public final class ApplicationInjector {
//
// private static ApplicationComponent sApplicationComponent;
//
// private ApplicationInjector() {
// }
//
// /**
// * Inject the context.
// *
// * @param context
// */
// public static void inject(Context context) {
// sApplicationComponent = DaggerApplicationComponent.builder()
// .applicationModule(new ApplicationModule(context))
// .build();
// }
//
// public static ApplicationComponent getApplicationComponent() {
// return sApplicationComponent;
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/util/BuildConfigUtils.java
// public class BuildConfigUtils extends BaseBuildConfigUtils {
//
// private static BuildConfigUtils instance;
//
// private BuildConfigUtils(String buildType) {
// super(buildType);
// }
//
// public static BuildConfigUtils getInstance() {
// if (instance == null) {
// instance = new BuildConfigUtils(BuildConfig.BUILD_TYPE);
// }
// return instance;
// }
// }
//
// Path: util/src/main/java/com/marcohc/architecture/common/util/TimerUtils.java
// public class TimerUtils {
//
// private long stepTime;
// private long totalTime;
// private int stepNumber;
// private String tag;
//
// public static TimerUtils getInstance(String tag) {
// return new TimerUtils(tag);
// }
//
// private TimerUtils(String tag) {
// this.tag = tag;
// stepNumber = 1;
// stepTime = System.currentTimeMillis();
// totalTime = System.currentTimeMillis();
// }
//
// /**
// * Prints a log with the step time.
// *
// * @return the step time
// */
// public Long logStep() {
// Long difference = System.currentTimeMillis() - stepTime;
// Timber.d("%s - Step %d: %d", tag, stepNumber++, difference);
// stepTime = System.currentTimeMillis();
// return difference;
// }
//
// /**
// * Prints a log with the step time.
// *
// * @param subTag sub tag used in the log
// * @return the step time
// */
// public Long logStep(String subTag) {
// Long difference = System.currentTimeMillis() - stepTime;
// Timber.d("%s (%s) - Step %d: %d", android.R.attr.tag, subTag, stepNumber++, difference);
// stepTime = System.currentTimeMillis();
// return difference;
// }
//
// /**
// * Prints a log with the total time.
// *
// * @return the total time
// */
// public Long logTotal() {
// Long difference = System.currentTimeMillis() - totalTime;
// Timber.d("%s - TOTAL: %d", tag, difference);
// return difference;
// }
// }
// Path: app/src/main/java/com/marcohc/architecture/app/MainApplication.java
import android.annotation.SuppressLint;
import android.os.StrictMode;
import com.marcohc.architecture.app.internal.di.ApplicationInjector;
import com.marcohc.architecture.app.presentation.util.BuildConfigUtils;
import com.marcohc.architecture.common.util.TimerUtils;
import com.squareup.leakcanary.LeakCanary;
import cat.ereza.customactivityoncrash.CustomActivityOnCrash;
import timber.log.Timber;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
package com.marcohc.architecture.app;
@SuppressLint({ "SimpleDateFormat", "DefaultLocale" })
public class MainApplication extends android.app.Application {
@Override
public void onCreate() {
super.onCreate();
if (BuildConfigUtils.getInstance().isDevelopment()) {
setUpStrictMode();
setUpLeakCanary();
}
setUpTimber();
| TimerUtils timer = TimerUtils.getInstance("MainApplication.setUp"); |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/MainApplication.java | // Path: app/src/main/java/com/marcohc/architecture/app/internal/di/ApplicationInjector.java
// public final class ApplicationInjector {
//
// private static ApplicationComponent sApplicationComponent;
//
// private ApplicationInjector() {
// }
//
// /**
// * Inject the context.
// *
// * @param context
// */
// public static void inject(Context context) {
// sApplicationComponent = DaggerApplicationComponent.builder()
// .applicationModule(new ApplicationModule(context))
// .build();
// }
//
// public static ApplicationComponent getApplicationComponent() {
// return sApplicationComponent;
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/util/BuildConfigUtils.java
// public class BuildConfigUtils extends BaseBuildConfigUtils {
//
// private static BuildConfigUtils instance;
//
// private BuildConfigUtils(String buildType) {
// super(buildType);
// }
//
// public static BuildConfigUtils getInstance() {
// if (instance == null) {
// instance = new BuildConfigUtils(BuildConfig.BUILD_TYPE);
// }
// return instance;
// }
// }
//
// Path: util/src/main/java/com/marcohc/architecture/common/util/TimerUtils.java
// public class TimerUtils {
//
// private long stepTime;
// private long totalTime;
// private int stepNumber;
// private String tag;
//
// public static TimerUtils getInstance(String tag) {
// return new TimerUtils(tag);
// }
//
// private TimerUtils(String tag) {
// this.tag = tag;
// stepNumber = 1;
// stepTime = System.currentTimeMillis();
// totalTime = System.currentTimeMillis();
// }
//
// /**
// * Prints a log with the step time.
// *
// * @return the step time
// */
// public Long logStep() {
// Long difference = System.currentTimeMillis() - stepTime;
// Timber.d("%s - Step %d: %d", tag, stepNumber++, difference);
// stepTime = System.currentTimeMillis();
// return difference;
// }
//
// /**
// * Prints a log with the step time.
// *
// * @param subTag sub tag used in the log
// * @return the step time
// */
// public Long logStep(String subTag) {
// Long difference = System.currentTimeMillis() - stepTime;
// Timber.d("%s (%s) - Step %d: %d", android.R.attr.tag, subTag, stepNumber++, difference);
// stepTime = System.currentTimeMillis();
// return difference;
// }
//
// /**
// * Prints a log with the total time.
// *
// * @return the total time
// */
// public Long logTotal() {
// Long difference = System.currentTimeMillis() - totalTime;
// Timber.d("%s - TOTAL: %d", tag, difference);
// return difference;
// }
// }
| import android.annotation.SuppressLint;
import android.os.StrictMode;
import com.marcohc.architecture.app.internal.di.ApplicationInjector;
import com.marcohc.architecture.app.presentation.util.BuildConfigUtils;
import com.marcohc.architecture.common.util.TimerUtils;
import com.squareup.leakcanary.LeakCanary;
import cat.ereza.customactivityoncrash.CustomActivityOnCrash;
import timber.log.Timber;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig; | private void setUpCustomCrash() {
CustomActivityOnCrash.install(this);
}
private void setUpLeakCanary() {
LeakCanary.install(this);
}
private void setUpStrictMode() {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectAll()
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
}
private void setUpTimber() {
if (BuildConfigUtils.getInstance().isDevelopment()) {
Timber.plant(new Timber.DebugTree());
}
}
private void setUpDagger() { | // Path: app/src/main/java/com/marcohc/architecture/app/internal/di/ApplicationInjector.java
// public final class ApplicationInjector {
//
// private static ApplicationComponent sApplicationComponent;
//
// private ApplicationInjector() {
// }
//
// /**
// * Inject the context.
// *
// * @param context
// */
// public static void inject(Context context) {
// sApplicationComponent = DaggerApplicationComponent.builder()
// .applicationModule(new ApplicationModule(context))
// .build();
// }
//
// public static ApplicationComponent getApplicationComponent() {
// return sApplicationComponent;
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/util/BuildConfigUtils.java
// public class BuildConfigUtils extends BaseBuildConfigUtils {
//
// private static BuildConfigUtils instance;
//
// private BuildConfigUtils(String buildType) {
// super(buildType);
// }
//
// public static BuildConfigUtils getInstance() {
// if (instance == null) {
// instance = new BuildConfigUtils(BuildConfig.BUILD_TYPE);
// }
// return instance;
// }
// }
//
// Path: util/src/main/java/com/marcohc/architecture/common/util/TimerUtils.java
// public class TimerUtils {
//
// private long stepTime;
// private long totalTime;
// private int stepNumber;
// private String tag;
//
// public static TimerUtils getInstance(String tag) {
// return new TimerUtils(tag);
// }
//
// private TimerUtils(String tag) {
// this.tag = tag;
// stepNumber = 1;
// stepTime = System.currentTimeMillis();
// totalTime = System.currentTimeMillis();
// }
//
// /**
// * Prints a log with the step time.
// *
// * @return the step time
// */
// public Long logStep() {
// Long difference = System.currentTimeMillis() - stepTime;
// Timber.d("%s - Step %d: %d", tag, stepNumber++, difference);
// stepTime = System.currentTimeMillis();
// return difference;
// }
//
// /**
// * Prints a log with the step time.
// *
// * @param subTag sub tag used in the log
// * @return the step time
// */
// public Long logStep(String subTag) {
// Long difference = System.currentTimeMillis() - stepTime;
// Timber.d("%s (%s) - Step %d: %d", android.R.attr.tag, subTag, stepNumber++, difference);
// stepTime = System.currentTimeMillis();
// return difference;
// }
//
// /**
// * Prints a log with the total time.
// *
// * @return the total time
// */
// public Long logTotal() {
// Long difference = System.currentTimeMillis() - totalTime;
// Timber.d("%s - TOTAL: %d", tag, difference);
// return difference;
// }
// }
// Path: app/src/main/java/com/marcohc/architecture/app/MainApplication.java
import android.annotation.SuppressLint;
import android.os.StrictMode;
import com.marcohc.architecture.app.internal.di.ApplicationInjector;
import com.marcohc.architecture.app.presentation.util.BuildConfigUtils;
import com.marcohc.architecture.common.util.TimerUtils;
import com.squareup.leakcanary.LeakCanary;
import cat.ereza.customactivityoncrash.CustomActivityOnCrash;
import timber.log.Timber;
import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
private void setUpCustomCrash() {
CustomActivityOnCrash.install(this);
}
private void setUpLeakCanary() {
LeakCanary.install(this);
}
private void setUpStrictMode() {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectAll()
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
}
private void setUpTimber() {
if (BuildConfigUtils.getInstance().isDevelopment()) {
Timber.plant(new Timber.DebugTree());
}
}
private void setUpDagger() { | ApplicationInjector.inject(MainApplication.this); |
marcohc/android-clean-architecture | util/src/main/java/com/marcohc/architecture/common/util/DateFormatterUtils.java | // Path: common/src/main/java/com/marcohc/architecture/common/util/helper/StringUtils.java
// public final class StringUtils {
//
// private static final String EMAIL_PATTERN = "^[\\w!#$%&'*+/=?`{|}~^-]+(?:\\.[\\w!#$%&'*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$";
// private static Pattern pattern;
//
// private StringUtils() {
// }
//
// /**
// * Validate hex with regular expression
// *
// * @param email hex for validation
// * @return true valid hex, false invalid hex
// */
// public static boolean isEmailValid(@NonNull final String email) {
// Preconditions.checkNotNull(email, "email");
// boolean isValid = false;
// if (pattern == null) {
// pattern = Pattern.compile(EMAIL_PATTERN);
// }
// isValid = pattern.matcher(email).matches();
// return isValid;
// }
//
// /**
// * Check if the parameters is blank.
// *
// * @param text the text to check
// * @return true if is blank, false otherwise
// */
// public static boolean isBlank(@Nullable final CharSequence text) {
// return text == null || text.toString().trim().isEmpty();
// }
//
// /**
// * Check if the parameters is blank.
// *
// * @param text the text to check
// * @return true if is blank, false otherwise
// */
// public static boolean isBlank(@Nullable final String text) {
// return text == null || text.trim().isEmpty();
// }
//
// @NonNull
// public static String getFirstCapitalize(@NonNull String text) {
// Preconditions.checkNotNull(text, "text");
// StringBuilder textCapitalize = new StringBuilder();
// if (!text.isEmpty()) {
// textCapitalize.append(text.substring(0, 1).toUpperCase()).append(text.substring(1, text.length()));
// }
// return textCapitalize.toString();
// }
//
// @NonNull
// public static String getAllCapitalize(@NonNull String text) {
// Preconditions.checkNotNull(text, "text");
// StringBuilder textCapitalize = new StringBuilder();
// if (!text.isEmpty()) {
// for (int i = 0; i < text.length(); i++) {
// textCapitalize.append(String.valueOf(text.charAt(i)).toUpperCase());
// }
// }
// return textCapitalize.toString();
// }
//
// }
//
// Path: common/src/main/java/com/marcohc/architecture/common/util/helper/StringUtils.java
// @NonNull
// public static String getFirstCapitalize(@NonNull String text) {
// Preconditions.checkNotNull(text, "text");
// StringBuilder textCapitalize = new StringBuilder();
// if (!text.isEmpty()) {
// textCapitalize.append(text.substring(0, 1).toUpperCase()).append(text.substring(1, text.length()));
// }
// return textCapitalize.toString();
// }
| import static com.marcohc.architecture.common.util.helper.StringUtils.getFirstCapitalize;
import android.annotation.SuppressLint;
import android.content.Context;
import com.marcohc.architecture.common.util.helper.StringUtils;
import java.io.IOException;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale; | /*
* Copyright (C) 2016 Marco Hernaiz Cao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marcohc.architecture.common.util;
/**
* Standard date and string formats
*/
@SuppressLint({"DefaultLocale", "SimpleDateFormat"})
public class DateFormatterUtils {
/**
* Format depending on Locale like: Tuesday 15
*
* @param date
* @return
*/
public static String formatDayDate(Date date) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE d"); | // Path: common/src/main/java/com/marcohc/architecture/common/util/helper/StringUtils.java
// public final class StringUtils {
//
// private static final String EMAIL_PATTERN = "^[\\w!#$%&'*+/=?`{|}~^-]+(?:\\.[\\w!#$%&'*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$";
// private static Pattern pattern;
//
// private StringUtils() {
// }
//
// /**
// * Validate hex with regular expression
// *
// * @param email hex for validation
// * @return true valid hex, false invalid hex
// */
// public static boolean isEmailValid(@NonNull final String email) {
// Preconditions.checkNotNull(email, "email");
// boolean isValid = false;
// if (pattern == null) {
// pattern = Pattern.compile(EMAIL_PATTERN);
// }
// isValid = pattern.matcher(email).matches();
// return isValid;
// }
//
// /**
// * Check if the parameters is blank.
// *
// * @param text the text to check
// * @return true if is blank, false otherwise
// */
// public static boolean isBlank(@Nullable final CharSequence text) {
// return text == null || text.toString().trim().isEmpty();
// }
//
// /**
// * Check if the parameters is blank.
// *
// * @param text the text to check
// * @return true if is blank, false otherwise
// */
// public static boolean isBlank(@Nullable final String text) {
// return text == null || text.trim().isEmpty();
// }
//
// @NonNull
// public static String getFirstCapitalize(@NonNull String text) {
// Preconditions.checkNotNull(text, "text");
// StringBuilder textCapitalize = new StringBuilder();
// if (!text.isEmpty()) {
// textCapitalize.append(text.substring(0, 1).toUpperCase()).append(text.substring(1, text.length()));
// }
// return textCapitalize.toString();
// }
//
// @NonNull
// public static String getAllCapitalize(@NonNull String text) {
// Preconditions.checkNotNull(text, "text");
// StringBuilder textCapitalize = new StringBuilder();
// if (!text.isEmpty()) {
// for (int i = 0; i < text.length(); i++) {
// textCapitalize.append(String.valueOf(text.charAt(i)).toUpperCase());
// }
// }
// return textCapitalize.toString();
// }
//
// }
//
// Path: common/src/main/java/com/marcohc/architecture/common/util/helper/StringUtils.java
// @NonNull
// public static String getFirstCapitalize(@NonNull String text) {
// Preconditions.checkNotNull(text, "text");
// StringBuilder textCapitalize = new StringBuilder();
// if (!text.isEmpty()) {
// textCapitalize.append(text.substring(0, 1).toUpperCase()).append(text.substring(1, text.length()));
// }
// return textCapitalize.toString();
// }
// Path: util/src/main/java/com/marcohc/architecture/common/util/DateFormatterUtils.java
import static com.marcohc.architecture.common.util.helper.StringUtils.getFirstCapitalize;
import android.annotation.SuppressLint;
import android.content.Context;
import com.marcohc.architecture.common.util.helper.StringUtils;
import java.io.IOException;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/*
* Copyright (C) 2016 Marco Hernaiz Cao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marcohc.architecture.common.util;
/**
* Standard date and string formats
*/
@SuppressLint({"DefaultLocale", "SimpleDateFormat"})
public class DateFormatterUtils {
/**
* Format depending on Locale like: Tuesday 15
*
* @param date
* @return
*/
public static String formatDayDate(Date date) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE d"); | return getFirstCapitalize(simpleDateFormat.format(date)); |
marcohc/android-clean-architecture | util/src/main/java/com/marcohc/architecture/common/util/DateFormatterUtils.java | // Path: common/src/main/java/com/marcohc/architecture/common/util/helper/StringUtils.java
// public final class StringUtils {
//
// private static final String EMAIL_PATTERN = "^[\\w!#$%&'*+/=?`{|}~^-]+(?:\\.[\\w!#$%&'*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$";
// private static Pattern pattern;
//
// private StringUtils() {
// }
//
// /**
// * Validate hex with regular expression
// *
// * @param email hex for validation
// * @return true valid hex, false invalid hex
// */
// public static boolean isEmailValid(@NonNull final String email) {
// Preconditions.checkNotNull(email, "email");
// boolean isValid = false;
// if (pattern == null) {
// pattern = Pattern.compile(EMAIL_PATTERN);
// }
// isValid = pattern.matcher(email).matches();
// return isValid;
// }
//
// /**
// * Check if the parameters is blank.
// *
// * @param text the text to check
// * @return true if is blank, false otherwise
// */
// public static boolean isBlank(@Nullable final CharSequence text) {
// return text == null || text.toString().trim().isEmpty();
// }
//
// /**
// * Check if the parameters is blank.
// *
// * @param text the text to check
// * @return true if is blank, false otherwise
// */
// public static boolean isBlank(@Nullable final String text) {
// return text == null || text.trim().isEmpty();
// }
//
// @NonNull
// public static String getFirstCapitalize(@NonNull String text) {
// Preconditions.checkNotNull(text, "text");
// StringBuilder textCapitalize = new StringBuilder();
// if (!text.isEmpty()) {
// textCapitalize.append(text.substring(0, 1).toUpperCase()).append(text.substring(1, text.length()));
// }
// return textCapitalize.toString();
// }
//
// @NonNull
// public static String getAllCapitalize(@NonNull String text) {
// Preconditions.checkNotNull(text, "text");
// StringBuilder textCapitalize = new StringBuilder();
// if (!text.isEmpty()) {
// for (int i = 0; i < text.length(); i++) {
// textCapitalize.append(String.valueOf(text.charAt(i)).toUpperCase());
// }
// }
// return textCapitalize.toString();
// }
//
// }
//
// Path: common/src/main/java/com/marcohc/architecture/common/util/helper/StringUtils.java
// @NonNull
// public static String getFirstCapitalize(@NonNull String text) {
// Preconditions.checkNotNull(text, "text");
// StringBuilder textCapitalize = new StringBuilder();
// if (!text.isEmpty()) {
// textCapitalize.append(text.substring(0, 1).toUpperCase()).append(text.substring(1, text.length()));
// }
// return textCapitalize.toString();
// }
| import static com.marcohc.architecture.common.util.helper.StringUtils.getFirstCapitalize;
import android.annotation.SuppressLint;
import android.content.Context;
import com.marcohc.architecture.common.util.helper.StringUtils;
import java.io.IOException;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale; | /*
* Copyright (C) 2016 Marco Hernaiz Cao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marcohc.architecture.common.util;
/**
* Standard date and string formats
*/
@SuppressLint({"DefaultLocale", "SimpleDateFormat"})
public class DateFormatterUtils {
/**
* Format depending on Locale like: Tuesday 15
*
* @param date
* @return
*/
public static String formatDayDate(Date date) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE d");
return getFirstCapitalize(simpleDateFormat.format(date));
}
/**
* Format depending on Locale like: 11/25/2014
*
* @param date
* @return
*/
public static String formatShortDate(Date date) {
DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
return dateFormatter.format(date);
}
/**
* Format depending on Locale like: Nov 5, 2014 or 05/11/2014
*
* @param date
* @return
*/
public static String formatMediumDate(Date date) {
DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault());
return dateFormatter.format(date);
}
/**
* Format like: Tue 28, 17:05
*
* @param date
* @return
*/
public static String formatWithWeekDayAndHour(Date date, Context context) {
SimpleDateFormat simpleDateFormat;
if (android.text.format.DateFormat.is24HourFormat(context)) {
simpleDateFormat = new SimpleDateFormat("E d, HH:mm");
} else {
simpleDateFormat = new SimpleDateFormat("E d, hh:mm a");
} | // Path: common/src/main/java/com/marcohc/architecture/common/util/helper/StringUtils.java
// public final class StringUtils {
//
// private static final String EMAIL_PATTERN = "^[\\w!#$%&'*+/=?`{|}~^-]+(?:\\.[\\w!#$%&'*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$";
// private static Pattern pattern;
//
// private StringUtils() {
// }
//
// /**
// * Validate hex with regular expression
// *
// * @param email hex for validation
// * @return true valid hex, false invalid hex
// */
// public static boolean isEmailValid(@NonNull final String email) {
// Preconditions.checkNotNull(email, "email");
// boolean isValid = false;
// if (pattern == null) {
// pattern = Pattern.compile(EMAIL_PATTERN);
// }
// isValid = pattern.matcher(email).matches();
// return isValid;
// }
//
// /**
// * Check if the parameters is blank.
// *
// * @param text the text to check
// * @return true if is blank, false otherwise
// */
// public static boolean isBlank(@Nullable final CharSequence text) {
// return text == null || text.toString().trim().isEmpty();
// }
//
// /**
// * Check if the parameters is blank.
// *
// * @param text the text to check
// * @return true if is blank, false otherwise
// */
// public static boolean isBlank(@Nullable final String text) {
// return text == null || text.trim().isEmpty();
// }
//
// @NonNull
// public static String getFirstCapitalize(@NonNull String text) {
// Preconditions.checkNotNull(text, "text");
// StringBuilder textCapitalize = new StringBuilder();
// if (!text.isEmpty()) {
// textCapitalize.append(text.substring(0, 1).toUpperCase()).append(text.substring(1, text.length()));
// }
// return textCapitalize.toString();
// }
//
// @NonNull
// public static String getAllCapitalize(@NonNull String text) {
// Preconditions.checkNotNull(text, "text");
// StringBuilder textCapitalize = new StringBuilder();
// if (!text.isEmpty()) {
// for (int i = 0; i < text.length(); i++) {
// textCapitalize.append(String.valueOf(text.charAt(i)).toUpperCase());
// }
// }
// return textCapitalize.toString();
// }
//
// }
//
// Path: common/src/main/java/com/marcohc/architecture/common/util/helper/StringUtils.java
// @NonNull
// public static String getFirstCapitalize(@NonNull String text) {
// Preconditions.checkNotNull(text, "text");
// StringBuilder textCapitalize = new StringBuilder();
// if (!text.isEmpty()) {
// textCapitalize.append(text.substring(0, 1).toUpperCase()).append(text.substring(1, text.length()));
// }
// return textCapitalize.toString();
// }
// Path: util/src/main/java/com/marcohc/architecture/common/util/DateFormatterUtils.java
import static com.marcohc.architecture.common.util.helper.StringUtils.getFirstCapitalize;
import android.annotation.SuppressLint;
import android.content.Context;
import com.marcohc.architecture.common.util.helper.StringUtils;
import java.io.IOException;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/*
* Copyright (C) 2016 Marco Hernaiz Cao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marcohc.architecture.common.util;
/**
* Standard date and string formats
*/
@SuppressLint({"DefaultLocale", "SimpleDateFormat"})
public class DateFormatterUtils {
/**
* Format depending on Locale like: Tuesday 15
*
* @param date
* @return
*/
public static String formatDayDate(Date date) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE d");
return getFirstCapitalize(simpleDateFormat.format(date));
}
/**
* Format depending on Locale like: 11/25/2014
*
* @param date
* @return
*/
public static String formatShortDate(Date date) {
DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault());
return dateFormatter.format(date);
}
/**
* Format depending on Locale like: Nov 5, 2014 or 05/11/2014
*
* @param date
* @return
*/
public static String formatMediumDate(Date date) {
DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault());
return dateFormatter.format(date);
}
/**
* Format like: Tue 28, 17:05
*
* @param date
* @return
*/
public static String formatWithWeekDayAndHour(Date date, Context context) {
SimpleDateFormat simpleDateFormat;
if (android.text.format.DateFormat.is24HourFormat(context)) {
simpleDateFormat = new SimpleDateFormat("E d, HH:mm");
} else {
simpleDateFormat = new SimpleDateFormat("E d, hh:mm a");
} | return StringUtils.getFirstCapitalize(simpleDateFormat.format(date)); |
marcohc/android-clean-architecture | util/src/main/java/com/marcohc/architecture/common/util/ScreenUtils.java | // Path: common/src/main/java/com/marcohc/architecture/common/util/utils/Preconditions.java
// public final class Preconditions {
//
// private Preconditions() {
// // no-op
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @param name the variable name
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference, String name) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException(name + " must not be null.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @param name the variable name
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression, @Nullable String name) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be false.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures not blank in parameters.
// *
// * @param value the value to check
// * @param name the name you want to display in the logs
// * @param <T> the type of the value
// * @return the value you want to check
// */
// @NonNull
// public static <T extends CharSequence> T nonBlank(@Nullable T value, String name) {
// if (StringUtils.isBlank(value)) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be blank.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return value;
// }
//
// @NonNull
// private static StackTraceElement[] getStackTrace(@NonNull Exception exception) {
// final StackTraceElement[] sourceStack = exception.getStackTrace();
//
// final StackTraceElement[] updatedStack = new StackTraceElement[sourceStack.length - 1];
// System.arraycopy(sourceStack, 1, updatedStack, 0, updatedStack.length);
//
// return updatedStack;
// }
// }
| import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import com.marcohc.architecture.common.util.utils.Preconditions; | /*
* Copyright (C) 2015 Marco Hernaiz Cao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marcohc.architecture.common.util;
/**
* Screen related methods
*/
public class ScreenUtils {
public static int getDpFromPx(@NonNull Context context, float px) { | // Path: common/src/main/java/com/marcohc/architecture/common/util/utils/Preconditions.java
// public final class Preconditions {
//
// private Preconditions() {
// // no-op
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @param name the variable name
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference, String name) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException(name + " must not be null.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @param name the variable name
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression, @Nullable String name) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be false.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures not blank in parameters.
// *
// * @param value the value to check
// * @param name the name you want to display in the logs
// * @param <T> the type of the value
// * @return the value you want to check
// */
// @NonNull
// public static <T extends CharSequence> T nonBlank(@Nullable T value, String name) {
// if (StringUtils.isBlank(value)) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be blank.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return value;
// }
//
// @NonNull
// private static StackTraceElement[] getStackTrace(@NonNull Exception exception) {
// final StackTraceElement[] sourceStack = exception.getStackTrace();
//
// final StackTraceElement[] updatedStack = new StackTraceElement[sourceStack.length - 1];
// System.arraycopy(sourceStack, 1, updatedStack, 0, updatedStack.length);
//
// return updatedStack;
// }
// }
// Path: util/src/main/java/com/marcohc/architecture/common/util/ScreenUtils.java
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import com.marcohc.architecture.common.util.utils.Preconditions;
/*
* Copyright (C) 2015 Marco Hernaiz Cao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marcohc.architecture.common.util;
/**
* Screen related methods
*/
public class ScreenUtils {
public static int getDpFromPx(@NonNull Context context, float px) { | Preconditions.checkNotNull(context); |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UsersWithoutPictureDataStore.java | // Path: app/src/main/java/com/marcohc/architecture/app/data/service/user/UsersWithoutPictureService.java
// public interface UsersWithoutPictureService {
//
// /**
// * Get users without picture.
// *
// * @return the observable with users without picture
// */
// @GET("users")
// Observable<List<UserEntity>> getAll();
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/domain/entity/UserEntity.java
// public class UserEntity implements Entity {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserEntity() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
//
// }
//
// Path: rest/src/main/java/com/marcohc/architecture/rx/data/net/ServiceFactory.java
// public final class ServiceFactory {
//
// private static final int CONNECTION_TIME_OUT = 10;
// private static final int WRITE_TIME_OUT = 10;
// private static final int READ_TIME_OUT = 10;
//
// // No need to instantiate this class.
// private ServiceFactory() {
// }
//
// /**
// * Create service with the given parameters.
// *
// * @param serviceClass the service class
// * @param factory the converter factory
// * @param baseUrl the base url
// * @param <S> the service class
// * @return an instance of the service with the specific type
// */
// public static <S> S createService(Class<S> serviceClass, Converter.Factory factory, String baseUrl) {
// return createService(serviceClass, factory, null, baseUrl);
// }
//
// /**
// * Create service with the given parameters.
// *
// * @param serviceClass the service class
// * @param factory the converter factory
// * @param adapter the response adapter
// * @param baseUrl the base url
// * @param <S> the service class
// * @return an instance of the service with the specific type
// */
// public static <S> S createService(Class<S> serviceClass, Converter.Factory factory, @Nullable CallAdapter.Factory adapter, String baseUrl) {
// OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder()
// .connectTimeout(CONNECTION_TIME_OUT, TimeUnit.SECONDS)
// .writeTimeout(WRITE_TIME_OUT, TimeUnit.SECONDS)
// .readTimeout(READ_TIME_OUT, TimeUnit.SECONDS);
//
// // Add logging
// HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
// httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// okHttpClientBuilder.addInterceptor(httpLoggingInterceptor);
//
// Retrofit.Builder builder = new Retrofit.Builder()
// .baseUrl(baseUrl)
// .addConverterFactory(factory)
// .client(okHttpClientBuilder.build());
//
// if (adapter != null) {
// builder.addCallAdapterFactory(adapter);
// }
//
// Retrofit retrofit = builder.build();
//
// return retrofit.create(serviceClass);
// }
//
// }
| import com.marcohc.architecture.app.data.service.user.UsersWithoutPictureService;
import com.marcohc.architecture.app.domain.entity.UserEntity;
import com.marcohc.architecture.rx.data.net.ServiceFactory;
import java.util.List;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable; | package com.marcohc.architecture.app.data.datastore.user;
/**
* Users without pictures data store.
* <p>
* It uses a random user API for it
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public class UsersWithoutPictureDataStore implements UserCloudDataStore {
private static final String USERS_WITHOUT_PICTURES_URL = "http://jsonplaceholder.typicode.com/";
@Override | // Path: app/src/main/java/com/marcohc/architecture/app/data/service/user/UsersWithoutPictureService.java
// public interface UsersWithoutPictureService {
//
// /**
// * Get users without picture.
// *
// * @return the observable with users without picture
// */
// @GET("users")
// Observable<List<UserEntity>> getAll();
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/domain/entity/UserEntity.java
// public class UserEntity implements Entity {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserEntity() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
//
// }
//
// Path: rest/src/main/java/com/marcohc/architecture/rx/data/net/ServiceFactory.java
// public final class ServiceFactory {
//
// private static final int CONNECTION_TIME_OUT = 10;
// private static final int WRITE_TIME_OUT = 10;
// private static final int READ_TIME_OUT = 10;
//
// // No need to instantiate this class.
// private ServiceFactory() {
// }
//
// /**
// * Create service with the given parameters.
// *
// * @param serviceClass the service class
// * @param factory the converter factory
// * @param baseUrl the base url
// * @param <S> the service class
// * @return an instance of the service with the specific type
// */
// public static <S> S createService(Class<S> serviceClass, Converter.Factory factory, String baseUrl) {
// return createService(serviceClass, factory, null, baseUrl);
// }
//
// /**
// * Create service with the given parameters.
// *
// * @param serviceClass the service class
// * @param factory the converter factory
// * @param adapter the response adapter
// * @param baseUrl the base url
// * @param <S> the service class
// * @return an instance of the service with the specific type
// */
// public static <S> S createService(Class<S> serviceClass, Converter.Factory factory, @Nullable CallAdapter.Factory adapter, String baseUrl) {
// OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder()
// .connectTimeout(CONNECTION_TIME_OUT, TimeUnit.SECONDS)
// .writeTimeout(WRITE_TIME_OUT, TimeUnit.SECONDS)
// .readTimeout(READ_TIME_OUT, TimeUnit.SECONDS);
//
// // Add logging
// HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
// httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// okHttpClientBuilder.addInterceptor(httpLoggingInterceptor);
//
// Retrofit.Builder builder = new Retrofit.Builder()
// .baseUrl(baseUrl)
// .addConverterFactory(factory)
// .client(okHttpClientBuilder.build());
//
// if (adapter != null) {
// builder.addCallAdapterFactory(adapter);
// }
//
// Retrofit retrofit = builder.build();
//
// return retrofit.create(serviceClass);
// }
//
// }
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UsersWithoutPictureDataStore.java
import com.marcohc.architecture.app.data.service.user.UsersWithoutPictureService;
import com.marcohc.architecture.app.domain.entity.UserEntity;
import com.marcohc.architecture.rx.data.net.ServiceFactory;
import java.util.List;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
package com.marcohc.architecture.app.data.datastore.user;
/**
* Users without pictures data store.
* <p>
* It uses a random user API for it
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public class UsersWithoutPictureDataStore implements UserCloudDataStore {
private static final String USERS_WITHOUT_PICTURES_URL = "http://jsonplaceholder.typicode.com/";
@Override | public Observable<List<UserEntity>> getAll() { |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UsersWithoutPictureDataStore.java | // Path: app/src/main/java/com/marcohc/architecture/app/data/service/user/UsersWithoutPictureService.java
// public interface UsersWithoutPictureService {
//
// /**
// * Get users without picture.
// *
// * @return the observable with users without picture
// */
// @GET("users")
// Observable<List<UserEntity>> getAll();
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/domain/entity/UserEntity.java
// public class UserEntity implements Entity {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserEntity() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
//
// }
//
// Path: rest/src/main/java/com/marcohc/architecture/rx/data/net/ServiceFactory.java
// public final class ServiceFactory {
//
// private static final int CONNECTION_TIME_OUT = 10;
// private static final int WRITE_TIME_OUT = 10;
// private static final int READ_TIME_OUT = 10;
//
// // No need to instantiate this class.
// private ServiceFactory() {
// }
//
// /**
// * Create service with the given parameters.
// *
// * @param serviceClass the service class
// * @param factory the converter factory
// * @param baseUrl the base url
// * @param <S> the service class
// * @return an instance of the service with the specific type
// */
// public static <S> S createService(Class<S> serviceClass, Converter.Factory factory, String baseUrl) {
// return createService(serviceClass, factory, null, baseUrl);
// }
//
// /**
// * Create service with the given parameters.
// *
// * @param serviceClass the service class
// * @param factory the converter factory
// * @param adapter the response adapter
// * @param baseUrl the base url
// * @param <S> the service class
// * @return an instance of the service with the specific type
// */
// public static <S> S createService(Class<S> serviceClass, Converter.Factory factory, @Nullable CallAdapter.Factory adapter, String baseUrl) {
// OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder()
// .connectTimeout(CONNECTION_TIME_OUT, TimeUnit.SECONDS)
// .writeTimeout(WRITE_TIME_OUT, TimeUnit.SECONDS)
// .readTimeout(READ_TIME_OUT, TimeUnit.SECONDS);
//
// // Add logging
// HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
// httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// okHttpClientBuilder.addInterceptor(httpLoggingInterceptor);
//
// Retrofit.Builder builder = new Retrofit.Builder()
// .baseUrl(baseUrl)
// .addConverterFactory(factory)
// .client(okHttpClientBuilder.build());
//
// if (adapter != null) {
// builder.addCallAdapterFactory(adapter);
// }
//
// Retrofit retrofit = builder.build();
//
// return retrofit.create(serviceClass);
// }
//
// }
| import com.marcohc.architecture.app.data.service.user.UsersWithoutPictureService;
import com.marcohc.architecture.app.domain.entity.UserEntity;
import com.marcohc.architecture.rx.data.net.ServiceFactory;
import java.util.List;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable; | package com.marcohc.architecture.app.data.datastore.user;
/**
* Users without pictures data store.
* <p>
* It uses a random user API for it
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public class UsersWithoutPictureDataStore implements UserCloudDataStore {
private static final String USERS_WITHOUT_PICTURES_URL = "http://jsonplaceholder.typicode.com/";
@Override
public Observable<List<UserEntity>> getAll() {
| // Path: app/src/main/java/com/marcohc/architecture/app/data/service/user/UsersWithoutPictureService.java
// public interface UsersWithoutPictureService {
//
// /**
// * Get users without picture.
// *
// * @return the observable with users without picture
// */
// @GET("users")
// Observable<List<UserEntity>> getAll();
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/domain/entity/UserEntity.java
// public class UserEntity implements Entity {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserEntity() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
//
// }
//
// Path: rest/src/main/java/com/marcohc/architecture/rx/data/net/ServiceFactory.java
// public final class ServiceFactory {
//
// private static final int CONNECTION_TIME_OUT = 10;
// private static final int WRITE_TIME_OUT = 10;
// private static final int READ_TIME_OUT = 10;
//
// // No need to instantiate this class.
// private ServiceFactory() {
// }
//
// /**
// * Create service with the given parameters.
// *
// * @param serviceClass the service class
// * @param factory the converter factory
// * @param baseUrl the base url
// * @param <S> the service class
// * @return an instance of the service with the specific type
// */
// public static <S> S createService(Class<S> serviceClass, Converter.Factory factory, String baseUrl) {
// return createService(serviceClass, factory, null, baseUrl);
// }
//
// /**
// * Create service with the given parameters.
// *
// * @param serviceClass the service class
// * @param factory the converter factory
// * @param adapter the response adapter
// * @param baseUrl the base url
// * @param <S> the service class
// * @return an instance of the service with the specific type
// */
// public static <S> S createService(Class<S> serviceClass, Converter.Factory factory, @Nullable CallAdapter.Factory adapter, String baseUrl) {
// OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder()
// .connectTimeout(CONNECTION_TIME_OUT, TimeUnit.SECONDS)
// .writeTimeout(WRITE_TIME_OUT, TimeUnit.SECONDS)
// .readTimeout(READ_TIME_OUT, TimeUnit.SECONDS);
//
// // Add logging
// HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
// httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// okHttpClientBuilder.addInterceptor(httpLoggingInterceptor);
//
// Retrofit.Builder builder = new Retrofit.Builder()
// .baseUrl(baseUrl)
// .addConverterFactory(factory)
// .client(okHttpClientBuilder.build());
//
// if (adapter != null) {
// builder.addCallAdapterFactory(adapter);
// }
//
// Retrofit retrofit = builder.build();
//
// return retrofit.create(serviceClass);
// }
//
// }
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UsersWithoutPictureDataStore.java
import com.marcohc.architecture.app.data.service.user.UsersWithoutPictureService;
import com.marcohc.architecture.app.domain.entity.UserEntity;
import com.marcohc.architecture.rx.data.net.ServiceFactory;
import java.util.List;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
package com.marcohc.architecture.app.data.datastore.user;
/**
* Users without pictures data store.
* <p>
* It uses a random user API for it
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public class UsersWithoutPictureDataStore implements UserCloudDataStore {
private static final String USERS_WITHOUT_PICTURES_URL = "http://jsonplaceholder.typicode.com/";
@Override
public Observable<List<UserEntity>> getAll() {
| UsersWithoutPictureService service = ServiceFactory.createService( |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UsersWithoutPictureDataStore.java | // Path: app/src/main/java/com/marcohc/architecture/app/data/service/user/UsersWithoutPictureService.java
// public interface UsersWithoutPictureService {
//
// /**
// * Get users without picture.
// *
// * @return the observable with users without picture
// */
// @GET("users")
// Observable<List<UserEntity>> getAll();
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/domain/entity/UserEntity.java
// public class UserEntity implements Entity {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserEntity() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
//
// }
//
// Path: rest/src/main/java/com/marcohc/architecture/rx/data/net/ServiceFactory.java
// public final class ServiceFactory {
//
// private static final int CONNECTION_TIME_OUT = 10;
// private static final int WRITE_TIME_OUT = 10;
// private static final int READ_TIME_OUT = 10;
//
// // No need to instantiate this class.
// private ServiceFactory() {
// }
//
// /**
// * Create service with the given parameters.
// *
// * @param serviceClass the service class
// * @param factory the converter factory
// * @param baseUrl the base url
// * @param <S> the service class
// * @return an instance of the service with the specific type
// */
// public static <S> S createService(Class<S> serviceClass, Converter.Factory factory, String baseUrl) {
// return createService(serviceClass, factory, null, baseUrl);
// }
//
// /**
// * Create service with the given parameters.
// *
// * @param serviceClass the service class
// * @param factory the converter factory
// * @param adapter the response adapter
// * @param baseUrl the base url
// * @param <S> the service class
// * @return an instance of the service with the specific type
// */
// public static <S> S createService(Class<S> serviceClass, Converter.Factory factory, @Nullable CallAdapter.Factory adapter, String baseUrl) {
// OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder()
// .connectTimeout(CONNECTION_TIME_OUT, TimeUnit.SECONDS)
// .writeTimeout(WRITE_TIME_OUT, TimeUnit.SECONDS)
// .readTimeout(READ_TIME_OUT, TimeUnit.SECONDS);
//
// // Add logging
// HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
// httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// okHttpClientBuilder.addInterceptor(httpLoggingInterceptor);
//
// Retrofit.Builder builder = new Retrofit.Builder()
// .baseUrl(baseUrl)
// .addConverterFactory(factory)
// .client(okHttpClientBuilder.build());
//
// if (adapter != null) {
// builder.addCallAdapterFactory(adapter);
// }
//
// Retrofit retrofit = builder.build();
//
// return retrofit.create(serviceClass);
// }
//
// }
| import com.marcohc.architecture.app.data.service.user.UsersWithoutPictureService;
import com.marcohc.architecture.app.domain.entity.UserEntity;
import com.marcohc.architecture.rx.data.net.ServiceFactory;
import java.util.List;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable; | package com.marcohc.architecture.app.data.datastore.user;
/**
* Users without pictures data store.
* <p>
* It uses a random user API for it
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public class UsersWithoutPictureDataStore implements UserCloudDataStore {
private static final String USERS_WITHOUT_PICTURES_URL = "http://jsonplaceholder.typicode.com/";
@Override
public Observable<List<UserEntity>> getAll() {
| // Path: app/src/main/java/com/marcohc/architecture/app/data/service/user/UsersWithoutPictureService.java
// public interface UsersWithoutPictureService {
//
// /**
// * Get users without picture.
// *
// * @return the observable with users without picture
// */
// @GET("users")
// Observable<List<UserEntity>> getAll();
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/domain/entity/UserEntity.java
// public class UserEntity implements Entity {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserEntity() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
//
// }
//
// Path: rest/src/main/java/com/marcohc/architecture/rx/data/net/ServiceFactory.java
// public final class ServiceFactory {
//
// private static final int CONNECTION_TIME_OUT = 10;
// private static final int WRITE_TIME_OUT = 10;
// private static final int READ_TIME_OUT = 10;
//
// // No need to instantiate this class.
// private ServiceFactory() {
// }
//
// /**
// * Create service with the given parameters.
// *
// * @param serviceClass the service class
// * @param factory the converter factory
// * @param baseUrl the base url
// * @param <S> the service class
// * @return an instance of the service with the specific type
// */
// public static <S> S createService(Class<S> serviceClass, Converter.Factory factory, String baseUrl) {
// return createService(serviceClass, factory, null, baseUrl);
// }
//
// /**
// * Create service with the given parameters.
// *
// * @param serviceClass the service class
// * @param factory the converter factory
// * @param adapter the response adapter
// * @param baseUrl the base url
// * @param <S> the service class
// * @return an instance of the service with the specific type
// */
// public static <S> S createService(Class<S> serviceClass, Converter.Factory factory, @Nullable CallAdapter.Factory adapter, String baseUrl) {
// OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder()
// .connectTimeout(CONNECTION_TIME_OUT, TimeUnit.SECONDS)
// .writeTimeout(WRITE_TIME_OUT, TimeUnit.SECONDS)
// .readTimeout(READ_TIME_OUT, TimeUnit.SECONDS);
//
// // Add logging
// HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
// httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
// okHttpClientBuilder.addInterceptor(httpLoggingInterceptor);
//
// Retrofit.Builder builder = new Retrofit.Builder()
// .baseUrl(baseUrl)
// .addConverterFactory(factory)
// .client(okHttpClientBuilder.build());
//
// if (adapter != null) {
// builder.addCallAdapterFactory(adapter);
// }
//
// Retrofit retrofit = builder.build();
//
// return retrofit.create(serviceClass);
// }
//
// }
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UsersWithoutPictureDataStore.java
import com.marcohc.architecture.app.data.service.user.UsersWithoutPictureService;
import com.marcohc.architecture.app.domain.entity.UserEntity;
import com.marcohc.architecture.rx.data.net.ServiceFactory;
import java.util.List;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
package com.marcohc.architecture.app.data.datastore.user;
/**
* Users without pictures data store.
* <p>
* It uses a random user API for it
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public class UsersWithoutPictureDataStore implements UserCloudDataStore {
private static final String USERS_WITHOUT_PICTURES_URL = "http://jsonplaceholder.typicode.com/";
@Override
public Observable<List<UserEntity>> getAll() {
| UsersWithoutPictureService service = ServiceFactory.createService( |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/presentation/story/user/userlist/viewholder/UserViewHolder.java | // Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/adapter/BaseViewHolder.java
// public abstract class BaseViewHolder<M extends Model> {
//
// private BaseListAdapter.ChildViewClickListener mListener;
//
// protected void onChildViewClick(View view, int position) {
// if (mListener != null) {
// mListener.onChildViewClick(view, position);
// }
// }
//
// /**
// * Called by the adaper to set up the view.
// *
// * @param context the context
// * @param model the model
// * @param position the position
// */
// protected abstract void setUpView(Context context, M model, int position);
//
// void bindViews(View view, BaseListAdapter.ChildViewClickListener listener) {
// this.mListener = listener;
// ButterKnife.bind(this, view);
// }
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/domain/model/UserModel.java
// public class UserModel implements Model {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserModel() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
// }
//
// Path: common/src/main/java/com/marcohc/architecture/common/util/helper/StringUtils.java
// public final class StringUtils {
//
// private static final String EMAIL_PATTERN = "^[\\w!#$%&'*+/=?`{|}~^-]+(?:\\.[\\w!#$%&'*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$";
// private static Pattern pattern;
//
// private StringUtils() {
// }
//
// /**
// * Validate hex with regular expression
// *
// * @param email hex for validation
// * @return true valid hex, false invalid hex
// */
// public static boolean isEmailValid(@NonNull final String email) {
// Preconditions.checkNotNull(email, "email");
// boolean isValid = false;
// if (pattern == null) {
// pattern = Pattern.compile(EMAIL_PATTERN);
// }
// isValid = pattern.matcher(email).matches();
// return isValid;
// }
//
// /**
// * Check if the parameters is blank.
// *
// * @param text the text to check
// * @return true if is blank, false otherwise
// */
// public static boolean isBlank(@Nullable final CharSequence text) {
// return text == null || text.toString().trim().isEmpty();
// }
//
// /**
// * Check if the parameters is blank.
// *
// * @param text the text to check
// * @return true if is blank, false otherwise
// */
// public static boolean isBlank(@Nullable final String text) {
// return text == null || text.trim().isEmpty();
// }
//
// @NonNull
// public static String getFirstCapitalize(@NonNull String text) {
// Preconditions.checkNotNull(text, "text");
// StringBuilder textCapitalize = new StringBuilder();
// if (!text.isEmpty()) {
// textCapitalize.append(text.substring(0, 1).toUpperCase()).append(text.substring(1, text.length()));
// }
// return textCapitalize.toString();
// }
//
// @NonNull
// public static String getAllCapitalize(@NonNull String text) {
// Preconditions.checkNotNull(text, "text");
// StringBuilder textCapitalize = new StringBuilder();
// if (!text.isEmpty()) {
// for (int i = 0; i < text.length(); i++) {
// textCapitalize.append(String.valueOf(text.charAt(i)).toUpperCase());
// }
// }
// return textCapitalize.toString();
// }
//
// }
| import android.content.Context;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.marcohc.architecture.aca.presentation.adapter.BaseViewHolder;
import com.marcohc.architecture.app.R;
import com.marcohc.architecture.app.domain.model.UserModel;
import com.marcohc.architecture.common.util.helper.StringUtils;
import butterknife.BindView;
import butterknife.OnClick; | package com.marcohc.architecture.app.presentation.story.user.userlist.viewholder;
/**
* View holder of a {@link UserModel}.
*/
public class UserViewHolder extends BaseViewHolder<UserModel> {
@BindView(R.id.userImageView)
ImageView mUserImageView;
@BindView(R.id.usernameTextView)
TextView mUsernameTextView;
@BindView(R.id.emailTextView)
TextView mEmailTextView;
// Class
private int mPosition;
@Override
public void setUpView(Context context, UserModel model, int position) {
String image = model.getPictureUrl();
this.mPosition = position; | // Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/adapter/BaseViewHolder.java
// public abstract class BaseViewHolder<M extends Model> {
//
// private BaseListAdapter.ChildViewClickListener mListener;
//
// protected void onChildViewClick(View view, int position) {
// if (mListener != null) {
// mListener.onChildViewClick(view, position);
// }
// }
//
// /**
// * Called by the adaper to set up the view.
// *
// * @param context the context
// * @param model the model
// * @param position the position
// */
// protected abstract void setUpView(Context context, M model, int position);
//
// void bindViews(View view, BaseListAdapter.ChildViewClickListener listener) {
// this.mListener = listener;
// ButterKnife.bind(this, view);
// }
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/domain/model/UserModel.java
// public class UserModel implements Model {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserModel() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
// }
//
// Path: common/src/main/java/com/marcohc/architecture/common/util/helper/StringUtils.java
// public final class StringUtils {
//
// private static final String EMAIL_PATTERN = "^[\\w!#$%&'*+/=?`{|}~^-]+(?:\\.[\\w!#$%&'*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$";
// private static Pattern pattern;
//
// private StringUtils() {
// }
//
// /**
// * Validate hex with regular expression
// *
// * @param email hex for validation
// * @return true valid hex, false invalid hex
// */
// public static boolean isEmailValid(@NonNull final String email) {
// Preconditions.checkNotNull(email, "email");
// boolean isValid = false;
// if (pattern == null) {
// pattern = Pattern.compile(EMAIL_PATTERN);
// }
// isValid = pattern.matcher(email).matches();
// return isValid;
// }
//
// /**
// * Check if the parameters is blank.
// *
// * @param text the text to check
// * @return true if is blank, false otherwise
// */
// public static boolean isBlank(@Nullable final CharSequence text) {
// return text == null || text.toString().trim().isEmpty();
// }
//
// /**
// * Check if the parameters is blank.
// *
// * @param text the text to check
// * @return true if is blank, false otherwise
// */
// public static boolean isBlank(@Nullable final String text) {
// return text == null || text.trim().isEmpty();
// }
//
// @NonNull
// public static String getFirstCapitalize(@NonNull String text) {
// Preconditions.checkNotNull(text, "text");
// StringBuilder textCapitalize = new StringBuilder();
// if (!text.isEmpty()) {
// textCapitalize.append(text.substring(0, 1).toUpperCase()).append(text.substring(1, text.length()));
// }
// return textCapitalize.toString();
// }
//
// @NonNull
// public static String getAllCapitalize(@NonNull String text) {
// Preconditions.checkNotNull(text, "text");
// StringBuilder textCapitalize = new StringBuilder();
// if (!text.isEmpty()) {
// for (int i = 0; i < text.length(); i++) {
// textCapitalize.append(String.valueOf(text.charAt(i)).toUpperCase());
// }
// }
// return textCapitalize.toString();
// }
//
// }
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/story/user/userlist/viewholder/UserViewHolder.java
import android.content.Context;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.marcohc.architecture.aca.presentation.adapter.BaseViewHolder;
import com.marcohc.architecture.app.R;
import com.marcohc.architecture.app.domain.model.UserModel;
import com.marcohc.architecture.common.util.helper.StringUtils;
import butterknife.BindView;
import butterknife.OnClick;
package com.marcohc.architecture.app.presentation.story.user.userlist.viewholder;
/**
* View holder of a {@link UserModel}.
*/
public class UserViewHolder extends BaseViewHolder<UserModel> {
@BindView(R.id.userImageView)
ImageView mUserImageView;
@BindView(R.id.usernameTextView)
TextView mUsernameTextView;
@BindView(R.id.emailTextView)
TextView mEmailTextView;
// Class
private int mPosition;
@Override
public void setUpView(Context context, UserModel model, int position) {
String image = model.getPictureUrl();
this.mPosition = position; | if (!StringUtils.isBlank(image)) { |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/presentation/story/user/userlist/view/UsersListPresenter.java | // Path: app/src/main/java/com/marcohc/architecture/app/domain/model/UserModel.java
// public class UserModel implements Model {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserModel() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
// }
| import com.hannesdorfmann.mosby.mvp.MvpPresenter;
import com.marcohc.architecture.app.domain.model.UserModel; | package com.marcohc.architecture.app.presentation.story.user.userlist.view;
/**
* Presenter interface which displays random users in a list with different display options.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
interface UsersListPresenter extends MvpPresenter<UsersListView> {
void onViewCreated();
void onRefresh();
| // Path: app/src/main/java/com/marcohc/architecture/app/domain/model/UserModel.java
// public class UserModel implements Model {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserModel() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
// }
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/story/user/userlist/view/UsersListPresenter.java
import com.hannesdorfmann.mosby.mvp.MvpPresenter;
import com.marcohc.architecture.app.domain.model.UserModel;
package com.marcohc.architecture.app.presentation.story.user.userlist.view;
/**
* Presenter interface which displays random users in a list with different display options.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
interface UsersListPresenter extends MvpPresenter<UsersListView> {
void onViewCreated();
void onRefresh();
| void onItemClick(UserModel model); |
marcohc/android-clean-architecture | bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/presentation/mvp/BaseBusMvpPresenter.java | // Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/domain/exception/DomainException.java
// public class DomainException extends Exception {
//
// public DomainException() {
// }
//
// public DomainException(String detailMessage) {
// super(detailMessage);
// }
//
// public DomainException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public DomainException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/domain/interactor/BusUseCase.java
// public interface BusUseCase {
//
// Object execute();
//
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpPresenter.java
// public abstract class BaseMvpPresenter<V extends BaseMvpView> extends MvpNullObjectBasePresenter<V> {
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpView.java
// public interface BaseMvpView extends MvpView {
//
// }
//
// Path: common/src/main/java/com/marcohc/architecture/common/thread/JobExecutor.java
// public final class JobExecutor {
//
// private static final int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
// private static final int CORE_POOL_SIZE = NUMBER_OF_CORES * 2;
// private static final int MAX_POOL_SIZE = Integer.MAX_VALUE;
// private static final int KEEP_ALIVE_TIME = 10;
// private static final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;
// private static final ThreadPoolExecutor threadPoolExecutor;
//
// static {
// ThreadFactory threadFactory = new JobThreadFactory();
// BlockingQueue<Runnable> linkedBlockingQueue = new LinkedBlockingQueue<>();
// threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, linkedBlockingQueue, threadFactory);
// }
//
// private JobExecutor() {
// }
//
// public static void execute(@NonNull Runnable runnable) {
// Preconditions.checkNotNull(runnable, "runnable");
// threadPoolExecutor.execute(runnable);
// }
//
// public static ThreadPoolExecutor getThreadPoolExecutor() {
// return threadPoolExecutor;
// }
//
// }
| import android.support.annotation.NonNull;
import android.support.annotation.UiThread;
import com.marcohc.architecture.aca.presentation.bus.domain.exception.DomainException;
import com.marcohc.architecture.aca.presentation.bus.domain.interactor.BusUseCase;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpPresenter;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpView;
import com.marcohc.architecture.common.thread.JobExecutor;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import timber.log.Timber; | package com.marcohc.architecture.aca.presentation.bus.presentation.mvp;
public abstract class BaseBusMvpPresenter<V extends BaseMvpView> extends BaseMvpPresenter<V> {
/**
* Executes a use case using a ThreadPool.
* <p>
* It'll be executed in the pool thread.
*
* @param useCase use case to execute
*/
@UiThread | // Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/domain/exception/DomainException.java
// public class DomainException extends Exception {
//
// public DomainException() {
// }
//
// public DomainException(String detailMessage) {
// super(detailMessage);
// }
//
// public DomainException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public DomainException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/domain/interactor/BusUseCase.java
// public interface BusUseCase {
//
// Object execute();
//
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpPresenter.java
// public abstract class BaseMvpPresenter<V extends BaseMvpView> extends MvpNullObjectBasePresenter<V> {
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpView.java
// public interface BaseMvpView extends MvpView {
//
// }
//
// Path: common/src/main/java/com/marcohc/architecture/common/thread/JobExecutor.java
// public final class JobExecutor {
//
// private static final int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
// private static final int CORE_POOL_SIZE = NUMBER_OF_CORES * 2;
// private static final int MAX_POOL_SIZE = Integer.MAX_VALUE;
// private static final int KEEP_ALIVE_TIME = 10;
// private static final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;
// private static final ThreadPoolExecutor threadPoolExecutor;
//
// static {
// ThreadFactory threadFactory = new JobThreadFactory();
// BlockingQueue<Runnable> linkedBlockingQueue = new LinkedBlockingQueue<>();
// threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, linkedBlockingQueue, threadFactory);
// }
//
// private JobExecutor() {
// }
//
// public static void execute(@NonNull Runnable runnable) {
// Preconditions.checkNotNull(runnable, "runnable");
// threadPoolExecutor.execute(runnable);
// }
//
// public static ThreadPoolExecutor getThreadPoolExecutor() {
// return threadPoolExecutor;
// }
//
// }
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/presentation/mvp/BaseBusMvpPresenter.java
import android.support.annotation.NonNull;
import android.support.annotation.UiThread;
import com.marcohc.architecture.aca.presentation.bus.domain.exception.DomainException;
import com.marcohc.architecture.aca.presentation.bus.domain.interactor.BusUseCase;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpPresenter;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpView;
import com.marcohc.architecture.common.thread.JobExecutor;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import timber.log.Timber;
package com.marcohc.architecture.aca.presentation.bus.presentation.mvp;
public abstract class BaseBusMvpPresenter<V extends BaseMvpView> extends BaseMvpPresenter<V> {
/**
* Executes a use case using a ThreadPool.
* <p>
* It'll be executed in the pool thread.
*
* @param useCase use case to execute
*/
@UiThread | protected void executeUseCase(@NonNull final BusUseCase useCase) { |
marcohc/android-clean-architecture | bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/presentation/mvp/BaseBusMvpPresenter.java | // Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/domain/exception/DomainException.java
// public class DomainException extends Exception {
//
// public DomainException() {
// }
//
// public DomainException(String detailMessage) {
// super(detailMessage);
// }
//
// public DomainException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public DomainException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/domain/interactor/BusUseCase.java
// public interface BusUseCase {
//
// Object execute();
//
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpPresenter.java
// public abstract class BaseMvpPresenter<V extends BaseMvpView> extends MvpNullObjectBasePresenter<V> {
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpView.java
// public interface BaseMvpView extends MvpView {
//
// }
//
// Path: common/src/main/java/com/marcohc/architecture/common/thread/JobExecutor.java
// public final class JobExecutor {
//
// private static final int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
// private static final int CORE_POOL_SIZE = NUMBER_OF_CORES * 2;
// private static final int MAX_POOL_SIZE = Integer.MAX_VALUE;
// private static final int KEEP_ALIVE_TIME = 10;
// private static final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;
// private static final ThreadPoolExecutor threadPoolExecutor;
//
// static {
// ThreadFactory threadFactory = new JobThreadFactory();
// BlockingQueue<Runnable> linkedBlockingQueue = new LinkedBlockingQueue<>();
// threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, linkedBlockingQueue, threadFactory);
// }
//
// private JobExecutor() {
// }
//
// public static void execute(@NonNull Runnable runnable) {
// Preconditions.checkNotNull(runnable, "runnable");
// threadPoolExecutor.execute(runnable);
// }
//
// public static ThreadPoolExecutor getThreadPoolExecutor() {
// return threadPoolExecutor;
// }
//
// }
| import android.support.annotation.NonNull;
import android.support.annotation.UiThread;
import com.marcohc.architecture.aca.presentation.bus.domain.exception.DomainException;
import com.marcohc.architecture.aca.presentation.bus.domain.interactor.BusUseCase;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpPresenter;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpView;
import com.marcohc.architecture.common.thread.JobExecutor;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import timber.log.Timber; | package com.marcohc.architecture.aca.presentation.bus.presentation.mvp;
public abstract class BaseBusMvpPresenter<V extends BaseMvpView> extends BaseMvpPresenter<V> {
/**
* Executes a use case using a ThreadPool.
* <p>
* It'll be executed in the pool thread.
*
* @param useCase use case to execute
*/
@UiThread
protected void executeUseCase(@NonNull final BusUseCase useCase) {
Timber.d("executeUseCase: %s", useCase.getClass().getSimpleName()); | // Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/domain/exception/DomainException.java
// public class DomainException extends Exception {
//
// public DomainException() {
// }
//
// public DomainException(String detailMessage) {
// super(detailMessage);
// }
//
// public DomainException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public DomainException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/domain/interactor/BusUseCase.java
// public interface BusUseCase {
//
// Object execute();
//
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpPresenter.java
// public abstract class BaseMvpPresenter<V extends BaseMvpView> extends MvpNullObjectBasePresenter<V> {
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpView.java
// public interface BaseMvpView extends MvpView {
//
// }
//
// Path: common/src/main/java/com/marcohc/architecture/common/thread/JobExecutor.java
// public final class JobExecutor {
//
// private static final int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
// private static final int CORE_POOL_SIZE = NUMBER_OF_CORES * 2;
// private static final int MAX_POOL_SIZE = Integer.MAX_VALUE;
// private static final int KEEP_ALIVE_TIME = 10;
// private static final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;
// private static final ThreadPoolExecutor threadPoolExecutor;
//
// static {
// ThreadFactory threadFactory = new JobThreadFactory();
// BlockingQueue<Runnable> linkedBlockingQueue = new LinkedBlockingQueue<>();
// threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, linkedBlockingQueue, threadFactory);
// }
//
// private JobExecutor() {
// }
//
// public static void execute(@NonNull Runnable runnable) {
// Preconditions.checkNotNull(runnable, "runnable");
// threadPoolExecutor.execute(runnable);
// }
//
// public static ThreadPoolExecutor getThreadPoolExecutor() {
// return threadPoolExecutor;
// }
//
// }
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/presentation/mvp/BaseBusMvpPresenter.java
import android.support.annotation.NonNull;
import android.support.annotation.UiThread;
import com.marcohc.architecture.aca.presentation.bus.domain.exception.DomainException;
import com.marcohc.architecture.aca.presentation.bus.domain.interactor.BusUseCase;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpPresenter;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpView;
import com.marcohc.architecture.common.thread.JobExecutor;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import timber.log.Timber;
package com.marcohc.architecture.aca.presentation.bus.presentation.mvp;
public abstract class BaseBusMvpPresenter<V extends BaseMvpView> extends BaseMvpPresenter<V> {
/**
* Executes a use case using a ThreadPool.
* <p>
* It'll be executed in the pool thread.
*
* @param useCase use case to execute
*/
@UiThread
protected void executeUseCase(@NonNull final BusUseCase useCase) {
Timber.d("executeUseCase: %s", useCase.getClass().getSimpleName()); | JobExecutor.execute(new Runnable() { |
marcohc/android-clean-architecture | bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/presentation/mvp/BaseBusMvpPresenter.java | // Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/domain/exception/DomainException.java
// public class DomainException extends Exception {
//
// public DomainException() {
// }
//
// public DomainException(String detailMessage) {
// super(detailMessage);
// }
//
// public DomainException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public DomainException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/domain/interactor/BusUseCase.java
// public interface BusUseCase {
//
// Object execute();
//
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpPresenter.java
// public abstract class BaseMvpPresenter<V extends BaseMvpView> extends MvpNullObjectBasePresenter<V> {
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpView.java
// public interface BaseMvpView extends MvpView {
//
// }
//
// Path: common/src/main/java/com/marcohc/architecture/common/thread/JobExecutor.java
// public final class JobExecutor {
//
// private static final int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
// private static final int CORE_POOL_SIZE = NUMBER_OF_CORES * 2;
// private static final int MAX_POOL_SIZE = Integer.MAX_VALUE;
// private static final int KEEP_ALIVE_TIME = 10;
// private static final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;
// private static final ThreadPoolExecutor threadPoolExecutor;
//
// static {
// ThreadFactory threadFactory = new JobThreadFactory();
// BlockingQueue<Runnable> linkedBlockingQueue = new LinkedBlockingQueue<>();
// threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, linkedBlockingQueue, threadFactory);
// }
//
// private JobExecutor() {
// }
//
// public static void execute(@NonNull Runnable runnable) {
// Preconditions.checkNotNull(runnable, "runnable");
// threadPoolExecutor.execute(runnable);
// }
//
// public static ThreadPoolExecutor getThreadPoolExecutor() {
// return threadPoolExecutor;
// }
//
// }
| import android.support.annotation.NonNull;
import android.support.annotation.UiThread;
import com.marcohc.architecture.aca.presentation.bus.domain.exception.DomainException;
import com.marcohc.architecture.aca.presentation.bus.domain.interactor.BusUseCase;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpPresenter;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpView;
import com.marcohc.architecture.common.thread.JobExecutor;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import timber.log.Timber; | package com.marcohc.architecture.aca.presentation.bus.presentation.mvp;
public abstract class BaseBusMvpPresenter<V extends BaseMvpView> extends BaseMvpPresenter<V> {
/**
* Executes a use case using a ThreadPool.
* <p>
* It'll be executed in the pool thread.
*
* @param useCase use case to execute
*/
@UiThread
protected void executeUseCase(@NonNull final BusUseCase useCase) {
Timber.d("executeUseCase: %s", useCase.getClass().getSimpleName());
JobExecutor.execute(new Runnable() {
@Override
public void run() {
useCase.execute();
}
});
}
@Subscribe(threadMode = ThreadMode.MAIN) | // Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/domain/exception/DomainException.java
// public class DomainException extends Exception {
//
// public DomainException() {
// }
//
// public DomainException(String detailMessage) {
// super(detailMessage);
// }
//
// public DomainException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public DomainException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/domain/interactor/BusUseCase.java
// public interface BusUseCase {
//
// Object execute();
//
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpPresenter.java
// public abstract class BaseMvpPresenter<V extends BaseMvpView> extends MvpNullObjectBasePresenter<V> {
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpView.java
// public interface BaseMvpView extends MvpView {
//
// }
//
// Path: common/src/main/java/com/marcohc/architecture/common/thread/JobExecutor.java
// public final class JobExecutor {
//
// private static final int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
// private static final int CORE_POOL_SIZE = NUMBER_OF_CORES * 2;
// private static final int MAX_POOL_SIZE = Integer.MAX_VALUE;
// private static final int KEEP_ALIVE_TIME = 10;
// private static final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;
// private static final ThreadPoolExecutor threadPoolExecutor;
//
// static {
// ThreadFactory threadFactory = new JobThreadFactory();
// BlockingQueue<Runnable> linkedBlockingQueue = new LinkedBlockingQueue<>();
// threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, linkedBlockingQueue, threadFactory);
// }
//
// private JobExecutor() {
// }
//
// public static void execute(@NonNull Runnable runnable) {
// Preconditions.checkNotNull(runnable, "runnable");
// threadPoolExecutor.execute(runnable);
// }
//
// public static ThreadPoolExecutor getThreadPoolExecutor() {
// return threadPoolExecutor;
// }
//
// }
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/presentation/mvp/BaseBusMvpPresenter.java
import android.support.annotation.NonNull;
import android.support.annotation.UiThread;
import com.marcohc.architecture.aca.presentation.bus.domain.exception.DomainException;
import com.marcohc.architecture.aca.presentation.bus.domain.interactor.BusUseCase;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpPresenter;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpView;
import com.marcohc.architecture.common.thread.JobExecutor;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import timber.log.Timber;
package com.marcohc.architecture.aca.presentation.bus.presentation.mvp;
public abstract class BaseBusMvpPresenter<V extends BaseMvpView> extends BaseMvpPresenter<V> {
/**
* Executes a use case using a ThreadPool.
* <p>
* It'll be executed in the pool thread.
*
* @param useCase use case to execute
*/
@UiThread
protected void executeUseCase(@NonNull final BusUseCase useCase) {
Timber.d("executeUseCase: %s", useCase.getClass().getSimpleName());
JobExecutor.execute(new Runnable() {
@Override
public void run() {
useCase.execute();
}
});
}
@Subscribe(threadMode = ThreadMode.MAIN) | public void onDomainException(DomainException domainException) { |
marcohc/android-clean-architecture | common/src/main/java/com/marcohc/architecture/common/thread/JobExecutor.java | // Path: common/src/main/java/com/marcohc/architecture/common/util/utils/Preconditions.java
// public final class Preconditions {
//
// private Preconditions() {
// // no-op
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @param name the variable name
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference, String name) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException(name + " must not be null.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @param name the variable name
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression, @Nullable String name) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be false.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures not blank in parameters.
// *
// * @param value the value to check
// * @param name the name you want to display in the logs
// * @param <T> the type of the value
// * @return the value you want to check
// */
// @NonNull
// public static <T extends CharSequence> T nonBlank(@Nullable T value, String name) {
// if (StringUtils.isBlank(value)) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be blank.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return value;
// }
//
// @NonNull
// private static StackTraceElement[] getStackTrace(@NonNull Exception exception) {
// final StackTraceElement[] sourceStack = exception.getStackTrace();
//
// final StackTraceElement[] updatedStack = new StackTraceElement[sourceStack.length - 1];
// System.arraycopy(sourceStack, 1, updatedStack, 0, updatedStack.length);
//
// return updatedStack;
// }
// }
| import android.support.annotation.NonNull;
import com.marcohc.architecture.common.util.utils.Preconditions;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; | package com.marcohc.architecture.common.thread;
/**
* Executor with a thread pool.
*
* @author Marco Hernaiz
* @since 09/08/16
*/
public final class JobExecutor {
private static final int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = NUMBER_OF_CORES * 2;
private static final int MAX_POOL_SIZE = Integer.MAX_VALUE;
private static final int KEEP_ALIVE_TIME = 10;
private static final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;
private static final ThreadPoolExecutor threadPoolExecutor;
static {
ThreadFactory threadFactory = new JobThreadFactory();
BlockingQueue<Runnable> linkedBlockingQueue = new LinkedBlockingQueue<>();
threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, linkedBlockingQueue, threadFactory);
}
private JobExecutor() {
}
public static void execute(@NonNull Runnable runnable) { | // Path: common/src/main/java/com/marcohc/architecture/common/util/utils/Preconditions.java
// public final class Preconditions {
//
// private Preconditions() {
// // no-op
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @param name the variable name
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference, String name) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException(name + " must not be null.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @param name the variable name
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression, @Nullable String name) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be false.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures not blank in parameters.
// *
// * @param value the value to check
// * @param name the name you want to display in the logs
// * @param <T> the type of the value
// * @return the value you want to check
// */
// @NonNull
// public static <T extends CharSequence> T nonBlank(@Nullable T value, String name) {
// if (StringUtils.isBlank(value)) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be blank.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return value;
// }
//
// @NonNull
// private static StackTraceElement[] getStackTrace(@NonNull Exception exception) {
// final StackTraceElement[] sourceStack = exception.getStackTrace();
//
// final StackTraceElement[] updatedStack = new StackTraceElement[sourceStack.length - 1];
// System.arraycopy(sourceStack, 1, updatedStack, 0, updatedStack.length);
//
// return updatedStack;
// }
// }
// Path: common/src/main/java/com/marcohc/architecture/common/thread/JobExecutor.java
import android.support.annotation.NonNull;
import com.marcohc.architecture.common.util.utils.Preconditions;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
package com.marcohc.architecture.common.thread;
/**
* Executor with a thread pool.
*
* @author Marco Hernaiz
* @since 09/08/16
*/
public final class JobExecutor {
private static final int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = NUMBER_OF_CORES * 2;
private static final int MAX_POOL_SIZE = Integer.MAX_VALUE;
private static final int KEEP_ALIVE_TIME = 10;
private static final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;
private static final ThreadPoolExecutor threadPoolExecutor;
static {
ThreadFactory threadFactory = new JobThreadFactory();
BlockingQueue<Runnable> linkedBlockingQueue = new LinkedBlockingQueue<>();
threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, linkedBlockingQueue, threadFactory);
}
private JobExecutor() {
}
public static void execute(@NonNull Runnable runnable) { | Preconditions.checkNotNull(runnable, "runnable"); |
marcohc/android-clean-architecture | security/src/main/java/com/marcohc/architecture/common/util/helper/SecurePreferencesServiceImpl.java | // Path: common/src/main/java/com/marcohc/architecture/common/service/preferences/PreferencesService.java
// public interface PreferencesService {
//
// void clear();
//
// boolean getBoolean(@NonNull String key, boolean defaultValue);
//
// float getFloat(@NonNull String key, float defaultValue);
//
// int getInt(@NonNull String key, int defaultValue);
//
// long getLong(@NonNull String key, long defaultValue);
//
// @Nullable
// String getString(@NonNull String key, String defaultValue);
//
// void putBoolean(@NonNull String key, boolean value);
//
// void putFloat(@NonNull String key, float value);
//
// void putInt(@NonNull String key, int value);
//
// void putLong(@NonNull String key, long value);
//
// void putString(@NonNull String key, String value);
//
// void remove(@NonNull String key);
// }
//
// Path: common/src/main/java/com/marcohc/architecture/common/util/utils/Preconditions.java
// public final class Preconditions {
//
// private Preconditions() {
// // no-op
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @param name the variable name
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference, String name) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException(name + " must not be null.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @param name the variable name
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression, @Nullable String name) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be false.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures not blank in parameters.
// *
// * @param value the value to check
// * @param name the name you want to display in the logs
// * @param <T> the type of the value
// * @return the value you want to check
// */
// @NonNull
// public static <T extends CharSequence> T nonBlank(@Nullable T value, String name) {
// if (StringUtils.isBlank(value)) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be blank.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return value;
// }
//
// @NonNull
// private static StackTraceElement[] getStackTrace(@NonNull Exception exception) {
// final StackTraceElement[] sourceStack = exception.getStackTrace();
//
// final StackTraceElement[] updatedStack = new StackTraceElement[sourceStack.length - 1];
// System.arraycopy(sourceStack, 1, updatedStack, 0, updatedStack.length);
//
// return updatedStack;
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.marcohc.architecture.common.service.preferences.PreferencesService;
import com.marcohc.architecture.common.util.utils.Preconditions; | /*
* Copyright (C) 2016 Marco Hernaiz Cao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marcohc.architecture.common.util.helper;
/**
* Used for managing shared preferences with encryption.
*/
public class SecurePreferencesServiceImpl implements PreferencesService {
private final SharedPreferences sharedPreferences;
public SecurePreferencesServiceImpl(Context context) {
String defaultName = String.format("%s_%s", context.getPackageName(), "preferences");
String uniqueId = getUniqueId();
sharedPreferences = new com.securepreferences.SecurePreferences(context, uniqueId, defaultName);
}
@Override
public void clear() {
sharedPreferences.edit().clear().apply();
}
@Override
public boolean getBoolean(@NonNull String key, boolean defaultValue) { | // Path: common/src/main/java/com/marcohc/architecture/common/service/preferences/PreferencesService.java
// public interface PreferencesService {
//
// void clear();
//
// boolean getBoolean(@NonNull String key, boolean defaultValue);
//
// float getFloat(@NonNull String key, float defaultValue);
//
// int getInt(@NonNull String key, int defaultValue);
//
// long getLong(@NonNull String key, long defaultValue);
//
// @Nullable
// String getString(@NonNull String key, String defaultValue);
//
// void putBoolean(@NonNull String key, boolean value);
//
// void putFloat(@NonNull String key, float value);
//
// void putInt(@NonNull String key, int value);
//
// void putLong(@NonNull String key, long value);
//
// void putString(@NonNull String key, String value);
//
// void remove(@NonNull String key);
// }
//
// Path: common/src/main/java/com/marcohc/architecture/common/util/utils/Preconditions.java
// public final class Preconditions {
//
// private Preconditions() {
// // no-op
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @param name the variable name
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference, String name) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException(name + " must not be null.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @param name the variable name
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression, @Nullable String name) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be false.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures not blank in parameters.
// *
// * @param value the value to check
// * @param name the name you want to display in the logs
// * @param <T> the type of the value
// * @return the value you want to check
// */
// @NonNull
// public static <T extends CharSequence> T nonBlank(@Nullable T value, String name) {
// if (StringUtils.isBlank(value)) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be blank.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return value;
// }
//
// @NonNull
// private static StackTraceElement[] getStackTrace(@NonNull Exception exception) {
// final StackTraceElement[] sourceStack = exception.getStackTrace();
//
// final StackTraceElement[] updatedStack = new StackTraceElement[sourceStack.length - 1];
// System.arraycopy(sourceStack, 1, updatedStack, 0, updatedStack.length);
//
// return updatedStack;
// }
// }
// Path: security/src/main/java/com/marcohc/architecture/common/util/helper/SecurePreferencesServiceImpl.java
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.marcohc.architecture.common.service.preferences.PreferencesService;
import com.marcohc.architecture.common.util.utils.Preconditions;
/*
* Copyright (C) 2016 Marco Hernaiz Cao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marcohc.architecture.common.util.helper;
/**
* Used for managing shared preferences with encryption.
*/
public class SecurePreferencesServiceImpl implements PreferencesService {
private final SharedPreferences sharedPreferences;
public SecurePreferencesServiceImpl(Context context) {
String defaultName = String.format("%s_%s", context.getPackageName(), "preferences");
String uniqueId = getUniqueId();
sharedPreferences = new com.securepreferences.SecurePreferences(context, uniqueId, defaultName);
}
@Override
public void clear() {
sharedPreferences.edit().clear().apply();
}
@Override
public boolean getBoolean(@NonNull String key, boolean defaultValue) { | return sharedPreferences.getBoolean(Preconditions.checkNotNull(key), defaultValue); |
marcohc/android-clean-architecture | service/src/main/java/com/marcohc/architecture/common/service/appinfo/AppInfoServiceImpl.java | // Path: common/src/main/java/com/marcohc/architecture/common/service/preferences/PreferencesService.java
// public interface PreferencesService {
//
// void clear();
//
// boolean getBoolean(@NonNull String key, boolean defaultValue);
//
// float getFloat(@NonNull String key, float defaultValue);
//
// int getInt(@NonNull String key, int defaultValue);
//
// long getLong(@NonNull String key, long defaultValue);
//
// @Nullable
// String getString(@NonNull String key, String defaultValue);
//
// void putBoolean(@NonNull String key, boolean value);
//
// void putFloat(@NonNull String key, float value);
//
// void putInt(@NonNull String key, int value);
//
// void putLong(@NonNull String key, long value);
//
// void putString(@NonNull String key, String value);
//
// void remove(@NonNull String key);
// }
| import com.marcohc.architecture.common.service.preferences.PreferencesService;
import java.util.Calendar; | /*
* Copyright (C) 2016 Marco Hernaiz Cao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marcohc.architecture.common.service.appinfo;
/**
* Class to retrieve information from user or device.
*/
public class AppInfoServiceImpl implements AppInfoService {
private static final String IS_FIRST_APP_EXECUTION = "is_first_app_start";
private static final String LAST_APP_EXECUTION = "last_app_execution"; | // Path: common/src/main/java/com/marcohc/architecture/common/service/preferences/PreferencesService.java
// public interface PreferencesService {
//
// void clear();
//
// boolean getBoolean(@NonNull String key, boolean defaultValue);
//
// float getFloat(@NonNull String key, float defaultValue);
//
// int getInt(@NonNull String key, int defaultValue);
//
// long getLong(@NonNull String key, long defaultValue);
//
// @Nullable
// String getString(@NonNull String key, String defaultValue);
//
// void putBoolean(@NonNull String key, boolean value);
//
// void putFloat(@NonNull String key, float value);
//
// void putInt(@NonNull String key, int value);
//
// void putLong(@NonNull String key, long value);
//
// void putString(@NonNull String key, String value);
//
// void remove(@NonNull String key);
// }
// Path: service/src/main/java/com/marcohc/architecture/common/service/appinfo/AppInfoServiceImpl.java
import com.marcohc.architecture.common.service.preferences.PreferencesService;
import java.util.Calendar;
/*
* Copyright (C) 2016 Marco Hernaiz Cao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marcohc.architecture.common.service.appinfo;
/**
* Class to retrieve information from user or device.
*/
public class AppInfoServiceImpl implements AppInfoService {
private static final String IS_FIRST_APP_EXECUTION = "is_first_app_start";
private static final String LAST_APP_EXECUTION = "last_app_execution"; | private final PreferencesService mPreferenceService; |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/data/service/user/UsersWithoutPictureService.java | // Path: app/src/main/java/com/marcohc/architecture/app/domain/entity/UserEntity.java
// public class UserEntity implements Entity {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserEntity() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
//
// }
| import rx.Observable;
import com.marcohc.architecture.app.domain.entity.UserEntity;
import java.util.List;
import retrofit2.http.GET; |
package com.marcohc.architecture.app.data.service.user;
/**
* Data source interface without pictures.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public interface UsersWithoutPictureService {
/**
* Get users without picture.
*
* @return the observable with users without picture
*/
@GET("users") | // Path: app/src/main/java/com/marcohc/architecture/app/domain/entity/UserEntity.java
// public class UserEntity implements Entity {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserEntity() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
//
// }
// Path: app/src/main/java/com/marcohc/architecture/app/data/service/user/UsersWithoutPictureService.java
import rx.Observable;
import com.marcohc.architecture.app.domain.entity.UserEntity;
import java.util.List;
import retrofit2.http.GET;
package com.marcohc.architecture.app.data.service.user;
/**
* Data source interface without pictures.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public interface UsersWithoutPictureService {
/**
* Get users without picture.
*
* @return the observable with users without picture
*/
@GET("users") | Observable<List<UserEntity>> getAll(); |
marcohc/android-clean-architecture | bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/domain/interactor/AsynchronousUseCase.java | // Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/data/error/DataException.java
// public class DataException extends Exception {
//
// public DataException() {
// }
//
// public DataException(String detailMessage) {
// super(detailMessage);
// }
//
// public DataException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public DataException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/domain/exception/DomainException.java
// public class DomainException extends Exception {
//
// public DomainException() {
// }
//
// public DomainException(String detailMessage) {
// super(detailMessage);
// }
//
// public DomainException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public DomainException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/common/BusEvent.java
// public interface BusEvent {
// }
//
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/common/BusHandler.java
// public abstract class BusHandler {
//
// public BusHandler() {
// registerToBus();
// }
//
// protected void registerToBus() {
// BusProvider.register(this);
// }
//
// protected void unregisterFromBus() {
// BusProvider.unregister(this);
// }
//
// protected void post(Object busEvent) {
// BusProvider.post(busEvent);
// }
//
// protected void postSticky(Object busEvent) {
// BusProvider.postSticky(busEvent);
// }
// }
| import com.marcohc.architecture.aca.presentation.bus.data.error.DataException;
import com.marcohc.architecture.aca.presentation.bus.domain.exception.DomainException;
import com.marcohc.architecture.aca.presentation.bus.common.BusEvent;
import com.marcohc.architecture.aca.presentation.bus.common.BusHandler;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode; | package com.marcohc.architecture.aca.presentation.bus.domain.interactor;
/**
* This class represents an asynchronous use case connected to the bus.
* Always listening for {@link DataException} which occurs in the data layer
*/
public abstract class AsynchronousUseCase extends BusHandler implements BusUseCase {
protected abstract BusEvent createRequest();
protected abstract BusEvent createResponse();
/**
* Executes the logic of the use case
*
* @return null, the use case is executed asynchronously so the result will be delivered in other ways
*/
@Override
public Void execute() {
BusEvent request = createRequest();
if (request != null) {
post(request);
}
return null;
}
@Subscribe(threadMode = ThreadMode.ASYNC) | // Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/data/error/DataException.java
// public class DataException extends Exception {
//
// public DataException() {
// }
//
// public DataException(String detailMessage) {
// super(detailMessage);
// }
//
// public DataException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public DataException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/domain/exception/DomainException.java
// public class DomainException extends Exception {
//
// public DomainException() {
// }
//
// public DomainException(String detailMessage) {
// super(detailMessage);
// }
//
// public DomainException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public DomainException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/common/BusEvent.java
// public interface BusEvent {
// }
//
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/common/BusHandler.java
// public abstract class BusHandler {
//
// public BusHandler() {
// registerToBus();
// }
//
// protected void registerToBus() {
// BusProvider.register(this);
// }
//
// protected void unregisterFromBus() {
// BusProvider.unregister(this);
// }
//
// protected void post(Object busEvent) {
// BusProvider.post(busEvent);
// }
//
// protected void postSticky(Object busEvent) {
// BusProvider.postSticky(busEvent);
// }
// }
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/domain/interactor/AsynchronousUseCase.java
import com.marcohc.architecture.aca.presentation.bus.data.error.DataException;
import com.marcohc.architecture.aca.presentation.bus.domain.exception.DomainException;
import com.marcohc.architecture.aca.presentation.bus.common.BusEvent;
import com.marcohc.architecture.aca.presentation.bus.common.BusHandler;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
package com.marcohc.architecture.aca.presentation.bus.domain.interactor;
/**
* This class represents an asynchronous use case connected to the bus.
* Always listening for {@link DataException} which occurs in the data layer
*/
public abstract class AsynchronousUseCase extends BusHandler implements BusUseCase {
protected abstract BusEvent createRequest();
protected abstract BusEvent createResponse();
/**
* Executes the logic of the use case
*
* @return null, the use case is executed asynchronously so the result will be delivered in other ways
*/
@Override
public Void execute() {
BusEvent request = createRequest();
if (request != null) {
post(request);
}
return null;
}
@Subscribe(threadMode = ThreadMode.ASYNC) | public void onDataException(DataException dataException) { |
marcohc/android-clean-architecture | bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/domain/interactor/AsynchronousUseCase.java | // Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/data/error/DataException.java
// public class DataException extends Exception {
//
// public DataException() {
// }
//
// public DataException(String detailMessage) {
// super(detailMessage);
// }
//
// public DataException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public DataException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/domain/exception/DomainException.java
// public class DomainException extends Exception {
//
// public DomainException() {
// }
//
// public DomainException(String detailMessage) {
// super(detailMessage);
// }
//
// public DomainException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public DomainException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/common/BusEvent.java
// public interface BusEvent {
// }
//
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/common/BusHandler.java
// public abstract class BusHandler {
//
// public BusHandler() {
// registerToBus();
// }
//
// protected void registerToBus() {
// BusProvider.register(this);
// }
//
// protected void unregisterFromBus() {
// BusProvider.unregister(this);
// }
//
// protected void post(Object busEvent) {
// BusProvider.post(busEvent);
// }
//
// protected void postSticky(Object busEvent) {
// BusProvider.postSticky(busEvent);
// }
// }
| import com.marcohc.architecture.aca.presentation.bus.data.error.DataException;
import com.marcohc.architecture.aca.presentation.bus.domain.exception.DomainException;
import com.marcohc.architecture.aca.presentation.bus.common.BusEvent;
import com.marcohc.architecture.aca.presentation.bus.common.BusHandler;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode; | package com.marcohc.architecture.aca.presentation.bus.domain.interactor;
/**
* This class represents an asynchronous use case connected to the bus.
* Always listening for {@link DataException} which occurs in the data layer
*/
public abstract class AsynchronousUseCase extends BusHandler implements BusUseCase {
protected abstract BusEvent createRequest();
protected abstract BusEvent createResponse();
/**
* Executes the logic of the use case
*
* @return null, the use case is executed asynchronously so the result will be delivered in other ways
*/
@Override
public Void execute() {
BusEvent request = createRequest();
if (request != null) {
post(request);
}
return null;
}
@Subscribe(threadMode = ThreadMode.ASYNC)
public void onDataException(DataException dataException) {
handleDataException(dataException);
}
/**
* Converts the {@link DataException} to {@link DomainException} to be handle by presenter.
* Override this method if you want to customize your data error handling
*/
protected void handleDataException(DataException dataException) { | // Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/data/error/DataException.java
// public class DataException extends Exception {
//
// public DataException() {
// }
//
// public DataException(String detailMessage) {
// super(detailMessage);
// }
//
// public DataException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public DataException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/domain/exception/DomainException.java
// public class DomainException extends Exception {
//
// public DomainException() {
// }
//
// public DomainException(String detailMessage) {
// super(detailMessage);
// }
//
// public DomainException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public DomainException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/common/BusEvent.java
// public interface BusEvent {
// }
//
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/common/BusHandler.java
// public abstract class BusHandler {
//
// public BusHandler() {
// registerToBus();
// }
//
// protected void registerToBus() {
// BusProvider.register(this);
// }
//
// protected void unregisterFromBus() {
// BusProvider.unregister(this);
// }
//
// protected void post(Object busEvent) {
// BusProvider.post(busEvent);
// }
//
// protected void postSticky(Object busEvent) {
// BusProvider.postSticky(busEvent);
// }
// }
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/domain/interactor/AsynchronousUseCase.java
import com.marcohc.architecture.aca.presentation.bus.data.error.DataException;
import com.marcohc.architecture.aca.presentation.bus.domain.exception.DomainException;
import com.marcohc.architecture.aca.presentation.bus.common.BusEvent;
import com.marcohc.architecture.aca.presentation.bus.common.BusHandler;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
package com.marcohc.architecture.aca.presentation.bus.domain.interactor;
/**
* This class represents an asynchronous use case connected to the bus.
* Always listening for {@link DataException} which occurs in the data layer
*/
public abstract class AsynchronousUseCase extends BusHandler implements BusUseCase {
protected abstract BusEvent createRequest();
protected abstract BusEvent createResponse();
/**
* Executes the logic of the use case
*
* @return null, the use case is executed asynchronously so the result will be delivered in other ways
*/
@Override
public Void execute() {
BusEvent request = createRequest();
if (request != null) {
post(request);
}
return null;
}
@Subscribe(threadMode = ThreadMode.ASYNC)
public void onDataException(DataException dataException) {
handleDataException(dataException);
}
/**
* Converts the {@link DataException} to {@link DomainException} to be handle by presenter.
* Override this method if you want to customize your data error handling
*/
protected void handleDataException(DataException dataException) { | DomainException domainException = new DomainException(dataException.getMessage(), dataException.getCause()); |
marcohc/android-clean-architecture | rx/src/main/java/com/marcohc/architecture/rx/domain/interactor/BaseRxUseCase.java | // Path: common/src/main/java/com/marcohc/architecture/common/thread/JobExecutor.java
// public final class JobExecutor {
//
// private static final int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
// private static final int CORE_POOL_SIZE = NUMBER_OF_CORES * 2;
// private static final int MAX_POOL_SIZE = Integer.MAX_VALUE;
// private static final int KEEP_ALIVE_TIME = 10;
// private static final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;
// private static final ThreadPoolExecutor threadPoolExecutor;
//
// static {
// ThreadFactory threadFactory = new JobThreadFactory();
// BlockingQueue<Runnable> linkedBlockingQueue = new LinkedBlockingQueue<>();
// threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, linkedBlockingQueue, threadFactory);
// }
//
// private JobExecutor() {
// }
//
// public static void execute(@NonNull Runnable runnable) {
// Preconditions.checkNotNull(runnable, "runnable");
// threadPoolExecutor.execute(runnable);
// }
//
// public static ThreadPoolExecutor getThreadPoolExecutor() {
// return threadPoolExecutor;
// }
//
// }
//
// Path: common/src/main/java/com/marcohc/architecture/common/util/utils/Preconditions.java
// public final class Preconditions {
//
// private Preconditions() {
// // no-op
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @param name the variable name
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference, String name) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException(name + " must not be null.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @param name the variable name
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression, @Nullable String name) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be false.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures not blank in parameters.
// *
// * @param value the value to check
// * @param name the name you want to display in the logs
// * @param <T> the type of the value
// * @return the value you want to check
// */
// @NonNull
// public static <T extends CharSequence> T nonBlank(@Nullable T value, String name) {
// if (StringUtils.isBlank(value)) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be blank.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return value;
// }
//
// @NonNull
// private static StackTraceElement[] getStackTrace(@NonNull Exception exception) {
// final StackTraceElement[] sourceStack = exception.getStackTrace();
//
// final StackTraceElement[] updatedStack = new StackTraceElement[sourceStack.length - 1];
// System.arraycopy(sourceStack, 1, updatedStack, 0, updatedStack.length);
//
// return updatedStack;
// }
// }
| import android.support.annotation.NonNull;
import com.marcohc.architecture.common.thread.JobExecutor;
import com.marcohc.architecture.common.util.utils.Preconditions;
import rx.Observable;
import rx.Scheduler;
import rx.Subscription;
import rx.subscriptions.Subscriptions; | package com.marcohc.architecture.rx.domain.interactor;
/**
* Base use case which encapsulates the implementation of Rx.
* <p>
* The specific use case "should" be implemented with pure java
*
* @param <M>: the model response you expect to receive in the presentation layer
*/
public abstract class BaseRxUseCase<M> implements RxUseCase<M> {
@NonNull
private Subscription mSubscription = Subscriptions.empty();
/**
* Get the observable from where you want to get the data.
* <p>
*
* @return the observable
*/
@NonNull
protected abstract Observable<M> getObservable();
/**
* Execute the use case. This method is called through {@link JobExecutor},
* but you can override it handle Rx as you like.
*
* @param subscriber the subscriber
* @param subscribeOn "in which thread you want the use case executed"
* @param observeOn "in which thread you want to get the data back"
*/
@SuppressWarnings("unchecked")
@Override
public void execute(@NonNull final SimpleSubscriber<M> subscriber, @NonNull Scheduler subscribeOn, @NonNull Scheduler observeOn) { | // Path: common/src/main/java/com/marcohc/architecture/common/thread/JobExecutor.java
// public final class JobExecutor {
//
// private static final int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
// private static final int CORE_POOL_SIZE = NUMBER_OF_CORES * 2;
// private static final int MAX_POOL_SIZE = Integer.MAX_VALUE;
// private static final int KEEP_ALIVE_TIME = 10;
// private static final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;
// private static final ThreadPoolExecutor threadPoolExecutor;
//
// static {
// ThreadFactory threadFactory = new JobThreadFactory();
// BlockingQueue<Runnable> linkedBlockingQueue = new LinkedBlockingQueue<>();
// threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, linkedBlockingQueue, threadFactory);
// }
//
// private JobExecutor() {
// }
//
// public static void execute(@NonNull Runnable runnable) {
// Preconditions.checkNotNull(runnable, "runnable");
// threadPoolExecutor.execute(runnable);
// }
//
// public static ThreadPoolExecutor getThreadPoolExecutor() {
// return threadPoolExecutor;
// }
//
// }
//
// Path: common/src/main/java/com/marcohc/architecture/common/util/utils/Preconditions.java
// public final class Preconditions {
//
// private Preconditions() {
// // no-op
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @param name the variable name
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference, String name) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException(name + " must not be null.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @param name the variable name
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression, @Nullable String name) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be false.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures not blank in parameters.
// *
// * @param value the value to check
// * @param name the name you want to display in the logs
// * @param <T> the type of the value
// * @return the value you want to check
// */
// @NonNull
// public static <T extends CharSequence> T nonBlank(@Nullable T value, String name) {
// if (StringUtils.isBlank(value)) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be blank.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return value;
// }
//
// @NonNull
// private static StackTraceElement[] getStackTrace(@NonNull Exception exception) {
// final StackTraceElement[] sourceStack = exception.getStackTrace();
//
// final StackTraceElement[] updatedStack = new StackTraceElement[sourceStack.length - 1];
// System.arraycopy(sourceStack, 1, updatedStack, 0, updatedStack.length);
//
// return updatedStack;
// }
// }
// Path: rx/src/main/java/com/marcohc/architecture/rx/domain/interactor/BaseRxUseCase.java
import android.support.annotation.NonNull;
import com.marcohc.architecture.common.thread.JobExecutor;
import com.marcohc.architecture.common.util.utils.Preconditions;
import rx.Observable;
import rx.Scheduler;
import rx.Subscription;
import rx.subscriptions.Subscriptions;
package com.marcohc.architecture.rx.domain.interactor;
/**
* Base use case which encapsulates the implementation of Rx.
* <p>
* The specific use case "should" be implemented with pure java
*
* @param <M>: the model response you expect to receive in the presentation layer
*/
public abstract class BaseRxUseCase<M> implements RxUseCase<M> {
@NonNull
private Subscription mSubscription = Subscriptions.empty();
/**
* Get the observable from where you want to get the data.
* <p>
*
* @return the observable
*/
@NonNull
protected abstract Observable<M> getObservable();
/**
* Execute the use case. This method is called through {@link JobExecutor},
* but you can override it handle Rx as you like.
*
* @param subscriber the subscriber
* @param subscribeOn "in which thread you want the use case executed"
* @param observeOn "in which thread you want to get the data back"
*/
@SuppressWarnings("unchecked")
@Override
public void execute(@NonNull final SimpleSubscriber<M> subscriber, @NonNull Scheduler subscribeOn, @NonNull Scheduler observeOn) { | Preconditions.checkNotNull(subscriber, "subscriber"); |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/data/factory/UserDataStoreFactory.java | // Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserCacheDataStore.java
// public class UserCacheDataStore implements UserDiskDataStore {
//
// @Override
// public Observable<List<UserEntity>> getUsersWithPicture() {
// return Observable.fromCallable(new SaveInCacheCallable(ALL_WITH_PICTURE));
// }
//
// @Override
// public Observable<List<UserEntity>> getUsersWithoutPicture() {
// return Observable.fromCallable(new SaveInCacheCallable(ALL_WITHOUT_PICTURE));
// }
//
// @Override
// public boolean isCached(@NonNull String cacheKey) {
// return UserCache.getInstance().isCached(cacheKey);
// }
//
// @Override
// public void put(@NonNull String cacheKey, @NonNull List<UserEntity> entityList) {
// UserCache.getInstance().put(cacheKey, entityList);
// }
//
// private static class SaveInCacheCallable implements Callable<List<UserEntity>> {
//
// private String mKey;
//
// SaveInCacheCallable(String key) {
// this.mKey = key;
// }
//
// @Override
// public List<UserEntity> call() throws Exception {
// return UserCache.getInstance().get(mKey);
// }
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserCloudDataStore.java
// public interface UserCloudDataStore {
//
// /**
// * Get all users.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getAll();
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserDiskDataStore.java
// public interface UserDiskDataStore {
//
// String ALL_WITH_PICTURE = "all_with_picture";
// String ALL_WITHOUT_PICTURE = "all_without_picture";
//
// /**
// * Get users with picture.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getUsersWithPicture();
//
// /**
// * Get users without pictures.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getUsersWithoutPicture();
//
// /**
// * Checks if the value is stored.
// *
// * @param cacheKey the key for the cache
// * @return true if is store, false otherwise
// */
// boolean isCached(String cacheKey);
//
// /**
// * Puts the list in the cache with the specific cache key.
// *
// * @param cacheKey the key for the cache
// * @param entityList the list of entities to persist
// */
// void put(String cacheKey, List<UserEntity> entityList);
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UsersWithPictureDataStore.java
// public class UsersWithPictureDataStore implements UserCloudDataStore {
//
// private static final String USERS_WITH_PICTURES_URL = "http://api.randomuser.me/";
//
// @Override
// public Observable<List<UserEntity>> getAll() {
//
// UsersWithPictureService service = ServiceFactory.createService(
// UsersWithPictureService.class,
// GsonConverterFactory.create(),
// RxJavaCallAdapterFactory.create(),
// USERS_WITH_PICTURES_URL);
//
// return service.getAll().map(new ParseResponseFunction());
// }
//
// private static final class ParseResponseFunction implements Func1<UsersWithPictureEntity, List<UserEntity>> {
// @Override
// public List<UserEntity> call(UsersWithPictureEntity usersWithPictureEntity) {
// return UserMapper.getInstance().parseResponse(usersWithPictureEntity);
// }
// }
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UsersWithoutPictureDataStore.java
// public class UsersWithoutPictureDataStore implements UserCloudDataStore {
//
// private static final String USERS_WITHOUT_PICTURES_URL = "http://jsonplaceholder.typicode.com/";
//
// @Override
// public Observable<List<UserEntity>> getAll() {
//
// UsersWithoutPictureService service = ServiceFactory.createService(
// UsersWithoutPictureService.class,
// GsonConverterFactory.create(),
// RxJavaCallAdapterFactory.create(),
// USERS_WITHOUT_PICTURES_URL);
//
// return service.getAll();
// }
// }
| import com.marcohc.architecture.app.data.datastore.user.UserCacheDataStore;
import com.marcohc.architecture.app.data.datastore.user.UserCloudDataStore;
import com.marcohc.architecture.app.data.datastore.user.UserDiskDataStore;
import com.marcohc.architecture.app.data.datastore.user.UsersWithPictureDataStore;
import com.marcohc.architecture.app.data.datastore.user.UsersWithoutPictureDataStore; | package com.marcohc.architecture.app.data.factory;
/**
* The factory provides different data sources .
* <p>
* Its responsibility is to hide the origin of each data source.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public final class UserDataStoreFactory {
public static UserDiskDataStore createUserDiskDataStore() { | // Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserCacheDataStore.java
// public class UserCacheDataStore implements UserDiskDataStore {
//
// @Override
// public Observable<List<UserEntity>> getUsersWithPicture() {
// return Observable.fromCallable(new SaveInCacheCallable(ALL_WITH_PICTURE));
// }
//
// @Override
// public Observable<List<UserEntity>> getUsersWithoutPicture() {
// return Observable.fromCallable(new SaveInCacheCallable(ALL_WITHOUT_PICTURE));
// }
//
// @Override
// public boolean isCached(@NonNull String cacheKey) {
// return UserCache.getInstance().isCached(cacheKey);
// }
//
// @Override
// public void put(@NonNull String cacheKey, @NonNull List<UserEntity> entityList) {
// UserCache.getInstance().put(cacheKey, entityList);
// }
//
// private static class SaveInCacheCallable implements Callable<List<UserEntity>> {
//
// private String mKey;
//
// SaveInCacheCallable(String key) {
// this.mKey = key;
// }
//
// @Override
// public List<UserEntity> call() throws Exception {
// return UserCache.getInstance().get(mKey);
// }
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserCloudDataStore.java
// public interface UserCloudDataStore {
//
// /**
// * Get all users.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getAll();
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserDiskDataStore.java
// public interface UserDiskDataStore {
//
// String ALL_WITH_PICTURE = "all_with_picture";
// String ALL_WITHOUT_PICTURE = "all_without_picture";
//
// /**
// * Get users with picture.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getUsersWithPicture();
//
// /**
// * Get users without pictures.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getUsersWithoutPicture();
//
// /**
// * Checks if the value is stored.
// *
// * @param cacheKey the key for the cache
// * @return true if is store, false otherwise
// */
// boolean isCached(String cacheKey);
//
// /**
// * Puts the list in the cache with the specific cache key.
// *
// * @param cacheKey the key for the cache
// * @param entityList the list of entities to persist
// */
// void put(String cacheKey, List<UserEntity> entityList);
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UsersWithPictureDataStore.java
// public class UsersWithPictureDataStore implements UserCloudDataStore {
//
// private static final String USERS_WITH_PICTURES_URL = "http://api.randomuser.me/";
//
// @Override
// public Observable<List<UserEntity>> getAll() {
//
// UsersWithPictureService service = ServiceFactory.createService(
// UsersWithPictureService.class,
// GsonConverterFactory.create(),
// RxJavaCallAdapterFactory.create(),
// USERS_WITH_PICTURES_URL);
//
// return service.getAll().map(new ParseResponseFunction());
// }
//
// private static final class ParseResponseFunction implements Func1<UsersWithPictureEntity, List<UserEntity>> {
// @Override
// public List<UserEntity> call(UsersWithPictureEntity usersWithPictureEntity) {
// return UserMapper.getInstance().parseResponse(usersWithPictureEntity);
// }
// }
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UsersWithoutPictureDataStore.java
// public class UsersWithoutPictureDataStore implements UserCloudDataStore {
//
// private static final String USERS_WITHOUT_PICTURES_URL = "http://jsonplaceholder.typicode.com/";
//
// @Override
// public Observable<List<UserEntity>> getAll() {
//
// UsersWithoutPictureService service = ServiceFactory.createService(
// UsersWithoutPictureService.class,
// GsonConverterFactory.create(),
// RxJavaCallAdapterFactory.create(),
// USERS_WITHOUT_PICTURES_URL);
//
// return service.getAll();
// }
// }
// Path: app/src/main/java/com/marcohc/architecture/app/data/factory/UserDataStoreFactory.java
import com.marcohc.architecture.app.data.datastore.user.UserCacheDataStore;
import com.marcohc.architecture.app.data.datastore.user.UserCloudDataStore;
import com.marcohc.architecture.app.data.datastore.user.UserDiskDataStore;
import com.marcohc.architecture.app.data.datastore.user.UsersWithPictureDataStore;
import com.marcohc.architecture.app.data.datastore.user.UsersWithoutPictureDataStore;
package com.marcohc.architecture.app.data.factory;
/**
* The factory provides different data sources .
* <p>
* Its responsibility is to hide the origin of each data source.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public final class UserDataStoreFactory {
public static UserDiskDataStore createUserDiskDataStore() { | return new UserCacheDataStore(); |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/data/factory/UserDataStoreFactory.java | // Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserCacheDataStore.java
// public class UserCacheDataStore implements UserDiskDataStore {
//
// @Override
// public Observable<List<UserEntity>> getUsersWithPicture() {
// return Observable.fromCallable(new SaveInCacheCallable(ALL_WITH_PICTURE));
// }
//
// @Override
// public Observable<List<UserEntity>> getUsersWithoutPicture() {
// return Observable.fromCallable(new SaveInCacheCallable(ALL_WITHOUT_PICTURE));
// }
//
// @Override
// public boolean isCached(@NonNull String cacheKey) {
// return UserCache.getInstance().isCached(cacheKey);
// }
//
// @Override
// public void put(@NonNull String cacheKey, @NonNull List<UserEntity> entityList) {
// UserCache.getInstance().put(cacheKey, entityList);
// }
//
// private static class SaveInCacheCallable implements Callable<List<UserEntity>> {
//
// private String mKey;
//
// SaveInCacheCallable(String key) {
// this.mKey = key;
// }
//
// @Override
// public List<UserEntity> call() throws Exception {
// return UserCache.getInstance().get(mKey);
// }
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserCloudDataStore.java
// public interface UserCloudDataStore {
//
// /**
// * Get all users.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getAll();
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserDiskDataStore.java
// public interface UserDiskDataStore {
//
// String ALL_WITH_PICTURE = "all_with_picture";
// String ALL_WITHOUT_PICTURE = "all_without_picture";
//
// /**
// * Get users with picture.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getUsersWithPicture();
//
// /**
// * Get users without pictures.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getUsersWithoutPicture();
//
// /**
// * Checks if the value is stored.
// *
// * @param cacheKey the key for the cache
// * @return true if is store, false otherwise
// */
// boolean isCached(String cacheKey);
//
// /**
// * Puts the list in the cache with the specific cache key.
// *
// * @param cacheKey the key for the cache
// * @param entityList the list of entities to persist
// */
// void put(String cacheKey, List<UserEntity> entityList);
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UsersWithPictureDataStore.java
// public class UsersWithPictureDataStore implements UserCloudDataStore {
//
// private static final String USERS_WITH_PICTURES_URL = "http://api.randomuser.me/";
//
// @Override
// public Observable<List<UserEntity>> getAll() {
//
// UsersWithPictureService service = ServiceFactory.createService(
// UsersWithPictureService.class,
// GsonConverterFactory.create(),
// RxJavaCallAdapterFactory.create(),
// USERS_WITH_PICTURES_URL);
//
// return service.getAll().map(new ParseResponseFunction());
// }
//
// private static final class ParseResponseFunction implements Func1<UsersWithPictureEntity, List<UserEntity>> {
// @Override
// public List<UserEntity> call(UsersWithPictureEntity usersWithPictureEntity) {
// return UserMapper.getInstance().parseResponse(usersWithPictureEntity);
// }
// }
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UsersWithoutPictureDataStore.java
// public class UsersWithoutPictureDataStore implements UserCloudDataStore {
//
// private static final String USERS_WITHOUT_PICTURES_URL = "http://jsonplaceholder.typicode.com/";
//
// @Override
// public Observable<List<UserEntity>> getAll() {
//
// UsersWithoutPictureService service = ServiceFactory.createService(
// UsersWithoutPictureService.class,
// GsonConverterFactory.create(),
// RxJavaCallAdapterFactory.create(),
// USERS_WITHOUT_PICTURES_URL);
//
// return service.getAll();
// }
// }
| import com.marcohc.architecture.app.data.datastore.user.UserCacheDataStore;
import com.marcohc.architecture.app.data.datastore.user.UserCloudDataStore;
import com.marcohc.architecture.app.data.datastore.user.UserDiskDataStore;
import com.marcohc.architecture.app.data.datastore.user.UsersWithPictureDataStore;
import com.marcohc.architecture.app.data.datastore.user.UsersWithoutPictureDataStore; | package com.marcohc.architecture.app.data.factory;
/**
* The factory provides different data sources .
* <p>
* Its responsibility is to hide the origin of each data source.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public final class UserDataStoreFactory {
public static UserDiskDataStore createUserDiskDataStore() {
return new UserCacheDataStore();
}
| // Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserCacheDataStore.java
// public class UserCacheDataStore implements UserDiskDataStore {
//
// @Override
// public Observable<List<UserEntity>> getUsersWithPicture() {
// return Observable.fromCallable(new SaveInCacheCallable(ALL_WITH_PICTURE));
// }
//
// @Override
// public Observable<List<UserEntity>> getUsersWithoutPicture() {
// return Observable.fromCallable(new SaveInCacheCallable(ALL_WITHOUT_PICTURE));
// }
//
// @Override
// public boolean isCached(@NonNull String cacheKey) {
// return UserCache.getInstance().isCached(cacheKey);
// }
//
// @Override
// public void put(@NonNull String cacheKey, @NonNull List<UserEntity> entityList) {
// UserCache.getInstance().put(cacheKey, entityList);
// }
//
// private static class SaveInCacheCallable implements Callable<List<UserEntity>> {
//
// private String mKey;
//
// SaveInCacheCallable(String key) {
// this.mKey = key;
// }
//
// @Override
// public List<UserEntity> call() throws Exception {
// return UserCache.getInstance().get(mKey);
// }
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserCloudDataStore.java
// public interface UserCloudDataStore {
//
// /**
// * Get all users.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getAll();
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserDiskDataStore.java
// public interface UserDiskDataStore {
//
// String ALL_WITH_PICTURE = "all_with_picture";
// String ALL_WITHOUT_PICTURE = "all_without_picture";
//
// /**
// * Get users with picture.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getUsersWithPicture();
//
// /**
// * Get users without pictures.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getUsersWithoutPicture();
//
// /**
// * Checks if the value is stored.
// *
// * @param cacheKey the key for the cache
// * @return true if is store, false otherwise
// */
// boolean isCached(String cacheKey);
//
// /**
// * Puts the list in the cache with the specific cache key.
// *
// * @param cacheKey the key for the cache
// * @param entityList the list of entities to persist
// */
// void put(String cacheKey, List<UserEntity> entityList);
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UsersWithPictureDataStore.java
// public class UsersWithPictureDataStore implements UserCloudDataStore {
//
// private static final String USERS_WITH_PICTURES_URL = "http://api.randomuser.me/";
//
// @Override
// public Observable<List<UserEntity>> getAll() {
//
// UsersWithPictureService service = ServiceFactory.createService(
// UsersWithPictureService.class,
// GsonConverterFactory.create(),
// RxJavaCallAdapterFactory.create(),
// USERS_WITH_PICTURES_URL);
//
// return service.getAll().map(new ParseResponseFunction());
// }
//
// private static final class ParseResponseFunction implements Func1<UsersWithPictureEntity, List<UserEntity>> {
// @Override
// public List<UserEntity> call(UsersWithPictureEntity usersWithPictureEntity) {
// return UserMapper.getInstance().parseResponse(usersWithPictureEntity);
// }
// }
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UsersWithoutPictureDataStore.java
// public class UsersWithoutPictureDataStore implements UserCloudDataStore {
//
// private static final String USERS_WITHOUT_PICTURES_URL = "http://jsonplaceholder.typicode.com/";
//
// @Override
// public Observable<List<UserEntity>> getAll() {
//
// UsersWithoutPictureService service = ServiceFactory.createService(
// UsersWithoutPictureService.class,
// GsonConverterFactory.create(),
// RxJavaCallAdapterFactory.create(),
// USERS_WITHOUT_PICTURES_URL);
//
// return service.getAll();
// }
// }
// Path: app/src/main/java/com/marcohc/architecture/app/data/factory/UserDataStoreFactory.java
import com.marcohc.architecture.app.data.datastore.user.UserCacheDataStore;
import com.marcohc.architecture.app.data.datastore.user.UserCloudDataStore;
import com.marcohc.architecture.app.data.datastore.user.UserDiskDataStore;
import com.marcohc.architecture.app.data.datastore.user.UsersWithPictureDataStore;
import com.marcohc.architecture.app.data.datastore.user.UsersWithoutPictureDataStore;
package com.marcohc.architecture.app.data.factory;
/**
* The factory provides different data sources .
* <p>
* Its responsibility is to hide the origin of each data source.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public final class UserDataStoreFactory {
public static UserDiskDataStore createUserDiskDataStore() {
return new UserCacheDataStore();
}
| public static UserCloudDataStore createUserWithoutPicturesCloudDataStore() { |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/data/factory/UserDataStoreFactory.java | // Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserCacheDataStore.java
// public class UserCacheDataStore implements UserDiskDataStore {
//
// @Override
// public Observable<List<UserEntity>> getUsersWithPicture() {
// return Observable.fromCallable(new SaveInCacheCallable(ALL_WITH_PICTURE));
// }
//
// @Override
// public Observable<List<UserEntity>> getUsersWithoutPicture() {
// return Observable.fromCallable(new SaveInCacheCallable(ALL_WITHOUT_PICTURE));
// }
//
// @Override
// public boolean isCached(@NonNull String cacheKey) {
// return UserCache.getInstance().isCached(cacheKey);
// }
//
// @Override
// public void put(@NonNull String cacheKey, @NonNull List<UserEntity> entityList) {
// UserCache.getInstance().put(cacheKey, entityList);
// }
//
// private static class SaveInCacheCallable implements Callable<List<UserEntity>> {
//
// private String mKey;
//
// SaveInCacheCallable(String key) {
// this.mKey = key;
// }
//
// @Override
// public List<UserEntity> call() throws Exception {
// return UserCache.getInstance().get(mKey);
// }
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserCloudDataStore.java
// public interface UserCloudDataStore {
//
// /**
// * Get all users.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getAll();
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserDiskDataStore.java
// public interface UserDiskDataStore {
//
// String ALL_WITH_PICTURE = "all_with_picture";
// String ALL_WITHOUT_PICTURE = "all_without_picture";
//
// /**
// * Get users with picture.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getUsersWithPicture();
//
// /**
// * Get users without pictures.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getUsersWithoutPicture();
//
// /**
// * Checks if the value is stored.
// *
// * @param cacheKey the key for the cache
// * @return true if is store, false otherwise
// */
// boolean isCached(String cacheKey);
//
// /**
// * Puts the list in the cache with the specific cache key.
// *
// * @param cacheKey the key for the cache
// * @param entityList the list of entities to persist
// */
// void put(String cacheKey, List<UserEntity> entityList);
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UsersWithPictureDataStore.java
// public class UsersWithPictureDataStore implements UserCloudDataStore {
//
// private static final String USERS_WITH_PICTURES_URL = "http://api.randomuser.me/";
//
// @Override
// public Observable<List<UserEntity>> getAll() {
//
// UsersWithPictureService service = ServiceFactory.createService(
// UsersWithPictureService.class,
// GsonConverterFactory.create(),
// RxJavaCallAdapterFactory.create(),
// USERS_WITH_PICTURES_URL);
//
// return service.getAll().map(new ParseResponseFunction());
// }
//
// private static final class ParseResponseFunction implements Func1<UsersWithPictureEntity, List<UserEntity>> {
// @Override
// public List<UserEntity> call(UsersWithPictureEntity usersWithPictureEntity) {
// return UserMapper.getInstance().parseResponse(usersWithPictureEntity);
// }
// }
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UsersWithoutPictureDataStore.java
// public class UsersWithoutPictureDataStore implements UserCloudDataStore {
//
// private static final String USERS_WITHOUT_PICTURES_URL = "http://jsonplaceholder.typicode.com/";
//
// @Override
// public Observable<List<UserEntity>> getAll() {
//
// UsersWithoutPictureService service = ServiceFactory.createService(
// UsersWithoutPictureService.class,
// GsonConverterFactory.create(),
// RxJavaCallAdapterFactory.create(),
// USERS_WITHOUT_PICTURES_URL);
//
// return service.getAll();
// }
// }
| import com.marcohc.architecture.app.data.datastore.user.UserCacheDataStore;
import com.marcohc.architecture.app.data.datastore.user.UserCloudDataStore;
import com.marcohc.architecture.app.data.datastore.user.UserDiskDataStore;
import com.marcohc.architecture.app.data.datastore.user.UsersWithPictureDataStore;
import com.marcohc.architecture.app.data.datastore.user.UsersWithoutPictureDataStore; | package com.marcohc.architecture.app.data.factory;
/**
* The factory provides different data sources .
* <p>
* Its responsibility is to hide the origin of each data source.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public final class UserDataStoreFactory {
public static UserDiskDataStore createUserDiskDataStore() {
return new UserCacheDataStore();
}
public static UserCloudDataStore createUserWithoutPicturesCloudDataStore() { | // Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserCacheDataStore.java
// public class UserCacheDataStore implements UserDiskDataStore {
//
// @Override
// public Observable<List<UserEntity>> getUsersWithPicture() {
// return Observable.fromCallable(new SaveInCacheCallable(ALL_WITH_PICTURE));
// }
//
// @Override
// public Observable<List<UserEntity>> getUsersWithoutPicture() {
// return Observable.fromCallable(new SaveInCacheCallable(ALL_WITHOUT_PICTURE));
// }
//
// @Override
// public boolean isCached(@NonNull String cacheKey) {
// return UserCache.getInstance().isCached(cacheKey);
// }
//
// @Override
// public void put(@NonNull String cacheKey, @NonNull List<UserEntity> entityList) {
// UserCache.getInstance().put(cacheKey, entityList);
// }
//
// private static class SaveInCacheCallable implements Callable<List<UserEntity>> {
//
// private String mKey;
//
// SaveInCacheCallable(String key) {
// this.mKey = key;
// }
//
// @Override
// public List<UserEntity> call() throws Exception {
// return UserCache.getInstance().get(mKey);
// }
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserCloudDataStore.java
// public interface UserCloudDataStore {
//
// /**
// * Get all users.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getAll();
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserDiskDataStore.java
// public interface UserDiskDataStore {
//
// String ALL_WITH_PICTURE = "all_with_picture";
// String ALL_WITHOUT_PICTURE = "all_without_picture";
//
// /**
// * Get users with picture.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getUsersWithPicture();
//
// /**
// * Get users without pictures.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getUsersWithoutPicture();
//
// /**
// * Checks if the value is stored.
// *
// * @param cacheKey the key for the cache
// * @return true if is store, false otherwise
// */
// boolean isCached(String cacheKey);
//
// /**
// * Puts the list in the cache with the specific cache key.
// *
// * @param cacheKey the key for the cache
// * @param entityList the list of entities to persist
// */
// void put(String cacheKey, List<UserEntity> entityList);
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UsersWithPictureDataStore.java
// public class UsersWithPictureDataStore implements UserCloudDataStore {
//
// private static final String USERS_WITH_PICTURES_URL = "http://api.randomuser.me/";
//
// @Override
// public Observable<List<UserEntity>> getAll() {
//
// UsersWithPictureService service = ServiceFactory.createService(
// UsersWithPictureService.class,
// GsonConverterFactory.create(),
// RxJavaCallAdapterFactory.create(),
// USERS_WITH_PICTURES_URL);
//
// return service.getAll().map(new ParseResponseFunction());
// }
//
// private static final class ParseResponseFunction implements Func1<UsersWithPictureEntity, List<UserEntity>> {
// @Override
// public List<UserEntity> call(UsersWithPictureEntity usersWithPictureEntity) {
// return UserMapper.getInstance().parseResponse(usersWithPictureEntity);
// }
// }
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UsersWithoutPictureDataStore.java
// public class UsersWithoutPictureDataStore implements UserCloudDataStore {
//
// private static final String USERS_WITHOUT_PICTURES_URL = "http://jsonplaceholder.typicode.com/";
//
// @Override
// public Observable<List<UserEntity>> getAll() {
//
// UsersWithoutPictureService service = ServiceFactory.createService(
// UsersWithoutPictureService.class,
// GsonConverterFactory.create(),
// RxJavaCallAdapterFactory.create(),
// USERS_WITHOUT_PICTURES_URL);
//
// return service.getAll();
// }
// }
// Path: app/src/main/java/com/marcohc/architecture/app/data/factory/UserDataStoreFactory.java
import com.marcohc.architecture.app.data.datastore.user.UserCacheDataStore;
import com.marcohc.architecture.app.data.datastore.user.UserCloudDataStore;
import com.marcohc.architecture.app.data.datastore.user.UserDiskDataStore;
import com.marcohc.architecture.app.data.datastore.user.UsersWithPictureDataStore;
import com.marcohc.architecture.app.data.datastore.user.UsersWithoutPictureDataStore;
package com.marcohc.architecture.app.data.factory;
/**
* The factory provides different data sources .
* <p>
* Its responsibility is to hide the origin of each data source.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public final class UserDataStoreFactory {
public static UserDiskDataStore createUserDiskDataStore() {
return new UserCacheDataStore();
}
public static UserCloudDataStore createUserWithoutPicturesCloudDataStore() { | return new UsersWithoutPictureDataStore(); |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/data/factory/UserDataStoreFactory.java | // Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserCacheDataStore.java
// public class UserCacheDataStore implements UserDiskDataStore {
//
// @Override
// public Observable<List<UserEntity>> getUsersWithPicture() {
// return Observable.fromCallable(new SaveInCacheCallable(ALL_WITH_PICTURE));
// }
//
// @Override
// public Observable<List<UserEntity>> getUsersWithoutPicture() {
// return Observable.fromCallable(new SaveInCacheCallable(ALL_WITHOUT_PICTURE));
// }
//
// @Override
// public boolean isCached(@NonNull String cacheKey) {
// return UserCache.getInstance().isCached(cacheKey);
// }
//
// @Override
// public void put(@NonNull String cacheKey, @NonNull List<UserEntity> entityList) {
// UserCache.getInstance().put(cacheKey, entityList);
// }
//
// private static class SaveInCacheCallable implements Callable<List<UserEntity>> {
//
// private String mKey;
//
// SaveInCacheCallable(String key) {
// this.mKey = key;
// }
//
// @Override
// public List<UserEntity> call() throws Exception {
// return UserCache.getInstance().get(mKey);
// }
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserCloudDataStore.java
// public interface UserCloudDataStore {
//
// /**
// * Get all users.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getAll();
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserDiskDataStore.java
// public interface UserDiskDataStore {
//
// String ALL_WITH_PICTURE = "all_with_picture";
// String ALL_WITHOUT_PICTURE = "all_without_picture";
//
// /**
// * Get users with picture.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getUsersWithPicture();
//
// /**
// * Get users without pictures.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getUsersWithoutPicture();
//
// /**
// * Checks if the value is stored.
// *
// * @param cacheKey the key for the cache
// * @return true if is store, false otherwise
// */
// boolean isCached(String cacheKey);
//
// /**
// * Puts the list in the cache with the specific cache key.
// *
// * @param cacheKey the key for the cache
// * @param entityList the list of entities to persist
// */
// void put(String cacheKey, List<UserEntity> entityList);
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UsersWithPictureDataStore.java
// public class UsersWithPictureDataStore implements UserCloudDataStore {
//
// private static final String USERS_WITH_PICTURES_URL = "http://api.randomuser.me/";
//
// @Override
// public Observable<List<UserEntity>> getAll() {
//
// UsersWithPictureService service = ServiceFactory.createService(
// UsersWithPictureService.class,
// GsonConverterFactory.create(),
// RxJavaCallAdapterFactory.create(),
// USERS_WITH_PICTURES_URL);
//
// return service.getAll().map(new ParseResponseFunction());
// }
//
// private static final class ParseResponseFunction implements Func1<UsersWithPictureEntity, List<UserEntity>> {
// @Override
// public List<UserEntity> call(UsersWithPictureEntity usersWithPictureEntity) {
// return UserMapper.getInstance().parseResponse(usersWithPictureEntity);
// }
// }
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UsersWithoutPictureDataStore.java
// public class UsersWithoutPictureDataStore implements UserCloudDataStore {
//
// private static final String USERS_WITHOUT_PICTURES_URL = "http://jsonplaceholder.typicode.com/";
//
// @Override
// public Observable<List<UserEntity>> getAll() {
//
// UsersWithoutPictureService service = ServiceFactory.createService(
// UsersWithoutPictureService.class,
// GsonConverterFactory.create(),
// RxJavaCallAdapterFactory.create(),
// USERS_WITHOUT_PICTURES_URL);
//
// return service.getAll();
// }
// }
| import com.marcohc.architecture.app.data.datastore.user.UserCacheDataStore;
import com.marcohc.architecture.app.data.datastore.user.UserCloudDataStore;
import com.marcohc.architecture.app.data.datastore.user.UserDiskDataStore;
import com.marcohc.architecture.app.data.datastore.user.UsersWithPictureDataStore;
import com.marcohc.architecture.app.data.datastore.user.UsersWithoutPictureDataStore; | package com.marcohc.architecture.app.data.factory;
/**
* The factory provides different data sources .
* <p>
* Its responsibility is to hide the origin of each data source.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public final class UserDataStoreFactory {
public static UserDiskDataStore createUserDiskDataStore() {
return new UserCacheDataStore();
}
public static UserCloudDataStore createUserWithoutPicturesCloudDataStore() {
return new UsersWithoutPictureDataStore();
}
public static UserCloudDataStore createUserWithPicturesCloudDataStore() { | // Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserCacheDataStore.java
// public class UserCacheDataStore implements UserDiskDataStore {
//
// @Override
// public Observable<List<UserEntity>> getUsersWithPicture() {
// return Observable.fromCallable(new SaveInCacheCallable(ALL_WITH_PICTURE));
// }
//
// @Override
// public Observable<List<UserEntity>> getUsersWithoutPicture() {
// return Observable.fromCallable(new SaveInCacheCallable(ALL_WITHOUT_PICTURE));
// }
//
// @Override
// public boolean isCached(@NonNull String cacheKey) {
// return UserCache.getInstance().isCached(cacheKey);
// }
//
// @Override
// public void put(@NonNull String cacheKey, @NonNull List<UserEntity> entityList) {
// UserCache.getInstance().put(cacheKey, entityList);
// }
//
// private static class SaveInCacheCallable implements Callable<List<UserEntity>> {
//
// private String mKey;
//
// SaveInCacheCallable(String key) {
// this.mKey = key;
// }
//
// @Override
// public List<UserEntity> call() throws Exception {
// return UserCache.getInstance().get(mKey);
// }
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserCloudDataStore.java
// public interface UserCloudDataStore {
//
// /**
// * Get all users.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getAll();
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserDiskDataStore.java
// public interface UserDiskDataStore {
//
// String ALL_WITH_PICTURE = "all_with_picture";
// String ALL_WITHOUT_PICTURE = "all_without_picture";
//
// /**
// * Get users with picture.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getUsersWithPicture();
//
// /**
// * Get users without pictures.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getUsersWithoutPicture();
//
// /**
// * Checks if the value is stored.
// *
// * @param cacheKey the key for the cache
// * @return true if is store, false otherwise
// */
// boolean isCached(String cacheKey);
//
// /**
// * Puts the list in the cache with the specific cache key.
// *
// * @param cacheKey the key for the cache
// * @param entityList the list of entities to persist
// */
// void put(String cacheKey, List<UserEntity> entityList);
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UsersWithPictureDataStore.java
// public class UsersWithPictureDataStore implements UserCloudDataStore {
//
// private static final String USERS_WITH_PICTURES_URL = "http://api.randomuser.me/";
//
// @Override
// public Observable<List<UserEntity>> getAll() {
//
// UsersWithPictureService service = ServiceFactory.createService(
// UsersWithPictureService.class,
// GsonConverterFactory.create(),
// RxJavaCallAdapterFactory.create(),
// USERS_WITH_PICTURES_URL);
//
// return service.getAll().map(new ParseResponseFunction());
// }
//
// private static final class ParseResponseFunction implements Func1<UsersWithPictureEntity, List<UserEntity>> {
// @Override
// public List<UserEntity> call(UsersWithPictureEntity usersWithPictureEntity) {
// return UserMapper.getInstance().parseResponse(usersWithPictureEntity);
// }
// }
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UsersWithoutPictureDataStore.java
// public class UsersWithoutPictureDataStore implements UserCloudDataStore {
//
// private static final String USERS_WITHOUT_PICTURES_URL = "http://jsonplaceholder.typicode.com/";
//
// @Override
// public Observable<List<UserEntity>> getAll() {
//
// UsersWithoutPictureService service = ServiceFactory.createService(
// UsersWithoutPictureService.class,
// GsonConverterFactory.create(),
// RxJavaCallAdapterFactory.create(),
// USERS_WITHOUT_PICTURES_URL);
//
// return service.getAll();
// }
// }
// Path: app/src/main/java/com/marcohc/architecture/app/data/factory/UserDataStoreFactory.java
import com.marcohc.architecture.app.data.datastore.user.UserCacheDataStore;
import com.marcohc.architecture.app.data.datastore.user.UserCloudDataStore;
import com.marcohc.architecture.app.data.datastore.user.UserDiskDataStore;
import com.marcohc.architecture.app.data.datastore.user.UsersWithPictureDataStore;
import com.marcohc.architecture.app.data.datastore.user.UsersWithoutPictureDataStore;
package com.marcohc.architecture.app.data.factory;
/**
* The factory provides different data sources .
* <p>
* Its responsibility is to hide the origin of each data source.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public final class UserDataStoreFactory {
public static UserDiskDataStore createUserDiskDataStore() {
return new UserCacheDataStore();
}
public static UserCloudDataStore createUserWithoutPicturesCloudDataStore() {
return new UsersWithoutPictureDataStore();
}
public static UserCloudDataStore createUserWithPicturesCloudDataStore() { | return new UsersWithPictureDataStore(); |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/presentation/story/user/userlist/view/UsersListPresenterImpl.java | // Path: app/src/main/java/com/marcohc/architecture/app/domain/interactor/GetUsersUseCase.java
// public class GetUsersUseCase extends BaseRxUseCase<List<UserModel>> {
//
// private final boolean mWithPicture;
// private final boolean mUseCache;
// private final UserRepository mUserRepository;
//
// public GetUsersUseCase(boolean withPicture, boolean useCache) {
// mWithPicture = withPicture;
// mUseCache = useCache;
// mUserRepository = new UserRepositoryImpl();
// }
//
// @NonNull
// @Override
// protected Observable<List<UserModel>> getObservable() {
// if (mWithPicture) {
// return mUserRepository
// .getAllWithPicture(mUseCache)
// .map(new Func1<List<UserEntity>, List<UserModel>>() {
// @Override
// public List<UserModel> call(List<UserEntity> userEntities) {
// return UserMapper.getInstance().transformEntityList(userEntities);
// }
// });
// } else {
// return mUserRepository
// .getAllWithoutPicture(mUseCache)
// .map(new Func1<List<UserEntity>, List<UserModel>>() {
// @Override
// public List<UserModel> call(List<UserEntity> userEntities) {
// return UserMapper.getInstance().transformEntityList(userEntities);
// }
// });
// }
// }
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/domain/model/UserModel.java
// public class UserModel implements Model {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserModel() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/mvp/BasePresenter.java
// public abstract class BasePresenter<V extends BaseMvpView> extends BaseRxMvpPresenter<V> {
//
// }
//
// Path: util/src/main/java/com/marcohc/architecture/common/util/TimerUtils.java
// public class TimerUtils {
//
// private long stepTime;
// private long totalTime;
// private int stepNumber;
// private String tag;
//
// public static TimerUtils getInstance(String tag) {
// return new TimerUtils(tag);
// }
//
// private TimerUtils(String tag) {
// this.tag = tag;
// stepNumber = 1;
// stepTime = System.currentTimeMillis();
// totalTime = System.currentTimeMillis();
// }
//
// /**
// * Prints a log with the step time.
// *
// * @return the step time
// */
// public Long logStep() {
// Long difference = System.currentTimeMillis() - stepTime;
// Timber.d("%s - Step %d: %d", tag, stepNumber++, difference);
// stepTime = System.currentTimeMillis();
// return difference;
// }
//
// /**
// * Prints a log with the step time.
// *
// * @param subTag sub tag used in the log
// * @return the step time
// */
// public Long logStep(String subTag) {
// Long difference = System.currentTimeMillis() - stepTime;
// Timber.d("%s (%s) - Step %d: %d", android.R.attr.tag, subTag, stepNumber++, difference);
// stepTime = System.currentTimeMillis();
// return difference;
// }
//
// /**
// * Prints a log with the total time.
// *
// * @return the total time
// */
// public Long logTotal() {
// Long difference = System.currentTimeMillis() - totalTime;
// Timber.d("%s - TOTAL: %d", tag, difference);
// return difference;
// }
// }
| import android.support.annotation.NonNull;
import com.marcohc.architecture.app.domain.interactor.GetUsersUseCase;
import com.marcohc.architecture.app.domain.model.UserModel;
import com.marcohc.architecture.app.presentation.mvp.BasePresenter;
import com.marcohc.architecture.common.util.TimerUtils;
import java.util.List; | package com.marcohc.architecture.app.presentation.story.user.userlist.view;
/**
* Presenter implementation of {@link UsersListPresenter}.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
class UsersListPresenterImpl extends BasePresenter<UsersListView> implements UsersListPresenter, GetUsersSubscriber.GetUsersListener {
//region Attributes
private boolean mDataSourceWithPicture = false;
private boolean mUseCache = false; | // Path: app/src/main/java/com/marcohc/architecture/app/domain/interactor/GetUsersUseCase.java
// public class GetUsersUseCase extends BaseRxUseCase<List<UserModel>> {
//
// private final boolean mWithPicture;
// private final boolean mUseCache;
// private final UserRepository mUserRepository;
//
// public GetUsersUseCase(boolean withPicture, boolean useCache) {
// mWithPicture = withPicture;
// mUseCache = useCache;
// mUserRepository = new UserRepositoryImpl();
// }
//
// @NonNull
// @Override
// protected Observable<List<UserModel>> getObservable() {
// if (mWithPicture) {
// return mUserRepository
// .getAllWithPicture(mUseCache)
// .map(new Func1<List<UserEntity>, List<UserModel>>() {
// @Override
// public List<UserModel> call(List<UserEntity> userEntities) {
// return UserMapper.getInstance().transformEntityList(userEntities);
// }
// });
// } else {
// return mUserRepository
// .getAllWithoutPicture(mUseCache)
// .map(new Func1<List<UserEntity>, List<UserModel>>() {
// @Override
// public List<UserModel> call(List<UserEntity> userEntities) {
// return UserMapper.getInstance().transformEntityList(userEntities);
// }
// });
// }
// }
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/domain/model/UserModel.java
// public class UserModel implements Model {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserModel() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/mvp/BasePresenter.java
// public abstract class BasePresenter<V extends BaseMvpView> extends BaseRxMvpPresenter<V> {
//
// }
//
// Path: util/src/main/java/com/marcohc/architecture/common/util/TimerUtils.java
// public class TimerUtils {
//
// private long stepTime;
// private long totalTime;
// private int stepNumber;
// private String tag;
//
// public static TimerUtils getInstance(String tag) {
// return new TimerUtils(tag);
// }
//
// private TimerUtils(String tag) {
// this.tag = tag;
// stepNumber = 1;
// stepTime = System.currentTimeMillis();
// totalTime = System.currentTimeMillis();
// }
//
// /**
// * Prints a log with the step time.
// *
// * @return the step time
// */
// public Long logStep() {
// Long difference = System.currentTimeMillis() - stepTime;
// Timber.d("%s - Step %d: %d", tag, stepNumber++, difference);
// stepTime = System.currentTimeMillis();
// return difference;
// }
//
// /**
// * Prints a log with the step time.
// *
// * @param subTag sub tag used in the log
// * @return the step time
// */
// public Long logStep(String subTag) {
// Long difference = System.currentTimeMillis() - stepTime;
// Timber.d("%s (%s) - Step %d: %d", android.R.attr.tag, subTag, stepNumber++, difference);
// stepTime = System.currentTimeMillis();
// return difference;
// }
//
// /**
// * Prints a log with the total time.
// *
// * @return the total time
// */
// public Long logTotal() {
// Long difference = System.currentTimeMillis() - totalTime;
// Timber.d("%s - TOTAL: %d", tag, difference);
// return difference;
// }
// }
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/story/user/userlist/view/UsersListPresenterImpl.java
import android.support.annotation.NonNull;
import com.marcohc.architecture.app.domain.interactor.GetUsersUseCase;
import com.marcohc.architecture.app.domain.model.UserModel;
import com.marcohc.architecture.app.presentation.mvp.BasePresenter;
import com.marcohc.architecture.common.util.TimerUtils;
import java.util.List;
package com.marcohc.architecture.app.presentation.story.user.userlist.view;
/**
* Presenter implementation of {@link UsersListPresenter}.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
class UsersListPresenterImpl extends BasePresenter<UsersListView> implements UsersListPresenter, GetUsersSubscriber.GetUsersListener {
//region Attributes
private boolean mDataSourceWithPicture = false;
private boolean mUseCache = false; | private TimerUtils mTimer; |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/presentation/story/user/userlist/view/UsersListPresenterImpl.java | // Path: app/src/main/java/com/marcohc/architecture/app/domain/interactor/GetUsersUseCase.java
// public class GetUsersUseCase extends BaseRxUseCase<List<UserModel>> {
//
// private final boolean mWithPicture;
// private final boolean mUseCache;
// private final UserRepository mUserRepository;
//
// public GetUsersUseCase(boolean withPicture, boolean useCache) {
// mWithPicture = withPicture;
// mUseCache = useCache;
// mUserRepository = new UserRepositoryImpl();
// }
//
// @NonNull
// @Override
// protected Observable<List<UserModel>> getObservable() {
// if (mWithPicture) {
// return mUserRepository
// .getAllWithPicture(mUseCache)
// .map(new Func1<List<UserEntity>, List<UserModel>>() {
// @Override
// public List<UserModel> call(List<UserEntity> userEntities) {
// return UserMapper.getInstance().transformEntityList(userEntities);
// }
// });
// } else {
// return mUserRepository
// .getAllWithoutPicture(mUseCache)
// .map(new Func1<List<UserEntity>, List<UserModel>>() {
// @Override
// public List<UserModel> call(List<UserEntity> userEntities) {
// return UserMapper.getInstance().transformEntityList(userEntities);
// }
// });
// }
// }
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/domain/model/UserModel.java
// public class UserModel implements Model {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserModel() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/mvp/BasePresenter.java
// public abstract class BasePresenter<V extends BaseMvpView> extends BaseRxMvpPresenter<V> {
//
// }
//
// Path: util/src/main/java/com/marcohc/architecture/common/util/TimerUtils.java
// public class TimerUtils {
//
// private long stepTime;
// private long totalTime;
// private int stepNumber;
// private String tag;
//
// public static TimerUtils getInstance(String tag) {
// return new TimerUtils(tag);
// }
//
// private TimerUtils(String tag) {
// this.tag = tag;
// stepNumber = 1;
// stepTime = System.currentTimeMillis();
// totalTime = System.currentTimeMillis();
// }
//
// /**
// * Prints a log with the step time.
// *
// * @return the step time
// */
// public Long logStep() {
// Long difference = System.currentTimeMillis() - stepTime;
// Timber.d("%s - Step %d: %d", tag, stepNumber++, difference);
// stepTime = System.currentTimeMillis();
// return difference;
// }
//
// /**
// * Prints a log with the step time.
// *
// * @param subTag sub tag used in the log
// * @return the step time
// */
// public Long logStep(String subTag) {
// Long difference = System.currentTimeMillis() - stepTime;
// Timber.d("%s (%s) - Step %d: %d", android.R.attr.tag, subTag, stepNumber++, difference);
// stepTime = System.currentTimeMillis();
// return difference;
// }
//
// /**
// * Prints a log with the total time.
// *
// * @return the total time
// */
// public Long logTotal() {
// Long difference = System.currentTimeMillis() - totalTime;
// Timber.d("%s - TOTAL: %d", tag, difference);
// return difference;
// }
// }
| import android.support.annotation.NonNull;
import com.marcohc.architecture.app.domain.interactor.GetUsersUseCase;
import com.marcohc.architecture.app.domain.model.UserModel;
import com.marcohc.architecture.app.presentation.mvp.BasePresenter;
import com.marcohc.architecture.common.util.TimerUtils;
import java.util.List; | package com.marcohc.architecture.app.presentation.story.user.userlist.view;
/**
* Presenter implementation of {@link UsersListPresenter}.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
class UsersListPresenterImpl extends BasePresenter<UsersListView> implements UsersListPresenter, GetUsersSubscriber.GetUsersListener {
//region Attributes
private boolean mDataSourceWithPicture = false;
private boolean mUseCache = false;
private TimerUtils mTimer; | // Path: app/src/main/java/com/marcohc/architecture/app/domain/interactor/GetUsersUseCase.java
// public class GetUsersUseCase extends BaseRxUseCase<List<UserModel>> {
//
// private final boolean mWithPicture;
// private final boolean mUseCache;
// private final UserRepository mUserRepository;
//
// public GetUsersUseCase(boolean withPicture, boolean useCache) {
// mWithPicture = withPicture;
// mUseCache = useCache;
// mUserRepository = new UserRepositoryImpl();
// }
//
// @NonNull
// @Override
// protected Observable<List<UserModel>> getObservable() {
// if (mWithPicture) {
// return mUserRepository
// .getAllWithPicture(mUseCache)
// .map(new Func1<List<UserEntity>, List<UserModel>>() {
// @Override
// public List<UserModel> call(List<UserEntity> userEntities) {
// return UserMapper.getInstance().transformEntityList(userEntities);
// }
// });
// } else {
// return mUserRepository
// .getAllWithoutPicture(mUseCache)
// .map(new Func1<List<UserEntity>, List<UserModel>>() {
// @Override
// public List<UserModel> call(List<UserEntity> userEntities) {
// return UserMapper.getInstance().transformEntityList(userEntities);
// }
// });
// }
// }
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/domain/model/UserModel.java
// public class UserModel implements Model {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserModel() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/mvp/BasePresenter.java
// public abstract class BasePresenter<V extends BaseMvpView> extends BaseRxMvpPresenter<V> {
//
// }
//
// Path: util/src/main/java/com/marcohc/architecture/common/util/TimerUtils.java
// public class TimerUtils {
//
// private long stepTime;
// private long totalTime;
// private int stepNumber;
// private String tag;
//
// public static TimerUtils getInstance(String tag) {
// return new TimerUtils(tag);
// }
//
// private TimerUtils(String tag) {
// this.tag = tag;
// stepNumber = 1;
// stepTime = System.currentTimeMillis();
// totalTime = System.currentTimeMillis();
// }
//
// /**
// * Prints a log with the step time.
// *
// * @return the step time
// */
// public Long logStep() {
// Long difference = System.currentTimeMillis() - stepTime;
// Timber.d("%s - Step %d: %d", tag, stepNumber++, difference);
// stepTime = System.currentTimeMillis();
// return difference;
// }
//
// /**
// * Prints a log with the step time.
// *
// * @param subTag sub tag used in the log
// * @return the step time
// */
// public Long logStep(String subTag) {
// Long difference = System.currentTimeMillis() - stepTime;
// Timber.d("%s (%s) - Step %d: %d", android.R.attr.tag, subTag, stepNumber++, difference);
// stepTime = System.currentTimeMillis();
// return difference;
// }
//
// /**
// * Prints a log with the total time.
// *
// * @return the total time
// */
// public Long logTotal() {
// Long difference = System.currentTimeMillis() - totalTime;
// Timber.d("%s - TOTAL: %d", tag, difference);
// return difference;
// }
// }
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/story/user/userlist/view/UsersListPresenterImpl.java
import android.support.annotation.NonNull;
import com.marcohc.architecture.app.domain.interactor.GetUsersUseCase;
import com.marcohc.architecture.app.domain.model.UserModel;
import com.marcohc.architecture.app.presentation.mvp.BasePresenter;
import com.marcohc.architecture.common.util.TimerUtils;
import java.util.List;
package com.marcohc.architecture.app.presentation.story.user.userlist.view;
/**
* Presenter implementation of {@link UsersListPresenter}.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
class UsersListPresenterImpl extends BasePresenter<UsersListView> implements UsersListPresenter, GetUsersSubscriber.GetUsersListener {
//region Attributes
private boolean mDataSourceWithPicture = false;
private boolean mUseCache = false;
private TimerUtils mTimer; | private GetUsersUseCase mGetUsersUseCase; |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/presentation/story/user/userlist/view/UsersListPresenterImpl.java | // Path: app/src/main/java/com/marcohc/architecture/app/domain/interactor/GetUsersUseCase.java
// public class GetUsersUseCase extends BaseRxUseCase<List<UserModel>> {
//
// private final boolean mWithPicture;
// private final boolean mUseCache;
// private final UserRepository mUserRepository;
//
// public GetUsersUseCase(boolean withPicture, boolean useCache) {
// mWithPicture = withPicture;
// mUseCache = useCache;
// mUserRepository = new UserRepositoryImpl();
// }
//
// @NonNull
// @Override
// protected Observable<List<UserModel>> getObservable() {
// if (mWithPicture) {
// return mUserRepository
// .getAllWithPicture(mUseCache)
// .map(new Func1<List<UserEntity>, List<UserModel>>() {
// @Override
// public List<UserModel> call(List<UserEntity> userEntities) {
// return UserMapper.getInstance().transformEntityList(userEntities);
// }
// });
// } else {
// return mUserRepository
// .getAllWithoutPicture(mUseCache)
// .map(new Func1<List<UserEntity>, List<UserModel>>() {
// @Override
// public List<UserModel> call(List<UserEntity> userEntities) {
// return UserMapper.getInstance().transformEntityList(userEntities);
// }
// });
// }
// }
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/domain/model/UserModel.java
// public class UserModel implements Model {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserModel() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/mvp/BasePresenter.java
// public abstract class BasePresenter<V extends BaseMvpView> extends BaseRxMvpPresenter<V> {
//
// }
//
// Path: util/src/main/java/com/marcohc/architecture/common/util/TimerUtils.java
// public class TimerUtils {
//
// private long stepTime;
// private long totalTime;
// private int stepNumber;
// private String tag;
//
// public static TimerUtils getInstance(String tag) {
// return new TimerUtils(tag);
// }
//
// private TimerUtils(String tag) {
// this.tag = tag;
// stepNumber = 1;
// stepTime = System.currentTimeMillis();
// totalTime = System.currentTimeMillis();
// }
//
// /**
// * Prints a log with the step time.
// *
// * @return the step time
// */
// public Long logStep() {
// Long difference = System.currentTimeMillis() - stepTime;
// Timber.d("%s - Step %d: %d", tag, stepNumber++, difference);
// stepTime = System.currentTimeMillis();
// return difference;
// }
//
// /**
// * Prints a log with the step time.
// *
// * @param subTag sub tag used in the log
// * @return the step time
// */
// public Long logStep(String subTag) {
// Long difference = System.currentTimeMillis() - stepTime;
// Timber.d("%s (%s) - Step %d: %d", android.R.attr.tag, subTag, stepNumber++, difference);
// stepTime = System.currentTimeMillis();
// return difference;
// }
//
// /**
// * Prints a log with the total time.
// *
// * @return the total time
// */
// public Long logTotal() {
// Long difference = System.currentTimeMillis() - totalTime;
// Timber.d("%s - TOTAL: %d", tag, difference);
// return difference;
// }
// }
| import android.support.annotation.NonNull;
import com.marcohc.architecture.app.domain.interactor.GetUsersUseCase;
import com.marcohc.architecture.app.domain.model.UserModel;
import com.marcohc.architecture.app.presentation.mvp.BasePresenter;
import com.marcohc.architecture.common.util.TimerUtils;
import java.util.List; | package com.marcohc.architecture.app.presentation.story.user.userlist.view;
/**
* Presenter implementation of {@link UsersListPresenter}.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
class UsersListPresenterImpl extends BasePresenter<UsersListView> implements UsersListPresenter, GetUsersSubscriber.GetUsersListener {
//region Attributes
private boolean mDataSourceWithPicture = false;
private boolean mUseCache = false;
private TimerUtils mTimer;
private GetUsersUseCase mGetUsersUseCase;
//endregion
//region Presenter interface methods
@Override
public void onViewCreated() {
getView().showLoadingDialog();
requestFreshData();
}
@Override
public void onRefresh() {
requestFreshData();
}
@Override | // Path: app/src/main/java/com/marcohc/architecture/app/domain/interactor/GetUsersUseCase.java
// public class GetUsersUseCase extends BaseRxUseCase<List<UserModel>> {
//
// private final boolean mWithPicture;
// private final boolean mUseCache;
// private final UserRepository mUserRepository;
//
// public GetUsersUseCase(boolean withPicture, boolean useCache) {
// mWithPicture = withPicture;
// mUseCache = useCache;
// mUserRepository = new UserRepositoryImpl();
// }
//
// @NonNull
// @Override
// protected Observable<List<UserModel>> getObservable() {
// if (mWithPicture) {
// return mUserRepository
// .getAllWithPicture(mUseCache)
// .map(new Func1<List<UserEntity>, List<UserModel>>() {
// @Override
// public List<UserModel> call(List<UserEntity> userEntities) {
// return UserMapper.getInstance().transformEntityList(userEntities);
// }
// });
// } else {
// return mUserRepository
// .getAllWithoutPicture(mUseCache)
// .map(new Func1<List<UserEntity>, List<UserModel>>() {
// @Override
// public List<UserModel> call(List<UserEntity> userEntities) {
// return UserMapper.getInstance().transformEntityList(userEntities);
// }
// });
// }
// }
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/domain/model/UserModel.java
// public class UserModel implements Model {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserModel() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/mvp/BasePresenter.java
// public abstract class BasePresenter<V extends BaseMvpView> extends BaseRxMvpPresenter<V> {
//
// }
//
// Path: util/src/main/java/com/marcohc/architecture/common/util/TimerUtils.java
// public class TimerUtils {
//
// private long stepTime;
// private long totalTime;
// private int stepNumber;
// private String tag;
//
// public static TimerUtils getInstance(String tag) {
// return new TimerUtils(tag);
// }
//
// private TimerUtils(String tag) {
// this.tag = tag;
// stepNumber = 1;
// stepTime = System.currentTimeMillis();
// totalTime = System.currentTimeMillis();
// }
//
// /**
// * Prints a log with the step time.
// *
// * @return the step time
// */
// public Long logStep() {
// Long difference = System.currentTimeMillis() - stepTime;
// Timber.d("%s - Step %d: %d", tag, stepNumber++, difference);
// stepTime = System.currentTimeMillis();
// return difference;
// }
//
// /**
// * Prints a log with the step time.
// *
// * @param subTag sub tag used in the log
// * @return the step time
// */
// public Long logStep(String subTag) {
// Long difference = System.currentTimeMillis() - stepTime;
// Timber.d("%s (%s) - Step %d: %d", android.R.attr.tag, subTag, stepNumber++, difference);
// stepTime = System.currentTimeMillis();
// return difference;
// }
//
// /**
// * Prints a log with the total time.
// *
// * @return the total time
// */
// public Long logTotal() {
// Long difference = System.currentTimeMillis() - totalTime;
// Timber.d("%s - TOTAL: %d", tag, difference);
// return difference;
// }
// }
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/story/user/userlist/view/UsersListPresenterImpl.java
import android.support.annotation.NonNull;
import com.marcohc.architecture.app.domain.interactor.GetUsersUseCase;
import com.marcohc.architecture.app.domain.model.UserModel;
import com.marcohc.architecture.app.presentation.mvp.BasePresenter;
import com.marcohc.architecture.common.util.TimerUtils;
import java.util.List;
package com.marcohc.architecture.app.presentation.story.user.userlist.view;
/**
* Presenter implementation of {@link UsersListPresenter}.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
class UsersListPresenterImpl extends BasePresenter<UsersListView> implements UsersListPresenter, GetUsersSubscriber.GetUsersListener {
//region Attributes
private boolean mDataSourceWithPicture = false;
private boolean mUseCache = false;
private TimerUtils mTimer;
private GetUsersUseCase mGetUsersUseCase;
//endregion
//region Presenter interface methods
@Override
public void onViewCreated() {
getView().showLoadingDialog();
requestFreshData();
}
@Override
public void onRefresh() {
requestFreshData();
}
@Override | public void onItemClick(UserModel model) { |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/data/service/user/UsersWithPictureService.java | // Path: app/src/main/java/com/marcohc/architecture/app/domain/entity/UsersWithPictureEntity.java
// public class UsersWithPictureEntity implements Entity {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("results")
// private List<UserWithPicture> mUserWithPicturesList;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UsersWithPictureEntity() {
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public List<UserWithPicture> getUserWithPicturesList() {
// return mUserWithPicturesList;
// }
//
// public void setUserWithPicturesList(List<UserWithPicture> userWithPicturesList) {
// this.mUserWithPicturesList = userWithPicturesList;
// }
//
// /**
// * This is just an example. Gson needs the inner classes as static
// */
// public static class UserWithPicture {
//
// @SerializedName("name")
// private Name mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("picture")
// private Picture mPicture;
//
// public UserWithPicture() {
//
// }
//
// public Picture getPicture() {
// return mPicture;
// }
//
// public void setPicture(Picture picture) {
// this.mPicture = picture;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public Name getName() {
// return mName;
// }
//
// public void setName(Name name) {
// this.mName = name;
// }
//
// /**
// * Pojo class.
// */
// public static class Name {
//
// @SerializedName("first")
// private String mFirst;
//
// public Name() {
// }
//
// public String getFirst() {
// return mFirst;
// }
//
// public void setFirst(String first) {
// this.mFirst = first;
// }
// }
//
// /**
// * Pojo class.
// */
// public static class Picture {
//
// @SerializedName("medium")
// private String mUrl;
//
// public Picture() {
// }
//
// public String getUrl() {
// return mUrl;
// }
//
// public void setUrl(String url) {
// this.mUrl = url;
// }
// }
// }
// }
| import com.marcohc.architecture.app.domain.entity.UsersWithPictureEntity;
import retrofit2.http.GET;
import rx.Observable; | package com.marcohc.architecture.app.data.service.user;
/**
* Data source interface with pictures.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public interface UsersWithPictureService {
/**
* Get a lot of users with picture.
*
* @return the observable with users with picture
*/
@GET("?results=2500") | // Path: app/src/main/java/com/marcohc/architecture/app/domain/entity/UsersWithPictureEntity.java
// public class UsersWithPictureEntity implements Entity {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("results")
// private List<UserWithPicture> mUserWithPicturesList;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UsersWithPictureEntity() {
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public List<UserWithPicture> getUserWithPicturesList() {
// return mUserWithPicturesList;
// }
//
// public void setUserWithPicturesList(List<UserWithPicture> userWithPicturesList) {
// this.mUserWithPicturesList = userWithPicturesList;
// }
//
// /**
// * This is just an example. Gson needs the inner classes as static
// */
// public static class UserWithPicture {
//
// @SerializedName("name")
// private Name mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("picture")
// private Picture mPicture;
//
// public UserWithPicture() {
//
// }
//
// public Picture getPicture() {
// return mPicture;
// }
//
// public void setPicture(Picture picture) {
// this.mPicture = picture;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public Name getName() {
// return mName;
// }
//
// public void setName(Name name) {
// this.mName = name;
// }
//
// /**
// * Pojo class.
// */
// public static class Name {
//
// @SerializedName("first")
// private String mFirst;
//
// public Name() {
// }
//
// public String getFirst() {
// return mFirst;
// }
//
// public void setFirst(String first) {
// this.mFirst = first;
// }
// }
//
// /**
// * Pojo class.
// */
// public static class Picture {
//
// @SerializedName("medium")
// private String mUrl;
//
// public Picture() {
// }
//
// public String getUrl() {
// return mUrl;
// }
//
// public void setUrl(String url) {
// this.mUrl = url;
// }
// }
// }
// }
// Path: app/src/main/java/com/marcohc/architecture/app/data/service/user/UsersWithPictureService.java
import com.marcohc.architecture.app.domain.entity.UsersWithPictureEntity;
import retrofit2.http.GET;
import rx.Observable;
package com.marcohc.architecture.app.data.service.user;
/**
* Data source interface with pictures.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public interface UsersWithPictureService {
/**
* Get a lot of users with picture.
*
* @return the observable with users with picture
*/
@GET("?results=2500") | Observable<UsersWithPictureEntity> getAll(); |
marcohc/android-clean-architecture | service/src/androidTest/java/com/marcohc/architecture/common/service/appinfo/AppInfoServiceTest.java | // Path: common/src/main/java/com/marcohc/architecture/common/service/preferences/PreferencesService.java
// public interface PreferencesService {
//
// void clear();
//
// boolean getBoolean(@NonNull String key, boolean defaultValue);
//
// float getFloat(@NonNull String key, float defaultValue);
//
// int getInt(@NonNull String key, int defaultValue);
//
// long getLong(@NonNull String key, long defaultValue);
//
// @Nullable
// String getString(@NonNull String key, String defaultValue);
//
// void putBoolean(@NonNull String key, boolean value);
//
// void putFloat(@NonNull String key, float value);
//
// void putInt(@NonNull String key, int value);
//
// void putLong(@NonNull String key, long value);
//
// void putString(@NonNull String key, String value);
//
// void remove(@NonNull String key);
// }
//
// Path: service/src/main/java/com/marcohc/architecture/common/service/preferences/PreferencesServiceImpl.java
// public class PreferencesServiceImpl implements PreferencesService {
//
// private final SharedPreferences sharedPreferences;
//
// public PreferencesServiceImpl(Context context, String sharedPreferencesName) {
// sharedPreferences = context.getSharedPreferences(sharedPreferencesName, Context.MODE_PRIVATE);
// }
//
// public PreferencesServiceImpl(Context context) {
// String defaultName = String.format("%s_%s", context.getPackageName(), "preferences");
// sharedPreferences = context.getSharedPreferences(defaultName, Context.MODE_PRIVATE);
// }
//
// @Override
// public void clear() {
// sharedPreferences.edit().clear().apply();
// }
//
// @Override
// public boolean getBoolean(@NonNull String key, boolean defaultValue) {
// return sharedPreferences.getBoolean(Preconditions.checkNotNull(key), defaultValue);
// }
//
// @Override
// public float getFloat(@NonNull String key, float defaultValue) {
// return sharedPreferences.getFloat(Preconditions.checkNotNull(key), defaultValue);
// }
//
// @Override
// public int getInt(@NonNull String key, int defaultValue) {
// return sharedPreferences.getInt(Preconditions.checkNotNull(key), defaultValue);
// }
//
// @Override
// public long getLong(@NonNull String key, long defaultValue) {
// return sharedPreferences.getLong(Preconditions.checkNotNull(key), defaultValue);
// }
//
// @Override
// @Nullable
// public String getString(@NonNull String key, @Nullable String defaultValue) {
// return sharedPreferences.getString(Preconditions.checkNotNull(key), defaultValue);
// }
//
// @Override
// public void putBoolean(@NonNull String key, boolean value) {
// sharedPreferences.edit().putBoolean(Preconditions.checkNotNull(key), value).apply();
// }
//
// @Override
// public void putFloat(@NonNull String key, float value) {
// sharedPreferences.edit().putFloat(Preconditions.checkNotNull(key), value).apply();
// }
//
// @Override
// public void putInt(@NonNull String key, int value) {
// sharedPreferences.edit().putInt(Preconditions.checkNotNull(key), value).apply();
// }
//
// @Override
// public void putLong(@NonNull String key, long value) {
// sharedPreferences.edit().putLong(Preconditions.checkNotNull(key), value).apply();
// }
//
// @Override
// public void putString(@NonNull String key, @Nullable String value) {
// sharedPreferences.edit().putString(Preconditions.checkNotNull(key), value).apply();
// }
//
// @Override
// public void remove(@NonNull String key) {
// sharedPreferences.edit().remove(key).apply();
// }
//
// }
| import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import com.marcohc.architecture.common.service.preferences.PreferencesService;
import com.marcohc.architecture.common.service.preferences.PreferencesServiceImpl;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import java.util.Calendar;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue; | package com.marcohc.architecture.common.service.appinfo;
@RunWith(AndroidJUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class AppInfoServiceTest {
private AppInfoService appInfoService; | // Path: common/src/main/java/com/marcohc/architecture/common/service/preferences/PreferencesService.java
// public interface PreferencesService {
//
// void clear();
//
// boolean getBoolean(@NonNull String key, boolean defaultValue);
//
// float getFloat(@NonNull String key, float defaultValue);
//
// int getInt(@NonNull String key, int defaultValue);
//
// long getLong(@NonNull String key, long defaultValue);
//
// @Nullable
// String getString(@NonNull String key, String defaultValue);
//
// void putBoolean(@NonNull String key, boolean value);
//
// void putFloat(@NonNull String key, float value);
//
// void putInt(@NonNull String key, int value);
//
// void putLong(@NonNull String key, long value);
//
// void putString(@NonNull String key, String value);
//
// void remove(@NonNull String key);
// }
//
// Path: service/src/main/java/com/marcohc/architecture/common/service/preferences/PreferencesServiceImpl.java
// public class PreferencesServiceImpl implements PreferencesService {
//
// private final SharedPreferences sharedPreferences;
//
// public PreferencesServiceImpl(Context context, String sharedPreferencesName) {
// sharedPreferences = context.getSharedPreferences(sharedPreferencesName, Context.MODE_PRIVATE);
// }
//
// public PreferencesServiceImpl(Context context) {
// String defaultName = String.format("%s_%s", context.getPackageName(), "preferences");
// sharedPreferences = context.getSharedPreferences(defaultName, Context.MODE_PRIVATE);
// }
//
// @Override
// public void clear() {
// sharedPreferences.edit().clear().apply();
// }
//
// @Override
// public boolean getBoolean(@NonNull String key, boolean defaultValue) {
// return sharedPreferences.getBoolean(Preconditions.checkNotNull(key), defaultValue);
// }
//
// @Override
// public float getFloat(@NonNull String key, float defaultValue) {
// return sharedPreferences.getFloat(Preconditions.checkNotNull(key), defaultValue);
// }
//
// @Override
// public int getInt(@NonNull String key, int defaultValue) {
// return sharedPreferences.getInt(Preconditions.checkNotNull(key), defaultValue);
// }
//
// @Override
// public long getLong(@NonNull String key, long defaultValue) {
// return sharedPreferences.getLong(Preconditions.checkNotNull(key), defaultValue);
// }
//
// @Override
// @Nullable
// public String getString(@NonNull String key, @Nullable String defaultValue) {
// return sharedPreferences.getString(Preconditions.checkNotNull(key), defaultValue);
// }
//
// @Override
// public void putBoolean(@NonNull String key, boolean value) {
// sharedPreferences.edit().putBoolean(Preconditions.checkNotNull(key), value).apply();
// }
//
// @Override
// public void putFloat(@NonNull String key, float value) {
// sharedPreferences.edit().putFloat(Preconditions.checkNotNull(key), value).apply();
// }
//
// @Override
// public void putInt(@NonNull String key, int value) {
// sharedPreferences.edit().putInt(Preconditions.checkNotNull(key), value).apply();
// }
//
// @Override
// public void putLong(@NonNull String key, long value) {
// sharedPreferences.edit().putLong(Preconditions.checkNotNull(key), value).apply();
// }
//
// @Override
// public void putString(@NonNull String key, @Nullable String value) {
// sharedPreferences.edit().putString(Preconditions.checkNotNull(key), value).apply();
// }
//
// @Override
// public void remove(@NonNull String key) {
// sharedPreferences.edit().remove(key).apply();
// }
//
// }
// Path: service/src/androidTest/java/com/marcohc/architecture/common/service/appinfo/AppInfoServiceTest.java
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import com.marcohc.architecture.common.service.preferences.PreferencesService;
import com.marcohc.architecture.common.service.preferences.PreferencesServiceImpl;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import java.util.Calendar;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
package com.marcohc.architecture.common.service.appinfo;
@RunWith(AndroidJUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class AppInfoServiceTest {
private AppInfoService appInfoService; | private PreferencesService mPreferencesService; |
marcohc/android-clean-architecture | service/src/androidTest/java/com/marcohc/architecture/common/service/appinfo/AppInfoServiceTest.java | // Path: common/src/main/java/com/marcohc/architecture/common/service/preferences/PreferencesService.java
// public interface PreferencesService {
//
// void clear();
//
// boolean getBoolean(@NonNull String key, boolean defaultValue);
//
// float getFloat(@NonNull String key, float defaultValue);
//
// int getInt(@NonNull String key, int defaultValue);
//
// long getLong(@NonNull String key, long defaultValue);
//
// @Nullable
// String getString(@NonNull String key, String defaultValue);
//
// void putBoolean(@NonNull String key, boolean value);
//
// void putFloat(@NonNull String key, float value);
//
// void putInt(@NonNull String key, int value);
//
// void putLong(@NonNull String key, long value);
//
// void putString(@NonNull String key, String value);
//
// void remove(@NonNull String key);
// }
//
// Path: service/src/main/java/com/marcohc/architecture/common/service/preferences/PreferencesServiceImpl.java
// public class PreferencesServiceImpl implements PreferencesService {
//
// private final SharedPreferences sharedPreferences;
//
// public PreferencesServiceImpl(Context context, String sharedPreferencesName) {
// sharedPreferences = context.getSharedPreferences(sharedPreferencesName, Context.MODE_PRIVATE);
// }
//
// public PreferencesServiceImpl(Context context) {
// String defaultName = String.format("%s_%s", context.getPackageName(), "preferences");
// sharedPreferences = context.getSharedPreferences(defaultName, Context.MODE_PRIVATE);
// }
//
// @Override
// public void clear() {
// sharedPreferences.edit().clear().apply();
// }
//
// @Override
// public boolean getBoolean(@NonNull String key, boolean defaultValue) {
// return sharedPreferences.getBoolean(Preconditions.checkNotNull(key), defaultValue);
// }
//
// @Override
// public float getFloat(@NonNull String key, float defaultValue) {
// return sharedPreferences.getFloat(Preconditions.checkNotNull(key), defaultValue);
// }
//
// @Override
// public int getInt(@NonNull String key, int defaultValue) {
// return sharedPreferences.getInt(Preconditions.checkNotNull(key), defaultValue);
// }
//
// @Override
// public long getLong(@NonNull String key, long defaultValue) {
// return sharedPreferences.getLong(Preconditions.checkNotNull(key), defaultValue);
// }
//
// @Override
// @Nullable
// public String getString(@NonNull String key, @Nullable String defaultValue) {
// return sharedPreferences.getString(Preconditions.checkNotNull(key), defaultValue);
// }
//
// @Override
// public void putBoolean(@NonNull String key, boolean value) {
// sharedPreferences.edit().putBoolean(Preconditions.checkNotNull(key), value).apply();
// }
//
// @Override
// public void putFloat(@NonNull String key, float value) {
// sharedPreferences.edit().putFloat(Preconditions.checkNotNull(key), value).apply();
// }
//
// @Override
// public void putInt(@NonNull String key, int value) {
// sharedPreferences.edit().putInt(Preconditions.checkNotNull(key), value).apply();
// }
//
// @Override
// public void putLong(@NonNull String key, long value) {
// sharedPreferences.edit().putLong(Preconditions.checkNotNull(key), value).apply();
// }
//
// @Override
// public void putString(@NonNull String key, @Nullable String value) {
// sharedPreferences.edit().putString(Preconditions.checkNotNull(key), value).apply();
// }
//
// @Override
// public void remove(@NonNull String key) {
// sharedPreferences.edit().remove(key).apply();
// }
//
// }
| import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import com.marcohc.architecture.common.service.preferences.PreferencesService;
import com.marcohc.architecture.common.service.preferences.PreferencesServiceImpl;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import java.util.Calendar;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue; | package com.marcohc.architecture.common.service.appinfo;
@RunWith(AndroidJUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class AppInfoServiceTest {
private AppInfoService appInfoService;
private PreferencesService mPreferencesService;
@Before
public void before() {
Context context = InstrumentationRegistry.getTargetContext(); | // Path: common/src/main/java/com/marcohc/architecture/common/service/preferences/PreferencesService.java
// public interface PreferencesService {
//
// void clear();
//
// boolean getBoolean(@NonNull String key, boolean defaultValue);
//
// float getFloat(@NonNull String key, float defaultValue);
//
// int getInt(@NonNull String key, int defaultValue);
//
// long getLong(@NonNull String key, long defaultValue);
//
// @Nullable
// String getString(@NonNull String key, String defaultValue);
//
// void putBoolean(@NonNull String key, boolean value);
//
// void putFloat(@NonNull String key, float value);
//
// void putInt(@NonNull String key, int value);
//
// void putLong(@NonNull String key, long value);
//
// void putString(@NonNull String key, String value);
//
// void remove(@NonNull String key);
// }
//
// Path: service/src/main/java/com/marcohc/architecture/common/service/preferences/PreferencesServiceImpl.java
// public class PreferencesServiceImpl implements PreferencesService {
//
// private final SharedPreferences sharedPreferences;
//
// public PreferencesServiceImpl(Context context, String sharedPreferencesName) {
// sharedPreferences = context.getSharedPreferences(sharedPreferencesName, Context.MODE_PRIVATE);
// }
//
// public PreferencesServiceImpl(Context context) {
// String defaultName = String.format("%s_%s", context.getPackageName(), "preferences");
// sharedPreferences = context.getSharedPreferences(defaultName, Context.MODE_PRIVATE);
// }
//
// @Override
// public void clear() {
// sharedPreferences.edit().clear().apply();
// }
//
// @Override
// public boolean getBoolean(@NonNull String key, boolean defaultValue) {
// return sharedPreferences.getBoolean(Preconditions.checkNotNull(key), defaultValue);
// }
//
// @Override
// public float getFloat(@NonNull String key, float defaultValue) {
// return sharedPreferences.getFloat(Preconditions.checkNotNull(key), defaultValue);
// }
//
// @Override
// public int getInt(@NonNull String key, int defaultValue) {
// return sharedPreferences.getInt(Preconditions.checkNotNull(key), defaultValue);
// }
//
// @Override
// public long getLong(@NonNull String key, long defaultValue) {
// return sharedPreferences.getLong(Preconditions.checkNotNull(key), defaultValue);
// }
//
// @Override
// @Nullable
// public String getString(@NonNull String key, @Nullable String defaultValue) {
// return sharedPreferences.getString(Preconditions.checkNotNull(key), defaultValue);
// }
//
// @Override
// public void putBoolean(@NonNull String key, boolean value) {
// sharedPreferences.edit().putBoolean(Preconditions.checkNotNull(key), value).apply();
// }
//
// @Override
// public void putFloat(@NonNull String key, float value) {
// sharedPreferences.edit().putFloat(Preconditions.checkNotNull(key), value).apply();
// }
//
// @Override
// public void putInt(@NonNull String key, int value) {
// sharedPreferences.edit().putInt(Preconditions.checkNotNull(key), value).apply();
// }
//
// @Override
// public void putLong(@NonNull String key, long value) {
// sharedPreferences.edit().putLong(Preconditions.checkNotNull(key), value).apply();
// }
//
// @Override
// public void putString(@NonNull String key, @Nullable String value) {
// sharedPreferences.edit().putString(Preconditions.checkNotNull(key), value).apply();
// }
//
// @Override
// public void remove(@NonNull String key) {
// sharedPreferences.edit().remove(key).apply();
// }
//
// }
// Path: service/src/androidTest/java/com/marcohc/architecture/common/service/appinfo/AppInfoServiceTest.java
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import com.marcohc.architecture.common.service.preferences.PreferencesService;
import com.marcohc.architecture.common.service.preferences.PreferencesServiceImpl;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import java.util.Calendar;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
package com.marcohc.architecture.common.service.appinfo;
@RunWith(AndroidJUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class AppInfoServiceTest {
private AppInfoService appInfoService;
private PreferencesService mPreferencesService;
@Before
public void before() {
Context context = InstrumentationRegistry.getTargetContext(); | appInfoService = new AppInfoServiceImpl(new PreferencesServiceImpl(context)); |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/internal/di/ApplicationModule.java | // Path: app/src/main/java/com/marcohc/architecture/app/data/repository/user/UserRepository.java
// public interface UserRepository {
//
// /**
// * Get all users with picture based on parameters.
// *
// * @param useCache use the cache
// * @return the Observable with a list of users
// */
// Observable<List<UserEntity>> getAllWithPicture(boolean useCache);
//
// /**
// * Get all users without picture based on parameters.
// *
// * @param useCache use the cache
// * @return the Observable with a list of users
// */
// Observable<List<UserEntity>> getAllWithoutPicture(boolean useCache);
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/repository/user/UserRepositoryImpl.java
// @Singleton
// public class UserRepositoryImpl implements UserRepository {
//
// private final UserDiskDataStore diskDataStore;
// private final UserCloudDataStore userWithPicturesCloudDataStore;
// private final UserCloudDataStore userWithoutPicturesCloudDataStore;
//
// public UserRepositoryImpl() {
// diskDataStore = UserDataStoreFactory.createUserDiskDataStore();
// userWithPicturesCloudDataStore = UserDataStoreFactory.createUserWithPicturesCloudDataStore();
// userWithoutPicturesCloudDataStore = UserDataStoreFactory.createUserWithoutPicturesCloudDataStore();
// }
//
// @Override
// public Observable<List<UserEntity>> getAllWithPicture(boolean useCache) {
// final String cacheKey = ALL_WITH_PICTURE;
// if (useCache && diskDataStore.isCached(cacheKey)) {
// return diskDataStore.getUsersWithPicture();
// } else {
// return userWithPicturesCloudDataStore
// .getAll()
// .doOnNext(new Action1<List<UserEntity>>() {
// @Override
// public void call(List<UserEntity> entityList) {
// diskDataStore.put(cacheKey, entityList);
// }
// });
// }
// }
//
// @Override
// public Observable<List<UserEntity>> getAllWithoutPicture(boolean useCache) {
// final String cacheKey = ALL_WITHOUT_PICTURE;
// if (useCache && diskDataStore.isCached(cacheKey)) {
// return diskDataStore.getUsersWithoutPicture();
// } else {
// return userWithoutPicturesCloudDataStore
// .getAll()
// .doOnNext(new Action1<List<UserEntity>>() {
// @Override
// public void call(List<UserEntity> entityList) {
// diskDataStore.put(cacheKey, entityList);
// }
// });
// }
// }
//
// }
| import android.content.Context;
import com.marcohc.architecture.app.data.repository.user.UserRepository;
import com.marcohc.architecture.app.data.repository.user.UserRepositoryImpl;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides; | package com.marcohc.architecture.app.internal.di;
/**
* Dagger module.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
@Module
public class ApplicationModule {
private final Context mContext;
ApplicationModule(Context context) {
this.mContext = context;
}
@Provides
@Singleton
Context provideContext() {
return mContext;
}
@Provides
@Singleton | // Path: app/src/main/java/com/marcohc/architecture/app/data/repository/user/UserRepository.java
// public interface UserRepository {
//
// /**
// * Get all users with picture based on parameters.
// *
// * @param useCache use the cache
// * @return the Observable with a list of users
// */
// Observable<List<UserEntity>> getAllWithPicture(boolean useCache);
//
// /**
// * Get all users without picture based on parameters.
// *
// * @param useCache use the cache
// * @return the Observable with a list of users
// */
// Observable<List<UserEntity>> getAllWithoutPicture(boolean useCache);
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/repository/user/UserRepositoryImpl.java
// @Singleton
// public class UserRepositoryImpl implements UserRepository {
//
// private final UserDiskDataStore diskDataStore;
// private final UserCloudDataStore userWithPicturesCloudDataStore;
// private final UserCloudDataStore userWithoutPicturesCloudDataStore;
//
// public UserRepositoryImpl() {
// diskDataStore = UserDataStoreFactory.createUserDiskDataStore();
// userWithPicturesCloudDataStore = UserDataStoreFactory.createUserWithPicturesCloudDataStore();
// userWithoutPicturesCloudDataStore = UserDataStoreFactory.createUserWithoutPicturesCloudDataStore();
// }
//
// @Override
// public Observable<List<UserEntity>> getAllWithPicture(boolean useCache) {
// final String cacheKey = ALL_WITH_PICTURE;
// if (useCache && diskDataStore.isCached(cacheKey)) {
// return diskDataStore.getUsersWithPicture();
// } else {
// return userWithPicturesCloudDataStore
// .getAll()
// .doOnNext(new Action1<List<UserEntity>>() {
// @Override
// public void call(List<UserEntity> entityList) {
// diskDataStore.put(cacheKey, entityList);
// }
// });
// }
// }
//
// @Override
// public Observable<List<UserEntity>> getAllWithoutPicture(boolean useCache) {
// final String cacheKey = ALL_WITHOUT_PICTURE;
// if (useCache && diskDataStore.isCached(cacheKey)) {
// return diskDataStore.getUsersWithoutPicture();
// } else {
// return userWithoutPicturesCloudDataStore
// .getAll()
// .doOnNext(new Action1<List<UserEntity>>() {
// @Override
// public void call(List<UserEntity> entityList) {
// diskDataStore.put(cacheKey, entityList);
// }
// });
// }
// }
//
// }
// Path: app/src/main/java/com/marcohc/architecture/app/internal/di/ApplicationModule.java
import android.content.Context;
import com.marcohc.architecture.app.data.repository.user.UserRepository;
import com.marcohc.architecture.app.data.repository.user.UserRepositoryImpl;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
package com.marcohc.architecture.app.internal.di;
/**
* Dagger module.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
@Module
public class ApplicationModule {
private final Context mContext;
ApplicationModule(Context context) {
this.mContext = context;
}
@Provides
@Singleton
Context provideContext() {
return mContext;
}
@Provides
@Singleton | UserRepository provideUserRepository() { |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/internal/di/ApplicationModule.java | // Path: app/src/main/java/com/marcohc/architecture/app/data/repository/user/UserRepository.java
// public interface UserRepository {
//
// /**
// * Get all users with picture based on parameters.
// *
// * @param useCache use the cache
// * @return the Observable with a list of users
// */
// Observable<List<UserEntity>> getAllWithPicture(boolean useCache);
//
// /**
// * Get all users without picture based on parameters.
// *
// * @param useCache use the cache
// * @return the Observable with a list of users
// */
// Observable<List<UserEntity>> getAllWithoutPicture(boolean useCache);
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/repository/user/UserRepositoryImpl.java
// @Singleton
// public class UserRepositoryImpl implements UserRepository {
//
// private final UserDiskDataStore diskDataStore;
// private final UserCloudDataStore userWithPicturesCloudDataStore;
// private final UserCloudDataStore userWithoutPicturesCloudDataStore;
//
// public UserRepositoryImpl() {
// diskDataStore = UserDataStoreFactory.createUserDiskDataStore();
// userWithPicturesCloudDataStore = UserDataStoreFactory.createUserWithPicturesCloudDataStore();
// userWithoutPicturesCloudDataStore = UserDataStoreFactory.createUserWithoutPicturesCloudDataStore();
// }
//
// @Override
// public Observable<List<UserEntity>> getAllWithPicture(boolean useCache) {
// final String cacheKey = ALL_WITH_PICTURE;
// if (useCache && diskDataStore.isCached(cacheKey)) {
// return diskDataStore.getUsersWithPicture();
// } else {
// return userWithPicturesCloudDataStore
// .getAll()
// .doOnNext(new Action1<List<UserEntity>>() {
// @Override
// public void call(List<UserEntity> entityList) {
// diskDataStore.put(cacheKey, entityList);
// }
// });
// }
// }
//
// @Override
// public Observable<List<UserEntity>> getAllWithoutPicture(boolean useCache) {
// final String cacheKey = ALL_WITHOUT_PICTURE;
// if (useCache && diskDataStore.isCached(cacheKey)) {
// return diskDataStore.getUsersWithoutPicture();
// } else {
// return userWithoutPicturesCloudDataStore
// .getAll()
// .doOnNext(new Action1<List<UserEntity>>() {
// @Override
// public void call(List<UserEntity> entityList) {
// diskDataStore.put(cacheKey, entityList);
// }
// });
// }
// }
//
// }
| import android.content.Context;
import com.marcohc.architecture.app.data.repository.user.UserRepository;
import com.marcohc.architecture.app.data.repository.user.UserRepositoryImpl;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides; | package com.marcohc.architecture.app.internal.di;
/**
* Dagger module.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
@Module
public class ApplicationModule {
private final Context mContext;
ApplicationModule(Context context) {
this.mContext = context;
}
@Provides
@Singleton
Context provideContext() {
return mContext;
}
@Provides
@Singleton
UserRepository provideUserRepository() { | // Path: app/src/main/java/com/marcohc/architecture/app/data/repository/user/UserRepository.java
// public interface UserRepository {
//
// /**
// * Get all users with picture based on parameters.
// *
// * @param useCache use the cache
// * @return the Observable with a list of users
// */
// Observable<List<UserEntity>> getAllWithPicture(boolean useCache);
//
// /**
// * Get all users without picture based on parameters.
// *
// * @param useCache use the cache
// * @return the Observable with a list of users
// */
// Observable<List<UserEntity>> getAllWithoutPicture(boolean useCache);
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/repository/user/UserRepositoryImpl.java
// @Singleton
// public class UserRepositoryImpl implements UserRepository {
//
// private final UserDiskDataStore diskDataStore;
// private final UserCloudDataStore userWithPicturesCloudDataStore;
// private final UserCloudDataStore userWithoutPicturesCloudDataStore;
//
// public UserRepositoryImpl() {
// diskDataStore = UserDataStoreFactory.createUserDiskDataStore();
// userWithPicturesCloudDataStore = UserDataStoreFactory.createUserWithPicturesCloudDataStore();
// userWithoutPicturesCloudDataStore = UserDataStoreFactory.createUserWithoutPicturesCloudDataStore();
// }
//
// @Override
// public Observable<List<UserEntity>> getAllWithPicture(boolean useCache) {
// final String cacheKey = ALL_WITH_PICTURE;
// if (useCache && diskDataStore.isCached(cacheKey)) {
// return diskDataStore.getUsersWithPicture();
// } else {
// return userWithPicturesCloudDataStore
// .getAll()
// .doOnNext(new Action1<List<UserEntity>>() {
// @Override
// public void call(List<UserEntity> entityList) {
// diskDataStore.put(cacheKey, entityList);
// }
// });
// }
// }
//
// @Override
// public Observable<List<UserEntity>> getAllWithoutPicture(boolean useCache) {
// final String cacheKey = ALL_WITHOUT_PICTURE;
// if (useCache && diskDataStore.isCached(cacheKey)) {
// return diskDataStore.getUsersWithoutPicture();
// } else {
// return userWithoutPicturesCloudDataStore
// .getAll()
// .doOnNext(new Action1<List<UserEntity>>() {
// @Override
// public void call(List<UserEntity> entityList) {
// diskDataStore.put(cacheKey, entityList);
// }
// });
// }
// }
//
// }
// Path: app/src/main/java/com/marcohc/architecture/app/internal/di/ApplicationModule.java
import android.content.Context;
import com.marcohc.architecture.app.data.repository.user.UserRepository;
import com.marcohc.architecture.app.data.repository.user.UserRepositoryImpl;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
package com.marcohc.architecture.app.internal.di;
/**
* Dagger module.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
@Module
public class ApplicationModule {
private final Context mContext;
ApplicationModule(Context context) {
this.mContext = context;
}
@Provides
@Singleton
Context provideContext() {
return mContext;
}
@Provides
@Singleton
UserRepository provideUserRepository() { | return new UserRepositoryImpl(); |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/presentation/story/user/userdetail/view/UserDetailPresenterImpl.java | // Path: app/src/main/java/com/marcohc/architecture/app/domain/model/UserModel.java
// public class UserModel implements Model {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserModel() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/navigation/Navigator.java
// public final class Navigator {
//
// // ************************************************************************************************************************************************************************
// // * Constants
// // ************************************************************************************************************************************************************************
//
// public static final String USER = "user";
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// private Navigator() {
// }
//
// // ************************************************************************************************************************************************************************
// // * Navigation methods
// // ************************************************************************************************************************************************************************
//
// /**
// * Go to {@link UserDetailActivity}.
// *
// * @param context the context
// * @param model the UserModel to be displayed in the details
// */
// public static void goToUserDetail(Context context, UserModel model) {
// if (context != null && model != null) {
// Intent intent = new Intent(context, UserDetailActivity.class);
// intent.putExtra(Navigator.USER, model);
// context.startActivity(intent);
// }
// }
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpPresenter.java
// public abstract class BaseMvpPresenter<V extends BaseMvpView> extends MvpNullObjectBasePresenter<V> {
// }
| import android.app.Activity;
import com.marcohc.architecture.app.domain.model.UserModel;
import com.marcohc.architecture.app.presentation.navigation.Navigator;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpPresenter;
import dagger.internal.Preconditions; | package com.marcohc.architecture.app.presentation.story.user.userdetail.view;
/**
* Presenter implementation of {@link UserDetailPresenter}.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
class UserDetailPresenterImpl extends BaseMvpPresenter<UserDetailView> implements UserDetailPresenter {
// ************************************************************************************************************************************************************************
// * View handler methods
// ************************************************************************************************************************************************************************
@Override
public void onViewCreated(Activity activity) {
Preconditions.checkNotNull(activity, "activity");
| // Path: app/src/main/java/com/marcohc/architecture/app/domain/model/UserModel.java
// public class UserModel implements Model {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserModel() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/navigation/Navigator.java
// public final class Navigator {
//
// // ************************************************************************************************************************************************************************
// // * Constants
// // ************************************************************************************************************************************************************************
//
// public static final String USER = "user";
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// private Navigator() {
// }
//
// // ************************************************************************************************************************************************************************
// // * Navigation methods
// // ************************************************************************************************************************************************************************
//
// /**
// * Go to {@link UserDetailActivity}.
// *
// * @param context the context
// * @param model the UserModel to be displayed in the details
// */
// public static void goToUserDetail(Context context, UserModel model) {
// if (context != null && model != null) {
// Intent intent = new Intent(context, UserDetailActivity.class);
// intent.putExtra(Navigator.USER, model);
// context.startActivity(intent);
// }
// }
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpPresenter.java
// public abstract class BaseMvpPresenter<V extends BaseMvpView> extends MvpNullObjectBasePresenter<V> {
// }
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/story/user/userdetail/view/UserDetailPresenterImpl.java
import android.app.Activity;
import com.marcohc.architecture.app.domain.model.UserModel;
import com.marcohc.architecture.app.presentation.navigation.Navigator;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpPresenter;
import dagger.internal.Preconditions;
package com.marcohc.architecture.app.presentation.story.user.userdetail.view;
/**
* Presenter implementation of {@link UserDetailPresenter}.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
class UserDetailPresenterImpl extends BaseMvpPresenter<UserDetailView> implements UserDetailPresenter {
// ************************************************************************************************************************************************************************
// * View handler methods
// ************************************************************************************************************************************************************************
@Override
public void onViewCreated(Activity activity) {
Preconditions.checkNotNull(activity, "activity");
| UserModel user = (UserModel) activity.getIntent().getSerializableExtra(Navigator.USER); |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/presentation/story/user/userdetail/view/UserDetailPresenterImpl.java | // Path: app/src/main/java/com/marcohc/architecture/app/domain/model/UserModel.java
// public class UserModel implements Model {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserModel() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/navigation/Navigator.java
// public final class Navigator {
//
// // ************************************************************************************************************************************************************************
// // * Constants
// // ************************************************************************************************************************************************************************
//
// public static final String USER = "user";
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// private Navigator() {
// }
//
// // ************************************************************************************************************************************************************************
// // * Navigation methods
// // ************************************************************************************************************************************************************************
//
// /**
// * Go to {@link UserDetailActivity}.
// *
// * @param context the context
// * @param model the UserModel to be displayed in the details
// */
// public static void goToUserDetail(Context context, UserModel model) {
// if (context != null && model != null) {
// Intent intent = new Intent(context, UserDetailActivity.class);
// intent.putExtra(Navigator.USER, model);
// context.startActivity(intent);
// }
// }
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpPresenter.java
// public abstract class BaseMvpPresenter<V extends BaseMvpView> extends MvpNullObjectBasePresenter<V> {
// }
| import android.app.Activity;
import com.marcohc.architecture.app.domain.model.UserModel;
import com.marcohc.architecture.app.presentation.navigation.Navigator;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpPresenter;
import dagger.internal.Preconditions; | package com.marcohc.architecture.app.presentation.story.user.userdetail.view;
/**
* Presenter implementation of {@link UserDetailPresenter}.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
class UserDetailPresenterImpl extends BaseMvpPresenter<UserDetailView> implements UserDetailPresenter {
// ************************************************************************************************************************************************************************
// * View handler methods
// ************************************************************************************************************************************************************************
@Override
public void onViewCreated(Activity activity) {
Preconditions.checkNotNull(activity, "activity");
| // Path: app/src/main/java/com/marcohc/architecture/app/domain/model/UserModel.java
// public class UserModel implements Model {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserModel() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/navigation/Navigator.java
// public final class Navigator {
//
// // ************************************************************************************************************************************************************************
// // * Constants
// // ************************************************************************************************************************************************************************
//
// public static final String USER = "user";
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// private Navigator() {
// }
//
// // ************************************************************************************************************************************************************************
// // * Navigation methods
// // ************************************************************************************************************************************************************************
//
// /**
// * Go to {@link UserDetailActivity}.
// *
// * @param context the context
// * @param model the UserModel to be displayed in the details
// */
// public static void goToUserDetail(Context context, UserModel model) {
// if (context != null && model != null) {
// Intent intent = new Intent(context, UserDetailActivity.class);
// intent.putExtra(Navigator.USER, model);
// context.startActivity(intent);
// }
// }
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpPresenter.java
// public abstract class BaseMvpPresenter<V extends BaseMvpView> extends MvpNullObjectBasePresenter<V> {
// }
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/story/user/userdetail/view/UserDetailPresenterImpl.java
import android.app.Activity;
import com.marcohc.architecture.app.domain.model.UserModel;
import com.marcohc.architecture.app.presentation.navigation.Navigator;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpPresenter;
import dagger.internal.Preconditions;
package com.marcohc.architecture.app.presentation.story.user.userdetail.view;
/**
* Presenter implementation of {@link UserDetailPresenter}.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
class UserDetailPresenterImpl extends BaseMvpPresenter<UserDetailView> implements UserDetailPresenter {
// ************************************************************************************************************************************************************************
// * View handler methods
// ************************************************************************************************************************************************************************
@Override
public void onViewCreated(Activity activity) {
Preconditions.checkNotNull(activity, "activity");
| UserModel user = (UserModel) activity.getIntent().getSerializableExtra(Navigator.USER); |
marcohc/android-clean-architecture | common/src/main/java/com/marcohc/architecture/common/thread/JobThreadFactory.java | // Path: common/src/main/java/com/marcohc/architecture/common/util/utils/Preconditions.java
// public final class Preconditions {
//
// private Preconditions() {
// // no-op
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @param name the variable name
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference, String name) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException(name + " must not be null.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @param name the variable name
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression, @Nullable String name) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be false.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures not blank in parameters.
// *
// * @param value the value to check
// * @param name the name you want to display in the logs
// * @param <T> the type of the value
// * @return the value you want to check
// */
// @NonNull
// public static <T extends CharSequence> T nonBlank(@Nullable T value, String name) {
// if (StringUtils.isBlank(value)) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be blank.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return value;
// }
//
// @NonNull
// private static StackTraceElement[] getStackTrace(@NonNull Exception exception) {
// final StackTraceElement[] sourceStack = exception.getStackTrace();
//
// final StackTraceElement[] updatedStack = new StackTraceElement[sourceStack.length - 1];
// System.arraycopy(sourceStack, 1, updatedStack, 0, updatedStack.length);
//
// return updatedStack;
// }
// }
| import android.support.annotation.NonNull;
import com.marcohc.architecture.common.util.utils.Preconditions;
import java.util.concurrent.ThreadFactory; | package com.marcohc.architecture.common.thread;
/**
* Thread factory which assignees tags for each thread.
*/
class JobThreadFactory implements ThreadFactory {
private static final String THREAD_NAME = "job_executor_";
private int counter = 0;
@Override
public Thread newThread(@NonNull Runnable runnable) { | // Path: common/src/main/java/com/marcohc/architecture/common/util/utils/Preconditions.java
// public final class Preconditions {
//
// private Preconditions() {
// // no-op
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @param name the variable name
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference, String name) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException(name + " must not be null.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @param name the variable name
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression, @Nullable String name) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be false.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures not blank in parameters.
// *
// * @param value the value to check
// * @param name the name you want to display in the logs
// * @param <T> the type of the value
// * @return the value you want to check
// */
// @NonNull
// public static <T extends CharSequence> T nonBlank(@Nullable T value, String name) {
// if (StringUtils.isBlank(value)) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be blank.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return value;
// }
//
// @NonNull
// private static StackTraceElement[] getStackTrace(@NonNull Exception exception) {
// final StackTraceElement[] sourceStack = exception.getStackTrace();
//
// final StackTraceElement[] updatedStack = new StackTraceElement[sourceStack.length - 1];
// System.arraycopy(sourceStack, 1, updatedStack, 0, updatedStack.length);
//
// return updatedStack;
// }
// }
// Path: common/src/main/java/com/marcohc/architecture/common/thread/JobThreadFactory.java
import android.support.annotation.NonNull;
import com.marcohc.architecture.common.util.utils.Preconditions;
import java.util.concurrent.ThreadFactory;
package com.marcohc.architecture.common.thread;
/**
* Thread factory which assignees tags for each thread.
*/
class JobThreadFactory implements ThreadFactory {
private static final String THREAD_NAME = "job_executor_";
private int counter = 0;
@Override
public Thread newThread(@NonNull Runnable runnable) { | Preconditions.checkNotNull(runnable, "runnable"); |
marcohc/android-clean-architecture | firebase/src/main/java/com/marcohc/architecture/firebase/Firebase.java | // Path: common/src/main/java/com/marcohc/architecture/common/util/utils/Preconditions.java
// public final class Preconditions {
//
// private Preconditions() {
// // no-op
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @param name the variable name
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference, String name) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException(name + " must not be null.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @param name the variable name
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression, @Nullable String name) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be false.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures not blank in parameters.
// *
// * @param value the value to check
// * @param name the name you want to display in the logs
// * @param <T> the type of the value
// * @return the value you want to check
// */
// @NonNull
// public static <T extends CharSequence> T nonBlank(@Nullable T value, String name) {
// if (StringUtils.isBlank(value)) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be blank.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return value;
// }
//
// @NonNull
// private static StackTraceElement[] getStackTrace(@NonNull Exception exception) {
// final StackTraceElement[] sourceStack = exception.getStackTrace();
//
// final StackTraceElement[] updatedStack = new StackTraceElement[sourceStack.length - 1];
// System.arraycopy(sourceStack, 1, updatedStack, 0, updatedStack.length);
//
// return updatedStack;
// }
// }
| import android.content.Context;
import android.support.annotation.NonNull;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.TaskCompletionSource;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Logger;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.kelvinapps.rxfirebase.RxFirebaseDatabase;
import com.marcohc.architecture.common.util.utils.Preconditions;
import java.util.Map;
import rx.Observable;
import timber.log.Timber; | package com.marcohc.architecture.firebase;
public final class Firebase {
private static DatabaseReference databaseReference;
private static NetworkService networkService;
private Firebase() {
}
//region Public static methods
public static String buildPath(@NonNull String... pathItems) { | // Path: common/src/main/java/com/marcohc/architecture/common/util/utils/Preconditions.java
// public final class Preconditions {
//
// private Preconditions() {
// // no-op
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @param name the variable name
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference, String name) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException(name + " must not be null.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @param name the variable name
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression, @Nullable String name) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be false.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures not blank in parameters.
// *
// * @param value the value to check
// * @param name the name you want to display in the logs
// * @param <T> the type of the value
// * @return the value you want to check
// */
// @NonNull
// public static <T extends CharSequence> T nonBlank(@Nullable T value, String name) {
// if (StringUtils.isBlank(value)) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be blank.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return value;
// }
//
// @NonNull
// private static StackTraceElement[] getStackTrace(@NonNull Exception exception) {
// final StackTraceElement[] sourceStack = exception.getStackTrace();
//
// final StackTraceElement[] updatedStack = new StackTraceElement[sourceStack.length - 1];
// System.arraycopy(sourceStack, 1, updatedStack, 0, updatedStack.length);
//
// return updatedStack;
// }
// }
// Path: firebase/src/main/java/com/marcohc/architecture/firebase/Firebase.java
import android.content.Context;
import android.support.annotation.NonNull;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.TaskCompletionSource;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Logger;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.kelvinapps.rxfirebase.RxFirebaseDatabase;
import com.marcohc.architecture.common.util.utils.Preconditions;
import java.util.Map;
import rx.Observable;
import timber.log.Timber;
package com.marcohc.architecture.firebase;
public final class Firebase {
private static DatabaseReference databaseReference;
private static NetworkService networkService;
private Firebase() {
}
//region Public static methods
public static String buildPath(@NonNull String... pathItems) { | Preconditions.checkNotNull(pathItems, "pathItems"); |
marcohc/android-clean-architecture | aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/NoOp.java | // Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/Defaults.java
// @SuppressWarnings("unchecked")
// public static <T> T defaultValue(Class<T> type) {
// return (T) DEFAULTS.get(type);
// }
| import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import static com.marcohc.architecture.aca.presentation.mvp.Defaults.defaultValue;
import static java.lang.reflect.Proxy.newProxyInstance; | /*
* Copyright 2015. Hannes Dorfmann.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.marcohc.architecture.aca.presentation.mvp;
/**
* Dynamically proxy to generate a new object instance for a given class by using reflections.
*
* @author Jens Dirller
* @since 1.2.0
*/
final class NoOp {
private static final InvocationHandler DEFAULT_VALUE = new DefaultValueInvocationHandler();
private NoOp() {
// no instances
}
@SuppressWarnings("unchecked")
public static <T> T of(Class<T> interfaceClass) {
return (T) newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass},
DEFAULT_VALUE);
}
/**
* Mosby class.
*/
private static class DefaultValueInvocationHandler implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { | // Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/Defaults.java
// @SuppressWarnings("unchecked")
// public static <T> T defaultValue(Class<T> type) {
// return (T) DEFAULTS.get(type);
// }
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/NoOp.java
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import static com.marcohc.architecture.aca.presentation.mvp.Defaults.defaultValue;
import static java.lang.reflect.Proxy.newProxyInstance;
/*
* Copyright 2015. Hannes Dorfmann.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.marcohc.architecture.aca.presentation.mvp;
/**
* Dynamically proxy to generate a new object instance for a given class by using reflections.
*
* @author Jens Dirller
* @since 1.2.0
*/
final class NoOp {
private static final InvocationHandler DEFAULT_VALUE = new DefaultValueInvocationHandler();
private NoOp() {
// no instances
}
@SuppressWarnings("unchecked")
public static <T> T of(Class<T> interfaceClass) {
return (T) newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass},
DEFAULT_VALUE);
}
/**
* Mosby class.
*/
private static class DefaultValueInvocationHandler implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { | return defaultValue(method.getReturnType()); |
marcohc/android-clean-architecture | common/src/main/java/com/marcohc/architecture/common/util/utils/Preconditions.java | // Path: common/src/main/java/com/marcohc/architecture/common/util/helper/StringUtils.java
// public final class StringUtils {
//
// private static final String EMAIL_PATTERN = "^[\\w!#$%&'*+/=?`{|}~^-]+(?:\\.[\\w!#$%&'*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$";
// private static Pattern pattern;
//
// private StringUtils() {
// }
//
// /**
// * Validate hex with regular expression
// *
// * @param email hex for validation
// * @return true valid hex, false invalid hex
// */
// public static boolean isEmailValid(@NonNull final String email) {
// Preconditions.checkNotNull(email, "email");
// boolean isValid = false;
// if (pattern == null) {
// pattern = Pattern.compile(EMAIL_PATTERN);
// }
// isValid = pattern.matcher(email).matches();
// return isValid;
// }
//
// /**
// * Check if the parameters is blank.
// *
// * @param text the text to check
// * @return true if is blank, false otherwise
// */
// public static boolean isBlank(@Nullable final CharSequence text) {
// return text == null || text.toString().trim().isEmpty();
// }
//
// /**
// * Check if the parameters is blank.
// *
// * @param text the text to check
// * @return true if is blank, false otherwise
// */
// public static boolean isBlank(@Nullable final String text) {
// return text == null || text.trim().isEmpty();
// }
//
// @NonNull
// public static String getFirstCapitalize(@NonNull String text) {
// Preconditions.checkNotNull(text, "text");
// StringBuilder textCapitalize = new StringBuilder();
// if (!text.isEmpty()) {
// textCapitalize.append(text.substring(0, 1).toUpperCase()).append(text.substring(1, text.length()));
// }
// return textCapitalize.toString();
// }
//
// @NonNull
// public static String getAllCapitalize(@NonNull String text) {
// Preconditions.checkNotNull(text, "text");
// StringBuilder textCapitalize = new StringBuilder();
// if (!text.isEmpty()) {
// for (int i = 0; i < text.length(); i++) {
// textCapitalize.append(String.valueOf(text.charAt(i)).toUpperCase());
// }
// }
// return textCapitalize.toString();
// }
//
// }
| import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.marcohc.architecture.common.util.helper.StringUtils; | }
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* @param expression a boolean expression
* @param name the variable name
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(boolean expression, @Nullable String name) {
if (!expression) {
final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be false.");
exception.setStackTrace(getStackTrace(exception));
throw exception;
}
}
/**
* Ensures not blank in parameters.
*
* @param value the value to check
* @param name the name you want to display in the logs
* @param <T> the type of the value
* @return the value you want to check
*/
@NonNull
public static <T extends CharSequence> T nonBlank(@Nullable T value, String name) { | // Path: common/src/main/java/com/marcohc/architecture/common/util/helper/StringUtils.java
// public final class StringUtils {
//
// private static final String EMAIL_PATTERN = "^[\\w!#$%&'*+/=?`{|}~^-]+(?:\\.[\\w!#$%&'*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$";
// private static Pattern pattern;
//
// private StringUtils() {
// }
//
// /**
// * Validate hex with regular expression
// *
// * @param email hex for validation
// * @return true valid hex, false invalid hex
// */
// public static boolean isEmailValid(@NonNull final String email) {
// Preconditions.checkNotNull(email, "email");
// boolean isValid = false;
// if (pattern == null) {
// pattern = Pattern.compile(EMAIL_PATTERN);
// }
// isValid = pattern.matcher(email).matches();
// return isValid;
// }
//
// /**
// * Check if the parameters is blank.
// *
// * @param text the text to check
// * @return true if is blank, false otherwise
// */
// public static boolean isBlank(@Nullable final CharSequence text) {
// return text == null || text.toString().trim().isEmpty();
// }
//
// /**
// * Check if the parameters is blank.
// *
// * @param text the text to check
// * @return true if is blank, false otherwise
// */
// public static boolean isBlank(@Nullable final String text) {
// return text == null || text.trim().isEmpty();
// }
//
// @NonNull
// public static String getFirstCapitalize(@NonNull String text) {
// Preconditions.checkNotNull(text, "text");
// StringBuilder textCapitalize = new StringBuilder();
// if (!text.isEmpty()) {
// textCapitalize.append(text.substring(0, 1).toUpperCase()).append(text.substring(1, text.length()));
// }
// return textCapitalize.toString();
// }
//
// @NonNull
// public static String getAllCapitalize(@NonNull String text) {
// Preconditions.checkNotNull(text, "text");
// StringBuilder textCapitalize = new StringBuilder();
// if (!text.isEmpty()) {
// for (int i = 0; i < text.length(); i++) {
// textCapitalize.append(String.valueOf(text.charAt(i)).toUpperCase());
// }
// }
// return textCapitalize.toString();
// }
//
// }
// Path: common/src/main/java/com/marcohc/architecture/common/util/utils/Preconditions.java
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.marcohc.architecture.common.util.helper.StringUtils;
}
}
/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* @param expression a boolean expression
* @param name the variable name
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(boolean expression, @Nullable String name) {
if (!expression) {
final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be false.");
exception.setStackTrace(getStackTrace(exception));
throw exception;
}
}
/**
* Ensures not blank in parameters.
*
* @param value the value to check
* @param name the name you want to display in the logs
* @param <T> the type of the value
* @return the value you want to check
*/
@NonNull
public static <T extends CharSequence> T nonBlank(@Nullable T value, String name) { | if (StringUtils.isBlank(value)) { |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/presentation/story/user/userlist/view/UsersListView.java | // Path: app/src/main/java/com/marcohc/architecture/app/domain/model/UserModel.java
// public class UserModel implements Model {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserModel() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpView.java
// public interface BaseMvpView extends MvpView {
//
// }
| import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.marcohc.architecture.app.domain.model.UserModel;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpView;
import java.util.List; | package com.marcohc.architecture.app.presentation.story.user.userlist.view;
/**
* View interface which displays random users in a list with different display options.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
interface UsersListView extends BaseMvpView {
void enableCancelButton(boolean enable);
| // Path: app/src/main/java/com/marcohc/architecture/app/domain/model/UserModel.java
// public class UserModel implements Model {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserModel() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpView.java
// public interface BaseMvpView extends MvpView {
//
// }
// Path: app/src/main/java/com/marcohc/architecture/app/presentation/story/user/userlist/view/UsersListView.java
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.marcohc.architecture.app.domain.model.UserModel;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpView;
import java.util.List;
package com.marcohc.architecture.app.presentation.story.user.userlist.view;
/**
* View interface which displays random users in a list with different display options.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
interface UsersListView extends BaseMvpView {
void enableCancelButton(boolean enable);
| void goToUserDetail(@NonNull UserModel model); |
marcohc/android-clean-architecture | bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/presentation/mvp/BaseBusMvpFragment.java | // Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/common/BusProvider.java
// public final class BusProvider {
//
// private static final EventBus BUS = EventBus.getDefault();
//
// private static EventBus getInstance() {
// return BUS;
// }
//
// public static void register(Object subscriber) {
// try {
// getInstance().register(subscriber);
// } catch (EventBusException e) {
// Timber.i("register: %s", e.getMessage());
// getInstance().unregister(subscriber);
// getInstance().register(subscriber);
// }
// }
//
// public static void unregister(Object subscriber) {
// getInstance().unregister(subscriber);
// }
//
// public static void post(Object busEvent) {
// if (busEvent != null) {
// log(busEvent);
// getInstance().post(busEvent);
// }
// }
//
// public static void cancelEventDelivery(BusEvent busEvent) {
// getInstance().cancelEventDelivery(busEvent);
// }
//
// public static void postSticky(Object busEvent) {
// if (busEvent != null) {
// log(busEvent);
// getInstance().postSticky(busEvent);
// }
// }
//
// public static <T> boolean containsStickyEvent(Class<T> clazz) {
// return getInstance().getStickyEvent(clazz) != null;
// }
//
// public static <T> T getStickyEvent(Class<T> busEventClass) {
// return getInstance().getStickyEvent(busEventClass);
// }
//
// public static void removeStickyEvent(BusEvent busEvent) {
// getInstance().removeStickyEvent(busEvent);
// }
//
// public static void removeAllStickyEvents() {
// getInstance().removeAllStickyEvents();
// }
//
// private static void log(Object busEvent) {
// String name = busEvent.getClass().getSimpleName();
// if (name.contains("Event")) {
// Timber.v("Event: %s", name);
// } else if (name.contains("Request")) {
// Timber.v("Request: %s", name);
// } else if (name.contains("DataResponse")) {
// Timber.v("DataResponse: %s", name);
// } else if (name.contains("DomainResponse")) {
// Timber.v("DomainResponse: %s", name);
// } else {
// Timber.v("Posting to bus: %s", name);
// }
// }
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpView.java
// public interface BaseMvpView extends MvpView {
//
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpFragment.java
// public abstract class BaseMvpFragment<V extends BaseMvpView, P extends MvpPresenter<V>> extends MvpFragment<V, P> implements BaseMvpView {
//
// private Unbinder unbinder;
//
// /**
// * Return the layout resource like R.layout.my_layout
// *
// * @return the layout resource or zero ("0"), if you don't want to have an UI
// */
// @LayoutRes
// protected abstract int getLayoutRes();
//
// /**
// * This method will be call by the parent activity when the back button is pressed.
// *
// * @return true if fragment handle the event or false otherwise
// */
// public boolean onBackPressed() {
// return false;
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// int layoutRes = getLayoutRes();
// if (layoutRes == 0) {
// throw new IllegalArgumentException("getLayoutRes() returned 0, which is not allowed. "
// + "If you don't want to use getLayoutRes() but implement your own view for this "
// + "fragment manually, then you have to override onCreateView();");
// } else {
// return inflater.inflate(layoutRes, container, false);
// }
// }
//
// /**
// * Override to bind views with ButterKnife.
// */
// @CallSuper
// @Override
// public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
// super.onViewCreated(view, savedInstanceState);
// unbinder = ButterKnife.bind(this, view);
// }
//
// /**
// * Override to unbind views with ButterKnife.
// */
// @CallSuper
// @Override
// public void onDestroyView() {
// super.onDestroyView();
// if (unbinder != null) {
// unbinder.unbind();
// }
// }
//
// }
| import com.hannesdorfmann.mosby.mvp.MvpPresenter;
import com.marcohc.architecture.aca.presentation.bus.common.BusProvider;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpView;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpFragment; | package com.marcohc.architecture.aca.presentation.bus.presentation.mvp;
/**
* Base bus fragment which automatically register into the event bus.
* <p>
* Override it for specific common methods in fragments
*
* @param <V> the BaseMvpView type the superclass is implementing
* @param <P> the type of MvpPresenter which will handle the logic of the class
* @author Marco Hernaiz
* @since 09/08/16
*/
public abstract class BaseBusMvpFragment<V extends BaseMvpView, P extends MvpPresenter<V>> extends BaseMvpFragment<V, P> implements BaseMvpView {
@Override
public void onStart() {
super.onStart(); | // Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/common/BusProvider.java
// public final class BusProvider {
//
// private static final EventBus BUS = EventBus.getDefault();
//
// private static EventBus getInstance() {
// return BUS;
// }
//
// public static void register(Object subscriber) {
// try {
// getInstance().register(subscriber);
// } catch (EventBusException e) {
// Timber.i("register: %s", e.getMessage());
// getInstance().unregister(subscriber);
// getInstance().register(subscriber);
// }
// }
//
// public static void unregister(Object subscriber) {
// getInstance().unregister(subscriber);
// }
//
// public static void post(Object busEvent) {
// if (busEvent != null) {
// log(busEvent);
// getInstance().post(busEvent);
// }
// }
//
// public static void cancelEventDelivery(BusEvent busEvent) {
// getInstance().cancelEventDelivery(busEvent);
// }
//
// public static void postSticky(Object busEvent) {
// if (busEvent != null) {
// log(busEvent);
// getInstance().postSticky(busEvent);
// }
// }
//
// public static <T> boolean containsStickyEvent(Class<T> clazz) {
// return getInstance().getStickyEvent(clazz) != null;
// }
//
// public static <T> T getStickyEvent(Class<T> busEventClass) {
// return getInstance().getStickyEvent(busEventClass);
// }
//
// public static void removeStickyEvent(BusEvent busEvent) {
// getInstance().removeStickyEvent(busEvent);
// }
//
// public static void removeAllStickyEvents() {
// getInstance().removeAllStickyEvents();
// }
//
// private static void log(Object busEvent) {
// String name = busEvent.getClass().getSimpleName();
// if (name.contains("Event")) {
// Timber.v("Event: %s", name);
// } else if (name.contains("Request")) {
// Timber.v("Request: %s", name);
// } else if (name.contains("DataResponse")) {
// Timber.v("DataResponse: %s", name);
// } else if (name.contains("DomainResponse")) {
// Timber.v("DomainResponse: %s", name);
// } else {
// Timber.v("Posting to bus: %s", name);
// }
// }
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpView.java
// public interface BaseMvpView extends MvpView {
//
// }
//
// Path: aca/src/main/java/com/marcohc/architecture/aca/presentation/mvp/BaseMvpFragment.java
// public abstract class BaseMvpFragment<V extends BaseMvpView, P extends MvpPresenter<V>> extends MvpFragment<V, P> implements BaseMvpView {
//
// private Unbinder unbinder;
//
// /**
// * Return the layout resource like R.layout.my_layout
// *
// * @return the layout resource or zero ("0"), if you don't want to have an UI
// */
// @LayoutRes
// protected abstract int getLayoutRes();
//
// /**
// * This method will be call by the parent activity when the back button is pressed.
// *
// * @return true if fragment handle the event or false otherwise
// */
// public boolean onBackPressed() {
// return false;
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// int layoutRes = getLayoutRes();
// if (layoutRes == 0) {
// throw new IllegalArgumentException("getLayoutRes() returned 0, which is not allowed. "
// + "If you don't want to use getLayoutRes() but implement your own view for this "
// + "fragment manually, then you have to override onCreateView();");
// } else {
// return inflater.inflate(layoutRes, container, false);
// }
// }
//
// /**
// * Override to bind views with ButterKnife.
// */
// @CallSuper
// @Override
// public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
// super.onViewCreated(view, savedInstanceState);
// unbinder = ButterKnife.bind(this, view);
// }
//
// /**
// * Override to unbind views with ButterKnife.
// */
// @CallSuper
// @Override
// public void onDestroyView() {
// super.onDestroyView();
// if (unbinder != null) {
// unbinder.unbind();
// }
// }
//
// }
// Path: bus/src/main/java/com/marcohc/architecture/aca/presentation/bus/presentation/mvp/BaseBusMvpFragment.java
import com.hannesdorfmann.mosby.mvp.MvpPresenter;
import com.marcohc.architecture.aca.presentation.bus.common.BusProvider;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpView;
import com.marcohc.architecture.aca.presentation.mvp.BaseMvpFragment;
package com.marcohc.architecture.aca.presentation.bus.presentation.mvp;
/**
* Base bus fragment which automatically register into the event bus.
* <p>
* Override it for specific common methods in fragments
*
* @param <V> the BaseMvpView type the superclass is implementing
* @param <P> the type of MvpPresenter which will handle the logic of the class
* @author Marco Hernaiz
* @since 09/08/16
*/
public abstract class BaseBusMvpFragment<V extends BaseMvpView, P extends MvpPresenter<V>> extends BaseMvpFragment<V, P> implements BaseMvpView {
@Override
public void onStart() {
super.onStart(); | BusProvider.register(presenter); |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserDiskDataStore.java | // Path: app/src/main/java/com/marcohc/architecture/app/domain/entity/UserEntity.java
// public class UserEntity implements Entity {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserEntity() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
//
// }
| import com.marcohc.architecture.app.domain.entity.UserEntity;
import java.util.List;
import rx.Observable; | package com.marcohc.architecture.app.data.datastore.user;
/**
* Disk data store for {@link UserEntity}.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public interface UserDiskDataStore {
String ALL_WITH_PICTURE = "all_with_picture";
String ALL_WITHOUT_PICTURE = "all_without_picture";
/**
* Get users with picture.
*
* @return the observable with users
*/ | // Path: app/src/main/java/com/marcohc/architecture/app/domain/entity/UserEntity.java
// public class UserEntity implements Entity {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserEntity() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
//
// }
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserDiskDataStore.java
import com.marcohc.architecture.app.domain.entity.UserEntity;
import java.util.List;
import rx.Observable;
package com.marcohc.architecture.app.data.datastore.user;
/**
* Disk data store for {@link UserEntity}.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public interface UserDiskDataStore {
String ALL_WITH_PICTURE = "all_with_picture";
String ALL_WITHOUT_PICTURE = "all_without_picture";
/**
* Get users with picture.
*
* @return the observable with users
*/ | Observable<List<UserEntity>> getUsersWithPicture(); |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserCacheDataStore.java | // Path: app/src/main/java/com/marcohc/architecture/app/data/cache/UserCache.java
// public final class UserCache implements DataCache<List<UserEntity>> {
//
// private static final long CACHE_EXPIRATION_TIME = 3600 * 1000;
// private static final String CACHE_NAME = UserCache.class.getSimpleName() + BuildConfig.VERSION_NAME;
// private static final int TEST_APP_VERSION = BuildConfig.VERSION_CODE;
// private static final int RAM_MAX_SIZE = 1024 * 1024 * 512;
// private static UserCache sInstance;
// private final DualCache<String> mCache;
//
// private UserCache() {
// ApplicationInjector.getApplicationComponent().inject(this);
// CacheSerializer<String> jsonSerializer = new JsonSerializer<>(String.class);
// mCache = new Builder<String>(CACHE_NAME, TEST_APP_VERSION)
// .useSerializerInRam(RAM_MAX_SIZE, jsonSerializer)
// .useSerializerInDisk(RAM_MAX_SIZE, true, jsonSerializer, ApplicationInjector.getApplicationComponent().provideContext())
// .build();
// }
//
// /**
// * Get singleton instance.
// *
// * @return UserCache
// */
// public synchronized static UserCache getInstance() {
// if (sInstance == null) {
// sInstance = new UserCache();
// }
// return sInstance;
// }
//
// @Override
// public void clear() {
// mCache.invalidate();
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public List<UserEntity> get(String key) {
// String jsonStored = mCache.get(key);
// return Parser.parseCollection(jsonStored, new GenericCollection<>(List.class, UserEntity.class));
// }
//
// @Override
// public boolean isCached(String key) {
//
// if (StringUtils.isBlank(key)) {
// Timber.e("isCached: key is null!");
// return false;
// }
//
// if (mCache.get(key) != null) {
// Timber.v("isCached: true");
// return true;
// } else {
// Timber.v("isCached: false");
// return false;
// }
// }
//
// @Override
// public boolean isValid(String key) {
//
// if (StringUtils.isBlank(key)) {
// Timber.e("isValid: key is null!");
// return false;
// }
//
// String jsonStored = mCache.get(key);
// Long timeStored = null;
// try {
// timeStored = Long.valueOf(mCache.get(getTimeToken(key)));
// } catch (NumberFormatException e) {
// Timber.e("isValid: timeStored is not a Long!");
// }
//
// boolean isValid = false;
// if (jsonStored != null && timeStored != null) {
// Timber.v("isValid: is stored");
//
// if (((System.currentTimeMillis() - timeStored) < CACHE_EXPIRATION_TIME)) {
// Timber.v("isValid: true");
// isValid = true;
// } else {
// Timber.v("isValid: is expired");
// }
// } else {
// Timber.v("isValid: false");
// }
//
// Timber.v("isValid: %s", isValid);
// return isValid;
// }
//
// @Override
// public void put(String key, List<UserEntity> item) {
//
// if (StringUtils.isBlank(key)) {
// Timber.e("put: key is null!");
// return;
// }
//
// mCache.put(key, Parser.toJsonString(item));
// mCache.put(getTimeToken(key), String.valueOf(System.currentTimeMillis()));
// }
//
// @Override
// public void remove(String key) {
//
// if (StringUtils.isBlank(key)) {
// Timber.e("remove: key is null!");
// return;
// }
//
// mCache.delete(key);
// mCache.delete(getTimeToken(key));
// }
//
// private String getTimeToken(String key) {
// return key + "_timestamp";
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/domain/entity/UserEntity.java
// public class UserEntity implements Entity {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserEntity() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
//
// }
| import android.support.annotation.NonNull;
import com.marcohc.architecture.app.data.cache.UserCache;
import com.marcohc.architecture.app.domain.entity.UserEntity;
import java.util.List;
import java.util.concurrent.Callable;
import rx.Observable; | package com.marcohc.architecture.app.data.datastore.user;
/**
* User disk data store. It uses the android cache to get the data from.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public class UserCacheDataStore implements UserDiskDataStore {
@Override | // Path: app/src/main/java/com/marcohc/architecture/app/data/cache/UserCache.java
// public final class UserCache implements DataCache<List<UserEntity>> {
//
// private static final long CACHE_EXPIRATION_TIME = 3600 * 1000;
// private static final String CACHE_NAME = UserCache.class.getSimpleName() + BuildConfig.VERSION_NAME;
// private static final int TEST_APP_VERSION = BuildConfig.VERSION_CODE;
// private static final int RAM_MAX_SIZE = 1024 * 1024 * 512;
// private static UserCache sInstance;
// private final DualCache<String> mCache;
//
// private UserCache() {
// ApplicationInjector.getApplicationComponent().inject(this);
// CacheSerializer<String> jsonSerializer = new JsonSerializer<>(String.class);
// mCache = new Builder<String>(CACHE_NAME, TEST_APP_VERSION)
// .useSerializerInRam(RAM_MAX_SIZE, jsonSerializer)
// .useSerializerInDisk(RAM_MAX_SIZE, true, jsonSerializer, ApplicationInjector.getApplicationComponent().provideContext())
// .build();
// }
//
// /**
// * Get singleton instance.
// *
// * @return UserCache
// */
// public synchronized static UserCache getInstance() {
// if (sInstance == null) {
// sInstance = new UserCache();
// }
// return sInstance;
// }
//
// @Override
// public void clear() {
// mCache.invalidate();
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public List<UserEntity> get(String key) {
// String jsonStored = mCache.get(key);
// return Parser.parseCollection(jsonStored, new GenericCollection<>(List.class, UserEntity.class));
// }
//
// @Override
// public boolean isCached(String key) {
//
// if (StringUtils.isBlank(key)) {
// Timber.e("isCached: key is null!");
// return false;
// }
//
// if (mCache.get(key) != null) {
// Timber.v("isCached: true");
// return true;
// } else {
// Timber.v("isCached: false");
// return false;
// }
// }
//
// @Override
// public boolean isValid(String key) {
//
// if (StringUtils.isBlank(key)) {
// Timber.e("isValid: key is null!");
// return false;
// }
//
// String jsonStored = mCache.get(key);
// Long timeStored = null;
// try {
// timeStored = Long.valueOf(mCache.get(getTimeToken(key)));
// } catch (NumberFormatException e) {
// Timber.e("isValid: timeStored is not a Long!");
// }
//
// boolean isValid = false;
// if (jsonStored != null && timeStored != null) {
// Timber.v("isValid: is stored");
//
// if (((System.currentTimeMillis() - timeStored) < CACHE_EXPIRATION_TIME)) {
// Timber.v("isValid: true");
// isValid = true;
// } else {
// Timber.v("isValid: is expired");
// }
// } else {
// Timber.v("isValid: false");
// }
//
// Timber.v("isValid: %s", isValid);
// return isValid;
// }
//
// @Override
// public void put(String key, List<UserEntity> item) {
//
// if (StringUtils.isBlank(key)) {
// Timber.e("put: key is null!");
// return;
// }
//
// mCache.put(key, Parser.toJsonString(item));
// mCache.put(getTimeToken(key), String.valueOf(System.currentTimeMillis()));
// }
//
// @Override
// public void remove(String key) {
//
// if (StringUtils.isBlank(key)) {
// Timber.e("remove: key is null!");
// return;
// }
//
// mCache.delete(key);
// mCache.delete(getTimeToken(key));
// }
//
// private String getTimeToken(String key) {
// return key + "_timestamp";
// }
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/domain/entity/UserEntity.java
// public class UserEntity implements Entity {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserEntity() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
//
// }
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserCacheDataStore.java
import android.support.annotation.NonNull;
import com.marcohc.architecture.app.data.cache.UserCache;
import com.marcohc.architecture.app.domain.entity.UserEntity;
import java.util.List;
import java.util.concurrent.Callable;
import rx.Observable;
package com.marcohc.architecture.app.data.datastore.user;
/**
* User disk data store. It uses the android cache to get the data from.
*
* @author Marco Hernaiz
* @since 08/08/16
*/
public class UserCacheDataStore implements UserDiskDataStore {
@Override | public Observable<List<UserEntity>> getUsersWithPicture() { |
marcohc/android-clean-architecture | service/src/main/java/com/marcohc/architecture/common/service/preferences/PreferencesServiceImpl.java | // Path: common/src/main/java/com/marcohc/architecture/common/util/utils/Preconditions.java
// public final class Preconditions {
//
// private Preconditions() {
// // no-op
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @param name the variable name
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference, String name) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException(name + " must not be null.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @param name the variable name
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression, @Nullable String name) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be false.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures not blank in parameters.
// *
// * @param value the value to check
// * @param name the name you want to display in the logs
// * @param <T> the type of the value
// * @return the value you want to check
// */
// @NonNull
// public static <T extends CharSequence> T nonBlank(@Nullable T value, String name) {
// if (StringUtils.isBlank(value)) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be blank.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return value;
// }
//
// @NonNull
// private static StackTraceElement[] getStackTrace(@NonNull Exception exception) {
// final StackTraceElement[] sourceStack = exception.getStackTrace();
//
// final StackTraceElement[] updatedStack = new StackTraceElement[sourceStack.length - 1];
// System.arraycopy(sourceStack, 1, updatedStack, 0, updatedStack.length);
//
// return updatedStack;
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.marcohc.architecture.common.util.utils.Preconditions; | /*
* Copyright (C) 2016 Marco Hernaiz Cao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marcohc.architecture.common.service.preferences;
/**
* For managing shared preferences.
*/
public class PreferencesServiceImpl implements PreferencesService {
private final SharedPreferences sharedPreferences;
public PreferencesServiceImpl(Context context, String sharedPreferencesName) {
sharedPreferences = context.getSharedPreferences(sharedPreferencesName, Context.MODE_PRIVATE);
}
public PreferencesServiceImpl(Context context) {
String defaultName = String.format("%s_%s", context.getPackageName(), "preferences");
sharedPreferences = context.getSharedPreferences(defaultName, Context.MODE_PRIVATE);
}
@Override
public void clear() {
sharedPreferences.edit().clear().apply();
}
@Override
public boolean getBoolean(@NonNull String key, boolean defaultValue) { | // Path: common/src/main/java/com/marcohc/architecture/common/util/utils/Preconditions.java
// public final class Preconditions {
//
// private Preconditions() {
// // no-op
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures that an object reference passed as a parameter to the calling method is not null.
// *
// * @param reference an object reference
// * @param name the variable name
// * @return the non-null reference that was validated
// * @throws NullPointerException if {@code reference} is null
// */
// @NonNull
// public static <T> T checkNotNull(@Nullable T reference, String name) {
// if (reference == null) {
// final NullPointerException exception = new NullPointerException(name + " must not be null.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return reference;
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException();
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures the truth of an expression involving one or more parameters to the calling method.
// *
// * @param expression a boolean expression
// * @param name the variable name
// * @throws IllegalArgumentException if {@code expression} is false
// */
// public static void checkArgument(boolean expression, @Nullable String name) {
// if (!expression) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be false.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// }
//
// /**
// * Ensures not blank in parameters.
// *
// * @param value the value to check
// * @param name the name you want to display in the logs
// * @param <T> the type of the value
// * @return the value you want to check
// */
// @NonNull
// public static <T extends CharSequence> T nonBlank(@Nullable T value, String name) {
// if (StringUtils.isBlank(value)) {
// final IllegalArgumentException exception = new IllegalArgumentException(name + " must not be blank.");
//
// exception.setStackTrace(getStackTrace(exception));
//
// throw exception;
// }
// return value;
// }
//
// @NonNull
// private static StackTraceElement[] getStackTrace(@NonNull Exception exception) {
// final StackTraceElement[] sourceStack = exception.getStackTrace();
//
// final StackTraceElement[] updatedStack = new StackTraceElement[sourceStack.length - 1];
// System.arraycopy(sourceStack, 1, updatedStack, 0, updatedStack.length);
//
// return updatedStack;
// }
// }
// Path: service/src/main/java/com/marcohc/architecture/common/service/preferences/PreferencesServiceImpl.java
import android.content.Context;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.marcohc.architecture.common.util.utils.Preconditions;
/*
* Copyright (C) 2016 Marco Hernaiz Cao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.marcohc.architecture.common.service.preferences;
/**
* For managing shared preferences.
*/
public class PreferencesServiceImpl implements PreferencesService {
private final SharedPreferences sharedPreferences;
public PreferencesServiceImpl(Context context, String sharedPreferencesName) {
sharedPreferences = context.getSharedPreferences(sharedPreferencesName, Context.MODE_PRIVATE);
}
public PreferencesServiceImpl(Context context) {
String defaultName = String.format("%s_%s", context.getPackageName(), "preferences");
sharedPreferences = context.getSharedPreferences(defaultName, Context.MODE_PRIVATE);
}
@Override
public void clear() {
sharedPreferences.edit().clear().apply();
}
@Override
public boolean getBoolean(@NonNull String key, boolean defaultValue) { | return sharedPreferences.getBoolean(Preconditions.checkNotNull(key), defaultValue); |
marcohc/android-clean-architecture | app/src/main/java/com/marcohc/architecture/app/data/repository/user/UserRepositoryImpl.java | // Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserCloudDataStore.java
// public interface UserCloudDataStore {
//
// /**
// * Get all users.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getAll();
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserDiskDataStore.java
// public interface UserDiskDataStore {
//
// String ALL_WITH_PICTURE = "all_with_picture";
// String ALL_WITHOUT_PICTURE = "all_without_picture";
//
// /**
// * Get users with picture.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getUsersWithPicture();
//
// /**
// * Get users without pictures.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getUsersWithoutPicture();
//
// /**
// * Checks if the value is stored.
// *
// * @param cacheKey the key for the cache
// * @return true if is store, false otherwise
// */
// boolean isCached(String cacheKey);
//
// /**
// * Puts the list in the cache with the specific cache key.
// *
// * @param cacheKey the key for the cache
// * @param entityList the list of entities to persist
// */
// void put(String cacheKey, List<UserEntity> entityList);
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/factory/UserDataStoreFactory.java
// public final class UserDataStoreFactory {
//
// public static UserDiskDataStore createUserDiskDataStore() {
// return new UserCacheDataStore();
// }
//
// public static UserCloudDataStore createUserWithoutPicturesCloudDataStore() {
// return new UsersWithoutPictureDataStore();
// }
//
// public static UserCloudDataStore createUserWithPicturesCloudDataStore() {
// return new UsersWithPictureDataStore();
// }
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/domain/entity/UserEntity.java
// public class UserEntity implements Entity {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserEntity() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
//
// }
| import com.marcohc.architecture.app.data.datastore.user.UserCloudDataStore;
import com.marcohc.architecture.app.data.datastore.user.UserDiskDataStore;
import com.marcohc.architecture.app.data.factory.UserDataStoreFactory;
import com.marcohc.architecture.app.domain.entity.UserEntity;
import java.util.List;
import javax.inject.Singleton;
import rx.Observable;
import rx.functions.Action1;
import static com.marcohc.architecture.app.data.datastore.user.UserDiskDataStore.ALL_WITHOUT_PICTURE;
import static com.marcohc.architecture.app.data.datastore.user.UserDiskDataStore.ALL_WITH_PICTURE; | package com.marcohc.architecture.app.data.repository.user;
/**
* A repository class must be created for each model in the application.
* <p>
* It provides data retrieved from its factory
*
* @author Marco Hernaiz
* @since 08/08/16
*/
@Singleton
public class UserRepositoryImpl implements UserRepository {
| // Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserCloudDataStore.java
// public interface UserCloudDataStore {
//
// /**
// * Get all users.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getAll();
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/datastore/user/UserDiskDataStore.java
// public interface UserDiskDataStore {
//
// String ALL_WITH_PICTURE = "all_with_picture";
// String ALL_WITHOUT_PICTURE = "all_without_picture";
//
// /**
// * Get users with picture.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getUsersWithPicture();
//
// /**
// * Get users without pictures.
// *
// * @return the observable with users
// */
// Observable<List<UserEntity>> getUsersWithoutPicture();
//
// /**
// * Checks if the value is stored.
// *
// * @param cacheKey the key for the cache
// * @return true if is store, false otherwise
// */
// boolean isCached(String cacheKey);
//
// /**
// * Puts the list in the cache with the specific cache key.
// *
// * @param cacheKey the key for the cache
// * @param entityList the list of entities to persist
// */
// void put(String cacheKey, List<UserEntity> entityList);
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/data/factory/UserDataStoreFactory.java
// public final class UserDataStoreFactory {
//
// public static UserDiskDataStore createUserDiskDataStore() {
// return new UserCacheDataStore();
// }
//
// public static UserCloudDataStore createUserWithoutPicturesCloudDataStore() {
// return new UsersWithoutPictureDataStore();
// }
//
// public static UserCloudDataStore createUserWithPicturesCloudDataStore() {
// return new UsersWithPictureDataStore();
// }
//
// }
//
// Path: app/src/main/java/com/marcohc/architecture/app/domain/entity/UserEntity.java
// public class UserEntity implements Entity {
//
// // ************************************************************************************************************************************************************************
// // * Attributes
// // ************************************************************************************************************************************************************************
//
// @SerializedName("name")
// private String mName;
//
// @SerializedName("email")
// private String mEmail;
//
// @SerializedName("pictureUrl")
// private String mPictureUrl;
//
// // ************************************************************************************************************************************************************************
// // * Constructors
// // ************************************************************************************************************************************************************************
//
// public UserEntity() {
// mName = "Unknown";
// mEmail = "Unknown";
// }
//
// // ************************************************************************************************************************************************************************
// // * Getter and setters
// // ************************************************************************************************************************************************************************
//
// public String getName() {
// return mName;
// }
//
// public void setName(String name) {
// this.mName = name;
// }
//
// public String getEmail() {
// return mEmail;
// }
//
// public void setEmail(String email) {
// this.mEmail = email;
// }
//
// public String getPictureUrl() {
// return mPictureUrl;
// }
//
// public void setPictureUrl(String pictureUrl) {
// this.mPictureUrl = pictureUrl;
// }
//
// }
// Path: app/src/main/java/com/marcohc/architecture/app/data/repository/user/UserRepositoryImpl.java
import com.marcohc.architecture.app.data.datastore.user.UserCloudDataStore;
import com.marcohc.architecture.app.data.datastore.user.UserDiskDataStore;
import com.marcohc.architecture.app.data.factory.UserDataStoreFactory;
import com.marcohc.architecture.app.domain.entity.UserEntity;
import java.util.List;
import javax.inject.Singleton;
import rx.Observable;
import rx.functions.Action1;
import static com.marcohc.architecture.app.data.datastore.user.UserDiskDataStore.ALL_WITHOUT_PICTURE;
import static com.marcohc.architecture.app.data.datastore.user.UserDiskDataStore.ALL_WITH_PICTURE;
package com.marcohc.architecture.app.data.repository.user;
/**
* A repository class must be created for each model in the application.
* <p>
* It provides data retrieved from its factory
*
* @author Marco Hernaiz
* @since 08/08/16
*/
@Singleton
public class UserRepositoryImpl implements UserRepository {
| private final UserDiskDataStore diskDataStore; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.