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 |
|---|---|---|---|---|---|---|
d2si-oss/ooso | ooso/src/main/java/fr/d2si/ooso/mappers_driver/MappersDriverInfo.java | // Path: ooso/src/main/java/fr/d2si/ooso/utils/JobInfo.java
// public class JobInfo {
// private String jobId;
// private String jobInputBucket;
// private String mapperOutputBucket;
// private String reducerOutputBucket;
// private String mapperFunctionName;
// private String mappersDriverFunctionName;
// private String mappersListenerFunctionName;
// private String reducerFunctionName;
// private String reducersDriverFunctionName;
// private String reducersListenerFunctionName;
// private String statusTable;
// private String mapperMemory;
// private String reducerMemory;
// private String mapperForceBatchSize;
// private String reducerForceBatchSize;
// private String disableReducer;
//
// public JobInfo() {
// }
//
// public JobInfo(String jobId, String jobInputBucket, String mapperOutputBucket, String reducerOutputBucket, String mapperFunctionName, String mappersDriverFunctionName, String mappersListenerFunctionName, String reducerFunctionName, String reducersDriverFunctionName, String reducersListenerFunctionName, String statusTable, String mapperMemory, String reducerMemory, String mapperForceBatchSize, String reducerForceBatchSize, String disableReducer) {
// this.jobId = jobId;
// this.jobInputBucket = jobInputBucket;
// this.mapperOutputBucket = mapperOutputBucket;
// this.reducerOutputBucket = reducerOutputBucket;
// this.mapperFunctionName = mapperFunctionName;
// this.mappersDriverFunctionName = mappersDriverFunctionName;
// this.mappersListenerFunctionName = mappersListenerFunctionName;
// this.reducerFunctionName = reducerFunctionName;
// this.reducersDriverFunctionName = reducersDriverFunctionName;
// this.reducersListenerFunctionName = reducersListenerFunctionName;
// this.statusTable = statusTable;
// this.mapperMemory = mapperMemory;
// this.reducerMemory = reducerMemory;
// this.mapperForceBatchSize = mapperForceBatchSize;
// this.reducerForceBatchSize = reducerForceBatchSize;
// this.disableReducer = disableReducer;
// }
//
// public String getJobInputBucket() {
// return jobInputBucket;
// }
//
// public void setJobInputBucket(String jobInputBucket) {
// this.jobInputBucket = jobInputBucket;
// }
//
// public String getMapperOutputBucket() {
// return mapperOutputBucket;
// }
//
// public void setMapperOutputBucket(String mapperOutputBucket) {
// this.mapperOutputBucket = mapperOutputBucket;
// }
//
// public String getReducerOutputBucket() {
// return reducerOutputBucket;
// }
//
// public void setReducerOutputBucket(String reducerOutputBucket) {
// this.reducerOutputBucket = reducerOutputBucket;
// }
//
// public String getMapperFunctionName() {
// return mapperFunctionName;
// }
//
// public void setMapperFunctionName(String mapperFunctionName) {
// this.mapperFunctionName = mapperFunctionName;
// }
//
// public String getReducerFunctionName() {
// return reducerFunctionName;
// }
//
// public void setReducerFunctionName(String reducerFunctionName) {
// this.reducerFunctionName = reducerFunctionName;
// }
//
// public String getStatusTable() {
// return statusTable;
// }
//
// public void setStatusTable(String statusTable) {
// this.statusTable = statusTable;
// }
//
// public String getJobId() {
// return jobId;
// }
//
// public void setJobId(String jobId) {
// this.jobId = jobId;
// }
//
// public int getMapperMemory() {
// return Integer.parseInt(mapperMemory);
// }
//
// public void setMapperMemory(String mapperMemory) {
// this.mapperMemory = mapperMemory;
// }
//
// public int getReducerMemory() {
// return Integer.parseInt(reducerMemory);
// }
//
// public void setReducerMemory(String reducerMemory) {
// this.reducerMemory = reducerMemory;
// }
//
// public int getMapperForceBatchSize() {
// return Integer.parseInt(mapperForceBatchSize);
// }
//
// public void setMapperForceBatchSize(String mapperForceBatchSize) {
// this.mapperForceBatchSize = mapperForceBatchSize;
// }
//
// public int getReducerForceBatchSize() {
// return Integer.parseInt(reducerForceBatchSize);
// }
//
// public void setReducerForceBatchSize(String reducerForceBatchSize) {
// this.reducerForceBatchSize = reducerForceBatchSize;
// }
//
// public boolean getDisableReducer() {
// return Boolean.parseBoolean(disableReducer);
// }
//
// public void setDisableReducer(String disableReducer) {
// this.disableReducer = disableReducer;
// }
//
// public String getMappersDriverFunctionName() {
// return mappersDriverFunctionName;
// }
//
// public void setMappersDriverFunctionName(String mappersDriverFunctionName) {
// this.mappersDriverFunctionName = mappersDriverFunctionName;
// }
//
// public String getMappersListenerFunctionName() {
// return mappersListenerFunctionName;
// }
//
// public void setMappersListenerFunctionName(String mappersListenerFunctionName) {
// this.mappersListenerFunctionName = mappersListenerFunctionName;
// }
//
// public String getReducersDriverFunctionName() {
// return reducersDriverFunctionName;
// }
//
// public void setReducersDriverFunctionName(String reducersDriverFunctionName) {
// this.reducersDriverFunctionName = reducersDriverFunctionName;
// }
//
// public String getReducersListenerFunctionName() {
// return reducersListenerFunctionName;
// }
//
// public void setReducersListenerFunctionName(String reducersListenerFunctionName) {
// this.reducersListenerFunctionName = reducersListenerFunctionName;
// }
// }
| import fr.d2si.ooso.utils.JobInfo; | package fr.d2si.ooso.mappers_driver;
public class MappersDriverInfo {
private String mapperInBase64;
private String reducerInBase64; | // Path: ooso/src/main/java/fr/d2si/ooso/utils/JobInfo.java
// public class JobInfo {
// private String jobId;
// private String jobInputBucket;
// private String mapperOutputBucket;
// private String reducerOutputBucket;
// private String mapperFunctionName;
// private String mappersDriverFunctionName;
// private String mappersListenerFunctionName;
// private String reducerFunctionName;
// private String reducersDriverFunctionName;
// private String reducersListenerFunctionName;
// private String statusTable;
// private String mapperMemory;
// private String reducerMemory;
// private String mapperForceBatchSize;
// private String reducerForceBatchSize;
// private String disableReducer;
//
// public JobInfo() {
// }
//
// public JobInfo(String jobId, String jobInputBucket, String mapperOutputBucket, String reducerOutputBucket, String mapperFunctionName, String mappersDriverFunctionName, String mappersListenerFunctionName, String reducerFunctionName, String reducersDriverFunctionName, String reducersListenerFunctionName, String statusTable, String mapperMemory, String reducerMemory, String mapperForceBatchSize, String reducerForceBatchSize, String disableReducer) {
// this.jobId = jobId;
// this.jobInputBucket = jobInputBucket;
// this.mapperOutputBucket = mapperOutputBucket;
// this.reducerOutputBucket = reducerOutputBucket;
// this.mapperFunctionName = mapperFunctionName;
// this.mappersDriverFunctionName = mappersDriverFunctionName;
// this.mappersListenerFunctionName = mappersListenerFunctionName;
// this.reducerFunctionName = reducerFunctionName;
// this.reducersDriverFunctionName = reducersDriverFunctionName;
// this.reducersListenerFunctionName = reducersListenerFunctionName;
// this.statusTable = statusTable;
// this.mapperMemory = mapperMemory;
// this.reducerMemory = reducerMemory;
// this.mapperForceBatchSize = mapperForceBatchSize;
// this.reducerForceBatchSize = reducerForceBatchSize;
// this.disableReducer = disableReducer;
// }
//
// public String getJobInputBucket() {
// return jobInputBucket;
// }
//
// public void setJobInputBucket(String jobInputBucket) {
// this.jobInputBucket = jobInputBucket;
// }
//
// public String getMapperOutputBucket() {
// return mapperOutputBucket;
// }
//
// public void setMapperOutputBucket(String mapperOutputBucket) {
// this.mapperOutputBucket = mapperOutputBucket;
// }
//
// public String getReducerOutputBucket() {
// return reducerOutputBucket;
// }
//
// public void setReducerOutputBucket(String reducerOutputBucket) {
// this.reducerOutputBucket = reducerOutputBucket;
// }
//
// public String getMapperFunctionName() {
// return mapperFunctionName;
// }
//
// public void setMapperFunctionName(String mapperFunctionName) {
// this.mapperFunctionName = mapperFunctionName;
// }
//
// public String getReducerFunctionName() {
// return reducerFunctionName;
// }
//
// public void setReducerFunctionName(String reducerFunctionName) {
// this.reducerFunctionName = reducerFunctionName;
// }
//
// public String getStatusTable() {
// return statusTable;
// }
//
// public void setStatusTable(String statusTable) {
// this.statusTable = statusTable;
// }
//
// public String getJobId() {
// return jobId;
// }
//
// public void setJobId(String jobId) {
// this.jobId = jobId;
// }
//
// public int getMapperMemory() {
// return Integer.parseInt(mapperMemory);
// }
//
// public void setMapperMemory(String mapperMemory) {
// this.mapperMemory = mapperMemory;
// }
//
// public int getReducerMemory() {
// return Integer.parseInt(reducerMemory);
// }
//
// public void setReducerMemory(String reducerMemory) {
// this.reducerMemory = reducerMemory;
// }
//
// public int getMapperForceBatchSize() {
// return Integer.parseInt(mapperForceBatchSize);
// }
//
// public void setMapperForceBatchSize(String mapperForceBatchSize) {
// this.mapperForceBatchSize = mapperForceBatchSize;
// }
//
// public int getReducerForceBatchSize() {
// return Integer.parseInt(reducerForceBatchSize);
// }
//
// public void setReducerForceBatchSize(String reducerForceBatchSize) {
// this.reducerForceBatchSize = reducerForceBatchSize;
// }
//
// public boolean getDisableReducer() {
// return Boolean.parseBoolean(disableReducer);
// }
//
// public void setDisableReducer(String disableReducer) {
// this.disableReducer = disableReducer;
// }
//
// public String getMappersDriverFunctionName() {
// return mappersDriverFunctionName;
// }
//
// public void setMappersDriverFunctionName(String mappersDriverFunctionName) {
// this.mappersDriverFunctionName = mappersDriverFunctionName;
// }
//
// public String getMappersListenerFunctionName() {
// return mappersListenerFunctionName;
// }
//
// public void setMappersListenerFunctionName(String mappersListenerFunctionName) {
// this.mappersListenerFunctionName = mappersListenerFunctionName;
// }
//
// public String getReducersDriverFunctionName() {
// return reducersDriverFunctionName;
// }
//
// public void setReducersDriverFunctionName(String reducersDriverFunctionName) {
// this.reducersDriverFunctionName = reducersDriverFunctionName;
// }
//
// public String getReducersListenerFunctionName() {
// return reducersListenerFunctionName;
// }
//
// public void setReducersListenerFunctionName(String reducersListenerFunctionName) {
// this.reducersListenerFunctionName = reducersListenerFunctionName;
// }
// }
// Path: ooso/src/main/java/fr/d2si/ooso/mappers_driver/MappersDriverInfo.java
import fr.d2si.ooso.utils.JobInfo;
package fr.d2si.ooso.mappers_driver;
public class MappersDriverInfo {
private String mapperInBase64;
private String reducerInBase64; | private JobInfo jobInfo; |
d2si-oss/ooso | ooso/src/main/java/fr/d2si/ooso/reducers_listener/ReducersListenerInfo.java | // Path: ooso/src/main/java/fr/d2si/ooso/utils/JobInfo.java
// public class JobInfo {
// private String jobId;
// private String jobInputBucket;
// private String mapperOutputBucket;
// private String reducerOutputBucket;
// private String mapperFunctionName;
// private String mappersDriverFunctionName;
// private String mappersListenerFunctionName;
// private String reducerFunctionName;
// private String reducersDriverFunctionName;
// private String reducersListenerFunctionName;
// private String statusTable;
// private String mapperMemory;
// private String reducerMemory;
// private String mapperForceBatchSize;
// private String reducerForceBatchSize;
// private String disableReducer;
//
// public JobInfo() {
// }
//
// public JobInfo(String jobId, String jobInputBucket, String mapperOutputBucket, String reducerOutputBucket, String mapperFunctionName, String mappersDriverFunctionName, String mappersListenerFunctionName, String reducerFunctionName, String reducersDriverFunctionName, String reducersListenerFunctionName, String statusTable, String mapperMemory, String reducerMemory, String mapperForceBatchSize, String reducerForceBatchSize, String disableReducer) {
// this.jobId = jobId;
// this.jobInputBucket = jobInputBucket;
// this.mapperOutputBucket = mapperOutputBucket;
// this.reducerOutputBucket = reducerOutputBucket;
// this.mapperFunctionName = mapperFunctionName;
// this.mappersDriverFunctionName = mappersDriverFunctionName;
// this.mappersListenerFunctionName = mappersListenerFunctionName;
// this.reducerFunctionName = reducerFunctionName;
// this.reducersDriverFunctionName = reducersDriverFunctionName;
// this.reducersListenerFunctionName = reducersListenerFunctionName;
// this.statusTable = statusTable;
// this.mapperMemory = mapperMemory;
// this.reducerMemory = reducerMemory;
// this.mapperForceBatchSize = mapperForceBatchSize;
// this.reducerForceBatchSize = reducerForceBatchSize;
// this.disableReducer = disableReducer;
// }
//
// public String getJobInputBucket() {
// return jobInputBucket;
// }
//
// public void setJobInputBucket(String jobInputBucket) {
// this.jobInputBucket = jobInputBucket;
// }
//
// public String getMapperOutputBucket() {
// return mapperOutputBucket;
// }
//
// public void setMapperOutputBucket(String mapperOutputBucket) {
// this.mapperOutputBucket = mapperOutputBucket;
// }
//
// public String getReducerOutputBucket() {
// return reducerOutputBucket;
// }
//
// public void setReducerOutputBucket(String reducerOutputBucket) {
// this.reducerOutputBucket = reducerOutputBucket;
// }
//
// public String getMapperFunctionName() {
// return mapperFunctionName;
// }
//
// public void setMapperFunctionName(String mapperFunctionName) {
// this.mapperFunctionName = mapperFunctionName;
// }
//
// public String getReducerFunctionName() {
// return reducerFunctionName;
// }
//
// public void setReducerFunctionName(String reducerFunctionName) {
// this.reducerFunctionName = reducerFunctionName;
// }
//
// public String getStatusTable() {
// return statusTable;
// }
//
// public void setStatusTable(String statusTable) {
// this.statusTable = statusTable;
// }
//
// public String getJobId() {
// return jobId;
// }
//
// public void setJobId(String jobId) {
// this.jobId = jobId;
// }
//
// public int getMapperMemory() {
// return Integer.parseInt(mapperMemory);
// }
//
// public void setMapperMemory(String mapperMemory) {
// this.mapperMemory = mapperMemory;
// }
//
// public int getReducerMemory() {
// return Integer.parseInt(reducerMemory);
// }
//
// public void setReducerMemory(String reducerMemory) {
// this.reducerMemory = reducerMemory;
// }
//
// public int getMapperForceBatchSize() {
// return Integer.parseInt(mapperForceBatchSize);
// }
//
// public void setMapperForceBatchSize(String mapperForceBatchSize) {
// this.mapperForceBatchSize = mapperForceBatchSize;
// }
//
// public int getReducerForceBatchSize() {
// return Integer.parseInt(reducerForceBatchSize);
// }
//
// public void setReducerForceBatchSize(String reducerForceBatchSize) {
// this.reducerForceBatchSize = reducerForceBatchSize;
// }
//
// public boolean getDisableReducer() {
// return Boolean.parseBoolean(disableReducer);
// }
//
// public void setDisableReducer(String disableReducer) {
// this.disableReducer = disableReducer;
// }
//
// public String getMappersDriverFunctionName() {
// return mappersDriverFunctionName;
// }
//
// public void setMappersDriverFunctionName(String mappersDriverFunctionName) {
// this.mappersDriverFunctionName = mappersDriverFunctionName;
// }
//
// public String getMappersListenerFunctionName() {
// return mappersListenerFunctionName;
// }
//
// public void setMappersListenerFunctionName(String mappersListenerFunctionName) {
// this.mappersListenerFunctionName = mappersListenerFunctionName;
// }
//
// public String getReducersDriverFunctionName() {
// return reducersDriverFunctionName;
// }
//
// public void setReducersDriverFunctionName(String reducersDriverFunctionName) {
// this.reducersDriverFunctionName = reducersDriverFunctionName;
// }
//
// public String getReducersListenerFunctionName() {
// return reducersListenerFunctionName;
// }
//
// public void setReducersListenerFunctionName(String reducersListenerFunctionName) {
// this.reducersListenerFunctionName = reducersListenerFunctionName;
// }
// }
| import fr.d2si.ooso.utils.JobInfo; | package fr.d2si.ooso.reducers_listener;
public class ReducersListenerInfo {
private int step;
private int expectedFilesCount;
private String reducerInBase64; | // Path: ooso/src/main/java/fr/d2si/ooso/utils/JobInfo.java
// public class JobInfo {
// private String jobId;
// private String jobInputBucket;
// private String mapperOutputBucket;
// private String reducerOutputBucket;
// private String mapperFunctionName;
// private String mappersDriverFunctionName;
// private String mappersListenerFunctionName;
// private String reducerFunctionName;
// private String reducersDriverFunctionName;
// private String reducersListenerFunctionName;
// private String statusTable;
// private String mapperMemory;
// private String reducerMemory;
// private String mapperForceBatchSize;
// private String reducerForceBatchSize;
// private String disableReducer;
//
// public JobInfo() {
// }
//
// public JobInfo(String jobId, String jobInputBucket, String mapperOutputBucket, String reducerOutputBucket, String mapperFunctionName, String mappersDriverFunctionName, String mappersListenerFunctionName, String reducerFunctionName, String reducersDriverFunctionName, String reducersListenerFunctionName, String statusTable, String mapperMemory, String reducerMemory, String mapperForceBatchSize, String reducerForceBatchSize, String disableReducer) {
// this.jobId = jobId;
// this.jobInputBucket = jobInputBucket;
// this.mapperOutputBucket = mapperOutputBucket;
// this.reducerOutputBucket = reducerOutputBucket;
// this.mapperFunctionName = mapperFunctionName;
// this.mappersDriverFunctionName = mappersDriverFunctionName;
// this.mappersListenerFunctionName = mappersListenerFunctionName;
// this.reducerFunctionName = reducerFunctionName;
// this.reducersDriverFunctionName = reducersDriverFunctionName;
// this.reducersListenerFunctionName = reducersListenerFunctionName;
// this.statusTable = statusTable;
// this.mapperMemory = mapperMemory;
// this.reducerMemory = reducerMemory;
// this.mapperForceBatchSize = mapperForceBatchSize;
// this.reducerForceBatchSize = reducerForceBatchSize;
// this.disableReducer = disableReducer;
// }
//
// public String getJobInputBucket() {
// return jobInputBucket;
// }
//
// public void setJobInputBucket(String jobInputBucket) {
// this.jobInputBucket = jobInputBucket;
// }
//
// public String getMapperOutputBucket() {
// return mapperOutputBucket;
// }
//
// public void setMapperOutputBucket(String mapperOutputBucket) {
// this.mapperOutputBucket = mapperOutputBucket;
// }
//
// public String getReducerOutputBucket() {
// return reducerOutputBucket;
// }
//
// public void setReducerOutputBucket(String reducerOutputBucket) {
// this.reducerOutputBucket = reducerOutputBucket;
// }
//
// public String getMapperFunctionName() {
// return mapperFunctionName;
// }
//
// public void setMapperFunctionName(String mapperFunctionName) {
// this.mapperFunctionName = mapperFunctionName;
// }
//
// public String getReducerFunctionName() {
// return reducerFunctionName;
// }
//
// public void setReducerFunctionName(String reducerFunctionName) {
// this.reducerFunctionName = reducerFunctionName;
// }
//
// public String getStatusTable() {
// return statusTable;
// }
//
// public void setStatusTable(String statusTable) {
// this.statusTable = statusTable;
// }
//
// public String getJobId() {
// return jobId;
// }
//
// public void setJobId(String jobId) {
// this.jobId = jobId;
// }
//
// public int getMapperMemory() {
// return Integer.parseInt(mapperMemory);
// }
//
// public void setMapperMemory(String mapperMemory) {
// this.mapperMemory = mapperMemory;
// }
//
// public int getReducerMemory() {
// return Integer.parseInt(reducerMemory);
// }
//
// public void setReducerMemory(String reducerMemory) {
// this.reducerMemory = reducerMemory;
// }
//
// public int getMapperForceBatchSize() {
// return Integer.parseInt(mapperForceBatchSize);
// }
//
// public void setMapperForceBatchSize(String mapperForceBatchSize) {
// this.mapperForceBatchSize = mapperForceBatchSize;
// }
//
// public int getReducerForceBatchSize() {
// return Integer.parseInt(reducerForceBatchSize);
// }
//
// public void setReducerForceBatchSize(String reducerForceBatchSize) {
// this.reducerForceBatchSize = reducerForceBatchSize;
// }
//
// public boolean getDisableReducer() {
// return Boolean.parseBoolean(disableReducer);
// }
//
// public void setDisableReducer(String disableReducer) {
// this.disableReducer = disableReducer;
// }
//
// public String getMappersDriverFunctionName() {
// return mappersDriverFunctionName;
// }
//
// public void setMappersDriverFunctionName(String mappersDriverFunctionName) {
// this.mappersDriverFunctionName = mappersDriverFunctionName;
// }
//
// public String getMappersListenerFunctionName() {
// return mappersListenerFunctionName;
// }
//
// public void setMappersListenerFunctionName(String mappersListenerFunctionName) {
// this.mappersListenerFunctionName = mappersListenerFunctionName;
// }
//
// public String getReducersDriverFunctionName() {
// return reducersDriverFunctionName;
// }
//
// public void setReducersDriverFunctionName(String reducersDriverFunctionName) {
// this.reducersDriverFunctionName = reducersDriverFunctionName;
// }
//
// public String getReducersListenerFunctionName() {
// return reducersListenerFunctionName;
// }
//
// public void setReducersListenerFunctionName(String reducersListenerFunctionName) {
// this.reducersListenerFunctionName = reducersListenerFunctionName;
// }
// }
// Path: ooso/src/main/java/fr/d2si/ooso/reducers_listener/ReducersListenerInfo.java
import fr.d2si.ooso.utils.JobInfo;
package fr.d2si.ooso.reducers_listener;
public class ReducersListenerInfo {
private int step;
private int expectedFilesCount;
private String reducerInBase64; | private JobInfo jobInfo; |
d2si-oss/ooso | examples/batch-processing-example/src/main/java/job/JobLauncher.java | // Path: ooso/src/main/java/fr/d2si/ooso/launcher/Launcher.java
// public class Launcher {
// private JobInfo jobInfo;
//
// private MapperAbstract mapper;
// private ReducerAbstract reducer;
//
// private boolean generateId = false;
//
// private Logger logger;
//
// public Launcher withMapper(MapperAbstract mapper) {
// this.mapper = mapper;
// return this;
// }
//
// public Launcher withReducer(ReducerAbstract reducer) {
// this.reducer = reducer;
// return this;
// }
//
// public Launcher withRandomId(boolean generateId) {
// this.generateId = generateId;
// return this;
// }
//
// public String launchJob() {
// try {
// String generatedId = null;
//
// configureLogger();
// loadJobInfo();
//
// if (generateId) {
// generatedId = generateUUID().toString();
// jobInfo.setJobId(generatedId);
// }
//
// if (this.mapper == null || (!this.jobInfo.getDisableReducer() && reducer == null)) {
// throw new RuntimeException("You must set the mapper and reducer classes");
// }
//
// launchMappersDriver();
//
// return generatedId;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// private UUID generateUUID() {
// return new UUID();
// }
//
// private void configureLogger() {
// this.logger = Logger.getAnonymousLogger();
// }
//
// private void loadJobInfo() throws IOException {
// this.logger.info("Loading Job Configuration...");
//
// Gson gson = new Gson();
// InputStream driverInfoStream = getClass().getClassLoader().getResourceAsStream("jobInfo.json");
// BufferedReader driverInfoReader = new BufferedReader(new InputStreamReader(driverInfoStream));
// this.jobInfo = gson.fromJson(driverInfoReader, JobInfo.class);
// driverInfoReader.close();
// }
//
// private void launchMappersDriver() throws IOException {
// this.logger.info("Serializing mapper and reducer...");
//
// String mapperInBase64 = Commons.objectToBase64(this.mapper);
// String reducerInBase64 = Commons.objectToBase64(this.reducer);
//
// this.logger.info("Launching job...");
//
// MappersDriverInfo mappersDriverInfo = new MappersDriverInfo(mapperInBase64, reducerInBase64, this.jobInfo);
//
// Commons.invokeLambdaAsync(this.jobInfo.getMappersDriverFunctionName(), mappersDriverInfo);
// }
// }
//
// Path: examples/ad-hoc-example-1/src/main/java/mapper/Mapper.java
// public class Mapper extends MapperAbstract {
//
// public String map(BufferedReader objectBufferedReader) {
//
// try {
// Map<String, Long> transactionsPerProduct = new HashMap<>();
//
// String line;
// while (((line = objectBufferedReader.readLine()) != null)) {
// String[] fields = line.split(",");
// String productId = fields[3];
// Long currentCount = transactionsPerProduct.get(productId);
// transactionsPerProduct.put(productId, currentCount != null ? currentCount + 1 : 1);
// }
//
// Gson gson = new Gson();
// return gson.toJson(transactionsPerProduct);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
// }
//
// Path: examples/ad-hoc-example-1/src/main/java/reducer/Reducer.java
// public class Reducer extends ReducerAbstract {
//
// public String reduce(List<ObjectInfoSimple> batch) {
// try {
// Gson gson = new Gson();
//
// Map<String, Double> reduceTransactionCountPerProduct = new HashMap<>();
//
// for (ObjectInfoSimple objectInfo : batch) {
//
// BufferedReader objectBufferedReader = Commons.getReaderFromObjectInfo(objectInfo);
//
// Map<String, Double> transactionCountPerProduct = gson.fromJson(objectBufferedReader, HashMap.class);
// transactionCountPerProduct.forEach((k, v) -> reduceTransactionCountPerProduct.merge(k, v, (v1, v2) -> v1 + v2));
//
// objectBufferedReader.close();
// }
//
// return gson.toJson(reduceTransactionCountPerProduct);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
// }
| import fr.d2si.ooso.launcher.Launcher;
import mapper.Mapper;
import reducer.Reducer; | package job;
public class JobLauncher {
public static void main(String[] args) { | // Path: ooso/src/main/java/fr/d2si/ooso/launcher/Launcher.java
// public class Launcher {
// private JobInfo jobInfo;
//
// private MapperAbstract mapper;
// private ReducerAbstract reducer;
//
// private boolean generateId = false;
//
// private Logger logger;
//
// public Launcher withMapper(MapperAbstract mapper) {
// this.mapper = mapper;
// return this;
// }
//
// public Launcher withReducer(ReducerAbstract reducer) {
// this.reducer = reducer;
// return this;
// }
//
// public Launcher withRandomId(boolean generateId) {
// this.generateId = generateId;
// return this;
// }
//
// public String launchJob() {
// try {
// String generatedId = null;
//
// configureLogger();
// loadJobInfo();
//
// if (generateId) {
// generatedId = generateUUID().toString();
// jobInfo.setJobId(generatedId);
// }
//
// if (this.mapper == null || (!this.jobInfo.getDisableReducer() && reducer == null)) {
// throw new RuntimeException("You must set the mapper and reducer classes");
// }
//
// launchMappersDriver();
//
// return generatedId;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// private UUID generateUUID() {
// return new UUID();
// }
//
// private void configureLogger() {
// this.logger = Logger.getAnonymousLogger();
// }
//
// private void loadJobInfo() throws IOException {
// this.logger.info("Loading Job Configuration...");
//
// Gson gson = new Gson();
// InputStream driverInfoStream = getClass().getClassLoader().getResourceAsStream("jobInfo.json");
// BufferedReader driverInfoReader = new BufferedReader(new InputStreamReader(driverInfoStream));
// this.jobInfo = gson.fromJson(driverInfoReader, JobInfo.class);
// driverInfoReader.close();
// }
//
// private void launchMappersDriver() throws IOException {
// this.logger.info("Serializing mapper and reducer...");
//
// String mapperInBase64 = Commons.objectToBase64(this.mapper);
// String reducerInBase64 = Commons.objectToBase64(this.reducer);
//
// this.logger.info("Launching job...");
//
// MappersDriverInfo mappersDriverInfo = new MappersDriverInfo(mapperInBase64, reducerInBase64, this.jobInfo);
//
// Commons.invokeLambdaAsync(this.jobInfo.getMappersDriverFunctionName(), mappersDriverInfo);
// }
// }
//
// Path: examples/ad-hoc-example-1/src/main/java/mapper/Mapper.java
// public class Mapper extends MapperAbstract {
//
// public String map(BufferedReader objectBufferedReader) {
//
// try {
// Map<String, Long> transactionsPerProduct = new HashMap<>();
//
// String line;
// while (((line = objectBufferedReader.readLine()) != null)) {
// String[] fields = line.split(",");
// String productId = fields[3];
// Long currentCount = transactionsPerProduct.get(productId);
// transactionsPerProduct.put(productId, currentCount != null ? currentCount + 1 : 1);
// }
//
// Gson gson = new Gson();
// return gson.toJson(transactionsPerProduct);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
// }
//
// Path: examples/ad-hoc-example-1/src/main/java/reducer/Reducer.java
// public class Reducer extends ReducerAbstract {
//
// public String reduce(List<ObjectInfoSimple> batch) {
// try {
// Gson gson = new Gson();
//
// Map<String, Double> reduceTransactionCountPerProduct = new HashMap<>();
//
// for (ObjectInfoSimple objectInfo : batch) {
//
// BufferedReader objectBufferedReader = Commons.getReaderFromObjectInfo(objectInfo);
//
// Map<String, Double> transactionCountPerProduct = gson.fromJson(objectBufferedReader, HashMap.class);
// transactionCountPerProduct.forEach((k, v) -> reduceTransactionCountPerProduct.merge(k, v, (v1, v2) -> v1 + v2));
//
// objectBufferedReader.close();
// }
//
// return gson.toJson(reduceTransactionCountPerProduct);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
// }
// Path: examples/batch-processing-example/src/main/java/job/JobLauncher.java
import fr.d2si.ooso.launcher.Launcher;
import mapper.Mapper;
import reducer.Reducer;
package job;
public class JobLauncher {
public static void main(String[] args) { | new Launcher() |
d2si-oss/ooso | examples/batch-processing-example/src/main/java/job/JobLauncher.java | // Path: ooso/src/main/java/fr/d2si/ooso/launcher/Launcher.java
// public class Launcher {
// private JobInfo jobInfo;
//
// private MapperAbstract mapper;
// private ReducerAbstract reducer;
//
// private boolean generateId = false;
//
// private Logger logger;
//
// public Launcher withMapper(MapperAbstract mapper) {
// this.mapper = mapper;
// return this;
// }
//
// public Launcher withReducer(ReducerAbstract reducer) {
// this.reducer = reducer;
// return this;
// }
//
// public Launcher withRandomId(boolean generateId) {
// this.generateId = generateId;
// return this;
// }
//
// public String launchJob() {
// try {
// String generatedId = null;
//
// configureLogger();
// loadJobInfo();
//
// if (generateId) {
// generatedId = generateUUID().toString();
// jobInfo.setJobId(generatedId);
// }
//
// if (this.mapper == null || (!this.jobInfo.getDisableReducer() && reducer == null)) {
// throw new RuntimeException("You must set the mapper and reducer classes");
// }
//
// launchMappersDriver();
//
// return generatedId;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// private UUID generateUUID() {
// return new UUID();
// }
//
// private void configureLogger() {
// this.logger = Logger.getAnonymousLogger();
// }
//
// private void loadJobInfo() throws IOException {
// this.logger.info("Loading Job Configuration...");
//
// Gson gson = new Gson();
// InputStream driverInfoStream = getClass().getClassLoader().getResourceAsStream("jobInfo.json");
// BufferedReader driverInfoReader = new BufferedReader(new InputStreamReader(driverInfoStream));
// this.jobInfo = gson.fromJson(driverInfoReader, JobInfo.class);
// driverInfoReader.close();
// }
//
// private void launchMappersDriver() throws IOException {
// this.logger.info("Serializing mapper and reducer...");
//
// String mapperInBase64 = Commons.objectToBase64(this.mapper);
// String reducerInBase64 = Commons.objectToBase64(this.reducer);
//
// this.logger.info("Launching job...");
//
// MappersDriverInfo mappersDriverInfo = new MappersDriverInfo(mapperInBase64, reducerInBase64, this.jobInfo);
//
// Commons.invokeLambdaAsync(this.jobInfo.getMappersDriverFunctionName(), mappersDriverInfo);
// }
// }
//
// Path: examples/ad-hoc-example-1/src/main/java/mapper/Mapper.java
// public class Mapper extends MapperAbstract {
//
// public String map(BufferedReader objectBufferedReader) {
//
// try {
// Map<String, Long> transactionsPerProduct = new HashMap<>();
//
// String line;
// while (((line = objectBufferedReader.readLine()) != null)) {
// String[] fields = line.split(",");
// String productId = fields[3];
// Long currentCount = transactionsPerProduct.get(productId);
// transactionsPerProduct.put(productId, currentCount != null ? currentCount + 1 : 1);
// }
//
// Gson gson = new Gson();
// return gson.toJson(transactionsPerProduct);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
// }
//
// Path: examples/ad-hoc-example-1/src/main/java/reducer/Reducer.java
// public class Reducer extends ReducerAbstract {
//
// public String reduce(List<ObjectInfoSimple> batch) {
// try {
// Gson gson = new Gson();
//
// Map<String, Double> reduceTransactionCountPerProduct = new HashMap<>();
//
// for (ObjectInfoSimple objectInfo : batch) {
//
// BufferedReader objectBufferedReader = Commons.getReaderFromObjectInfo(objectInfo);
//
// Map<String, Double> transactionCountPerProduct = gson.fromJson(objectBufferedReader, HashMap.class);
// transactionCountPerProduct.forEach((k, v) -> reduceTransactionCountPerProduct.merge(k, v, (v1, v2) -> v1 + v2));
//
// objectBufferedReader.close();
// }
//
// return gson.toJson(reduceTransactionCountPerProduct);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
// }
| import fr.d2si.ooso.launcher.Launcher;
import mapper.Mapper;
import reducer.Reducer; | package job;
public class JobLauncher {
public static void main(String[] args) {
new Launcher() | // Path: ooso/src/main/java/fr/d2si/ooso/launcher/Launcher.java
// public class Launcher {
// private JobInfo jobInfo;
//
// private MapperAbstract mapper;
// private ReducerAbstract reducer;
//
// private boolean generateId = false;
//
// private Logger logger;
//
// public Launcher withMapper(MapperAbstract mapper) {
// this.mapper = mapper;
// return this;
// }
//
// public Launcher withReducer(ReducerAbstract reducer) {
// this.reducer = reducer;
// return this;
// }
//
// public Launcher withRandomId(boolean generateId) {
// this.generateId = generateId;
// return this;
// }
//
// public String launchJob() {
// try {
// String generatedId = null;
//
// configureLogger();
// loadJobInfo();
//
// if (generateId) {
// generatedId = generateUUID().toString();
// jobInfo.setJobId(generatedId);
// }
//
// if (this.mapper == null || (!this.jobInfo.getDisableReducer() && reducer == null)) {
// throw new RuntimeException("You must set the mapper and reducer classes");
// }
//
// launchMappersDriver();
//
// return generatedId;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// private UUID generateUUID() {
// return new UUID();
// }
//
// private void configureLogger() {
// this.logger = Logger.getAnonymousLogger();
// }
//
// private void loadJobInfo() throws IOException {
// this.logger.info("Loading Job Configuration...");
//
// Gson gson = new Gson();
// InputStream driverInfoStream = getClass().getClassLoader().getResourceAsStream("jobInfo.json");
// BufferedReader driverInfoReader = new BufferedReader(new InputStreamReader(driverInfoStream));
// this.jobInfo = gson.fromJson(driverInfoReader, JobInfo.class);
// driverInfoReader.close();
// }
//
// private void launchMappersDriver() throws IOException {
// this.logger.info("Serializing mapper and reducer...");
//
// String mapperInBase64 = Commons.objectToBase64(this.mapper);
// String reducerInBase64 = Commons.objectToBase64(this.reducer);
//
// this.logger.info("Launching job...");
//
// MappersDriverInfo mappersDriverInfo = new MappersDriverInfo(mapperInBase64, reducerInBase64, this.jobInfo);
//
// Commons.invokeLambdaAsync(this.jobInfo.getMappersDriverFunctionName(), mappersDriverInfo);
// }
// }
//
// Path: examples/ad-hoc-example-1/src/main/java/mapper/Mapper.java
// public class Mapper extends MapperAbstract {
//
// public String map(BufferedReader objectBufferedReader) {
//
// try {
// Map<String, Long> transactionsPerProduct = new HashMap<>();
//
// String line;
// while (((line = objectBufferedReader.readLine()) != null)) {
// String[] fields = line.split(",");
// String productId = fields[3];
// Long currentCount = transactionsPerProduct.get(productId);
// transactionsPerProduct.put(productId, currentCount != null ? currentCount + 1 : 1);
// }
//
// Gson gson = new Gson();
// return gson.toJson(transactionsPerProduct);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
// }
//
// Path: examples/ad-hoc-example-1/src/main/java/reducer/Reducer.java
// public class Reducer extends ReducerAbstract {
//
// public String reduce(List<ObjectInfoSimple> batch) {
// try {
// Gson gson = new Gson();
//
// Map<String, Double> reduceTransactionCountPerProduct = new HashMap<>();
//
// for (ObjectInfoSimple objectInfo : batch) {
//
// BufferedReader objectBufferedReader = Commons.getReaderFromObjectInfo(objectInfo);
//
// Map<String, Double> transactionCountPerProduct = gson.fromJson(objectBufferedReader, HashMap.class);
// transactionCountPerProduct.forEach((k, v) -> reduceTransactionCountPerProduct.merge(k, v, (v1, v2) -> v1 + v2));
//
// objectBufferedReader.close();
// }
//
// return gson.toJson(reduceTransactionCountPerProduct);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
// }
// Path: examples/batch-processing-example/src/main/java/job/JobLauncher.java
import fr.d2si.ooso.launcher.Launcher;
import mapper.Mapper;
import reducer.Reducer;
package job;
public class JobLauncher {
public static void main(String[] args) {
new Launcher() | .withMapper(new Mapper()) |
d2si-oss/ooso | examples/batch-processing-example/src/main/java/job/JobLauncher.java | // Path: ooso/src/main/java/fr/d2si/ooso/launcher/Launcher.java
// public class Launcher {
// private JobInfo jobInfo;
//
// private MapperAbstract mapper;
// private ReducerAbstract reducer;
//
// private boolean generateId = false;
//
// private Logger logger;
//
// public Launcher withMapper(MapperAbstract mapper) {
// this.mapper = mapper;
// return this;
// }
//
// public Launcher withReducer(ReducerAbstract reducer) {
// this.reducer = reducer;
// return this;
// }
//
// public Launcher withRandomId(boolean generateId) {
// this.generateId = generateId;
// return this;
// }
//
// public String launchJob() {
// try {
// String generatedId = null;
//
// configureLogger();
// loadJobInfo();
//
// if (generateId) {
// generatedId = generateUUID().toString();
// jobInfo.setJobId(generatedId);
// }
//
// if (this.mapper == null || (!this.jobInfo.getDisableReducer() && reducer == null)) {
// throw new RuntimeException("You must set the mapper and reducer classes");
// }
//
// launchMappersDriver();
//
// return generatedId;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// private UUID generateUUID() {
// return new UUID();
// }
//
// private void configureLogger() {
// this.logger = Logger.getAnonymousLogger();
// }
//
// private void loadJobInfo() throws IOException {
// this.logger.info("Loading Job Configuration...");
//
// Gson gson = new Gson();
// InputStream driverInfoStream = getClass().getClassLoader().getResourceAsStream("jobInfo.json");
// BufferedReader driverInfoReader = new BufferedReader(new InputStreamReader(driverInfoStream));
// this.jobInfo = gson.fromJson(driverInfoReader, JobInfo.class);
// driverInfoReader.close();
// }
//
// private void launchMappersDriver() throws IOException {
// this.logger.info("Serializing mapper and reducer...");
//
// String mapperInBase64 = Commons.objectToBase64(this.mapper);
// String reducerInBase64 = Commons.objectToBase64(this.reducer);
//
// this.logger.info("Launching job...");
//
// MappersDriverInfo mappersDriverInfo = new MappersDriverInfo(mapperInBase64, reducerInBase64, this.jobInfo);
//
// Commons.invokeLambdaAsync(this.jobInfo.getMappersDriverFunctionName(), mappersDriverInfo);
// }
// }
//
// Path: examples/ad-hoc-example-1/src/main/java/mapper/Mapper.java
// public class Mapper extends MapperAbstract {
//
// public String map(BufferedReader objectBufferedReader) {
//
// try {
// Map<String, Long> transactionsPerProduct = new HashMap<>();
//
// String line;
// while (((line = objectBufferedReader.readLine()) != null)) {
// String[] fields = line.split(",");
// String productId = fields[3];
// Long currentCount = transactionsPerProduct.get(productId);
// transactionsPerProduct.put(productId, currentCount != null ? currentCount + 1 : 1);
// }
//
// Gson gson = new Gson();
// return gson.toJson(transactionsPerProduct);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
// }
//
// Path: examples/ad-hoc-example-1/src/main/java/reducer/Reducer.java
// public class Reducer extends ReducerAbstract {
//
// public String reduce(List<ObjectInfoSimple> batch) {
// try {
// Gson gson = new Gson();
//
// Map<String, Double> reduceTransactionCountPerProduct = new HashMap<>();
//
// for (ObjectInfoSimple objectInfo : batch) {
//
// BufferedReader objectBufferedReader = Commons.getReaderFromObjectInfo(objectInfo);
//
// Map<String, Double> transactionCountPerProduct = gson.fromJson(objectBufferedReader, HashMap.class);
// transactionCountPerProduct.forEach((k, v) -> reduceTransactionCountPerProduct.merge(k, v, (v1, v2) -> v1 + v2));
//
// objectBufferedReader.close();
// }
//
// return gson.toJson(reduceTransactionCountPerProduct);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
// }
| import fr.d2si.ooso.launcher.Launcher;
import mapper.Mapper;
import reducer.Reducer; | package job;
public class JobLauncher {
public static void main(String[] args) {
new Launcher()
.withMapper(new Mapper()) | // Path: ooso/src/main/java/fr/d2si/ooso/launcher/Launcher.java
// public class Launcher {
// private JobInfo jobInfo;
//
// private MapperAbstract mapper;
// private ReducerAbstract reducer;
//
// private boolean generateId = false;
//
// private Logger logger;
//
// public Launcher withMapper(MapperAbstract mapper) {
// this.mapper = mapper;
// return this;
// }
//
// public Launcher withReducer(ReducerAbstract reducer) {
// this.reducer = reducer;
// return this;
// }
//
// public Launcher withRandomId(boolean generateId) {
// this.generateId = generateId;
// return this;
// }
//
// public String launchJob() {
// try {
// String generatedId = null;
//
// configureLogger();
// loadJobInfo();
//
// if (generateId) {
// generatedId = generateUUID().toString();
// jobInfo.setJobId(generatedId);
// }
//
// if (this.mapper == null || (!this.jobInfo.getDisableReducer() && reducer == null)) {
// throw new RuntimeException("You must set the mapper and reducer classes");
// }
//
// launchMappersDriver();
//
// return generatedId;
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// private UUID generateUUID() {
// return new UUID();
// }
//
// private void configureLogger() {
// this.logger = Logger.getAnonymousLogger();
// }
//
// private void loadJobInfo() throws IOException {
// this.logger.info("Loading Job Configuration...");
//
// Gson gson = new Gson();
// InputStream driverInfoStream = getClass().getClassLoader().getResourceAsStream("jobInfo.json");
// BufferedReader driverInfoReader = new BufferedReader(new InputStreamReader(driverInfoStream));
// this.jobInfo = gson.fromJson(driverInfoReader, JobInfo.class);
// driverInfoReader.close();
// }
//
// private void launchMappersDriver() throws IOException {
// this.logger.info("Serializing mapper and reducer...");
//
// String mapperInBase64 = Commons.objectToBase64(this.mapper);
// String reducerInBase64 = Commons.objectToBase64(this.reducer);
//
// this.logger.info("Launching job...");
//
// MappersDriverInfo mappersDriverInfo = new MappersDriverInfo(mapperInBase64, reducerInBase64, this.jobInfo);
//
// Commons.invokeLambdaAsync(this.jobInfo.getMappersDriverFunctionName(), mappersDriverInfo);
// }
// }
//
// Path: examples/ad-hoc-example-1/src/main/java/mapper/Mapper.java
// public class Mapper extends MapperAbstract {
//
// public String map(BufferedReader objectBufferedReader) {
//
// try {
// Map<String, Long> transactionsPerProduct = new HashMap<>();
//
// String line;
// while (((line = objectBufferedReader.readLine()) != null)) {
// String[] fields = line.split(",");
// String productId = fields[3];
// Long currentCount = transactionsPerProduct.get(productId);
// transactionsPerProduct.put(productId, currentCount != null ? currentCount + 1 : 1);
// }
//
// Gson gson = new Gson();
// return gson.toJson(transactionsPerProduct);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
// }
//
// Path: examples/ad-hoc-example-1/src/main/java/reducer/Reducer.java
// public class Reducer extends ReducerAbstract {
//
// public String reduce(List<ObjectInfoSimple> batch) {
// try {
// Gson gson = new Gson();
//
// Map<String, Double> reduceTransactionCountPerProduct = new HashMap<>();
//
// for (ObjectInfoSimple objectInfo : batch) {
//
// BufferedReader objectBufferedReader = Commons.getReaderFromObjectInfo(objectInfo);
//
// Map<String, Double> transactionCountPerProduct = gson.fromJson(objectBufferedReader, HashMap.class);
// transactionCountPerProduct.forEach((k, v) -> reduceTransactionCountPerProduct.merge(k, v, (v1, v2) -> v1 + v2));
//
// objectBufferedReader.close();
// }
//
// return gson.toJson(reduceTransactionCountPerProduct);
// } catch (IOException e) {
// e.printStackTrace();
// }
// return null;
// }
// }
// Path: examples/batch-processing-example/src/main/java/job/JobLauncher.java
import fr.d2si.ooso.launcher.Launcher;
import mapper.Mapper;
import reducer.Reducer;
package job;
public class JobLauncher {
public static void main(String[] args) {
new Launcher()
.withMapper(new Mapper()) | .withReducer(new Reducer()) |
d2si-oss/ooso | ooso/src/main/java/fr/d2si/ooso/reducers_driver/ReducersDriverInfo.java | // Path: ooso/src/main/java/fr/d2si/ooso/utils/JobInfo.java
// public class JobInfo {
// private String jobId;
// private String jobInputBucket;
// private String mapperOutputBucket;
// private String reducerOutputBucket;
// private String mapperFunctionName;
// private String mappersDriverFunctionName;
// private String mappersListenerFunctionName;
// private String reducerFunctionName;
// private String reducersDriverFunctionName;
// private String reducersListenerFunctionName;
// private String statusTable;
// private String mapperMemory;
// private String reducerMemory;
// private String mapperForceBatchSize;
// private String reducerForceBatchSize;
// private String disableReducer;
//
// public JobInfo() {
// }
//
// public JobInfo(String jobId, String jobInputBucket, String mapperOutputBucket, String reducerOutputBucket, String mapperFunctionName, String mappersDriverFunctionName, String mappersListenerFunctionName, String reducerFunctionName, String reducersDriverFunctionName, String reducersListenerFunctionName, String statusTable, String mapperMemory, String reducerMemory, String mapperForceBatchSize, String reducerForceBatchSize, String disableReducer) {
// this.jobId = jobId;
// this.jobInputBucket = jobInputBucket;
// this.mapperOutputBucket = mapperOutputBucket;
// this.reducerOutputBucket = reducerOutputBucket;
// this.mapperFunctionName = mapperFunctionName;
// this.mappersDriverFunctionName = mappersDriverFunctionName;
// this.mappersListenerFunctionName = mappersListenerFunctionName;
// this.reducerFunctionName = reducerFunctionName;
// this.reducersDriverFunctionName = reducersDriverFunctionName;
// this.reducersListenerFunctionName = reducersListenerFunctionName;
// this.statusTable = statusTable;
// this.mapperMemory = mapperMemory;
// this.reducerMemory = reducerMemory;
// this.mapperForceBatchSize = mapperForceBatchSize;
// this.reducerForceBatchSize = reducerForceBatchSize;
// this.disableReducer = disableReducer;
// }
//
// public String getJobInputBucket() {
// return jobInputBucket;
// }
//
// public void setJobInputBucket(String jobInputBucket) {
// this.jobInputBucket = jobInputBucket;
// }
//
// public String getMapperOutputBucket() {
// return mapperOutputBucket;
// }
//
// public void setMapperOutputBucket(String mapperOutputBucket) {
// this.mapperOutputBucket = mapperOutputBucket;
// }
//
// public String getReducerOutputBucket() {
// return reducerOutputBucket;
// }
//
// public void setReducerOutputBucket(String reducerOutputBucket) {
// this.reducerOutputBucket = reducerOutputBucket;
// }
//
// public String getMapperFunctionName() {
// return mapperFunctionName;
// }
//
// public void setMapperFunctionName(String mapperFunctionName) {
// this.mapperFunctionName = mapperFunctionName;
// }
//
// public String getReducerFunctionName() {
// return reducerFunctionName;
// }
//
// public void setReducerFunctionName(String reducerFunctionName) {
// this.reducerFunctionName = reducerFunctionName;
// }
//
// public String getStatusTable() {
// return statusTable;
// }
//
// public void setStatusTable(String statusTable) {
// this.statusTable = statusTable;
// }
//
// public String getJobId() {
// return jobId;
// }
//
// public void setJobId(String jobId) {
// this.jobId = jobId;
// }
//
// public int getMapperMemory() {
// return Integer.parseInt(mapperMemory);
// }
//
// public void setMapperMemory(String mapperMemory) {
// this.mapperMemory = mapperMemory;
// }
//
// public int getReducerMemory() {
// return Integer.parseInt(reducerMemory);
// }
//
// public void setReducerMemory(String reducerMemory) {
// this.reducerMemory = reducerMemory;
// }
//
// public int getMapperForceBatchSize() {
// return Integer.parseInt(mapperForceBatchSize);
// }
//
// public void setMapperForceBatchSize(String mapperForceBatchSize) {
// this.mapperForceBatchSize = mapperForceBatchSize;
// }
//
// public int getReducerForceBatchSize() {
// return Integer.parseInt(reducerForceBatchSize);
// }
//
// public void setReducerForceBatchSize(String reducerForceBatchSize) {
// this.reducerForceBatchSize = reducerForceBatchSize;
// }
//
// public boolean getDisableReducer() {
// return Boolean.parseBoolean(disableReducer);
// }
//
// public void setDisableReducer(String disableReducer) {
// this.disableReducer = disableReducer;
// }
//
// public String getMappersDriverFunctionName() {
// return mappersDriverFunctionName;
// }
//
// public void setMappersDriverFunctionName(String mappersDriverFunctionName) {
// this.mappersDriverFunctionName = mappersDriverFunctionName;
// }
//
// public String getMappersListenerFunctionName() {
// return mappersListenerFunctionName;
// }
//
// public void setMappersListenerFunctionName(String mappersListenerFunctionName) {
// this.mappersListenerFunctionName = mappersListenerFunctionName;
// }
//
// public String getReducersDriverFunctionName() {
// return reducersDriverFunctionName;
// }
//
// public void setReducersDriverFunctionName(String reducersDriverFunctionName) {
// this.reducersDriverFunctionName = reducersDriverFunctionName;
// }
//
// public String getReducersListenerFunctionName() {
// return reducersListenerFunctionName;
// }
//
// public void setReducersListenerFunctionName(String reducersListenerFunctionName) {
// this.reducersListenerFunctionName = reducersListenerFunctionName;
// }
// }
| import fr.d2si.ooso.utils.JobInfo; | package fr.d2si.ooso.reducers_driver;
public class ReducersDriverInfo {
private int step;
private String reducerInBase64; | // Path: ooso/src/main/java/fr/d2si/ooso/utils/JobInfo.java
// public class JobInfo {
// private String jobId;
// private String jobInputBucket;
// private String mapperOutputBucket;
// private String reducerOutputBucket;
// private String mapperFunctionName;
// private String mappersDriverFunctionName;
// private String mappersListenerFunctionName;
// private String reducerFunctionName;
// private String reducersDriverFunctionName;
// private String reducersListenerFunctionName;
// private String statusTable;
// private String mapperMemory;
// private String reducerMemory;
// private String mapperForceBatchSize;
// private String reducerForceBatchSize;
// private String disableReducer;
//
// public JobInfo() {
// }
//
// public JobInfo(String jobId, String jobInputBucket, String mapperOutputBucket, String reducerOutputBucket, String mapperFunctionName, String mappersDriverFunctionName, String mappersListenerFunctionName, String reducerFunctionName, String reducersDriverFunctionName, String reducersListenerFunctionName, String statusTable, String mapperMemory, String reducerMemory, String mapperForceBatchSize, String reducerForceBatchSize, String disableReducer) {
// this.jobId = jobId;
// this.jobInputBucket = jobInputBucket;
// this.mapperOutputBucket = mapperOutputBucket;
// this.reducerOutputBucket = reducerOutputBucket;
// this.mapperFunctionName = mapperFunctionName;
// this.mappersDriverFunctionName = mappersDriverFunctionName;
// this.mappersListenerFunctionName = mappersListenerFunctionName;
// this.reducerFunctionName = reducerFunctionName;
// this.reducersDriverFunctionName = reducersDriverFunctionName;
// this.reducersListenerFunctionName = reducersListenerFunctionName;
// this.statusTable = statusTable;
// this.mapperMemory = mapperMemory;
// this.reducerMemory = reducerMemory;
// this.mapperForceBatchSize = mapperForceBatchSize;
// this.reducerForceBatchSize = reducerForceBatchSize;
// this.disableReducer = disableReducer;
// }
//
// public String getJobInputBucket() {
// return jobInputBucket;
// }
//
// public void setJobInputBucket(String jobInputBucket) {
// this.jobInputBucket = jobInputBucket;
// }
//
// public String getMapperOutputBucket() {
// return mapperOutputBucket;
// }
//
// public void setMapperOutputBucket(String mapperOutputBucket) {
// this.mapperOutputBucket = mapperOutputBucket;
// }
//
// public String getReducerOutputBucket() {
// return reducerOutputBucket;
// }
//
// public void setReducerOutputBucket(String reducerOutputBucket) {
// this.reducerOutputBucket = reducerOutputBucket;
// }
//
// public String getMapperFunctionName() {
// return mapperFunctionName;
// }
//
// public void setMapperFunctionName(String mapperFunctionName) {
// this.mapperFunctionName = mapperFunctionName;
// }
//
// public String getReducerFunctionName() {
// return reducerFunctionName;
// }
//
// public void setReducerFunctionName(String reducerFunctionName) {
// this.reducerFunctionName = reducerFunctionName;
// }
//
// public String getStatusTable() {
// return statusTable;
// }
//
// public void setStatusTable(String statusTable) {
// this.statusTable = statusTable;
// }
//
// public String getJobId() {
// return jobId;
// }
//
// public void setJobId(String jobId) {
// this.jobId = jobId;
// }
//
// public int getMapperMemory() {
// return Integer.parseInt(mapperMemory);
// }
//
// public void setMapperMemory(String mapperMemory) {
// this.mapperMemory = mapperMemory;
// }
//
// public int getReducerMemory() {
// return Integer.parseInt(reducerMemory);
// }
//
// public void setReducerMemory(String reducerMemory) {
// this.reducerMemory = reducerMemory;
// }
//
// public int getMapperForceBatchSize() {
// return Integer.parseInt(mapperForceBatchSize);
// }
//
// public void setMapperForceBatchSize(String mapperForceBatchSize) {
// this.mapperForceBatchSize = mapperForceBatchSize;
// }
//
// public int getReducerForceBatchSize() {
// return Integer.parseInt(reducerForceBatchSize);
// }
//
// public void setReducerForceBatchSize(String reducerForceBatchSize) {
// this.reducerForceBatchSize = reducerForceBatchSize;
// }
//
// public boolean getDisableReducer() {
// return Boolean.parseBoolean(disableReducer);
// }
//
// public void setDisableReducer(String disableReducer) {
// this.disableReducer = disableReducer;
// }
//
// public String getMappersDriverFunctionName() {
// return mappersDriverFunctionName;
// }
//
// public void setMappersDriverFunctionName(String mappersDriverFunctionName) {
// this.mappersDriverFunctionName = mappersDriverFunctionName;
// }
//
// public String getMappersListenerFunctionName() {
// return mappersListenerFunctionName;
// }
//
// public void setMappersListenerFunctionName(String mappersListenerFunctionName) {
// this.mappersListenerFunctionName = mappersListenerFunctionName;
// }
//
// public String getReducersDriverFunctionName() {
// return reducersDriverFunctionName;
// }
//
// public void setReducersDriverFunctionName(String reducersDriverFunctionName) {
// this.reducersDriverFunctionName = reducersDriverFunctionName;
// }
//
// public String getReducersListenerFunctionName() {
// return reducersListenerFunctionName;
// }
//
// public void setReducersListenerFunctionName(String reducersListenerFunctionName) {
// this.reducersListenerFunctionName = reducersListenerFunctionName;
// }
// }
// Path: ooso/src/main/java/fr/d2si/ooso/reducers_driver/ReducersDriverInfo.java
import fr.d2si.ooso.utils.JobInfo;
package fr.d2si.ooso.reducers_driver;
public class ReducersDriverInfo {
private int step;
private String reducerInBase64; | private JobInfo jobInfo; |
d2si-oss/ooso | ooso/src/main/java/fr/d2si/ooso/mappers_driver/MappersDriver.java | // Path: ooso/src/main/java/fr/d2si/ooso/mapper_wrapper/MapperWrapperInfo.java
// public class MapperWrapperInfo {
// private long id;
// private List<ObjectInfoSimple> batch;
// private String mapperLogicInBase64;
// private JobInfo jobInfo;
//
// public MapperWrapperInfo() {
// }
//
// public MapperWrapperInfo(List<ObjectInfoSimple> batch, long id, String mapperLogicInBase64, JobInfo jobInfo) {
// this.batch = batch;
// this.id = id;
// this.mapperLogicInBase64 = mapperLogicInBase64;
// this.jobInfo = jobInfo;
// }
//
// public List<ObjectInfoSimple> getBatch() {
// return batch;
// }
//
// public void setBatch(List<ObjectInfoSimple> batch) {
// this.batch = batch;
// }
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getMapperLogicInBase64() {
// return mapperLogicInBase64;
// }
//
// public void setMapperLogicInBase64(String mapperLogicInBase64) {
// this.mapperLogicInBase64 = mapperLogicInBase64;
// }
//
// public JobInfo getJobInfo() {
// return jobInfo;
// }
//
// public void setJobInfo(JobInfo jobInfo) {
// this.jobInfo = jobInfo;
// }
// }
//
// Path: ooso/src/main/java/fr/d2si/ooso/mappers_listener/MappersListenerInfo.java
// public class MappersListenerInfo {
// private String reducerInBase64;
// private JobInfo jobInfo;
//
// public MappersListenerInfo() {
// }
//
// public MappersListenerInfo(String reducerInBase64, JobInfo jobInfo) {
// this.reducerInBase64 = reducerInBase64;
// this.jobInfo = jobInfo;
// }
//
// public String getReducerInBase64() {
// return reducerInBase64;
// }
//
// public void setReducerInBase64(String reducerInBase64) {
// this.reducerInBase64 = reducerInBase64;
// }
//
// public JobInfo getJobInfo() {
// return jobInfo;
// }
//
// public void setJobInfo(JobInfo jobInfo) {
// this.jobInfo = jobInfo;
// }
// }
//
// Path: ooso/src/main/java/fr/d2si/ooso/utils/Commons.java
// public final static String IGNORED_RETURN_VALUE = "";
| import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import fr.d2si.ooso.mapper_wrapper.MapperWrapperInfo;
import fr.d2si.ooso.mappers_listener.MappersListenerInfo;
import fr.d2si.ooso.utils.*;
import java.util.List;
import static fr.d2si.ooso.utils.Commons.IGNORED_RETURN_VALUE; | package fr.d2si.ooso.mappers_driver;
public class MappersDriver implements RequestHandler<MappersDriverInfo, String> {
private AmazonS3 s3Client;
private JobInfo jobInfo;
private String jobId;
private MappersDriverInfo mappersDriverInfo;
@Override
public String handleRequest(MappersDriverInfo mappersDriverInfo, Context context) {
try {
this.mappersDriverInfo = mappersDriverInfo;
this.s3Client = AmazonS3Provider.getS3Client();
this.jobInfo = this.mappersDriverInfo.getJobInfo();
this.jobId = this.jobInfo.getJobId();
cleanup();
validateParamsOrFail();
List<List<ObjectInfoSimple>> batches = getBatches();
invokeMappersListener();
invokeMappers(batches);
} catch (Exception e) {
throw new RuntimeException(e);
}
| // Path: ooso/src/main/java/fr/d2si/ooso/mapper_wrapper/MapperWrapperInfo.java
// public class MapperWrapperInfo {
// private long id;
// private List<ObjectInfoSimple> batch;
// private String mapperLogicInBase64;
// private JobInfo jobInfo;
//
// public MapperWrapperInfo() {
// }
//
// public MapperWrapperInfo(List<ObjectInfoSimple> batch, long id, String mapperLogicInBase64, JobInfo jobInfo) {
// this.batch = batch;
// this.id = id;
// this.mapperLogicInBase64 = mapperLogicInBase64;
// this.jobInfo = jobInfo;
// }
//
// public List<ObjectInfoSimple> getBatch() {
// return batch;
// }
//
// public void setBatch(List<ObjectInfoSimple> batch) {
// this.batch = batch;
// }
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getMapperLogicInBase64() {
// return mapperLogicInBase64;
// }
//
// public void setMapperLogicInBase64(String mapperLogicInBase64) {
// this.mapperLogicInBase64 = mapperLogicInBase64;
// }
//
// public JobInfo getJobInfo() {
// return jobInfo;
// }
//
// public void setJobInfo(JobInfo jobInfo) {
// this.jobInfo = jobInfo;
// }
// }
//
// Path: ooso/src/main/java/fr/d2si/ooso/mappers_listener/MappersListenerInfo.java
// public class MappersListenerInfo {
// private String reducerInBase64;
// private JobInfo jobInfo;
//
// public MappersListenerInfo() {
// }
//
// public MappersListenerInfo(String reducerInBase64, JobInfo jobInfo) {
// this.reducerInBase64 = reducerInBase64;
// this.jobInfo = jobInfo;
// }
//
// public String getReducerInBase64() {
// return reducerInBase64;
// }
//
// public void setReducerInBase64(String reducerInBase64) {
// this.reducerInBase64 = reducerInBase64;
// }
//
// public JobInfo getJobInfo() {
// return jobInfo;
// }
//
// public void setJobInfo(JobInfo jobInfo) {
// this.jobInfo = jobInfo;
// }
// }
//
// Path: ooso/src/main/java/fr/d2si/ooso/utils/Commons.java
// public final static String IGNORED_RETURN_VALUE = "";
// Path: ooso/src/main/java/fr/d2si/ooso/mappers_driver/MappersDriver.java
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import fr.d2si.ooso.mapper_wrapper.MapperWrapperInfo;
import fr.d2si.ooso.mappers_listener.MappersListenerInfo;
import fr.d2si.ooso.utils.*;
import java.util.List;
import static fr.d2si.ooso.utils.Commons.IGNORED_RETURN_VALUE;
package fr.d2si.ooso.mappers_driver;
public class MappersDriver implements RequestHandler<MappersDriverInfo, String> {
private AmazonS3 s3Client;
private JobInfo jobInfo;
private String jobId;
private MappersDriverInfo mappersDriverInfo;
@Override
public String handleRequest(MappersDriverInfo mappersDriverInfo, Context context) {
try {
this.mappersDriverInfo = mappersDriverInfo;
this.s3Client = AmazonS3Provider.getS3Client();
this.jobInfo = this.mappersDriverInfo.getJobInfo();
this.jobId = this.jobInfo.getJobId();
cleanup();
validateParamsOrFail();
List<List<ObjectInfoSimple>> batches = getBatches();
invokeMappersListener();
invokeMappers(batches);
} catch (Exception e) {
throw new RuntimeException(e);
}
| return IGNORED_RETURN_VALUE; |
d2si-oss/ooso | ooso/src/main/java/fr/d2si/ooso/mappers_driver/MappersDriver.java | // Path: ooso/src/main/java/fr/d2si/ooso/mapper_wrapper/MapperWrapperInfo.java
// public class MapperWrapperInfo {
// private long id;
// private List<ObjectInfoSimple> batch;
// private String mapperLogicInBase64;
// private JobInfo jobInfo;
//
// public MapperWrapperInfo() {
// }
//
// public MapperWrapperInfo(List<ObjectInfoSimple> batch, long id, String mapperLogicInBase64, JobInfo jobInfo) {
// this.batch = batch;
// this.id = id;
// this.mapperLogicInBase64 = mapperLogicInBase64;
// this.jobInfo = jobInfo;
// }
//
// public List<ObjectInfoSimple> getBatch() {
// return batch;
// }
//
// public void setBatch(List<ObjectInfoSimple> batch) {
// this.batch = batch;
// }
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getMapperLogicInBase64() {
// return mapperLogicInBase64;
// }
//
// public void setMapperLogicInBase64(String mapperLogicInBase64) {
// this.mapperLogicInBase64 = mapperLogicInBase64;
// }
//
// public JobInfo getJobInfo() {
// return jobInfo;
// }
//
// public void setJobInfo(JobInfo jobInfo) {
// this.jobInfo = jobInfo;
// }
// }
//
// Path: ooso/src/main/java/fr/d2si/ooso/mappers_listener/MappersListenerInfo.java
// public class MappersListenerInfo {
// private String reducerInBase64;
// private JobInfo jobInfo;
//
// public MappersListenerInfo() {
// }
//
// public MappersListenerInfo(String reducerInBase64, JobInfo jobInfo) {
// this.reducerInBase64 = reducerInBase64;
// this.jobInfo = jobInfo;
// }
//
// public String getReducerInBase64() {
// return reducerInBase64;
// }
//
// public void setReducerInBase64(String reducerInBase64) {
// this.reducerInBase64 = reducerInBase64;
// }
//
// public JobInfo getJobInfo() {
// return jobInfo;
// }
//
// public void setJobInfo(JobInfo jobInfo) {
// this.jobInfo = jobInfo;
// }
// }
//
// Path: ooso/src/main/java/fr/d2si/ooso/utils/Commons.java
// public final static String IGNORED_RETURN_VALUE = "";
| import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import fr.d2si.ooso.mapper_wrapper.MapperWrapperInfo;
import fr.d2si.ooso.mappers_listener.MappersListenerInfo;
import fr.d2si.ooso.utils.*;
import java.util.List;
import static fr.d2si.ooso.utils.Commons.IGNORED_RETURN_VALUE; |
for (S3ObjectSummary object : reduceOutput)
this.s3Client.deleteObject(object.getBucketName(), object.getKey());
}
private void validateParamsOrFail() {
String realInputBucket = Commons.getBucketFromFullPath(this.jobInfo.getJobInputBucket());
if (!this.s3Client.doesBucketExist(realInputBucket))
throw new AmazonS3Exception("Bad parameter <jobInputBucket>: Bucket does not exist");
if (!this.s3Client.doesBucketExist(this.jobInfo.getMapperOutputBucket()))
throw new AmazonS3Exception("Bad parameter <mapperOutputBucket>: Bucket does not exist");
if (!this.s3Client.doesBucketExist(this.jobInfo.getReducerOutputBucket()))
throw new AmazonS3Exception("Bad parameter <reducerOutputBucket>: Bucket does not exist");
if (this.jobInfo.getReducerForceBatchSize() == 1)
throw new AmazonS3Exception("Bad parameter <reducerForceBatchSize>: Reducer batch size must be greater or equal than 2");
}
private List<List<ObjectInfoSimple>> getBatches() {
return Commons.getBatches(
this.jobInfo.getJobInputBucket(),
this.jobInfo.getMapperMemory(),
this.jobInfo.getMapperForceBatchSize());
}
private void invokeMappersListener() {
Commons.invokeLambdaAsync(
this.jobInfo.getMappersListenerFunctionName(), | // Path: ooso/src/main/java/fr/d2si/ooso/mapper_wrapper/MapperWrapperInfo.java
// public class MapperWrapperInfo {
// private long id;
// private List<ObjectInfoSimple> batch;
// private String mapperLogicInBase64;
// private JobInfo jobInfo;
//
// public MapperWrapperInfo() {
// }
//
// public MapperWrapperInfo(List<ObjectInfoSimple> batch, long id, String mapperLogicInBase64, JobInfo jobInfo) {
// this.batch = batch;
// this.id = id;
// this.mapperLogicInBase64 = mapperLogicInBase64;
// this.jobInfo = jobInfo;
// }
//
// public List<ObjectInfoSimple> getBatch() {
// return batch;
// }
//
// public void setBatch(List<ObjectInfoSimple> batch) {
// this.batch = batch;
// }
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getMapperLogicInBase64() {
// return mapperLogicInBase64;
// }
//
// public void setMapperLogicInBase64(String mapperLogicInBase64) {
// this.mapperLogicInBase64 = mapperLogicInBase64;
// }
//
// public JobInfo getJobInfo() {
// return jobInfo;
// }
//
// public void setJobInfo(JobInfo jobInfo) {
// this.jobInfo = jobInfo;
// }
// }
//
// Path: ooso/src/main/java/fr/d2si/ooso/mappers_listener/MappersListenerInfo.java
// public class MappersListenerInfo {
// private String reducerInBase64;
// private JobInfo jobInfo;
//
// public MappersListenerInfo() {
// }
//
// public MappersListenerInfo(String reducerInBase64, JobInfo jobInfo) {
// this.reducerInBase64 = reducerInBase64;
// this.jobInfo = jobInfo;
// }
//
// public String getReducerInBase64() {
// return reducerInBase64;
// }
//
// public void setReducerInBase64(String reducerInBase64) {
// this.reducerInBase64 = reducerInBase64;
// }
//
// public JobInfo getJobInfo() {
// return jobInfo;
// }
//
// public void setJobInfo(JobInfo jobInfo) {
// this.jobInfo = jobInfo;
// }
// }
//
// Path: ooso/src/main/java/fr/d2si/ooso/utils/Commons.java
// public final static String IGNORED_RETURN_VALUE = "";
// Path: ooso/src/main/java/fr/d2si/ooso/mappers_driver/MappersDriver.java
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import fr.d2si.ooso.mapper_wrapper.MapperWrapperInfo;
import fr.d2si.ooso.mappers_listener.MappersListenerInfo;
import fr.d2si.ooso.utils.*;
import java.util.List;
import static fr.d2si.ooso.utils.Commons.IGNORED_RETURN_VALUE;
for (S3ObjectSummary object : reduceOutput)
this.s3Client.deleteObject(object.getBucketName(), object.getKey());
}
private void validateParamsOrFail() {
String realInputBucket = Commons.getBucketFromFullPath(this.jobInfo.getJobInputBucket());
if (!this.s3Client.doesBucketExist(realInputBucket))
throw new AmazonS3Exception("Bad parameter <jobInputBucket>: Bucket does not exist");
if (!this.s3Client.doesBucketExist(this.jobInfo.getMapperOutputBucket()))
throw new AmazonS3Exception("Bad parameter <mapperOutputBucket>: Bucket does not exist");
if (!this.s3Client.doesBucketExist(this.jobInfo.getReducerOutputBucket()))
throw new AmazonS3Exception("Bad parameter <reducerOutputBucket>: Bucket does not exist");
if (this.jobInfo.getReducerForceBatchSize() == 1)
throw new AmazonS3Exception("Bad parameter <reducerForceBatchSize>: Reducer batch size must be greater or equal than 2");
}
private List<List<ObjectInfoSimple>> getBatches() {
return Commons.getBatches(
this.jobInfo.getJobInputBucket(),
this.jobInfo.getMapperMemory(),
this.jobInfo.getMapperForceBatchSize());
}
private void invokeMappersListener() {
Commons.invokeLambdaAsync(
this.jobInfo.getMappersListenerFunctionName(), | new MappersListenerInfo( |
d2si-oss/ooso | ooso/src/main/java/fr/d2si/ooso/mappers_driver/MappersDriver.java | // Path: ooso/src/main/java/fr/d2si/ooso/mapper_wrapper/MapperWrapperInfo.java
// public class MapperWrapperInfo {
// private long id;
// private List<ObjectInfoSimple> batch;
// private String mapperLogicInBase64;
// private JobInfo jobInfo;
//
// public MapperWrapperInfo() {
// }
//
// public MapperWrapperInfo(List<ObjectInfoSimple> batch, long id, String mapperLogicInBase64, JobInfo jobInfo) {
// this.batch = batch;
// this.id = id;
// this.mapperLogicInBase64 = mapperLogicInBase64;
// this.jobInfo = jobInfo;
// }
//
// public List<ObjectInfoSimple> getBatch() {
// return batch;
// }
//
// public void setBatch(List<ObjectInfoSimple> batch) {
// this.batch = batch;
// }
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getMapperLogicInBase64() {
// return mapperLogicInBase64;
// }
//
// public void setMapperLogicInBase64(String mapperLogicInBase64) {
// this.mapperLogicInBase64 = mapperLogicInBase64;
// }
//
// public JobInfo getJobInfo() {
// return jobInfo;
// }
//
// public void setJobInfo(JobInfo jobInfo) {
// this.jobInfo = jobInfo;
// }
// }
//
// Path: ooso/src/main/java/fr/d2si/ooso/mappers_listener/MappersListenerInfo.java
// public class MappersListenerInfo {
// private String reducerInBase64;
// private JobInfo jobInfo;
//
// public MappersListenerInfo() {
// }
//
// public MappersListenerInfo(String reducerInBase64, JobInfo jobInfo) {
// this.reducerInBase64 = reducerInBase64;
// this.jobInfo = jobInfo;
// }
//
// public String getReducerInBase64() {
// return reducerInBase64;
// }
//
// public void setReducerInBase64(String reducerInBase64) {
// this.reducerInBase64 = reducerInBase64;
// }
//
// public JobInfo getJobInfo() {
// return jobInfo;
// }
//
// public void setJobInfo(JobInfo jobInfo) {
// this.jobInfo = jobInfo;
// }
// }
//
// Path: ooso/src/main/java/fr/d2si/ooso/utils/Commons.java
// public final static String IGNORED_RETURN_VALUE = "";
| import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import fr.d2si.ooso.mapper_wrapper.MapperWrapperInfo;
import fr.d2si.ooso.mappers_listener.MappersListenerInfo;
import fr.d2si.ooso.utils.*;
import java.util.List;
import static fr.d2si.ooso.utils.Commons.IGNORED_RETURN_VALUE; |
if (!this.s3Client.doesBucketExist(this.jobInfo.getMapperOutputBucket()))
throw new AmazonS3Exception("Bad parameter <mapperOutputBucket>: Bucket does not exist");
if (!this.s3Client.doesBucketExist(this.jobInfo.getReducerOutputBucket()))
throw new AmazonS3Exception("Bad parameter <reducerOutputBucket>: Bucket does not exist");
if (this.jobInfo.getReducerForceBatchSize() == 1)
throw new AmazonS3Exception("Bad parameter <reducerForceBatchSize>: Reducer batch size must be greater or equal than 2");
}
private List<List<ObjectInfoSimple>> getBatches() {
return Commons.getBatches(
this.jobInfo.getJobInputBucket(),
this.jobInfo.getMapperMemory(),
this.jobInfo.getMapperForceBatchSize());
}
private void invokeMappersListener() {
Commons.invokeLambdaAsync(
this.jobInfo.getMappersListenerFunctionName(),
new MappersListenerInfo(
this.mappersDriverInfo.getReducerInBase64(),
this.jobInfo));
}
private void invokeMappers(List<List<ObjectInfoSimple>> batches) {
int currentMapperId = 0;
for (List<ObjectInfoSimple> batch : batches) { | // Path: ooso/src/main/java/fr/d2si/ooso/mapper_wrapper/MapperWrapperInfo.java
// public class MapperWrapperInfo {
// private long id;
// private List<ObjectInfoSimple> batch;
// private String mapperLogicInBase64;
// private JobInfo jobInfo;
//
// public MapperWrapperInfo() {
// }
//
// public MapperWrapperInfo(List<ObjectInfoSimple> batch, long id, String mapperLogicInBase64, JobInfo jobInfo) {
// this.batch = batch;
// this.id = id;
// this.mapperLogicInBase64 = mapperLogicInBase64;
// this.jobInfo = jobInfo;
// }
//
// public List<ObjectInfoSimple> getBatch() {
// return batch;
// }
//
// public void setBatch(List<ObjectInfoSimple> batch) {
// this.batch = batch;
// }
//
// public long getId() {
// return id;
// }
//
// public void setId(long id) {
// this.id = id;
// }
//
// public String getMapperLogicInBase64() {
// return mapperLogicInBase64;
// }
//
// public void setMapperLogicInBase64(String mapperLogicInBase64) {
// this.mapperLogicInBase64 = mapperLogicInBase64;
// }
//
// public JobInfo getJobInfo() {
// return jobInfo;
// }
//
// public void setJobInfo(JobInfo jobInfo) {
// this.jobInfo = jobInfo;
// }
// }
//
// Path: ooso/src/main/java/fr/d2si/ooso/mappers_listener/MappersListenerInfo.java
// public class MappersListenerInfo {
// private String reducerInBase64;
// private JobInfo jobInfo;
//
// public MappersListenerInfo() {
// }
//
// public MappersListenerInfo(String reducerInBase64, JobInfo jobInfo) {
// this.reducerInBase64 = reducerInBase64;
// this.jobInfo = jobInfo;
// }
//
// public String getReducerInBase64() {
// return reducerInBase64;
// }
//
// public void setReducerInBase64(String reducerInBase64) {
// this.reducerInBase64 = reducerInBase64;
// }
//
// public JobInfo getJobInfo() {
// return jobInfo;
// }
//
// public void setJobInfo(JobInfo jobInfo) {
// this.jobInfo = jobInfo;
// }
// }
//
// Path: ooso/src/main/java/fr/d2si/ooso/utils/Commons.java
// public final static String IGNORED_RETURN_VALUE = "";
// Path: ooso/src/main/java/fr/d2si/ooso/mappers_driver/MappersDriver.java
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.AmazonS3Exception;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import fr.d2si.ooso.mapper_wrapper.MapperWrapperInfo;
import fr.d2si.ooso.mappers_listener.MappersListenerInfo;
import fr.d2si.ooso.utils.*;
import java.util.List;
import static fr.d2si.ooso.utils.Commons.IGNORED_RETURN_VALUE;
if (!this.s3Client.doesBucketExist(this.jobInfo.getMapperOutputBucket()))
throw new AmazonS3Exception("Bad parameter <mapperOutputBucket>: Bucket does not exist");
if (!this.s3Client.doesBucketExist(this.jobInfo.getReducerOutputBucket()))
throw new AmazonS3Exception("Bad parameter <reducerOutputBucket>: Bucket does not exist");
if (this.jobInfo.getReducerForceBatchSize() == 1)
throw new AmazonS3Exception("Bad parameter <reducerForceBatchSize>: Reducer batch size must be greater or equal than 2");
}
private List<List<ObjectInfoSimple>> getBatches() {
return Commons.getBatches(
this.jobInfo.getJobInputBucket(),
this.jobInfo.getMapperMemory(),
this.jobInfo.getMapperForceBatchSize());
}
private void invokeMappersListener() {
Commons.invokeLambdaAsync(
this.jobInfo.getMappersListenerFunctionName(),
new MappersListenerInfo(
this.mappersDriverInfo.getReducerInBase64(),
this.jobInfo));
}
private void invokeMappers(List<List<ObjectInfoSimple>> batches) {
int currentMapperId = 0;
for (List<ObjectInfoSimple> batch : batches) { | MapperWrapperInfo mapperWrapperInfo = new MapperWrapperInfo( |
AEnterprise/Eureka | src/main/java/eureka/json/JSONChapter.java | // Path: src/main/java/eureka/api/EnumProgressOptions.java
// public enum EnumProgressOptions {
// CRAFTING(true),
// CRAFT_ANYTHING(false),
// BREAK_BLOCK(true),
// BREAK_ANY_BLOCK(false),
// PLACE_BLOCK(true),
// PLACE_ANY_BLOCK(false),
// ENDER_TELEPORT(false),
// KILL_ANYTHING(false),
// DIE(false),
// FILL_BUCKET(false);
//
// private final boolean hasArg;
//
// EnumProgressOptions(boolean hasArg) {
// this.hasArg = hasArg;
// }
//
// public boolean hasArg() {
// return hasArg;
// }
// }
| import java.util.List;
import eureka.api.EnumProgressOptions; | package eureka.json;
/**
* Copyright (c) 2014-2015, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Buildcraft Additions is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class JSONChapter {
public String name, displayStack, category, progressObject;
public List<String> requiredResearch, blockedObjects;
public int maxProgress; | // Path: src/main/java/eureka/api/EnumProgressOptions.java
// public enum EnumProgressOptions {
// CRAFTING(true),
// CRAFT_ANYTHING(false),
// BREAK_BLOCK(true),
// BREAK_ANY_BLOCK(false),
// PLACE_BLOCK(true),
// PLACE_ANY_BLOCK(false),
// ENDER_TELEPORT(false),
// KILL_ANYTHING(false),
// DIE(false),
// FILL_BUCKET(false);
//
// private final boolean hasArg;
//
// EnumProgressOptions(boolean hasArg) {
// this.hasArg = hasArg;
// }
//
// public boolean hasArg() {
// return hasArg;
// }
// }
// Path: src/main/java/eureka/json/JSONChapter.java
import java.util.List;
import eureka.api.EnumProgressOptions;
package eureka.json;
/**
* Copyright (c) 2014-2015, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Buildcraft Additions is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class JSONChapter {
public String name, displayStack, category, progressObject;
public List<String> requiredResearch, blockedObjects;
public int maxProgress; | public EnumProgressOptions progressOption; |
AEnterprise/Eureka | src/main/java/eureka/core/TextGetter.java | // Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
//
// Path: src/main/java/eureka/json/ConfigReader.java
// public class ConfigReader {
// public static File mainfolder, catagoryFolder, keyFolder, localizations;
// private static Gson gson = new GsonBuilder().setPrettyPrinting().create();
//
// public static void read() {
// createFolderIfNeeded(mainfolder);
// if (!mainfolder.exists())
// return;
// catagoryFolder = new File(mainfolder, "Categories");
// keyFolder = new File(mainfolder, "Keys");
// localizations = new File(mainfolder, "Localizations");
// createFolderIfNeeded(catagoryFolder);
// createFolderIfNeeded(keyFolder);
// createFolderIfNeeded(localizations);
// createFolderIfNeeded(new File(localizations, "en_US"));
//
// if (!catagoryFolder.exists())
// return;
//
// for (File file : catagoryFolder.listFiles(new FilenameFilter() {
// @Override
// public boolean accept(File dir, String name) {
// return name.endsWith(".json");
// }
// })) {
// readCategory(file);
// }
// if (!keyFolder.exists())
// return;
// for (File file : keyFolder.listFiles(new FilenameFilter() {
// @Override
// public boolean accept(File dir, String name) {
// return name.endsWith(".json");
// }
// })) {
// readKey(file);
// }
// }
//
// private static void readCategory(File file) {
// try {
// JSONCategory category = gson.fromJson(new FileReader(file), JSONCategory.class);
// EurekaAPI.API.registerCategory(new BasicEurekaCategory(category.name, getStack(category.displayStack)));
// } catch (Throwable t) {
// Logger.error("Failed to read category file (" + file.getName() + ")");
// }
// }
//
// private static void readKey(File file) {
// try {
// JSONChapter chapter = gson.fromJson(new FileReader(file), JSONChapter.class);
// List<ItemStack> objects = new ArrayList<ItemStack>();
// for (String stack : chapter.blockedObjects)
// objects.add(getStack(stack));
// EurekaAPI.API.register(new BasicEurekaInfo(chapter.name, chapter.category, chapter.maxProgress, getStack(chapter.displayStack), chapter.requiredResearch.toArray(new String[100])));
// for (ItemStack stack : objects) {
// EurekaAPI.API.bindToKey(stack, chapter.name);
// }
// if (chapter.progressOption != null) {
// Object obj;
// ItemStack stack = getStack(chapter.progressObject);
// if (stack != null && stack.getItem() instanceof ItemBlock)
// obj = ((ItemBlock) stack.getItem()).field_150939_a;
// else
// obj = stack;
// EurekaAPI.API.registerProgressOption(chapter.name, chapter.progressOption, obj);
// }
// } catch (Throwable t) {
// Logger.error("Failed to read category file (" + file.getName() + ")");
// t.printStackTrace();
// }
// }
//
// private static ItemStack getStack(String name) {
// if (Strings.isNullOrEmpty(name))
// return null;
// int meta = -1;
// if (name.contains("@")) {
// meta = Integer.getInteger(name.split("@")[1]);
// }
// String split[] = name.split(":");
// ItemStack stack = GameRegistry.findItemStack(split[0], split[1], 1);
// if (meta != -1 && stack != null)
// stack.setItemDamage(meta);
// return stack;
// }
//
// private static void createFolderIfNeeded(File folder) {
// try {
// if (!Files.exists(folder.toPath()))
// Files.createDirectory(folder.toPath());
// } catch (Throwable e) {
// Logger.error("Something went wrong while checking or creating the Eureka folders");
// e.printStackTrace();
// }
// }
// }
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import net.minecraft.client.resources.IResource;
import net.minecraft.util.ResourceLocation;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
import eureka.api.EurekaAPI;
import eureka.json.ConfigReader; | package eureka.core;
/**
* Copyright (c) 2014-2015, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Eureka is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class TextGetter {
private static HashMap<String, String> titles = new HashMap<String, String>();
private static HashMap<String, String> descriptions = new HashMap<String, String>();
private static HashMap<String, List<String>> texts = new HashMap<String, List<String>>();
private static HashMap<String, String> progressTexts = new HashMap<String, String>();
public static String getTitle(String key) {
if (FMLCommonHandler.instance().getSide() == Side.SERVER)
return "Unable to localize on the server side";
if (titles.containsKey(key))
return titles.get(key);
getText(key);
if (titles.containsKey(key))
return titles.get(key);
return "ERROR, UNABLE TO FIND LOCALIZATION FILE";
}
public static String getDesc(String key) { | // Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
//
// Path: src/main/java/eureka/json/ConfigReader.java
// public class ConfigReader {
// public static File mainfolder, catagoryFolder, keyFolder, localizations;
// private static Gson gson = new GsonBuilder().setPrettyPrinting().create();
//
// public static void read() {
// createFolderIfNeeded(mainfolder);
// if (!mainfolder.exists())
// return;
// catagoryFolder = new File(mainfolder, "Categories");
// keyFolder = new File(mainfolder, "Keys");
// localizations = new File(mainfolder, "Localizations");
// createFolderIfNeeded(catagoryFolder);
// createFolderIfNeeded(keyFolder);
// createFolderIfNeeded(localizations);
// createFolderIfNeeded(new File(localizations, "en_US"));
//
// if (!catagoryFolder.exists())
// return;
//
// for (File file : catagoryFolder.listFiles(new FilenameFilter() {
// @Override
// public boolean accept(File dir, String name) {
// return name.endsWith(".json");
// }
// })) {
// readCategory(file);
// }
// if (!keyFolder.exists())
// return;
// for (File file : keyFolder.listFiles(new FilenameFilter() {
// @Override
// public boolean accept(File dir, String name) {
// return name.endsWith(".json");
// }
// })) {
// readKey(file);
// }
// }
//
// private static void readCategory(File file) {
// try {
// JSONCategory category = gson.fromJson(new FileReader(file), JSONCategory.class);
// EurekaAPI.API.registerCategory(new BasicEurekaCategory(category.name, getStack(category.displayStack)));
// } catch (Throwable t) {
// Logger.error("Failed to read category file (" + file.getName() + ")");
// }
// }
//
// private static void readKey(File file) {
// try {
// JSONChapter chapter = gson.fromJson(new FileReader(file), JSONChapter.class);
// List<ItemStack> objects = new ArrayList<ItemStack>();
// for (String stack : chapter.blockedObjects)
// objects.add(getStack(stack));
// EurekaAPI.API.register(new BasicEurekaInfo(chapter.name, chapter.category, chapter.maxProgress, getStack(chapter.displayStack), chapter.requiredResearch.toArray(new String[100])));
// for (ItemStack stack : objects) {
// EurekaAPI.API.bindToKey(stack, chapter.name);
// }
// if (chapter.progressOption != null) {
// Object obj;
// ItemStack stack = getStack(chapter.progressObject);
// if (stack != null && stack.getItem() instanceof ItemBlock)
// obj = ((ItemBlock) stack.getItem()).field_150939_a;
// else
// obj = stack;
// EurekaAPI.API.registerProgressOption(chapter.name, chapter.progressOption, obj);
// }
// } catch (Throwable t) {
// Logger.error("Failed to read category file (" + file.getName() + ")");
// t.printStackTrace();
// }
// }
//
// private static ItemStack getStack(String name) {
// if (Strings.isNullOrEmpty(name))
// return null;
// int meta = -1;
// if (name.contains("@")) {
// meta = Integer.getInteger(name.split("@")[1]);
// }
// String split[] = name.split(":");
// ItemStack stack = GameRegistry.findItemStack(split[0], split[1], 1);
// if (meta != -1 && stack != null)
// stack.setItemDamage(meta);
// return stack;
// }
//
// private static void createFolderIfNeeded(File folder) {
// try {
// if (!Files.exists(folder.toPath()))
// Files.createDirectory(folder.toPath());
// } catch (Throwable e) {
// Logger.error("Something went wrong while checking or creating the Eureka folders");
// e.printStackTrace();
// }
// }
// }
// Path: src/main/java/eureka/core/TextGetter.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import net.minecraft.client.resources.IResource;
import net.minecraft.util.ResourceLocation;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
import eureka.api.EurekaAPI;
import eureka.json.ConfigReader;
package eureka.core;
/**
* Copyright (c) 2014-2015, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Eureka is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class TextGetter {
private static HashMap<String, String> titles = new HashMap<String, String>();
private static HashMap<String, String> descriptions = new HashMap<String, String>();
private static HashMap<String, List<String>> texts = new HashMap<String, List<String>>();
private static HashMap<String, String> progressTexts = new HashMap<String, String>();
public static String getTitle(String key) {
if (FMLCommonHandler.instance().getSide() == Side.SERVER)
return "Unable to localize on the server side";
if (titles.containsKey(key))
return titles.get(key);
getText(key);
if (titles.containsKey(key))
return titles.get(key);
return "ERROR, UNABLE TO FIND LOCALIZATION FILE";
}
public static String getDesc(String key) { | if (!EurekaAPI.API.keyRegistered(key)) |
AEnterprise/Eureka | src/main/java/eureka/core/TextGetter.java | // Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
//
// Path: src/main/java/eureka/json/ConfigReader.java
// public class ConfigReader {
// public static File mainfolder, catagoryFolder, keyFolder, localizations;
// private static Gson gson = new GsonBuilder().setPrettyPrinting().create();
//
// public static void read() {
// createFolderIfNeeded(mainfolder);
// if (!mainfolder.exists())
// return;
// catagoryFolder = new File(mainfolder, "Categories");
// keyFolder = new File(mainfolder, "Keys");
// localizations = new File(mainfolder, "Localizations");
// createFolderIfNeeded(catagoryFolder);
// createFolderIfNeeded(keyFolder);
// createFolderIfNeeded(localizations);
// createFolderIfNeeded(new File(localizations, "en_US"));
//
// if (!catagoryFolder.exists())
// return;
//
// for (File file : catagoryFolder.listFiles(new FilenameFilter() {
// @Override
// public boolean accept(File dir, String name) {
// return name.endsWith(".json");
// }
// })) {
// readCategory(file);
// }
// if (!keyFolder.exists())
// return;
// for (File file : keyFolder.listFiles(new FilenameFilter() {
// @Override
// public boolean accept(File dir, String name) {
// return name.endsWith(".json");
// }
// })) {
// readKey(file);
// }
// }
//
// private static void readCategory(File file) {
// try {
// JSONCategory category = gson.fromJson(new FileReader(file), JSONCategory.class);
// EurekaAPI.API.registerCategory(new BasicEurekaCategory(category.name, getStack(category.displayStack)));
// } catch (Throwable t) {
// Logger.error("Failed to read category file (" + file.getName() + ")");
// }
// }
//
// private static void readKey(File file) {
// try {
// JSONChapter chapter = gson.fromJson(new FileReader(file), JSONChapter.class);
// List<ItemStack> objects = new ArrayList<ItemStack>();
// for (String stack : chapter.blockedObjects)
// objects.add(getStack(stack));
// EurekaAPI.API.register(new BasicEurekaInfo(chapter.name, chapter.category, chapter.maxProgress, getStack(chapter.displayStack), chapter.requiredResearch.toArray(new String[100])));
// for (ItemStack stack : objects) {
// EurekaAPI.API.bindToKey(stack, chapter.name);
// }
// if (chapter.progressOption != null) {
// Object obj;
// ItemStack stack = getStack(chapter.progressObject);
// if (stack != null && stack.getItem() instanceof ItemBlock)
// obj = ((ItemBlock) stack.getItem()).field_150939_a;
// else
// obj = stack;
// EurekaAPI.API.registerProgressOption(chapter.name, chapter.progressOption, obj);
// }
// } catch (Throwable t) {
// Logger.error("Failed to read category file (" + file.getName() + ")");
// t.printStackTrace();
// }
// }
//
// private static ItemStack getStack(String name) {
// if (Strings.isNullOrEmpty(name))
// return null;
// int meta = -1;
// if (name.contains("@")) {
// meta = Integer.getInteger(name.split("@")[1]);
// }
// String split[] = name.split(":");
// ItemStack stack = GameRegistry.findItemStack(split[0], split[1], 1);
// if (meta != -1 && stack != null)
// stack.setItemDamage(meta);
// return stack;
// }
//
// private static void createFolderIfNeeded(File folder) {
// try {
// if (!Files.exists(folder.toPath()))
// Files.createDirectory(folder.toPath());
// } catch (Throwable e) {
// Logger.error("Something went wrong while checking or creating the Eureka folders");
// e.printStackTrace();
// }
// }
// }
| import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import net.minecraft.client.resources.IResource;
import net.minecraft.util.ResourceLocation;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
import eureka.api.EurekaAPI;
import eureka.json.ConfigReader; | if (!EurekaAPI.API.keyRegistered(key))
return "";
if (progressTexts.containsKey(key))
return progressTexts.get(key);
getText(key);
if (progressTexts.containsKey(key))
return progressTexts.get(key);
return "";
}
public static List<String> getText(String key) {
if (texts.containsKey(key))
return texts.get(key);
else
getText(key, FMLClientHandler.instance().getCurrentLanguage(), !EurekaAPI.API.keyRegistered(key), true);
getText(key, FMLClientHandler.instance().getCurrentLanguage(), !EurekaAPI.API.keyRegistered(key), false);
return texts.get(key);
}
private static void getText(String key, String lang, boolean category, boolean configFolder) {
List<String> list = new ArrayList<String>();
InputStream stream = null;
ResourceLocation location = new ResourceLocation("eureka:localizations/" + lang + "/" + key + ".txt");
try {
BufferedReader reader;
if (!configFolder) {
IResource resource = FMLClientHandler.instance().getClient().getResourceManager().getResource(location);
stream = resource.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
} else { | // Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
//
// Path: src/main/java/eureka/json/ConfigReader.java
// public class ConfigReader {
// public static File mainfolder, catagoryFolder, keyFolder, localizations;
// private static Gson gson = new GsonBuilder().setPrettyPrinting().create();
//
// public static void read() {
// createFolderIfNeeded(mainfolder);
// if (!mainfolder.exists())
// return;
// catagoryFolder = new File(mainfolder, "Categories");
// keyFolder = new File(mainfolder, "Keys");
// localizations = new File(mainfolder, "Localizations");
// createFolderIfNeeded(catagoryFolder);
// createFolderIfNeeded(keyFolder);
// createFolderIfNeeded(localizations);
// createFolderIfNeeded(new File(localizations, "en_US"));
//
// if (!catagoryFolder.exists())
// return;
//
// for (File file : catagoryFolder.listFiles(new FilenameFilter() {
// @Override
// public boolean accept(File dir, String name) {
// return name.endsWith(".json");
// }
// })) {
// readCategory(file);
// }
// if (!keyFolder.exists())
// return;
// for (File file : keyFolder.listFiles(new FilenameFilter() {
// @Override
// public boolean accept(File dir, String name) {
// return name.endsWith(".json");
// }
// })) {
// readKey(file);
// }
// }
//
// private static void readCategory(File file) {
// try {
// JSONCategory category = gson.fromJson(new FileReader(file), JSONCategory.class);
// EurekaAPI.API.registerCategory(new BasicEurekaCategory(category.name, getStack(category.displayStack)));
// } catch (Throwable t) {
// Logger.error("Failed to read category file (" + file.getName() + ")");
// }
// }
//
// private static void readKey(File file) {
// try {
// JSONChapter chapter = gson.fromJson(new FileReader(file), JSONChapter.class);
// List<ItemStack> objects = new ArrayList<ItemStack>();
// for (String stack : chapter.blockedObjects)
// objects.add(getStack(stack));
// EurekaAPI.API.register(new BasicEurekaInfo(chapter.name, chapter.category, chapter.maxProgress, getStack(chapter.displayStack), chapter.requiredResearch.toArray(new String[100])));
// for (ItemStack stack : objects) {
// EurekaAPI.API.bindToKey(stack, chapter.name);
// }
// if (chapter.progressOption != null) {
// Object obj;
// ItemStack stack = getStack(chapter.progressObject);
// if (stack != null && stack.getItem() instanceof ItemBlock)
// obj = ((ItemBlock) stack.getItem()).field_150939_a;
// else
// obj = stack;
// EurekaAPI.API.registerProgressOption(chapter.name, chapter.progressOption, obj);
// }
// } catch (Throwable t) {
// Logger.error("Failed to read category file (" + file.getName() + ")");
// t.printStackTrace();
// }
// }
//
// private static ItemStack getStack(String name) {
// if (Strings.isNullOrEmpty(name))
// return null;
// int meta = -1;
// if (name.contains("@")) {
// meta = Integer.getInteger(name.split("@")[1]);
// }
// String split[] = name.split(":");
// ItemStack stack = GameRegistry.findItemStack(split[0], split[1], 1);
// if (meta != -1 && stack != null)
// stack.setItemDamage(meta);
// return stack;
// }
//
// private static void createFolderIfNeeded(File folder) {
// try {
// if (!Files.exists(folder.toPath()))
// Files.createDirectory(folder.toPath());
// } catch (Throwable e) {
// Logger.error("Something went wrong while checking or creating the Eureka folders");
// e.printStackTrace();
// }
// }
// }
// Path: src/main/java/eureka/core/TextGetter.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import net.minecraft.client.resources.IResource;
import net.minecraft.util.ResourceLocation;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
import eureka.api.EurekaAPI;
import eureka.json.ConfigReader;
if (!EurekaAPI.API.keyRegistered(key))
return "";
if (progressTexts.containsKey(key))
return progressTexts.get(key);
getText(key);
if (progressTexts.containsKey(key))
return progressTexts.get(key);
return "";
}
public static List<String> getText(String key) {
if (texts.containsKey(key))
return texts.get(key);
else
getText(key, FMLClientHandler.instance().getCurrentLanguage(), !EurekaAPI.API.keyRegistered(key), true);
getText(key, FMLClientHandler.instance().getCurrentLanguage(), !EurekaAPI.API.keyRegistered(key), false);
return texts.get(key);
}
private static void getText(String key, String lang, boolean category, boolean configFolder) {
List<String> list = new ArrayList<String>();
InputStream stream = null;
ResourceLocation location = new ResourceLocation("eureka:localizations/" + lang + "/" + key + ".txt");
try {
BufferedReader reader;
if (!configFolder) {
IResource resource = FMLClientHandler.instance().getClient().getResourceManager().getResource(location);
stream = resource.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
} else { | reader = new BufferedReader(new FileReader(new File(new File(ConfigReader.localizations, lang), key + ".txt"))); |
AEnterprise/Eureka | src/main/java/eureka/core/EurekaCommand.java | // Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
//
// Path: src/main/java/eureka/api/IEurekaInfo.java
// public interface IEurekaInfo {
//
// String getCategory();
//
// int getMaxProgress();
//
// ItemStack getDisplayStack();
//
// String getName();
//
// List<String> getRequiredResearch();
// }
| import java.util.ArrayList;
import java.util.List;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.WrongUsageException;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ChatComponentText;
import eureka.api.EurekaAPI;
import eureka.api.IEurekaInfo; | package eureka.core;
/**
* Copyright (c) 2014-2015, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Eureka is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class EurekaCommand extends CommandBase {
@Override
public String getCommandName() {
return "eureka";
}
@Override
public String getCommandUsage(ICommandSender sender) {
return "type '/eureka help' for possible commands and syntax";
}
@Override
public void processCommand(ICommandSender sender, String[] args) {
if (args == null || args.length == 0) {
sender.addChatMessage(new ChatComponentText(getCommandUsage(sender)));
return;
}
if (args[0].equalsIgnoreCase("help")) {
sender.addChatMessage(new ChatComponentText("Eureka Command help:"));
sender.addChatMessage(new ChatComponentText("/eureka lock <playername> <key> : locks the research identified by the key for the specified player"));
sender.addChatMessage(new ChatComponentText("/eureka unlock <playername> <key> : unlocks the research identified by the key for the specified player"));
sender.addChatMessage(new ChatComponentText("/eureka keylist : lists all registered keys and there localized titles"));
return;
}
if (args[0].equalsIgnoreCase("keylist")) { | // Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
//
// Path: src/main/java/eureka/api/IEurekaInfo.java
// public interface IEurekaInfo {
//
// String getCategory();
//
// int getMaxProgress();
//
// ItemStack getDisplayStack();
//
// String getName();
//
// List<String> getRequiredResearch();
// }
// Path: src/main/java/eureka/core/EurekaCommand.java
import java.util.ArrayList;
import java.util.List;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.WrongUsageException;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ChatComponentText;
import eureka.api.EurekaAPI;
import eureka.api.IEurekaInfo;
package eureka.core;
/**
* Copyright (c) 2014-2015, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Eureka is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class EurekaCommand extends CommandBase {
@Override
public String getCommandName() {
return "eureka";
}
@Override
public String getCommandUsage(ICommandSender sender) {
return "type '/eureka help' for possible commands and syntax";
}
@Override
public void processCommand(ICommandSender sender, String[] args) {
if (args == null || args.length == 0) {
sender.addChatMessage(new ChatComponentText(getCommandUsage(sender)));
return;
}
if (args[0].equalsIgnoreCase("help")) {
sender.addChatMessage(new ChatComponentText("Eureka Command help:"));
sender.addChatMessage(new ChatComponentText("/eureka lock <playername> <key> : locks the research identified by the key for the specified player"));
sender.addChatMessage(new ChatComponentText("/eureka unlock <playername> <key> : unlocks the research identified by the key for the specified player"));
sender.addChatMessage(new ChatComponentText("/eureka keylist : lists all registered keys and there localized titles"));
return;
}
if (args[0].equalsIgnoreCase("keylist")) { | for (IEurekaInfo info : EurekaAPI.API.getAllKeys()) { |
AEnterprise/Eureka | src/main/java/eureka/core/EurekaCommand.java | // Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
//
// Path: src/main/java/eureka/api/IEurekaInfo.java
// public interface IEurekaInfo {
//
// String getCategory();
//
// int getMaxProgress();
//
// ItemStack getDisplayStack();
//
// String getName();
//
// List<String> getRequiredResearch();
// }
| import java.util.ArrayList;
import java.util.List;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.WrongUsageException;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ChatComponentText;
import eureka.api.EurekaAPI;
import eureka.api.IEurekaInfo; | package eureka.core;
/**
* Copyright (c) 2014-2015, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Eureka is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class EurekaCommand extends CommandBase {
@Override
public String getCommandName() {
return "eureka";
}
@Override
public String getCommandUsage(ICommandSender sender) {
return "type '/eureka help' for possible commands and syntax";
}
@Override
public void processCommand(ICommandSender sender, String[] args) {
if (args == null || args.length == 0) {
sender.addChatMessage(new ChatComponentText(getCommandUsage(sender)));
return;
}
if (args[0].equalsIgnoreCase("help")) {
sender.addChatMessage(new ChatComponentText("Eureka Command help:"));
sender.addChatMessage(new ChatComponentText("/eureka lock <playername> <key> : locks the research identified by the key for the specified player"));
sender.addChatMessage(new ChatComponentText("/eureka unlock <playername> <key> : unlocks the research identified by the key for the specified player"));
sender.addChatMessage(new ChatComponentText("/eureka keylist : lists all registered keys and there localized titles"));
return;
}
if (args[0].equalsIgnoreCase("keylist")) { | // Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
//
// Path: src/main/java/eureka/api/IEurekaInfo.java
// public interface IEurekaInfo {
//
// String getCategory();
//
// int getMaxProgress();
//
// ItemStack getDisplayStack();
//
// String getName();
//
// List<String> getRequiredResearch();
// }
// Path: src/main/java/eureka/core/EurekaCommand.java
import java.util.ArrayList;
import java.util.List;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.WrongUsageException;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ChatComponentText;
import eureka.api.EurekaAPI;
import eureka.api.IEurekaInfo;
package eureka.core;
/**
* Copyright (c) 2014-2015, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Eureka is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class EurekaCommand extends CommandBase {
@Override
public String getCommandName() {
return "eureka";
}
@Override
public String getCommandUsage(ICommandSender sender) {
return "type '/eureka help' for possible commands and syntax";
}
@Override
public void processCommand(ICommandSender sender, String[] args) {
if (args == null || args.length == 0) {
sender.addChatMessage(new ChatComponentText(getCommandUsage(sender)));
return;
}
if (args[0].equalsIgnoreCase("help")) {
sender.addChatMessage(new ChatComponentText("Eureka Command help:"));
sender.addChatMessage(new ChatComponentText("/eureka lock <playername> <key> : locks the research identified by the key for the specified player"));
sender.addChatMessage(new ChatComponentText("/eureka unlock <playername> <key> : unlocks the research identified by the key for the specified player"));
sender.addChatMessage(new ChatComponentText("/eureka keylist : lists all registered keys and there localized titles"));
return;
}
if (args[0].equalsIgnoreCase("keylist")) { | for (IEurekaInfo info : EurekaAPI.API.getAllKeys()) { |
AEnterprise/Eureka | src/main/java/eureka/items/ItemEngineeringDiary.java | // Path: src/main/java/eureka/Eureka.java
// @Mod(modid = "eureka", name = "Eureka", version = "@MODVERSION@", acceptedMinecraftVersions = "1.7.10")
// public class Eureka {
//
// @Mod.Instance("eureka")
// public static Eureka instance;
//
// @SidedProxy(clientSide = "eureka.proxy.ClientProxy", serverSide = "eureka.proxy.ServerProxy")
// public static IProxy proxy;
// public static ItemEngineeringDiary engineeringDiary;
// public static CreativeTabs eureka = new CreativeTabs("Eureka") {
//
// @Override
// public Item getTabIconItem() {
// return engineeringDiary;
// }
//
// };
//
// public static boolean giveBook;
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// EurekaAPI.API = new EurekaAPIImplementation();
// engineeringDiary = new ItemEngineeringDiary();
// GameRegistry.registerItem(engineeringDiary, "engineeringDiary");
// GameRegistry.addShapelessRecipe(new ItemStack(engineeringDiary), new Object[]{Items.book, Items.iron_ingot});
// MinecraftForge.EVENT_BUS.register(new EventHandler());
// FMLCommonHandler.instance().bus().register(new EventHandler());
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// EurekaAPI.API.registerCategory(new BasicEurekaCategory("Eureka", new ItemStack(engineeringDiary)));
// PacketHandler.init();
// ConfigReader.mainfolder = new File(event.getModConfigurationDirectory(), "Eureka");
// ConfigReader.read();
// Configuration config = new Configuration(event.getSuggestedConfigurationFile());
// giveBook = config.get("General", "giveBook", true).setDefaultValue(true).getBoolean();
// config.save();
// }
//
// @Mod.EventHandler
// public void serverStart(FMLServerStartingEvent event) {
// event.registerServerCommand(new EurekaCommand());
// }
//
// }
//
// Path: src/main/java/eureka/networking/MessageResearch.java
// public class MessageResearch implements IMessage, IMessageHandler<MessageResearch, IMessage> {
// public PlayerResearch research;
// public HashMap<String, Integer> progress = new HashMap<String, Integer>();
// public HashMap<String, Boolean> finished = new HashMap<String, Boolean>();
//
// public MessageResearch() {
//
// }
//
// public MessageResearch(EntityPlayer player) {
// research = PlayerResearch.get(player);
// }
//
// @Override
// public void fromBytes(ByteBuf buf) {
// for (IEurekaInfo info : EurekaAPI.API.getAllKeys()) {
// progress.put(info.getName(), buf.readInt());
// finished.put(info.getName(), buf.readBoolean());
// }
// }
//
// @Override
// public void toBytes(ByteBuf buf) {
// for (IEurekaInfo info : EurekaAPI.API.getAllKeys()) {
// buf.writeInt(research.getProgress(info.getName()));
// buf.writeBoolean(research.isFinished(info.getName()));
// }
// }
//
// @Override
// public IMessage onMessage(MessageResearch message, MessageContext ctx) {
// research = PlayerResearch.get(Eureka.proxy.getPlayer());
// for (IEurekaInfo info : EurekaAPI.API.getAllKeys()) {
// research.overrideProgress(info.getName(), message.progress.get(info.getName()));
// research.overrideFinished(info.getName(), message.finished.get(info.getName()));
// }
// return null;
// }
// }
//
// Path: src/main/java/eureka/networking/PacketHandler.java
// public class PacketHandler {
//
// public static final SimpleNetworkWrapper instance = NetworkRegistry.INSTANCE.newSimpleChannel("eureka");
//
// public static void init() {
// instance.registerMessage(MessageResearch.class, MessageResearch.class, 0, Side.CLIENT);
// instance.registerMessage(MessageResearchFinished.class, MessageResearchFinished.class, 1, Side.CLIENT);
// instance.registerMessage(MessageBookSave.class, MessageBookSave.class, 2, Side.SERVER);
// }
// }
| import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemBook;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.relauncher.Side;
import eureka.Eureka;
import eureka.networking.MessageResearch;
import eureka.networking.PacketHandler; | package eureka.items;
/**
* Copyright (c) 2014-2015, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Eureka is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class ItemEngineeringDiary extends ItemBook {
public ItemEngineeringDiary() { | // Path: src/main/java/eureka/Eureka.java
// @Mod(modid = "eureka", name = "Eureka", version = "@MODVERSION@", acceptedMinecraftVersions = "1.7.10")
// public class Eureka {
//
// @Mod.Instance("eureka")
// public static Eureka instance;
//
// @SidedProxy(clientSide = "eureka.proxy.ClientProxy", serverSide = "eureka.proxy.ServerProxy")
// public static IProxy proxy;
// public static ItemEngineeringDiary engineeringDiary;
// public static CreativeTabs eureka = new CreativeTabs("Eureka") {
//
// @Override
// public Item getTabIconItem() {
// return engineeringDiary;
// }
//
// };
//
// public static boolean giveBook;
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// EurekaAPI.API = new EurekaAPIImplementation();
// engineeringDiary = new ItemEngineeringDiary();
// GameRegistry.registerItem(engineeringDiary, "engineeringDiary");
// GameRegistry.addShapelessRecipe(new ItemStack(engineeringDiary), new Object[]{Items.book, Items.iron_ingot});
// MinecraftForge.EVENT_BUS.register(new EventHandler());
// FMLCommonHandler.instance().bus().register(new EventHandler());
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// EurekaAPI.API.registerCategory(new BasicEurekaCategory("Eureka", new ItemStack(engineeringDiary)));
// PacketHandler.init();
// ConfigReader.mainfolder = new File(event.getModConfigurationDirectory(), "Eureka");
// ConfigReader.read();
// Configuration config = new Configuration(event.getSuggestedConfigurationFile());
// giveBook = config.get("General", "giveBook", true).setDefaultValue(true).getBoolean();
// config.save();
// }
//
// @Mod.EventHandler
// public void serverStart(FMLServerStartingEvent event) {
// event.registerServerCommand(new EurekaCommand());
// }
//
// }
//
// Path: src/main/java/eureka/networking/MessageResearch.java
// public class MessageResearch implements IMessage, IMessageHandler<MessageResearch, IMessage> {
// public PlayerResearch research;
// public HashMap<String, Integer> progress = new HashMap<String, Integer>();
// public HashMap<String, Boolean> finished = new HashMap<String, Boolean>();
//
// public MessageResearch() {
//
// }
//
// public MessageResearch(EntityPlayer player) {
// research = PlayerResearch.get(player);
// }
//
// @Override
// public void fromBytes(ByteBuf buf) {
// for (IEurekaInfo info : EurekaAPI.API.getAllKeys()) {
// progress.put(info.getName(), buf.readInt());
// finished.put(info.getName(), buf.readBoolean());
// }
// }
//
// @Override
// public void toBytes(ByteBuf buf) {
// for (IEurekaInfo info : EurekaAPI.API.getAllKeys()) {
// buf.writeInt(research.getProgress(info.getName()));
// buf.writeBoolean(research.isFinished(info.getName()));
// }
// }
//
// @Override
// public IMessage onMessage(MessageResearch message, MessageContext ctx) {
// research = PlayerResearch.get(Eureka.proxy.getPlayer());
// for (IEurekaInfo info : EurekaAPI.API.getAllKeys()) {
// research.overrideProgress(info.getName(), message.progress.get(info.getName()));
// research.overrideFinished(info.getName(), message.finished.get(info.getName()));
// }
// return null;
// }
// }
//
// Path: src/main/java/eureka/networking/PacketHandler.java
// public class PacketHandler {
//
// public static final SimpleNetworkWrapper instance = NetworkRegistry.INSTANCE.newSimpleChannel("eureka");
//
// public static void init() {
// instance.registerMessage(MessageResearch.class, MessageResearch.class, 0, Side.CLIENT);
// instance.registerMessage(MessageResearchFinished.class, MessageResearchFinished.class, 1, Side.CLIENT);
// instance.registerMessage(MessageBookSave.class, MessageBookSave.class, 2, Side.SERVER);
// }
// }
// Path: src/main/java/eureka/items/ItemEngineeringDiary.java
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemBook;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.relauncher.Side;
import eureka.Eureka;
import eureka.networking.MessageResearch;
import eureka.networking.PacketHandler;
package eureka.items;
/**
* Copyright (c) 2014-2015, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Eureka is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class ItemEngineeringDiary extends ItemBook {
public ItemEngineeringDiary() { | setCreativeTab(Eureka.eureka); |
AEnterprise/Eureka | src/main/java/eureka/items/ItemEngineeringDiary.java | // Path: src/main/java/eureka/Eureka.java
// @Mod(modid = "eureka", name = "Eureka", version = "@MODVERSION@", acceptedMinecraftVersions = "1.7.10")
// public class Eureka {
//
// @Mod.Instance("eureka")
// public static Eureka instance;
//
// @SidedProxy(clientSide = "eureka.proxy.ClientProxy", serverSide = "eureka.proxy.ServerProxy")
// public static IProxy proxy;
// public static ItemEngineeringDiary engineeringDiary;
// public static CreativeTabs eureka = new CreativeTabs("Eureka") {
//
// @Override
// public Item getTabIconItem() {
// return engineeringDiary;
// }
//
// };
//
// public static boolean giveBook;
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// EurekaAPI.API = new EurekaAPIImplementation();
// engineeringDiary = new ItemEngineeringDiary();
// GameRegistry.registerItem(engineeringDiary, "engineeringDiary");
// GameRegistry.addShapelessRecipe(new ItemStack(engineeringDiary), new Object[]{Items.book, Items.iron_ingot});
// MinecraftForge.EVENT_BUS.register(new EventHandler());
// FMLCommonHandler.instance().bus().register(new EventHandler());
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// EurekaAPI.API.registerCategory(new BasicEurekaCategory("Eureka", new ItemStack(engineeringDiary)));
// PacketHandler.init();
// ConfigReader.mainfolder = new File(event.getModConfigurationDirectory(), "Eureka");
// ConfigReader.read();
// Configuration config = new Configuration(event.getSuggestedConfigurationFile());
// giveBook = config.get("General", "giveBook", true).setDefaultValue(true).getBoolean();
// config.save();
// }
//
// @Mod.EventHandler
// public void serverStart(FMLServerStartingEvent event) {
// event.registerServerCommand(new EurekaCommand());
// }
//
// }
//
// Path: src/main/java/eureka/networking/MessageResearch.java
// public class MessageResearch implements IMessage, IMessageHandler<MessageResearch, IMessage> {
// public PlayerResearch research;
// public HashMap<String, Integer> progress = new HashMap<String, Integer>();
// public HashMap<String, Boolean> finished = new HashMap<String, Boolean>();
//
// public MessageResearch() {
//
// }
//
// public MessageResearch(EntityPlayer player) {
// research = PlayerResearch.get(player);
// }
//
// @Override
// public void fromBytes(ByteBuf buf) {
// for (IEurekaInfo info : EurekaAPI.API.getAllKeys()) {
// progress.put(info.getName(), buf.readInt());
// finished.put(info.getName(), buf.readBoolean());
// }
// }
//
// @Override
// public void toBytes(ByteBuf buf) {
// for (IEurekaInfo info : EurekaAPI.API.getAllKeys()) {
// buf.writeInt(research.getProgress(info.getName()));
// buf.writeBoolean(research.isFinished(info.getName()));
// }
// }
//
// @Override
// public IMessage onMessage(MessageResearch message, MessageContext ctx) {
// research = PlayerResearch.get(Eureka.proxy.getPlayer());
// for (IEurekaInfo info : EurekaAPI.API.getAllKeys()) {
// research.overrideProgress(info.getName(), message.progress.get(info.getName()));
// research.overrideFinished(info.getName(), message.finished.get(info.getName()));
// }
// return null;
// }
// }
//
// Path: src/main/java/eureka/networking/PacketHandler.java
// public class PacketHandler {
//
// public static final SimpleNetworkWrapper instance = NetworkRegistry.INSTANCE.newSimpleChannel("eureka");
//
// public static void init() {
// instance.registerMessage(MessageResearch.class, MessageResearch.class, 0, Side.CLIENT);
// instance.registerMessage(MessageResearchFinished.class, MessageResearchFinished.class, 1, Side.CLIENT);
// instance.registerMessage(MessageBookSave.class, MessageBookSave.class, 2, Side.SERVER);
// }
// }
| import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemBook;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.relauncher.Side;
import eureka.Eureka;
import eureka.networking.MessageResearch;
import eureka.networking.PacketHandler; | package eureka.items;
/**
* Copyright (c) 2014-2015, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Eureka is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class ItemEngineeringDiary extends ItemBook {
public ItemEngineeringDiary() {
setCreativeTab(Eureka.eureka);
setTextureName("eureka:engineeringDiary");
setUnlocalizedName("engineeringDiary");
}
@Override
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) {
if (FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER) | // Path: src/main/java/eureka/Eureka.java
// @Mod(modid = "eureka", name = "Eureka", version = "@MODVERSION@", acceptedMinecraftVersions = "1.7.10")
// public class Eureka {
//
// @Mod.Instance("eureka")
// public static Eureka instance;
//
// @SidedProxy(clientSide = "eureka.proxy.ClientProxy", serverSide = "eureka.proxy.ServerProxy")
// public static IProxy proxy;
// public static ItemEngineeringDiary engineeringDiary;
// public static CreativeTabs eureka = new CreativeTabs("Eureka") {
//
// @Override
// public Item getTabIconItem() {
// return engineeringDiary;
// }
//
// };
//
// public static boolean giveBook;
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// EurekaAPI.API = new EurekaAPIImplementation();
// engineeringDiary = new ItemEngineeringDiary();
// GameRegistry.registerItem(engineeringDiary, "engineeringDiary");
// GameRegistry.addShapelessRecipe(new ItemStack(engineeringDiary), new Object[]{Items.book, Items.iron_ingot});
// MinecraftForge.EVENT_BUS.register(new EventHandler());
// FMLCommonHandler.instance().bus().register(new EventHandler());
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// EurekaAPI.API.registerCategory(new BasicEurekaCategory("Eureka", new ItemStack(engineeringDiary)));
// PacketHandler.init();
// ConfigReader.mainfolder = new File(event.getModConfigurationDirectory(), "Eureka");
// ConfigReader.read();
// Configuration config = new Configuration(event.getSuggestedConfigurationFile());
// giveBook = config.get("General", "giveBook", true).setDefaultValue(true).getBoolean();
// config.save();
// }
//
// @Mod.EventHandler
// public void serverStart(FMLServerStartingEvent event) {
// event.registerServerCommand(new EurekaCommand());
// }
//
// }
//
// Path: src/main/java/eureka/networking/MessageResearch.java
// public class MessageResearch implements IMessage, IMessageHandler<MessageResearch, IMessage> {
// public PlayerResearch research;
// public HashMap<String, Integer> progress = new HashMap<String, Integer>();
// public HashMap<String, Boolean> finished = new HashMap<String, Boolean>();
//
// public MessageResearch() {
//
// }
//
// public MessageResearch(EntityPlayer player) {
// research = PlayerResearch.get(player);
// }
//
// @Override
// public void fromBytes(ByteBuf buf) {
// for (IEurekaInfo info : EurekaAPI.API.getAllKeys()) {
// progress.put(info.getName(), buf.readInt());
// finished.put(info.getName(), buf.readBoolean());
// }
// }
//
// @Override
// public void toBytes(ByteBuf buf) {
// for (IEurekaInfo info : EurekaAPI.API.getAllKeys()) {
// buf.writeInt(research.getProgress(info.getName()));
// buf.writeBoolean(research.isFinished(info.getName()));
// }
// }
//
// @Override
// public IMessage onMessage(MessageResearch message, MessageContext ctx) {
// research = PlayerResearch.get(Eureka.proxy.getPlayer());
// for (IEurekaInfo info : EurekaAPI.API.getAllKeys()) {
// research.overrideProgress(info.getName(), message.progress.get(info.getName()));
// research.overrideFinished(info.getName(), message.finished.get(info.getName()));
// }
// return null;
// }
// }
//
// Path: src/main/java/eureka/networking/PacketHandler.java
// public class PacketHandler {
//
// public static final SimpleNetworkWrapper instance = NetworkRegistry.INSTANCE.newSimpleChannel("eureka");
//
// public static void init() {
// instance.registerMessage(MessageResearch.class, MessageResearch.class, 0, Side.CLIENT);
// instance.registerMessage(MessageResearchFinished.class, MessageResearchFinished.class, 1, Side.CLIENT);
// instance.registerMessage(MessageBookSave.class, MessageBookSave.class, 2, Side.SERVER);
// }
// }
// Path: src/main/java/eureka/items/ItemEngineeringDiary.java
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemBook;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.relauncher.Side;
import eureka.Eureka;
import eureka.networking.MessageResearch;
import eureka.networking.PacketHandler;
package eureka.items;
/**
* Copyright (c) 2014-2015, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Eureka is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class ItemEngineeringDiary extends ItemBook {
public ItemEngineeringDiary() {
setCreativeTab(Eureka.eureka);
setTextureName("eureka:engineeringDiary");
setUnlocalizedName("engineeringDiary");
}
@Override
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) {
if (FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER) | PacketHandler.instance.sendToAllAround(new MessageResearch(player), new NetworkRegistry.TargetPoint(player.dimension, player.posX, player.posY, player.posZ, 1)); |
AEnterprise/Eureka | src/main/java/eureka/items/ItemEngineeringDiary.java | // Path: src/main/java/eureka/Eureka.java
// @Mod(modid = "eureka", name = "Eureka", version = "@MODVERSION@", acceptedMinecraftVersions = "1.7.10")
// public class Eureka {
//
// @Mod.Instance("eureka")
// public static Eureka instance;
//
// @SidedProxy(clientSide = "eureka.proxy.ClientProxy", serverSide = "eureka.proxy.ServerProxy")
// public static IProxy proxy;
// public static ItemEngineeringDiary engineeringDiary;
// public static CreativeTabs eureka = new CreativeTabs("Eureka") {
//
// @Override
// public Item getTabIconItem() {
// return engineeringDiary;
// }
//
// };
//
// public static boolean giveBook;
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// EurekaAPI.API = new EurekaAPIImplementation();
// engineeringDiary = new ItemEngineeringDiary();
// GameRegistry.registerItem(engineeringDiary, "engineeringDiary");
// GameRegistry.addShapelessRecipe(new ItemStack(engineeringDiary), new Object[]{Items.book, Items.iron_ingot});
// MinecraftForge.EVENT_BUS.register(new EventHandler());
// FMLCommonHandler.instance().bus().register(new EventHandler());
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// EurekaAPI.API.registerCategory(new BasicEurekaCategory("Eureka", new ItemStack(engineeringDiary)));
// PacketHandler.init();
// ConfigReader.mainfolder = new File(event.getModConfigurationDirectory(), "Eureka");
// ConfigReader.read();
// Configuration config = new Configuration(event.getSuggestedConfigurationFile());
// giveBook = config.get("General", "giveBook", true).setDefaultValue(true).getBoolean();
// config.save();
// }
//
// @Mod.EventHandler
// public void serverStart(FMLServerStartingEvent event) {
// event.registerServerCommand(new EurekaCommand());
// }
//
// }
//
// Path: src/main/java/eureka/networking/MessageResearch.java
// public class MessageResearch implements IMessage, IMessageHandler<MessageResearch, IMessage> {
// public PlayerResearch research;
// public HashMap<String, Integer> progress = new HashMap<String, Integer>();
// public HashMap<String, Boolean> finished = new HashMap<String, Boolean>();
//
// public MessageResearch() {
//
// }
//
// public MessageResearch(EntityPlayer player) {
// research = PlayerResearch.get(player);
// }
//
// @Override
// public void fromBytes(ByteBuf buf) {
// for (IEurekaInfo info : EurekaAPI.API.getAllKeys()) {
// progress.put(info.getName(), buf.readInt());
// finished.put(info.getName(), buf.readBoolean());
// }
// }
//
// @Override
// public void toBytes(ByteBuf buf) {
// for (IEurekaInfo info : EurekaAPI.API.getAllKeys()) {
// buf.writeInt(research.getProgress(info.getName()));
// buf.writeBoolean(research.isFinished(info.getName()));
// }
// }
//
// @Override
// public IMessage onMessage(MessageResearch message, MessageContext ctx) {
// research = PlayerResearch.get(Eureka.proxy.getPlayer());
// for (IEurekaInfo info : EurekaAPI.API.getAllKeys()) {
// research.overrideProgress(info.getName(), message.progress.get(info.getName()));
// research.overrideFinished(info.getName(), message.finished.get(info.getName()));
// }
// return null;
// }
// }
//
// Path: src/main/java/eureka/networking/PacketHandler.java
// public class PacketHandler {
//
// public static final SimpleNetworkWrapper instance = NetworkRegistry.INSTANCE.newSimpleChannel("eureka");
//
// public static void init() {
// instance.registerMessage(MessageResearch.class, MessageResearch.class, 0, Side.CLIENT);
// instance.registerMessage(MessageResearchFinished.class, MessageResearchFinished.class, 1, Side.CLIENT);
// instance.registerMessage(MessageBookSave.class, MessageBookSave.class, 2, Side.SERVER);
// }
// }
| import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemBook;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.relauncher.Side;
import eureka.Eureka;
import eureka.networking.MessageResearch;
import eureka.networking.PacketHandler; | package eureka.items;
/**
* Copyright (c) 2014-2015, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Eureka is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class ItemEngineeringDiary extends ItemBook {
public ItemEngineeringDiary() {
setCreativeTab(Eureka.eureka);
setTextureName("eureka:engineeringDiary");
setUnlocalizedName("engineeringDiary");
}
@Override
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) {
if (FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER) | // Path: src/main/java/eureka/Eureka.java
// @Mod(modid = "eureka", name = "Eureka", version = "@MODVERSION@", acceptedMinecraftVersions = "1.7.10")
// public class Eureka {
//
// @Mod.Instance("eureka")
// public static Eureka instance;
//
// @SidedProxy(clientSide = "eureka.proxy.ClientProxy", serverSide = "eureka.proxy.ServerProxy")
// public static IProxy proxy;
// public static ItemEngineeringDiary engineeringDiary;
// public static CreativeTabs eureka = new CreativeTabs("Eureka") {
//
// @Override
// public Item getTabIconItem() {
// return engineeringDiary;
// }
//
// };
//
// public static boolean giveBook;
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// EurekaAPI.API = new EurekaAPIImplementation();
// engineeringDiary = new ItemEngineeringDiary();
// GameRegistry.registerItem(engineeringDiary, "engineeringDiary");
// GameRegistry.addShapelessRecipe(new ItemStack(engineeringDiary), new Object[]{Items.book, Items.iron_ingot});
// MinecraftForge.EVENT_BUS.register(new EventHandler());
// FMLCommonHandler.instance().bus().register(new EventHandler());
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// EurekaAPI.API.registerCategory(new BasicEurekaCategory("Eureka", new ItemStack(engineeringDiary)));
// PacketHandler.init();
// ConfigReader.mainfolder = new File(event.getModConfigurationDirectory(), "Eureka");
// ConfigReader.read();
// Configuration config = new Configuration(event.getSuggestedConfigurationFile());
// giveBook = config.get("General", "giveBook", true).setDefaultValue(true).getBoolean();
// config.save();
// }
//
// @Mod.EventHandler
// public void serverStart(FMLServerStartingEvent event) {
// event.registerServerCommand(new EurekaCommand());
// }
//
// }
//
// Path: src/main/java/eureka/networking/MessageResearch.java
// public class MessageResearch implements IMessage, IMessageHandler<MessageResearch, IMessage> {
// public PlayerResearch research;
// public HashMap<String, Integer> progress = new HashMap<String, Integer>();
// public HashMap<String, Boolean> finished = new HashMap<String, Boolean>();
//
// public MessageResearch() {
//
// }
//
// public MessageResearch(EntityPlayer player) {
// research = PlayerResearch.get(player);
// }
//
// @Override
// public void fromBytes(ByteBuf buf) {
// for (IEurekaInfo info : EurekaAPI.API.getAllKeys()) {
// progress.put(info.getName(), buf.readInt());
// finished.put(info.getName(), buf.readBoolean());
// }
// }
//
// @Override
// public void toBytes(ByteBuf buf) {
// for (IEurekaInfo info : EurekaAPI.API.getAllKeys()) {
// buf.writeInt(research.getProgress(info.getName()));
// buf.writeBoolean(research.isFinished(info.getName()));
// }
// }
//
// @Override
// public IMessage onMessage(MessageResearch message, MessageContext ctx) {
// research = PlayerResearch.get(Eureka.proxy.getPlayer());
// for (IEurekaInfo info : EurekaAPI.API.getAllKeys()) {
// research.overrideProgress(info.getName(), message.progress.get(info.getName()));
// research.overrideFinished(info.getName(), message.finished.get(info.getName()));
// }
// return null;
// }
// }
//
// Path: src/main/java/eureka/networking/PacketHandler.java
// public class PacketHandler {
//
// public static final SimpleNetworkWrapper instance = NetworkRegistry.INSTANCE.newSimpleChannel("eureka");
//
// public static void init() {
// instance.registerMessage(MessageResearch.class, MessageResearch.class, 0, Side.CLIENT);
// instance.registerMessage(MessageResearchFinished.class, MessageResearchFinished.class, 1, Side.CLIENT);
// instance.registerMessage(MessageBookSave.class, MessageBookSave.class, 2, Side.SERVER);
// }
// }
// Path: src/main/java/eureka/items/ItemEngineeringDiary.java
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemBook;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.relauncher.Side;
import eureka.Eureka;
import eureka.networking.MessageResearch;
import eureka.networking.PacketHandler;
package eureka.items;
/**
* Copyright (c) 2014-2015, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Eureka is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class ItemEngineeringDiary extends ItemBook {
public ItemEngineeringDiary() {
setCreativeTab(Eureka.eureka);
setTextureName("eureka:engineeringDiary");
setUnlocalizedName("engineeringDiary");
}
@Override
public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) {
if (FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER) | PacketHandler.instance.sendToAllAround(new MessageResearch(player), new NetworkRegistry.TargetPoint(player.dimension, player.posX, player.posY, player.posZ, 1)); |
AEnterprise/Eureka | src/main/java/eureka/core/EurekaAPIImplementation.java | // Path: src/main/java/eureka/items/ItemResearchNote.java
// public class ItemResearchNote extends Item {
// public String key;
//
// public ItemResearchNote(String key) {
// setCreativeTab(Eureka.eureka);
// setTextureName("eureka:ResearchNote");
// setUnlocalizedName("researchNote");
// this.key = key;
// }
//
// @Override
// public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) {
// EurekaAPI.API.completeResearch(player, key);
// if (EurekaAPI.API.hasPlayerFinishedResearch(key, player))
// player.destroyCurrentEquippedItem();
// return stack;
// }
//
// @Override
// public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean advanced) {
// list.add(TextGetter.getTitle(key));
// }
// }
| import com.google.common.collect.ImmutableList;
import cpw.mods.fml.common.registry.GameRegistry;
import eureka.api.*;
import eureka.items.ItemResearchNote;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import java.util.*; | private ArrayList<IEurekaInfo> keylist = new ArrayList<IEurekaInfo>();
private HashMap<String, IEurekaInfo> keylookup = new HashMap<String, IEurekaInfo>();
private ArrayList<IDropHandler> dropHandlers = new ArrayList<IDropHandler>();
private HashMap<Block, String> blockMap = new HashMap<Block, String>();
private HashMap<Item, String> itemMap = new HashMap<Item, String>();
private EnumMap<EnumProgressOptions, HashMap<Object, List<String>>> progress = new EnumMap<EnumProgressOptions, HashMap<Object, List<String>>>(EnumProgressOptions.class);
@Override
public void registerCategory(ICategory category) {
categories.add(category);
keys.put(category.getName(), new ArrayList<IEurekaInfo>());
this.category.put(category.getName(), category);
}
@Override
public void register(IEurekaInfo info) {
if (keys.keySet().contains(info.getName())) {
Logger.error("Duplicate registation: '" + info.getName() + "' is already used");
} else {
if (!categories.contains(category.get(info.getCategory()))) {
Logger.error("Warning: Key with non-existing category added");
return;
}
keylist.add(info);
List<IEurekaInfo> list = keys.get(info.getCategory());
list.add(info);
keys.remove(info.getCategory());
keys.put(info.getCategory(), list);
keylookup.put(info.getName(), info);
} | // Path: src/main/java/eureka/items/ItemResearchNote.java
// public class ItemResearchNote extends Item {
// public String key;
//
// public ItemResearchNote(String key) {
// setCreativeTab(Eureka.eureka);
// setTextureName("eureka:ResearchNote");
// setUnlocalizedName("researchNote");
// this.key = key;
// }
//
// @Override
// public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) {
// EurekaAPI.API.completeResearch(player, key);
// if (EurekaAPI.API.hasPlayerFinishedResearch(key, player))
// player.destroyCurrentEquippedItem();
// return stack;
// }
//
// @Override
// public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean advanced) {
// list.add(TextGetter.getTitle(key));
// }
// }
// Path: src/main/java/eureka/core/EurekaAPIImplementation.java
import com.google.common.collect.ImmutableList;
import cpw.mods.fml.common.registry.GameRegistry;
import eureka.api.*;
import eureka.items.ItemResearchNote;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import java.util.*;
private ArrayList<IEurekaInfo> keylist = new ArrayList<IEurekaInfo>();
private HashMap<String, IEurekaInfo> keylookup = new HashMap<String, IEurekaInfo>();
private ArrayList<IDropHandler> dropHandlers = new ArrayList<IDropHandler>();
private HashMap<Block, String> blockMap = new HashMap<Block, String>();
private HashMap<Item, String> itemMap = new HashMap<Item, String>();
private EnumMap<EnumProgressOptions, HashMap<Object, List<String>>> progress = new EnumMap<EnumProgressOptions, HashMap<Object, List<String>>>(EnumProgressOptions.class);
@Override
public void registerCategory(ICategory category) {
categories.add(category);
keys.put(category.getName(), new ArrayList<IEurekaInfo>());
this.category.put(category.getName(), category);
}
@Override
public void register(IEurekaInfo info) {
if (keys.keySet().contains(info.getName())) {
Logger.error("Duplicate registation: '" + info.getName() + "' is already used");
} else {
if (!categories.contains(category.get(info.getCategory()))) {
Logger.error("Warning: Key with non-existing category added");
return;
}
keylist.add(info);
List<IEurekaInfo> list = keys.get(info.getCategory());
list.add(info);
keys.remove(info.getCategory());
keys.put(info.getCategory(), list);
keylookup.put(info.getName(), info);
} | ItemResearchNote note = new ItemResearchNote(info.getName()); |
AEnterprise/Eureka | src/main/java/eureka/core/EventHandler.java | // Path: src/main/java/eureka/Eureka.java
// @Mod(modid = "eureka", name = "Eureka", version = "@MODVERSION@", acceptedMinecraftVersions = "1.7.10")
// public class Eureka {
//
// @Mod.Instance("eureka")
// public static Eureka instance;
//
// @SidedProxy(clientSide = "eureka.proxy.ClientProxy", serverSide = "eureka.proxy.ServerProxy")
// public static IProxy proxy;
// public static ItemEngineeringDiary engineeringDiary;
// public static CreativeTabs eureka = new CreativeTabs("Eureka") {
//
// @Override
// public Item getTabIconItem() {
// return engineeringDiary;
// }
//
// };
//
// public static boolean giveBook;
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// EurekaAPI.API = new EurekaAPIImplementation();
// engineeringDiary = new ItemEngineeringDiary();
// GameRegistry.registerItem(engineeringDiary, "engineeringDiary");
// GameRegistry.addShapelessRecipe(new ItemStack(engineeringDiary), new Object[]{Items.book, Items.iron_ingot});
// MinecraftForge.EVENT_BUS.register(new EventHandler());
// FMLCommonHandler.instance().bus().register(new EventHandler());
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// EurekaAPI.API.registerCategory(new BasicEurekaCategory("Eureka", new ItemStack(engineeringDiary)));
// PacketHandler.init();
// ConfigReader.mainfolder = new File(event.getModConfigurationDirectory(), "Eureka");
// ConfigReader.read();
// Configuration config = new Configuration(event.getSuggestedConfigurationFile());
// giveBook = config.get("General", "giveBook", true).setDefaultValue(true).getBoolean();
// config.save();
// }
//
// @Mod.EventHandler
// public void serverStart(FMLServerStartingEvent event) {
// event.registerServerCommand(new EurekaCommand());
// }
//
// }
//
// Path: src/main/java/eureka/api/EnumProgressOptions.java
// public enum EnumProgressOptions {
// CRAFTING(true),
// CRAFT_ANYTHING(false),
// BREAK_BLOCK(true),
// BREAK_ANY_BLOCK(false),
// PLACE_BLOCK(true),
// PLACE_ANY_BLOCK(false),
// ENDER_TELEPORT(false),
// KILL_ANYTHING(false),
// DIE(false),
// FILL_BUCKET(false);
//
// private final boolean hasArg;
//
// EnumProgressOptions(boolean hasArg) {
// this.hasArg = hasArg;
// }
//
// public boolean hasArg() {
// return hasArg;
// }
// }
//
// Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
| import java.util.List;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.event.entity.EntityEvent;
import net.minecraftforge.event.entity.living.EnderTeleportEvent;
import net.minecraftforge.event.entity.player.FillBucketEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.world.BlockEvent;
import eureka.Eureka;
import eureka.api.EnumProgressOptions;
import eureka.api.EurekaAPI; | package eureka.core;
/**
* Copyright (c) 2014-2015, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Eureka is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class EventHandler {
@SubscribeEvent
public void onEntityConstruction(EntityEvent.EntityConstructing event) {
if (event.entity instanceof EntityPlayer && PlayerResearch.get((EntityPlayer) event.entity) == null) {
PlayerResearch.register((EntityPlayer) event.entity);
}
}
@SubscribeEvent
public void onClone(PlayerEvent.Clone event) {
PlayerResearch.get(event.entityPlayer).copy(PlayerResearch.get(event.original));
}
@SubscribeEvent
public void playerLogin(cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent event) {
//give engineering diary | // Path: src/main/java/eureka/Eureka.java
// @Mod(modid = "eureka", name = "Eureka", version = "@MODVERSION@", acceptedMinecraftVersions = "1.7.10")
// public class Eureka {
//
// @Mod.Instance("eureka")
// public static Eureka instance;
//
// @SidedProxy(clientSide = "eureka.proxy.ClientProxy", serverSide = "eureka.proxy.ServerProxy")
// public static IProxy proxy;
// public static ItemEngineeringDiary engineeringDiary;
// public static CreativeTabs eureka = new CreativeTabs("Eureka") {
//
// @Override
// public Item getTabIconItem() {
// return engineeringDiary;
// }
//
// };
//
// public static boolean giveBook;
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// EurekaAPI.API = new EurekaAPIImplementation();
// engineeringDiary = new ItemEngineeringDiary();
// GameRegistry.registerItem(engineeringDiary, "engineeringDiary");
// GameRegistry.addShapelessRecipe(new ItemStack(engineeringDiary), new Object[]{Items.book, Items.iron_ingot});
// MinecraftForge.EVENT_BUS.register(new EventHandler());
// FMLCommonHandler.instance().bus().register(new EventHandler());
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// EurekaAPI.API.registerCategory(new BasicEurekaCategory("Eureka", new ItemStack(engineeringDiary)));
// PacketHandler.init();
// ConfigReader.mainfolder = new File(event.getModConfigurationDirectory(), "Eureka");
// ConfigReader.read();
// Configuration config = new Configuration(event.getSuggestedConfigurationFile());
// giveBook = config.get("General", "giveBook", true).setDefaultValue(true).getBoolean();
// config.save();
// }
//
// @Mod.EventHandler
// public void serverStart(FMLServerStartingEvent event) {
// event.registerServerCommand(new EurekaCommand());
// }
//
// }
//
// Path: src/main/java/eureka/api/EnumProgressOptions.java
// public enum EnumProgressOptions {
// CRAFTING(true),
// CRAFT_ANYTHING(false),
// BREAK_BLOCK(true),
// BREAK_ANY_BLOCK(false),
// PLACE_BLOCK(true),
// PLACE_ANY_BLOCK(false),
// ENDER_TELEPORT(false),
// KILL_ANYTHING(false),
// DIE(false),
// FILL_BUCKET(false);
//
// private final boolean hasArg;
//
// EnumProgressOptions(boolean hasArg) {
// this.hasArg = hasArg;
// }
//
// public boolean hasArg() {
// return hasArg;
// }
// }
//
// Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
// Path: src/main/java/eureka/core/EventHandler.java
import java.util.List;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.event.entity.EntityEvent;
import net.minecraftforge.event.entity.living.EnderTeleportEvent;
import net.minecraftforge.event.entity.player.FillBucketEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.world.BlockEvent;
import eureka.Eureka;
import eureka.api.EnumProgressOptions;
import eureka.api.EurekaAPI;
package eureka.core;
/**
* Copyright (c) 2014-2015, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Eureka is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class EventHandler {
@SubscribeEvent
public void onEntityConstruction(EntityEvent.EntityConstructing event) {
if (event.entity instanceof EntityPlayer && PlayerResearch.get((EntityPlayer) event.entity) == null) {
PlayerResearch.register((EntityPlayer) event.entity);
}
}
@SubscribeEvent
public void onClone(PlayerEvent.Clone event) {
PlayerResearch.get(event.entityPlayer).copy(PlayerResearch.get(event.original));
}
@SubscribeEvent
public void playerLogin(cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent event) {
//give engineering diary | if (!event.player.getEntityData().getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG).hasKey("bookRecieved") && Eureka.giveBook) { |
AEnterprise/Eureka | src/main/java/eureka/core/EventHandler.java | // Path: src/main/java/eureka/Eureka.java
// @Mod(modid = "eureka", name = "Eureka", version = "@MODVERSION@", acceptedMinecraftVersions = "1.7.10")
// public class Eureka {
//
// @Mod.Instance("eureka")
// public static Eureka instance;
//
// @SidedProxy(clientSide = "eureka.proxy.ClientProxy", serverSide = "eureka.proxy.ServerProxy")
// public static IProxy proxy;
// public static ItemEngineeringDiary engineeringDiary;
// public static CreativeTabs eureka = new CreativeTabs("Eureka") {
//
// @Override
// public Item getTabIconItem() {
// return engineeringDiary;
// }
//
// };
//
// public static boolean giveBook;
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// EurekaAPI.API = new EurekaAPIImplementation();
// engineeringDiary = new ItemEngineeringDiary();
// GameRegistry.registerItem(engineeringDiary, "engineeringDiary");
// GameRegistry.addShapelessRecipe(new ItemStack(engineeringDiary), new Object[]{Items.book, Items.iron_ingot});
// MinecraftForge.EVENT_BUS.register(new EventHandler());
// FMLCommonHandler.instance().bus().register(new EventHandler());
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// EurekaAPI.API.registerCategory(new BasicEurekaCategory("Eureka", new ItemStack(engineeringDiary)));
// PacketHandler.init();
// ConfigReader.mainfolder = new File(event.getModConfigurationDirectory(), "Eureka");
// ConfigReader.read();
// Configuration config = new Configuration(event.getSuggestedConfigurationFile());
// giveBook = config.get("General", "giveBook", true).setDefaultValue(true).getBoolean();
// config.save();
// }
//
// @Mod.EventHandler
// public void serverStart(FMLServerStartingEvent event) {
// event.registerServerCommand(new EurekaCommand());
// }
//
// }
//
// Path: src/main/java/eureka/api/EnumProgressOptions.java
// public enum EnumProgressOptions {
// CRAFTING(true),
// CRAFT_ANYTHING(false),
// BREAK_BLOCK(true),
// BREAK_ANY_BLOCK(false),
// PLACE_BLOCK(true),
// PLACE_ANY_BLOCK(false),
// ENDER_TELEPORT(false),
// KILL_ANYTHING(false),
// DIE(false),
// FILL_BUCKET(false);
//
// private final boolean hasArg;
//
// EnumProgressOptions(boolean hasArg) {
// this.hasArg = hasArg;
// }
//
// public boolean hasArg() {
// return hasArg;
// }
// }
//
// Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
| import java.util.List;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.event.entity.EntityEvent;
import net.minecraftforge.event.entity.living.EnderTeleportEvent;
import net.minecraftforge.event.entity.player.FillBucketEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.world.BlockEvent;
import eureka.Eureka;
import eureka.api.EnumProgressOptions;
import eureka.api.EurekaAPI; | @SubscribeEvent
public void onClone(PlayerEvent.Clone event) {
PlayerResearch.get(event.entityPlayer).copy(PlayerResearch.get(event.original));
}
@SubscribeEvent
public void playerLogin(cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent event) {
//give engineering diary
if (!event.player.getEntityData().getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG).hasKey("bookRecieved") && Eureka.giveBook) {
for (int slot = 0; slot < event.player.inventory.getSizeInventory(); slot++) {
if (event.player.inventory.getStackInSlot(slot) == null) {
event.player.inventory.setInventorySlotContents(slot, new ItemStack(Eureka.engineeringDiary));
NBTTagCompound tag = event.player.getEntityData().getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG);
tag.setBoolean("bookRecieved", true);
event.player.getEntityData().setTag(EntityPlayer.PERSISTED_NBT_TAG, tag);
return;
}
}
}
}
@SubscribeEvent(priority = EventPriority.HIGHEST)
//make sure it gets trigered first to prevent handeling from other mods
public void onPlayerUsesBlock(PlayerInteractEvent event) {
String key = "";
if (event.world.isRemote)
return;
EntityPlayer player = event.entityPlayer;
PlayerResearch research = PlayerResearch.get(player);
if (player.getCurrentEquippedItem() != null) | // Path: src/main/java/eureka/Eureka.java
// @Mod(modid = "eureka", name = "Eureka", version = "@MODVERSION@", acceptedMinecraftVersions = "1.7.10")
// public class Eureka {
//
// @Mod.Instance("eureka")
// public static Eureka instance;
//
// @SidedProxy(clientSide = "eureka.proxy.ClientProxy", serverSide = "eureka.proxy.ServerProxy")
// public static IProxy proxy;
// public static ItemEngineeringDiary engineeringDiary;
// public static CreativeTabs eureka = new CreativeTabs("Eureka") {
//
// @Override
// public Item getTabIconItem() {
// return engineeringDiary;
// }
//
// };
//
// public static boolean giveBook;
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// EurekaAPI.API = new EurekaAPIImplementation();
// engineeringDiary = new ItemEngineeringDiary();
// GameRegistry.registerItem(engineeringDiary, "engineeringDiary");
// GameRegistry.addShapelessRecipe(new ItemStack(engineeringDiary), new Object[]{Items.book, Items.iron_ingot});
// MinecraftForge.EVENT_BUS.register(new EventHandler());
// FMLCommonHandler.instance().bus().register(new EventHandler());
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// EurekaAPI.API.registerCategory(new BasicEurekaCategory("Eureka", new ItemStack(engineeringDiary)));
// PacketHandler.init();
// ConfigReader.mainfolder = new File(event.getModConfigurationDirectory(), "Eureka");
// ConfigReader.read();
// Configuration config = new Configuration(event.getSuggestedConfigurationFile());
// giveBook = config.get("General", "giveBook", true).setDefaultValue(true).getBoolean();
// config.save();
// }
//
// @Mod.EventHandler
// public void serverStart(FMLServerStartingEvent event) {
// event.registerServerCommand(new EurekaCommand());
// }
//
// }
//
// Path: src/main/java/eureka/api/EnumProgressOptions.java
// public enum EnumProgressOptions {
// CRAFTING(true),
// CRAFT_ANYTHING(false),
// BREAK_BLOCK(true),
// BREAK_ANY_BLOCK(false),
// PLACE_BLOCK(true),
// PLACE_ANY_BLOCK(false),
// ENDER_TELEPORT(false),
// KILL_ANYTHING(false),
// DIE(false),
// FILL_BUCKET(false);
//
// private final boolean hasArg;
//
// EnumProgressOptions(boolean hasArg) {
// this.hasArg = hasArg;
// }
//
// public boolean hasArg() {
// return hasArg;
// }
// }
//
// Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
// Path: src/main/java/eureka/core/EventHandler.java
import java.util.List;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.event.entity.EntityEvent;
import net.minecraftforge.event.entity.living.EnderTeleportEvent;
import net.minecraftforge.event.entity.player.FillBucketEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.world.BlockEvent;
import eureka.Eureka;
import eureka.api.EnumProgressOptions;
import eureka.api.EurekaAPI;
@SubscribeEvent
public void onClone(PlayerEvent.Clone event) {
PlayerResearch.get(event.entityPlayer).copy(PlayerResearch.get(event.original));
}
@SubscribeEvent
public void playerLogin(cpw.mods.fml.common.gameevent.PlayerEvent.PlayerLoggedInEvent event) {
//give engineering diary
if (!event.player.getEntityData().getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG).hasKey("bookRecieved") && Eureka.giveBook) {
for (int slot = 0; slot < event.player.inventory.getSizeInventory(); slot++) {
if (event.player.inventory.getStackInSlot(slot) == null) {
event.player.inventory.setInventorySlotContents(slot, new ItemStack(Eureka.engineeringDiary));
NBTTagCompound tag = event.player.getEntityData().getCompoundTag(EntityPlayer.PERSISTED_NBT_TAG);
tag.setBoolean("bookRecieved", true);
event.player.getEntityData().setTag(EntityPlayer.PERSISTED_NBT_TAG, tag);
return;
}
}
}
}
@SubscribeEvent(priority = EventPriority.HIGHEST)
//make sure it gets trigered first to prevent handeling from other mods
public void onPlayerUsesBlock(PlayerInteractEvent event) {
String key = "";
if (event.world.isRemote)
return;
EntityPlayer player = event.entityPlayer;
PlayerResearch research = PlayerResearch.get(player);
if (player.getCurrentEquippedItem() != null) | key = EurekaAPI.API.getKey(player.getCurrentEquippedItem()); |
AEnterprise/Eureka | src/main/java/eureka/core/EventHandler.java | // Path: src/main/java/eureka/Eureka.java
// @Mod(modid = "eureka", name = "Eureka", version = "@MODVERSION@", acceptedMinecraftVersions = "1.7.10")
// public class Eureka {
//
// @Mod.Instance("eureka")
// public static Eureka instance;
//
// @SidedProxy(clientSide = "eureka.proxy.ClientProxy", serverSide = "eureka.proxy.ServerProxy")
// public static IProxy proxy;
// public static ItemEngineeringDiary engineeringDiary;
// public static CreativeTabs eureka = new CreativeTabs("Eureka") {
//
// @Override
// public Item getTabIconItem() {
// return engineeringDiary;
// }
//
// };
//
// public static boolean giveBook;
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// EurekaAPI.API = new EurekaAPIImplementation();
// engineeringDiary = new ItemEngineeringDiary();
// GameRegistry.registerItem(engineeringDiary, "engineeringDiary");
// GameRegistry.addShapelessRecipe(new ItemStack(engineeringDiary), new Object[]{Items.book, Items.iron_ingot});
// MinecraftForge.EVENT_BUS.register(new EventHandler());
// FMLCommonHandler.instance().bus().register(new EventHandler());
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// EurekaAPI.API.registerCategory(new BasicEurekaCategory("Eureka", new ItemStack(engineeringDiary)));
// PacketHandler.init();
// ConfigReader.mainfolder = new File(event.getModConfigurationDirectory(), "Eureka");
// ConfigReader.read();
// Configuration config = new Configuration(event.getSuggestedConfigurationFile());
// giveBook = config.get("General", "giveBook", true).setDefaultValue(true).getBoolean();
// config.save();
// }
//
// @Mod.EventHandler
// public void serverStart(FMLServerStartingEvent event) {
// event.registerServerCommand(new EurekaCommand());
// }
//
// }
//
// Path: src/main/java/eureka/api/EnumProgressOptions.java
// public enum EnumProgressOptions {
// CRAFTING(true),
// CRAFT_ANYTHING(false),
// BREAK_BLOCK(true),
// BREAK_ANY_BLOCK(false),
// PLACE_BLOCK(true),
// PLACE_ANY_BLOCK(false),
// ENDER_TELEPORT(false),
// KILL_ANYTHING(false),
// DIE(false),
// FILL_BUCKET(false);
//
// private final boolean hasArg;
//
// EnumProgressOptions(boolean hasArg) {
// this.hasArg = hasArg;
// }
//
// public boolean hasArg() {
// return hasArg;
// }
// }
//
// Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
| import java.util.List;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.event.entity.EntityEvent;
import net.minecraftforge.event.entity.living.EnderTeleportEvent;
import net.minecraftforge.event.entity.player.FillBucketEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.world.BlockEvent;
import eureka.Eureka;
import eureka.api.EnumProgressOptions;
import eureka.api.EurekaAPI; | }
@SubscribeEvent(priority = EventPriority.HIGHEST)
//make sure it gets trigered first to prevent handeling from other mods
public void onPlayerUsesBlock(PlayerInteractEvent event) {
String key = "";
if (event.world.isRemote)
return;
EntityPlayer player = event.entityPlayer;
PlayerResearch research = PlayerResearch.get(player);
if (player.getCurrentEquippedItem() != null)
key = EurekaAPI.API.getKey(player.getCurrentEquippedItem());
if (!research.isFinished(key) && !key.equals("")) {
ItemStack stack = player.getCurrentEquippedItem().copy();
stack.stackSize = 1;
dropItems(event.world, event.x, event.y, event.z, EurekaAPI.API.getDrops(stack));
if (event.entityPlayer.getCurrentEquippedItem().stackSize > 1)
event.entityPlayer.getCurrentEquippedItem().stackSize--;
else
event.entityPlayer.destroyCurrentEquippedItem();
event.setCanceled(true);
}
key = EurekaAPI.API.getKey(event.world.getBlock(event.x, event.y, event.z));
if (key != null && !key.equals("") && !research.isFinished(key))
event.setCanceled(true);
}
@SubscribeEvent
public void bucketFill(FillBucketEvent event) { | // Path: src/main/java/eureka/Eureka.java
// @Mod(modid = "eureka", name = "Eureka", version = "@MODVERSION@", acceptedMinecraftVersions = "1.7.10")
// public class Eureka {
//
// @Mod.Instance("eureka")
// public static Eureka instance;
//
// @SidedProxy(clientSide = "eureka.proxy.ClientProxy", serverSide = "eureka.proxy.ServerProxy")
// public static IProxy proxy;
// public static ItemEngineeringDiary engineeringDiary;
// public static CreativeTabs eureka = new CreativeTabs("Eureka") {
//
// @Override
// public Item getTabIconItem() {
// return engineeringDiary;
// }
//
// };
//
// public static boolean giveBook;
//
// @Mod.EventHandler
// public void preInit(FMLPreInitializationEvent event) {
// EurekaAPI.API = new EurekaAPIImplementation();
// engineeringDiary = new ItemEngineeringDiary();
// GameRegistry.registerItem(engineeringDiary, "engineeringDiary");
// GameRegistry.addShapelessRecipe(new ItemStack(engineeringDiary), new Object[]{Items.book, Items.iron_ingot});
// MinecraftForge.EVENT_BUS.register(new EventHandler());
// FMLCommonHandler.instance().bus().register(new EventHandler());
// NetworkRegistry.INSTANCE.registerGuiHandler(instance, new GuiHandler());
// EurekaAPI.API.registerCategory(new BasicEurekaCategory("Eureka", new ItemStack(engineeringDiary)));
// PacketHandler.init();
// ConfigReader.mainfolder = new File(event.getModConfigurationDirectory(), "Eureka");
// ConfigReader.read();
// Configuration config = new Configuration(event.getSuggestedConfigurationFile());
// giveBook = config.get("General", "giveBook", true).setDefaultValue(true).getBoolean();
// config.save();
// }
//
// @Mod.EventHandler
// public void serverStart(FMLServerStartingEvent event) {
// event.registerServerCommand(new EurekaCommand());
// }
//
// }
//
// Path: src/main/java/eureka/api/EnumProgressOptions.java
// public enum EnumProgressOptions {
// CRAFTING(true),
// CRAFT_ANYTHING(false),
// BREAK_BLOCK(true),
// BREAK_ANY_BLOCK(false),
// PLACE_BLOCK(true),
// PLACE_ANY_BLOCK(false),
// ENDER_TELEPORT(false),
// KILL_ANYTHING(false),
// DIE(false),
// FILL_BUCKET(false);
//
// private final boolean hasArg;
//
// EnumProgressOptions(boolean hasArg) {
// this.hasArg = hasArg;
// }
//
// public boolean hasArg() {
// return hasArg;
// }
// }
//
// Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
// Path: src/main/java/eureka/core/EventHandler.java
import java.util.List;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import cpw.mods.fml.common.eventhandler.EventPriority;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.event.entity.EntityEvent;
import net.minecraftforge.event.entity.living.EnderTeleportEvent;
import net.minecraftforge.event.entity.player.FillBucketEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.world.BlockEvent;
import eureka.Eureka;
import eureka.api.EnumProgressOptions;
import eureka.api.EurekaAPI;
}
@SubscribeEvent(priority = EventPriority.HIGHEST)
//make sure it gets trigered first to prevent handeling from other mods
public void onPlayerUsesBlock(PlayerInteractEvent event) {
String key = "";
if (event.world.isRemote)
return;
EntityPlayer player = event.entityPlayer;
PlayerResearch research = PlayerResearch.get(player);
if (player.getCurrentEquippedItem() != null)
key = EurekaAPI.API.getKey(player.getCurrentEquippedItem());
if (!research.isFinished(key) && !key.equals("")) {
ItemStack stack = player.getCurrentEquippedItem().copy();
stack.stackSize = 1;
dropItems(event.world, event.x, event.y, event.z, EurekaAPI.API.getDrops(stack));
if (event.entityPlayer.getCurrentEquippedItem().stackSize > 1)
event.entityPlayer.getCurrentEquippedItem().stackSize--;
else
event.entityPlayer.destroyCurrentEquippedItem();
event.setCanceled(true);
}
key = EurekaAPI.API.getKey(event.world.getBlock(event.x, event.y, event.z));
if (key != null && !key.equals("") && !research.isFinished(key))
event.setCanceled(true);
}
@SubscribeEvent
public void bucketFill(FillBucketEvent event) { | makeProgress(EnumProgressOptions.FILL_BUCKET, PlayerResearch.get(event.entityPlayer), null); |
AEnterprise/Eureka | src/main/java/eureka/networking/MessageResearchFinished.java | // Path: src/main/java/eureka/core/TextGetter.java
// public class TextGetter {
// private static HashMap<String, String> titles = new HashMap<String, String>();
// private static HashMap<String, String> descriptions = new HashMap<String, String>();
// private static HashMap<String, List<String>> texts = new HashMap<String, List<String>>();
// private static HashMap<String, String> progressTexts = new HashMap<String, String>();
//
// public static String getTitle(String key) {
// if (FMLCommonHandler.instance().getSide() == Side.SERVER)
// return "Unable to localize on the server side";
// if (titles.containsKey(key))
// return titles.get(key);
// getText(key);
// if (titles.containsKey(key))
// return titles.get(key);
// return "ERROR, UNABLE TO FIND LOCALIZATION FILE";
// }
//
// public static String getDesc(String key) {
// if (!EurekaAPI.API.keyRegistered(key))
// return "";
// if (descriptions.containsKey(key))
// return descriptions.get(key);
// getText(key);
// if (descriptions.containsKey(key))
// return descriptions.get(key);
// return "";
// }
//
// public static String getProgressText(String key) {
// if (!EurekaAPI.API.keyRegistered(key))
// return "";
// if (progressTexts.containsKey(key))
// return progressTexts.get(key);
// getText(key);
// if (progressTexts.containsKey(key))
// return progressTexts.get(key);
// return "";
// }
//
// public static List<String> getText(String key) {
// if (texts.containsKey(key))
// return texts.get(key);
// else
// getText(key, FMLClientHandler.instance().getCurrentLanguage(), !EurekaAPI.API.keyRegistered(key), true);
// getText(key, FMLClientHandler.instance().getCurrentLanguage(), !EurekaAPI.API.keyRegistered(key), false);
// return texts.get(key);
// }
//
// private static void getText(String key, String lang, boolean category, boolean configFolder) {
// List<String> list = new ArrayList<String>();
// InputStream stream = null;
// ResourceLocation location = new ResourceLocation("eureka:localizations/" + lang + "/" + key + ".txt");
// try {
// BufferedReader reader;
// if (!configFolder) {
// IResource resource = FMLClientHandler.instance().getClient().getResourceManager().getResource(location);
// stream = resource.getInputStream();
// reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
// } else {
// reader = new BufferedReader(new FileReader(new File(new File(ConfigReader.localizations, lang), key + ".txt")));
// }
//
// String line = reader.readLine();
// while (line != null) {
// list.add(line);
// line = reader.readLine();
// }
// reader.close();
// titles.put(key, list.get(0));
// if (!category) {
// descriptions.put(key, list.get(1));
// progressTexts.put(key, list.get(2));
// list.remove(0);
// list.remove(0);
// }
//
// list.remove(0);
// } catch (Exception e) {
// if (!lang.equals("en_US")) {
// getText(key, "en_US", category, true);
// getText(key, "en_US", category, false);
// }
// } finally {
// try {
// if (stream != null)
// stream.close();
// } catch (Exception e) {
// //ignore it, file doesn't exist
// }
// }
// texts.put(key, list);
// }
// }
| import io.netty.buffer.ByteBuf;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChatComponentTranslation;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import eureka.core.TextGetter; | package eureka.networking;
/**
* Copyright (c) 2014-2015, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Buildcraft Additions is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class MessageResearchFinished implements IMessage, IMessageHandler<MessageResearchFinished, IMessage> {
public String key;
public MessageResearchFinished() {
}
public MessageResearchFinished(String key) {
this.key = key;
}
@Override
public void fromBytes(ByteBuf buf) {
int num = buf.readInt();
key = "";
for (int t = 0; t < num; t++)
key += buf.readChar();
key = key.trim();
}
@Override
public void toBytes(ByteBuf buf) {
buf.writeInt(key.length());
for (char c : key.toCharArray())
buf.writeChar(c);
}
@Override
public IMessage onMessage(MessageResearchFinished message, MessageContext ctx) {
FMLClientHandler.instance().getClient().thePlayer.addChatComponentMessage(new ChatComponentTranslation("EUREKA")); | // Path: src/main/java/eureka/core/TextGetter.java
// public class TextGetter {
// private static HashMap<String, String> titles = new HashMap<String, String>();
// private static HashMap<String, String> descriptions = new HashMap<String, String>();
// private static HashMap<String, List<String>> texts = new HashMap<String, List<String>>();
// private static HashMap<String, String> progressTexts = new HashMap<String, String>();
//
// public static String getTitle(String key) {
// if (FMLCommonHandler.instance().getSide() == Side.SERVER)
// return "Unable to localize on the server side";
// if (titles.containsKey(key))
// return titles.get(key);
// getText(key);
// if (titles.containsKey(key))
// return titles.get(key);
// return "ERROR, UNABLE TO FIND LOCALIZATION FILE";
// }
//
// public static String getDesc(String key) {
// if (!EurekaAPI.API.keyRegistered(key))
// return "";
// if (descriptions.containsKey(key))
// return descriptions.get(key);
// getText(key);
// if (descriptions.containsKey(key))
// return descriptions.get(key);
// return "";
// }
//
// public static String getProgressText(String key) {
// if (!EurekaAPI.API.keyRegistered(key))
// return "";
// if (progressTexts.containsKey(key))
// return progressTexts.get(key);
// getText(key);
// if (progressTexts.containsKey(key))
// return progressTexts.get(key);
// return "";
// }
//
// public static List<String> getText(String key) {
// if (texts.containsKey(key))
// return texts.get(key);
// else
// getText(key, FMLClientHandler.instance().getCurrentLanguage(), !EurekaAPI.API.keyRegistered(key), true);
// getText(key, FMLClientHandler.instance().getCurrentLanguage(), !EurekaAPI.API.keyRegistered(key), false);
// return texts.get(key);
// }
//
// private static void getText(String key, String lang, boolean category, boolean configFolder) {
// List<String> list = new ArrayList<String>();
// InputStream stream = null;
// ResourceLocation location = new ResourceLocation("eureka:localizations/" + lang + "/" + key + ".txt");
// try {
// BufferedReader reader;
// if (!configFolder) {
// IResource resource = FMLClientHandler.instance().getClient().getResourceManager().getResource(location);
// stream = resource.getInputStream();
// reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
// } else {
// reader = new BufferedReader(new FileReader(new File(new File(ConfigReader.localizations, lang), key + ".txt")));
// }
//
// String line = reader.readLine();
// while (line != null) {
// list.add(line);
// line = reader.readLine();
// }
// reader.close();
// titles.put(key, list.get(0));
// if (!category) {
// descriptions.put(key, list.get(1));
// progressTexts.put(key, list.get(2));
// list.remove(0);
// list.remove(0);
// }
//
// list.remove(0);
// } catch (Exception e) {
// if (!lang.equals("en_US")) {
// getText(key, "en_US", category, true);
// getText(key, "en_US", category, false);
// }
// } finally {
// try {
// if (stream != null)
// stream.close();
// } catch (Exception e) {
// //ignore it, file doesn't exist
// }
// }
// texts.put(key, list);
// }
// }
// Path: src/main/java/eureka/networking/MessageResearchFinished.java
import io.netty.buffer.ByteBuf;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChatComponentTranslation;
import cpw.mods.fml.client.FMLClientHandler;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import eureka.core.TextGetter;
package eureka.networking;
/**
* Copyright (c) 2014-2015, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Buildcraft Additions is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class MessageResearchFinished implements IMessage, IMessageHandler<MessageResearchFinished, IMessage> {
public String key;
public MessageResearchFinished() {
}
public MessageResearchFinished(String key) {
this.key = key;
}
@Override
public void fromBytes(ByteBuf buf) {
int num = buf.readInt();
key = "";
for (int t = 0; t < num; t++)
key += buf.readChar();
key = key.trim();
}
@Override
public void toBytes(ByteBuf buf) {
buf.writeInt(key.length());
for (char c : key.toCharArray())
buf.writeChar(c);
}
@Override
public IMessage onMessage(MessageResearchFinished message, MessageContext ctx) {
FMLClientHandler.instance().getClient().thePlayer.addChatComponentMessage(new ChatComponentTranslation("EUREKA")); | FMLClientHandler.instance().getClient().thePlayer.addChatComponentMessage(new ChatComponentText("Research finished: " + TextGetter.getTitle(message.key))); |
AEnterprise/Eureka | src/main/java/eureka/core/PlayerResearch.java | // Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
//
// Path: src/main/java/eureka/api/IEurekaInfo.java
// public interface IEurekaInfo {
//
// String getCategory();
//
// int getMaxProgress();
//
// ItemStack getDisplayStack();
//
// String getName();
//
// List<String> getRequiredResearch();
// }
//
// Path: src/main/java/eureka/networking/MessageResearchFinished.java
// public class MessageResearchFinished implements IMessage, IMessageHandler<MessageResearchFinished, IMessage> {
// public String key;
//
// public MessageResearchFinished() {
// }
//
// public MessageResearchFinished(String key) {
// this.key = key;
// }
//
// @Override
// public void fromBytes(ByteBuf buf) {
// int num = buf.readInt();
// key = "";
// for (int t = 0; t < num; t++)
// key += buf.readChar();
// key = key.trim();
// }
//
// @Override
// public void toBytes(ByteBuf buf) {
// buf.writeInt(key.length());
// for (char c : key.toCharArray())
// buf.writeChar(c);
// }
//
// @Override
// public IMessage onMessage(MessageResearchFinished message, MessageContext ctx) {
// FMLClientHandler.instance().getClient().thePlayer.addChatComponentMessage(new ChatComponentTranslation("EUREKA"));
// FMLClientHandler.instance().getClient().thePlayer.addChatComponentMessage(new ChatComponentText("Research finished: " + TextGetter.getTitle(message.key)));
// return null;
// }
// }
//
// Path: src/main/java/eureka/networking/PacketHandler.java
// public class PacketHandler {
//
// public static final SimpleNetworkWrapper instance = NetworkRegistry.INSTANCE.newSimpleChannel("eureka");
//
// public static void init() {
// instance.registerMessage(MessageResearch.class, MessageResearch.class, 0, Side.CLIENT);
// instance.registerMessage(MessageResearchFinished.class, MessageResearchFinished.class, 1, Side.CLIENT);
// instance.registerMessage(MessageBookSave.class, MessageBookSave.class, 2, Side.SERVER);
// }
// }
| import java.util.HashMap;
import java.util.List;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import net.minecraftforge.common.IExtendedEntityProperties;
import eureka.api.EurekaAPI;
import eureka.api.IEurekaInfo;
import eureka.networking.MessageResearchFinished;
import eureka.networking.PacketHandler; | package eureka.core;
/**
* Copyright (c) 2014-2015, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Eureka is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class PlayerResearch implements IExtendedEntityProperties {
private final static String EXT_PROP_NAME = "EurekaPlayerResearch";
private final EntityPlayer player;
private HashMap<String, Integer> progressList = new HashMap<String, Integer>();
private HashMap<String, Boolean> finished = new HashMap<String, Boolean>();
public PlayerResearch(EntityPlayer player) {
this.player = player;
}
public static void register(EntityPlayer player) {
player.registerExtendedProperties(EXT_PROP_NAME, new PlayerResearch(player));
}
public static PlayerResearch get(EntityPlayer player) {
if (player == null)
return null;
return (PlayerResearch) player.getExtendedProperties(EXT_PROP_NAME);
}
@Override
public void saveNBTData(NBTTagCompound compound) {
NBTTagCompound tag = new NBTTagCompound(); | // Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
//
// Path: src/main/java/eureka/api/IEurekaInfo.java
// public interface IEurekaInfo {
//
// String getCategory();
//
// int getMaxProgress();
//
// ItemStack getDisplayStack();
//
// String getName();
//
// List<String> getRequiredResearch();
// }
//
// Path: src/main/java/eureka/networking/MessageResearchFinished.java
// public class MessageResearchFinished implements IMessage, IMessageHandler<MessageResearchFinished, IMessage> {
// public String key;
//
// public MessageResearchFinished() {
// }
//
// public MessageResearchFinished(String key) {
// this.key = key;
// }
//
// @Override
// public void fromBytes(ByteBuf buf) {
// int num = buf.readInt();
// key = "";
// for (int t = 0; t < num; t++)
// key += buf.readChar();
// key = key.trim();
// }
//
// @Override
// public void toBytes(ByteBuf buf) {
// buf.writeInt(key.length());
// for (char c : key.toCharArray())
// buf.writeChar(c);
// }
//
// @Override
// public IMessage onMessage(MessageResearchFinished message, MessageContext ctx) {
// FMLClientHandler.instance().getClient().thePlayer.addChatComponentMessage(new ChatComponentTranslation("EUREKA"));
// FMLClientHandler.instance().getClient().thePlayer.addChatComponentMessage(new ChatComponentText("Research finished: " + TextGetter.getTitle(message.key)));
// return null;
// }
// }
//
// Path: src/main/java/eureka/networking/PacketHandler.java
// public class PacketHandler {
//
// public static final SimpleNetworkWrapper instance = NetworkRegistry.INSTANCE.newSimpleChannel("eureka");
//
// public static void init() {
// instance.registerMessage(MessageResearch.class, MessageResearch.class, 0, Side.CLIENT);
// instance.registerMessage(MessageResearchFinished.class, MessageResearchFinished.class, 1, Side.CLIENT);
// instance.registerMessage(MessageBookSave.class, MessageBookSave.class, 2, Side.SERVER);
// }
// }
// Path: src/main/java/eureka/core/PlayerResearch.java
import java.util.HashMap;
import java.util.List;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import net.minecraftforge.common.IExtendedEntityProperties;
import eureka.api.EurekaAPI;
import eureka.api.IEurekaInfo;
import eureka.networking.MessageResearchFinished;
import eureka.networking.PacketHandler;
package eureka.core;
/**
* Copyright (c) 2014-2015, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Eureka is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class PlayerResearch implements IExtendedEntityProperties {
private final static String EXT_PROP_NAME = "EurekaPlayerResearch";
private final EntityPlayer player;
private HashMap<String, Integer> progressList = new HashMap<String, Integer>();
private HashMap<String, Boolean> finished = new HashMap<String, Boolean>();
public PlayerResearch(EntityPlayer player) {
this.player = player;
}
public static void register(EntityPlayer player) {
player.registerExtendedProperties(EXT_PROP_NAME, new PlayerResearch(player));
}
public static PlayerResearch get(EntityPlayer player) {
if (player == null)
return null;
return (PlayerResearch) player.getExtendedProperties(EXT_PROP_NAME);
}
@Override
public void saveNBTData(NBTTagCompound compound) {
NBTTagCompound tag = new NBTTagCompound(); | for (IEurekaInfo research : EurekaAPI.API.getAllKeys()) { |
AEnterprise/Eureka | src/main/java/eureka/core/PlayerResearch.java | // Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
//
// Path: src/main/java/eureka/api/IEurekaInfo.java
// public interface IEurekaInfo {
//
// String getCategory();
//
// int getMaxProgress();
//
// ItemStack getDisplayStack();
//
// String getName();
//
// List<String> getRequiredResearch();
// }
//
// Path: src/main/java/eureka/networking/MessageResearchFinished.java
// public class MessageResearchFinished implements IMessage, IMessageHandler<MessageResearchFinished, IMessage> {
// public String key;
//
// public MessageResearchFinished() {
// }
//
// public MessageResearchFinished(String key) {
// this.key = key;
// }
//
// @Override
// public void fromBytes(ByteBuf buf) {
// int num = buf.readInt();
// key = "";
// for (int t = 0; t < num; t++)
// key += buf.readChar();
// key = key.trim();
// }
//
// @Override
// public void toBytes(ByteBuf buf) {
// buf.writeInt(key.length());
// for (char c : key.toCharArray())
// buf.writeChar(c);
// }
//
// @Override
// public IMessage onMessage(MessageResearchFinished message, MessageContext ctx) {
// FMLClientHandler.instance().getClient().thePlayer.addChatComponentMessage(new ChatComponentTranslation("EUREKA"));
// FMLClientHandler.instance().getClient().thePlayer.addChatComponentMessage(new ChatComponentText("Research finished: " + TextGetter.getTitle(message.key)));
// return null;
// }
// }
//
// Path: src/main/java/eureka/networking/PacketHandler.java
// public class PacketHandler {
//
// public static final SimpleNetworkWrapper instance = NetworkRegistry.INSTANCE.newSimpleChannel("eureka");
//
// public static void init() {
// instance.registerMessage(MessageResearch.class, MessageResearch.class, 0, Side.CLIENT);
// instance.registerMessage(MessageResearchFinished.class, MessageResearchFinished.class, 1, Side.CLIENT);
// instance.registerMessage(MessageBookSave.class, MessageBookSave.class, 2, Side.SERVER);
// }
// }
| import java.util.HashMap;
import java.util.List;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import net.minecraftforge.common.IExtendedEntityProperties;
import eureka.api.EurekaAPI;
import eureka.api.IEurekaInfo;
import eureka.networking.MessageResearchFinished;
import eureka.networking.PacketHandler; | package eureka.core;
/**
* Copyright (c) 2014-2015, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Eureka is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class PlayerResearch implements IExtendedEntityProperties {
private final static String EXT_PROP_NAME = "EurekaPlayerResearch";
private final EntityPlayer player;
private HashMap<String, Integer> progressList = new HashMap<String, Integer>();
private HashMap<String, Boolean> finished = new HashMap<String, Boolean>();
public PlayerResearch(EntityPlayer player) {
this.player = player;
}
public static void register(EntityPlayer player) {
player.registerExtendedProperties(EXT_PROP_NAME, new PlayerResearch(player));
}
public static PlayerResearch get(EntityPlayer player) {
if (player == null)
return null;
return (PlayerResearch) player.getExtendedProperties(EXT_PROP_NAME);
}
@Override
public void saveNBTData(NBTTagCompound compound) {
NBTTagCompound tag = new NBTTagCompound(); | // Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
//
// Path: src/main/java/eureka/api/IEurekaInfo.java
// public interface IEurekaInfo {
//
// String getCategory();
//
// int getMaxProgress();
//
// ItemStack getDisplayStack();
//
// String getName();
//
// List<String> getRequiredResearch();
// }
//
// Path: src/main/java/eureka/networking/MessageResearchFinished.java
// public class MessageResearchFinished implements IMessage, IMessageHandler<MessageResearchFinished, IMessage> {
// public String key;
//
// public MessageResearchFinished() {
// }
//
// public MessageResearchFinished(String key) {
// this.key = key;
// }
//
// @Override
// public void fromBytes(ByteBuf buf) {
// int num = buf.readInt();
// key = "";
// for (int t = 0; t < num; t++)
// key += buf.readChar();
// key = key.trim();
// }
//
// @Override
// public void toBytes(ByteBuf buf) {
// buf.writeInt(key.length());
// for (char c : key.toCharArray())
// buf.writeChar(c);
// }
//
// @Override
// public IMessage onMessage(MessageResearchFinished message, MessageContext ctx) {
// FMLClientHandler.instance().getClient().thePlayer.addChatComponentMessage(new ChatComponentTranslation("EUREKA"));
// FMLClientHandler.instance().getClient().thePlayer.addChatComponentMessage(new ChatComponentText("Research finished: " + TextGetter.getTitle(message.key)));
// return null;
// }
// }
//
// Path: src/main/java/eureka/networking/PacketHandler.java
// public class PacketHandler {
//
// public static final SimpleNetworkWrapper instance = NetworkRegistry.INSTANCE.newSimpleChannel("eureka");
//
// public static void init() {
// instance.registerMessage(MessageResearch.class, MessageResearch.class, 0, Side.CLIENT);
// instance.registerMessage(MessageResearchFinished.class, MessageResearchFinished.class, 1, Side.CLIENT);
// instance.registerMessage(MessageBookSave.class, MessageBookSave.class, 2, Side.SERVER);
// }
// }
// Path: src/main/java/eureka/core/PlayerResearch.java
import java.util.HashMap;
import java.util.List;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import net.minecraftforge.common.IExtendedEntityProperties;
import eureka.api.EurekaAPI;
import eureka.api.IEurekaInfo;
import eureka.networking.MessageResearchFinished;
import eureka.networking.PacketHandler;
package eureka.core;
/**
* Copyright (c) 2014-2015, AEnterprise
* http://buildcraftadditions.wordpress.com/
* Eureka is distributed under the terms of GNU GPL v3.0
* Please check the contents of the license located in
* http://buildcraftadditions.wordpress.com/wiki/licensing-stuff/
*/
public class PlayerResearch implements IExtendedEntityProperties {
private final static String EXT_PROP_NAME = "EurekaPlayerResearch";
private final EntityPlayer player;
private HashMap<String, Integer> progressList = new HashMap<String, Integer>();
private HashMap<String, Boolean> finished = new HashMap<String, Boolean>();
public PlayerResearch(EntityPlayer player) {
this.player = player;
}
public static void register(EntityPlayer player) {
player.registerExtendedProperties(EXT_PROP_NAME, new PlayerResearch(player));
}
public static PlayerResearch get(EntityPlayer player) {
if (player == null)
return null;
return (PlayerResearch) player.getExtendedProperties(EXT_PROP_NAME);
}
@Override
public void saveNBTData(NBTTagCompound compound) {
NBTTagCompound tag = new NBTTagCompound(); | for (IEurekaInfo research : EurekaAPI.API.getAllKeys()) { |
AEnterprise/Eureka | src/main/java/eureka/core/PlayerResearch.java | // Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
//
// Path: src/main/java/eureka/api/IEurekaInfo.java
// public interface IEurekaInfo {
//
// String getCategory();
//
// int getMaxProgress();
//
// ItemStack getDisplayStack();
//
// String getName();
//
// List<String> getRequiredResearch();
// }
//
// Path: src/main/java/eureka/networking/MessageResearchFinished.java
// public class MessageResearchFinished implements IMessage, IMessageHandler<MessageResearchFinished, IMessage> {
// public String key;
//
// public MessageResearchFinished() {
// }
//
// public MessageResearchFinished(String key) {
// this.key = key;
// }
//
// @Override
// public void fromBytes(ByteBuf buf) {
// int num = buf.readInt();
// key = "";
// for (int t = 0; t < num; t++)
// key += buf.readChar();
// key = key.trim();
// }
//
// @Override
// public void toBytes(ByteBuf buf) {
// buf.writeInt(key.length());
// for (char c : key.toCharArray())
// buf.writeChar(c);
// }
//
// @Override
// public IMessage onMessage(MessageResearchFinished message, MessageContext ctx) {
// FMLClientHandler.instance().getClient().thePlayer.addChatComponentMessage(new ChatComponentTranslation("EUREKA"));
// FMLClientHandler.instance().getClient().thePlayer.addChatComponentMessage(new ChatComponentText("Research finished: " + TextGetter.getTitle(message.key)));
// return null;
// }
// }
//
// Path: src/main/java/eureka/networking/PacketHandler.java
// public class PacketHandler {
//
// public static final SimpleNetworkWrapper instance = NetworkRegistry.INSTANCE.newSimpleChannel("eureka");
//
// public static void init() {
// instance.registerMessage(MessageResearch.class, MessageResearch.class, 0, Side.CLIENT);
// instance.registerMessage(MessageResearchFinished.class, MessageResearchFinished.class, 1, Side.CLIENT);
// instance.registerMessage(MessageBookSave.class, MessageBookSave.class, 2, Side.SERVER);
// }
// }
| import java.util.HashMap;
import java.util.List;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import net.minecraftforge.common.IExtendedEntityProperties;
import eureka.api.EurekaAPI;
import eureka.api.IEurekaInfo;
import eureka.networking.MessageResearchFinished;
import eureka.networking.PacketHandler; |
public void loadOldResearch(NBTTagCompound compound) {
if (compound.getCompoundTag("ForgeData") != null && compound.getCompoundTag("ForgeData").getCompoundTag("PlayerPersisted") != null) {
NBTTagCompound tag = compound.getCompoundTag("ForgeData").getCompoundTag("PlayerPersisted");
for (IEurekaInfo research : EurekaAPI.API.getAllKeys()) {
progressList.put(research.getName(), tag.getInteger(research.getName() + "Progress"));
finished.put(research.getName(), tag.getBoolean(research.getName() + "Finished"));
tag.removeTag(research.getName() + "Progress");
tag.removeTag(research.getName() + "Finished");
}
}
}
@Override
public void init(Entity entity, World world) {
}
public void makeProgress(String key) {
try {
List<String> keys = EurekaAPI.API.getInfo(key).getRequiredResearch();
for (String checkKey : keys)
if (!isFinished(checkKey))
return;
if (!progressList.containsKey(key))
progressList.put(key, 0);
int progress = progressList.get(key);
progress++;
if (progress >= EurekaAPI.API.getMaxProgress(key)) {
progress = EurekaAPI.API.getMaxProgress(key);
if (finished != null && key != null && !finished.get(key)) { | // Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
//
// Path: src/main/java/eureka/api/IEurekaInfo.java
// public interface IEurekaInfo {
//
// String getCategory();
//
// int getMaxProgress();
//
// ItemStack getDisplayStack();
//
// String getName();
//
// List<String> getRequiredResearch();
// }
//
// Path: src/main/java/eureka/networking/MessageResearchFinished.java
// public class MessageResearchFinished implements IMessage, IMessageHandler<MessageResearchFinished, IMessage> {
// public String key;
//
// public MessageResearchFinished() {
// }
//
// public MessageResearchFinished(String key) {
// this.key = key;
// }
//
// @Override
// public void fromBytes(ByteBuf buf) {
// int num = buf.readInt();
// key = "";
// for (int t = 0; t < num; t++)
// key += buf.readChar();
// key = key.trim();
// }
//
// @Override
// public void toBytes(ByteBuf buf) {
// buf.writeInt(key.length());
// for (char c : key.toCharArray())
// buf.writeChar(c);
// }
//
// @Override
// public IMessage onMessage(MessageResearchFinished message, MessageContext ctx) {
// FMLClientHandler.instance().getClient().thePlayer.addChatComponentMessage(new ChatComponentTranslation("EUREKA"));
// FMLClientHandler.instance().getClient().thePlayer.addChatComponentMessage(new ChatComponentText("Research finished: " + TextGetter.getTitle(message.key)));
// return null;
// }
// }
//
// Path: src/main/java/eureka/networking/PacketHandler.java
// public class PacketHandler {
//
// public static final SimpleNetworkWrapper instance = NetworkRegistry.INSTANCE.newSimpleChannel("eureka");
//
// public static void init() {
// instance.registerMessage(MessageResearch.class, MessageResearch.class, 0, Side.CLIENT);
// instance.registerMessage(MessageResearchFinished.class, MessageResearchFinished.class, 1, Side.CLIENT);
// instance.registerMessage(MessageBookSave.class, MessageBookSave.class, 2, Side.SERVER);
// }
// }
// Path: src/main/java/eureka/core/PlayerResearch.java
import java.util.HashMap;
import java.util.List;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import net.minecraftforge.common.IExtendedEntityProperties;
import eureka.api.EurekaAPI;
import eureka.api.IEurekaInfo;
import eureka.networking.MessageResearchFinished;
import eureka.networking.PacketHandler;
public void loadOldResearch(NBTTagCompound compound) {
if (compound.getCompoundTag("ForgeData") != null && compound.getCompoundTag("ForgeData").getCompoundTag("PlayerPersisted") != null) {
NBTTagCompound tag = compound.getCompoundTag("ForgeData").getCompoundTag("PlayerPersisted");
for (IEurekaInfo research : EurekaAPI.API.getAllKeys()) {
progressList.put(research.getName(), tag.getInteger(research.getName() + "Progress"));
finished.put(research.getName(), tag.getBoolean(research.getName() + "Finished"));
tag.removeTag(research.getName() + "Progress");
tag.removeTag(research.getName() + "Finished");
}
}
}
@Override
public void init(Entity entity, World world) {
}
public void makeProgress(String key) {
try {
List<String> keys = EurekaAPI.API.getInfo(key).getRequiredResearch();
for (String checkKey : keys)
if (!isFinished(checkKey))
return;
if (!progressList.containsKey(key))
progressList.put(key, 0);
int progress = progressList.get(key);
progress++;
if (progress >= EurekaAPI.API.getMaxProgress(key)) {
progress = EurekaAPI.API.getMaxProgress(key);
if (finished != null && key != null && !finished.get(key)) { | PacketHandler.instance.sendTo(new MessageResearchFinished(key), (EntityPlayerMP) player); |
AEnterprise/Eureka | src/main/java/eureka/core/PlayerResearch.java | // Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
//
// Path: src/main/java/eureka/api/IEurekaInfo.java
// public interface IEurekaInfo {
//
// String getCategory();
//
// int getMaxProgress();
//
// ItemStack getDisplayStack();
//
// String getName();
//
// List<String> getRequiredResearch();
// }
//
// Path: src/main/java/eureka/networking/MessageResearchFinished.java
// public class MessageResearchFinished implements IMessage, IMessageHandler<MessageResearchFinished, IMessage> {
// public String key;
//
// public MessageResearchFinished() {
// }
//
// public MessageResearchFinished(String key) {
// this.key = key;
// }
//
// @Override
// public void fromBytes(ByteBuf buf) {
// int num = buf.readInt();
// key = "";
// for (int t = 0; t < num; t++)
// key += buf.readChar();
// key = key.trim();
// }
//
// @Override
// public void toBytes(ByteBuf buf) {
// buf.writeInt(key.length());
// for (char c : key.toCharArray())
// buf.writeChar(c);
// }
//
// @Override
// public IMessage onMessage(MessageResearchFinished message, MessageContext ctx) {
// FMLClientHandler.instance().getClient().thePlayer.addChatComponentMessage(new ChatComponentTranslation("EUREKA"));
// FMLClientHandler.instance().getClient().thePlayer.addChatComponentMessage(new ChatComponentText("Research finished: " + TextGetter.getTitle(message.key)));
// return null;
// }
// }
//
// Path: src/main/java/eureka/networking/PacketHandler.java
// public class PacketHandler {
//
// public static final SimpleNetworkWrapper instance = NetworkRegistry.INSTANCE.newSimpleChannel("eureka");
//
// public static void init() {
// instance.registerMessage(MessageResearch.class, MessageResearch.class, 0, Side.CLIENT);
// instance.registerMessage(MessageResearchFinished.class, MessageResearchFinished.class, 1, Side.CLIENT);
// instance.registerMessage(MessageBookSave.class, MessageBookSave.class, 2, Side.SERVER);
// }
// }
| import java.util.HashMap;
import java.util.List;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import net.minecraftforge.common.IExtendedEntityProperties;
import eureka.api.EurekaAPI;
import eureka.api.IEurekaInfo;
import eureka.networking.MessageResearchFinished;
import eureka.networking.PacketHandler; |
public void loadOldResearch(NBTTagCompound compound) {
if (compound.getCompoundTag("ForgeData") != null && compound.getCompoundTag("ForgeData").getCompoundTag("PlayerPersisted") != null) {
NBTTagCompound tag = compound.getCompoundTag("ForgeData").getCompoundTag("PlayerPersisted");
for (IEurekaInfo research : EurekaAPI.API.getAllKeys()) {
progressList.put(research.getName(), tag.getInteger(research.getName() + "Progress"));
finished.put(research.getName(), tag.getBoolean(research.getName() + "Finished"));
tag.removeTag(research.getName() + "Progress");
tag.removeTag(research.getName() + "Finished");
}
}
}
@Override
public void init(Entity entity, World world) {
}
public void makeProgress(String key) {
try {
List<String> keys = EurekaAPI.API.getInfo(key).getRequiredResearch();
for (String checkKey : keys)
if (!isFinished(checkKey))
return;
if (!progressList.containsKey(key))
progressList.put(key, 0);
int progress = progressList.get(key);
progress++;
if (progress >= EurekaAPI.API.getMaxProgress(key)) {
progress = EurekaAPI.API.getMaxProgress(key);
if (finished != null && key != null && !finished.get(key)) { | // Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
//
// Path: src/main/java/eureka/api/IEurekaInfo.java
// public interface IEurekaInfo {
//
// String getCategory();
//
// int getMaxProgress();
//
// ItemStack getDisplayStack();
//
// String getName();
//
// List<String> getRequiredResearch();
// }
//
// Path: src/main/java/eureka/networking/MessageResearchFinished.java
// public class MessageResearchFinished implements IMessage, IMessageHandler<MessageResearchFinished, IMessage> {
// public String key;
//
// public MessageResearchFinished() {
// }
//
// public MessageResearchFinished(String key) {
// this.key = key;
// }
//
// @Override
// public void fromBytes(ByteBuf buf) {
// int num = buf.readInt();
// key = "";
// for (int t = 0; t < num; t++)
// key += buf.readChar();
// key = key.trim();
// }
//
// @Override
// public void toBytes(ByteBuf buf) {
// buf.writeInt(key.length());
// for (char c : key.toCharArray())
// buf.writeChar(c);
// }
//
// @Override
// public IMessage onMessage(MessageResearchFinished message, MessageContext ctx) {
// FMLClientHandler.instance().getClient().thePlayer.addChatComponentMessage(new ChatComponentTranslation("EUREKA"));
// FMLClientHandler.instance().getClient().thePlayer.addChatComponentMessage(new ChatComponentText("Research finished: " + TextGetter.getTitle(message.key)));
// return null;
// }
// }
//
// Path: src/main/java/eureka/networking/PacketHandler.java
// public class PacketHandler {
//
// public static final SimpleNetworkWrapper instance = NetworkRegistry.INSTANCE.newSimpleChannel("eureka");
//
// public static void init() {
// instance.registerMessage(MessageResearch.class, MessageResearch.class, 0, Side.CLIENT);
// instance.registerMessage(MessageResearchFinished.class, MessageResearchFinished.class, 1, Side.CLIENT);
// instance.registerMessage(MessageBookSave.class, MessageBookSave.class, 2, Side.SERVER);
// }
// }
// Path: src/main/java/eureka/core/PlayerResearch.java
import java.util.HashMap;
import java.util.List;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import net.minecraftforge.common.IExtendedEntityProperties;
import eureka.api.EurekaAPI;
import eureka.api.IEurekaInfo;
import eureka.networking.MessageResearchFinished;
import eureka.networking.PacketHandler;
public void loadOldResearch(NBTTagCompound compound) {
if (compound.getCompoundTag("ForgeData") != null && compound.getCompoundTag("ForgeData").getCompoundTag("PlayerPersisted") != null) {
NBTTagCompound tag = compound.getCompoundTag("ForgeData").getCompoundTag("PlayerPersisted");
for (IEurekaInfo research : EurekaAPI.API.getAllKeys()) {
progressList.put(research.getName(), tag.getInteger(research.getName() + "Progress"));
finished.put(research.getName(), tag.getBoolean(research.getName() + "Finished"));
tag.removeTag(research.getName() + "Progress");
tag.removeTag(research.getName() + "Finished");
}
}
}
@Override
public void init(Entity entity, World world) {
}
public void makeProgress(String key) {
try {
List<String> keys = EurekaAPI.API.getInfo(key).getRequiredResearch();
for (String checkKey : keys)
if (!isFinished(checkKey))
return;
if (!progressList.containsKey(key))
progressList.put(key, 0);
int progress = progressList.get(key);
progress++;
if (progress >= EurekaAPI.API.getMaxProgress(key)) {
progress = EurekaAPI.API.getMaxProgress(key);
if (finished != null && key != null && !finished.get(key)) { | PacketHandler.instance.sendTo(new MessageResearchFinished(key), (EntityPlayerMP) player); |
AEnterprise/Eureka | src/main/java/eureka/json/ConfigReader.java | // Path: src/main/java/eureka/api/BasicEurekaCategory.java
// public class BasicEurekaCategory implements ICategory {
// private final String name;
// private final ItemStack displayStack;
//
// public BasicEurekaCategory(String name, ItemStack displayStack) {
// this.name = name;
// this.displayStack = displayStack;
// }
//
// public BasicEurekaCategory(String name, Block block) {
// this(name, new ItemStack(block));
// }
//
// public BasicEurekaCategory(String name, Item item) {
// this(name, new ItemStack(item));
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public ItemStack getDisplayStack() {
// return displayStack;
// }
// }
//
// Path: src/main/java/eureka/api/BasicEurekaInfo.java
// public class BasicEurekaInfo implements IEurekaInfo {
// private final String category, name;
// private final int maxProgress;
// private final ItemStack displayStack;
// private final List<String> requiredResearch;
//
// public BasicEurekaInfo(String name, String category, int maxProgress, ItemStack displayStack, String... requiredResearch) {
// this.name = name;
// this.category = category;
// this.maxProgress = maxProgress;
// this.displayStack = displayStack;
// List<String> research = new ArrayList<String>();
// research.addAll(Arrays.asList(requiredResearch));
// this.requiredResearch = research;
// }
//
// public BasicEurekaInfo(String name, String category, int maxProgress, Item item, String... requiredResearch) {
// this(name, category, maxProgress, new ItemStack(item), requiredResearch);
// }
//
// public BasicEurekaInfo(String name, String category, int maxProgress, Block block, String... requiredResearch) {
// this(name, category, maxProgress, new ItemStack(block), requiredResearch);
// }
//
// @Override
// public String getCategory() {
// return category;
// }
//
// @Override
// public int getMaxProgress() {
// return maxProgress;
// }
//
// @Override
// public ItemStack getDisplayStack() {
// return displayStack;
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public List<String> getRequiredResearch() {
// return requiredResearch;
// }
// }
//
// Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
//
// Path: src/main/java/eureka/core/Logger.java
// public class Logger {
//
// public static final org.apache.logging.log4j.Logger logger = LogManager.getLogger("Eureka");
//
// public static void info(String message) {
// logger.info(message);
// }
//
// public static void error(String message) {
// logger.error(message);
// }
// }
| import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.registry.GameRegistry;
import eureka.api.BasicEurekaCategory;
import eureka.api.BasicEurekaInfo;
import eureka.api.EurekaAPI;
import eureka.core.Logger; | createFolderIfNeeded(keyFolder);
createFolderIfNeeded(localizations);
createFolderIfNeeded(new File(localizations, "en_US"));
if (!catagoryFolder.exists())
return;
for (File file : catagoryFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".json");
}
})) {
readCategory(file);
}
if (!keyFolder.exists())
return;
for (File file : keyFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".json");
}
})) {
readKey(file);
}
}
private static void readCategory(File file) {
try {
JSONCategory category = gson.fromJson(new FileReader(file), JSONCategory.class); | // Path: src/main/java/eureka/api/BasicEurekaCategory.java
// public class BasicEurekaCategory implements ICategory {
// private final String name;
// private final ItemStack displayStack;
//
// public BasicEurekaCategory(String name, ItemStack displayStack) {
// this.name = name;
// this.displayStack = displayStack;
// }
//
// public BasicEurekaCategory(String name, Block block) {
// this(name, new ItemStack(block));
// }
//
// public BasicEurekaCategory(String name, Item item) {
// this(name, new ItemStack(item));
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public ItemStack getDisplayStack() {
// return displayStack;
// }
// }
//
// Path: src/main/java/eureka/api/BasicEurekaInfo.java
// public class BasicEurekaInfo implements IEurekaInfo {
// private final String category, name;
// private final int maxProgress;
// private final ItemStack displayStack;
// private final List<String> requiredResearch;
//
// public BasicEurekaInfo(String name, String category, int maxProgress, ItemStack displayStack, String... requiredResearch) {
// this.name = name;
// this.category = category;
// this.maxProgress = maxProgress;
// this.displayStack = displayStack;
// List<String> research = new ArrayList<String>();
// research.addAll(Arrays.asList(requiredResearch));
// this.requiredResearch = research;
// }
//
// public BasicEurekaInfo(String name, String category, int maxProgress, Item item, String... requiredResearch) {
// this(name, category, maxProgress, new ItemStack(item), requiredResearch);
// }
//
// public BasicEurekaInfo(String name, String category, int maxProgress, Block block, String... requiredResearch) {
// this(name, category, maxProgress, new ItemStack(block), requiredResearch);
// }
//
// @Override
// public String getCategory() {
// return category;
// }
//
// @Override
// public int getMaxProgress() {
// return maxProgress;
// }
//
// @Override
// public ItemStack getDisplayStack() {
// return displayStack;
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public List<String> getRequiredResearch() {
// return requiredResearch;
// }
// }
//
// Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
//
// Path: src/main/java/eureka/core/Logger.java
// public class Logger {
//
// public static final org.apache.logging.log4j.Logger logger = LogManager.getLogger("Eureka");
//
// public static void info(String message) {
// logger.info(message);
// }
//
// public static void error(String message) {
// logger.error(message);
// }
// }
// Path: src/main/java/eureka/json/ConfigReader.java
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.registry.GameRegistry;
import eureka.api.BasicEurekaCategory;
import eureka.api.BasicEurekaInfo;
import eureka.api.EurekaAPI;
import eureka.core.Logger;
createFolderIfNeeded(keyFolder);
createFolderIfNeeded(localizations);
createFolderIfNeeded(new File(localizations, "en_US"));
if (!catagoryFolder.exists())
return;
for (File file : catagoryFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".json");
}
})) {
readCategory(file);
}
if (!keyFolder.exists())
return;
for (File file : keyFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".json");
}
})) {
readKey(file);
}
}
private static void readCategory(File file) {
try {
JSONCategory category = gson.fromJson(new FileReader(file), JSONCategory.class); | EurekaAPI.API.registerCategory(new BasicEurekaCategory(category.name, getStack(category.displayStack))); |
AEnterprise/Eureka | src/main/java/eureka/json/ConfigReader.java | // Path: src/main/java/eureka/api/BasicEurekaCategory.java
// public class BasicEurekaCategory implements ICategory {
// private final String name;
// private final ItemStack displayStack;
//
// public BasicEurekaCategory(String name, ItemStack displayStack) {
// this.name = name;
// this.displayStack = displayStack;
// }
//
// public BasicEurekaCategory(String name, Block block) {
// this(name, new ItemStack(block));
// }
//
// public BasicEurekaCategory(String name, Item item) {
// this(name, new ItemStack(item));
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public ItemStack getDisplayStack() {
// return displayStack;
// }
// }
//
// Path: src/main/java/eureka/api/BasicEurekaInfo.java
// public class BasicEurekaInfo implements IEurekaInfo {
// private final String category, name;
// private final int maxProgress;
// private final ItemStack displayStack;
// private final List<String> requiredResearch;
//
// public BasicEurekaInfo(String name, String category, int maxProgress, ItemStack displayStack, String... requiredResearch) {
// this.name = name;
// this.category = category;
// this.maxProgress = maxProgress;
// this.displayStack = displayStack;
// List<String> research = new ArrayList<String>();
// research.addAll(Arrays.asList(requiredResearch));
// this.requiredResearch = research;
// }
//
// public BasicEurekaInfo(String name, String category, int maxProgress, Item item, String... requiredResearch) {
// this(name, category, maxProgress, new ItemStack(item), requiredResearch);
// }
//
// public BasicEurekaInfo(String name, String category, int maxProgress, Block block, String... requiredResearch) {
// this(name, category, maxProgress, new ItemStack(block), requiredResearch);
// }
//
// @Override
// public String getCategory() {
// return category;
// }
//
// @Override
// public int getMaxProgress() {
// return maxProgress;
// }
//
// @Override
// public ItemStack getDisplayStack() {
// return displayStack;
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public List<String> getRequiredResearch() {
// return requiredResearch;
// }
// }
//
// Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
//
// Path: src/main/java/eureka/core/Logger.java
// public class Logger {
//
// public static final org.apache.logging.log4j.Logger logger = LogManager.getLogger("Eureka");
//
// public static void info(String message) {
// logger.info(message);
// }
//
// public static void error(String message) {
// logger.error(message);
// }
// }
| import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.registry.GameRegistry;
import eureka.api.BasicEurekaCategory;
import eureka.api.BasicEurekaInfo;
import eureka.api.EurekaAPI;
import eureka.core.Logger; | createFolderIfNeeded(keyFolder);
createFolderIfNeeded(localizations);
createFolderIfNeeded(new File(localizations, "en_US"));
if (!catagoryFolder.exists())
return;
for (File file : catagoryFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".json");
}
})) {
readCategory(file);
}
if (!keyFolder.exists())
return;
for (File file : keyFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".json");
}
})) {
readKey(file);
}
}
private static void readCategory(File file) {
try {
JSONCategory category = gson.fromJson(new FileReader(file), JSONCategory.class); | // Path: src/main/java/eureka/api/BasicEurekaCategory.java
// public class BasicEurekaCategory implements ICategory {
// private final String name;
// private final ItemStack displayStack;
//
// public BasicEurekaCategory(String name, ItemStack displayStack) {
// this.name = name;
// this.displayStack = displayStack;
// }
//
// public BasicEurekaCategory(String name, Block block) {
// this(name, new ItemStack(block));
// }
//
// public BasicEurekaCategory(String name, Item item) {
// this(name, new ItemStack(item));
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public ItemStack getDisplayStack() {
// return displayStack;
// }
// }
//
// Path: src/main/java/eureka/api/BasicEurekaInfo.java
// public class BasicEurekaInfo implements IEurekaInfo {
// private final String category, name;
// private final int maxProgress;
// private final ItemStack displayStack;
// private final List<String> requiredResearch;
//
// public BasicEurekaInfo(String name, String category, int maxProgress, ItemStack displayStack, String... requiredResearch) {
// this.name = name;
// this.category = category;
// this.maxProgress = maxProgress;
// this.displayStack = displayStack;
// List<String> research = new ArrayList<String>();
// research.addAll(Arrays.asList(requiredResearch));
// this.requiredResearch = research;
// }
//
// public BasicEurekaInfo(String name, String category, int maxProgress, Item item, String... requiredResearch) {
// this(name, category, maxProgress, new ItemStack(item), requiredResearch);
// }
//
// public BasicEurekaInfo(String name, String category, int maxProgress, Block block, String... requiredResearch) {
// this(name, category, maxProgress, new ItemStack(block), requiredResearch);
// }
//
// @Override
// public String getCategory() {
// return category;
// }
//
// @Override
// public int getMaxProgress() {
// return maxProgress;
// }
//
// @Override
// public ItemStack getDisplayStack() {
// return displayStack;
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public List<String> getRequiredResearch() {
// return requiredResearch;
// }
// }
//
// Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
//
// Path: src/main/java/eureka/core/Logger.java
// public class Logger {
//
// public static final org.apache.logging.log4j.Logger logger = LogManager.getLogger("Eureka");
//
// public static void info(String message) {
// logger.info(message);
// }
//
// public static void error(String message) {
// logger.error(message);
// }
// }
// Path: src/main/java/eureka/json/ConfigReader.java
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.registry.GameRegistry;
import eureka.api.BasicEurekaCategory;
import eureka.api.BasicEurekaInfo;
import eureka.api.EurekaAPI;
import eureka.core.Logger;
createFolderIfNeeded(keyFolder);
createFolderIfNeeded(localizations);
createFolderIfNeeded(new File(localizations, "en_US"));
if (!catagoryFolder.exists())
return;
for (File file : catagoryFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".json");
}
})) {
readCategory(file);
}
if (!keyFolder.exists())
return;
for (File file : keyFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".json");
}
})) {
readKey(file);
}
}
private static void readCategory(File file) {
try {
JSONCategory category = gson.fromJson(new FileReader(file), JSONCategory.class); | EurekaAPI.API.registerCategory(new BasicEurekaCategory(category.name, getStack(category.displayStack))); |
AEnterprise/Eureka | src/main/java/eureka/json/ConfigReader.java | // Path: src/main/java/eureka/api/BasicEurekaCategory.java
// public class BasicEurekaCategory implements ICategory {
// private final String name;
// private final ItemStack displayStack;
//
// public BasicEurekaCategory(String name, ItemStack displayStack) {
// this.name = name;
// this.displayStack = displayStack;
// }
//
// public BasicEurekaCategory(String name, Block block) {
// this(name, new ItemStack(block));
// }
//
// public BasicEurekaCategory(String name, Item item) {
// this(name, new ItemStack(item));
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public ItemStack getDisplayStack() {
// return displayStack;
// }
// }
//
// Path: src/main/java/eureka/api/BasicEurekaInfo.java
// public class BasicEurekaInfo implements IEurekaInfo {
// private final String category, name;
// private final int maxProgress;
// private final ItemStack displayStack;
// private final List<String> requiredResearch;
//
// public BasicEurekaInfo(String name, String category, int maxProgress, ItemStack displayStack, String... requiredResearch) {
// this.name = name;
// this.category = category;
// this.maxProgress = maxProgress;
// this.displayStack = displayStack;
// List<String> research = new ArrayList<String>();
// research.addAll(Arrays.asList(requiredResearch));
// this.requiredResearch = research;
// }
//
// public BasicEurekaInfo(String name, String category, int maxProgress, Item item, String... requiredResearch) {
// this(name, category, maxProgress, new ItemStack(item), requiredResearch);
// }
//
// public BasicEurekaInfo(String name, String category, int maxProgress, Block block, String... requiredResearch) {
// this(name, category, maxProgress, new ItemStack(block), requiredResearch);
// }
//
// @Override
// public String getCategory() {
// return category;
// }
//
// @Override
// public int getMaxProgress() {
// return maxProgress;
// }
//
// @Override
// public ItemStack getDisplayStack() {
// return displayStack;
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public List<String> getRequiredResearch() {
// return requiredResearch;
// }
// }
//
// Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
//
// Path: src/main/java/eureka/core/Logger.java
// public class Logger {
//
// public static final org.apache.logging.log4j.Logger logger = LogManager.getLogger("Eureka");
//
// public static void info(String message) {
// logger.info(message);
// }
//
// public static void error(String message) {
// logger.error(message);
// }
// }
| import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.registry.GameRegistry;
import eureka.api.BasicEurekaCategory;
import eureka.api.BasicEurekaInfo;
import eureka.api.EurekaAPI;
import eureka.core.Logger; | createFolderIfNeeded(new File(localizations, "en_US"));
if (!catagoryFolder.exists())
return;
for (File file : catagoryFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".json");
}
})) {
readCategory(file);
}
if (!keyFolder.exists())
return;
for (File file : keyFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".json");
}
})) {
readKey(file);
}
}
private static void readCategory(File file) {
try {
JSONCategory category = gson.fromJson(new FileReader(file), JSONCategory.class);
EurekaAPI.API.registerCategory(new BasicEurekaCategory(category.name, getStack(category.displayStack)));
} catch (Throwable t) { | // Path: src/main/java/eureka/api/BasicEurekaCategory.java
// public class BasicEurekaCategory implements ICategory {
// private final String name;
// private final ItemStack displayStack;
//
// public BasicEurekaCategory(String name, ItemStack displayStack) {
// this.name = name;
// this.displayStack = displayStack;
// }
//
// public BasicEurekaCategory(String name, Block block) {
// this(name, new ItemStack(block));
// }
//
// public BasicEurekaCategory(String name, Item item) {
// this(name, new ItemStack(item));
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public ItemStack getDisplayStack() {
// return displayStack;
// }
// }
//
// Path: src/main/java/eureka/api/BasicEurekaInfo.java
// public class BasicEurekaInfo implements IEurekaInfo {
// private final String category, name;
// private final int maxProgress;
// private final ItemStack displayStack;
// private final List<String> requiredResearch;
//
// public BasicEurekaInfo(String name, String category, int maxProgress, ItemStack displayStack, String... requiredResearch) {
// this.name = name;
// this.category = category;
// this.maxProgress = maxProgress;
// this.displayStack = displayStack;
// List<String> research = new ArrayList<String>();
// research.addAll(Arrays.asList(requiredResearch));
// this.requiredResearch = research;
// }
//
// public BasicEurekaInfo(String name, String category, int maxProgress, Item item, String... requiredResearch) {
// this(name, category, maxProgress, new ItemStack(item), requiredResearch);
// }
//
// public BasicEurekaInfo(String name, String category, int maxProgress, Block block, String... requiredResearch) {
// this(name, category, maxProgress, new ItemStack(block), requiredResearch);
// }
//
// @Override
// public String getCategory() {
// return category;
// }
//
// @Override
// public int getMaxProgress() {
// return maxProgress;
// }
//
// @Override
// public ItemStack getDisplayStack() {
// return displayStack;
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public List<String> getRequiredResearch() {
// return requiredResearch;
// }
// }
//
// Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
//
// Path: src/main/java/eureka/core/Logger.java
// public class Logger {
//
// public static final org.apache.logging.log4j.Logger logger = LogManager.getLogger("Eureka");
//
// public static void info(String message) {
// logger.info(message);
// }
//
// public static void error(String message) {
// logger.error(message);
// }
// }
// Path: src/main/java/eureka/json/ConfigReader.java
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.registry.GameRegistry;
import eureka.api.BasicEurekaCategory;
import eureka.api.BasicEurekaInfo;
import eureka.api.EurekaAPI;
import eureka.core.Logger;
createFolderIfNeeded(new File(localizations, "en_US"));
if (!catagoryFolder.exists())
return;
for (File file : catagoryFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".json");
}
})) {
readCategory(file);
}
if (!keyFolder.exists())
return;
for (File file : keyFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".json");
}
})) {
readKey(file);
}
}
private static void readCategory(File file) {
try {
JSONCategory category = gson.fromJson(new FileReader(file), JSONCategory.class);
EurekaAPI.API.registerCategory(new BasicEurekaCategory(category.name, getStack(category.displayStack)));
} catch (Throwable t) { | Logger.error("Failed to read category file (" + file.getName() + ")"); |
AEnterprise/Eureka | src/main/java/eureka/json/ConfigReader.java | // Path: src/main/java/eureka/api/BasicEurekaCategory.java
// public class BasicEurekaCategory implements ICategory {
// private final String name;
// private final ItemStack displayStack;
//
// public BasicEurekaCategory(String name, ItemStack displayStack) {
// this.name = name;
// this.displayStack = displayStack;
// }
//
// public BasicEurekaCategory(String name, Block block) {
// this(name, new ItemStack(block));
// }
//
// public BasicEurekaCategory(String name, Item item) {
// this(name, new ItemStack(item));
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public ItemStack getDisplayStack() {
// return displayStack;
// }
// }
//
// Path: src/main/java/eureka/api/BasicEurekaInfo.java
// public class BasicEurekaInfo implements IEurekaInfo {
// private final String category, name;
// private final int maxProgress;
// private final ItemStack displayStack;
// private final List<String> requiredResearch;
//
// public BasicEurekaInfo(String name, String category, int maxProgress, ItemStack displayStack, String... requiredResearch) {
// this.name = name;
// this.category = category;
// this.maxProgress = maxProgress;
// this.displayStack = displayStack;
// List<String> research = new ArrayList<String>();
// research.addAll(Arrays.asList(requiredResearch));
// this.requiredResearch = research;
// }
//
// public BasicEurekaInfo(String name, String category, int maxProgress, Item item, String... requiredResearch) {
// this(name, category, maxProgress, new ItemStack(item), requiredResearch);
// }
//
// public BasicEurekaInfo(String name, String category, int maxProgress, Block block, String... requiredResearch) {
// this(name, category, maxProgress, new ItemStack(block), requiredResearch);
// }
//
// @Override
// public String getCategory() {
// return category;
// }
//
// @Override
// public int getMaxProgress() {
// return maxProgress;
// }
//
// @Override
// public ItemStack getDisplayStack() {
// return displayStack;
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public List<String> getRequiredResearch() {
// return requiredResearch;
// }
// }
//
// Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
//
// Path: src/main/java/eureka/core/Logger.java
// public class Logger {
//
// public static final org.apache.logging.log4j.Logger logger = LogManager.getLogger("Eureka");
//
// public static void info(String message) {
// logger.info(message);
// }
//
// public static void error(String message) {
// logger.error(message);
// }
// }
| import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.registry.GameRegistry;
import eureka.api.BasicEurekaCategory;
import eureka.api.BasicEurekaInfo;
import eureka.api.EurekaAPI;
import eureka.core.Logger; | })) {
readCategory(file);
}
if (!keyFolder.exists())
return;
for (File file : keyFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".json");
}
})) {
readKey(file);
}
}
private static void readCategory(File file) {
try {
JSONCategory category = gson.fromJson(new FileReader(file), JSONCategory.class);
EurekaAPI.API.registerCategory(new BasicEurekaCategory(category.name, getStack(category.displayStack)));
} catch (Throwable t) {
Logger.error("Failed to read category file (" + file.getName() + ")");
}
}
private static void readKey(File file) {
try {
JSONChapter chapter = gson.fromJson(new FileReader(file), JSONChapter.class);
List<ItemStack> objects = new ArrayList<ItemStack>();
for (String stack : chapter.blockedObjects)
objects.add(getStack(stack)); | // Path: src/main/java/eureka/api/BasicEurekaCategory.java
// public class BasicEurekaCategory implements ICategory {
// private final String name;
// private final ItemStack displayStack;
//
// public BasicEurekaCategory(String name, ItemStack displayStack) {
// this.name = name;
// this.displayStack = displayStack;
// }
//
// public BasicEurekaCategory(String name, Block block) {
// this(name, new ItemStack(block));
// }
//
// public BasicEurekaCategory(String name, Item item) {
// this(name, new ItemStack(item));
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public ItemStack getDisplayStack() {
// return displayStack;
// }
// }
//
// Path: src/main/java/eureka/api/BasicEurekaInfo.java
// public class BasicEurekaInfo implements IEurekaInfo {
// private final String category, name;
// private final int maxProgress;
// private final ItemStack displayStack;
// private final List<String> requiredResearch;
//
// public BasicEurekaInfo(String name, String category, int maxProgress, ItemStack displayStack, String... requiredResearch) {
// this.name = name;
// this.category = category;
// this.maxProgress = maxProgress;
// this.displayStack = displayStack;
// List<String> research = new ArrayList<String>();
// research.addAll(Arrays.asList(requiredResearch));
// this.requiredResearch = research;
// }
//
// public BasicEurekaInfo(String name, String category, int maxProgress, Item item, String... requiredResearch) {
// this(name, category, maxProgress, new ItemStack(item), requiredResearch);
// }
//
// public BasicEurekaInfo(String name, String category, int maxProgress, Block block, String... requiredResearch) {
// this(name, category, maxProgress, new ItemStack(block), requiredResearch);
// }
//
// @Override
// public String getCategory() {
// return category;
// }
//
// @Override
// public int getMaxProgress() {
// return maxProgress;
// }
//
// @Override
// public ItemStack getDisplayStack() {
// return displayStack;
// }
//
// @Override
// public String getName() {
// return name;
// }
//
// @Override
// public List<String> getRequiredResearch() {
// return requiredResearch;
// }
// }
//
// Path: src/main/java/eureka/api/EurekaAPI.java
// public class EurekaAPI {
//
// public static IEurekAPI API;
// }
//
// Path: src/main/java/eureka/core/Logger.java
// public class Logger {
//
// public static final org.apache.logging.log4j.Logger logger = LogManager.getLogger("Eureka");
//
// public static void info(String message) {
// logger.info(message);
// }
//
// public static void error(String message) {
// logger.error(message);
// }
// }
// Path: src/main/java/eureka/json/ConfigReader.java
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.registry.GameRegistry;
import eureka.api.BasicEurekaCategory;
import eureka.api.BasicEurekaInfo;
import eureka.api.EurekaAPI;
import eureka.core.Logger;
})) {
readCategory(file);
}
if (!keyFolder.exists())
return;
for (File file : keyFolder.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".json");
}
})) {
readKey(file);
}
}
private static void readCategory(File file) {
try {
JSONCategory category = gson.fromJson(new FileReader(file), JSONCategory.class);
EurekaAPI.API.registerCategory(new BasicEurekaCategory(category.name, getStack(category.displayStack)));
} catch (Throwable t) {
Logger.error("Failed to read category file (" + file.getName() + ")");
}
}
private static void readKey(File file) {
try {
JSONChapter chapter = gson.fromJson(new FileReader(file), JSONChapter.class);
List<ItemStack> objects = new ArrayList<ItemStack>();
for (String stack : chapter.blockedObjects)
objects.add(getStack(stack)); | EurekaAPI.API.register(new BasicEurekaInfo(chapter.name, chapter.category, chapter.maxProgress, getStack(chapter.displayStack), chapter.requiredResearch.toArray(new String[100]))); |
mikljohansson/retroboy | app/src/main/java/se/embargo/retroboy/filter/RasterFilter.java | // Path: app/src/main/java/se/embargo/retroboy/color/IColorDistance.java
// public interface IColorDistance {
// /**
// * @return A number between 0 and 1 indicating the color distance.
// */
// public double get(int r1,int g1,int b1, int r2,int g2,int b2);
// }
| import se.embargo.core.concurrent.IForBody;
import se.embargo.core.concurrent.Parallel;
import se.embargo.retroboy.color.IColorDistance;
import android.content.Context;
| package se.embargo.retroboy.filter;
/**
* 2-tone raster dithering as used on most Amstrad CPC games.
*/
public class RasterFilter extends AbstractColorFilter {
/**
* Version number for the cache files
*/
private static final int CACHE_VERSION_NUMBER = 10;
/**
* Number of integers per bucket.
*/
private static final int COLOR_BUCKET_SIZE = 2;
/**
* Dither matrix.
*/
private final int[] _matrix;
/**
* Length of matrix side.
*/
private final int _patternsize;
/**
* Ratio of color mixing.
*/
private final int _mixingratio;
/**
* Divisor for the too-far-apart color penalty.
*/
private final double _penaltyDivisor;
/**
* Parallel functor used to process frames.
*/
private final IForBody<ImageBuffer> _body = new ColorBody();
/**
* @param context Context running the filter
* @param distance Measure for color distance
* @param colors Palette of available colors
* @param matrix Dithering matrix to use
* @param rasterlevel Level of rastering to apply
*/
| // Path: app/src/main/java/se/embargo/retroboy/color/IColorDistance.java
// public interface IColorDistance {
// /**
// * @return A number between 0 and 1 indicating the color distance.
// */
// public double get(int r1,int g1,int b1, int r2,int g2,int b2);
// }
// Path: app/src/main/java/se/embargo/retroboy/filter/RasterFilter.java
import se.embargo.core.concurrent.IForBody;
import se.embargo.core.concurrent.Parallel;
import se.embargo.retroboy.color.IColorDistance;
import android.content.Context;
package se.embargo.retroboy.filter;
/**
* 2-tone raster dithering as used on most Amstrad CPC games.
*/
public class RasterFilter extends AbstractColorFilter {
/**
* Version number for the cache files
*/
private static final int CACHE_VERSION_NUMBER = 10;
/**
* Number of integers per bucket.
*/
private static final int COLOR_BUCKET_SIZE = 2;
/**
* Dither matrix.
*/
private final int[] _matrix;
/**
* Length of matrix side.
*/
private final int _patternsize;
/**
* Ratio of color mixing.
*/
private final int _mixingratio;
/**
* Divisor for the too-far-apart color penalty.
*/
private final double _penaltyDivisor;
/**
* Parallel functor used to process frames.
*/
private final IForBody<ImageBuffer> _body = new ColorBody();
/**
* @param context Context running the filter
* @param distance Measure for color distance
* @param colors Palette of available colors
* @param matrix Dithering matrix to use
* @param rasterlevel Level of rastering to apply
*/
| public RasterFilter(Context context, IColorDistance distance, int[] colors, int[] matrix, int rasterlevel) {
|
mikljohansson/retroboy | app/src/main/java/se/embargo/retroboy/filter/Pxl2000Filter.java | // Path: app/src/main/java/se/embargo/retroboy/color/MonochromePalette.java
// public class MonochromePalette implements IIndexedPalette {
// private final int _bits, _mask;
// private int[] _colors;
//
// public MonochromePalette(int bits) {
// _bits = bits;
// _mask = ~((1 << (8 - _bits)) - 1);
// _colors = new int[1 << bits];
//
// for (int i = 0; i < _colors.length; i++) {
// final int lum = i << (8 - bits);
// _colors[i] = 0xff000000 | (lum << 16) | (lum << 8) | lum;
// }
// }
//
// @Override
// public int getNearestColor(int r1, int g1, int b1) {
// return ((b1 & _mask) << 16) | ((g1 & _mask) << 8) | (r1 & _mask);
// }
//
// @Override
// public int getColorCount() {
// return _colors.length;
// }
//
// @Override
// public int[] getColors() {
// return _colors;
// }
//
// @Override
// public int getIndex(int color) {
// return (color & 0xff) >> (8 - _bits);
// }
// }
//
// Path: app/src/main/java/se/embargo/retroboy/graphic/GaussianBlur.java
// public class GaussianBlur {
// /**
// * Creates a Gaussian kernel.
// * @link http://www.swageroo.com/wordpress/how-to-program-a-gaussian-blur-without-using-3rd-party-libraries/
// * @param sigma Blurriness factor, e.g. 1.5
// * @param width Width of kernel in pixels
// * @param height Height of kernel in pixels
// * @return A matrix of weights to apply to neighboring pixels, size is width * height
// */
// public static float[] createKernel(double sigma, int width, int height) {
// if (width % 2 == 0 || height % 2 == 0) {
// throw new IllegalArgumentException("Width and height must be odd numbers");
// }
//
// float[] result = new float[width * height];
// int xoffset = width / 2, yoffset = height / 2;
//
// double base = 1 / (2 * Math.PI * sigma * sigma);
// double sum = 0;
//
// // Calculate all the weights
// for (int y = -yoffset, i = 0; y <= yoffset; y++) {
// for (int x = -xoffset; x <= xoffset; x++) {
// double weight = base * Math.exp(-((x * x + y * y) / (2 * sigma * sigma)));
// sum += weight;
// result[i++] = (float)weight;
// }
// }
//
// // Normalize all the weights so the sum is 1
// for (int i = 0; i < result.length; i++) {
// result[i] = (float)((double)result[i] * (1 / sum));
// }
//
// return result;
// }
// }
| import java.util.Arrays;
import se.embargo.core.concurrent.IForBody;
import se.embargo.core.concurrent.Parallel;
import se.embargo.core.graphic.color.IIndexedPalette;
import se.embargo.core.graphic.color.IPalette;
import se.embargo.retroboy.color.MonochromePalette;
import se.embargo.retroboy.graphic.GaussianBlur;
| package se.embargo.retroboy.filter;
/**
* @link http://fox-gieg.com/tutorials/2008/fake-pxl2000-effect/
*/
public class Pxl2000Filter extends AbstractFilter {
private final double _bordersize = 0.125d;
private final FilterBody _body = new FilterBody();
| // Path: app/src/main/java/se/embargo/retroboy/color/MonochromePalette.java
// public class MonochromePalette implements IIndexedPalette {
// private final int _bits, _mask;
// private int[] _colors;
//
// public MonochromePalette(int bits) {
// _bits = bits;
// _mask = ~((1 << (8 - _bits)) - 1);
// _colors = new int[1 << bits];
//
// for (int i = 0; i < _colors.length; i++) {
// final int lum = i << (8 - bits);
// _colors[i] = 0xff000000 | (lum << 16) | (lum << 8) | lum;
// }
// }
//
// @Override
// public int getNearestColor(int r1, int g1, int b1) {
// return ((b1 & _mask) << 16) | ((g1 & _mask) << 8) | (r1 & _mask);
// }
//
// @Override
// public int getColorCount() {
// return _colors.length;
// }
//
// @Override
// public int[] getColors() {
// return _colors;
// }
//
// @Override
// public int getIndex(int color) {
// return (color & 0xff) >> (8 - _bits);
// }
// }
//
// Path: app/src/main/java/se/embargo/retroboy/graphic/GaussianBlur.java
// public class GaussianBlur {
// /**
// * Creates a Gaussian kernel.
// * @link http://www.swageroo.com/wordpress/how-to-program-a-gaussian-blur-without-using-3rd-party-libraries/
// * @param sigma Blurriness factor, e.g. 1.5
// * @param width Width of kernel in pixels
// * @param height Height of kernel in pixels
// * @return A matrix of weights to apply to neighboring pixels, size is width * height
// */
// public static float[] createKernel(double sigma, int width, int height) {
// if (width % 2 == 0 || height % 2 == 0) {
// throw new IllegalArgumentException("Width and height must be odd numbers");
// }
//
// float[] result = new float[width * height];
// int xoffset = width / 2, yoffset = height / 2;
//
// double base = 1 / (2 * Math.PI * sigma * sigma);
// double sum = 0;
//
// // Calculate all the weights
// for (int y = -yoffset, i = 0; y <= yoffset; y++) {
// for (int x = -xoffset; x <= xoffset; x++) {
// double weight = base * Math.exp(-((x * x + y * y) / (2 * sigma * sigma)));
// sum += weight;
// result[i++] = (float)weight;
// }
// }
//
// // Normalize all the weights so the sum is 1
// for (int i = 0; i < result.length; i++) {
// result[i] = (float)((double)result[i] * (1 / sum));
// }
//
// return result;
// }
// }
// Path: app/src/main/java/se/embargo/retroboy/filter/Pxl2000Filter.java
import java.util.Arrays;
import se.embargo.core.concurrent.IForBody;
import se.embargo.core.concurrent.Parallel;
import se.embargo.core.graphic.color.IIndexedPalette;
import se.embargo.core.graphic.color.IPalette;
import se.embargo.retroboy.color.MonochromePalette;
import se.embargo.retroboy.graphic.GaussianBlur;
package se.embargo.retroboy.filter;
/**
* @link http://fox-gieg.com/tutorials/2008/fake-pxl2000-effect/
*/
public class Pxl2000Filter extends AbstractFilter {
private final double _bordersize = 0.125d;
private final FilterBody _body = new FilterBody();
| private final IIndexedPalette _palette = new MonochromePalette(7);
|
mikljohansson/retroboy | app/src/main/java/se/embargo/retroboy/filter/Pxl2000Filter.java | // Path: app/src/main/java/se/embargo/retroboy/color/MonochromePalette.java
// public class MonochromePalette implements IIndexedPalette {
// private final int _bits, _mask;
// private int[] _colors;
//
// public MonochromePalette(int bits) {
// _bits = bits;
// _mask = ~((1 << (8 - _bits)) - 1);
// _colors = new int[1 << bits];
//
// for (int i = 0; i < _colors.length; i++) {
// final int lum = i << (8 - bits);
// _colors[i] = 0xff000000 | (lum << 16) | (lum << 8) | lum;
// }
// }
//
// @Override
// public int getNearestColor(int r1, int g1, int b1) {
// return ((b1 & _mask) << 16) | ((g1 & _mask) << 8) | (r1 & _mask);
// }
//
// @Override
// public int getColorCount() {
// return _colors.length;
// }
//
// @Override
// public int[] getColors() {
// return _colors;
// }
//
// @Override
// public int getIndex(int color) {
// return (color & 0xff) >> (8 - _bits);
// }
// }
//
// Path: app/src/main/java/se/embargo/retroboy/graphic/GaussianBlur.java
// public class GaussianBlur {
// /**
// * Creates a Gaussian kernel.
// * @link http://www.swageroo.com/wordpress/how-to-program-a-gaussian-blur-without-using-3rd-party-libraries/
// * @param sigma Blurriness factor, e.g. 1.5
// * @param width Width of kernel in pixels
// * @param height Height of kernel in pixels
// * @return A matrix of weights to apply to neighboring pixels, size is width * height
// */
// public static float[] createKernel(double sigma, int width, int height) {
// if (width % 2 == 0 || height % 2 == 0) {
// throw new IllegalArgumentException("Width and height must be odd numbers");
// }
//
// float[] result = new float[width * height];
// int xoffset = width / 2, yoffset = height / 2;
//
// double base = 1 / (2 * Math.PI * sigma * sigma);
// double sum = 0;
//
// // Calculate all the weights
// for (int y = -yoffset, i = 0; y <= yoffset; y++) {
// for (int x = -xoffset; x <= xoffset; x++) {
// double weight = base * Math.exp(-((x * x + y * y) / (2 * sigma * sigma)));
// sum += weight;
// result[i++] = (float)weight;
// }
// }
//
// // Normalize all the weights so the sum is 1
// for (int i = 0; i < result.length; i++) {
// result[i] = (float)((double)result[i] * (1 / sum));
// }
//
// return result;
// }
// }
| import java.util.Arrays;
import se.embargo.core.concurrent.IForBody;
import se.embargo.core.concurrent.Parallel;
import se.embargo.core.graphic.color.IIndexedPalette;
import se.embargo.core.graphic.color.IPalette;
import se.embargo.retroboy.color.MonochromePalette;
import se.embargo.retroboy.graphic.GaussianBlur;
| package se.embargo.retroboy.filter;
/**
* @link http://fox-gieg.com/tutorials/2008/fake-pxl2000-effect/
*/
public class Pxl2000Filter extends AbstractFilter {
private final double _bordersize = 0.125d;
private final FilterBody _body = new FilterBody();
private final IIndexedPalette _palette = new MonochromePalette(7);
/**
* Amount of blurring
*/
| // Path: app/src/main/java/se/embargo/retroboy/color/MonochromePalette.java
// public class MonochromePalette implements IIndexedPalette {
// private final int _bits, _mask;
// private int[] _colors;
//
// public MonochromePalette(int bits) {
// _bits = bits;
// _mask = ~((1 << (8 - _bits)) - 1);
// _colors = new int[1 << bits];
//
// for (int i = 0; i < _colors.length; i++) {
// final int lum = i << (8 - bits);
// _colors[i] = 0xff000000 | (lum << 16) | (lum << 8) | lum;
// }
// }
//
// @Override
// public int getNearestColor(int r1, int g1, int b1) {
// return ((b1 & _mask) << 16) | ((g1 & _mask) << 8) | (r1 & _mask);
// }
//
// @Override
// public int getColorCount() {
// return _colors.length;
// }
//
// @Override
// public int[] getColors() {
// return _colors;
// }
//
// @Override
// public int getIndex(int color) {
// return (color & 0xff) >> (8 - _bits);
// }
// }
//
// Path: app/src/main/java/se/embargo/retroboy/graphic/GaussianBlur.java
// public class GaussianBlur {
// /**
// * Creates a Gaussian kernel.
// * @link http://www.swageroo.com/wordpress/how-to-program-a-gaussian-blur-without-using-3rd-party-libraries/
// * @param sigma Blurriness factor, e.g. 1.5
// * @param width Width of kernel in pixels
// * @param height Height of kernel in pixels
// * @return A matrix of weights to apply to neighboring pixels, size is width * height
// */
// public static float[] createKernel(double sigma, int width, int height) {
// if (width % 2 == 0 || height % 2 == 0) {
// throw new IllegalArgumentException("Width and height must be odd numbers");
// }
//
// float[] result = new float[width * height];
// int xoffset = width / 2, yoffset = height / 2;
//
// double base = 1 / (2 * Math.PI * sigma * sigma);
// double sum = 0;
//
// // Calculate all the weights
// for (int y = -yoffset, i = 0; y <= yoffset; y++) {
// for (int x = -xoffset; x <= xoffset; x++) {
// double weight = base * Math.exp(-((x * x + y * y) / (2 * sigma * sigma)));
// sum += weight;
// result[i++] = (float)weight;
// }
// }
//
// // Normalize all the weights so the sum is 1
// for (int i = 0; i < result.length; i++) {
// result[i] = (float)((double)result[i] * (1 / sum));
// }
//
// return result;
// }
// }
// Path: app/src/main/java/se/embargo/retroboy/filter/Pxl2000Filter.java
import java.util.Arrays;
import se.embargo.core.concurrent.IForBody;
import se.embargo.core.concurrent.Parallel;
import se.embargo.core.graphic.color.IIndexedPalette;
import se.embargo.core.graphic.color.IPalette;
import se.embargo.retroboy.color.MonochromePalette;
import se.embargo.retroboy.graphic.GaussianBlur;
package se.embargo.retroboy.filter;
/**
* @link http://fox-gieg.com/tutorials/2008/fake-pxl2000-effect/
*/
public class Pxl2000Filter extends AbstractFilter {
private final double _bordersize = 0.125d;
private final FilterBody _body = new FilterBody();
private final IIndexedPalette _palette = new MonochromePalette(7);
/**
* Amount of blurring
*/
| private final float[] _blurkernel = GaussianBlur.createKernel(0.5d, 5, 3);
|
mikljohansson/retroboy | app/src/main/java/se/embargo/retroboy/filter/YliluomaFilter.java | // Path: app/src/main/java/se/embargo/retroboy/color/IColorDistance.java
// public interface IColorDistance {
// /**
// * @return A number between 0 and 1 indicating the color distance.
// */
// public double get(int r1,int g1,int b1, int r2,int g2,int b2);
// }
//
// Path: app/src/main/java/se/embargo/retroboy/graphic/DitherMatrixes.java
// public class DitherMatrixes {
// public static final int[] MATRIX_8x8 = new int[] {
// 1, 49, 13, 61, 4, 52, 16, 62,
// 33, 17, 45, 29, 36, 20, 48, 32,
// 9, 57, 5, 53, 12, 60, 8, 56,
// 41, 25, 37, 21, 44, 28, 40, 24,
// 3, 51, 15, 62, 2, 50, 14, 62,
// 35, 19, 47, 31, 34, 18, 46, 30,
// 11, 59, 7, 55, 10, 58, 6, 54,
// 43, 27, 39, 23, 42, 26, 38, 22};
//
// public static final int[] MATRIX_4x4 = new int[] {
// 1, 9, 3, 11,
// 13, 5, 15, 7,
// 4, 12, 2, 10,
// 15, 8, 14, 6};
//
// public static final int[] MATRIX_2x2 = new int[] {
// 0, 2,
// 3, 1};
// }
| import se.embargo.core.concurrent.IForBody;
import se.embargo.core.concurrent.Parallel;
import se.embargo.retroboy.color.IColorDistance;
import se.embargo.retroboy.graphic.DitherMatrixes;
import android.content.Context;
| package se.embargo.retroboy.filter;
/**
* 2-tone Yliluoma dithering.
* @link http://bisqwit.iki.fi/story/howto/dither/jy/
*/
public class YliluomaFilter extends AbstractColorFilter {
/**
* Number of integers per bucket.
*/
private static final int COLOR_BUCKET_SIZE = 3;
/**
* Dither matrix.
*/
| // Path: app/src/main/java/se/embargo/retroboy/color/IColorDistance.java
// public interface IColorDistance {
// /**
// * @return A number between 0 and 1 indicating the color distance.
// */
// public double get(int r1,int g1,int b1, int r2,int g2,int b2);
// }
//
// Path: app/src/main/java/se/embargo/retroboy/graphic/DitherMatrixes.java
// public class DitherMatrixes {
// public static final int[] MATRIX_8x8 = new int[] {
// 1, 49, 13, 61, 4, 52, 16, 62,
// 33, 17, 45, 29, 36, 20, 48, 32,
// 9, 57, 5, 53, 12, 60, 8, 56,
// 41, 25, 37, 21, 44, 28, 40, 24,
// 3, 51, 15, 62, 2, 50, 14, 62,
// 35, 19, 47, 31, 34, 18, 46, 30,
// 11, 59, 7, 55, 10, 58, 6, 54,
// 43, 27, 39, 23, 42, 26, 38, 22};
//
// public static final int[] MATRIX_4x4 = new int[] {
// 1, 9, 3, 11,
// 13, 5, 15, 7,
// 4, 12, 2, 10,
// 15, 8, 14, 6};
//
// public static final int[] MATRIX_2x2 = new int[] {
// 0, 2,
// 3, 1};
// }
// Path: app/src/main/java/se/embargo/retroboy/filter/YliluomaFilter.java
import se.embargo.core.concurrent.IForBody;
import se.embargo.core.concurrent.Parallel;
import se.embargo.retroboy.color.IColorDistance;
import se.embargo.retroboy.graphic.DitherMatrixes;
import android.content.Context;
package se.embargo.retroboy.filter;
/**
* 2-tone Yliluoma dithering.
* @link http://bisqwit.iki.fi/story/howto/dither/jy/
*/
public class YliluomaFilter extends AbstractColorFilter {
/**
* Number of integers per bucket.
*/
private static final int COLOR_BUCKET_SIZE = 3;
/**
* Dither matrix.
*/
| private static final int[] _matrix = DitherMatrixes.MATRIX_8x8;
|
mikljohansson/retroboy | app/src/main/java/se/embargo/retroboy/filter/YliluomaFilter.java | // Path: app/src/main/java/se/embargo/retroboy/color/IColorDistance.java
// public interface IColorDistance {
// /**
// * @return A number between 0 and 1 indicating the color distance.
// */
// public double get(int r1,int g1,int b1, int r2,int g2,int b2);
// }
//
// Path: app/src/main/java/se/embargo/retroboy/graphic/DitherMatrixes.java
// public class DitherMatrixes {
// public static final int[] MATRIX_8x8 = new int[] {
// 1, 49, 13, 61, 4, 52, 16, 62,
// 33, 17, 45, 29, 36, 20, 48, 32,
// 9, 57, 5, 53, 12, 60, 8, 56,
// 41, 25, 37, 21, 44, 28, 40, 24,
// 3, 51, 15, 62, 2, 50, 14, 62,
// 35, 19, 47, 31, 34, 18, 46, 30,
// 11, 59, 7, 55, 10, 58, 6, 54,
// 43, 27, 39, 23, 42, 26, 38, 22};
//
// public static final int[] MATRIX_4x4 = new int[] {
// 1, 9, 3, 11,
// 13, 5, 15, 7,
// 4, 12, 2, 10,
// 15, 8, 14, 6};
//
// public static final int[] MATRIX_2x2 = new int[] {
// 0, 2,
// 3, 1};
// }
| import se.embargo.core.concurrent.IForBody;
import se.embargo.core.concurrent.Parallel;
import se.embargo.retroboy.color.IColorDistance;
import se.embargo.retroboy.graphic.DitherMatrixes;
import android.content.Context;
| package se.embargo.retroboy.filter;
/**
* 2-tone Yliluoma dithering.
* @link http://bisqwit.iki.fi/story/howto/dither/jy/
*/
public class YliluomaFilter extends AbstractColorFilter {
/**
* Number of integers per bucket.
*/
private static final int COLOR_BUCKET_SIZE = 3;
/**
* Dither matrix.
*/
private static final int[] _matrix = DitherMatrixes.MATRIX_8x8;
/**
* Length of matrix side.
*/
private static final int _patternsize = (int)Math.sqrt(_matrix.length);
/**
* Ratio of color mixing.
*/
private static final int _mixingRatio = _matrix.length / 2;
/**
* Version number for the cache files
*/
private static final int CACHE_VERSION_NUMBER = 6 | (_matrix.length << 16);
/**
* Parallel functor used to process frames.
*/
private final IForBody<ImageBuffer> _body = new ColorBody();
| // Path: app/src/main/java/se/embargo/retroboy/color/IColorDistance.java
// public interface IColorDistance {
// /**
// * @return A number between 0 and 1 indicating the color distance.
// */
// public double get(int r1,int g1,int b1, int r2,int g2,int b2);
// }
//
// Path: app/src/main/java/se/embargo/retroboy/graphic/DitherMatrixes.java
// public class DitherMatrixes {
// public static final int[] MATRIX_8x8 = new int[] {
// 1, 49, 13, 61, 4, 52, 16, 62,
// 33, 17, 45, 29, 36, 20, 48, 32,
// 9, 57, 5, 53, 12, 60, 8, 56,
// 41, 25, 37, 21, 44, 28, 40, 24,
// 3, 51, 15, 62, 2, 50, 14, 62,
// 35, 19, 47, 31, 34, 18, 46, 30,
// 11, 59, 7, 55, 10, 58, 6, 54,
// 43, 27, 39, 23, 42, 26, 38, 22};
//
// public static final int[] MATRIX_4x4 = new int[] {
// 1, 9, 3, 11,
// 13, 5, 15, 7,
// 4, 12, 2, 10,
// 15, 8, 14, 6};
//
// public static final int[] MATRIX_2x2 = new int[] {
// 0, 2,
// 3, 1};
// }
// Path: app/src/main/java/se/embargo/retroboy/filter/YliluomaFilter.java
import se.embargo.core.concurrent.IForBody;
import se.embargo.core.concurrent.Parallel;
import se.embargo.retroboy.color.IColorDistance;
import se.embargo.retroboy.graphic.DitherMatrixes;
import android.content.Context;
package se.embargo.retroboy.filter;
/**
* 2-tone Yliluoma dithering.
* @link http://bisqwit.iki.fi/story/howto/dither/jy/
*/
public class YliluomaFilter extends AbstractColorFilter {
/**
* Number of integers per bucket.
*/
private static final int COLOR_BUCKET_SIZE = 3;
/**
* Dither matrix.
*/
private static final int[] _matrix = DitherMatrixes.MATRIX_8x8;
/**
* Length of matrix side.
*/
private static final int _patternsize = (int)Math.sqrt(_matrix.length);
/**
* Ratio of color mixing.
*/
private static final int _mixingRatio = _matrix.length / 2;
/**
* Version number for the cache files
*/
private static final int CACHE_VERSION_NUMBER = 6 | (_matrix.length << 16);
/**
* Parallel functor used to process frames.
*/
private final IForBody<ImageBuffer> _body = new ColorBody();
| public YliluomaFilter(Context context, IColorDistance distance, int[] palette) {
|
mikljohansson/retroboy | app/src/main/java/se/embargo/retroboy/filter/YliluomaTriFilter.java | // Path: app/src/main/java/se/embargo/retroboy/color/IColorDistance.java
// public interface IColorDistance {
// /**
// * @return A number between 0 and 1 indicating the color distance.
// */
// public double get(int r1,int g1,int b1, int r2,int g2,int b2);
// }
//
// Path: app/src/main/java/se/embargo/retroboy/graphic/DitherMatrixes.java
// public class DitherMatrixes {
// public static final int[] MATRIX_8x8 = new int[] {
// 1, 49, 13, 61, 4, 52, 16, 62,
// 33, 17, 45, 29, 36, 20, 48, 32,
// 9, 57, 5, 53, 12, 60, 8, 56,
// 41, 25, 37, 21, 44, 28, 40, 24,
// 3, 51, 15, 62, 2, 50, 14, 62,
// 35, 19, 47, 31, 34, 18, 46, 30,
// 11, 59, 7, 55, 10, 58, 6, 54,
// 43, 27, 39, 23, 42, 26, 38, 22};
//
// public static final int[] MATRIX_4x4 = new int[] {
// 1, 9, 3, 11,
// 13, 5, 15, 7,
// 4, 12, 2, 10,
// 15, 8, 14, 6};
//
// public static final int[] MATRIX_2x2 = new int[] {
// 0, 2,
// 3, 1};
// }
| import se.embargo.core.concurrent.IForBody;
import se.embargo.core.concurrent.Parallel;
import se.embargo.retroboy.color.IColorDistance;
import se.embargo.retroboy.graphic.DitherMatrixes;
import android.content.Context;
| package se.embargo.retroboy.filter;
/**
* 3-tone Yliluoma dithering.
* @link http://bisqwit.iki.fi/story/howto/dither/jy/
*/
public class YliluomaTriFilter extends AbstractColorFilter {
/**
* Number of integers per bucket.
*/
private static final int COLOR_BUCKET_SIZE = 5;
/**
* Dither matrix.
*/
| // Path: app/src/main/java/se/embargo/retroboy/color/IColorDistance.java
// public interface IColorDistance {
// /**
// * @return A number between 0 and 1 indicating the color distance.
// */
// public double get(int r1,int g1,int b1, int r2,int g2,int b2);
// }
//
// Path: app/src/main/java/se/embargo/retroboy/graphic/DitherMatrixes.java
// public class DitherMatrixes {
// public static final int[] MATRIX_8x8 = new int[] {
// 1, 49, 13, 61, 4, 52, 16, 62,
// 33, 17, 45, 29, 36, 20, 48, 32,
// 9, 57, 5, 53, 12, 60, 8, 56,
// 41, 25, 37, 21, 44, 28, 40, 24,
// 3, 51, 15, 62, 2, 50, 14, 62,
// 35, 19, 47, 31, 34, 18, 46, 30,
// 11, 59, 7, 55, 10, 58, 6, 54,
// 43, 27, 39, 23, 42, 26, 38, 22};
//
// public static final int[] MATRIX_4x4 = new int[] {
// 1, 9, 3, 11,
// 13, 5, 15, 7,
// 4, 12, 2, 10,
// 15, 8, 14, 6};
//
// public static final int[] MATRIX_2x2 = new int[] {
// 0, 2,
// 3, 1};
// }
// Path: app/src/main/java/se/embargo/retroboy/filter/YliluomaTriFilter.java
import se.embargo.core.concurrent.IForBody;
import se.embargo.core.concurrent.Parallel;
import se.embargo.retroboy.color.IColorDistance;
import se.embargo.retroboy.graphic.DitherMatrixes;
import android.content.Context;
package se.embargo.retroboy.filter;
/**
* 3-tone Yliluoma dithering.
* @link http://bisqwit.iki.fi/story/howto/dither/jy/
*/
public class YliluomaTriFilter extends AbstractColorFilter {
/**
* Number of integers per bucket.
*/
private static final int COLOR_BUCKET_SIZE = 5;
/**
* Dither matrix.
*/
| private static final int[] _matrix = DitherMatrixes.MATRIX_8x8;
|
mikljohansson/retroboy | app/src/main/java/se/embargo/retroboy/filter/YliluomaTriFilter.java | // Path: app/src/main/java/se/embargo/retroboy/color/IColorDistance.java
// public interface IColorDistance {
// /**
// * @return A number between 0 and 1 indicating the color distance.
// */
// public double get(int r1,int g1,int b1, int r2,int g2,int b2);
// }
//
// Path: app/src/main/java/se/embargo/retroboy/graphic/DitherMatrixes.java
// public class DitherMatrixes {
// public static final int[] MATRIX_8x8 = new int[] {
// 1, 49, 13, 61, 4, 52, 16, 62,
// 33, 17, 45, 29, 36, 20, 48, 32,
// 9, 57, 5, 53, 12, 60, 8, 56,
// 41, 25, 37, 21, 44, 28, 40, 24,
// 3, 51, 15, 62, 2, 50, 14, 62,
// 35, 19, 47, 31, 34, 18, 46, 30,
// 11, 59, 7, 55, 10, 58, 6, 54,
// 43, 27, 39, 23, 42, 26, 38, 22};
//
// public static final int[] MATRIX_4x4 = new int[] {
// 1, 9, 3, 11,
// 13, 5, 15, 7,
// 4, 12, 2, 10,
// 15, 8, 14, 6};
//
// public static final int[] MATRIX_2x2 = new int[] {
// 0, 2,
// 3, 1};
// }
| import se.embargo.core.concurrent.IForBody;
import se.embargo.core.concurrent.Parallel;
import se.embargo.retroboy.color.IColorDistance;
import se.embargo.retroboy.graphic.DitherMatrixes;
import android.content.Context;
| package se.embargo.retroboy.filter;
/**
* 3-tone Yliluoma dithering.
* @link http://bisqwit.iki.fi/story/howto/dither/jy/
*/
public class YliluomaTriFilter extends AbstractColorFilter {
/**
* Number of integers per bucket.
*/
private static final int COLOR_BUCKET_SIZE = 5;
/**
* Dither matrix.
*/
private static final int[] _matrix = DitherMatrixes.MATRIX_8x8;
/**
* Length of matrix side.
*/
private static final int _patternsize = (int)Math.sqrt(_matrix.length);
/**
* Ratio of color mixing.
*/
private static final int _mixingRatio = _matrix.length / 2;
/**
* Version number for the cache files
*/
private static final int CACHE_VERSION_NUMBER = 6 | (_matrix.length << 16);
/**
* Parallel functor used to process frames.
*/
private final IForBody<ImageBuffer> _body = new ColorBody();
| // Path: app/src/main/java/se/embargo/retroboy/color/IColorDistance.java
// public interface IColorDistance {
// /**
// * @return A number between 0 and 1 indicating the color distance.
// */
// public double get(int r1,int g1,int b1, int r2,int g2,int b2);
// }
//
// Path: app/src/main/java/se/embargo/retroboy/graphic/DitherMatrixes.java
// public class DitherMatrixes {
// public static final int[] MATRIX_8x8 = new int[] {
// 1, 49, 13, 61, 4, 52, 16, 62,
// 33, 17, 45, 29, 36, 20, 48, 32,
// 9, 57, 5, 53, 12, 60, 8, 56,
// 41, 25, 37, 21, 44, 28, 40, 24,
// 3, 51, 15, 62, 2, 50, 14, 62,
// 35, 19, 47, 31, 34, 18, 46, 30,
// 11, 59, 7, 55, 10, 58, 6, 54,
// 43, 27, 39, 23, 42, 26, 38, 22};
//
// public static final int[] MATRIX_4x4 = new int[] {
// 1, 9, 3, 11,
// 13, 5, 15, 7,
// 4, 12, 2, 10,
// 15, 8, 14, 6};
//
// public static final int[] MATRIX_2x2 = new int[] {
// 0, 2,
// 3, 1};
// }
// Path: app/src/main/java/se/embargo/retroboy/filter/YliluomaTriFilter.java
import se.embargo.core.concurrent.IForBody;
import se.embargo.core.concurrent.Parallel;
import se.embargo.retroboy.color.IColorDistance;
import se.embargo.retroboy.graphic.DitherMatrixes;
import android.content.Context;
package se.embargo.retroboy.filter;
/**
* 3-tone Yliluoma dithering.
* @link http://bisqwit.iki.fi/story/howto/dither/jy/
*/
public class YliluomaTriFilter extends AbstractColorFilter {
/**
* Number of integers per bucket.
*/
private static final int COLOR_BUCKET_SIZE = 5;
/**
* Dither matrix.
*/
private static final int[] _matrix = DitherMatrixes.MATRIX_8x8;
/**
* Length of matrix side.
*/
private static final int _patternsize = (int)Math.sqrt(_matrix.length);
/**
* Ratio of color mixing.
*/
private static final int _mixingRatio = _matrix.length / 2;
/**
* Version number for the cache files
*/
private static final int CACHE_VERSION_NUMBER = 6 | (_matrix.length << 16);
/**
* Parallel functor used to process frames.
*/
private final IForBody<ImageBuffer> _body = new ColorBody();
| public YliluomaTriFilter(Context context, IColorDistance distance, int[] palette) {
|
sweer/hex-image-compress | src/lattice/HexSystem.java | // Path: src/util/MathUtils.java
// public class MathUtils {
//
// public static double[] multiplyVectorByMatrix(double[] vector,
// double[][] matrix) {
// double result[] = new double[matrix[0].length];
//
// for (int i = 0; i < matrix[0].length; i++) {
// double sum = 0;
// for (int j = 0; j < vector.length; j++) {
// sum += vector[j] * matrix[j][i];
// }
// result[i] = sum;
// }
//
// return result;
// }
//
// public static double[][] multiplyMatrixByNumber(double[][] matrix,
// double number) {
// double result[][] = new double[matrix.length][];
//
// for (int i = 0; i < matrix.length; i++) {
// result[i] = new double[matrix[i].length];
// for (int j = 0; j < matrix[i].length; j++) {
// result[i][j] = matrix[i][j] * number;
// }
// }
//
// return result;
// }
//
// public static double[][] invert2x2Matrix(double[][] matrix) {
// double determinant = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
// return new double[][] { { matrix[1][1]/determinant, - matrix[0][1]/determinant },
// { - matrix[1][0]/determinant, matrix[0][0]/determinant }
// };
//
// }
//
// }
| import util.MathUtils;
| package lattice;
public class HexSystem {
public static final double[][] hexBaseMatrix = { { 1, 0 },
{ 0.5, Math.sqrt(3) / 2.0 } };
| // Path: src/util/MathUtils.java
// public class MathUtils {
//
// public static double[] multiplyVectorByMatrix(double[] vector,
// double[][] matrix) {
// double result[] = new double[matrix[0].length];
//
// for (int i = 0; i < matrix[0].length; i++) {
// double sum = 0;
// for (int j = 0; j < vector.length; j++) {
// sum += vector[j] * matrix[j][i];
// }
// result[i] = sum;
// }
//
// return result;
// }
//
// public static double[][] multiplyMatrixByNumber(double[][] matrix,
// double number) {
// double result[][] = new double[matrix.length][];
//
// for (int i = 0; i < matrix.length; i++) {
// result[i] = new double[matrix[i].length];
// for (int j = 0; j < matrix[i].length; j++) {
// result[i][j] = matrix[i][j] * number;
// }
// }
//
// return result;
// }
//
// public static double[][] invert2x2Matrix(double[][] matrix) {
// double determinant = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
// return new double[][] { { matrix[1][1]/determinant, - matrix[0][1]/determinant },
// { - matrix[1][0]/determinant, matrix[0][0]/determinant }
// };
//
// }
//
// }
// Path: src/lattice/HexSystem.java
import util.MathUtils;
package lattice;
public class HexSystem {
public static final double[][] hexBaseMatrix = { { 1, 0 },
{ 0.5, Math.sqrt(3) / 2.0 } };
| public static final double[][] hexBaseMatrixDensity1 = MathUtils
|
sweer/hex-image-compress | src/test/util/ArrayUtilsTest.java | // Path: src/test/TestUtils.java
// public static final double DELTA = 0.00000001;
//
// Path: src/util/ArrayUtils.java
// public class ArrayUtils {
//
// public static double[] subtract2DArraysAs1D(double[][] a, double[][] b) {
// int height = a.length;
// int width = a[0].length;
// double[] result = new double[height * width];
// int i = 0;
// for (int y = 0; y < height; y++) {
// for (int x = 0; x < width; x++) {
// result[i++] = a[y][x] - b[y][x];
// }
// }
// return result;
// }
//
// public static long[][] copyOfArray(long[][] src) {
// long[][] dst = new long[src.length][];
// for (int i = 0; i < src.length; i++) {
// dst[i] = Arrays.copyOf(src[i], src[i].length);
// }
// return dst;
// }
//
//
// public static boolean arraysAreCloseEnough(double[][] expected, double[][] actual, double delta) {
// for (int i = 0; i < expected.length; i++) {
// for (int j = 0; j < expected[i].length; j++) {
// if (Double.isNaN(expected[i][j]) && Double.isNaN(actual[i][j]))
// continue;
// if (Double.isNaN(expected[i][j]) || Double.isNaN(actual[i][j])
// || Math.abs(expected[i][j] - actual[i][j]) > delta) {
// System.out.println("arraysAreCloseEnough failed at YX[" + i + "," + j + "], value "
// + actual[i][j] + " differs from expected " + expected[i][j]);
// return false;
// }
// }
// }
// return true;
// }
//
// public static void saveArrayAsTextFile(double[] noise, String fileName) {
// try {
// FileWriter fw = new FileWriter(fileName);
// BufferedWriter bw = new BufferedWriter(fw);
//
// for (double d : noise) {
// bw.write(String.format("%09.5f\n", d));
// }
//
// bw.close();
// fw.close();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
//
// }
//
// public static boolean arraysAreCloseEnough(long[][] expected, long[][] actual) {
// for (int i = 0; i < expected.length; i++) {
// for (int j = 0; j < expected[i].length; j++) {
// if (expected[i][j] != actual[i][j]) {
// System.out.println("arraysAreCloseEnough failed at YX[" + i + "," + j
// + "], actual value " + actual[i][j] + " differs from expected "
// + expected[i][j]);
// return false;
// }
// }
// }
// return true;
// }
//
// public static void print2dArray(long[][] data) {
// for (int y = 0; y < data.length; y++) {
// for (int x = 0; x < data[y].length; x++) {
// if (data[y][x] != LongLattice.NAN) {
// System.out.print((int) data[y][x] + " ");
// } else {
// System.out.print("NAN ");
// }
// }
// System.out.println();
// }
// }
//
// public static void saveArrayAsTextFileSkipNAN(long[] data, String fileName) {
// try {
// FileWriter fw = new FileWriter(fileName);
// BufferedWriter bw = new BufferedWriter(fw);
//
// for (long l : data) {
// if (l != LongLattice.NAN) {
// bw.write(Long.toString(l));
// bw.write('\n');
// }
// }
//
// bw.close();
// fw.close();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static void saveArrayAsTextFileSkipNAN(long[][] data, String fileName) {
// try {
// FileWriter fw = new FileWriter(fileName);
// BufferedWriter bw = new BufferedWriter(fw);
//
// for (long a[] : data) {
// for (long l : a) {
// if (l != LongLattice.NAN) {
// bw.write(Long.toString(l));
// bw.write(' ');
// }
// }
// bw.write('\n');
// }
//
// bw.close();
// fw.close();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
//
// }
//
// public static byte[] joinArrays(List<byte[]> data) {
// int size = 0;
// for (byte[] a : data) {
// size += a.length;
// }
// int i = 0;
// byte[] result = new byte[size];
// for (byte[] a : data) {
// for (int j = 0; j < a.length; j++) {
// result[i++] = a[j];
// }
// }
// return result;
// }
//
// public static byte[] intAsByteArray(int n) {
// ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
// DataOutputStream dataOut = new DataOutputStream(byteOut);
// try {
// dataOut.writeInt(n);
// return byteOut.toByteArray();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
| import static org.junit.Assert.assertArrayEquals;
import static test.TestUtils.DELTA;
import java.util.LinkedList;
import java.util.List;
import org.junit.Test;
import util.ArrayUtils; | package test.util;
public class ArrayUtilsTest {
@Test
public final void testArraySubtract() {
double a[][] = { { 1, 2 }, { 3, 4 } };
double b[][] = { { 0, 1 }, { 4, 2 } };
double expected[] = { 1, 1 , -1, 2 };
| // Path: src/test/TestUtils.java
// public static final double DELTA = 0.00000001;
//
// Path: src/util/ArrayUtils.java
// public class ArrayUtils {
//
// public static double[] subtract2DArraysAs1D(double[][] a, double[][] b) {
// int height = a.length;
// int width = a[0].length;
// double[] result = new double[height * width];
// int i = 0;
// for (int y = 0; y < height; y++) {
// for (int x = 0; x < width; x++) {
// result[i++] = a[y][x] - b[y][x];
// }
// }
// return result;
// }
//
// public static long[][] copyOfArray(long[][] src) {
// long[][] dst = new long[src.length][];
// for (int i = 0; i < src.length; i++) {
// dst[i] = Arrays.copyOf(src[i], src[i].length);
// }
// return dst;
// }
//
//
// public static boolean arraysAreCloseEnough(double[][] expected, double[][] actual, double delta) {
// for (int i = 0; i < expected.length; i++) {
// for (int j = 0; j < expected[i].length; j++) {
// if (Double.isNaN(expected[i][j]) && Double.isNaN(actual[i][j]))
// continue;
// if (Double.isNaN(expected[i][j]) || Double.isNaN(actual[i][j])
// || Math.abs(expected[i][j] - actual[i][j]) > delta) {
// System.out.println("arraysAreCloseEnough failed at YX[" + i + "," + j + "], value "
// + actual[i][j] + " differs from expected " + expected[i][j]);
// return false;
// }
// }
// }
// return true;
// }
//
// public static void saveArrayAsTextFile(double[] noise, String fileName) {
// try {
// FileWriter fw = new FileWriter(fileName);
// BufferedWriter bw = new BufferedWriter(fw);
//
// for (double d : noise) {
// bw.write(String.format("%09.5f\n", d));
// }
//
// bw.close();
// fw.close();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
//
// }
//
// public static boolean arraysAreCloseEnough(long[][] expected, long[][] actual) {
// for (int i = 0; i < expected.length; i++) {
// for (int j = 0; j < expected[i].length; j++) {
// if (expected[i][j] != actual[i][j]) {
// System.out.println("arraysAreCloseEnough failed at YX[" + i + "," + j
// + "], actual value " + actual[i][j] + " differs from expected "
// + expected[i][j]);
// return false;
// }
// }
// }
// return true;
// }
//
// public static void print2dArray(long[][] data) {
// for (int y = 0; y < data.length; y++) {
// for (int x = 0; x < data[y].length; x++) {
// if (data[y][x] != LongLattice.NAN) {
// System.out.print((int) data[y][x] + " ");
// } else {
// System.out.print("NAN ");
// }
// }
// System.out.println();
// }
// }
//
// public static void saveArrayAsTextFileSkipNAN(long[] data, String fileName) {
// try {
// FileWriter fw = new FileWriter(fileName);
// BufferedWriter bw = new BufferedWriter(fw);
//
// for (long l : data) {
// if (l != LongLattice.NAN) {
// bw.write(Long.toString(l));
// bw.write('\n');
// }
// }
//
// bw.close();
// fw.close();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static void saveArrayAsTextFileSkipNAN(long[][] data, String fileName) {
// try {
// FileWriter fw = new FileWriter(fileName);
// BufferedWriter bw = new BufferedWriter(fw);
//
// for (long a[] : data) {
// for (long l : a) {
// if (l != LongLattice.NAN) {
// bw.write(Long.toString(l));
// bw.write(' ');
// }
// }
// bw.write('\n');
// }
//
// bw.close();
// fw.close();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
//
// }
//
// public static byte[] joinArrays(List<byte[]> data) {
// int size = 0;
// for (byte[] a : data) {
// size += a.length;
// }
// int i = 0;
// byte[] result = new byte[size];
// for (byte[] a : data) {
// for (int j = 0; j < a.length; j++) {
// result[i++] = a[j];
// }
// }
// return result;
// }
//
// public static byte[] intAsByteArray(int n) {
// ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
// DataOutputStream dataOut = new DataOutputStream(byteOut);
// try {
// dataOut.writeInt(n);
// return byteOut.toByteArray();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
// Path: src/test/util/ArrayUtilsTest.java
import static org.junit.Assert.assertArrayEquals;
import static test.TestUtils.DELTA;
import java.util.LinkedList;
import java.util.List;
import org.junit.Test;
import util.ArrayUtils;
package test.util;
public class ArrayUtilsTest {
@Test
public final void testArraySubtract() {
double a[][] = { { 1, 2 }, { 3, 4 } };
double b[][] = { { 0, 1 }, { 4, 2 } };
double expected[] = { 1, 1 , -1, 2 };
| assertArrayEquals(expected, ArrayUtils.subtract2DArraysAs1D(a, b), DELTA); |
sweer/hex-image-compress | src/test/util/ArrayUtilsTest.java | // Path: src/test/TestUtils.java
// public static final double DELTA = 0.00000001;
//
// Path: src/util/ArrayUtils.java
// public class ArrayUtils {
//
// public static double[] subtract2DArraysAs1D(double[][] a, double[][] b) {
// int height = a.length;
// int width = a[0].length;
// double[] result = new double[height * width];
// int i = 0;
// for (int y = 0; y < height; y++) {
// for (int x = 0; x < width; x++) {
// result[i++] = a[y][x] - b[y][x];
// }
// }
// return result;
// }
//
// public static long[][] copyOfArray(long[][] src) {
// long[][] dst = new long[src.length][];
// for (int i = 0; i < src.length; i++) {
// dst[i] = Arrays.copyOf(src[i], src[i].length);
// }
// return dst;
// }
//
//
// public static boolean arraysAreCloseEnough(double[][] expected, double[][] actual, double delta) {
// for (int i = 0; i < expected.length; i++) {
// for (int j = 0; j < expected[i].length; j++) {
// if (Double.isNaN(expected[i][j]) && Double.isNaN(actual[i][j]))
// continue;
// if (Double.isNaN(expected[i][j]) || Double.isNaN(actual[i][j])
// || Math.abs(expected[i][j] - actual[i][j]) > delta) {
// System.out.println("arraysAreCloseEnough failed at YX[" + i + "," + j + "], value "
// + actual[i][j] + " differs from expected " + expected[i][j]);
// return false;
// }
// }
// }
// return true;
// }
//
// public static void saveArrayAsTextFile(double[] noise, String fileName) {
// try {
// FileWriter fw = new FileWriter(fileName);
// BufferedWriter bw = new BufferedWriter(fw);
//
// for (double d : noise) {
// bw.write(String.format("%09.5f\n", d));
// }
//
// bw.close();
// fw.close();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
//
// }
//
// public static boolean arraysAreCloseEnough(long[][] expected, long[][] actual) {
// for (int i = 0; i < expected.length; i++) {
// for (int j = 0; j < expected[i].length; j++) {
// if (expected[i][j] != actual[i][j]) {
// System.out.println("arraysAreCloseEnough failed at YX[" + i + "," + j
// + "], actual value " + actual[i][j] + " differs from expected "
// + expected[i][j]);
// return false;
// }
// }
// }
// return true;
// }
//
// public static void print2dArray(long[][] data) {
// for (int y = 0; y < data.length; y++) {
// for (int x = 0; x < data[y].length; x++) {
// if (data[y][x] != LongLattice.NAN) {
// System.out.print((int) data[y][x] + " ");
// } else {
// System.out.print("NAN ");
// }
// }
// System.out.println();
// }
// }
//
// public static void saveArrayAsTextFileSkipNAN(long[] data, String fileName) {
// try {
// FileWriter fw = new FileWriter(fileName);
// BufferedWriter bw = new BufferedWriter(fw);
//
// for (long l : data) {
// if (l != LongLattice.NAN) {
// bw.write(Long.toString(l));
// bw.write('\n');
// }
// }
//
// bw.close();
// fw.close();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static void saveArrayAsTextFileSkipNAN(long[][] data, String fileName) {
// try {
// FileWriter fw = new FileWriter(fileName);
// BufferedWriter bw = new BufferedWriter(fw);
//
// for (long a[] : data) {
// for (long l : a) {
// if (l != LongLattice.NAN) {
// bw.write(Long.toString(l));
// bw.write(' ');
// }
// }
// bw.write('\n');
// }
//
// bw.close();
// fw.close();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
//
// }
//
// public static byte[] joinArrays(List<byte[]> data) {
// int size = 0;
// for (byte[] a : data) {
// size += a.length;
// }
// int i = 0;
// byte[] result = new byte[size];
// for (byte[] a : data) {
// for (int j = 0; j < a.length; j++) {
// result[i++] = a[j];
// }
// }
// return result;
// }
//
// public static byte[] intAsByteArray(int n) {
// ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
// DataOutputStream dataOut = new DataOutputStream(byteOut);
// try {
// dataOut.writeInt(n);
// return byteOut.toByteArray();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
| import static org.junit.Assert.assertArrayEquals;
import static test.TestUtils.DELTA;
import java.util.LinkedList;
import java.util.List;
import org.junit.Test;
import util.ArrayUtils; | package test.util;
public class ArrayUtilsTest {
@Test
public final void testArraySubtract() {
double a[][] = { { 1, 2 }, { 3, 4 } };
double b[][] = { { 0, 1 }, { 4, 2 } };
double expected[] = { 1, 1 , -1, 2 };
| // Path: src/test/TestUtils.java
// public static final double DELTA = 0.00000001;
//
// Path: src/util/ArrayUtils.java
// public class ArrayUtils {
//
// public static double[] subtract2DArraysAs1D(double[][] a, double[][] b) {
// int height = a.length;
// int width = a[0].length;
// double[] result = new double[height * width];
// int i = 0;
// for (int y = 0; y < height; y++) {
// for (int x = 0; x < width; x++) {
// result[i++] = a[y][x] - b[y][x];
// }
// }
// return result;
// }
//
// public static long[][] copyOfArray(long[][] src) {
// long[][] dst = new long[src.length][];
// for (int i = 0; i < src.length; i++) {
// dst[i] = Arrays.copyOf(src[i], src[i].length);
// }
// return dst;
// }
//
//
// public static boolean arraysAreCloseEnough(double[][] expected, double[][] actual, double delta) {
// for (int i = 0; i < expected.length; i++) {
// for (int j = 0; j < expected[i].length; j++) {
// if (Double.isNaN(expected[i][j]) && Double.isNaN(actual[i][j]))
// continue;
// if (Double.isNaN(expected[i][j]) || Double.isNaN(actual[i][j])
// || Math.abs(expected[i][j] - actual[i][j]) > delta) {
// System.out.println("arraysAreCloseEnough failed at YX[" + i + "," + j + "], value "
// + actual[i][j] + " differs from expected " + expected[i][j]);
// return false;
// }
// }
// }
// return true;
// }
//
// public static void saveArrayAsTextFile(double[] noise, String fileName) {
// try {
// FileWriter fw = new FileWriter(fileName);
// BufferedWriter bw = new BufferedWriter(fw);
//
// for (double d : noise) {
// bw.write(String.format("%09.5f\n", d));
// }
//
// bw.close();
// fw.close();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
//
// }
//
// public static boolean arraysAreCloseEnough(long[][] expected, long[][] actual) {
// for (int i = 0; i < expected.length; i++) {
// for (int j = 0; j < expected[i].length; j++) {
// if (expected[i][j] != actual[i][j]) {
// System.out.println("arraysAreCloseEnough failed at YX[" + i + "," + j
// + "], actual value " + actual[i][j] + " differs from expected "
// + expected[i][j]);
// return false;
// }
// }
// }
// return true;
// }
//
// public static void print2dArray(long[][] data) {
// for (int y = 0; y < data.length; y++) {
// for (int x = 0; x < data[y].length; x++) {
// if (data[y][x] != LongLattice.NAN) {
// System.out.print((int) data[y][x] + " ");
// } else {
// System.out.print("NAN ");
// }
// }
// System.out.println();
// }
// }
//
// public static void saveArrayAsTextFileSkipNAN(long[] data, String fileName) {
// try {
// FileWriter fw = new FileWriter(fileName);
// BufferedWriter bw = new BufferedWriter(fw);
//
// for (long l : data) {
// if (l != LongLattice.NAN) {
// bw.write(Long.toString(l));
// bw.write('\n');
// }
// }
//
// bw.close();
// fw.close();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static void saveArrayAsTextFileSkipNAN(long[][] data, String fileName) {
// try {
// FileWriter fw = new FileWriter(fileName);
// BufferedWriter bw = new BufferedWriter(fw);
//
// for (long a[] : data) {
// for (long l : a) {
// if (l != LongLattice.NAN) {
// bw.write(Long.toString(l));
// bw.write(' ');
// }
// }
// bw.write('\n');
// }
//
// bw.close();
// fw.close();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
//
// }
//
// public static byte[] joinArrays(List<byte[]> data) {
// int size = 0;
// for (byte[] a : data) {
// size += a.length;
// }
// int i = 0;
// byte[] result = new byte[size];
// for (byte[] a : data) {
// for (int j = 0; j < a.length; j++) {
// result[i++] = a[j];
// }
// }
// return result;
// }
//
// public static byte[] intAsByteArray(int n) {
// ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
// DataOutputStream dataOut = new DataOutputStream(byteOut);
// try {
// dataOut.writeInt(n);
// return byteOut.toByteArray();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// }
// Path: src/test/util/ArrayUtilsTest.java
import static org.junit.Assert.assertArrayEquals;
import static test.TestUtils.DELTA;
import java.util.LinkedList;
import java.util.List;
import org.junit.Test;
import util.ArrayUtils;
package test.util;
public class ArrayUtilsTest {
@Test
public final void testArraySubtract() {
double a[][] = { { 1, 2 }, { 3, 4 } };
double b[][] = { { 0, 1 }, { 4, 2 } };
double expected[] = { 1, 1 , -1, 2 };
| assertArrayEquals(expected, ArrayUtils.subtract2DArraysAs1D(a, b), DELTA); |
sweer/hex-image-compress | src/filter/H2O.java | // Path: src/lattice/DoubleLattice.java
// public class DoubleLattice extends Lattice {
// /**
// * @uml.property name="data"
// */
// private final double[][] data;
// public DoubleLattice(double[][] data, int ox, int oy) {
// super(ox,oy);
// this.data = data;
// }
//
// public DoubleLattice(DoubleLattice lattice) {
// this(lattice.data, lattice.ox, lattice.oy);
// }
//
// /**
// * @return
// * @uml.property name="data"
// */
// public double[][] getData() {
// return data;
// }
// }
//
// Path: src/filter/InterpolatingArray.java
// public interface Factory {
// InterpolatingArray getInstance(double[] points);
// }
//
// Path: src/filter/RectangleDiagonal.java
// static public class DiagonalParameters {
// final public int diagonalLength;
// final public int startX;
// final public int startY;
//
// private DiagonalParameters(int diagonalLength, int startX, int startY) {
// this.diagonalLength = diagonalLength;
// this.startX = startX;
// this.startY = startY;
// }
//
// public static DiagonalParameters getDiagonalParameters(int width,
// int height, int n) {
// if (width == height) {
// return getSquareDiagonalParameters(width, height, n);
// } else if (width < height) {
// return getTallRectangleDiagonalParameters(width, height, n);
// } else {
// return getLongRectangleDiagonalParameters(width, height, n);
// }
// }
//
// private static DiagonalParameters getLongRectangleDiagonalParameters(
// int width, int height, int n) {
// final int diagonalLength;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// diagonalLength = n + 1;
// } else {
// startX = n - height + 1;
// startY = height - 1;
// final int fromTheLastColumn = (width - 1) - startX;
// if (fromTheLastColumn < height - 1) {
// diagonalLength = fromTheLastColumn + 1;
// } else {
// diagonalLength = height;
// }
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
//
// private static DiagonalParameters getTallRectangleDiagonalParameters(
// int width, int height, int n) {
//
// final int diagonalLength;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// if (n < width - 1) {
// diagonalLength = n + 1;
// } else {
// diagonalLength = width;
// }
//
// } else {
// startX = n - height + 1;
// startY = height - 1;
// final int fromTheLastColumn = (width - 1) - startX;
// diagonalLength = fromTheLastColumn + 1;
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
//
// private static DiagonalParameters getSquareDiagonalParameters(
// int width, int height, int n) {
//
// final int distanceFromCornerDiagonal = Math.abs(n - (width - 1));
// final int diagonalLength = width - distanceFromCornerDiagonal;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// } else {
// startX = n - width + 1;
// startY = height - 1;
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
// }
| import static java.lang.Math.sqrt;
import lattice.DoubleLattice;
import filter.InterpolatingArray.Factory;
import filter.RectangleDiagonal.DiagonalParameters; | package filter;
/* 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/>.
*/
/**
* Implementation of H2O transformation described in L.Condat,
* B.Forster-Heinlein, D. Van De Ville,
* "Reversible Hexagonal-Orthogonal Grid Conversion by 1-D Filtering", IEEE
* ICIP, 2007, vol.II pg. 73-76
*
* Copyright (C) 2012 Aleksejs Truhans
**/
public class H2O {
public final static double M1A = 1 - sqrt(2 / sqrt(3));
public final static double M2B = sqrt(sqrt(3) / 2) - 1;
public final static double M3C = sqrt(2 / sqrt(3)) - 1 - 1 / sqrt(3);
/**
* @author Aleksejs Truhans
*/
public static enum Direction {
O2H, H2O, TEST_O2H, TEST_H2O;
}
/**
* Use it to convert from orthogonal to hexagonal lattice.
* o2h doesn't change the passed raster.
**/ | // Path: src/lattice/DoubleLattice.java
// public class DoubleLattice extends Lattice {
// /**
// * @uml.property name="data"
// */
// private final double[][] data;
// public DoubleLattice(double[][] data, int ox, int oy) {
// super(ox,oy);
// this.data = data;
// }
//
// public DoubleLattice(DoubleLattice lattice) {
// this(lattice.data, lattice.ox, lattice.oy);
// }
//
// /**
// * @return
// * @uml.property name="data"
// */
// public double[][] getData() {
// return data;
// }
// }
//
// Path: src/filter/InterpolatingArray.java
// public interface Factory {
// InterpolatingArray getInstance(double[] points);
// }
//
// Path: src/filter/RectangleDiagonal.java
// static public class DiagonalParameters {
// final public int diagonalLength;
// final public int startX;
// final public int startY;
//
// private DiagonalParameters(int diagonalLength, int startX, int startY) {
// this.diagonalLength = diagonalLength;
// this.startX = startX;
// this.startY = startY;
// }
//
// public static DiagonalParameters getDiagonalParameters(int width,
// int height, int n) {
// if (width == height) {
// return getSquareDiagonalParameters(width, height, n);
// } else if (width < height) {
// return getTallRectangleDiagonalParameters(width, height, n);
// } else {
// return getLongRectangleDiagonalParameters(width, height, n);
// }
// }
//
// private static DiagonalParameters getLongRectangleDiagonalParameters(
// int width, int height, int n) {
// final int diagonalLength;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// diagonalLength = n + 1;
// } else {
// startX = n - height + 1;
// startY = height - 1;
// final int fromTheLastColumn = (width - 1) - startX;
// if (fromTheLastColumn < height - 1) {
// diagonalLength = fromTheLastColumn + 1;
// } else {
// diagonalLength = height;
// }
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
//
// private static DiagonalParameters getTallRectangleDiagonalParameters(
// int width, int height, int n) {
//
// final int diagonalLength;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// if (n < width - 1) {
// diagonalLength = n + 1;
// } else {
// diagonalLength = width;
// }
//
// } else {
// startX = n - height + 1;
// startY = height - 1;
// final int fromTheLastColumn = (width - 1) - startX;
// diagonalLength = fromTheLastColumn + 1;
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
//
// private static DiagonalParameters getSquareDiagonalParameters(
// int width, int height, int n) {
//
// final int distanceFromCornerDiagonal = Math.abs(n - (width - 1));
// final int diagonalLength = width - distanceFromCornerDiagonal;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// } else {
// startX = n - width + 1;
// startY = height - 1;
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
// }
// Path: src/filter/H2O.java
import static java.lang.Math.sqrt;
import lattice.DoubleLattice;
import filter.InterpolatingArray.Factory;
import filter.RectangleDiagonal.DiagonalParameters;
package filter;
/* 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/>.
*/
/**
* Implementation of H2O transformation described in L.Condat,
* B.Forster-Heinlein, D. Van De Ville,
* "Reversible Hexagonal-Orthogonal Grid Conversion by 1-D Filtering", IEEE
* ICIP, 2007, vol.II pg. 73-76
*
* Copyright (C) 2012 Aleksejs Truhans
**/
public class H2O {
public final static double M1A = 1 - sqrt(2 / sqrt(3));
public final static double M2B = sqrt(sqrt(3) / 2) - 1;
public final static double M3C = sqrt(2 / sqrt(3)) - 1 - 1 / sqrt(3);
/**
* @author Aleksejs Truhans
*/
public static enum Direction {
O2H, H2O, TEST_O2H, TEST_H2O;
}
/**
* Use it to convert from orthogonal to hexagonal lattice.
* o2h doesn't change the passed raster.
**/ | public static DoubleLattice o2h(double[][] raster) { |
sweer/hex-image-compress | src/filter/H2O.java | // Path: src/lattice/DoubleLattice.java
// public class DoubleLattice extends Lattice {
// /**
// * @uml.property name="data"
// */
// private final double[][] data;
// public DoubleLattice(double[][] data, int ox, int oy) {
// super(ox,oy);
// this.data = data;
// }
//
// public DoubleLattice(DoubleLattice lattice) {
// this(lattice.data, lattice.ox, lattice.oy);
// }
//
// /**
// * @return
// * @uml.property name="data"
// */
// public double[][] getData() {
// return data;
// }
// }
//
// Path: src/filter/InterpolatingArray.java
// public interface Factory {
// InterpolatingArray getInstance(double[] points);
// }
//
// Path: src/filter/RectangleDiagonal.java
// static public class DiagonalParameters {
// final public int diagonalLength;
// final public int startX;
// final public int startY;
//
// private DiagonalParameters(int diagonalLength, int startX, int startY) {
// this.diagonalLength = diagonalLength;
// this.startX = startX;
// this.startY = startY;
// }
//
// public static DiagonalParameters getDiagonalParameters(int width,
// int height, int n) {
// if (width == height) {
// return getSquareDiagonalParameters(width, height, n);
// } else if (width < height) {
// return getTallRectangleDiagonalParameters(width, height, n);
// } else {
// return getLongRectangleDiagonalParameters(width, height, n);
// }
// }
//
// private static DiagonalParameters getLongRectangleDiagonalParameters(
// int width, int height, int n) {
// final int diagonalLength;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// diagonalLength = n + 1;
// } else {
// startX = n - height + 1;
// startY = height - 1;
// final int fromTheLastColumn = (width - 1) - startX;
// if (fromTheLastColumn < height - 1) {
// diagonalLength = fromTheLastColumn + 1;
// } else {
// diagonalLength = height;
// }
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
//
// private static DiagonalParameters getTallRectangleDiagonalParameters(
// int width, int height, int n) {
//
// final int diagonalLength;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// if (n < width - 1) {
// diagonalLength = n + 1;
// } else {
// diagonalLength = width;
// }
//
// } else {
// startX = n - height + 1;
// startY = height - 1;
// final int fromTheLastColumn = (width - 1) - startX;
// diagonalLength = fromTheLastColumn + 1;
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
//
// private static DiagonalParameters getSquareDiagonalParameters(
// int width, int height, int n) {
//
// final int distanceFromCornerDiagonal = Math.abs(n - (width - 1));
// final int diagonalLength = width - distanceFromCornerDiagonal;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// } else {
// startX = n - width + 1;
// startY = height - 1;
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
// }
| import static java.lang.Math.sqrt;
import lattice.DoubleLattice;
import filter.InterpolatingArray.Factory;
import filter.RectangleDiagonal.DiagonalParameters; | package filter;
/* 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/>.
*/
/**
* Implementation of H2O transformation described in L.Condat,
* B.Forster-Heinlein, D. Van De Ville,
* "Reversible Hexagonal-Orthogonal Grid Conversion by 1-D Filtering", IEEE
* ICIP, 2007, vol.II pg. 73-76
*
* Copyright (C) 2012 Aleksejs Truhans
**/
public class H2O {
public final static double M1A = 1 - sqrt(2 / sqrt(3));
public final static double M2B = sqrt(sqrt(3) / 2) - 1;
public final static double M3C = sqrt(2 / sqrt(3)) - 1 - 1 / sqrt(3);
/**
* @author Aleksejs Truhans
*/
public static enum Direction {
O2H, H2O, TEST_O2H, TEST_H2O;
}
/**
* Use it to convert from orthogonal to hexagonal lattice.
* o2h doesn't change the passed raster.
**/
public static DoubleLattice o2h(double[][] raster) {
H2ORunner h2o = new H2ORunner(SincRepeater.getFactory());
h2o.setData(raster, Direction.O2H);
return h2o.o2hBody();
}
/**
* Use it to convert from hexagonal to orthogonal lattice.
* o2h doesn't change the passed raster.
**/
public static DoubleLattice h2o(DoubleLattice source) {
H2ORunner h2o = new H2ORunner(SincRepeater.getFactory());
h2o.setData(source, Direction.H2O);
return h2o.h2oBody();
}
/**
* @author Aleksejs Truhans
*/
public static class H2ORunner {
| // Path: src/lattice/DoubleLattice.java
// public class DoubleLattice extends Lattice {
// /**
// * @uml.property name="data"
// */
// private final double[][] data;
// public DoubleLattice(double[][] data, int ox, int oy) {
// super(ox,oy);
// this.data = data;
// }
//
// public DoubleLattice(DoubleLattice lattice) {
// this(lattice.data, lattice.ox, lattice.oy);
// }
//
// /**
// * @return
// * @uml.property name="data"
// */
// public double[][] getData() {
// return data;
// }
// }
//
// Path: src/filter/InterpolatingArray.java
// public interface Factory {
// InterpolatingArray getInstance(double[] points);
// }
//
// Path: src/filter/RectangleDiagonal.java
// static public class DiagonalParameters {
// final public int diagonalLength;
// final public int startX;
// final public int startY;
//
// private DiagonalParameters(int diagonalLength, int startX, int startY) {
// this.diagonalLength = diagonalLength;
// this.startX = startX;
// this.startY = startY;
// }
//
// public static DiagonalParameters getDiagonalParameters(int width,
// int height, int n) {
// if (width == height) {
// return getSquareDiagonalParameters(width, height, n);
// } else if (width < height) {
// return getTallRectangleDiagonalParameters(width, height, n);
// } else {
// return getLongRectangleDiagonalParameters(width, height, n);
// }
// }
//
// private static DiagonalParameters getLongRectangleDiagonalParameters(
// int width, int height, int n) {
// final int diagonalLength;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// diagonalLength = n + 1;
// } else {
// startX = n - height + 1;
// startY = height - 1;
// final int fromTheLastColumn = (width - 1) - startX;
// if (fromTheLastColumn < height - 1) {
// diagonalLength = fromTheLastColumn + 1;
// } else {
// diagonalLength = height;
// }
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
//
// private static DiagonalParameters getTallRectangleDiagonalParameters(
// int width, int height, int n) {
//
// final int diagonalLength;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// if (n < width - 1) {
// diagonalLength = n + 1;
// } else {
// diagonalLength = width;
// }
//
// } else {
// startX = n - height + 1;
// startY = height - 1;
// final int fromTheLastColumn = (width - 1) - startX;
// diagonalLength = fromTheLastColumn + 1;
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
//
// private static DiagonalParameters getSquareDiagonalParameters(
// int width, int height, int n) {
//
// final int distanceFromCornerDiagonal = Math.abs(n - (width - 1));
// final int diagonalLength = width - distanceFromCornerDiagonal;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// } else {
// startX = n - width + 1;
// startY = height - 1;
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
// }
// Path: src/filter/H2O.java
import static java.lang.Math.sqrt;
import lattice.DoubleLattice;
import filter.InterpolatingArray.Factory;
import filter.RectangleDiagonal.DiagonalParameters;
package filter;
/* 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/>.
*/
/**
* Implementation of H2O transformation described in L.Condat,
* B.Forster-Heinlein, D. Van De Ville,
* "Reversible Hexagonal-Orthogonal Grid Conversion by 1-D Filtering", IEEE
* ICIP, 2007, vol.II pg. 73-76
*
* Copyright (C) 2012 Aleksejs Truhans
**/
public class H2O {
public final static double M1A = 1 - sqrt(2 / sqrt(3));
public final static double M2B = sqrt(sqrt(3) / 2) - 1;
public final static double M3C = sqrt(2 / sqrt(3)) - 1 - 1 / sqrt(3);
/**
* @author Aleksejs Truhans
*/
public static enum Direction {
O2H, H2O, TEST_O2H, TEST_H2O;
}
/**
* Use it to convert from orthogonal to hexagonal lattice.
* o2h doesn't change the passed raster.
**/
public static DoubleLattice o2h(double[][] raster) {
H2ORunner h2o = new H2ORunner(SincRepeater.getFactory());
h2o.setData(raster, Direction.O2H);
return h2o.o2hBody();
}
/**
* Use it to convert from hexagonal to orthogonal lattice.
* o2h doesn't change the passed raster.
**/
public static DoubleLattice h2o(DoubleLattice source) {
H2ORunner h2o = new H2ORunner(SincRepeater.getFactory());
h2o.setData(source, Direction.H2O);
return h2o.h2oBody();
}
/**
* @author Aleksejs Truhans
*/
public static class H2ORunner {
| private final Factory interpolatingArrayFactory; |
sweer/hex-image-compress | src/filter/H2O.java | // Path: src/lattice/DoubleLattice.java
// public class DoubleLattice extends Lattice {
// /**
// * @uml.property name="data"
// */
// private final double[][] data;
// public DoubleLattice(double[][] data, int ox, int oy) {
// super(ox,oy);
// this.data = data;
// }
//
// public DoubleLattice(DoubleLattice lattice) {
// this(lattice.data, lattice.ox, lattice.oy);
// }
//
// /**
// * @return
// * @uml.property name="data"
// */
// public double[][] getData() {
// return data;
// }
// }
//
// Path: src/filter/InterpolatingArray.java
// public interface Factory {
// InterpolatingArray getInstance(double[] points);
// }
//
// Path: src/filter/RectangleDiagonal.java
// static public class DiagonalParameters {
// final public int diagonalLength;
// final public int startX;
// final public int startY;
//
// private DiagonalParameters(int diagonalLength, int startX, int startY) {
// this.diagonalLength = diagonalLength;
// this.startX = startX;
// this.startY = startY;
// }
//
// public static DiagonalParameters getDiagonalParameters(int width,
// int height, int n) {
// if (width == height) {
// return getSquareDiagonalParameters(width, height, n);
// } else if (width < height) {
// return getTallRectangleDiagonalParameters(width, height, n);
// } else {
// return getLongRectangleDiagonalParameters(width, height, n);
// }
// }
//
// private static DiagonalParameters getLongRectangleDiagonalParameters(
// int width, int height, int n) {
// final int diagonalLength;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// diagonalLength = n + 1;
// } else {
// startX = n - height + 1;
// startY = height - 1;
// final int fromTheLastColumn = (width - 1) - startX;
// if (fromTheLastColumn < height - 1) {
// diagonalLength = fromTheLastColumn + 1;
// } else {
// diagonalLength = height;
// }
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
//
// private static DiagonalParameters getTallRectangleDiagonalParameters(
// int width, int height, int n) {
//
// final int diagonalLength;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// if (n < width - 1) {
// diagonalLength = n + 1;
// } else {
// diagonalLength = width;
// }
//
// } else {
// startX = n - height + 1;
// startY = height - 1;
// final int fromTheLastColumn = (width - 1) - startX;
// diagonalLength = fromTheLastColumn + 1;
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
//
// private static DiagonalParameters getSquareDiagonalParameters(
// int width, int height, int n) {
//
// final int distanceFromCornerDiagonal = Math.abs(n - (width - 1));
// final int diagonalLength = width - distanceFromCornerDiagonal;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// } else {
// startX = n - width + 1;
// startY = height - 1;
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
// }
| import static java.lang.Math.sqrt;
import lattice.DoubleLattice;
import filter.InterpolatingArray.Factory;
import filter.RectangleDiagonal.DiagonalParameters; | public DoubleLattice getResult() {
int w = maxx - minx + 1;
int h = maxy - miny + 1;
double[][] result = new double[h][w];
for (int y = miny; y <= maxy; y++) {
for (int x = minx; x <= maxx; x++) {
result[y - miny][x - minx] = data[y][x];
}
}
return new DoubleLattice(result, ox - minx, oy - miny);
}
public double[][] getRawData() {
return data;
}
public void shearDownRightM2(double shift) {
final int height = maxy - miny + 1;
final int width = maxx - minx + 1;
int ODiagonalNumber = ox - minx + oy - miny;
int newmaxx = maxx;
int newmaxy = maxy;
int newminx = minx;
int newminy = miny;
for (int i = 0; i < (height + width - 1); i++) {
int diagonalCoordinate = i - ODiagonalNumber;
if (diagonalCoordinate == 0)
continue; // shift by 0 means no shift
| // Path: src/lattice/DoubleLattice.java
// public class DoubleLattice extends Lattice {
// /**
// * @uml.property name="data"
// */
// private final double[][] data;
// public DoubleLattice(double[][] data, int ox, int oy) {
// super(ox,oy);
// this.data = data;
// }
//
// public DoubleLattice(DoubleLattice lattice) {
// this(lattice.data, lattice.ox, lattice.oy);
// }
//
// /**
// * @return
// * @uml.property name="data"
// */
// public double[][] getData() {
// return data;
// }
// }
//
// Path: src/filter/InterpolatingArray.java
// public interface Factory {
// InterpolatingArray getInstance(double[] points);
// }
//
// Path: src/filter/RectangleDiagonal.java
// static public class DiagonalParameters {
// final public int diagonalLength;
// final public int startX;
// final public int startY;
//
// private DiagonalParameters(int diagonalLength, int startX, int startY) {
// this.diagonalLength = diagonalLength;
// this.startX = startX;
// this.startY = startY;
// }
//
// public static DiagonalParameters getDiagonalParameters(int width,
// int height, int n) {
// if (width == height) {
// return getSquareDiagonalParameters(width, height, n);
// } else if (width < height) {
// return getTallRectangleDiagonalParameters(width, height, n);
// } else {
// return getLongRectangleDiagonalParameters(width, height, n);
// }
// }
//
// private static DiagonalParameters getLongRectangleDiagonalParameters(
// int width, int height, int n) {
// final int diagonalLength;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// diagonalLength = n + 1;
// } else {
// startX = n - height + 1;
// startY = height - 1;
// final int fromTheLastColumn = (width - 1) - startX;
// if (fromTheLastColumn < height - 1) {
// diagonalLength = fromTheLastColumn + 1;
// } else {
// diagonalLength = height;
// }
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
//
// private static DiagonalParameters getTallRectangleDiagonalParameters(
// int width, int height, int n) {
//
// final int diagonalLength;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// if (n < width - 1) {
// diagonalLength = n + 1;
// } else {
// diagonalLength = width;
// }
//
// } else {
// startX = n - height + 1;
// startY = height - 1;
// final int fromTheLastColumn = (width - 1) - startX;
// diagonalLength = fromTheLastColumn + 1;
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
//
// private static DiagonalParameters getSquareDiagonalParameters(
// int width, int height, int n) {
//
// final int distanceFromCornerDiagonal = Math.abs(n - (width - 1));
// final int diagonalLength = width - distanceFromCornerDiagonal;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// } else {
// startX = n - width + 1;
// startY = height - 1;
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
// }
// Path: src/filter/H2O.java
import static java.lang.Math.sqrt;
import lattice.DoubleLattice;
import filter.InterpolatingArray.Factory;
import filter.RectangleDiagonal.DiagonalParameters;
public DoubleLattice getResult() {
int w = maxx - minx + 1;
int h = maxy - miny + 1;
double[][] result = new double[h][w];
for (int y = miny; y <= maxy; y++) {
for (int x = minx; x <= maxx; x++) {
result[y - miny][x - minx] = data[y][x];
}
}
return new DoubleLattice(result, ox - minx, oy - miny);
}
public double[][] getRawData() {
return data;
}
public void shearDownRightM2(double shift) {
final int height = maxy - miny + 1;
final int width = maxx - minx + 1;
int ODiagonalNumber = ox - minx + oy - miny;
int newmaxx = maxx;
int newmaxy = maxy;
int newminx = minx;
int newminy = miny;
for (int i = 0; i < (height + width - 1); i++) {
int diagonalCoordinate = i - ODiagonalNumber;
if (diagonalCoordinate == 0)
continue; // shift by 0 means no shift
| DiagonalParameters dp = DiagonalParameters.getDiagonalParameters(width, height, i); |
sweer/hex-image-compress | src/test/filter/SincRepeaterTest.java | // Path: src/filter/InterpolatingArray.java
// public abstract class InterpolatingArray {
//
// protected final double[] points;
//
// public abstract double get(double x);
//
// public abstract double get(int i);
//
// protected int order = 2;
//
// public InterpolatingArray(double[] points, int order) {
// this(points);
// this.order = order;
// }
//
// public InterpolatingArray(double[] points) {
// this.points = points;
// }
//
// public double[] getShiftedArray(double shift) {
// int length = points.length;
// double[] result = new double[length];
// for (int i = 0; i < length; i++) {
// result[i] = get(i+shift);
// }
// return result;
// }
//
// public final int length() {
// return points.length;
// }
//
// public interface Factory {
// InterpolatingArray getInstance(double[] points);
// }
//
// }
//
// Path: src/filter/SincRepeater.java
// public class SincRepeater extends SincInterpolatingArray {
//
// /**
// * @uml.property name="fACTORY"
// * @uml.associationEnd
// */
// private static final Factory FACTORY = new Factory();
//
// public SincRepeater(double[] points, int order) {
// super(points, order);
// }
//
// public SincRepeater(double[] points) {
// super(points);
// }
//
// @Override
// public double get(int i) {
// // @formatter:off
// // 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4
// // -6-5-4-3-2-1 0 1 2 3 4 5 6 7
// // @formatter:on
// int length = points.length;
// int j = (i % length + length) % length;
// return points[j];
// }
//
// /**
// * @return
// * @uml.property name="fACTORY"
// */
// public static Factory getFactory() {
// return FACTORY;
// }
//
// public static class Factory implements InterpolatingArray.Factory {
//
// @Override
// public SincRepeater getInstance(double[] points) {
// return new SincRepeater(points);
// }
//
// }
//
// }
//
// Path: src/test/TestUtils.java
// public static final double DELTA = 0.00000001;
| import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Random;
import org.junit.Test;
import filter.InterpolatingArray;
import filter.SincRepeater;
import static test.TestUtils.DELTA; | package test.filter;
public class SincRepeaterTest {
@Test
public final void testMirroredGet() {
// 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4
// -6-5-4-3-2-1 0 1 2 3 4 5 6 7
double[] points = { 1, 2, 3, 4, 5, 6 };
| // Path: src/filter/InterpolatingArray.java
// public abstract class InterpolatingArray {
//
// protected final double[] points;
//
// public abstract double get(double x);
//
// public abstract double get(int i);
//
// protected int order = 2;
//
// public InterpolatingArray(double[] points, int order) {
// this(points);
// this.order = order;
// }
//
// public InterpolatingArray(double[] points) {
// this.points = points;
// }
//
// public double[] getShiftedArray(double shift) {
// int length = points.length;
// double[] result = new double[length];
// for (int i = 0; i < length; i++) {
// result[i] = get(i+shift);
// }
// return result;
// }
//
// public final int length() {
// return points.length;
// }
//
// public interface Factory {
// InterpolatingArray getInstance(double[] points);
// }
//
// }
//
// Path: src/filter/SincRepeater.java
// public class SincRepeater extends SincInterpolatingArray {
//
// /**
// * @uml.property name="fACTORY"
// * @uml.associationEnd
// */
// private static final Factory FACTORY = new Factory();
//
// public SincRepeater(double[] points, int order) {
// super(points, order);
// }
//
// public SincRepeater(double[] points) {
// super(points);
// }
//
// @Override
// public double get(int i) {
// // @formatter:off
// // 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4
// // -6-5-4-3-2-1 0 1 2 3 4 5 6 7
// // @formatter:on
// int length = points.length;
// int j = (i % length + length) % length;
// return points[j];
// }
//
// /**
// * @return
// * @uml.property name="fACTORY"
// */
// public static Factory getFactory() {
// return FACTORY;
// }
//
// public static class Factory implements InterpolatingArray.Factory {
//
// @Override
// public SincRepeater getInstance(double[] points) {
// return new SincRepeater(points);
// }
//
// }
//
// }
//
// Path: src/test/TestUtils.java
// public static final double DELTA = 0.00000001;
// Path: src/test/filter/SincRepeaterTest.java
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Random;
import org.junit.Test;
import filter.InterpolatingArray;
import filter.SincRepeater;
import static test.TestUtils.DELTA;
package test.filter;
public class SincRepeaterTest {
@Test
public final void testMirroredGet() {
// 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4
// -6-5-4-3-2-1 0 1 2 3 4 5 6 7
double[] points = { 1, 2, 3, 4, 5, 6 };
| InterpolatingArray sia = new SincRepeater(points, 0); |
sweer/hex-image-compress | src/test/filter/SincRepeaterTest.java | // Path: src/filter/InterpolatingArray.java
// public abstract class InterpolatingArray {
//
// protected final double[] points;
//
// public abstract double get(double x);
//
// public abstract double get(int i);
//
// protected int order = 2;
//
// public InterpolatingArray(double[] points, int order) {
// this(points);
// this.order = order;
// }
//
// public InterpolatingArray(double[] points) {
// this.points = points;
// }
//
// public double[] getShiftedArray(double shift) {
// int length = points.length;
// double[] result = new double[length];
// for (int i = 0; i < length; i++) {
// result[i] = get(i+shift);
// }
// return result;
// }
//
// public final int length() {
// return points.length;
// }
//
// public interface Factory {
// InterpolatingArray getInstance(double[] points);
// }
//
// }
//
// Path: src/filter/SincRepeater.java
// public class SincRepeater extends SincInterpolatingArray {
//
// /**
// * @uml.property name="fACTORY"
// * @uml.associationEnd
// */
// private static final Factory FACTORY = new Factory();
//
// public SincRepeater(double[] points, int order) {
// super(points, order);
// }
//
// public SincRepeater(double[] points) {
// super(points);
// }
//
// @Override
// public double get(int i) {
// // @formatter:off
// // 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4
// // -6-5-4-3-2-1 0 1 2 3 4 5 6 7
// // @formatter:on
// int length = points.length;
// int j = (i % length + length) % length;
// return points[j];
// }
//
// /**
// * @return
// * @uml.property name="fACTORY"
// */
// public static Factory getFactory() {
// return FACTORY;
// }
//
// public static class Factory implements InterpolatingArray.Factory {
//
// @Override
// public SincRepeater getInstance(double[] points) {
// return new SincRepeater(points);
// }
//
// }
//
// }
//
// Path: src/test/TestUtils.java
// public static final double DELTA = 0.00000001;
| import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Random;
import org.junit.Test;
import filter.InterpolatingArray;
import filter.SincRepeater;
import static test.TestUtils.DELTA; | package test.filter;
public class SincRepeaterTest {
@Test
public final void testMirroredGet() {
// 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4
// -6-5-4-3-2-1 0 1 2 3 4 5 6 7
double[] points = { 1, 2, 3, 4, 5, 6 };
| // Path: src/filter/InterpolatingArray.java
// public abstract class InterpolatingArray {
//
// protected final double[] points;
//
// public abstract double get(double x);
//
// public abstract double get(int i);
//
// protected int order = 2;
//
// public InterpolatingArray(double[] points, int order) {
// this(points);
// this.order = order;
// }
//
// public InterpolatingArray(double[] points) {
// this.points = points;
// }
//
// public double[] getShiftedArray(double shift) {
// int length = points.length;
// double[] result = new double[length];
// for (int i = 0; i < length; i++) {
// result[i] = get(i+shift);
// }
// return result;
// }
//
// public final int length() {
// return points.length;
// }
//
// public interface Factory {
// InterpolatingArray getInstance(double[] points);
// }
//
// }
//
// Path: src/filter/SincRepeater.java
// public class SincRepeater extends SincInterpolatingArray {
//
// /**
// * @uml.property name="fACTORY"
// * @uml.associationEnd
// */
// private static final Factory FACTORY = new Factory();
//
// public SincRepeater(double[] points, int order) {
// super(points, order);
// }
//
// public SincRepeater(double[] points) {
// super(points);
// }
//
// @Override
// public double get(int i) {
// // @formatter:off
// // 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4
// // -6-5-4-3-2-1 0 1 2 3 4 5 6 7
// // @formatter:on
// int length = points.length;
// int j = (i % length + length) % length;
// return points[j];
// }
//
// /**
// * @return
// * @uml.property name="fACTORY"
// */
// public static Factory getFactory() {
// return FACTORY;
// }
//
// public static class Factory implements InterpolatingArray.Factory {
//
// @Override
// public SincRepeater getInstance(double[] points) {
// return new SincRepeater(points);
// }
//
// }
//
// }
//
// Path: src/test/TestUtils.java
// public static final double DELTA = 0.00000001;
// Path: src/test/filter/SincRepeaterTest.java
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Random;
import org.junit.Test;
import filter.InterpolatingArray;
import filter.SincRepeater;
import static test.TestUtils.DELTA;
package test.filter;
public class SincRepeaterTest {
@Test
public final void testMirroredGet() {
// 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4
// -6-5-4-3-2-1 0 1 2 3 4 5 6 7
double[] points = { 1, 2, 3, 4, 5, 6 };
| InterpolatingArray sia = new SincRepeater(points, 0); |
sweer/hex-image-compress | src/test/filter/SincRepeaterTest.java | // Path: src/filter/InterpolatingArray.java
// public abstract class InterpolatingArray {
//
// protected final double[] points;
//
// public abstract double get(double x);
//
// public abstract double get(int i);
//
// protected int order = 2;
//
// public InterpolatingArray(double[] points, int order) {
// this(points);
// this.order = order;
// }
//
// public InterpolatingArray(double[] points) {
// this.points = points;
// }
//
// public double[] getShiftedArray(double shift) {
// int length = points.length;
// double[] result = new double[length];
// for (int i = 0; i < length; i++) {
// result[i] = get(i+shift);
// }
// return result;
// }
//
// public final int length() {
// return points.length;
// }
//
// public interface Factory {
// InterpolatingArray getInstance(double[] points);
// }
//
// }
//
// Path: src/filter/SincRepeater.java
// public class SincRepeater extends SincInterpolatingArray {
//
// /**
// * @uml.property name="fACTORY"
// * @uml.associationEnd
// */
// private static final Factory FACTORY = new Factory();
//
// public SincRepeater(double[] points, int order) {
// super(points, order);
// }
//
// public SincRepeater(double[] points) {
// super(points);
// }
//
// @Override
// public double get(int i) {
// // @formatter:off
// // 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4
// // -6-5-4-3-2-1 0 1 2 3 4 5 6 7
// // @formatter:on
// int length = points.length;
// int j = (i % length + length) % length;
// return points[j];
// }
//
// /**
// * @return
// * @uml.property name="fACTORY"
// */
// public static Factory getFactory() {
// return FACTORY;
// }
//
// public static class Factory implements InterpolatingArray.Factory {
//
// @Override
// public SincRepeater getInstance(double[] points) {
// return new SincRepeater(points);
// }
//
// }
//
// }
//
// Path: src/test/TestUtils.java
// public static final double DELTA = 0.00000001;
| import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Random;
import org.junit.Test;
import filter.InterpolatingArray;
import filter.SincRepeater;
import static test.TestUtils.DELTA; | package test.filter;
public class SincRepeaterTest {
@Test
public final void testMirroredGet() {
// 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4
// -6-5-4-3-2-1 0 1 2 3 4 5 6 7
double[] points = { 1, 2, 3, 4, 5, 6 };
InterpolatingArray sia = new SincRepeater(points, 0);
| // Path: src/filter/InterpolatingArray.java
// public abstract class InterpolatingArray {
//
// protected final double[] points;
//
// public abstract double get(double x);
//
// public abstract double get(int i);
//
// protected int order = 2;
//
// public InterpolatingArray(double[] points, int order) {
// this(points);
// this.order = order;
// }
//
// public InterpolatingArray(double[] points) {
// this.points = points;
// }
//
// public double[] getShiftedArray(double shift) {
// int length = points.length;
// double[] result = new double[length];
// for (int i = 0; i < length; i++) {
// result[i] = get(i+shift);
// }
// return result;
// }
//
// public final int length() {
// return points.length;
// }
//
// public interface Factory {
// InterpolatingArray getInstance(double[] points);
// }
//
// }
//
// Path: src/filter/SincRepeater.java
// public class SincRepeater extends SincInterpolatingArray {
//
// /**
// * @uml.property name="fACTORY"
// * @uml.associationEnd
// */
// private static final Factory FACTORY = new Factory();
//
// public SincRepeater(double[] points, int order) {
// super(points, order);
// }
//
// public SincRepeater(double[] points) {
// super(points);
// }
//
// @Override
// public double get(int i) {
// // @formatter:off
// // 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4
// // -6-5-4-3-2-1 0 1 2 3 4 5 6 7
// // @formatter:on
// int length = points.length;
// int j = (i % length + length) % length;
// return points[j];
// }
//
// /**
// * @return
// * @uml.property name="fACTORY"
// */
// public static Factory getFactory() {
// return FACTORY;
// }
//
// public static class Factory implements InterpolatingArray.Factory {
//
// @Override
// public SincRepeater getInstance(double[] points) {
// return new SincRepeater(points);
// }
//
// }
//
// }
//
// Path: src/test/TestUtils.java
// public static final double DELTA = 0.00000001;
// Path: src/test/filter/SincRepeaterTest.java
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Random;
import org.junit.Test;
import filter.InterpolatingArray;
import filter.SincRepeater;
import static test.TestUtils.DELTA;
package test.filter;
public class SincRepeaterTest {
@Test
public final void testMirroredGet() {
// 1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4
// -6-5-4-3-2-1 0 1 2 3 4 5 6 7
double[] points = { 1, 2, 3, 4, 5, 6 };
InterpolatingArray sia = new SincRepeater(points, 0);
| assertEquals(1, sia.get(0), DELTA); |
sweer/hex-image-compress | src/test/filter/RectangleDiagonalTest.java | // Path: src/test/TestUtils.java
// public static final double DELTA = 0.00000001;
//
// Path: src/filter/RectangleDiagonal.java
// public class RectangleDiagonal {
//
// public static double[] getDiagonal(int n, double[][] data) {
// final int height = data.length;
// final int width = data[0].length;
//
// DiagonalParameters dp = DiagonalParameters.getDiagonalParameters(width,
// height, n);
//
// double diagonal[] = new double[dp.diagonalLength];
//
// for (int i = 0; i < dp.diagonalLength; i++) {
// diagonal[i] = data[dp.startY - i][dp.startX + i];
// }
//
// return diagonal;
// }
//
// static public class DiagonalParameters {
// final public int diagonalLength;
// final public int startX;
// final public int startY;
//
// private DiagonalParameters(int diagonalLength, int startX, int startY) {
// this.diagonalLength = diagonalLength;
// this.startX = startX;
// this.startY = startY;
// }
//
// public static DiagonalParameters getDiagonalParameters(int width,
// int height, int n) {
// if (width == height) {
// return getSquareDiagonalParameters(width, height, n);
// } else if (width < height) {
// return getTallRectangleDiagonalParameters(width, height, n);
// } else {
// return getLongRectangleDiagonalParameters(width, height, n);
// }
// }
//
// private static DiagonalParameters getLongRectangleDiagonalParameters(
// int width, int height, int n) {
// final int diagonalLength;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// diagonalLength = n + 1;
// } else {
// startX = n - height + 1;
// startY = height - 1;
// final int fromTheLastColumn = (width - 1) - startX;
// if (fromTheLastColumn < height - 1) {
// diagonalLength = fromTheLastColumn + 1;
// } else {
// diagonalLength = height;
// }
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
//
// private static DiagonalParameters getTallRectangleDiagonalParameters(
// int width, int height, int n) {
//
// final int diagonalLength;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// if (n < width - 1) {
// diagonalLength = n + 1;
// } else {
// diagonalLength = width;
// }
//
// } else {
// startX = n - height + 1;
// startY = height - 1;
// final int fromTheLastColumn = (width - 1) - startX;
// diagonalLength = fromTheLastColumn + 1;
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
//
// private static DiagonalParameters getSquareDiagonalParameters(
// int width, int height, int n) {
//
// final int distanceFromCornerDiagonal = Math.abs(n - (width - 1));
// final int diagonalLength = width - distanceFromCornerDiagonal;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// } else {
// startX = n - width + 1;
// startY = height - 1;
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
// }
//
// }
| import static org.junit.Assert.*;
import static test.TestUtils.DELTA;
import org.junit.Test;
import filter.RectangleDiagonal; | package test.filter;
public class RectangleDiagonalTest {
@Test
public final void testGetDiagonalTallRectangleAfterCorner() {
double[][] tallRectangle = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 },
{ 10, 11, 12 }
};
double[] expected = { 11, 9 };
| // Path: src/test/TestUtils.java
// public static final double DELTA = 0.00000001;
//
// Path: src/filter/RectangleDiagonal.java
// public class RectangleDiagonal {
//
// public static double[] getDiagonal(int n, double[][] data) {
// final int height = data.length;
// final int width = data[0].length;
//
// DiagonalParameters dp = DiagonalParameters.getDiagonalParameters(width,
// height, n);
//
// double diagonal[] = new double[dp.diagonalLength];
//
// for (int i = 0; i < dp.diagonalLength; i++) {
// diagonal[i] = data[dp.startY - i][dp.startX + i];
// }
//
// return diagonal;
// }
//
// static public class DiagonalParameters {
// final public int diagonalLength;
// final public int startX;
// final public int startY;
//
// private DiagonalParameters(int diagonalLength, int startX, int startY) {
// this.diagonalLength = diagonalLength;
// this.startX = startX;
// this.startY = startY;
// }
//
// public static DiagonalParameters getDiagonalParameters(int width,
// int height, int n) {
// if (width == height) {
// return getSquareDiagonalParameters(width, height, n);
// } else if (width < height) {
// return getTallRectangleDiagonalParameters(width, height, n);
// } else {
// return getLongRectangleDiagonalParameters(width, height, n);
// }
// }
//
// private static DiagonalParameters getLongRectangleDiagonalParameters(
// int width, int height, int n) {
// final int diagonalLength;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// diagonalLength = n + 1;
// } else {
// startX = n - height + 1;
// startY = height - 1;
// final int fromTheLastColumn = (width - 1) - startX;
// if (fromTheLastColumn < height - 1) {
// diagonalLength = fromTheLastColumn + 1;
// } else {
// diagonalLength = height;
// }
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
//
// private static DiagonalParameters getTallRectangleDiagonalParameters(
// int width, int height, int n) {
//
// final int diagonalLength;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// if (n < width - 1) {
// diagonalLength = n + 1;
// } else {
// diagonalLength = width;
// }
//
// } else {
// startX = n - height + 1;
// startY = height - 1;
// final int fromTheLastColumn = (width - 1) - startX;
// diagonalLength = fromTheLastColumn + 1;
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
//
// private static DiagonalParameters getSquareDiagonalParameters(
// int width, int height, int n) {
//
// final int distanceFromCornerDiagonal = Math.abs(n - (width - 1));
// final int diagonalLength = width - distanceFromCornerDiagonal;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// } else {
// startX = n - width + 1;
// startY = height - 1;
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
// }
//
// }
// Path: src/test/filter/RectangleDiagonalTest.java
import static org.junit.Assert.*;
import static test.TestUtils.DELTA;
import org.junit.Test;
import filter.RectangleDiagonal;
package test.filter;
public class RectangleDiagonalTest {
@Test
public final void testGetDiagonalTallRectangleAfterCorner() {
double[][] tallRectangle = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 },
{ 10, 11, 12 }
};
double[] expected = { 11, 9 };
| double[] actual = RectangleDiagonal.getDiagonal(4, tallRectangle); |
sweer/hex-image-compress | src/test/filter/RectangleDiagonalTest.java | // Path: src/test/TestUtils.java
// public static final double DELTA = 0.00000001;
//
// Path: src/filter/RectangleDiagonal.java
// public class RectangleDiagonal {
//
// public static double[] getDiagonal(int n, double[][] data) {
// final int height = data.length;
// final int width = data[0].length;
//
// DiagonalParameters dp = DiagonalParameters.getDiagonalParameters(width,
// height, n);
//
// double diagonal[] = new double[dp.diagonalLength];
//
// for (int i = 0; i < dp.diagonalLength; i++) {
// diagonal[i] = data[dp.startY - i][dp.startX + i];
// }
//
// return diagonal;
// }
//
// static public class DiagonalParameters {
// final public int diagonalLength;
// final public int startX;
// final public int startY;
//
// private DiagonalParameters(int diagonalLength, int startX, int startY) {
// this.diagonalLength = diagonalLength;
// this.startX = startX;
// this.startY = startY;
// }
//
// public static DiagonalParameters getDiagonalParameters(int width,
// int height, int n) {
// if (width == height) {
// return getSquareDiagonalParameters(width, height, n);
// } else if (width < height) {
// return getTallRectangleDiagonalParameters(width, height, n);
// } else {
// return getLongRectangleDiagonalParameters(width, height, n);
// }
// }
//
// private static DiagonalParameters getLongRectangleDiagonalParameters(
// int width, int height, int n) {
// final int diagonalLength;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// diagonalLength = n + 1;
// } else {
// startX = n - height + 1;
// startY = height - 1;
// final int fromTheLastColumn = (width - 1) - startX;
// if (fromTheLastColumn < height - 1) {
// diagonalLength = fromTheLastColumn + 1;
// } else {
// diagonalLength = height;
// }
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
//
// private static DiagonalParameters getTallRectangleDiagonalParameters(
// int width, int height, int n) {
//
// final int diagonalLength;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// if (n < width - 1) {
// diagonalLength = n + 1;
// } else {
// diagonalLength = width;
// }
//
// } else {
// startX = n - height + 1;
// startY = height - 1;
// final int fromTheLastColumn = (width - 1) - startX;
// diagonalLength = fromTheLastColumn + 1;
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
//
// private static DiagonalParameters getSquareDiagonalParameters(
// int width, int height, int n) {
//
// final int distanceFromCornerDiagonal = Math.abs(n - (width - 1));
// final int diagonalLength = width - distanceFromCornerDiagonal;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// } else {
// startX = n - width + 1;
// startY = height - 1;
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
// }
//
// }
| import static org.junit.Assert.*;
import static test.TestUtils.DELTA;
import org.junit.Test;
import filter.RectangleDiagonal; | package test.filter;
public class RectangleDiagonalTest {
@Test
public final void testGetDiagonalTallRectangleAfterCorner() {
double[][] tallRectangle = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 },
{ 10, 11, 12 }
};
double[] expected = { 11, 9 };
double[] actual = RectangleDiagonal.getDiagonal(4, tallRectangle);
| // Path: src/test/TestUtils.java
// public static final double DELTA = 0.00000001;
//
// Path: src/filter/RectangleDiagonal.java
// public class RectangleDiagonal {
//
// public static double[] getDiagonal(int n, double[][] data) {
// final int height = data.length;
// final int width = data[0].length;
//
// DiagonalParameters dp = DiagonalParameters.getDiagonalParameters(width,
// height, n);
//
// double diagonal[] = new double[dp.diagonalLength];
//
// for (int i = 0; i < dp.diagonalLength; i++) {
// diagonal[i] = data[dp.startY - i][dp.startX + i];
// }
//
// return diagonal;
// }
//
// static public class DiagonalParameters {
// final public int diagonalLength;
// final public int startX;
// final public int startY;
//
// private DiagonalParameters(int diagonalLength, int startX, int startY) {
// this.diagonalLength = diagonalLength;
// this.startX = startX;
// this.startY = startY;
// }
//
// public static DiagonalParameters getDiagonalParameters(int width,
// int height, int n) {
// if (width == height) {
// return getSquareDiagonalParameters(width, height, n);
// } else if (width < height) {
// return getTallRectangleDiagonalParameters(width, height, n);
// } else {
// return getLongRectangleDiagonalParameters(width, height, n);
// }
// }
//
// private static DiagonalParameters getLongRectangleDiagonalParameters(
// int width, int height, int n) {
// final int diagonalLength;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// diagonalLength = n + 1;
// } else {
// startX = n - height + 1;
// startY = height - 1;
// final int fromTheLastColumn = (width - 1) - startX;
// if (fromTheLastColumn < height - 1) {
// diagonalLength = fromTheLastColumn + 1;
// } else {
// diagonalLength = height;
// }
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
//
// private static DiagonalParameters getTallRectangleDiagonalParameters(
// int width, int height, int n) {
//
// final int diagonalLength;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// if (n < width - 1) {
// diagonalLength = n + 1;
// } else {
// diagonalLength = width;
// }
//
// } else {
// startX = n - height + 1;
// startY = height - 1;
// final int fromTheLastColumn = (width - 1) - startX;
// diagonalLength = fromTheLastColumn + 1;
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
//
// private static DiagonalParameters getSquareDiagonalParameters(
// int width, int height, int n) {
//
// final int distanceFromCornerDiagonal = Math.abs(n - (width - 1));
// final int diagonalLength = width - distanceFromCornerDiagonal;
// final int startX;
// final int startY;
// if (n < height) {
// startX = 0;
// startY = n;
// } else {
// startX = n - width + 1;
// startY = height - 1;
// }
//
// return new DiagonalParameters(diagonalLength, startX, startY);
// }
// }
//
// }
// Path: src/test/filter/RectangleDiagonalTest.java
import static org.junit.Assert.*;
import static test.TestUtils.DELTA;
import org.junit.Test;
import filter.RectangleDiagonal;
package test.filter;
public class RectangleDiagonalTest {
@Test
public final void testGetDiagonalTallRectangleAfterCorner() {
double[][] tallRectangle = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 },
{ 10, 11, 12 }
};
double[] expected = { 11, 9 };
double[] actual = RectangleDiagonal.getDiagonal(4, tallRectangle);
| assertArrayEquals(expected, actual, DELTA); |
sweer/hex-image-compress | src/test/pipeline/EncoderTest.java | // Path: src/lattice/LongLattice.java
// public static class Run {
// public short x;
// public short y;
// public short length;
//
// public Run(short x, short y, short length) {
// this.x = x;
// this.y = y;
// this.length = length;
// }
// }
//
// Path: src/pipeline/Encoder.java
// public class Encoder {
// //@formatter:on
// /**
// * @author Aleksejs Truhans
// */
// public static class Statistics {
// private int compressedHeaderSizeBytes;
// private int compressedLatticeSizeBytes;
// private int remainderBitsSizeBytes;
// private int NanRunsSizeBytes;
//
// public int getCompressedHeaderSizeBytes() {
// return compressedHeaderSizeBytes;
// }
//
// public int getCompressedLatticeSizeBytes() {
// return compressedLatticeSizeBytes;
// }
//
// public int getRemainderBitsSizeBytes() {
// return remainderBitsSizeBytes;
// }
//
// public int getNanRunsSizeBytes() {
// return NanRunsSizeBytes;
// }
// }
//
// private final LongLattice source;
// private final Statistics statistics = new Statistics();
//
// public Encoder(LongLattice source) {
// this.source = source;
// }
//
// public Encoder(BufferedImage sourceImage) {
// this(representImageAsHexagonalLattice(sourceImage));
// }
//
// public byte[] encode() {
// List<byte[]> data = new LinkedList<byte[]>();
// HexByteRavelet ravelet = new HexByteRavelet(source);
// ravelet.encode();
//
// byte[] compressedHeader = Compressor.compress(generateHeader(ravelet));
// statistics.compressedHeaderSizeBytes = compressedHeader.length;
// data.add(ArrayUtils.intAsByteArray(compressedHeader.length));
// data.add(compressedHeader);
//
// byte[] compressedLattice = Compressor.compress(ravelet.getDataAsByteStream());
// statistics.compressedLatticeSizeBytes = compressedLattice.length;
// data.add(ArrayUtils.intAsByteArray(compressedLattice.length));
// data.add(compressedLattice);
//
// List<Run> nanRuns = ravelet.getNanRuns();
// byte[] nanRunsBytes = generateNanRuns(nanRuns);
// statistics.NanRunsSizeBytes = nanRunsBytes.length;
// data.add(ArrayUtils.intAsByteArray(nanRunsBytes.length));
// data.add(nanRunsBytes);
//
// byte[] remainderBits = Compressor.compress(ravelet.getReminderBitStream());
// statistics.remainderBitsSizeBytes = remainderBits.length;
// data.add(ArrayUtils.intAsByteArray(remainderBits.length));
// data.add(remainderBits);
//
// return ArrayUtils.joinArrays(data);
// }
//
// public static byte[] generateNanRuns(List<LongLattice.Run> nanRuns) {
// try {
// ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
// DataOutputStream dataOut = new DataOutputStream(byteOut);
//
// for (Run run : nanRuns) {
// dataOut.writeShort((short) run.x);
// dataOut.writeShort((short) run.y);
// dataOut.writeShort((short) run.length);
// }
//
// return byteOut.toByteArray();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static LongLattice representImageAsHexagonalLattice(BufferedImage sourceImage) {
// double[][] source = ImageUtils.imageRasterToDoubleArray(sourceImage);
// return representImageAsHexagonalLattice(source);
// }
//
// public static LongLattice representImageAsHexagonalLattice(double[][] source) {
// DoubleLattice hexDoubleLattice = H2O.o2h(source);
// LongLattice hexLongLattice = LongLattice.fromLattice(hexDoubleLattice);
// return hexLongLattice;
// }
//
// public static byte[] generateHeader(LongLattice lattice) {
// try {
// ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
// DataOutputStream dataOut = new DataOutputStream(byteOut);
//
// dataOut.writeShort((short) lattice.ox);
// dataOut.writeShort((short) lattice.oy);
// dataOut.writeShort((short) lattice.getData()[0].length);
// dataOut.writeShort((short) lattice.getData().length);
// dataOut.writeDouble(lattice.min);
// dataOut.writeDouble(lattice.factor);
//
// short[][] NANPositions = lattice.getNANPositionStream();
// for (short a[] : NANPositions) {
// dataOut.writeShort(a[0]);
// dataOut.writeShort(a[1]);
// }
// return byteOut.toByteArray();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public Statistics getStatistics() {
// return statistics;
// }
//
// public LongLattice getLattice() {
// return source;
// }
//
// }
| import static org.junit.Assert.assertArrayEquals;
import java.util.Arrays;
import java.util.List;
import lattice.LongLattice.Run;
import org.junit.Test;
import pipeline.Encoder; | package test.pipeline;
public class EncoderTest {
@Test
public final void testGenerateNanRuns() {
//@formatter:off | // Path: src/lattice/LongLattice.java
// public static class Run {
// public short x;
// public short y;
// public short length;
//
// public Run(short x, short y, short length) {
// this.x = x;
// this.y = y;
// this.length = length;
// }
// }
//
// Path: src/pipeline/Encoder.java
// public class Encoder {
// //@formatter:on
// /**
// * @author Aleksejs Truhans
// */
// public static class Statistics {
// private int compressedHeaderSizeBytes;
// private int compressedLatticeSizeBytes;
// private int remainderBitsSizeBytes;
// private int NanRunsSizeBytes;
//
// public int getCompressedHeaderSizeBytes() {
// return compressedHeaderSizeBytes;
// }
//
// public int getCompressedLatticeSizeBytes() {
// return compressedLatticeSizeBytes;
// }
//
// public int getRemainderBitsSizeBytes() {
// return remainderBitsSizeBytes;
// }
//
// public int getNanRunsSizeBytes() {
// return NanRunsSizeBytes;
// }
// }
//
// private final LongLattice source;
// private final Statistics statistics = new Statistics();
//
// public Encoder(LongLattice source) {
// this.source = source;
// }
//
// public Encoder(BufferedImage sourceImage) {
// this(representImageAsHexagonalLattice(sourceImage));
// }
//
// public byte[] encode() {
// List<byte[]> data = new LinkedList<byte[]>();
// HexByteRavelet ravelet = new HexByteRavelet(source);
// ravelet.encode();
//
// byte[] compressedHeader = Compressor.compress(generateHeader(ravelet));
// statistics.compressedHeaderSizeBytes = compressedHeader.length;
// data.add(ArrayUtils.intAsByteArray(compressedHeader.length));
// data.add(compressedHeader);
//
// byte[] compressedLattice = Compressor.compress(ravelet.getDataAsByteStream());
// statistics.compressedLatticeSizeBytes = compressedLattice.length;
// data.add(ArrayUtils.intAsByteArray(compressedLattice.length));
// data.add(compressedLattice);
//
// List<Run> nanRuns = ravelet.getNanRuns();
// byte[] nanRunsBytes = generateNanRuns(nanRuns);
// statistics.NanRunsSizeBytes = nanRunsBytes.length;
// data.add(ArrayUtils.intAsByteArray(nanRunsBytes.length));
// data.add(nanRunsBytes);
//
// byte[] remainderBits = Compressor.compress(ravelet.getReminderBitStream());
// statistics.remainderBitsSizeBytes = remainderBits.length;
// data.add(ArrayUtils.intAsByteArray(remainderBits.length));
// data.add(remainderBits);
//
// return ArrayUtils.joinArrays(data);
// }
//
// public static byte[] generateNanRuns(List<LongLattice.Run> nanRuns) {
// try {
// ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
// DataOutputStream dataOut = new DataOutputStream(byteOut);
//
// for (Run run : nanRuns) {
// dataOut.writeShort((short) run.x);
// dataOut.writeShort((short) run.y);
// dataOut.writeShort((short) run.length);
// }
//
// return byteOut.toByteArray();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static LongLattice representImageAsHexagonalLattice(BufferedImage sourceImage) {
// double[][] source = ImageUtils.imageRasterToDoubleArray(sourceImage);
// return representImageAsHexagonalLattice(source);
// }
//
// public static LongLattice representImageAsHexagonalLattice(double[][] source) {
// DoubleLattice hexDoubleLattice = H2O.o2h(source);
// LongLattice hexLongLattice = LongLattice.fromLattice(hexDoubleLattice);
// return hexLongLattice;
// }
//
// public static byte[] generateHeader(LongLattice lattice) {
// try {
// ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
// DataOutputStream dataOut = new DataOutputStream(byteOut);
//
// dataOut.writeShort((short) lattice.ox);
// dataOut.writeShort((short) lattice.oy);
// dataOut.writeShort((short) lattice.getData()[0].length);
// dataOut.writeShort((short) lattice.getData().length);
// dataOut.writeDouble(lattice.min);
// dataOut.writeDouble(lattice.factor);
//
// short[][] NANPositions = lattice.getNANPositionStream();
// for (short a[] : NANPositions) {
// dataOut.writeShort(a[0]);
// dataOut.writeShort(a[1]);
// }
// return byteOut.toByteArray();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public Statistics getStatistics() {
// return statistics;
// }
//
// public LongLattice getLattice() {
// return source;
// }
//
// }
// Path: src/test/pipeline/EncoderTest.java
import static org.junit.Assert.assertArrayEquals;
import java.util.Arrays;
import java.util.List;
import lattice.LongLattice.Run;
import org.junit.Test;
import pipeline.Encoder;
package test.pipeline;
public class EncoderTest {
@Test
public final void testGenerateNanRuns() {
//@formatter:off | List<Run> source = Arrays.asList(new Run[] { |
sweer/hex-image-compress | src/test/pipeline/EncoderTest.java | // Path: src/lattice/LongLattice.java
// public static class Run {
// public short x;
// public short y;
// public short length;
//
// public Run(short x, short y, short length) {
// this.x = x;
// this.y = y;
// this.length = length;
// }
// }
//
// Path: src/pipeline/Encoder.java
// public class Encoder {
// //@formatter:on
// /**
// * @author Aleksejs Truhans
// */
// public static class Statistics {
// private int compressedHeaderSizeBytes;
// private int compressedLatticeSizeBytes;
// private int remainderBitsSizeBytes;
// private int NanRunsSizeBytes;
//
// public int getCompressedHeaderSizeBytes() {
// return compressedHeaderSizeBytes;
// }
//
// public int getCompressedLatticeSizeBytes() {
// return compressedLatticeSizeBytes;
// }
//
// public int getRemainderBitsSizeBytes() {
// return remainderBitsSizeBytes;
// }
//
// public int getNanRunsSizeBytes() {
// return NanRunsSizeBytes;
// }
// }
//
// private final LongLattice source;
// private final Statistics statistics = new Statistics();
//
// public Encoder(LongLattice source) {
// this.source = source;
// }
//
// public Encoder(BufferedImage sourceImage) {
// this(representImageAsHexagonalLattice(sourceImage));
// }
//
// public byte[] encode() {
// List<byte[]> data = new LinkedList<byte[]>();
// HexByteRavelet ravelet = new HexByteRavelet(source);
// ravelet.encode();
//
// byte[] compressedHeader = Compressor.compress(generateHeader(ravelet));
// statistics.compressedHeaderSizeBytes = compressedHeader.length;
// data.add(ArrayUtils.intAsByteArray(compressedHeader.length));
// data.add(compressedHeader);
//
// byte[] compressedLattice = Compressor.compress(ravelet.getDataAsByteStream());
// statistics.compressedLatticeSizeBytes = compressedLattice.length;
// data.add(ArrayUtils.intAsByteArray(compressedLattice.length));
// data.add(compressedLattice);
//
// List<Run> nanRuns = ravelet.getNanRuns();
// byte[] nanRunsBytes = generateNanRuns(nanRuns);
// statistics.NanRunsSizeBytes = nanRunsBytes.length;
// data.add(ArrayUtils.intAsByteArray(nanRunsBytes.length));
// data.add(nanRunsBytes);
//
// byte[] remainderBits = Compressor.compress(ravelet.getReminderBitStream());
// statistics.remainderBitsSizeBytes = remainderBits.length;
// data.add(ArrayUtils.intAsByteArray(remainderBits.length));
// data.add(remainderBits);
//
// return ArrayUtils.joinArrays(data);
// }
//
// public static byte[] generateNanRuns(List<LongLattice.Run> nanRuns) {
// try {
// ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
// DataOutputStream dataOut = new DataOutputStream(byteOut);
//
// for (Run run : nanRuns) {
// dataOut.writeShort((short) run.x);
// dataOut.writeShort((short) run.y);
// dataOut.writeShort((short) run.length);
// }
//
// return byteOut.toByteArray();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static LongLattice representImageAsHexagonalLattice(BufferedImage sourceImage) {
// double[][] source = ImageUtils.imageRasterToDoubleArray(sourceImage);
// return representImageAsHexagonalLattice(source);
// }
//
// public static LongLattice representImageAsHexagonalLattice(double[][] source) {
// DoubleLattice hexDoubleLattice = H2O.o2h(source);
// LongLattice hexLongLattice = LongLattice.fromLattice(hexDoubleLattice);
// return hexLongLattice;
// }
//
// public static byte[] generateHeader(LongLattice lattice) {
// try {
// ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
// DataOutputStream dataOut = new DataOutputStream(byteOut);
//
// dataOut.writeShort((short) lattice.ox);
// dataOut.writeShort((short) lattice.oy);
// dataOut.writeShort((short) lattice.getData()[0].length);
// dataOut.writeShort((short) lattice.getData().length);
// dataOut.writeDouble(lattice.min);
// dataOut.writeDouble(lattice.factor);
//
// short[][] NANPositions = lattice.getNANPositionStream();
// for (short a[] : NANPositions) {
// dataOut.writeShort(a[0]);
// dataOut.writeShort(a[1]);
// }
// return byteOut.toByteArray();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public Statistics getStatistics() {
// return statistics;
// }
//
// public LongLattice getLattice() {
// return source;
// }
//
// }
| import static org.junit.Assert.assertArrayEquals;
import java.util.Arrays;
import java.util.List;
import lattice.LongLattice.Run;
import org.junit.Test;
import pipeline.Encoder; | package test.pipeline;
public class EncoderTest {
@Test
public final void testGenerateNanRuns() {
//@formatter:off
List<Run> source = Arrays.asList(new Run[] {
new Run((short)3,(short)1,(short)2), new Run((short)2,(short)2,(short)1)
} );
byte[] expected = {0, 3, 0, 1, 0, 2, 0, 2, 0, 2, 0, 1};
//@formatter:on
| // Path: src/lattice/LongLattice.java
// public static class Run {
// public short x;
// public short y;
// public short length;
//
// public Run(short x, short y, short length) {
// this.x = x;
// this.y = y;
// this.length = length;
// }
// }
//
// Path: src/pipeline/Encoder.java
// public class Encoder {
// //@formatter:on
// /**
// * @author Aleksejs Truhans
// */
// public static class Statistics {
// private int compressedHeaderSizeBytes;
// private int compressedLatticeSizeBytes;
// private int remainderBitsSizeBytes;
// private int NanRunsSizeBytes;
//
// public int getCompressedHeaderSizeBytes() {
// return compressedHeaderSizeBytes;
// }
//
// public int getCompressedLatticeSizeBytes() {
// return compressedLatticeSizeBytes;
// }
//
// public int getRemainderBitsSizeBytes() {
// return remainderBitsSizeBytes;
// }
//
// public int getNanRunsSizeBytes() {
// return NanRunsSizeBytes;
// }
// }
//
// private final LongLattice source;
// private final Statistics statistics = new Statistics();
//
// public Encoder(LongLattice source) {
// this.source = source;
// }
//
// public Encoder(BufferedImage sourceImage) {
// this(representImageAsHexagonalLattice(sourceImage));
// }
//
// public byte[] encode() {
// List<byte[]> data = new LinkedList<byte[]>();
// HexByteRavelet ravelet = new HexByteRavelet(source);
// ravelet.encode();
//
// byte[] compressedHeader = Compressor.compress(generateHeader(ravelet));
// statistics.compressedHeaderSizeBytes = compressedHeader.length;
// data.add(ArrayUtils.intAsByteArray(compressedHeader.length));
// data.add(compressedHeader);
//
// byte[] compressedLattice = Compressor.compress(ravelet.getDataAsByteStream());
// statistics.compressedLatticeSizeBytes = compressedLattice.length;
// data.add(ArrayUtils.intAsByteArray(compressedLattice.length));
// data.add(compressedLattice);
//
// List<Run> nanRuns = ravelet.getNanRuns();
// byte[] nanRunsBytes = generateNanRuns(nanRuns);
// statistics.NanRunsSizeBytes = nanRunsBytes.length;
// data.add(ArrayUtils.intAsByteArray(nanRunsBytes.length));
// data.add(nanRunsBytes);
//
// byte[] remainderBits = Compressor.compress(ravelet.getReminderBitStream());
// statistics.remainderBitsSizeBytes = remainderBits.length;
// data.add(ArrayUtils.intAsByteArray(remainderBits.length));
// data.add(remainderBits);
//
// return ArrayUtils.joinArrays(data);
// }
//
// public static byte[] generateNanRuns(List<LongLattice.Run> nanRuns) {
// try {
// ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
// DataOutputStream dataOut = new DataOutputStream(byteOut);
//
// for (Run run : nanRuns) {
// dataOut.writeShort((short) run.x);
// dataOut.writeShort((short) run.y);
// dataOut.writeShort((short) run.length);
// }
//
// return byteOut.toByteArray();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public static LongLattice representImageAsHexagonalLattice(BufferedImage sourceImage) {
// double[][] source = ImageUtils.imageRasterToDoubleArray(sourceImage);
// return representImageAsHexagonalLattice(source);
// }
//
// public static LongLattice representImageAsHexagonalLattice(double[][] source) {
// DoubleLattice hexDoubleLattice = H2O.o2h(source);
// LongLattice hexLongLattice = LongLattice.fromLattice(hexDoubleLattice);
// return hexLongLattice;
// }
//
// public static byte[] generateHeader(LongLattice lattice) {
// try {
// ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
// DataOutputStream dataOut = new DataOutputStream(byteOut);
//
// dataOut.writeShort((short) lattice.ox);
// dataOut.writeShort((short) lattice.oy);
// dataOut.writeShort((short) lattice.getData()[0].length);
// dataOut.writeShort((short) lattice.getData().length);
// dataOut.writeDouble(lattice.min);
// dataOut.writeDouble(lattice.factor);
//
// short[][] NANPositions = lattice.getNANPositionStream();
// for (short a[] : NANPositions) {
// dataOut.writeShort(a[0]);
// dataOut.writeShort(a[1]);
// }
// return byteOut.toByteArray();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// public Statistics getStatistics() {
// return statistics;
// }
//
// public LongLattice getLattice() {
// return source;
// }
//
// }
// Path: src/test/pipeline/EncoderTest.java
import static org.junit.Assert.assertArrayEquals;
import java.util.Arrays;
import java.util.List;
import lattice.LongLattice.Run;
import org.junit.Test;
import pipeline.Encoder;
package test.pipeline;
public class EncoderTest {
@Test
public final void testGenerateNanRuns() {
//@formatter:off
List<Run> source = Arrays.asList(new Run[] {
new Run((short)3,(short)1,(short)2), new Run((short)2,(short)2,(short)1)
} );
byte[] expected = {0, 3, 0, 1, 0, 2, 0, 2, 0, 2, 0, 1};
//@formatter:on
| byte[] actual = Encoder.generateNanRuns(source); |
colin-lee/mybatis-spring-support | src/main/java/com/github/mybatis/interceptor/MasterSlaveInterceptor.java | // Path: src/main/java/com/github/mybatis/util/ReflectionUtil.java
// public class ReflectionUtil {
// private static final LoadingCache<String, Field> CACHE = buildCache();
//
// private static LoadingCache<String, Field> buildCache() {
// return CacheBuilder.newBuilder().maximumSize(1000).build(new CacheLoader<String, Field>() {
// @Override
// public Field load(String key) throws Exception {
// int pos = key.lastIndexOf('#');
// String className = key.substring(0, pos);
// String fieldName = key.substring(pos + 1);
// Class clz = Class.forName(className);
// Field field = getDeclaredField(clz, fieldName);
// makeAccessible(field);
// return field;
// }
// });
// }
//
// /**
// * 循环向上转型,获取对象的DeclaredField.
// */
// public static void makeAccessible(final Field field) {
// if (!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) {
// field.setAccessible(true);
// }
// }
//
// /**
// * 循环向上转型,获取类对象的DeclaredField.
// */
// public static Field getDeclaredField(Class<?> clz, final String fieldName) {
// for (Class<?> s = clz; s != Object.class; s = s.getSuperclass()) {
// try {
// return s.getDeclaredField(fieldName);
// } catch (NoSuchFieldException ignored) {
// }
// }
// return null;
// }
//
// /**
// * 获取类属性,无视private/protected限制,不经过getter方法
// *
// * @param object 类对象
// * @param fieldName 属性名
// * @param <T> 目标类型
// * @return
// */
// @SuppressWarnings("unchecked")
// public static <T> T getFieldValue(Object object, String fieldName) {
// Field field = CACHE.getUnchecked(object.getClass().getName() + '#' + fieldName);
// if (field == null) {
// throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
// }
//
// Object result = null;
// try {
// result = field.get(object);
// } catch (IllegalAccessException ignored) {
// }
// return (T) result;
// }
// }
| import com.github.mybatis.util.ReflectionUtil;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import java.sql.Connection;
import java.util.Properties; | package com.github.mybatis.interceptor;
/**
* 读写分离插件
*
* Created by lirui on 15/1/7.
*/
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class})})
public class MasterSlaveInterceptor implements Interceptor {
private static final ThreadLocal<Boolean> READ_ONLY_LOCAL = new ThreadLocal<Boolean>();
public static boolean isReadOnly() {
return Boolean.TRUE.equals(READ_ONLY_LOCAL.get());
}
@Override
public Object intercept(Invocation invocation) throws Throwable {
StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
MappedStatement mappedStatement;
if (statementHandler instanceof RoutingStatementHandler) { | // Path: src/main/java/com/github/mybatis/util/ReflectionUtil.java
// public class ReflectionUtil {
// private static final LoadingCache<String, Field> CACHE = buildCache();
//
// private static LoadingCache<String, Field> buildCache() {
// return CacheBuilder.newBuilder().maximumSize(1000).build(new CacheLoader<String, Field>() {
// @Override
// public Field load(String key) throws Exception {
// int pos = key.lastIndexOf('#');
// String className = key.substring(0, pos);
// String fieldName = key.substring(pos + 1);
// Class clz = Class.forName(className);
// Field field = getDeclaredField(clz, fieldName);
// makeAccessible(field);
// return field;
// }
// });
// }
//
// /**
// * 循环向上转型,获取对象的DeclaredField.
// */
// public static void makeAccessible(final Field field) {
// if (!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) {
// field.setAccessible(true);
// }
// }
//
// /**
// * 循环向上转型,获取类对象的DeclaredField.
// */
// public static Field getDeclaredField(Class<?> clz, final String fieldName) {
// for (Class<?> s = clz; s != Object.class; s = s.getSuperclass()) {
// try {
// return s.getDeclaredField(fieldName);
// } catch (NoSuchFieldException ignored) {
// }
// }
// return null;
// }
//
// /**
// * 获取类属性,无视private/protected限制,不经过getter方法
// *
// * @param object 类对象
// * @param fieldName 属性名
// * @param <T> 目标类型
// * @return
// */
// @SuppressWarnings("unchecked")
// public static <T> T getFieldValue(Object object, String fieldName) {
// Field field = CACHE.getUnchecked(object.getClass().getName() + '#' + fieldName);
// if (field == null) {
// throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");
// }
//
// Object result = null;
// try {
// result = field.get(object);
// } catch (IllegalAccessException ignored) {
// }
// return (T) result;
// }
// }
// Path: src/main/java/com/github/mybatis/interceptor/MasterSlaveInterceptor.java
import com.github.mybatis.util.ReflectionUtil;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import java.sql.Connection;
import java.util.Properties;
package com.github.mybatis.interceptor;
/**
* 读写分离插件
*
* Created by lirui on 15/1/7.
*/
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class})})
public class MasterSlaveInterceptor implements Interceptor {
private static final ThreadLocal<Boolean> READ_ONLY_LOCAL = new ThreadLocal<Boolean>();
public static boolean isReadOnly() {
return Boolean.TRUE.equals(READ_ONLY_LOCAL.get());
}
@Override
public Object intercept(Invocation invocation) throws Throwable {
StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
MappedStatement mappedStatement;
if (statementHandler instanceof RoutingStatementHandler) { | StatementHandler delegate = ReflectionUtil.getFieldValue(statementHandler, "delegate"); |
colin-lee/mybatis-spring-support | src/main/java/com/github/mybatis/spring/LazyConnection.java | // Path: src/main/java/com/github/mybatis/interceptor/MasterSlaveInterceptor.java
// @Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class})})
// public class MasterSlaveInterceptor implements Interceptor {
// private static final ThreadLocal<Boolean> READ_ONLY_LOCAL = new ThreadLocal<Boolean>();
//
// public static boolean isReadOnly() {
// return Boolean.TRUE.equals(READ_ONLY_LOCAL.get());
// }
//
// @Override
// public Object intercept(Invocation invocation) throws Throwable {
// StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
// MappedStatement mappedStatement;
// if (statementHandler instanceof RoutingStatementHandler) {
// StatementHandler delegate = ReflectionUtil.getFieldValue(statementHandler, "delegate");
// mappedStatement = ReflectionUtil.getFieldValue(delegate, "mappedStatement");
// } else {
// mappedStatement = ReflectionUtil.getFieldValue(statementHandler, "mappedStatement");
// }
// // 读写分离设置使用哪个数据源
// Boolean readOnly = Boolean.FALSE;
// if (mappedStatement.getSqlCommandType() == SqlCommandType.SELECT) {
// final String sql = statementHandler.getBoundSql().getSql();
// String s = sql.toLowerCase();
// readOnly = !(s.contains("last_insert_id()") || s.contains("row_count()"));
// }
// READ_ONLY_LOCAL.set(readOnly);
//
// return invocation.proceed();
// }
//
// @Override
// public Object plugin(Object target) {
// if (target instanceof StatementHandler) {
// return Plugin.wrap(target, this);
// } else {
// return target;
// }
// }
//
// @Override
// public void setProperties(Properties properties) {
//
// }
//
// }
| import com.alibaba.druid.pool.DruidDataSource;
import com.github.mybatis.interceptor.MasterSlaveInterceptor;
import com.github.trace.TraceContext;
import com.google.common.base.CharMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException; | // predicate: slave is always available
target = getTargetConnection(method);
}
}
// Target Connection already fetched,
// or target Connection necessary for current operation ->
// invoke method on target connection.
try {
return method.invoke(target, args);
} catch (InvocationTargetException ex) {
throw ex.getTargetException();
} catch (Exception e) {
log.error("[{}] method={}", router.getConfigName(), methodName, e);
throw new RuntimeException("cannot invoke " + methodName, e);
}
}
/**
* Return whether the proxy currently holds a target Connection.
*/
private boolean hasTargetConnection() {
return (this.target != null);
}
/**
* Return the target Connection, fetching it and initializing it if necessary.
*/
private Connection getTargetConnection(Method operation) throws SQLException {
if (this.target == null) { | // Path: src/main/java/com/github/mybatis/interceptor/MasterSlaveInterceptor.java
// @Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class})})
// public class MasterSlaveInterceptor implements Interceptor {
// private static final ThreadLocal<Boolean> READ_ONLY_LOCAL = new ThreadLocal<Boolean>();
//
// public static boolean isReadOnly() {
// return Boolean.TRUE.equals(READ_ONLY_LOCAL.get());
// }
//
// @Override
// public Object intercept(Invocation invocation) throws Throwable {
// StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
// MappedStatement mappedStatement;
// if (statementHandler instanceof RoutingStatementHandler) {
// StatementHandler delegate = ReflectionUtil.getFieldValue(statementHandler, "delegate");
// mappedStatement = ReflectionUtil.getFieldValue(delegate, "mappedStatement");
// } else {
// mappedStatement = ReflectionUtil.getFieldValue(statementHandler, "mappedStatement");
// }
// // 读写分离设置使用哪个数据源
// Boolean readOnly = Boolean.FALSE;
// if (mappedStatement.getSqlCommandType() == SqlCommandType.SELECT) {
// final String sql = statementHandler.getBoundSql().getSql();
// String s = sql.toLowerCase();
// readOnly = !(s.contains("last_insert_id()") || s.contains("row_count()"));
// }
// READ_ONLY_LOCAL.set(readOnly);
//
// return invocation.proceed();
// }
//
// @Override
// public Object plugin(Object target) {
// if (target instanceof StatementHandler) {
// return Plugin.wrap(target, this);
// } else {
// return target;
// }
// }
//
// @Override
// public void setProperties(Properties properties) {
//
// }
//
// }
// Path: src/main/java/com/github/mybatis/spring/LazyConnection.java
import com.alibaba.druid.pool.DruidDataSource;
import com.github.mybatis.interceptor.MasterSlaveInterceptor;
import com.github.trace.TraceContext;
import com.google.common.base.CharMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;
// predicate: slave is always available
target = getTargetConnection(method);
}
}
// Target Connection already fetched,
// or target Connection necessary for current operation ->
// invoke method on target connection.
try {
return method.invoke(target, args);
} catch (InvocationTargetException ex) {
throw ex.getTargetException();
} catch (Exception e) {
log.error("[{}] method={}", router.getConfigName(), methodName, e);
throw new RuntimeException("cannot invoke " + methodName, e);
}
}
/**
* Return whether the proxy currently holds a target Connection.
*/
private boolean hasTargetConnection() {
return (this.target != null);
}
/**
* Return the target Connection, fetching it and initializing it if necessary.
*/
private Connection getTargetConnection(Method operation) throws SQLException {
if (this.target == null) { | boolean readOnly = MasterSlaveInterceptor.isReadOnly(); |
colin-lee/mybatis-spring-support | src/test/java/com/github/mybatis/spring/AutowireTest.java | // Path: src/test/java/com/github/mybatis/entity/Blog.java
// @Table(name = "blog")
// public class Blog extends IdEntity {
// @Column
// private String author;
//
// @Column
// private String content;
//
// @Column
// private Date accessDate;
//
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
// public String getContent() {
// return content;
// }
//
// public void setContent(String content) {
// this.content = content;
// }
//
// public Date getAccessDate() {
// return accessDate;
// }
//
// public void setAccessDate(Date accessDate) {
// this.accessDate = accessDate;
// }
// }
//
// Path: src/test/java/com/github/mybatis/mapper/BlogMapper.java
// public interface BlogMapper extends ICrudPaginationMapper<Blog> {
// @Delete("delete from blog")
// int myDelete();
//
// @Select("select count(0) from blog")
// int myCount();
//
// @Update("create table IF NOT EXISTS blog (\n" +
// " id int PRIMARY KEY AUTO_INCREMENT NOT NULL,\n" +
// " author VARCHAR(60) NOT NULL,\n" +
// " content TEXT NOT NULL,\n" +
// " access_date TIMESTAMP\n" +
// ")")
// int createTable();
// }
| import com.github.mybatis.entity.Blog;
import com.github.mybatis.mapper.BlogMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.PostConstruct;
import java.util.Date;
import static org.junit.Assert.assertTrue; | package com.github.mybatis.spring;
/**
* 测试autowire
* Created by lirui on 15/1/7.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class AutowireTest {
@Autowired | // Path: src/test/java/com/github/mybatis/entity/Blog.java
// @Table(name = "blog")
// public class Blog extends IdEntity {
// @Column
// private String author;
//
// @Column
// private String content;
//
// @Column
// private Date accessDate;
//
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
// public String getContent() {
// return content;
// }
//
// public void setContent(String content) {
// this.content = content;
// }
//
// public Date getAccessDate() {
// return accessDate;
// }
//
// public void setAccessDate(Date accessDate) {
// this.accessDate = accessDate;
// }
// }
//
// Path: src/test/java/com/github/mybatis/mapper/BlogMapper.java
// public interface BlogMapper extends ICrudPaginationMapper<Blog> {
// @Delete("delete from blog")
// int myDelete();
//
// @Select("select count(0) from blog")
// int myCount();
//
// @Update("create table IF NOT EXISTS blog (\n" +
// " id int PRIMARY KEY AUTO_INCREMENT NOT NULL,\n" +
// " author VARCHAR(60) NOT NULL,\n" +
// " content TEXT NOT NULL,\n" +
// " access_date TIMESTAMP\n" +
// ")")
// int createTable();
// }
// Path: src/test/java/com/github/mybatis/spring/AutowireTest.java
import com.github.mybatis.entity.Blog;
import com.github.mybatis.mapper.BlogMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.PostConstruct;
import java.util.Date;
import static org.junit.Assert.assertTrue;
package com.github.mybatis.spring;
/**
* 测试autowire
* Created by lirui on 15/1/7.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class AutowireTest {
@Autowired | private BlogMapper mapper; |
colin-lee/mybatis-spring-support | src/test/java/com/github/mybatis/spring/AutowireTest.java | // Path: src/test/java/com/github/mybatis/entity/Blog.java
// @Table(name = "blog")
// public class Blog extends IdEntity {
// @Column
// private String author;
//
// @Column
// private String content;
//
// @Column
// private Date accessDate;
//
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
// public String getContent() {
// return content;
// }
//
// public void setContent(String content) {
// this.content = content;
// }
//
// public Date getAccessDate() {
// return accessDate;
// }
//
// public void setAccessDate(Date accessDate) {
// this.accessDate = accessDate;
// }
// }
//
// Path: src/test/java/com/github/mybatis/mapper/BlogMapper.java
// public interface BlogMapper extends ICrudPaginationMapper<Blog> {
// @Delete("delete from blog")
// int myDelete();
//
// @Select("select count(0) from blog")
// int myCount();
//
// @Update("create table IF NOT EXISTS blog (\n" +
// " id int PRIMARY KEY AUTO_INCREMENT NOT NULL,\n" +
// " author VARCHAR(60) NOT NULL,\n" +
// " content TEXT NOT NULL,\n" +
// " access_date TIMESTAMP\n" +
// ")")
// int createTable();
// }
| import com.github.mybatis.entity.Blog;
import com.github.mybatis.mapper.BlogMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.PostConstruct;
import java.util.Date;
import static org.junit.Assert.assertTrue; | package com.github.mybatis.spring;
/**
* 测试autowire
* Created by lirui on 15/1/7.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class AutowireTest {
@Autowired
private BlogMapper mapper;
@PostConstruct
void init() {
mapper.createTable();
mapper.truncate();
}
@Test
public void testAutowire() throws Exception { | // Path: src/test/java/com/github/mybatis/entity/Blog.java
// @Table(name = "blog")
// public class Blog extends IdEntity {
// @Column
// private String author;
//
// @Column
// private String content;
//
// @Column
// private Date accessDate;
//
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
// public String getContent() {
// return content;
// }
//
// public void setContent(String content) {
// this.content = content;
// }
//
// public Date getAccessDate() {
// return accessDate;
// }
//
// public void setAccessDate(Date accessDate) {
// this.accessDate = accessDate;
// }
// }
//
// Path: src/test/java/com/github/mybatis/mapper/BlogMapper.java
// public interface BlogMapper extends ICrudPaginationMapper<Blog> {
// @Delete("delete from blog")
// int myDelete();
//
// @Select("select count(0) from blog")
// int myCount();
//
// @Update("create table IF NOT EXISTS blog (\n" +
// " id int PRIMARY KEY AUTO_INCREMENT NOT NULL,\n" +
// " author VARCHAR(60) NOT NULL,\n" +
// " content TEXT NOT NULL,\n" +
// " access_date TIMESTAMP\n" +
// ")")
// int createTable();
// }
// Path: src/test/java/com/github/mybatis/spring/AutowireTest.java
import com.github.mybatis.entity.Blog;
import com.github.mybatis.mapper.BlogMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.PostConstruct;
import java.util.Date;
import static org.junit.Assert.assertTrue;
package com.github.mybatis.spring;
/**
* 测试autowire
* Created by lirui on 15/1/7.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class AutowireTest {
@Autowired
private BlogMapper mapper;
@PostConstruct
void init() {
mapper.createTable();
mapper.truncate();
}
@Test
public void testAutowire() throws Exception { | Blog b = new Blog(); |
colin-lee/mybatis-spring-support | src/main/java/com/github/mybatis/spring/MapperFactoryBean.java | // Path: src/main/java/com/github/mybatis/entity/IdEntity.java
// @MappedSuperclass
// public abstract class IdEntity implements Serializable {
// @Id
// protected Long id;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// @JsonIgnore
// public boolean isNew() {
// return id == null;
// }
//
// @JsonIgnore
// public boolean isExist() {
// return id != null;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (null == obj) {
// return false;
// }
//
// if (this == obj) {
// return true;
// }
//
// if (!getClass().equals(obj.getClass())) {
// return false;
// }
//
// IdEntity that = (IdEntity) obj;
// return 0 != this.getId() && this.getId().equals(that.getId());
// }
//
// @Override
// public int hashCode() {
// int hashCode = 17;
// hashCode += id == null ? 0 : getId() * 31;
// return hashCode;
// }
//
// @Override
// public String toString() {
// return String.format("%s(id=%s)", this.getClass().getSimpleName(), getId());
// }
// }
| import java.lang.reflect.Array;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.*;
import static org.springframework.util.Assert.notNull;
import com.github.mybatis.entity.IdEntity;
import com.github.trace.TraceContext;
import com.github.trace.TraceRecorder;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.reflect.Reflection;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean; | */
public boolean isSingleton() {
return false;
}
/**
* 函数参数信息
*
* @param args 参数列表
* @return 格式化输出
*/
protected String getParameters(Object[] args) {
if (args == null)
return "";
StringBuilder sbd = new StringBuilder();
if (args.length > 0) {
for (Object i : args) {
if (i == null) {
sbd.append("null");
} else {
Class clz = i.getClass();
if (isPrimitive(clz)) {
sbd.append(evalPrimitive(i));
} else if (clz.isArray()) {
evalArray(i, sbd);
} else if (Collection.class.isAssignableFrom(clz)) {
Object[] arr = ((Collection<?>) i).toArray();
evalArray(arr, sbd);
} else if (i instanceof Date) {
sbd.append('"').append(formatYmdHis(((Date) i))).append('"'); | // Path: src/main/java/com/github/mybatis/entity/IdEntity.java
// @MappedSuperclass
// public abstract class IdEntity implements Serializable {
// @Id
// protected Long id;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// @JsonIgnore
// public boolean isNew() {
// return id == null;
// }
//
// @JsonIgnore
// public boolean isExist() {
// return id != null;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (null == obj) {
// return false;
// }
//
// if (this == obj) {
// return true;
// }
//
// if (!getClass().equals(obj.getClass())) {
// return false;
// }
//
// IdEntity that = (IdEntity) obj;
// return 0 != this.getId() && this.getId().equals(that.getId());
// }
//
// @Override
// public int hashCode() {
// int hashCode = 17;
// hashCode += id == null ? 0 : getId() * 31;
// return hashCode;
// }
//
// @Override
// public String toString() {
// return String.format("%s(id=%s)", this.getClass().getSimpleName(), getId());
// }
// }
// Path: src/main/java/com/github/mybatis/spring/MapperFactoryBean.java
import java.lang.reflect.Array;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.*;
import static org.springframework.util.Assert.notNull;
import com.github.mybatis.entity.IdEntity;
import com.github.trace.TraceContext;
import com.github.trace.TraceRecorder;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.reflect.Reflection;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
*/
public boolean isSingleton() {
return false;
}
/**
* 函数参数信息
*
* @param args 参数列表
* @return 格式化输出
*/
protected String getParameters(Object[] args) {
if (args == null)
return "";
StringBuilder sbd = new StringBuilder();
if (args.length > 0) {
for (Object i : args) {
if (i == null) {
sbd.append("null");
} else {
Class clz = i.getClass();
if (isPrimitive(clz)) {
sbd.append(evalPrimitive(i));
} else if (clz.isArray()) {
evalArray(i, sbd);
} else if (Collection.class.isAssignableFrom(clz)) {
Object[] arr = ((Collection<?>) i).toArray();
evalArray(arr, sbd);
} else if (i instanceof Date) {
sbd.append('"').append(formatYmdHis(((Date) i))).append('"'); | } else if (i instanceof IdEntity) { |
colin-lee/mybatis-spring-support | src/main/java/com/github/mybatis/spring/DynamicDataSource.java | // Path: src/main/java/com/github/mybatis/util/CloseableUtil.java
// public class CloseableUtil {
// private CloseableUtil() {
// }
//
// public static void closeQuietly(AutoCloseable c) {
// if (c != null) {
// try {
// c.close();
// } catch (Exception ignored) {
// }
// }
// }
// }
| import com.alibaba.druid.pool.DruidDataSource;
import com.github.autoconf.ConfigFactory;
import com.github.autoconf.api.IChangeListener;
import com.github.autoconf.api.IConfig;
import com.github.autoconf.api.IConfigFactory;
import com.github.mybatis.util.CloseableUtil;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.reflect.Reflection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jdbc.datasource.AbstractDataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List; | configFactory = ConfigFactory.getInstance();
}
configFactory.getConfig(configName, new IChangeListener() {
@Override
public void changed(IConfig conf) {
String masterUrl = conf.get("masterUrl");
if (Strings.isNullOrEmpty(masterUrl)) {
LOG.error("cannot init {}", conf.getName());
return;
}
String username = conf.get("username");
String password = conf.get("password");
// 分开读和写的接口,这样互不影响,必要时可以停止读或者写
DruidDataSource writer = buildDruidDataSource("master", masterUrl, username, password);
String slaveUrl = conf.get("slaveUrl");
if (Strings.isNullOrEmpty(slaveUrl)) {
slaveUrl = masterUrl;
}
DruidDataSource reader = buildDruidDataSource("slave", slaveUrl, username, password);
List<DruidDataSource> ds = Lists.newArrayList();
if (DynamicDataSource.this.writer != null) {
ds.add(DynamicDataSource.this.writer);
}
if (DynamicDataSource.this.reader != null) {
ds.add(DynamicDataSource.this.reader);
}
DynamicDataSource.this.writer = writer;
DynamicDataSource.this.reader = reader;
for (DruidDataSource i : ds) { | // Path: src/main/java/com/github/mybatis/util/CloseableUtil.java
// public class CloseableUtil {
// private CloseableUtil() {
// }
//
// public static void closeQuietly(AutoCloseable c) {
// if (c != null) {
// try {
// c.close();
// } catch (Exception ignored) {
// }
// }
// }
// }
// Path: src/main/java/com/github/mybatis/spring/DynamicDataSource.java
import com.alibaba.druid.pool.DruidDataSource;
import com.github.autoconf.ConfigFactory;
import com.github.autoconf.api.IChangeListener;
import com.github.autoconf.api.IConfig;
import com.github.autoconf.api.IConfigFactory;
import com.github.mybatis.util.CloseableUtil;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.reflect.Reflection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jdbc.datasource.AbstractDataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
configFactory = ConfigFactory.getInstance();
}
configFactory.getConfig(configName, new IChangeListener() {
@Override
public void changed(IConfig conf) {
String masterUrl = conf.get("masterUrl");
if (Strings.isNullOrEmpty(masterUrl)) {
LOG.error("cannot init {}", conf.getName());
return;
}
String username = conf.get("username");
String password = conf.get("password");
// 分开读和写的接口,这样互不影响,必要时可以停止读或者写
DruidDataSource writer = buildDruidDataSource("master", masterUrl, username, password);
String slaveUrl = conf.get("slaveUrl");
if (Strings.isNullOrEmpty(slaveUrl)) {
slaveUrl = masterUrl;
}
DruidDataSource reader = buildDruidDataSource("slave", slaveUrl, username, password);
List<DruidDataSource> ds = Lists.newArrayList();
if (DynamicDataSource.this.writer != null) {
ds.add(DynamicDataSource.this.writer);
}
if (DynamicDataSource.this.reader != null) {
ds.add(DynamicDataSource.this.reader);
}
DynamicDataSource.this.writer = writer;
DynamicDataSource.this.reader = reader;
for (DruidDataSource i : ds) { | CloseableUtil.closeQuietly(i); |
colin-lee/mybatis-spring-support | src/test/java/com/github/mybatis/service/BlogService.java | // Path: src/test/java/com/github/mybatis/mapper/BlogMapper.java
// public interface BlogMapper extends ICrudPaginationMapper<Blog> {
// @Delete("delete from blog")
// int myDelete();
//
// @Select("select count(0) from blog")
// int myCount();
//
// @Update("create table IF NOT EXISTS blog (\n" +
// " id int PRIMARY KEY AUTO_INCREMENT NOT NULL,\n" +
// " author VARCHAR(60) NOT NULL,\n" +
// " content TEXT NOT NULL,\n" +
// " access_date TIMESTAMP\n" +
// ")")
// int createTable();
// }
| import com.github.mybatis.mapper.BlogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; | package com.github.mybatis.service;
/**
* 测试autowire
* Created by lirui on 15/1/11.
*/
@Service
public class BlogService {
@Autowired | // Path: src/test/java/com/github/mybatis/mapper/BlogMapper.java
// public interface BlogMapper extends ICrudPaginationMapper<Blog> {
// @Delete("delete from blog")
// int myDelete();
//
// @Select("select count(0) from blog")
// int myCount();
//
// @Update("create table IF NOT EXISTS blog (\n" +
// " id int PRIMARY KEY AUTO_INCREMENT NOT NULL,\n" +
// " author VARCHAR(60) NOT NULL,\n" +
// " content TEXT NOT NULL,\n" +
// " access_date TIMESTAMP\n" +
// ")")
// int createTable();
// }
// Path: src/test/java/com/github/mybatis/service/BlogService.java
import com.github.mybatis.mapper.BlogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
package com.github.mybatis.service;
/**
* 测试autowire
* Created by lirui on 15/1/11.
*/
@Service
public class BlogService {
@Autowired | private BlogMapper mapper; |
TranquilMarmot/spaceout | src/com/bitwaffle/spaceguts/graphics/gui/button/RectangleButton.java | // Path: src/com/bitwaffle/spaceguts/input/MouseManager.java
// public class MouseManager {
// /** whether or not button a is being pressed */
// public static boolean button0, button1, button2;
//
// /** how much the mouse has moved on the X axis */
// public static float dx;
// /** how much the mouse has move on the Y axis */
// public static float dy;
// /** how much the mouse wheel has moved */
// public static float wheel;
// /** the mouse's current location */
// public static int x, y;
//
// public static boolean inverted = false;
//
// /**
// * sensitivity values for mouse movement
// * NOTE:The mouse movement is divided by these
// * So setting them to 10 would result in 1/10th of the mouse movement
// * (higher numbers == less sensitivity)
// */
// public static float verticalSensitivity = 10.0f;
// public static float horizontalSensitivity = 10.0f;
//
// public void update() {
// while (Mouse.next()) {
// String eventButton = Mouse.getButtonName(Mouse.getEventButton());
// if (eventButton != null) {
// if (Mouse.getEventButtonState()) {
// if (eventButton.equals("BUTTON0")) {
// button0 = true;
// }
// if (eventButton.equals("BUTTON1")) {
// button1 = true;
// }
// if (eventButton.equals("BUTTON2")) {
// button2 = true;
// }
// } else {
// if (eventButton.equals("BUTTON0")) {
// button0 = false;
// }
// if (eventButton.equals("BUTTON1")) {
// button1 = false;
// }
// if (eventButton.equals("BUTTON2")) {
// button2 = false;
// }
// }
// }
// }
//
// // Only update dx and dy if the mouse is grabbed
// if (Mouse.isGrabbed()) {
// dx = (-(float) Mouse.getDX()) / verticalSensitivity;
// if(!inverted)
// dy = ((float) Mouse.getDY()) / horizontalSensitivity;
// else
// dy = -((float) Mouse.getDY()) / horizontalSensitivity;
// } else {
// dx = 0.0f;
// dy = 0.0f;
// }
//
// // grab wheel change amount
// wheel = (float) Mouse.getDWheel();
//
// x = Mouse.getX();
// // we want the top-left corner to be 0,0
// y = DisplayHelper.windowHeight - Mouse.getY();
// }
//
// }
| import org.lwjgl.util.Rectangle;
import com.bitwaffle.spaceguts.input.MouseManager; | package com.bitwaffle.spaceguts.graphics.gui.button;
/**
* A rectangular button! To use this class, create a class and have it extend
* this. Implement the <code>releasedEvent</code>,<code>mouseOverEvent</code>,
* <code>pressedEvent</code>
*
* @author TranquilMarmot
*
*/
public abstract class RectangleButton extends Button {
/** rectangle representing this button */
protected Rectangle rectangle;
/** the button's size */
public int height, width;
/**
* RectangleButton constructor
*
* @param x
* Initial X Position
* @param y
* Initial Y Position
* @param height
* Height of button
* @param width
* Width of button
*/
public RectangleButton(int x, int y, int height, int width) {
super(x, y);
this.height = height;
this.width = width;
rectangle = new Rectangle();
rectangle.setX(x);
rectangle.setY(y);
rectangle.setWidth(width);
rectangle.setHeight(height);
}
@Override
/**
* This just changes all the state booleans (<code>mouseOver</code>, <code>pressed</code>, <code>released</code>)) according to the mouse's actions during the current frame.
* It then calls the appropriate methods (<code>mouseOverEvent</code>, <code>pressedEvent</code>, <code>releasedEvent</code>) based on the state of the button.
*/
public void update() {
if (active && isVisible) {
// check to see if the mouse is in the rectangle | // Path: src/com/bitwaffle/spaceguts/input/MouseManager.java
// public class MouseManager {
// /** whether or not button a is being pressed */
// public static boolean button0, button1, button2;
//
// /** how much the mouse has moved on the X axis */
// public static float dx;
// /** how much the mouse has move on the Y axis */
// public static float dy;
// /** how much the mouse wheel has moved */
// public static float wheel;
// /** the mouse's current location */
// public static int x, y;
//
// public static boolean inverted = false;
//
// /**
// * sensitivity values for mouse movement
// * NOTE:The mouse movement is divided by these
// * So setting them to 10 would result in 1/10th of the mouse movement
// * (higher numbers == less sensitivity)
// */
// public static float verticalSensitivity = 10.0f;
// public static float horizontalSensitivity = 10.0f;
//
// public void update() {
// while (Mouse.next()) {
// String eventButton = Mouse.getButtonName(Mouse.getEventButton());
// if (eventButton != null) {
// if (Mouse.getEventButtonState()) {
// if (eventButton.equals("BUTTON0")) {
// button0 = true;
// }
// if (eventButton.equals("BUTTON1")) {
// button1 = true;
// }
// if (eventButton.equals("BUTTON2")) {
// button2 = true;
// }
// } else {
// if (eventButton.equals("BUTTON0")) {
// button0 = false;
// }
// if (eventButton.equals("BUTTON1")) {
// button1 = false;
// }
// if (eventButton.equals("BUTTON2")) {
// button2 = false;
// }
// }
// }
// }
//
// // Only update dx and dy if the mouse is grabbed
// if (Mouse.isGrabbed()) {
// dx = (-(float) Mouse.getDX()) / verticalSensitivity;
// if(!inverted)
// dy = ((float) Mouse.getDY()) / horizontalSensitivity;
// else
// dy = -((float) Mouse.getDY()) / horizontalSensitivity;
// } else {
// dx = 0.0f;
// dy = 0.0f;
// }
//
// // grab wheel change amount
// wheel = (float) Mouse.getDWheel();
//
// x = Mouse.getX();
// // we want the top-left corner to be 0,0
// y = DisplayHelper.windowHeight - Mouse.getY();
// }
//
// }
// Path: src/com/bitwaffle/spaceguts/graphics/gui/button/RectangleButton.java
import org.lwjgl.util.Rectangle;
import com.bitwaffle.spaceguts.input.MouseManager;
package com.bitwaffle.spaceguts.graphics.gui.button;
/**
* A rectangular button! To use this class, create a class and have it extend
* this. Implement the <code>releasedEvent</code>,<code>mouseOverEvent</code>,
* <code>pressedEvent</code>
*
* @author TranquilMarmot
*
*/
public abstract class RectangleButton extends Button {
/** rectangle representing this button */
protected Rectangle rectangle;
/** the button's size */
public int height, width;
/**
* RectangleButton constructor
*
* @param x
* Initial X Position
* @param y
* Initial Y Position
* @param height
* Height of button
* @param width
* Width of button
*/
public RectangleButton(int x, int y, int height, int width) {
super(x, y);
this.height = height;
this.width = width;
rectangle = new Rectangle();
rectangle.setX(x);
rectangle.setY(y);
rectangle.setWidth(width);
rectangle.setHeight(height);
}
@Override
/**
* This just changes all the state booleans (<code>mouseOver</code>, <code>pressed</code>, <code>released</code>)) according to the mouse's actions during the current frame.
* It then calls the appropriate methods (<code>mouseOverEvent</code>, <code>pressedEvent</code>, <code>releasedEvent</code>) based on the state of the button.
*/
public void update() {
if (active && isVisible) {
// check to see if the mouse is in the rectangle | if (rectangle.contains(MouseManager.x, MouseManager.y)) { |
TranquilMarmot/spaceout | src/com/bitwaffle/spaceguts/graphics/render/Graphics.java | // Path: src/com/bitwaffle/spaceguts/entities/Entities.java
// public class Entities {
// /** player instance */
// public static Player player;
// /** camera instance */
// public static Camera camera;
// /** the skybox */
// public static Skybox skybox;
//
// /** all the current passive entities */
// public static ArrayList<Entity> passiveEntities = new ArrayList<Entity>(10), passiveEntitiesToAdd = new ArrayList<Entity>(10), passiveEntitiesToRemove = new ArrayList<Entity>(10);
// /** all the dynamic entities */
// public static ArrayList<DynamicEntity> dynamicEntities = new ArrayList<DynamicEntity>(100);
// /** all the current lights */
// public static ArrayList<Light> lights = new ArrayList<Light>(8), lightsToAdd = new ArrayList<Light>(8), lightsToRemove = new ArrayList<Light>(8);
//
// /**
// * Updates everything that doesn't get updated by the {@link DynamicEntityCallback}
// * @param timeStep How much time has passed since the last tick (passed in from DynamicEntityCallback)
// */
// public static void updateAll(float timeStep){
// /*
// * Since passiveEntities and lights all get updated by iterating through their lists,
// * directly adding and removing from the list can cause a ConcurrentModificationException.
// * Everything in DynamicEntities is updated in the DynamicEntityCallback, and as such the list
// * in here is used solely for rendering. So adds and removes can be done directly on the
// * list.
// */
// if(!passiveEntitiesToRemove.isEmpty()){
// for(Entity ent : passiveEntitiesToRemove)
// passiveEntities.remove(ent);
// passiveEntitiesToRemove.clear();
// }
//
// if(!passiveEntitiesToAdd.isEmpty()){
// for(Entity ent : passiveEntitiesToAdd)
// passiveEntities.add(ent);
// passiveEntitiesToAdd.clear();
// }
//
// if(!lightsToRemove.isEmpty()){
// for(Light l : lightsToRemove)
// lights.remove(l);
// lightsToRemove.clear();
// }
//
// if(!lightsToAdd.isEmpty()){
// for(Light l : lightsToAdd)
// lights.add(l);
// lightsToAdd.clear();
// }
//
// camera.update(timeStep);
// skybox.update(timeStep);
//
// for(Entity ent : passiveEntities)
// ent.update(timeStep);
//
// for(Light l : lights)
// l.update(timeStep);
// }
//
// /**
// * Adds the given DynamicEntity to the rendering world
// * @param ent Entity to add
// */
// public static void addDynamicEntity(DynamicEntity ent){
// dynamicEntities.add(ent);
// }
//
// /**
// * Adds the given Entity to the rendering world
// * @param ent Entity to add
// */
// public static void addPassiveEntity(Entity ent){
// passiveEntitiesToAdd.add(ent);
// }
//
// /**
// * Adds the given Light to the rendering world
// * @param light Light to add
// */
// public static void addLight(Light light){
// lightsToAdd.add(light);
// }
//
// /**
// * Removes the given DynamicEntity from the rendering world
// * @param ent Entity to remove
// */
// public static void removeDynamicEntity(DynamicEntity ent){
// dynamicEntities.remove(ent);
// }
//
// /**
// * Removes the given Entity from the rendering world
// * @param ent Entity to remove
// */
// public static void removePassiveEntity(Entity ent){
// passiveEntitiesToRemove.add(ent);
// }
//
// /**
// * Removes the given Light from the rendering world
// * @param light Light to remove
// */
// public static void removeLight(Light l){
// lightsToRemove.add(l);
// }
//
// /**
// * @return Whether or not there are any entities at the moment
// */
// public static boolean entitiesExist() {
// return !passiveEntities.isEmpty() || !dynamicEntities.isEmpty() || player != null;
// }
//
// /**
// * Gets the distance between two vectors
// *
// * @param first
// * The first vector
// * @param second
// * The second vector
// * @return The distance between the two vectors
// */
// public static float distance(Vector3f first, Vector3f second) {
// float xDist = first.x - second.x;
// float yDist = first.y - second.y;
// float zDist = first.z - second.z;
//
// float xSqr = xDist * xDist;
// float ySqr = yDist * yDist;
// float zSqr = zDist * zDist;
//
// double total = (double) (xSqr + ySqr + zSqr);
//
// return (float) Math.sqrt(total);
// }
//
// /**
// * Delete all of the entities
// */
// public static void cleanup() {
// for(Entity ent : passiveEntities){
// ent.cleanup();
// }
//
// for(DynamicEntity ent : dynamicEntities){
// ent.cleanup();
// }
// player = null;
// camera = null;
// passiveEntities.clear();
// dynamicEntities.clear();
// lights.clear();
// }
// }
| import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.util.glu.GLU;
import com.bitwaffle.spaceguts.entities.Entities; | package com.bitwaffle.spaceguts.graphics.render;
/**
* This class contains methods for rendering the whole scene
* and for initializing OpenGL
*
* @author TranquilMarmot
*/
public class Graphics {
/**
* Renders the entire scene
*/
public static void render(){
// clear the color and depth buffers
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
// only render 3D stuff if 3D stuff exists | // Path: src/com/bitwaffle/spaceguts/entities/Entities.java
// public class Entities {
// /** player instance */
// public static Player player;
// /** camera instance */
// public static Camera camera;
// /** the skybox */
// public static Skybox skybox;
//
// /** all the current passive entities */
// public static ArrayList<Entity> passiveEntities = new ArrayList<Entity>(10), passiveEntitiesToAdd = new ArrayList<Entity>(10), passiveEntitiesToRemove = new ArrayList<Entity>(10);
// /** all the dynamic entities */
// public static ArrayList<DynamicEntity> dynamicEntities = new ArrayList<DynamicEntity>(100);
// /** all the current lights */
// public static ArrayList<Light> lights = new ArrayList<Light>(8), lightsToAdd = new ArrayList<Light>(8), lightsToRemove = new ArrayList<Light>(8);
//
// /**
// * Updates everything that doesn't get updated by the {@link DynamicEntityCallback}
// * @param timeStep How much time has passed since the last tick (passed in from DynamicEntityCallback)
// */
// public static void updateAll(float timeStep){
// /*
// * Since passiveEntities and lights all get updated by iterating through their lists,
// * directly adding and removing from the list can cause a ConcurrentModificationException.
// * Everything in DynamicEntities is updated in the DynamicEntityCallback, and as such the list
// * in here is used solely for rendering. So adds and removes can be done directly on the
// * list.
// */
// if(!passiveEntitiesToRemove.isEmpty()){
// for(Entity ent : passiveEntitiesToRemove)
// passiveEntities.remove(ent);
// passiveEntitiesToRemove.clear();
// }
//
// if(!passiveEntitiesToAdd.isEmpty()){
// for(Entity ent : passiveEntitiesToAdd)
// passiveEntities.add(ent);
// passiveEntitiesToAdd.clear();
// }
//
// if(!lightsToRemove.isEmpty()){
// for(Light l : lightsToRemove)
// lights.remove(l);
// lightsToRemove.clear();
// }
//
// if(!lightsToAdd.isEmpty()){
// for(Light l : lightsToAdd)
// lights.add(l);
// lightsToAdd.clear();
// }
//
// camera.update(timeStep);
// skybox.update(timeStep);
//
// for(Entity ent : passiveEntities)
// ent.update(timeStep);
//
// for(Light l : lights)
// l.update(timeStep);
// }
//
// /**
// * Adds the given DynamicEntity to the rendering world
// * @param ent Entity to add
// */
// public static void addDynamicEntity(DynamicEntity ent){
// dynamicEntities.add(ent);
// }
//
// /**
// * Adds the given Entity to the rendering world
// * @param ent Entity to add
// */
// public static void addPassiveEntity(Entity ent){
// passiveEntitiesToAdd.add(ent);
// }
//
// /**
// * Adds the given Light to the rendering world
// * @param light Light to add
// */
// public static void addLight(Light light){
// lightsToAdd.add(light);
// }
//
// /**
// * Removes the given DynamicEntity from the rendering world
// * @param ent Entity to remove
// */
// public static void removeDynamicEntity(DynamicEntity ent){
// dynamicEntities.remove(ent);
// }
//
// /**
// * Removes the given Entity from the rendering world
// * @param ent Entity to remove
// */
// public static void removePassiveEntity(Entity ent){
// passiveEntitiesToRemove.add(ent);
// }
//
// /**
// * Removes the given Light from the rendering world
// * @param light Light to remove
// */
// public static void removeLight(Light l){
// lightsToRemove.add(l);
// }
//
// /**
// * @return Whether or not there are any entities at the moment
// */
// public static boolean entitiesExist() {
// return !passiveEntities.isEmpty() || !dynamicEntities.isEmpty() || player != null;
// }
//
// /**
// * Gets the distance between two vectors
// *
// * @param first
// * The first vector
// * @param second
// * The second vector
// * @return The distance between the two vectors
// */
// public static float distance(Vector3f first, Vector3f second) {
// float xDist = first.x - second.x;
// float yDist = first.y - second.y;
// float zDist = first.z - second.z;
//
// float xSqr = xDist * xDist;
// float ySqr = yDist * yDist;
// float zSqr = zDist * zDist;
//
// double total = (double) (xSqr + ySqr + zSqr);
//
// return (float) Math.sqrt(total);
// }
//
// /**
// * Delete all of the entities
// */
// public static void cleanup() {
// for(Entity ent : passiveEntities){
// ent.cleanup();
// }
//
// for(DynamicEntity ent : dynamicEntities){
// ent.cleanup();
// }
// player = null;
// camera = null;
// passiveEntities.clear();
// dynamicEntities.clear();
// lights.clear();
// }
// }
// Path: src/com/bitwaffle/spaceguts/graphics/render/Graphics.java
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.util.glu.GLU;
import com.bitwaffle.spaceguts.entities.Entities;
package com.bitwaffle.spaceguts.graphics.render;
/**
* This class contains methods for rendering the whole scene
* and for initializing OpenGL
*
* @author TranquilMarmot
*/
public class Graphics {
/**
* Renders the entire scene
*/
public static void render(){
// clear the color and depth buffers
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
// only render 3D stuff if 3D stuff exists | if (Entities.camera != null && Entities.entitiesExist()) |
TranquilMarmot/spaceout | src/com/bitwaffle/spaceout/interfaces/Projectile.java | // Path: src/com/bitwaffle/spaceguts/entities/Entity.java
// public abstract class Entity {
// /** the entity's current location */
// public Vector3f location;
//
// /** quaternion representing rotation */
// public Quaternion rotation;
//
// /** type, used for lots of things */
// public String type;
//
// /**
// * Entity constructor
// */
// public Entity() {
// location = new Vector3f(0.0f, 0.0f, 0.0f);
// rotation = new Quaternion(1.0f, 0.0f, 0.0f, 1.0f);
// type = "entity";
// }
//
// /**
// * Updates this entity
// */
// public abstract void update(float timeStep);
//
// /**
// * Draws this entity
// */
// public abstract void draw();
//
// /**
// * Have the entity provide any necessary cleanup
// */
// public abstract void cleanup();
// }
| import com.bitwaffle.spaceguts.entities.Entity; | package com.bitwaffle.spaceout.interfaces;
/**
* Interface for a bullet (anything that does damage)
* @author TranquilMarmot
*/
public interface Projectile {
/**
* How much damage does this bullet do when it hits something?
* @return Amount of damage to do
*/
public int getDamage();
/**
* Who owns this bullet? (Who can't it hurt?)
* @return Whoever fired the bullet
*/ | // Path: src/com/bitwaffle/spaceguts/entities/Entity.java
// public abstract class Entity {
// /** the entity's current location */
// public Vector3f location;
//
// /** quaternion representing rotation */
// public Quaternion rotation;
//
// /** type, used for lots of things */
// public String type;
//
// /**
// * Entity constructor
// */
// public Entity() {
// location = new Vector3f(0.0f, 0.0f, 0.0f);
// rotation = new Quaternion(1.0f, 0.0f, 0.0f, 1.0f);
// type = "entity";
// }
//
// /**
// * Updates this entity
// */
// public abstract void update(float timeStep);
//
// /**
// * Draws this entity
// */
// public abstract void draw();
//
// /**
// * Have the entity provide any necessary cleanup
// */
// public abstract void cleanup();
// }
// Path: src/com/bitwaffle/spaceout/interfaces/Projectile.java
import com.bitwaffle.spaceguts.entities.Entity;
package com.bitwaffle.spaceout.interfaces;
/**
* Interface for a bullet (anything that does damage)
* @author TranquilMarmot
*/
public interface Projectile {
/**
* How much damage does this bullet do when it hits something?
* @return Amount of damage to do
*/
public int getDamage();
/**
* Who owns this bullet? (Who can't it hurt?)
* @return Whoever fired the bullet
*/ | public Entity getOwner(); |
thinktube-kobe/airtube | AndroidAudioVideoApp/src/com/thinktube/airtube/android/app/AudioDuplexActivity.java | // Path: AndroidLibrary/src/com/thinktube/android/audio/AudioSetup.java
// public class AudioSetup implements OnAudioFocusChangeListener {
//
// private final static String TAG = "AudioSetup";
// private Activity activity;
// private AudioManager am;
// public AudioSetup(Activity activity) {
// this.activity = activity;
//
// }
//
// static private int audioSessionId = -1;
//
// @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
// public void setup() {
//
// activity.setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
// am = (AudioManager) activity.getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
// int result = am.requestAudioFocus(this,
// AudioManager.STREAM_VOICE_CALL, // for VoIP like
// AudioManager.AUDIOFOCUS_GAIN); // Permanent focus.
//
// if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// Log.d(TAG, "AUDIOFOCUS_REQUEST_GRANTED");
//
// } else {
// Log.d(TAG, "AUDIOFOCUS_REQUEST_GRANTED NOT!!!!");
// }
//
// // setMode to MODE_IN_COMMUNICATION or don't, but never to MODE_IN_CALL
// am.setMode(AudioManager.MODE_IN_COMMUNICATION);
//
// // default app volumen to half to avoid initial audio feedback
// final int midVol= am.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL)/2;
// am.setStreamVolume(AudioManager.STREAM_VOICE_CALL, midVol, AudioManager.FLAG_SHOW_UI + AudioManager.FLAG_ALLOW_RINGER_MODES);
//
// if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) { // API level 17
// Log.d(TAG, "PROPERTY_OUTPUT_FRAMES_PER_BUFFER: " + am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER));
// Log.d(TAG, "PROPERTY_OUTPUT_SAMPLE_RATE: " + am.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE));
// }
// }
//
// public void teardown() {
// am.setMode(AudioManager.MODE_NORMAL);
// activity.setVolumeControlStream(AudioManager.USE_DEFAULT_STREAM_TYPE);
// am.abandonAudioFocus(this);
// }
//
// public void useSpeaker(boolean speaker) {
// Log.d(TAG, "Before: isSpeakerphoneOn = "+ am.isSpeakerphoneOn());
// am.setSpeakerphoneOn(speaker);
// Log.d(TAG, "After: isSpeakerphoneOn = "+ am.isSpeakerphoneOn());
//
// }
//
// public void setMicrophoneMute(boolean on) {
// am.setMicrophoneMute(on);
// }
//
// int curVolLevel;
// public void setSpeakerMute(boolean on) {
// if (on) {
// curVolLevel = am.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
// am.setStreamVolume(AudioManager.STREAM_VOICE_CALL, 0, 0);
// } else {
// am.setStreamVolume(AudioManager.STREAM_VOICE_CALL, curVolLevel, 0);
// }
// Log.d(TAG, "setSpeakerMute() = " + on);
// }
//
// @Override
// public void onAudioFocusChange(int focusChange) {
// if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
// Log.d(TAG, "onAudioFocusChange(): AUDIOFOCUS_LOSS");
// }
//
// }
//
// public static void setAudioSessionId(int id) {
// audioSessionId = id;
// Log.d(TAG, "Audio session ID: " + audioSessionId);
// }
// public static int getAudioSessionId() {
// return audioSessionId;
// }
// }
| import com.thinktube.airtube.android.AirTubeBaseActivity;
import com.thinktube.airtube.android.AirTubeServiceConnection;
import com.thinktube.airtube.android.AudioDuplex;
import com.thinktube.android.audio.AudioSetup;
import com.thinktube.audio.JitterBuffer.Statistics;
import com.thinktube.service.R;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.ToggleButton; | package com.thinktube.airtube.android.app;
public class AudioDuplexActivity extends AirTubeBaseActivity {
TextView stats;
AudioDuplex ad;
private AirTubeServiceConnection conn;
| // Path: AndroidLibrary/src/com/thinktube/android/audio/AudioSetup.java
// public class AudioSetup implements OnAudioFocusChangeListener {
//
// private final static String TAG = "AudioSetup";
// private Activity activity;
// private AudioManager am;
// public AudioSetup(Activity activity) {
// this.activity = activity;
//
// }
//
// static private int audioSessionId = -1;
//
// @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
// public void setup() {
//
// activity.setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
// am = (AudioManager) activity.getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
// int result = am.requestAudioFocus(this,
// AudioManager.STREAM_VOICE_CALL, // for VoIP like
// AudioManager.AUDIOFOCUS_GAIN); // Permanent focus.
//
// if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// Log.d(TAG, "AUDIOFOCUS_REQUEST_GRANTED");
//
// } else {
// Log.d(TAG, "AUDIOFOCUS_REQUEST_GRANTED NOT!!!!");
// }
//
// // setMode to MODE_IN_COMMUNICATION or don't, but never to MODE_IN_CALL
// am.setMode(AudioManager.MODE_IN_COMMUNICATION);
//
// // default app volumen to half to avoid initial audio feedback
// final int midVol= am.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL)/2;
// am.setStreamVolume(AudioManager.STREAM_VOICE_CALL, midVol, AudioManager.FLAG_SHOW_UI + AudioManager.FLAG_ALLOW_RINGER_MODES);
//
// if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) { // API level 17
// Log.d(TAG, "PROPERTY_OUTPUT_FRAMES_PER_BUFFER: " + am.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER));
// Log.d(TAG, "PROPERTY_OUTPUT_SAMPLE_RATE: " + am.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE));
// }
// }
//
// public void teardown() {
// am.setMode(AudioManager.MODE_NORMAL);
// activity.setVolumeControlStream(AudioManager.USE_DEFAULT_STREAM_TYPE);
// am.abandonAudioFocus(this);
// }
//
// public void useSpeaker(boolean speaker) {
// Log.d(TAG, "Before: isSpeakerphoneOn = "+ am.isSpeakerphoneOn());
// am.setSpeakerphoneOn(speaker);
// Log.d(TAG, "After: isSpeakerphoneOn = "+ am.isSpeakerphoneOn());
//
// }
//
// public void setMicrophoneMute(boolean on) {
// am.setMicrophoneMute(on);
// }
//
// int curVolLevel;
// public void setSpeakerMute(boolean on) {
// if (on) {
// curVolLevel = am.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
// am.setStreamVolume(AudioManager.STREAM_VOICE_CALL, 0, 0);
// } else {
// am.setStreamVolume(AudioManager.STREAM_VOICE_CALL, curVolLevel, 0);
// }
// Log.d(TAG, "setSpeakerMute() = " + on);
// }
//
// @Override
// public void onAudioFocusChange(int focusChange) {
// if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
// Log.d(TAG, "onAudioFocusChange(): AUDIOFOCUS_LOSS");
// }
//
// }
//
// public static void setAudioSessionId(int id) {
// audioSessionId = id;
// Log.d(TAG, "Audio session ID: " + audioSessionId);
// }
// public static int getAudioSessionId() {
// return audioSessionId;
// }
// }
// Path: AndroidAudioVideoApp/src/com/thinktube/airtube/android/app/AudioDuplexActivity.java
import com.thinktube.airtube.android.AirTubeBaseActivity;
import com.thinktube.airtube.android.AirTubeServiceConnection;
import com.thinktube.airtube.android.AudioDuplex;
import com.thinktube.android.audio.AudioSetup;
import com.thinktube.audio.JitterBuffer.Statistics;
import com.thinktube.service.R;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.ToggleButton;
package com.thinktube.airtube.android.app;
public class AudioDuplexActivity extends AirTubeBaseActivity {
TextView stats;
AudioDuplex ad;
private AirTubeServiceConnection conn;
| private AudioSetup as; |
TalkingData/Myna | Android/lib-Myna/src/main/java/biz/k11i/xgboost/gbm/GradBooster.java | // Path: Android/lib-Myna/src/main/java/biz/k11i/xgboost/util/FVec.java
// public interface FVec extends Serializable {
// /**
// * Gets index-th value.
// *
// * @param index index
// * @return value
// */
// double fvalue(int index);
//
// class Transformer {
// private Transformer() {
// // do nothing
// }
//
// /**
// * Builds FVec from dense vector.
// *
// * @param values float values
// * @param treatsZeroAsNA treat zero as N/A if true
// * @return FVec
// */
// public static FVec fromArray(float[] values, boolean treatsZeroAsNA) {
// return new FVecArrayImpl.FVecFloatArrayImpl(values, treatsZeroAsNA);
// }
//
// /**
// * Builds FVec from dense vector.
// *
// * @param values double values
// * @param treatsZeroAsNA treat zero as N/A if true
// * @return FVec
// */
// public static FVec fromArray(double[] values, boolean treatsZeroAsNA) {
// return new FVecArrayImpl.FVecDoubleArrayImpl(values, treatsZeroAsNA);
// }
//
// /**
// * Builds FVec from map.
// *
// * @param map map containing non-zero values
// * @return FVec
// */
// public static FVec fromMap(Map<Integer, ? extends Number> map) {
// return new FVecMapImpl(map);
// }
// }
// }
| import biz.k11i.xgboost.util.FVec;
import biz.k11i.xgboost.util.ModelReader;
import java.io.IOException;
import java.io.Serializable; | package biz.k11i.xgboost.gbm;
/**
* Interface of gradient boosting model.
*/
public interface GradBooster extends Serializable {
class Factory {
/**
* Creates a gradient booster from given name.
*
* @param name name of gradient booster
* @return created gradient booster
*/
public static GradBooster createGradBooster(String name) {
if ("gbtree".equals(name)) {
return new GBTree();
} else if ("gblinear".equals(name)) {
return new GBLinear();
}
throw new IllegalArgumentException(name + " is not supported model.");
}
}
void setNumClass(int num_class);
/**
* Loads model from stream.
*
* @param reader input stream
* @param with_pbuffer whether the incoming data contains pbuffer
* @throws IOException If an I/O error occurs
*/
void loadModel(ModelReader reader, boolean with_pbuffer) throws IOException;
/**
* Generates predictions for given feature vector.
*
* @param feat feature vector
* @param ntree_limit limit the number of trees used in prediction
* @return prediction result
*/ | // Path: Android/lib-Myna/src/main/java/biz/k11i/xgboost/util/FVec.java
// public interface FVec extends Serializable {
// /**
// * Gets index-th value.
// *
// * @param index index
// * @return value
// */
// double fvalue(int index);
//
// class Transformer {
// private Transformer() {
// // do nothing
// }
//
// /**
// * Builds FVec from dense vector.
// *
// * @param values float values
// * @param treatsZeroAsNA treat zero as N/A if true
// * @return FVec
// */
// public static FVec fromArray(float[] values, boolean treatsZeroAsNA) {
// return new FVecArrayImpl.FVecFloatArrayImpl(values, treatsZeroAsNA);
// }
//
// /**
// * Builds FVec from dense vector.
// *
// * @param values double values
// * @param treatsZeroAsNA treat zero as N/A if true
// * @return FVec
// */
// public static FVec fromArray(double[] values, boolean treatsZeroAsNA) {
// return new FVecArrayImpl.FVecDoubleArrayImpl(values, treatsZeroAsNA);
// }
//
// /**
// * Builds FVec from map.
// *
// * @param map map containing non-zero values
// * @return FVec
// */
// public static FVec fromMap(Map<Integer, ? extends Number> map) {
// return new FVecMapImpl(map);
// }
// }
// }
// Path: Android/lib-Myna/src/main/java/biz/k11i/xgboost/gbm/GradBooster.java
import biz.k11i.xgboost.util.FVec;
import biz.k11i.xgboost.util.ModelReader;
import java.io.IOException;
import java.io.Serializable;
package biz.k11i.xgboost.gbm;
/**
* Interface of gradient boosting model.
*/
public interface GradBooster extends Serializable {
class Factory {
/**
* Creates a gradient booster from given name.
*
* @param name name of gradient booster
* @return created gradient booster
*/
public static GradBooster createGradBooster(String name) {
if ("gbtree".equals(name)) {
return new GBTree();
} else if ("gblinear".equals(name)) {
return new GBLinear();
}
throw new IllegalArgumentException(name + " is not supported model.");
}
}
void setNumClass(int num_class);
/**
* Loads model from stream.
*
* @param reader input stream
* @param with_pbuffer whether the incoming data contains pbuffer
* @throws IOException If an I/O error occurs
*/
void loadModel(ModelReader reader, boolean with_pbuffer) throws IOException;
/**
* Generates predictions for given feature vector.
*
* @param feat feature vector
* @param ntree_limit limit the number of trees used in prediction
* @return prediction result
*/ | double[] predict(FVec feat, int ntree_limit); |
TalkingData/Myna | Android/lib-Myna/src/main/java/com/talkingdata/myna/LSTMClassifier.java | // Path: Android/lib-Myna/src/main/java/com/talkingdata/myna/sensor/SensorData.java
// public class SensorData {
// /**
// * Sensor data
// */
// public float[] accelerate, gyroscope, gravity, magnetic, game_rotation_vector, orientation;
//
//
// /**
// * Calculated accelerometer values in real world coordination system.
// */
// public float[] world_accelerometer;
//
// public float light, pressure, temperature;
//
// /**
// * Time when recording the data of these sensors
// */
// public long timestamp;
//
// public SensorData() {
// accelerate = new float[3];
// gyroscope = new float[3];
// gravity = new float[3];
// magnetic = new float[3];
// game_rotation_vector = new float[3];
// orientation = new float[3];
// world_accelerometer = new float[3];
// timestamp = System.currentTimeMillis();
// }
//
// /**
// * Reset the value of all fields with the given instance
// * @param sd Source instance with the sensor data waiting to be cloned.
// */
// public void clone(SensorData sd) {
// System.arraycopy(sd.accelerate, 0, this.accelerate, 0, 3);
// System.arraycopy(sd.gyroscope, 0, this.gyroscope, 0, 3);
// System.arraycopy(sd.gravity, 0, this.gravity, 0, 3);
// System.arraycopy(sd.magnetic, 0, this.magnetic, 0, 3);
// System.arraycopy(sd.game_rotation_vector, 0, this.game_rotation_vector, 0, 3);
// System.arraycopy(sd.orientation, 0, this.orientation, 0, 3);
// System.arraycopy(sd.world_accelerometer, 0, this.world_accelerometer, 0, 3);
//
// this.light = sd.light;
// this.temperature = sd.temperature;
// this.pressure = sd.pressure;
//
//
// // Update the timestamp
// this.timestamp = sd.timestamp;
// }
//
// @Override
// public String toString(){
// return toCSVString();
// }
//
// private String getValues(float[] array) {
// return String.valueOf(array[0]) + ","
// + String.valueOf(array[1]) + ","
// + String.valueOf(array[2]);
// }
//
// /**
// * Get all sensor data in JSON format
// * @return JSONObject object of all sensor data in JSON format
// */
// JSONObject toJsonObj() {
// try {
// JSONObject obj = new JSONObject();
// obj.put("accelerate", getXYZJsonObj(accelerate[0], accelerate[1], accelerate[2]));
// obj.put("gyroscope", getXYZJsonObj(gyroscope[0], gyroscope[1], gyroscope[2]));
// obj.put("gravity", getXYZJsonObj(gravity[0], gravity[1], gravity[2]));
// obj.put("magnetic", getXYZJsonObj(magnetic[0], magnetic[1], magnetic[2]));
// obj.put("game_rotation_vector", getXYZJsonObj(game_rotation_vector[0], game_rotation_vector[1], game_rotation_vector[2]));
// obj.put("orientation", getXYZJsonObj(orientation[0], orientation[1], orientation[2]));
// obj.put("world_accelerometer", getXYZJsonObj(world_accelerometer[0], world_accelerometer[1], world_accelerometer[2]));
// obj.put("light", light);
// obj.put("pressure", pressure);
// obj.put("temperature", temperature);
// obj.put("timestamp", timestamp);
// return obj;
// } catch (Throwable e) {
// e.printStackTrace();
// }
// return null;
// }
//
// /**
// * Get all sensor data in CSV format
// * @return String object of all sensor data in CSV format
// */
// private String toCSVString() {
// StringBuilder sb = new StringBuilder();
// sb.append(getValues(accelerate));
// sb.append(",");
// sb.append(getValues(gyroscope));
// sb.append(",");
// sb.append(getValues(gravity));
// sb.append(",");
// sb.append(getValues(magnetic));
// sb.append(",");
// sb.append(getValues(game_rotation_vector));
// sb.append(",");
// sb.append(getValues(orientation));
// sb.append(",");
// sb.append(getValues(world_accelerometer));
// sb.append(",");
// sb.append(String.valueOf(light));
// sb.append(",");
// sb.append(String.valueOf(pressure));
// sb.append(",");
// sb.append(String.valueOf(temperature));
// sb.append(",");
// sb.append(String.valueOf(timestamp));
// return sb.toString();
// }
//
// private JSONObject getXYZJsonObj(final float x, final float y, final float z) {
// try {
// JSONObject jsonObj = new JSONObject();
// jsonObj.put("x", x);
// jsonObj.put("y", y);
// jsonObj.put("z", z);
// return jsonObj;
//
// } catch (Throwable e) {
// e.printStackTrace();
// return null;
// }
// }
// }
| import android.content.Context;
import android.content.res.AssetManager;
import com.talkingdata.myna.sensor.SensorData;
import org.tensorflow.contrib.android.TensorFlowInferenceInterface; | package com.talkingdata.myna;
public class LSTMClassifier implements ClassifierInterface {
static {
System.loadLibrary("tensorflow_inference");
}
private TensorFlowInferenceInterface inferenceInterface;
private static final String MODEL_FILE = "file:///android_asset/optimized_frozen_lstm.pb";
private static final String INPUT_NODE = "input";
private static final String[] OUTPUT_NODES = {"output"};
private static final String OUTPUT_NODE = "output";
private static final int INPUT_SIZE = 3 * 128;
private static final int OUTPUT_SIZE = 6;
public LSTMClassifier(final Context ctx) {
AssetManager assetManager = ctx.getAssets();
inferenceInterface = new TensorFlowInferenceInterface(assetManager, MODEL_FILE);
}
public static final String TYPE = "lstm";
/**
* Extract and select features from the raw sensor data points.
* These data points are collected with certain sampling frequency and windows.
* @param sData Raw sensor data points.
* @return Extracted features.
*/ | // Path: Android/lib-Myna/src/main/java/com/talkingdata/myna/sensor/SensorData.java
// public class SensorData {
// /**
// * Sensor data
// */
// public float[] accelerate, gyroscope, gravity, magnetic, game_rotation_vector, orientation;
//
//
// /**
// * Calculated accelerometer values in real world coordination system.
// */
// public float[] world_accelerometer;
//
// public float light, pressure, temperature;
//
// /**
// * Time when recording the data of these sensors
// */
// public long timestamp;
//
// public SensorData() {
// accelerate = new float[3];
// gyroscope = new float[3];
// gravity = new float[3];
// magnetic = new float[3];
// game_rotation_vector = new float[3];
// orientation = new float[3];
// world_accelerometer = new float[3];
// timestamp = System.currentTimeMillis();
// }
//
// /**
// * Reset the value of all fields with the given instance
// * @param sd Source instance with the sensor data waiting to be cloned.
// */
// public void clone(SensorData sd) {
// System.arraycopy(sd.accelerate, 0, this.accelerate, 0, 3);
// System.arraycopy(sd.gyroscope, 0, this.gyroscope, 0, 3);
// System.arraycopy(sd.gravity, 0, this.gravity, 0, 3);
// System.arraycopy(sd.magnetic, 0, this.magnetic, 0, 3);
// System.arraycopy(sd.game_rotation_vector, 0, this.game_rotation_vector, 0, 3);
// System.arraycopy(sd.orientation, 0, this.orientation, 0, 3);
// System.arraycopy(sd.world_accelerometer, 0, this.world_accelerometer, 0, 3);
//
// this.light = sd.light;
// this.temperature = sd.temperature;
// this.pressure = sd.pressure;
//
//
// // Update the timestamp
// this.timestamp = sd.timestamp;
// }
//
// @Override
// public String toString(){
// return toCSVString();
// }
//
// private String getValues(float[] array) {
// return String.valueOf(array[0]) + ","
// + String.valueOf(array[1]) + ","
// + String.valueOf(array[2]);
// }
//
// /**
// * Get all sensor data in JSON format
// * @return JSONObject object of all sensor data in JSON format
// */
// JSONObject toJsonObj() {
// try {
// JSONObject obj = new JSONObject();
// obj.put("accelerate", getXYZJsonObj(accelerate[0], accelerate[1], accelerate[2]));
// obj.put("gyroscope", getXYZJsonObj(gyroscope[0], gyroscope[1], gyroscope[2]));
// obj.put("gravity", getXYZJsonObj(gravity[0], gravity[1], gravity[2]));
// obj.put("magnetic", getXYZJsonObj(magnetic[0], magnetic[1], magnetic[2]));
// obj.put("game_rotation_vector", getXYZJsonObj(game_rotation_vector[0], game_rotation_vector[1], game_rotation_vector[2]));
// obj.put("orientation", getXYZJsonObj(orientation[0], orientation[1], orientation[2]));
// obj.put("world_accelerometer", getXYZJsonObj(world_accelerometer[0], world_accelerometer[1], world_accelerometer[2]));
// obj.put("light", light);
// obj.put("pressure", pressure);
// obj.put("temperature", temperature);
// obj.put("timestamp", timestamp);
// return obj;
// } catch (Throwable e) {
// e.printStackTrace();
// }
// return null;
// }
//
// /**
// * Get all sensor data in CSV format
// * @return String object of all sensor data in CSV format
// */
// private String toCSVString() {
// StringBuilder sb = new StringBuilder();
// sb.append(getValues(accelerate));
// sb.append(",");
// sb.append(getValues(gyroscope));
// sb.append(",");
// sb.append(getValues(gravity));
// sb.append(",");
// sb.append(getValues(magnetic));
// sb.append(",");
// sb.append(getValues(game_rotation_vector));
// sb.append(",");
// sb.append(getValues(orientation));
// sb.append(",");
// sb.append(getValues(world_accelerometer));
// sb.append(",");
// sb.append(String.valueOf(light));
// sb.append(",");
// sb.append(String.valueOf(pressure));
// sb.append(",");
// sb.append(String.valueOf(temperature));
// sb.append(",");
// sb.append(String.valueOf(timestamp));
// return sb.toString();
// }
//
// private JSONObject getXYZJsonObj(final float x, final float y, final float z) {
// try {
// JSONObject jsonObj = new JSONObject();
// jsonObj.put("x", x);
// jsonObj.put("y", y);
// jsonObj.put("z", z);
// return jsonObj;
//
// } catch (Throwable e) {
// e.printStackTrace();
// return null;
// }
// }
// }
// Path: Android/lib-Myna/src/main/java/com/talkingdata/myna/LSTMClassifier.java
import android.content.Context;
import android.content.res.AssetManager;
import com.talkingdata.myna.sensor.SensorData;
import org.tensorflow.contrib.android.TensorFlowInferenceInterface;
package com.talkingdata.myna;
public class LSTMClassifier implements ClassifierInterface {
static {
System.loadLibrary("tensorflow_inference");
}
private TensorFlowInferenceInterface inferenceInterface;
private static final String MODEL_FILE = "file:///android_asset/optimized_frozen_lstm.pb";
private static final String INPUT_NODE = "input";
private static final String[] OUTPUT_NODES = {"output"};
private static final String OUTPUT_NODE = "output";
private static final int INPUT_SIZE = 3 * 128;
private static final int OUTPUT_SIZE = 6;
public LSTMClassifier(final Context ctx) {
AssetManager assetManager = ctx.getAssets();
inferenceInterface = new TensorFlowInferenceInterface(assetManager, MODEL_FILE);
}
public static final String TYPE = "lstm";
/**
* Extract and select features from the raw sensor data points.
* These data points are collected with certain sampling frequency and windows.
* @param sData Raw sensor data points.
* @return Extracted features.
*/ | private float[] prepareFeatures(SensorData[] sData, final int sampleCount) { |
TalkingData/Myna | Android/lib-Myna/src/main/java/biz/k11i/xgboost/gbm/GBTree.java | // Path: Android/lib-Myna/src/main/java/biz/k11i/xgboost/util/FVec.java
// public interface FVec extends Serializable {
// /**
// * Gets index-th value.
// *
// * @param index index
// * @return value
// */
// double fvalue(int index);
//
// class Transformer {
// private Transformer() {
// // do nothing
// }
//
// /**
// * Builds FVec from dense vector.
// *
// * @param values float values
// * @param treatsZeroAsNA treat zero as N/A if true
// * @return FVec
// */
// public static FVec fromArray(float[] values, boolean treatsZeroAsNA) {
// return new FVecArrayImpl.FVecFloatArrayImpl(values, treatsZeroAsNA);
// }
//
// /**
// * Builds FVec from dense vector.
// *
// * @param values double values
// * @param treatsZeroAsNA treat zero as N/A if true
// * @return FVec
// */
// public static FVec fromArray(double[] values, boolean treatsZeroAsNA) {
// return new FVecArrayImpl.FVecDoubleArrayImpl(values, treatsZeroAsNA);
// }
//
// /**
// * Builds FVec from map.
// *
// * @param map map containing non-zero values
// * @return FVec
// */
// public static FVec fromMap(Map<Integer, ? extends Number> map) {
// return new FVecMapImpl(map);
// }
// }
// }
| import biz.k11i.xgboost.tree.RegTree;
import biz.k11i.xgboost.util.FVec;
import biz.k11i.xgboost.util.ModelReader;
import java.io.IOException;
import java.io.Serializable; | if (mparam.num_trees != 0) {
tree_info = reader.readIntArray(mparam.num_trees);
}
if (mparam.num_pbuffer != 0 && with_pbuffer) {
reader.skip(4 * mparam.predBufferSize());
reader.skip(4 * mparam.predBufferSize());
}
_groupTrees = new RegTree[mparam.num_output_group][];
for (int i = 0; i < mparam.num_output_group; i++) {
int treeCount = 0;
for (int j = 0; j < tree_info.length; j++) {
if (tree_info[j] == i) {
treeCount++;
}
}
_groupTrees[i] = new RegTree[treeCount];
treeCount = 0;
for (int j = 0; j < tree_info.length; j++) {
if (tree_info[j] == i) {
_groupTrees[i][treeCount++] = trees[j];
}
}
}
}
@Override | // Path: Android/lib-Myna/src/main/java/biz/k11i/xgboost/util/FVec.java
// public interface FVec extends Serializable {
// /**
// * Gets index-th value.
// *
// * @param index index
// * @return value
// */
// double fvalue(int index);
//
// class Transformer {
// private Transformer() {
// // do nothing
// }
//
// /**
// * Builds FVec from dense vector.
// *
// * @param values float values
// * @param treatsZeroAsNA treat zero as N/A if true
// * @return FVec
// */
// public static FVec fromArray(float[] values, boolean treatsZeroAsNA) {
// return new FVecArrayImpl.FVecFloatArrayImpl(values, treatsZeroAsNA);
// }
//
// /**
// * Builds FVec from dense vector.
// *
// * @param values double values
// * @param treatsZeroAsNA treat zero as N/A if true
// * @return FVec
// */
// public static FVec fromArray(double[] values, boolean treatsZeroAsNA) {
// return new FVecArrayImpl.FVecDoubleArrayImpl(values, treatsZeroAsNA);
// }
//
// /**
// * Builds FVec from map.
// *
// * @param map map containing non-zero values
// * @return FVec
// */
// public static FVec fromMap(Map<Integer, ? extends Number> map) {
// return new FVecMapImpl(map);
// }
// }
// }
// Path: Android/lib-Myna/src/main/java/biz/k11i/xgboost/gbm/GBTree.java
import biz.k11i.xgboost.tree.RegTree;
import biz.k11i.xgboost.util.FVec;
import biz.k11i.xgboost.util.ModelReader;
import java.io.IOException;
import java.io.Serializable;
if (mparam.num_trees != 0) {
tree_info = reader.readIntArray(mparam.num_trees);
}
if (mparam.num_pbuffer != 0 && with_pbuffer) {
reader.skip(4 * mparam.predBufferSize());
reader.skip(4 * mparam.predBufferSize());
}
_groupTrees = new RegTree[mparam.num_output_group][];
for (int i = 0; i < mparam.num_output_group; i++) {
int treeCount = 0;
for (int j = 0; j < tree_info.length; j++) {
if (tree_info[j] == i) {
treeCount++;
}
}
_groupTrees[i] = new RegTree[treeCount];
treeCount = 0;
for (int j = 0; j < tree_info.length; j++) {
if (tree_info[j] == i) {
_groupTrees[i][treeCount++] = trees[j];
}
}
}
}
@Override | public double[] predict(FVec feat, int ntree_limit) { |
TalkingData/Myna | Android/lib-Myna/src/main/java/com/talkingdata/myna/tools/Utils.java | // Path: Android/lib-Myna/src/main/java/com/talkingdata/myna/sensor/SensorData.java
// public class SensorData {
// /**
// * Sensor data
// */
// public float[] accelerate, gyroscope, gravity, magnetic, game_rotation_vector, orientation;
//
//
// /**
// * Calculated accelerometer values in real world coordination system.
// */
// public float[] world_accelerometer;
//
// public float light, pressure, temperature;
//
// /**
// * Time when recording the data of these sensors
// */
// public long timestamp;
//
// public SensorData() {
// accelerate = new float[3];
// gyroscope = new float[3];
// gravity = new float[3];
// magnetic = new float[3];
// game_rotation_vector = new float[3];
// orientation = new float[3];
// world_accelerometer = new float[3];
// timestamp = System.currentTimeMillis();
// }
//
// /**
// * Reset the value of all fields with the given instance
// * @param sd Source instance with the sensor data waiting to be cloned.
// */
// public void clone(SensorData sd) {
// System.arraycopy(sd.accelerate, 0, this.accelerate, 0, 3);
// System.arraycopy(sd.gyroscope, 0, this.gyroscope, 0, 3);
// System.arraycopy(sd.gravity, 0, this.gravity, 0, 3);
// System.arraycopy(sd.magnetic, 0, this.magnetic, 0, 3);
// System.arraycopy(sd.game_rotation_vector, 0, this.game_rotation_vector, 0, 3);
// System.arraycopy(sd.orientation, 0, this.orientation, 0, 3);
// System.arraycopy(sd.world_accelerometer, 0, this.world_accelerometer, 0, 3);
//
// this.light = sd.light;
// this.temperature = sd.temperature;
// this.pressure = sd.pressure;
//
//
// // Update the timestamp
// this.timestamp = sd.timestamp;
// }
//
// @Override
// public String toString(){
// return toCSVString();
// }
//
// private String getValues(float[] array) {
// return String.valueOf(array[0]) + ","
// + String.valueOf(array[1]) + ","
// + String.valueOf(array[2]);
// }
//
// /**
// * Get all sensor data in JSON format
// * @return JSONObject object of all sensor data in JSON format
// */
// JSONObject toJsonObj() {
// try {
// JSONObject obj = new JSONObject();
// obj.put("accelerate", getXYZJsonObj(accelerate[0], accelerate[1], accelerate[2]));
// obj.put("gyroscope", getXYZJsonObj(gyroscope[0], gyroscope[1], gyroscope[2]));
// obj.put("gravity", getXYZJsonObj(gravity[0], gravity[1], gravity[2]));
// obj.put("magnetic", getXYZJsonObj(magnetic[0], magnetic[1], magnetic[2]));
// obj.put("game_rotation_vector", getXYZJsonObj(game_rotation_vector[0], game_rotation_vector[1], game_rotation_vector[2]));
// obj.put("orientation", getXYZJsonObj(orientation[0], orientation[1], orientation[2]));
// obj.put("world_accelerometer", getXYZJsonObj(world_accelerometer[0], world_accelerometer[1], world_accelerometer[2]));
// obj.put("light", light);
// obj.put("pressure", pressure);
// obj.put("temperature", temperature);
// obj.put("timestamp", timestamp);
// return obj;
// } catch (Throwable e) {
// e.printStackTrace();
// }
// return null;
// }
//
// /**
// * Get all sensor data in CSV format
// * @return String object of all sensor data in CSV format
// */
// private String toCSVString() {
// StringBuilder sb = new StringBuilder();
// sb.append(getValues(accelerate));
// sb.append(",");
// sb.append(getValues(gyroscope));
// sb.append(",");
// sb.append(getValues(gravity));
// sb.append(",");
// sb.append(getValues(magnetic));
// sb.append(",");
// sb.append(getValues(game_rotation_vector));
// sb.append(",");
// sb.append(getValues(orientation));
// sb.append(",");
// sb.append(getValues(world_accelerometer));
// sb.append(",");
// sb.append(String.valueOf(light));
// sb.append(",");
// sb.append(String.valueOf(pressure));
// sb.append(",");
// sb.append(String.valueOf(temperature));
// sb.append(",");
// sb.append(String.valueOf(timestamp));
// return sb.toString();
// }
//
// private JSONObject getXYZJsonObj(final float x, final float y, final float z) {
// try {
// JSONObject jsonObj = new JSONObject();
// jsonObj.put("x", x);
// jsonObj.put("y", y);
// jsonObj.put("z", z);
// return jsonObj;
//
// } catch (Throwable e) {
// e.printStackTrace();
// return null;
// }
// }
// }
| import android.content.Context;
import android.hardware.SensorManager;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.util.SparseArray;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.talkingdata.myna.sensor.SensorData;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable; | package com.talkingdata.myna.tools;
public class Utils {
public static final String TAG = "Myna";
| // Path: Android/lib-Myna/src/main/java/com/talkingdata/myna/sensor/SensorData.java
// public class SensorData {
// /**
// * Sensor data
// */
// public float[] accelerate, gyroscope, gravity, magnetic, game_rotation_vector, orientation;
//
//
// /**
// * Calculated accelerometer values in real world coordination system.
// */
// public float[] world_accelerometer;
//
// public float light, pressure, temperature;
//
// /**
// * Time when recording the data of these sensors
// */
// public long timestamp;
//
// public SensorData() {
// accelerate = new float[3];
// gyroscope = new float[3];
// gravity = new float[3];
// magnetic = new float[3];
// game_rotation_vector = new float[3];
// orientation = new float[3];
// world_accelerometer = new float[3];
// timestamp = System.currentTimeMillis();
// }
//
// /**
// * Reset the value of all fields with the given instance
// * @param sd Source instance with the sensor data waiting to be cloned.
// */
// public void clone(SensorData sd) {
// System.arraycopy(sd.accelerate, 0, this.accelerate, 0, 3);
// System.arraycopy(sd.gyroscope, 0, this.gyroscope, 0, 3);
// System.arraycopy(sd.gravity, 0, this.gravity, 0, 3);
// System.arraycopy(sd.magnetic, 0, this.magnetic, 0, 3);
// System.arraycopy(sd.game_rotation_vector, 0, this.game_rotation_vector, 0, 3);
// System.arraycopy(sd.orientation, 0, this.orientation, 0, 3);
// System.arraycopy(sd.world_accelerometer, 0, this.world_accelerometer, 0, 3);
//
// this.light = sd.light;
// this.temperature = sd.temperature;
// this.pressure = sd.pressure;
//
//
// // Update the timestamp
// this.timestamp = sd.timestamp;
// }
//
// @Override
// public String toString(){
// return toCSVString();
// }
//
// private String getValues(float[] array) {
// return String.valueOf(array[0]) + ","
// + String.valueOf(array[1]) + ","
// + String.valueOf(array[2]);
// }
//
// /**
// * Get all sensor data in JSON format
// * @return JSONObject object of all sensor data in JSON format
// */
// JSONObject toJsonObj() {
// try {
// JSONObject obj = new JSONObject();
// obj.put("accelerate", getXYZJsonObj(accelerate[0], accelerate[1], accelerate[2]));
// obj.put("gyroscope", getXYZJsonObj(gyroscope[0], gyroscope[1], gyroscope[2]));
// obj.put("gravity", getXYZJsonObj(gravity[0], gravity[1], gravity[2]));
// obj.put("magnetic", getXYZJsonObj(magnetic[0], magnetic[1], magnetic[2]));
// obj.put("game_rotation_vector", getXYZJsonObj(game_rotation_vector[0], game_rotation_vector[1], game_rotation_vector[2]));
// obj.put("orientation", getXYZJsonObj(orientation[0], orientation[1], orientation[2]));
// obj.put("world_accelerometer", getXYZJsonObj(world_accelerometer[0], world_accelerometer[1], world_accelerometer[2]));
// obj.put("light", light);
// obj.put("pressure", pressure);
// obj.put("temperature", temperature);
// obj.put("timestamp", timestamp);
// return obj;
// } catch (Throwable e) {
// e.printStackTrace();
// }
// return null;
// }
//
// /**
// * Get all sensor data in CSV format
// * @return String object of all sensor data in CSV format
// */
// private String toCSVString() {
// StringBuilder sb = new StringBuilder();
// sb.append(getValues(accelerate));
// sb.append(",");
// sb.append(getValues(gyroscope));
// sb.append(",");
// sb.append(getValues(gravity));
// sb.append(",");
// sb.append(getValues(magnetic));
// sb.append(",");
// sb.append(getValues(game_rotation_vector));
// sb.append(",");
// sb.append(getValues(orientation));
// sb.append(",");
// sb.append(getValues(world_accelerometer));
// sb.append(",");
// sb.append(String.valueOf(light));
// sb.append(",");
// sb.append(String.valueOf(pressure));
// sb.append(",");
// sb.append(String.valueOf(temperature));
// sb.append(",");
// sb.append(String.valueOf(timestamp));
// return sb.toString();
// }
//
// private JSONObject getXYZJsonObj(final float x, final float y, final float z) {
// try {
// JSONObject jsonObj = new JSONObject();
// jsonObj.put("x", x);
// jsonObj.put("y", y);
// jsonObj.put("z", z);
// return jsonObj;
//
// } catch (Throwable e) {
// e.printStackTrace();
// return null;
// }
// }
// }
// Path: Android/lib-Myna/src/main/java/com/talkingdata/myna/tools/Utils.java
import android.content.Context;
import android.hardware.SensorManager;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;
import android.util.SparseArray;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.talkingdata.myna.sensor.SensorData;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
package com.talkingdata.myna.tools;
public class Utils {
public static final String TAG = "Myna";
| public static void calculateWorldAcce(SensorData sd){ |
TalkingData/Myna | Android/lib-Myna/src/main/java/com/talkingdata/myna/MynaRecognizerAbstractClass.java | // Path: Android/lib-Myna/src/main/java/com/talkingdata/myna/sensor/SensorData.java
// public class SensorData {
// /**
// * Sensor data
// */
// public float[] accelerate, gyroscope, gravity, magnetic, game_rotation_vector, orientation;
//
//
// /**
// * Calculated accelerometer values in real world coordination system.
// */
// public float[] world_accelerometer;
//
// public float light, pressure, temperature;
//
// /**
// * Time when recording the data of these sensors
// */
// public long timestamp;
//
// public SensorData() {
// accelerate = new float[3];
// gyroscope = new float[3];
// gravity = new float[3];
// magnetic = new float[3];
// game_rotation_vector = new float[3];
// orientation = new float[3];
// world_accelerometer = new float[3];
// timestamp = System.currentTimeMillis();
// }
//
// /**
// * Reset the value of all fields with the given instance
// * @param sd Source instance with the sensor data waiting to be cloned.
// */
// public void clone(SensorData sd) {
// System.arraycopy(sd.accelerate, 0, this.accelerate, 0, 3);
// System.arraycopy(sd.gyroscope, 0, this.gyroscope, 0, 3);
// System.arraycopy(sd.gravity, 0, this.gravity, 0, 3);
// System.arraycopy(sd.magnetic, 0, this.magnetic, 0, 3);
// System.arraycopy(sd.game_rotation_vector, 0, this.game_rotation_vector, 0, 3);
// System.arraycopy(sd.orientation, 0, this.orientation, 0, 3);
// System.arraycopy(sd.world_accelerometer, 0, this.world_accelerometer, 0, 3);
//
// this.light = sd.light;
// this.temperature = sd.temperature;
// this.pressure = sd.pressure;
//
//
// // Update the timestamp
// this.timestamp = sd.timestamp;
// }
//
// @Override
// public String toString(){
// return toCSVString();
// }
//
// private String getValues(float[] array) {
// return String.valueOf(array[0]) + ","
// + String.valueOf(array[1]) + ","
// + String.valueOf(array[2]);
// }
//
// /**
// * Get all sensor data in JSON format
// * @return JSONObject object of all sensor data in JSON format
// */
// JSONObject toJsonObj() {
// try {
// JSONObject obj = new JSONObject();
// obj.put("accelerate", getXYZJsonObj(accelerate[0], accelerate[1], accelerate[2]));
// obj.put("gyroscope", getXYZJsonObj(gyroscope[0], gyroscope[1], gyroscope[2]));
// obj.put("gravity", getXYZJsonObj(gravity[0], gravity[1], gravity[2]));
// obj.put("magnetic", getXYZJsonObj(magnetic[0], magnetic[1], magnetic[2]));
// obj.put("game_rotation_vector", getXYZJsonObj(game_rotation_vector[0], game_rotation_vector[1], game_rotation_vector[2]));
// obj.put("orientation", getXYZJsonObj(orientation[0], orientation[1], orientation[2]));
// obj.put("world_accelerometer", getXYZJsonObj(world_accelerometer[0], world_accelerometer[1], world_accelerometer[2]));
// obj.put("light", light);
// obj.put("pressure", pressure);
// obj.put("temperature", temperature);
// obj.put("timestamp", timestamp);
// return obj;
// } catch (Throwable e) {
// e.printStackTrace();
// }
// return null;
// }
//
// /**
// * Get all sensor data in CSV format
// * @return String object of all sensor data in CSV format
// */
// private String toCSVString() {
// StringBuilder sb = new StringBuilder();
// sb.append(getValues(accelerate));
// sb.append(",");
// sb.append(getValues(gyroscope));
// sb.append(",");
// sb.append(getValues(gravity));
// sb.append(",");
// sb.append(getValues(magnetic));
// sb.append(",");
// sb.append(getValues(game_rotation_vector));
// sb.append(",");
// sb.append(getValues(orientation));
// sb.append(",");
// sb.append(getValues(world_accelerometer));
// sb.append(",");
// sb.append(String.valueOf(light));
// sb.append(",");
// sb.append(String.valueOf(pressure));
// sb.append(",");
// sb.append(String.valueOf(temperature));
// sb.append(",");
// sb.append(String.valueOf(timestamp));
// return sb.toString();
// }
//
// private JSONObject getXYZJsonObj(final float x, final float y, final float z) {
// try {
// JSONObject jsonObj = new JSONObject();
// jsonObj.put("x", x);
// jsonObj.put("y", y);
// jsonObj.put("z", z);
// return jsonObj;
//
// } catch (Throwable e) {
// e.printStackTrace();
// return null;
// }
// }
// }
| import android.hardware.Sensor;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.SparseIntArray;
import com.talkingdata.myna.sensor.SensorData; | package com.talkingdata.myna;
abstract class MynaRecognizerAbstractClass {
abstract void onResult(double[] confidences);
/**
* Sensors whose data will be collected.
* key = sensorType, value = sensorString
*/
private SparseIntArray chosenSensors;
/**
* Duration between each sampling, indicates sampling frequency.
*/
private int samplingInterval;
/**
* Total count of sampling points you expect to collected,
* indicates sampling window.
*/
private int samplingPointCount;
/**
* Algorithm which is used to recognize current activity.
*/
ClassifierInterface classifier;
/**
* Callback to return the results
*/
MynaResultCallback resultCallback;
int dataSetIndex;
Handler dataFusionHandler;
Handler recognitionHandler;
| // Path: Android/lib-Myna/src/main/java/com/talkingdata/myna/sensor/SensorData.java
// public class SensorData {
// /**
// * Sensor data
// */
// public float[] accelerate, gyroscope, gravity, magnetic, game_rotation_vector, orientation;
//
//
// /**
// * Calculated accelerometer values in real world coordination system.
// */
// public float[] world_accelerometer;
//
// public float light, pressure, temperature;
//
// /**
// * Time when recording the data of these sensors
// */
// public long timestamp;
//
// public SensorData() {
// accelerate = new float[3];
// gyroscope = new float[3];
// gravity = new float[3];
// magnetic = new float[3];
// game_rotation_vector = new float[3];
// orientation = new float[3];
// world_accelerometer = new float[3];
// timestamp = System.currentTimeMillis();
// }
//
// /**
// * Reset the value of all fields with the given instance
// * @param sd Source instance with the sensor data waiting to be cloned.
// */
// public void clone(SensorData sd) {
// System.arraycopy(sd.accelerate, 0, this.accelerate, 0, 3);
// System.arraycopy(sd.gyroscope, 0, this.gyroscope, 0, 3);
// System.arraycopy(sd.gravity, 0, this.gravity, 0, 3);
// System.arraycopy(sd.magnetic, 0, this.magnetic, 0, 3);
// System.arraycopy(sd.game_rotation_vector, 0, this.game_rotation_vector, 0, 3);
// System.arraycopy(sd.orientation, 0, this.orientation, 0, 3);
// System.arraycopy(sd.world_accelerometer, 0, this.world_accelerometer, 0, 3);
//
// this.light = sd.light;
// this.temperature = sd.temperature;
// this.pressure = sd.pressure;
//
//
// // Update the timestamp
// this.timestamp = sd.timestamp;
// }
//
// @Override
// public String toString(){
// return toCSVString();
// }
//
// private String getValues(float[] array) {
// return String.valueOf(array[0]) + ","
// + String.valueOf(array[1]) + ","
// + String.valueOf(array[2]);
// }
//
// /**
// * Get all sensor data in JSON format
// * @return JSONObject object of all sensor data in JSON format
// */
// JSONObject toJsonObj() {
// try {
// JSONObject obj = new JSONObject();
// obj.put("accelerate", getXYZJsonObj(accelerate[0], accelerate[1], accelerate[2]));
// obj.put("gyroscope", getXYZJsonObj(gyroscope[0], gyroscope[1], gyroscope[2]));
// obj.put("gravity", getXYZJsonObj(gravity[0], gravity[1], gravity[2]));
// obj.put("magnetic", getXYZJsonObj(magnetic[0], magnetic[1], magnetic[2]));
// obj.put("game_rotation_vector", getXYZJsonObj(game_rotation_vector[0], game_rotation_vector[1], game_rotation_vector[2]));
// obj.put("orientation", getXYZJsonObj(orientation[0], orientation[1], orientation[2]));
// obj.put("world_accelerometer", getXYZJsonObj(world_accelerometer[0], world_accelerometer[1], world_accelerometer[2]));
// obj.put("light", light);
// obj.put("pressure", pressure);
// obj.put("temperature", temperature);
// obj.put("timestamp", timestamp);
// return obj;
// } catch (Throwable e) {
// e.printStackTrace();
// }
// return null;
// }
//
// /**
// * Get all sensor data in CSV format
// * @return String object of all sensor data in CSV format
// */
// private String toCSVString() {
// StringBuilder sb = new StringBuilder();
// sb.append(getValues(accelerate));
// sb.append(",");
// sb.append(getValues(gyroscope));
// sb.append(",");
// sb.append(getValues(gravity));
// sb.append(",");
// sb.append(getValues(magnetic));
// sb.append(",");
// sb.append(getValues(game_rotation_vector));
// sb.append(",");
// sb.append(getValues(orientation));
// sb.append(",");
// sb.append(getValues(world_accelerometer));
// sb.append(",");
// sb.append(String.valueOf(light));
// sb.append(",");
// sb.append(String.valueOf(pressure));
// sb.append(",");
// sb.append(String.valueOf(temperature));
// sb.append(",");
// sb.append(String.valueOf(timestamp));
// return sb.toString();
// }
//
// private JSONObject getXYZJsonObj(final float x, final float y, final float z) {
// try {
// JSONObject jsonObj = new JSONObject();
// jsonObj.put("x", x);
// jsonObj.put("y", y);
// jsonObj.put("z", z);
// return jsonObj;
//
// } catch (Throwable e) {
// e.printStackTrace();
// return null;
// }
// }
// }
// Path: Android/lib-Myna/src/main/java/com/talkingdata/myna/MynaRecognizerAbstractClass.java
import android.hardware.Sensor;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.SparseIntArray;
import com.talkingdata.myna.sensor.SensorData;
package com.talkingdata.myna;
abstract class MynaRecognizerAbstractClass {
abstract void onResult(double[] confidences);
/**
* Sensors whose data will be collected.
* key = sensorType, value = sensorString
*/
private SparseIntArray chosenSensors;
/**
* Duration between each sampling, indicates sampling frequency.
*/
private int samplingInterval;
/**
* Total count of sampling points you expect to collected,
* indicates sampling window.
*/
private int samplingPointCount;
/**
* Algorithm which is used to recognize current activity.
*/
ClassifierInterface classifier;
/**
* Callback to return the results
*/
MynaResultCallback resultCallback;
int dataSetIndex;
Handler dataFusionHandler;
Handler recognitionHandler;
| SensorData[] dataSet; |
TalkingData/Myna | Android/lib-Myna/src/main/java/com/talkingdata/myna/sensor/Feature.java | // Path: Android/lib-Myna/src/main/java/com/talkingdata/myna/tools/Statistics.java
// public class Statistics {
//
// public static float getMean(float[] data) {
// float sum = 0.0f;
// for (float f : data)
// sum += f;
// return sum / data.length;
// }
//
// public static float getStdDev(float[] data) {
// return (float)Math.sqrt(getVariance(data));
// }
//
// public static float getMin(float[] data){
// float min = 10000;
// for (float f : data) {
// min = Math.min(min, f);
// }
// return min;
// }
//
// public static float getMax(float[] data){
// float max = -10000;
// for (float f : data) {
// max = Math.max(max, f);
// }
// return max;
// }
//
// public static float[] getFreqAndMagnitudeViaFFT(float[] data, int sampleFreq, int sampleCount){
// int batchSize = data.length;
// float[] freqAndMag = new float[2];
// Complex[] x = new Complex[batchSize];
// for (int j = 0; j < batchSize; ++j) {
// x[j] = new Complex(data[j], 0);
// }
// Complex[] y = FFT.fft(x);
// double max_magnitude = y[1].abs();
// int max_index = 1;
// for (int j = 2; j < batchSize / 2; ++j) {
// double curr_magnitude = y[j].abs();
// if(curr_magnitude > max_magnitude){
// max_magnitude = curr_magnitude;
// max_index = j;
// }
// }
// freqAndMag[0] = sampleFreq * 1.0f / sampleCount * max_index;
// freqAndMag[1] = (float)max_magnitude / 100.0f;
// return freqAndMag;
// }
//
// public static float[] getWaveletApproximation(float[] data){
// double[] raw = new double[data.length];
// for(int i = 0; i < data.length; ++i){
// raw[i] = data[i];
// }
// Haar1 h = new Haar1();
// double[] coefficients = h.forward(raw, raw.length);
// float[] approximation = new float[coefficients.length / 2];
// for(int i = 0; i < coefficients.length / 2; ++i){
// approximation[i] = (float)coefficients[i];
// }
// return approximation;
// }
//
// public static void normalize(float[] data){
// float mean = getMean(data);
// float stdDev = getStdDev(data);
// for(int i = 0; i < data.length; ++i){
// data[i] = (data[i] - mean) / stdDev;
// }
// }
//
//
// private static float getVariance(float[] data){
// return getVariance(data, 0);
// }
//
// private static float getVariance(float[] data, int ddof) {
// float mean = getMean(data);
// float temp = 0;
// for (float a : data)
// temp += (a - mean) * (a - mean);
//
// if(ddof >= data.length){
// return temp / data.length;
// }else{
// return temp / (data.length - ddof);
// }
// }
//
// public static float getMedian(float[] data){
// Arrays.sort(data);
// float median;
// if (data.length % 2 == 0)
// median = (data[data.length/2] + data[data.length/2 - 1])/2;
// else
// median = data[data.length/2];
// return median;
//
// }
// }
| import com.talkingdata.myna.tools.Statistics; |
package com.talkingdata.myna.sensor;
public class Feature {
private int batchSize;
private SensorFeature feature;
public Feature() {
feature = new SensorFeature();
batchSize = 0;
}
/**
* Get selected feature
* @return selected feature
*/
public SensorFeature getSelectedFeatures(){
return feature;
}
/**
* Extract feature from raw sensor data
*/
public void extractFeatures(SensorData[] sensorData, final int sampleFreq, final int sampleCount) {
batchSize = sensorData.length;
float[][] input = new float[3][batchSize];
for (int i = 0; i < batchSize; i++){
input[0][i] = sensorData[i].world_accelerometer[0];
input[1][i] = sensorData[i].world_accelerometer[1];
input[2][i] = sensorData[i].world_accelerometer[2];
}
// Statistics.normalize(input[0]);
// Statistics.normalize(input[1]);
// Statistics.normalize(input[2]);
getFeaturesInternally(input, sampleFreq, sampleCount);
}
/**
* Internal implementation of extracting feature from raw sensor data
*/
private void getFeaturesInternally(float[][] dataset, final int sampleFreq, final int sampleCount) { | // Path: Android/lib-Myna/src/main/java/com/talkingdata/myna/tools/Statistics.java
// public class Statistics {
//
// public static float getMean(float[] data) {
// float sum = 0.0f;
// for (float f : data)
// sum += f;
// return sum / data.length;
// }
//
// public static float getStdDev(float[] data) {
// return (float)Math.sqrt(getVariance(data));
// }
//
// public static float getMin(float[] data){
// float min = 10000;
// for (float f : data) {
// min = Math.min(min, f);
// }
// return min;
// }
//
// public static float getMax(float[] data){
// float max = -10000;
// for (float f : data) {
// max = Math.max(max, f);
// }
// return max;
// }
//
// public static float[] getFreqAndMagnitudeViaFFT(float[] data, int sampleFreq, int sampleCount){
// int batchSize = data.length;
// float[] freqAndMag = new float[2];
// Complex[] x = new Complex[batchSize];
// for (int j = 0; j < batchSize; ++j) {
// x[j] = new Complex(data[j], 0);
// }
// Complex[] y = FFT.fft(x);
// double max_magnitude = y[1].abs();
// int max_index = 1;
// for (int j = 2; j < batchSize / 2; ++j) {
// double curr_magnitude = y[j].abs();
// if(curr_magnitude > max_magnitude){
// max_magnitude = curr_magnitude;
// max_index = j;
// }
// }
// freqAndMag[0] = sampleFreq * 1.0f / sampleCount * max_index;
// freqAndMag[1] = (float)max_magnitude / 100.0f;
// return freqAndMag;
// }
//
// public static float[] getWaveletApproximation(float[] data){
// double[] raw = new double[data.length];
// for(int i = 0; i < data.length; ++i){
// raw[i] = data[i];
// }
// Haar1 h = new Haar1();
// double[] coefficients = h.forward(raw, raw.length);
// float[] approximation = new float[coefficients.length / 2];
// for(int i = 0; i < coefficients.length / 2; ++i){
// approximation[i] = (float)coefficients[i];
// }
// return approximation;
// }
//
// public static void normalize(float[] data){
// float mean = getMean(data);
// float stdDev = getStdDev(data);
// for(int i = 0; i < data.length; ++i){
// data[i] = (data[i] - mean) / stdDev;
// }
// }
//
//
// private static float getVariance(float[] data){
// return getVariance(data, 0);
// }
//
// private static float getVariance(float[] data, int ddof) {
// float mean = getMean(data);
// float temp = 0;
// for (float a : data)
// temp += (a - mean) * (a - mean);
//
// if(ddof >= data.length){
// return temp / data.length;
// }else{
// return temp / (data.length - ddof);
// }
// }
//
// public static float getMedian(float[] data){
// Arrays.sort(data);
// float median;
// if (data.length % 2 == 0)
// median = (data[data.length/2] + data[data.length/2 - 1])/2;
// else
// median = data[data.length/2];
// return median;
//
// }
// }
// Path: Android/lib-Myna/src/main/java/com/talkingdata/myna/sensor/Feature.java
import com.talkingdata.myna.tools.Statistics;
package com.talkingdata.myna.sensor;
public class Feature {
private int batchSize;
private SensorFeature feature;
public Feature() {
feature = new SensorFeature();
batchSize = 0;
}
/**
* Get selected feature
* @return selected feature
*/
public SensorFeature getSelectedFeatures(){
return feature;
}
/**
* Extract feature from raw sensor data
*/
public void extractFeatures(SensorData[] sensorData, final int sampleFreq, final int sampleCount) {
batchSize = sensorData.length;
float[][] input = new float[3][batchSize];
for (int i = 0; i < batchSize; i++){
input[0][i] = sensorData[i].world_accelerometer[0];
input[1][i] = sensorData[i].world_accelerometer[1];
input[2][i] = sensorData[i].world_accelerometer[2];
}
// Statistics.normalize(input[0]);
// Statistics.normalize(input[1]);
// Statistics.normalize(input[2]);
getFeaturesInternally(input, sampleFreq, sampleCount);
}
/**
* Internal implementation of extracting feature from raw sensor data
*/
private void getFeaturesInternally(float[][] dataset, final int sampleFreq, final int sampleCount) { | feature.maxX = Statistics.getMax(dataset[0]); |
onesocialweb/osw-lib-java | src/org/onesocialweb/smack/InboxImp.java | // Path: src/org/onesocialweb/client/Inbox.java
// public interface Inbox {
//
// public ActivityEntry getEntry(String id);
//
// public List<ActivityEntry> getEntries();
//
// public void setEntries(List<ActivityEntry> entries);
//
// public void addEntry(ActivityEntry entry);
//
// public void removeEntry(ActivityEntry entry);
//
// public void updateEntry(ActivityEntry entry);
//
// public boolean refresh();
//
// public void registerInboxEventHandler(InboxEventHandler handler);
//
// public void unregisterInboxEventHandler(InboxEventHandler handler);
//
// public int getSize();
//
// }
//
// Path: src/org/onesocialweb/client/InboxEventHandler.java
// public interface InboxEventHandler {
//
// public void onMessageReceived(ActivityEntry entry);
//
// public void onMessageDeleted(ActivityEntry entry);
//
// public void onMessageUpdated(ActivityEntry entry);
//
// public void onRefresh(List<ActivityEntry> activities);
//
// }
//
// Path: src/org/onesocialweb/client/exception/AuthenticationRequired.java
// @SuppressWarnings("serial")
// public class AuthenticationRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/ConnectionRequired.java
// @SuppressWarnings("serial")
// public class ConnectionRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/RequestException.java
// @SuppressWarnings("serial")
// public class RequestException extends Exception {
//
// public RequestException(String message) {
// super(message);
// }
// }
| import java.util.ArrayList;
import java.util.List;
import org.onesocialweb.client.Inbox;
import org.onesocialweb.client.InboxEventHandler;
import org.onesocialweb.client.exception.AuthenticationRequired;
import org.onesocialweb.client.exception.ConnectionRequired;
import org.onesocialweb.client.exception.RequestException;
import org.onesocialweb.model.activity.ActivityEntry; | /*
* Copyright 2010 Vodafone Group Services Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.onesocialweb.smack;
public class InboxImp implements Inbox {
private final List<InboxEventHandler> handlers = new ArrayList<InboxEventHandler>();
private final OswServiceImp service;
private List<ActivityEntry> entries = new ArrayList<ActivityEntry>();
public InboxImp(OswServiceImp service) {
this.service = service;
}
@Override
public List<ActivityEntry> getEntries() {
return entries;
}
@Override
public boolean refresh() {
try {
return service.refreshInbox(); | // Path: src/org/onesocialweb/client/Inbox.java
// public interface Inbox {
//
// public ActivityEntry getEntry(String id);
//
// public List<ActivityEntry> getEntries();
//
// public void setEntries(List<ActivityEntry> entries);
//
// public void addEntry(ActivityEntry entry);
//
// public void removeEntry(ActivityEntry entry);
//
// public void updateEntry(ActivityEntry entry);
//
// public boolean refresh();
//
// public void registerInboxEventHandler(InboxEventHandler handler);
//
// public void unregisterInboxEventHandler(InboxEventHandler handler);
//
// public int getSize();
//
// }
//
// Path: src/org/onesocialweb/client/InboxEventHandler.java
// public interface InboxEventHandler {
//
// public void onMessageReceived(ActivityEntry entry);
//
// public void onMessageDeleted(ActivityEntry entry);
//
// public void onMessageUpdated(ActivityEntry entry);
//
// public void onRefresh(List<ActivityEntry> activities);
//
// }
//
// Path: src/org/onesocialweb/client/exception/AuthenticationRequired.java
// @SuppressWarnings("serial")
// public class AuthenticationRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/ConnectionRequired.java
// @SuppressWarnings("serial")
// public class ConnectionRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/RequestException.java
// @SuppressWarnings("serial")
// public class RequestException extends Exception {
//
// public RequestException(String message) {
// super(message);
// }
// }
// Path: src/org/onesocialweb/smack/InboxImp.java
import java.util.ArrayList;
import java.util.List;
import org.onesocialweb.client.Inbox;
import org.onesocialweb.client.InboxEventHandler;
import org.onesocialweb.client.exception.AuthenticationRequired;
import org.onesocialweb.client.exception.ConnectionRequired;
import org.onesocialweb.client.exception.RequestException;
import org.onesocialweb.model.activity.ActivityEntry;
/*
* Copyright 2010 Vodafone Group Services Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.onesocialweb.smack;
public class InboxImp implements Inbox {
private final List<InboxEventHandler> handlers = new ArrayList<InboxEventHandler>();
private final OswServiceImp service;
private List<ActivityEntry> entries = new ArrayList<ActivityEntry>();
public InboxImp(OswServiceImp service) {
this.service = service;
}
@Override
public List<ActivityEntry> getEntries() {
return entries;
}
@Override
public boolean refresh() {
try {
return service.refreshInbox(); | } catch (ConnectionRequired e) { |
onesocialweb/osw-lib-java | src/org/onesocialweb/smack/InboxImp.java | // Path: src/org/onesocialweb/client/Inbox.java
// public interface Inbox {
//
// public ActivityEntry getEntry(String id);
//
// public List<ActivityEntry> getEntries();
//
// public void setEntries(List<ActivityEntry> entries);
//
// public void addEntry(ActivityEntry entry);
//
// public void removeEntry(ActivityEntry entry);
//
// public void updateEntry(ActivityEntry entry);
//
// public boolean refresh();
//
// public void registerInboxEventHandler(InboxEventHandler handler);
//
// public void unregisterInboxEventHandler(InboxEventHandler handler);
//
// public int getSize();
//
// }
//
// Path: src/org/onesocialweb/client/InboxEventHandler.java
// public interface InboxEventHandler {
//
// public void onMessageReceived(ActivityEntry entry);
//
// public void onMessageDeleted(ActivityEntry entry);
//
// public void onMessageUpdated(ActivityEntry entry);
//
// public void onRefresh(List<ActivityEntry> activities);
//
// }
//
// Path: src/org/onesocialweb/client/exception/AuthenticationRequired.java
// @SuppressWarnings("serial")
// public class AuthenticationRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/ConnectionRequired.java
// @SuppressWarnings("serial")
// public class ConnectionRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/RequestException.java
// @SuppressWarnings("serial")
// public class RequestException extends Exception {
//
// public RequestException(String message) {
// super(message);
// }
// }
| import java.util.ArrayList;
import java.util.List;
import org.onesocialweb.client.Inbox;
import org.onesocialweb.client.InboxEventHandler;
import org.onesocialweb.client.exception.AuthenticationRequired;
import org.onesocialweb.client.exception.ConnectionRequired;
import org.onesocialweb.client.exception.RequestException;
import org.onesocialweb.model.activity.ActivityEntry; | /*
* Copyright 2010 Vodafone Group Services Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.onesocialweb.smack;
public class InboxImp implements Inbox {
private final List<InboxEventHandler> handlers = new ArrayList<InboxEventHandler>();
private final OswServiceImp service;
private List<ActivityEntry> entries = new ArrayList<ActivityEntry>();
public InboxImp(OswServiceImp service) {
this.service = service;
}
@Override
public List<ActivityEntry> getEntries() {
return entries;
}
@Override
public boolean refresh() {
try {
return service.refreshInbox();
} catch (ConnectionRequired e) {
| // Path: src/org/onesocialweb/client/Inbox.java
// public interface Inbox {
//
// public ActivityEntry getEntry(String id);
//
// public List<ActivityEntry> getEntries();
//
// public void setEntries(List<ActivityEntry> entries);
//
// public void addEntry(ActivityEntry entry);
//
// public void removeEntry(ActivityEntry entry);
//
// public void updateEntry(ActivityEntry entry);
//
// public boolean refresh();
//
// public void registerInboxEventHandler(InboxEventHandler handler);
//
// public void unregisterInboxEventHandler(InboxEventHandler handler);
//
// public int getSize();
//
// }
//
// Path: src/org/onesocialweb/client/InboxEventHandler.java
// public interface InboxEventHandler {
//
// public void onMessageReceived(ActivityEntry entry);
//
// public void onMessageDeleted(ActivityEntry entry);
//
// public void onMessageUpdated(ActivityEntry entry);
//
// public void onRefresh(List<ActivityEntry> activities);
//
// }
//
// Path: src/org/onesocialweb/client/exception/AuthenticationRequired.java
// @SuppressWarnings("serial")
// public class AuthenticationRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/ConnectionRequired.java
// @SuppressWarnings("serial")
// public class ConnectionRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/RequestException.java
// @SuppressWarnings("serial")
// public class RequestException extends Exception {
//
// public RequestException(String message) {
// super(message);
// }
// }
// Path: src/org/onesocialweb/smack/InboxImp.java
import java.util.ArrayList;
import java.util.List;
import org.onesocialweb.client.Inbox;
import org.onesocialweb.client.InboxEventHandler;
import org.onesocialweb.client.exception.AuthenticationRequired;
import org.onesocialweb.client.exception.ConnectionRequired;
import org.onesocialweb.client.exception.RequestException;
import org.onesocialweb.model.activity.ActivityEntry;
/*
* Copyright 2010 Vodafone Group Services Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.onesocialweb.smack;
public class InboxImp implements Inbox {
private final List<InboxEventHandler> handlers = new ArrayList<InboxEventHandler>();
private final OswServiceImp service;
private List<ActivityEntry> entries = new ArrayList<ActivityEntry>();
public InboxImp(OswServiceImp service) {
this.service = service;
}
@Override
public List<ActivityEntry> getEntries() {
return entries;
}
@Override
public boolean refresh() {
try {
return service.refreshInbox();
} catch (ConnectionRequired e) {
| } catch (AuthenticationRequired e) { |
onesocialweb/osw-lib-java | src/org/onesocialweb/smack/InboxImp.java | // Path: src/org/onesocialweb/client/Inbox.java
// public interface Inbox {
//
// public ActivityEntry getEntry(String id);
//
// public List<ActivityEntry> getEntries();
//
// public void setEntries(List<ActivityEntry> entries);
//
// public void addEntry(ActivityEntry entry);
//
// public void removeEntry(ActivityEntry entry);
//
// public void updateEntry(ActivityEntry entry);
//
// public boolean refresh();
//
// public void registerInboxEventHandler(InboxEventHandler handler);
//
// public void unregisterInboxEventHandler(InboxEventHandler handler);
//
// public int getSize();
//
// }
//
// Path: src/org/onesocialweb/client/InboxEventHandler.java
// public interface InboxEventHandler {
//
// public void onMessageReceived(ActivityEntry entry);
//
// public void onMessageDeleted(ActivityEntry entry);
//
// public void onMessageUpdated(ActivityEntry entry);
//
// public void onRefresh(List<ActivityEntry> activities);
//
// }
//
// Path: src/org/onesocialweb/client/exception/AuthenticationRequired.java
// @SuppressWarnings("serial")
// public class AuthenticationRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/ConnectionRequired.java
// @SuppressWarnings("serial")
// public class ConnectionRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/RequestException.java
// @SuppressWarnings("serial")
// public class RequestException extends Exception {
//
// public RequestException(String message) {
// super(message);
// }
// }
| import java.util.ArrayList;
import java.util.List;
import org.onesocialweb.client.Inbox;
import org.onesocialweb.client.InboxEventHandler;
import org.onesocialweb.client.exception.AuthenticationRequired;
import org.onesocialweb.client.exception.ConnectionRequired;
import org.onesocialweb.client.exception.RequestException;
import org.onesocialweb.model.activity.ActivityEntry; | /*
* Copyright 2010 Vodafone Group Services Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.onesocialweb.smack;
public class InboxImp implements Inbox {
private final List<InboxEventHandler> handlers = new ArrayList<InboxEventHandler>();
private final OswServiceImp service;
private List<ActivityEntry> entries = new ArrayList<ActivityEntry>();
public InboxImp(OswServiceImp service) {
this.service = service;
}
@Override
public List<ActivityEntry> getEntries() {
return entries;
}
@Override
public boolean refresh() {
try {
return service.refreshInbox();
} catch (ConnectionRequired e) {
} catch (AuthenticationRequired e) {
| // Path: src/org/onesocialweb/client/Inbox.java
// public interface Inbox {
//
// public ActivityEntry getEntry(String id);
//
// public List<ActivityEntry> getEntries();
//
// public void setEntries(List<ActivityEntry> entries);
//
// public void addEntry(ActivityEntry entry);
//
// public void removeEntry(ActivityEntry entry);
//
// public void updateEntry(ActivityEntry entry);
//
// public boolean refresh();
//
// public void registerInboxEventHandler(InboxEventHandler handler);
//
// public void unregisterInboxEventHandler(InboxEventHandler handler);
//
// public int getSize();
//
// }
//
// Path: src/org/onesocialweb/client/InboxEventHandler.java
// public interface InboxEventHandler {
//
// public void onMessageReceived(ActivityEntry entry);
//
// public void onMessageDeleted(ActivityEntry entry);
//
// public void onMessageUpdated(ActivityEntry entry);
//
// public void onRefresh(List<ActivityEntry> activities);
//
// }
//
// Path: src/org/onesocialweb/client/exception/AuthenticationRequired.java
// @SuppressWarnings("serial")
// public class AuthenticationRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/ConnectionRequired.java
// @SuppressWarnings("serial")
// public class ConnectionRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/RequestException.java
// @SuppressWarnings("serial")
// public class RequestException extends Exception {
//
// public RequestException(String message) {
// super(message);
// }
// }
// Path: src/org/onesocialweb/smack/InboxImp.java
import java.util.ArrayList;
import java.util.List;
import org.onesocialweb.client.Inbox;
import org.onesocialweb.client.InboxEventHandler;
import org.onesocialweb.client.exception.AuthenticationRequired;
import org.onesocialweb.client.exception.ConnectionRequired;
import org.onesocialweb.client.exception.RequestException;
import org.onesocialweb.model.activity.ActivityEntry;
/*
* Copyright 2010 Vodafone Group Services Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.onesocialweb.smack;
public class InboxImp implements Inbox {
private final List<InboxEventHandler> handlers = new ArrayList<InboxEventHandler>();
private final OswServiceImp service;
private List<ActivityEntry> entries = new ArrayList<ActivityEntry>();
public InboxImp(OswServiceImp service) {
this.service = service;
}
@Override
public List<ActivityEntry> getEntries() {
return entries;
}
@Override
public boolean refresh() {
try {
return service.refreshInbox();
} catch (ConnectionRequired e) {
} catch (AuthenticationRequired e) {
| } catch (RequestException e) { |
onesocialweb/osw-lib-java | src/org/onesocialweb/client/OswService.java | // Path: src/org/onesocialweb/client/exception/AuthenticationRequired.java
// @SuppressWarnings("serial")
// public class AuthenticationRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/ConnectionException.java
// @SuppressWarnings("serial")
// public class ConnectionException extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/ConnectionRequired.java
// @SuppressWarnings("serial")
// public class ConnectionRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/RequestException.java
// @SuppressWarnings("serial")
// public class RequestException extends Exception {
//
// public RequestException(String message) {
// super(message);
// }
// }
| import java.util.List;
import java.util.Map;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Mode;
import org.jivesoftware.smack.packet.Presence.Type;
import org.onesocialweb.client.exception.AuthenticationRequired;
import org.onesocialweb.client.exception.ConnectionException;
import org.onesocialweb.client.exception.ConnectionRequired;
import org.onesocialweb.client.exception.RequestException;
import org.onesocialweb.model.activity.ActivityEntry;
import org.onesocialweb.model.relation.Relation;
import org.onesocialweb.model.vcard4.Profile; | /*
* Copyright 2010 Vodafone Group Services Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.onesocialweb.client;
public interface OswService {
/* Connection related commands */
/**
* Sets if the connection is going to use stream compression. Stream compression
* will be requested after TLS was established (if TLS was enabled) and only if the server
* offered stream compression. With stream compression network traffic can be reduced
* up to 90%. By default compression is disabled.
*
* @param compressionEnabled if the connection is going to use stream compression.
*/
public void setCompressionEnabled(boolean compressionEnabled);
/**
* Sets if the reconnection mechanism is allowed to be used. By default
* reconnection is allowed.
*
* @param isAllowed if the reconnection mechanism is allowed to use.
*/
public void setReconnectionAllowed(boolean isAllowed);
/**
* Connects to the specified XMPP server
*
* @param server hostname of the XMPP server to connect to.
* @param port port number in which the XMPP Server is running.
* @param parameters other connection parameters
* @return true if the connection was successful, false otherwise.
* @throws ConnectionException throws a ConnectionException if it doesn't succeed in
* establishing the XMPP Connection
*/ | // Path: src/org/onesocialweb/client/exception/AuthenticationRequired.java
// @SuppressWarnings("serial")
// public class AuthenticationRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/ConnectionException.java
// @SuppressWarnings("serial")
// public class ConnectionException extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/ConnectionRequired.java
// @SuppressWarnings("serial")
// public class ConnectionRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/RequestException.java
// @SuppressWarnings("serial")
// public class RequestException extends Exception {
//
// public RequestException(String message) {
// super(message);
// }
// }
// Path: src/org/onesocialweb/client/OswService.java
import java.util.List;
import java.util.Map;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Mode;
import org.jivesoftware.smack.packet.Presence.Type;
import org.onesocialweb.client.exception.AuthenticationRequired;
import org.onesocialweb.client.exception.ConnectionException;
import org.onesocialweb.client.exception.ConnectionRequired;
import org.onesocialweb.client.exception.RequestException;
import org.onesocialweb.model.activity.ActivityEntry;
import org.onesocialweb.model.relation.Relation;
import org.onesocialweb.model.vcard4.Profile;
/*
* Copyright 2010 Vodafone Group Services Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.onesocialweb.client;
public interface OswService {
/* Connection related commands */
/**
* Sets if the connection is going to use stream compression. Stream compression
* will be requested after TLS was established (if TLS was enabled) and only if the server
* offered stream compression. With stream compression network traffic can be reduced
* up to 90%. By default compression is disabled.
*
* @param compressionEnabled if the connection is going to use stream compression.
*/
public void setCompressionEnabled(boolean compressionEnabled);
/**
* Sets if the reconnection mechanism is allowed to be used. By default
* reconnection is allowed.
*
* @param isAllowed if the reconnection mechanism is allowed to use.
*/
public void setReconnectionAllowed(boolean isAllowed);
/**
* Connects to the specified XMPP server
*
* @param server hostname of the XMPP server to connect to.
* @param port port number in which the XMPP Server is running.
* @param parameters other connection parameters
* @return true if the connection was successful, false otherwise.
* @throws ConnectionException throws a ConnectionException if it doesn't succeed in
* establishing the XMPP Connection
*/ | public boolean connect(String server, Integer port, Map<String, String> parameters) throws ConnectionException; |
onesocialweb/osw-lib-java | src/org/onesocialweb/client/OswService.java | // Path: src/org/onesocialweb/client/exception/AuthenticationRequired.java
// @SuppressWarnings("serial")
// public class AuthenticationRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/ConnectionException.java
// @SuppressWarnings("serial")
// public class ConnectionException extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/ConnectionRequired.java
// @SuppressWarnings("serial")
// public class ConnectionRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/RequestException.java
// @SuppressWarnings("serial")
// public class RequestException extends Exception {
//
// public RequestException(String message) {
// super(message);
// }
// }
| import java.util.List;
import java.util.Map;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Mode;
import org.jivesoftware.smack.packet.Presence.Type;
import org.onesocialweb.client.exception.AuthenticationRequired;
import org.onesocialweb.client.exception.ConnectionException;
import org.onesocialweb.client.exception.ConnectionRequired;
import org.onesocialweb.client.exception.RequestException;
import org.onesocialweb.model.activity.ActivityEntry;
import org.onesocialweb.model.relation.Relation;
import org.onesocialweb.model.vcard4.Profile; | /*
* Copyright 2010 Vodafone Group Services Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.onesocialweb.client;
public interface OswService {
/* Connection related commands */
/**
* Sets if the connection is going to use stream compression. Stream compression
* will be requested after TLS was established (if TLS was enabled) and only if the server
* offered stream compression. With stream compression network traffic can be reduced
* up to 90%. By default compression is disabled.
*
* @param compressionEnabled if the connection is going to use stream compression.
*/
public void setCompressionEnabled(boolean compressionEnabled);
/**
* Sets if the reconnection mechanism is allowed to be used. By default
* reconnection is allowed.
*
* @param isAllowed if the reconnection mechanism is allowed to use.
*/
public void setReconnectionAllowed(boolean isAllowed);
/**
* Connects to the specified XMPP server
*
* @param server hostname of the XMPP server to connect to.
* @param port port number in which the XMPP Server is running.
* @param parameters other connection parameters
* @return true if the connection was successful, false otherwise.
* @throws ConnectionException throws a ConnectionException if it doesn't succeed in
* establishing the XMPP Connection
*/
public boolean connect(String server, Integer port, Map<String, String> parameters) throws ConnectionException;
/**
* Disconnects from the XMPP server
*
* @return true if it succeeds in disconnecting, false otherwise.
* @throws ConnectionRequired will throw an exception if the service was not connected.
*/ | // Path: src/org/onesocialweb/client/exception/AuthenticationRequired.java
// @SuppressWarnings("serial")
// public class AuthenticationRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/ConnectionException.java
// @SuppressWarnings("serial")
// public class ConnectionException extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/ConnectionRequired.java
// @SuppressWarnings("serial")
// public class ConnectionRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/RequestException.java
// @SuppressWarnings("serial")
// public class RequestException extends Exception {
//
// public RequestException(String message) {
// super(message);
// }
// }
// Path: src/org/onesocialweb/client/OswService.java
import java.util.List;
import java.util.Map;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Mode;
import org.jivesoftware.smack.packet.Presence.Type;
import org.onesocialweb.client.exception.AuthenticationRequired;
import org.onesocialweb.client.exception.ConnectionException;
import org.onesocialweb.client.exception.ConnectionRequired;
import org.onesocialweb.client.exception.RequestException;
import org.onesocialweb.model.activity.ActivityEntry;
import org.onesocialweb.model.relation.Relation;
import org.onesocialweb.model.vcard4.Profile;
/*
* Copyright 2010 Vodafone Group Services Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.onesocialweb.client;
public interface OswService {
/* Connection related commands */
/**
* Sets if the connection is going to use stream compression. Stream compression
* will be requested after TLS was established (if TLS was enabled) and only if the server
* offered stream compression. With stream compression network traffic can be reduced
* up to 90%. By default compression is disabled.
*
* @param compressionEnabled if the connection is going to use stream compression.
*/
public void setCompressionEnabled(boolean compressionEnabled);
/**
* Sets if the reconnection mechanism is allowed to be used. By default
* reconnection is allowed.
*
* @param isAllowed if the reconnection mechanism is allowed to use.
*/
public void setReconnectionAllowed(boolean isAllowed);
/**
* Connects to the specified XMPP server
*
* @param server hostname of the XMPP server to connect to.
* @param port port number in which the XMPP Server is running.
* @param parameters other connection parameters
* @return true if the connection was successful, false otherwise.
* @throws ConnectionException throws a ConnectionException if it doesn't succeed in
* establishing the XMPP Connection
*/
public boolean connect(String server, Integer port, Map<String, String> parameters) throws ConnectionException;
/**
* Disconnects from the XMPP server
*
* @return true if it succeeds in disconnecting, false otherwise.
* @throws ConnectionRequired will throw an exception if the service was not connected.
*/ | public boolean disconnect() throws ConnectionRequired; |
onesocialweb/osw-lib-java | src/org/onesocialweb/client/OswService.java | // Path: src/org/onesocialweb/client/exception/AuthenticationRequired.java
// @SuppressWarnings("serial")
// public class AuthenticationRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/ConnectionException.java
// @SuppressWarnings("serial")
// public class ConnectionException extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/ConnectionRequired.java
// @SuppressWarnings("serial")
// public class ConnectionRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/RequestException.java
// @SuppressWarnings("serial")
// public class RequestException extends Exception {
//
// public RequestException(String message) {
// super(message);
// }
// }
| import java.util.List;
import java.util.Map;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Mode;
import org.jivesoftware.smack.packet.Presence.Type;
import org.onesocialweb.client.exception.AuthenticationRequired;
import org.onesocialweb.client.exception.ConnectionException;
import org.onesocialweb.client.exception.ConnectionRequired;
import org.onesocialweb.client.exception.RequestException;
import org.onesocialweb.model.activity.ActivityEntry;
import org.onesocialweb.model.relation.Relation;
import org.onesocialweb.model.vcard4.Profile; | /*
* Copyright 2010 Vodafone Group Services Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.onesocialweb.client;
public interface OswService {
/* Connection related commands */
/**
* Sets if the connection is going to use stream compression. Stream compression
* will be requested after TLS was established (if TLS was enabled) and only if the server
* offered stream compression. With stream compression network traffic can be reduced
* up to 90%. By default compression is disabled.
*
* @param compressionEnabled if the connection is going to use stream compression.
*/
public void setCompressionEnabled(boolean compressionEnabled);
/**
* Sets if the reconnection mechanism is allowed to be used. By default
* reconnection is allowed.
*
* @param isAllowed if the reconnection mechanism is allowed to use.
*/
public void setReconnectionAllowed(boolean isAllowed);
/**
* Connects to the specified XMPP server
*
* @param server hostname of the XMPP server to connect to.
* @param port port number in which the XMPP Server is running.
* @param parameters other connection parameters
* @return true if the connection was successful, false otherwise.
* @throws ConnectionException throws a ConnectionException if it doesn't succeed in
* establishing the XMPP Connection
*/
public boolean connect(String server, Integer port, Map<String, String> parameters) throws ConnectionException;
/**
* Disconnects from the XMPP server
*
* @return true if it succeeds in disconnecting, false otherwise.
* @throws ConnectionRequired will throw an exception if the service was not connected.
*/
public boolean disconnect() throws ConnectionRequired;
/**
* Register a new user at the connected XMPP server (by sending a Registration IQ)
*
* @param username jid of the user to register.
* @param password password for the user at the connected server.
* @param name name of the user to register.
* @param email email address of the user to register.
* @return true if it succeeded in registering the user, i.e. receives
* a reply IQ of type RESULT.
* @throws ConnectionRequired will throw an exception if the service was not connected.
*/
public boolean register(String username, String password, String name, String email) throws ConnectionRequired;
/**
* Authenticates the user at the connected XMPP Server and tries to retrieve its roster and its inbox of Activities.
*
* @param username jid of the user that wants to login.
* @param password user's password in the server.
* @param resource specific jabber resource from which the user will be connected.
* @return true if it succeeded in login the user into the server.
* @throws ConnectionRequired will throw a ConnectionRequired exception if the service was not connected.
* @throws RequestException will throw a RequestException if the XMPP connection fails to login the user.
*/ | // Path: src/org/onesocialweb/client/exception/AuthenticationRequired.java
// @SuppressWarnings("serial")
// public class AuthenticationRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/ConnectionException.java
// @SuppressWarnings("serial")
// public class ConnectionException extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/ConnectionRequired.java
// @SuppressWarnings("serial")
// public class ConnectionRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/RequestException.java
// @SuppressWarnings("serial")
// public class RequestException extends Exception {
//
// public RequestException(String message) {
// super(message);
// }
// }
// Path: src/org/onesocialweb/client/OswService.java
import java.util.List;
import java.util.Map;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Mode;
import org.jivesoftware.smack.packet.Presence.Type;
import org.onesocialweb.client.exception.AuthenticationRequired;
import org.onesocialweb.client.exception.ConnectionException;
import org.onesocialweb.client.exception.ConnectionRequired;
import org.onesocialweb.client.exception.RequestException;
import org.onesocialweb.model.activity.ActivityEntry;
import org.onesocialweb.model.relation.Relation;
import org.onesocialweb.model.vcard4.Profile;
/*
* Copyright 2010 Vodafone Group Services Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.onesocialweb.client;
public interface OswService {
/* Connection related commands */
/**
* Sets if the connection is going to use stream compression. Stream compression
* will be requested after TLS was established (if TLS was enabled) and only if the server
* offered stream compression. With stream compression network traffic can be reduced
* up to 90%. By default compression is disabled.
*
* @param compressionEnabled if the connection is going to use stream compression.
*/
public void setCompressionEnabled(boolean compressionEnabled);
/**
* Sets if the reconnection mechanism is allowed to be used. By default
* reconnection is allowed.
*
* @param isAllowed if the reconnection mechanism is allowed to use.
*/
public void setReconnectionAllowed(boolean isAllowed);
/**
* Connects to the specified XMPP server
*
* @param server hostname of the XMPP server to connect to.
* @param port port number in which the XMPP Server is running.
* @param parameters other connection parameters
* @return true if the connection was successful, false otherwise.
* @throws ConnectionException throws a ConnectionException if it doesn't succeed in
* establishing the XMPP Connection
*/
public boolean connect(String server, Integer port, Map<String, String> parameters) throws ConnectionException;
/**
* Disconnects from the XMPP server
*
* @return true if it succeeds in disconnecting, false otherwise.
* @throws ConnectionRequired will throw an exception if the service was not connected.
*/
public boolean disconnect() throws ConnectionRequired;
/**
* Register a new user at the connected XMPP server (by sending a Registration IQ)
*
* @param username jid of the user to register.
* @param password password for the user at the connected server.
* @param name name of the user to register.
* @param email email address of the user to register.
* @return true if it succeeded in registering the user, i.e. receives
* a reply IQ of type RESULT.
* @throws ConnectionRequired will throw an exception if the service was not connected.
*/
public boolean register(String username, String password, String name, String email) throws ConnectionRequired;
/**
* Authenticates the user at the connected XMPP Server and tries to retrieve its roster and its inbox of Activities.
*
* @param username jid of the user that wants to login.
* @param password user's password in the server.
* @param resource specific jabber resource from which the user will be connected.
* @return true if it succeeded in login the user into the server.
* @throws ConnectionRequired will throw a ConnectionRequired exception if the service was not connected.
* @throws RequestException will throw a RequestException if the XMPP connection fails to login the user.
*/ | public boolean login(String username, String password, String resource) throws ConnectionRequired, RequestException; |
onesocialweb/osw-lib-java | src/org/onesocialweb/client/OswService.java | // Path: src/org/onesocialweb/client/exception/AuthenticationRequired.java
// @SuppressWarnings("serial")
// public class AuthenticationRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/ConnectionException.java
// @SuppressWarnings("serial")
// public class ConnectionException extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/ConnectionRequired.java
// @SuppressWarnings("serial")
// public class ConnectionRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/RequestException.java
// @SuppressWarnings("serial")
// public class RequestException extends Exception {
//
// public RequestException(String message) {
// super(message);
// }
// }
| import java.util.List;
import java.util.Map;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Mode;
import org.jivesoftware.smack.packet.Presence.Type;
import org.onesocialweb.client.exception.AuthenticationRequired;
import org.onesocialweb.client.exception.ConnectionException;
import org.onesocialweb.client.exception.ConnectionRequired;
import org.onesocialweb.client.exception.RequestException;
import org.onesocialweb.model.activity.ActivityEntry;
import org.onesocialweb.model.relation.Relation;
import org.onesocialweb.model.vcard4.Profile; | /*
* Copyright 2010 Vodafone Group Services Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.onesocialweb.client;
public interface OswService {
/* Connection related commands */
/**
* Sets if the connection is going to use stream compression. Stream compression
* will be requested after TLS was established (if TLS was enabled) and only if the server
* offered stream compression. With stream compression network traffic can be reduced
* up to 90%. By default compression is disabled.
*
* @param compressionEnabled if the connection is going to use stream compression.
*/
public void setCompressionEnabled(boolean compressionEnabled);
/**
* Sets if the reconnection mechanism is allowed to be used. By default
* reconnection is allowed.
*
* @param isAllowed if the reconnection mechanism is allowed to use.
*/
public void setReconnectionAllowed(boolean isAllowed);
/**
* Connects to the specified XMPP server
*
* @param server hostname of the XMPP server to connect to.
* @param port port number in which the XMPP Server is running.
* @param parameters other connection parameters
* @return true if the connection was successful, false otherwise.
* @throws ConnectionException throws a ConnectionException if it doesn't succeed in
* establishing the XMPP Connection
*/
public boolean connect(String server, Integer port, Map<String, String> parameters) throws ConnectionException;
/**
* Disconnects from the XMPP server
*
* @return true if it succeeds in disconnecting, false otherwise.
* @throws ConnectionRequired will throw an exception if the service was not connected.
*/
public boolean disconnect() throws ConnectionRequired;
/**
* Register a new user at the connected XMPP server (by sending a Registration IQ)
*
* @param username jid of the user to register.
* @param password password for the user at the connected server.
* @param name name of the user to register.
* @param email email address of the user to register.
* @return true if it succeeded in registering the user, i.e. receives
* a reply IQ of type RESULT.
* @throws ConnectionRequired will throw an exception if the service was not connected.
*/
public boolean register(String username, String password, String name, String email) throws ConnectionRequired;
/**
* Authenticates the user at the connected XMPP Server and tries to retrieve its roster and its inbox of Activities.
*
* @param username jid of the user that wants to login.
* @param password user's password in the server.
* @param resource specific jabber resource from which the user will be connected.
* @return true if it succeeded in login the user into the server.
* @throws ConnectionRequired will throw a ConnectionRequired exception if the service was not connected.
* @throws RequestException will throw a RequestException if the XMPP connection fails to login the user.
*/
public boolean login(String username, String password, String resource) throws ConnectionRequired, RequestException;
/**
* @return true if the XMPP connection is not null (i.e. the connection to XMPP Server has been established)
* and a user has already logged in by using the login method. Returns false otherwise.
*/
boolean isAuthenticated();
/**
* @return true if the connection is not null and is currently connected to an XMPP server.
*/
boolean isConnected();
/**
* @return the jabberId of the user that was authenticated using the login method.
* Returns null if no user was authenticated yet.
*
*/
public String getUser();
/**
* @return the host name of the XMPP Server currently connected to.
* Returns null if currently not connected.
*/
public String getHostname();
/**
* Adds a listener to the connection that will be notified when the state
* of the connection (connected, disconnectedOnError or disconnected) changes.
*
* @param listener
*/
public void addConnectionStateListener(ConnectionStateListener listener);
/**
* Removes the specified connection state listener from the service.
*
* @param listener
*/
public void removeConnectionStateListener(ConnectionStateListener listener);
/* Activity stream related commands */
/**
* Subscribe to the activity stream of another user, who will be added to the roster. ("Follow").
*
* @param userJid jid of the user to subscribe to
* @return true if it succeeds, i.e. receives a reply IQ of type RESULT.
* @throws RequestException throws a RequestException if it receives a reply IQ of type ERROR after
* attempting to send a subscription IQ to the server.
* @throws ConnectionRequired throws a ConnectionRequired exception if not connected to an XMPP Server.
* @throws AuthenticationRequired throws an AuthenticationRequired is no user has been logged in yet.
*/ | // Path: src/org/onesocialweb/client/exception/AuthenticationRequired.java
// @SuppressWarnings("serial")
// public class AuthenticationRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/ConnectionException.java
// @SuppressWarnings("serial")
// public class ConnectionException extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/ConnectionRequired.java
// @SuppressWarnings("serial")
// public class ConnectionRequired extends Exception {
//
// }
//
// Path: src/org/onesocialweb/client/exception/RequestException.java
// @SuppressWarnings("serial")
// public class RequestException extends Exception {
//
// public RequestException(String message) {
// super(message);
// }
// }
// Path: src/org/onesocialweb/client/OswService.java
import java.util.List;
import java.util.Map;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Mode;
import org.jivesoftware.smack.packet.Presence.Type;
import org.onesocialweb.client.exception.AuthenticationRequired;
import org.onesocialweb.client.exception.ConnectionException;
import org.onesocialweb.client.exception.ConnectionRequired;
import org.onesocialweb.client.exception.RequestException;
import org.onesocialweb.model.activity.ActivityEntry;
import org.onesocialweb.model.relation.Relation;
import org.onesocialweb.model.vcard4.Profile;
/*
* Copyright 2010 Vodafone Group Services Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.onesocialweb.client;
public interface OswService {
/* Connection related commands */
/**
* Sets if the connection is going to use stream compression. Stream compression
* will be requested after TLS was established (if TLS was enabled) and only if the server
* offered stream compression. With stream compression network traffic can be reduced
* up to 90%. By default compression is disabled.
*
* @param compressionEnabled if the connection is going to use stream compression.
*/
public void setCompressionEnabled(boolean compressionEnabled);
/**
* Sets if the reconnection mechanism is allowed to be used. By default
* reconnection is allowed.
*
* @param isAllowed if the reconnection mechanism is allowed to use.
*/
public void setReconnectionAllowed(boolean isAllowed);
/**
* Connects to the specified XMPP server
*
* @param server hostname of the XMPP server to connect to.
* @param port port number in which the XMPP Server is running.
* @param parameters other connection parameters
* @return true if the connection was successful, false otherwise.
* @throws ConnectionException throws a ConnectionException if it doesn't succeed in
* establishing the XMPP Connection
*/
public boolean connect(String server, Integer port, Map<String, String> parameters) throws ConnectionException;
/**
* Disconnects from the XMPP server
*
* @return true if it succeeds in disconnecting, false otherwise.
* @throws ConnectionRequired will throw an exception if the service was not connected.
*/
public boolean disconnect() throws ConnectionRequired;
/**
* Register a new user at the connected XMPP server (by sending a Registration IQ)
*
* @param username jid of the user to register.
* @param password password for the user at the connected server.
* @param name name of the user to register.
* @param email email address of the user to register.
* @return true if it succeeded in registering the user, i.e. receives
* a reply IQ of type RESULT.
* @throws ConnectionRequired will throw an exception if the service was not connected.
*/
public boolean register(String username, String password, String name, String email) throws ConnectionRequired;
/**
* Authenticates the user at the connected XMPP Server and tries to retrieve its roster and its inbox of Activities.
*
* @param username jid of the user that wants to login.
* @param password user's password in the server.
* @param resource specific jabber resource from which the user will be connected.
* @return true if it succeeded in login the user into the server.
* @throws ConnectionRequired will throw a ConnectionRequired exception if the service was not connected.
* @throws RequestException will throw a RequestException if the XMPP connection fails to login the user.
*/
public boolean login(String username, String password, String resource) throws ConnectionRequired, RequestException;
/**
* @return true if the XMPP connection is not null (i.e. the connection to XMPP Server has been established)
* and a user has already logged in by using the login method. Returns false otherwise.
*/
boolean isAuthenticated();
/**
* @return true if the connection is not null and is currently connected to an XMPP server.
*/
boolean isConnected();
/**
* @return the jabberId of the user that was authenticated using the login method.
* Returns null if no user was authenticated yet.
*
*/
public String getUser();
/**
* @return the host name of the XMPP Server currently connected to.
* Returns null if currently not connected.
*/
public String getHostname();
/**
* Adds a listener to the connection that will be notified when the state
* of the connection (connected, disconnectedOnError or disconnected) changes.
*
* @param listener
*/
public void addConnectionStateListener(ConnectionStateListener listener);
/**
* Removes the specified connection state listener from the service.
*
* @param listener
*/
public void removeConnectionStateListener(ConnectionStateListener listener);
/* Activity stream related commands */
/**
* Subscribe to the activity stream of another user, who will be added to the roster. ("Follow").
*
* @param userJid jid of the user to subscribe to
* @return true if it succeeds, i.e. receives a reply IQ of type RESULT.
* @throws RequestException throws a RequestException if it receives a reply IQ of type ERROR after
* attempting to send a subscription IQ to the server.
* @throws ConnectionRequired throws a ConnectionRequired exception if not connected to an XMPP Server.
* @throws AuthenticationRequired throws an AuthenticationRequired is no user has been logged in yet.
*/ | public boolean subscribe(String userJid) throws RequestException, ConnectionRequired, AuthenticationRequired; |
Mignet/Inspiration | core/src/com/v5ent/game/core/WorldRenderer.java | // Path: core/src/com/v5ent/game/utils/Constants.java
// public class Constants {
// // Visible game world is 5 meters wide
// // public static final float VIEWPORT_WIDTH = 854f;//20f;//640.0f/32;
// // Visible game world is 5 meters tall
// // public static final float VIEWPORT_HEIGHT = 480f;//15f;//480.0f/32;
// // Visible game world is 5 meters wide
// public static final float VIEWPORT_WIDTH = 640f;//20f;//640.0f/32;
// // Visible game world is 5 meters tall
// public static final float VIEWPORT_HEIGHT = 480f;//15f;//480.0f/32;
//
// }
//
// Path: core/src/com/v5ent/game/utils/DebugMarker.java
// public class DebugMarker {
// private static ShapeRenderer debugRenderer = new ShapeRenderer();
//
// private static final String TAG = DebugMarker.class.getName();
//
// public static void dispose(){
// debugRenderer.dispose();
// }
// public static void drawDebugLine(Vector2 start, Vector2 end, int lineWidth, Color color, Matrix4 projectionMatrix)
// {
// Gdx.gl.glLineWidth(lineWidth);
// debugRenderer.setProjectionMatrix(projectionMatrix);
// debugRenderer.begin(ShapeRenderer.ShapeType.Line);
// debugRenderer.setColor(color);
// debugRenderer.line(start, end);
// debugRenderer.end();
// Gdx.gl.glLineWidth(1);
// }
//
// public static void drawPolygon(Polygon polygon, Matrix4 projectionMatrix)
// {
//
// Gdx.gl.glLineWidth(2);
// debugRenderer.setProjectionMatrix(projectionMatrix);
// debugRenderer.begin(ShapeRenderer.ShapeType.Line);
//
// debugRenderer.setColor(Color.RED);
// float[] vertices = polygon.getVertices();
// for(int i=0; i<vertices.length; i+=2){
// debugRenderer.line(vertices[i], vertices[i+1], vertices[(i+2)%vertices.length], vertices[(i+3)%vertices.length]);
// }
// debugRenderer.end();
// Gdx.gl.glLineWidth(1);
// }
//
// public static void drawDebugLine(Vector2 start, Vector2 end, Matrix4 projectionMatrix)
// {
// Gdx.gl.glLineWidth(2);
// debugRenderer.setProjectionMatrix(projectionMatrix);
// debugRenderer.begin(ShapeRenderer.ShapeType.Line);
// debugRenderer.setColor(Color.WHITE);
// debugRenderer.line(start, end);
// debugRenderer.end();
// Gdx.gl.glLineWidth(1);
// }
//
// public static void drawTrace(List<Vector2> points, Matrix4 projectionMatrix) {
// Gdx.gl.glLineWidth(2);
// debugRenderer.setProjectionMatrix(projectionMatrix);
// debugRenderer.begin(ShapeRenderer.ShapeType.Line);
// debugRenderer.setColor(Color.WHITE);
// for(int i=0;i<points.size()-1;i++){
// debugRenderer.line(points.get(i), points.get(i+1));
// }
// debugRenderer.end();
// Gdx.gl.glLineWidth(1);
// }
//
// public static ShapeRenderer getDebugRenderer() {
// return debugRenderer;
// }
// }
| import com.badlogic.gdx.Application;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.maps.tiled.tiles.AnimatedTiledMapTile;
import com.badlogic.gdx.utils.Disposable;
import com.v5ent.game.utils.Constants;
import com.v5ent.game.utils.DebugMarker;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List; | package com.v5ent.game.core;
public class WorldRenderer implements Disposable {
private static final String TAG = WorldRenderer.class.getName();
// private OrthographicCamera camera;
// private SpriteBatch batch;
private WorldController worldController;
public OrthogonalTiledMapRenderer mapRenderer = null;
public WorldRenderer (WorldController worldController) {
this.worldController = worldController;
init();
}
private void init () {
mapRenderer = new OrthogonalTiledMapRenderer(worldController.mapMgr.getCurrentMap());
mapRenderer.setView(worldController.camera);
Gdx.app.debug(TAG, "UnitScale value is: " + mapRenderer.getUnitScale());
}
public void render (float delta) {
// Sets the clear screen color to: BLACK
Gdx.gl.glClearColor(0x00 / 255.0f, 0x00 / 255.0f, 0x00 / 255.0f, 0xff / 255.0f);
// Clears the screen
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
renderMap();
//HUD
worldController.hudScreen.render(delta);
if(!worldController.points.isEmpty()){ | // Path: core/src/com/v5ent/game/utils/Constants.java
// public class Constants {
// // Visible game world is 5 meters wide
// // public static final float VIEWPORT_WIDTH = 854f;//20f;//640.0f/32;
// // Visible game world is 5 meters tall
// // public static final float VIEWPORT_HEIGHT = 480f;//15f;//480.0f/32;
// // Visible game world is 5 meters wide
// public static final float VIEWPORT_WIDTH = 640f;//20f;//640.0f/32;
// // Visible game world is 5 meters tall
// public static final float VIEWPORT_HEIGHT = 480f;//15f;//480.0f/32;
//
// }
//
// Path: core/src/com/v5ent/game/utils/DebugMarker.java
// public class DebugMarker {
// private static ShapeRenderer debugRenderer = new ShapeRenderer();
//
// private static final String TAG = DebugMarker.class.getName();
//
// public static void dispose(){
// debugRenderer.dispose();
// }
// public static void drawDebugLine(Vector2 start, Vector2 end, int lineWidth, Color color, Matrix4 projectionMatrix)
// {
// Gdx.gl.glLineWidth(lineWidth);
// debugRenderer.setProjectionMatrix(projectionMatrix);
// debugRenderer.begin(ShapeRenderer.ShapeType.Line);
// debugRenderer.setColor(color);
// debugRenderer.line(start, end);
// debugRenderer.end();
// Gdx.gl.glLineWidth(1);
// }
//
// public static void drawPolygon(Polygon polygon, Matrix4 projectionMatrix)
// {
//
// Gdx.gl.glLineWidth(2);
// debugRenderer.setProjectionMatrix(projectionMatrix);
// debugRenderer.begin(ShapeRenderer.ShapeType.Line);
//
// debugRenderer.setColor(Color.RED);
// float[] vertices = polygon.getVertices();
// for(int i=0; i<vertices.length; i+=2){
// debugRenderer.line(vertices[i], vertices[i+1], vertices[(i+2)%vertices.length], vertices[(i+3)%vertices.length]);
// }
// debugRenderer.end();
// Gdx.gl.glLineWidth(1);
// }
//
// public static void drawDebugLine(Vector2 start, Vector2 end, Matrix4 projectionMatrix)
// {
// Gdx.gl.glLineWidth(2);
// debugRenderer.setProjectionMatrix(projectionMatrix);
// debugRenderer.begin(ShapeRenderer.ShapeType.Line);
// debugRenderer.setColor(Color.WHITE);
// debugRenderer.line(start, end);
// debugRenderer.end();
// Gdx.gl.glLineWidth(1);
// }
//
// public static void drawTrace(List<Vector2> points, Matrix4 projectionMatrix) {
// Gdx.gl.glLineWidth(2);
// debugRenderer.setProjectionMatrix(projectionMatrix);
// debugRenderer.begin(ShapeRenderer.ShapeType.Line);
// debugRenderer.setColor(Color.WHITE);
// for(int i=0;i<points.size()-1;i++){
// debugRenderer.line(points.get(i), points.get(i+1));
// }
// debugRenderer.end();
// Gdx.gl.glLineWidth(1);
// }
//
// public static ShapeRenderer getDebugRenderer() {
// return debugRenderer;
// }
// }
// Path: core/src/com/v5ent/game/core/WorldRenderer.java
import com.badlogic.gdx.Application;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.maps.tiled.tiles.AnimatedTiledMapTile;
import com.badlogic.gdx.utils.Disposable;
import com.v5ent.game.utils.Constants;
import com.v5ent.game.utils.DebugMarker;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
package com.v5ent.game.core;
public class WorldRenderer implements Disposable {
private static final String TAG = WorldRenderer.class.getName();
// private OrthographicCamera camera;
// private SpriteBatch batch;
private WorldController worldController;
public OrthogonalTiledMapRenderer mapRenderer = null;
public WorldRenderer (WorldController worldController) {
this.worldController = worldController;
init();
}
private void init () {
mapRenderer = new OrthogonalTiledMapRenderer(worldController.mapMgr.getCurrentMap());
mapRenderer.setView(worldController.camera);
Gdx.app.debug(TAG, "UnitScale value is: " + mapRenderer.getUnitScale());
}
public void render (float delta) {
// Sets the clear screen color to: BLACK
Gdx.gl.glClearColor(0x00 / 255.0f, 0x00 / 255.0f, 0x00 / 255.0f, 0xff / 255.0f);
// Clears the screen
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
renderMap();
//HUD
worldController.hudScreen.render(delta);
if(!worldController.points.isEmpty()){ | DebugMarker.drawTrace(worldController.points, worldController.camera.combined); |
Mignet/Inspiration | core/src/com/v5ent/game/core/WorldRenderer.java | // Path: core/src/com/v5ent/game/utils/Constants.java
// public class Constants {
// // Visible game world is 5 meters wide
// // public static final float VIEWPORT_WIDTH = 854f;//20f;//640.0f/32;
// // Visible game world is 5 meters tall
// // public static final float VIEWPORT_HEIGHT = 480f;//15f;//480.0f/32;
// // Visible game world is 5 meters wide
// public static final float VIEWPORT_WIDTH = 640f;//20f;//640.0f/32;
// // Visible game world is 5 meters tall
// public static final float VIEWPORT_HEIGHT = 480f;//15f;//480.0f/32;
//
// }
//
// Path: core/src/com/v5ent/game/utils/DebugMarker.java
// public class DebugMarker {
// private static ShapeRenderer debugRenderer = new ShapeRenderer();
//
// private static final String TAG = DebugMarker.class.getName();
//
// public static void dispose(){
// debugRenderer.dispose();
// }
// public static void drawDebugLine(Vector2 start, Vector2 end, int lineWidth, Color color, Matrix4 projectionMatrix)
// {
// Gdx.gl.glLineWidth(lineWidth);
// debugRenderer.setProjectionMatrix(projectionMatrix);
// debugRenderer.begin(ShapeRenderer.ShapeType.Line);
// debugRenderer.setColor(color);
// debugRenderer.line(start, end);
// debugRenderer.end();
// Gdx.gl.glLineWidth(1);
// }
//
// public static void drawPolygon(Polygon polygon, Matrix4 projectionMatrix)
// {
//
// Gdx.gl.glLineWidth(2);
// debugRenderer.setProjectionMatrix(projectionMatrix);
// debugRenderer.begin(ShapeRenderer.ShapeType.Line);
//
// debugRenderer.setColor(Color.RED);
// float[] vertices = polygon.getVertices();
// for(int i=0; i<vertices.length; i+=2){
// debugRenderer.line(vertices[i], vertices[i+1], vertices[(i+2)%vertices.length], vertices[(i+3)%vertices.length]);
// }
// debugRenderer.end();
// Gdx.gl.glLineWidth(1);
// }
//
// public static void drawDebugLine(Vector2 start, Vector2 end, Matrix4 projectionMatrix)
// {
// Gdx.gl.glLineWidth(2);
// debugRenderer.setProjectionMatrix(projectionMatrix);
// debugRenderer.begin(ShapeRenderer.ShapeType.Line);
// debugRenderer.setColor(Color.WHITE);
// debugRenderer.line(start, end);
// debugRenderer.end();
// Gdx.gl.glLineWidth(1);
// }
//
// public static void drawTrace(List<Vector2> points, Matrix4 projectionMatrix) {
// Gdx.gl.glLineWidth(2);
// debugRenderer.setProjectionMatrix(projectionMatrix);
// debugRenderer.begin(ShapeRenderer.ShapeType.Line);
// debugRenderer.setColor(Color.WHITE);
// for(int i=0;i<points.size()-1;i++){
// debugRenderer.line(points.get(i), points.get(i+1));
// }
// debugRenderer.end();
// Gdx.gl.glLineWidth(1);
// }
//
// public static ShapeRenderer getDebugRenderer() {
// return debugRenderer;
// }
// }
| import com.badlogic.gdx.Application;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.maps.tiled.tiles.AnimatedTiledMapTile;
import com.badlogic.gdx.utils.Disposable;
import com.v5ent.game.utils.Constants;
import com.v5ent.game.utils.DebugMarker;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List; | }
//show roles order by Y-axis
List<Sprite> temp =new ArrayList<Sprite>();
temp.add(worldController.player);
temp.addAll(worldController.mapMgr.npcs);
temp.addAll(worldController.mapMgr.enemies);
temp.addAll(worldController.mapMgr.traps);
Collections.sort(temp, new Comparator<Sprite>() {
@Override
public int compare(Sprite lhs, Sprite rhs) {
// -1 - less than, 1 - greater than, 0 - equal, all inversed for descending
return lhs.getY() > rhs.getY() ? -1 : (lhs.getY() < rhs.getY() ) ? 1 : 0;
}
});
for (Sprite sprite : temp) {
sprite.draw(mapRenderer.getBatch());
}
//ceil layer
TiledMapTileLayer ceilMapLayer = (TiledMapTileLayer)worldController.mapMgr.getCurrentMap().getLayers().get(MapsManager.CEILING_LAYER);
if( ceilMapLayer != null){
mapRenderer.renderTileLayer(ceilMapLayer);
}
if(worldController.skill!=null)worldController.skill.draw(mapRenderer.getBatch());
//TODO Sky Layer
mapRenderer.getBatch().end();
}
public void resize (int width, int height) { | // Path: core/src/com/v5ent/game/utils/Constants.java
// public class Constants {
// // Visible game world is 5 meters wide
// // public static final float VIEWPORT_WIDTH = 854f;//20f;//640.0f/32;
// // Visible game world is 5 meters tall
// // public static final float VIEWPORT_HEIGHT = 480f;//15f;//480.0f/32;
// // Visible game world is 5 meters wide
// public static final float VIEWPORT_WIDTH = 640f;//20f;//640.0f/32;
// // Visible game world is 5 meters tall
// public static final float VIEWPORT_HEIGHT = 480f;//15f;//480.0f/32;
//
// }
//
// Path: core/src/com/v5ent/game/utils/DebugMarker.java
// public class DebugMarker {
// private static ShapeRenderer debugRenderer = new ShapeRenderer();
//
// private static final String TAG = DebugMarker.class.getName();
//
// public static void dispose(){
// debugRenderer.dispose();
// }
// public static void drawDebugLine(Vector2 start, Vector2 end, int lineWidth, Color color, Matrix4 projectionMatrix)
// {
// Gdx.gl.glLineWidth(lineWidth);
// debugRenderer.setProjectionMatrix(projectionMatrix);
// debugRenderer.begin(ShapeRenderer.ShapeType.Line);
// debugRenderer.setColor(color);
// debugRenderer.line(start, end);
// debugRenderer.end();
// Gdx.gl.glLineWidth(1);
// }
//
// public static void drawPolygon(Polygon polygon, Matrix4 projectionMatrix)
// {
//
// Gdx.gl.glLineWidth(2);
// debugRenderer.setProjectionMatrix(projectionMatrix);
// debugRenderer.begin(ShapeRenderer.ShapeType.Line);
//
// debugRenderer.setColor(Color.RED);
// float[] vertices = polygon.getVertices();
// for(int i=0; i<vertices.length; i+=2){
// debugRenderer.line(vertices[i], vertices[i+1], vertices[(i+2)%vertices.length], vertices[(i+3)%vertices.length]);
// }
// debugRenderer.end();
// Gdx.gl.glLineWidth(1);
// }
//
// public static void drawDebugLine(Vector2 start, Vector2 end, Matrix4 projectionMatrix)
// {
// Gdx.gl.glLineWidth(2);
// debugRenderer.setProjectionMatrix(projectionMatrix);
// debugRenderer.begin(ShapeRenderer.ShapeType.Line);
// debugRenderer.setColor(Color.WHITE);
// debugRenderer.line(start, end);
// debugRenderer.end();
// Gdx.gl.glLineWidth(1);
// }
//
// public static void drawTrace(List<Vector2> points, Matrix4 projectionMatrix) {
// Gdx.gl.glLineWidth(2);
// debugRenderer.setProjectionMatrix(projectionMatrix);
// debugRenderer.begin(ShapeRenderer.ShapeType.Line);
// debugRenderer.setColor(Color.WHITE);
// for(int i=0;i<points.size()-1;i++){
// debugRenderer.line(points.get(i), points.get(i+1));
// }
// debugRenderer.end();
// Gdx.gl.glLineWidth(1);
// }
//
// public static ShapeRenderer getDebugRenderer() {
// return debugRenderer;
// }
// }
// Path: core/src/com/v5ent/game/core/WorldRenderer.java
import com.badlogic.gdx.Application;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.maps.tiled.tiles.AnimatedTiledMapTile;
import com.badlogic.gdx.utils.Disposable;
import com.v5ent.game.utils.Constants;
import com.v5ent.game.utils.DebugMarker;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
}
//show roles order by Y-axis
List<Sprite> temp =new ArrayList<Sprite>();
temp.add(worldController.player);
temp.addAll(worldController.mapMgr.npcs);
temp.addAll(worldController.mapMgr.enemies);
temp.addAll(worldController.mapMgr.traps);
Collections.sort(temp, new Comparator<Sprite>() {
@Override
public int compare(Sprite lhs, Sprite rhs) {
// -1 - less than, 1 - greater than, 0 - equal, all inversed for descending
return lhs.getY() > rhs.getY() ? -1 : (lhs.getY() < rhs.getY() ) ? 1 : 0;
}
});
for (Sprite sprite : temp) {
sprite.draw(mapRenderer.getBatch());
}
//ceil layer
TiledMapTileLayer ceilMapLayer = (TiledMapTileLayer)worldController.mapMgr.getCurrentMap().getLayers().get(MapsManager.CEILING_LAYER);
if( ceilMapLayer != null){
mapRenderer.renderTileLayer(ceilMapLayer);
}
if(worldController.skill!=null)worldController.skill.draw(mapRenderer.getBatch());
//TODO Sky Layer
mapRenderer.getBatch().end();
}
public void resize (int width, int height) { | worldController.camera.viewportWidth = (Constants.VIEWPORT_HEIGHT / height) * width; |
Mignet/Inspiration | html/src/com/v5ent/game/client/HtmlLauncher.java | // Path: core/src/com/v5ent/game/Inspiration.java
// public class Inspiration extends Game {
// public MainGameScreen mainGameScreen = null;
// public GameOverScreen gameOverScreen = null;
//
//
// @Override
// public void create() {
// //资源先加载
// Assets.instance.init(new AssetManager());
// mainGameScreen = new MainGameScreen(this);
// gameOverScreen = new GameOverScreen(this);
// setScreen(mainGameScreen);
// }
//
// @Override
// public void dispose() {
// Assets.instance.dispose();
// mainGameScreen.dispose();
// gameOverScreen.dispose();
// }
// }
| import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.backends.gwt.GwtApplication;
import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration;
import com.v5ent.game.Inspiration; | package com.v5ent.game.client;
public class HtmlLauncher extends GwtApplication {
@Override
public GwtApplicationConfiguration getConfig () {
return new GwtApplicationConfiguration(480, 320);
}
@Override
public ApplicationListener createApplicationListener () { | // Path: core/src/com/v5ent/game/Inspiration.java
// public class Inspiration extends Game {
// public MainGameScreen mainGameScreen = null;
// public GameOverScreen gameOverScreen = null;
//
//
// @Override
// public void create() {
// //资源先加载
// Assets.instance.init(new AssetManager());
// mainGameScreen = new MainGameScreen(this);
// gameOverScreen = new GameOverScreen(this);
// setScreen(mainGameScreen);
// }
//
// @Override
// public void dispose() {
// Assets.instance.dispose();
// mainGameScreen.dispose();
// gameOverScreen.dispose();
// }
// }
// Path: html/src/com/v5ent/game/client/HtmlLauncher.java
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.backends.gwt.GwtApplication;
import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration;
import com.v5ent.game.Inspiration;
package com.v5ent.game.client;
public class HtmlLauncher extends GwtApplication {
@Override
public GwtApplicationConfiguration getConfig () {
return new GwtApplicationConfiguration(480, 320);
}
@Override
public ApplicationListener createApplicationListener () { | return new Inspiration(); |
Mignet/Inspiration | core/src/com/v5ent/game/pfa/MyPathSmoother.java | // Path: core/src/com/badlogic/gdx/ai/pfa/GraphPath.java
// public interface GraphPath<N> extends Iterable<N> {
//
// /** Returns the number of items of this path. */
// public int getCount ();
//
// /** Returns the item of this path at the given index. */
// public N get (int index);
//
// /** Adds an item at the end of this path. */
// public void add (N node);
//
// /** Clears this path. */
// public void clear ();
//
// /** Reverses this path. */
// public void reverse ();
//
// public void swapNodes(int m, int n);
//
// public void truncatePath(int index);
//
// }
| import com.badlogic.gdx.ai.pfa.GraphPath;
import com.badlogic.gdx.ai.pfa.SmoothableGraphPath;
import com.badlogic.gdx.ai.utils.RaycastCollisionDetector; | /*******************************************************************************
* Copyright 2014 See AUTHORS file.
*
* 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.v5ent.game.pfa;
/** A {@code PathSmoother} takes a {@link SmoothableGraphPath} and transforms it by linking directly the nodes that are in line of
* sight. The smoothed path contains at most as many nodes as the original path. Also, the nodes in the smoothed path are unlikely
* to have any connections between them (if they were connected in the graph, the pathfinder would have found the smoothed route
* directly, unless their connections had dramatically large costs).
* <p>
* Some world representations are more prone to rough paths than others. Fore example, tile-based graphs tend to be highly
* erratic. The final appearance also depends on how characters act on the path. If they are using some kind of path following
* steering behavior, then the path will be gently smoothed by the steering. It is worth testing your game before assuming the
* path will need smoothing.
* <p>
* For some games, path smoothing is essential to get the AI looking smart. The path smoothing algorithm is rather simple but
* involves raycast and can be somewhat time-consuming.
* <p>
* The algorithm assumes that there is a clear route between any two adjacent nodes in the given path. Although this algorithm
* produces a smooth path, it doesn't search all possible smoothed paths to find the best one, but the final result is usually
* much more satisfactory than the original path.
*
* @param <MyNode> Type of node
*
* @author davebaol */
public class MyPathSmoother {
MyRaycastCollisionDetector raycastCollisionDetector;
MyRay ray;
/** Creates a {@code PathSmoother} using the given {@link RaycastCollisionDetector}
* @param raycastCollisionDetector the raycast collision detector */
public MyPathSmoother (MyRaycastCollisionDetector raycastCollisionDetector) {
this.raycastCollisionDetector = raycastCollisionDetector;
}
/** Smoothes the given path in place.
* @param outPath the path to smooth
* @return the number of nodes removed from the path. */ | // Path: core/src/com/badlogic/gdx/ai/pfa/GraphPath.java
// public interface GraphPath<N> extends Iterable<N> {
//
// /** Returns the number of items of this path. */
// public int getCount ();
//
// /** Returns the item of this path at the given index. */
// public N get (int index);
//
// /** Adds an item at the end of this path. */
// public void add (N node);
//
// /** Clears this path. */
// public void clear ();
//
// /** Reverses this path. */
// public void reverse ();
//
// public void swapNodes(int m, int n);
//
// public void truncatePath(int index);
//
// }
// Path: core/src/com/v5ent/game/pfa/MyPathSmoother.java
import com.badlogic.gdx.ai.pfa.GraphPath;
import com.badlogic.gdx.ai.pfa.SmoothableGraphPath;
import com.badlogic.gdx.ai.utils.RaycastCollisionDetector;
/*******************************************************************************
* Copyright 2014 See AUTHORS file.
*
* 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.v5ent.game.pfa;
/** A {@code PathSmoother} takes a {@link SmoothableGraphPath} and transforms it by linking directly the nodes that are in line of
* sight. The smoothed path contains at most as many nodes as the original path. Also, the nodes in the smoothed path are unlikely
* to have any connections between them (if they were connected in the graph, the pathfinder would have found the smoothed route
* directly, unless their connections had dramatically large costs).
* <p>
* Some world representations are more prone to rough paths than others. Fore example, tile-based graphs tend to be highly
* erratic. The final appearance also depends on how characters act on the path. If they are using some kind of path following
* steering behavior, then the path will be gently smoothed by the steering. It is worth testing your game before assuming the
* path will need smoothing.
* <p>
* For some games, path smoothing is essential to get the AI looking smart. The path smoothing algorithm is rather simple but
* involves raycast and can be somewhat time-consuming.
* <p>
* The algorithm assumes that there is a clear route between any two adjacent nodes in the given path. Although this algorithm
* produces a smooth path, it doesn't search all possible smoothed paths to find the best one, but the final result is usually
* much more satisfactory than the original path.
*
* @param <MyNode> Type of node
*
* @author davebaol */
public class MyPathSmoother {
MyRaycastCollisionDetector raycastCollisionDetector;
MyRay ray;
/** Creates a {@code PathSmoother} using the given {@link RaycastCollisionDetector}
* @param raycastCollisionDetector the raycast collision detector */
public MyPathSmoother (MyRaycastCollisionDetector raycastCollisionDetector) {
this.raycastCollisionDetector = raycastCollisionDetector;
}
/** Smoothes the given path in place.
* @param outPath the path to smooth
* @return the number of nodes removed from the path. */ | public int smoothPath (GraphPath<MyNode> outPath) { |
Mignet/Inspiration | core/src/com/v5ent/game/utils/Assets.java | // Path: core/src/com/v5ent/game/utils/Resource.java
// public static final String ITEMS_TEXTURE_ATLAS_PATH = "items/items.pack";
//
// Path: core/src/com/v5ent/game/utils/Resource.java
// public static final String STATUSUI_SKIN_PATH = "skins/statusui.json";
//
// Path: core/src/com/v5ent/game/utils/Resource.java
// public static final String STATUSUI_TEXTURE_ATLAS_PATH = "skins/statusui.pack";
| import java.util.HashMap;
import java.util.Map;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.assets.AssetErrorListener;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.MusicLoader;
import com.badlogic.gdx.assets.loaders.SoundLoader;
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.MapProperties;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import static com.v5ent.game.utils.Resource.ITEMS_TEXTURE_ATLAS_PATH;
import static com.v5ent.game.utils.Resource.STATUSUI_SKIN_PATH;
import static com.v5ent.game.utils.Resource.STATUSUI_TEXTURE_ATLAS_PATH; | thunder = loads("skill/thunder/benlei (",").png",35, 450, 450);
//load all hero's pack
for (Map.Entry<String, String> entry : Resource.instance.players.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
assetManager.load(value, Texture.class);
String attackFilePath = Resource.instance.fighters.get(key);
if(attackFilePath!=null){
assetManager.load(attackFilePath, Texture.class);
}
}
for (Map.Entry<String, String> entry : Resource.instance.npcs.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
assetManager.load(value, Texture.class);
}
//TODO:load all map's file
for (Map.Entry<String, String> entry : Resource.instance.maps.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
assetManager.load(value, TiledMap.class);
}
assetManager.load(Resource.MONSTERS0,Texture.class);
assetManager.load(Resource.MONSTERS1,Texture.class);
assetManager.load(Resource.TOUCH,Texture.class);
assetManager.load(Resource.SHADOW,Texture.class);
assetManager.load(Resource.SELECTED,Texture.class);
assetManager.load(Resource.HP_BAR,Texture.class);
assetManager.load(Resource.BAR,Texture.class);
| // Path: core/src/com/v5ent/game/utils/Resource.java
// public static final String ITEMS_TEXTURE_ATLAS_PATH = "items/items.pack";
//
// Path: core/src/com/v5ent/game/utils/Resource.java
// public static final String STATUSUI_SKIN_PATH = "skins/statusui.json";
//
// Path: core/src/com/v5ent/game/utils/Resource.java
// public static final String STATUSUI_TEXTURE_ATLAS_PATH = "skins/statusui.pack";
// Path: core/src/com/v5ent/game/utils/Assets.java
import java.util.HashMap;
import java.util.Map;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.assets.AssetErrorListener;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.MusicLoader;
import com.badlogic.gdx.assets.loaders.SoundLoader;
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.MapProperties;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import static com.v5ent.game.utils.Resource.ITEMS_TEXTURE_ATLAS_PATH;
import static com.v5ent.game.utils.Resource.STATUSUI_SKIN_PATH;
import static com.v5ent.game.utils.Resource.STATUSUI_TEXTURE_ATLAS_PATH;
thunder = loads("skill/thunder/benlei (",").png",35, 450, 450);
//load all hero's pack
for (Map.Entry<String, String> entry : Resource.instance.players.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
assetManager.load(value, Texture.class);
String attackFilePath = Resource.instance.fighters.get(key);
if(attackFilePath!=null){
assetManager.load(attackFilePath, Texture.class);
}
}
for (Map.Entry<String, String> entry : Resource.instance.npcs.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
assetManager.load(value, Texture.class);
}
//TODO:load all map's file
for (Map.Entry<String, String> entry : Resource.instance.maps.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
assetManager.load(value, TiledMap.class);
}
assetManager.load(Resource.MONSTERS0,Texture.class);
assetManager.load(Resource.MONSTERS1,Texture.class);
assetManager.load(Resource.TOUCH,Texture.class);
assetManager.load(Resource.SHADOW,Texture.class);
assetManager.load(Resource.SELECTED,Texture.class);
assetManager.load(Resource.HP_BAR,Texture.class);
assetManager.load(Resource.BAR,Texture.class);
| assetManager.load(Resource.STATUSUI_TEXTURE_ATLAS_PATH,TextureAtlas.class); |
Mignet/Inspiration | core/src/com/v5ent/game/utils/Assets.java | // Path: core/src/com/v5ent/game/utils/Resource.java
// public static final String ITEMS_TEXTURE_ATLAS_PATH = "items/items.pack";
//
// Path: core/src/com/v5ent/game/utils/Resource.java
// public static final String STATUSUI_SKIN_PATH = "skins/statusui.json";
//
// Path: core/src/com/v5ent/game/utils/Resource.java
// public static final String STATUSUI_TEXTURE_ATLAS_PATH = "skins/statusui.pack";
| import java.util.HashMap;
import java.util.Map;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.assets.AssetErrorListener;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.MusicLoader;
import com.badlogic.gdx.assets.loaders.SoundLoader;
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.MapProperties;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import static com.v5ent.game.utils.Resource.ITEMS_TEXTURE_ATLAS_PATH;
import static com.v5ent.game.utils.Resource.STATUSUI_SKIN_PATH;
import static com.v5ent.game.utils.Resource.STATUSUI_TEXTURE_ATLAS_PATH; | //load all hero's pack
for (Map.Entry<String, String> entry : Resource.instance.players.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
assetManager.load(value, Texture.class);
String attackFilePath = Resource.instance.fighters.get(key);
if(attackFilePath!=null){
assetManager.load(attackFilePath, Texture.class);
}
}
for (Map.Entry<String, String> entry : Resource.instance.npcs.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
assetManager.load(value, Texture.class);
}
//TODO:load all map's file
for (Map.Entry<String, String> entry : Resource.instance.maps.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
assetManager.load(value, TiledMap.class);
}
assetManager.load(Resource.MONSTERS0,Texture.class);
assetManager.load(Resource.MONSTERS1,Texture.class);
assetManager.load(Resource.TOUCH,Texture.class);
assetManager.load(Resource.SHADOW,Texture.class);
assetManager.load(Resource.SELECTED,Texture.class);
assetManager.load(Resource.HP_BAR,Texture.class);
assetManager.load(Resource.BAR,Texture.class);
assetManager.load(Resource.STATUSUI_TEXTURE_ATLAS_PATH,TextureAtlas.class); | // Path: core/src/com/v5ent/game/utils/Resource.java
// public static final String ITEMS_TEXTURE_ATLAS_PATH = "items/items.pack";
//
// Path: core/src/com/v5ent/game/utils/Resource.java
// public static final String STATUSUI_SKIN_PATH = "skins/statusui.json";
//
// Path: core/src/com/v5ent/game/utils/Resource.java
// public static final String STATUSUI_TEXTURE_ATLAS_PATH = "skins/statusui.pack";
// Path: core/src/com/v5ent/game/utils/Assets.java
import java.util.HashMap;
import java.util.Map;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.assets.AssetErrorListener;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.MusicLoader;
import com.badlogic.gdx.assets.loaders.SoundLoader;
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.MapProperties;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import static com.v5ent.game.utils.Resource.ITEMS_TEXTURE_ATLAS_PATH;
import static com.v5ent.game.utils.Resource.STATUSUI_SKIN_PATH;
import static com.v5ent.game.utils.Resource.STATUSUI_TEXTURE_ATLAS_PATH;
//load all hero's pack
for (Map.Entry<String, String> entry : Resource.instance.players.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
assetManager.load(value, Texture.class);
String attackFilePath = Resource.instance.fighters.get(key);
if(attackFilePath!=null){
assetManager.load(attackFilePath, Texture.class);
}
}
for (Map.Entry<String, String> entry : Resource.instance.npcs.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
assetManager.load(value, Texture.class);
}
//TODO:load all map's file
for (Map.Entry<String, String> entry : Resource.instance.maps.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
assetManager.load(value, TiledMap.class);
}
assetManager.load(Resource.MONSTERS0,Texture.class);
assetManager.load(Resource.MONSTERS1,Texture.class);
assetManager.load(Resource.TOUCH,Texture.class);
assetManager.load(Resource.SHADOW,Texture.class);
assetManager.load(Resource.SELECTED,Texture.class);
assetManager.load(Resource.HP_BAR,Texture.class);
assetManager.load(Resource.BAR,Texture.class);
assetManager.load(Resource.STATUSUI_TEXTURE_ATLAS_PATH,TextureAtlas.class); | assetManager.load(Resource.ITEMS_TEXTURE_ATLAS_PATH,TextureAtlas.class); |
Mignet/Inspiration | core/src/com/v5ent/game/utils/Assets.java | // Path: core/src/com/v5ent/game/utils/Resource.java
// public static final String ITEMS_TEXTURE_ATLAS_PATH = "items/items.pack";
//
// Path: core/src/com/v5ent/game/utils/Resource.java
// public static final String STATUSUI_SKIN_PATH = "skins/statusui.json";
//
// Path: core/src/com/v5ent/game/utils/Resource.java
// public static final String STATUSUI_TEXTURE_ATLAS_PATH = "skins/statusui.pack";
| import java.util.HashMap;
import java.util.Map;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.assets.AssetErrorListener;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.MusicLoader;
import com.badlogic.gdx.assets.loaders.SoundLoader;
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.MapProperties;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import static com.v5ent.game.utils.Resource.ITEMS_TEXTURE_ATLAS_PATH;
import static com.v5ent.game.utils.Resource.STATUSUI_SKIN_PATH;
import static com.v5ent.game.utils.Resource.STATUSUI_TEXTURE_ATLAS_PATH; | Texture atlas = assetManager.get(value);
String attackFilePath = Resource.instance.fighters.get(key);
Texture attackAtlas = null;
if(attackFilePath!=null){
attackAtlas = assetManager.get(attackFilePath);
}
// create game resource objects
assetRoles.put(key,new AssetRole(atlas,attackAtlas));
}
for (Map.Entry<String, String> entry : Resource.instance.npcs.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
Texture atlas = assetManager.get(value);
// create game resource objects
assetRoles.put(key,new AssetRole(atlas,null));
}
for (Map.Entry<String, String> entry : Resource.instance.maps.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
TiledMap map = assetManager.get(value);
// create game resource objects
assetTiledMaps.put(key,new AssetTiledMap(map));
}
touch = new AssetTouch(assetManager.get(Resource.TOUCH,Texture.class));
shadow = assetManager.get(Resource.SHADOW,Texture.class);
selected = assetManager.get(Resource.SELECTED,Texture.class);
hpBar = assetManager.get(Resource.HP_BAR,Texture.class);
bar = assetManager.get(Resource.BAR,Texture.class);
STATUSUI_TEXTUREATLAS = assetManager.get(STATUSUI_TEXTURE_ATLAS_PATH,TextureAtlas.class);
ITEMS_TEXTUREATLAS = assetManager.get(ITEMS_TEXTURE_ATLAS_PATH,TextureAtlas.class); | // Path: core/src/com/v5ent/game/utils/Resource.java
// public static final String ITEMS_TEXTURE_ATLAS_PATH = "items/items.pack";
//
// Path: core/src/com/v5ent/game/utils/Resource.java
// public static final String STATUSUI_SKIN_PATH = "skins/statusui.json";
//
// Path: core/src/com/v5ent/game/utils/Resource.java
// public static final String STATUSUI_TEXTURE_ATLAS_PATH = "skins/statusui.pack";
// Path: core/src/com/v5ent/game/utils/Assets.java
import java.util.HashMap;
import java.util.Map;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.assets.AssetErrorListener;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.assets.loaders.MusicLoader;
import com.badlogic.gdx.assets.loaders.SoundLoader;
import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.MapProperties;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import static com.v5ent.game.utils.Resource.ITEMS_TEXTURE_ATLAS_PATH;
import static com.v5ent.game.utils.Resource.STATUSUI_SKIN_PATH;
import static com.v5ent.game.utils.Resource.STATUSUI_TEXTURE_ATLAS_PATH;
Texture atlas = assetManager.get(value);
String attackFilePath = Resource.instance.fighters.get(key);
Texture attackAtlas = null;
if(attackFilePath!=null){
attackAtlas = assetManager.get(attackFilePath);
}
// create game resource objects
assetRoles.put(key,new AssetRole(atlas,attackAtlas));
}
for (Map.Entry<String, String> entry : Resource.instance.npcs.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
Texture atlas = assetManager.get(value);
// create game resource objects
assetRoles.put(key,new AssetRole(atlas,null));
}
for (Map.Entry<String, String> entry : Resource.instance.maps.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
TiledMap map = assetManager.get(value);
// create game resource objects
assetTiledMaps.put(key,new AssetTiledMap(map));
}
touch = new AssetTouch(assetManager.get(Resource.TOUCH,Texture.class));
shadow = assetManager.get(Resource.SHADOW,Texture.class);
selected = assetManager.get(Resource.SELECTED,Texture.class);
hpBar = assetManager.get(Resource.HP_BAR,Texture.class);
bar = assetManager.get(Resource.BAR,Texture.class);
STATUSUI_TEXTUREATLAS = assetManager.get(STATUSUI_TEXTURE_ATLAS_PATH,TextureAtlas.class);
ITEMS_TEXTUREATLAS = assetManager.get(ITEMS_TEXTURE_ATLAS_PATH,TextureAtlas.class); | STATUSUI_SKIN = new Skin(Gdx.files.internal(Resource.STATUSUI_SKIN_PATH), STATUSUI_TEXTUREATLAS); |
Mignet/Inspiration | ios/src/com/v5ent/game/IOSLauncher.java | // Path: core/src/com/v5ent/game/Inspiration.java
// public class Inspiration extends Game {
// public MainGameScreen mainGameScreen = null;
// public GameOverScreen gameOverScreen = null;
//
//
// @Override
// public void create() {
// //资源先加载
// Assets.instance.init(new AssetManager());
// mainGameScreen = new MainGameScreen(this);
// gameOverScreen = new GameOverScreen(this);
// setScreen(mainGameScreen);
// }
//
// @Override
// public void dispose() {
// Assets.instance.dispose();
// mainGameScreen.dispose();
// gameOverScreen.dispose();
// }
// }
| import org.robovm.apple.foundation.NSAutoreleasePool;
import org.robovm.apple.uikit.UIApplication;
import com.badlogic.gdx.backends.iosrobovm.IOSApplication;
import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration;
import com.v5ent.game.Inspiration; | package com.v5ent.game;
public class IOSLauncher extends IOSApplication.Delegate {
@Override
protected IOSApplication createApplication() {
IOSApplicationConfiguration config = new IOSApplicationConfiguration(); | // Path: core/src/com/v5ent/game/Inspiration.java
// public class Inspiration extends Game {
// public MainGameScreen mainGameScreen = null;
// public GameOverScreen gameOverScreen = null;
//
//
// @Override
// public void create() {
// //资源先加载
// Assets.instance.init(new AssetManager());
// mainGameScreen = new MainGameScreen(this);
// gameOverScreen = new GameOverScreen(this);
// setScreen(mainGameScreen);
// }
//
// @Override
// public void dispose() {
// Assets.instance.dispose();
// mainGameScreen.dispose();
// gameOverScreen.dispose();
// }
// }
// Path: ios/src/com/v5ent/game/IOSLauncher.java
import org.robovm.apple.foundation.NSAutoreleasePool;
import org.robovm.apple.uikit.UIApplication;
import com.badlogic.gdx.backends.iosrobovm.IOSApplication;
import com.badlogic.gdx.backends.iosrobovm.IOSApplicationConfiguration;
import com.v5ent.game.Inspiration;
package com.v5ent.game;
public class IOSLauncher extends IOSApplication.Delegate {
@Override
protected IOSApplication createApplication() {
IOSApplicationConfiguration config = new IOSApplicationConfiguration(); | return new IOSApplication(new Inspiration(), config); |
Mignet/Inspiration | desktop/src/com/v5ent/game/desktop/DebugDesktopLauncher.java | // Path: core/src/com/v5ent/game/Inspiration.java
// public class Inspiration extends Game {
// public MainGameScreen mainGameScreen = null;
// public GameOverScreen gameOverScreen = null;
//
//
// @Override
// public void create() {
// //资源先加载
// Assets.instance.init(new AssetManager());
// mainGameScreen = new MainGameScreen(this);
// gameOverScreen = new GameOverScreen(this);
// setScreen(mainGameScreen);
// }
//
// @Override
// public void dispose() {
// Assets.instance.dispose();
// mainGameScreen.dispose();
// gameOverScreen.dispose();
// }
// }
| import com.badlogic.gdx.Application;
import com.badlogic.gdx.Files;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.v5ent.game.Inspiration; | package com.v5ent.game.desktop;
public class DebugDesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration(); | // Path: core/src/com/v5ent/game/Inspiration.java
// public class Inspiration extends Game {
// public MainGameScreen mainGameScreen = null;
// public GameOverScreen gameOverScreen = null;
//
//
// @Override
// public void create() {
// //资源先加载
// Assets.instance.init(new AssetManager());
// mainGameScreen = new MainGameScreen(this);
// gameOverScreen = new GameOverScreen(this);
// setScreen(mainGameScreen);
// }
//
// @Override
// public void dispose() {
// Assets.instance.dispose();
// mainGameScreen.dispose();
// gameOverScreen.dispose();
// }
// }
// Path: desktop/src/com/v5ent/game/desktop/DebugDesktopLauncher.java
import com.badlogic.gdx.Application;
import com.badlogic.gdx.Files;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.v5ent.game.Inspiration;
package com.v5ent.game.desktop;
public class DebugDesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration(); | cfg.title = "Inspiration"; |
Mignet/Inspiration | core/src/com/v5ent/game/battle/Monsters.java | // Path: core/src/com/v5ent/game/entities/Monster.java
// public class Monster extends Role {
// private static final String TAG = Monster.class.getSimpleName();
//
// public Monster(String entityId,int x,int y) {
// super(entityId);
// this.setCurrentDir(Direction.RIGHT);
// this.idleRightAnimation =loadAnimation(x,y);
// currentFrame =idleRightAnimation.getKeyFrame(0);
// // Define sprite size to be 1m x 1m in game world
// this.setSize(currentFrame.getRegionWidth(), currentFrame.getRegionHeight());
// // Set origin to sprite's center
// this.setOrigin(this.getWidth() / 2.0f, 0);
// //inventory
// }
// //Specific to two frame animations where each frame is stored in a separate texture
// protected Animation loadAnimation(int x,int y){
//
// TextureRegion[][] texture1Frames = TextureRegion.split(Assets.instance.MONSTERS0, 16, 16);
// TextureRegion[][] texture2Frames = TextureRegion.split(Assets.instance.MONSTERS1, 16, 16);
//
// Array<TextureRegion> animationKeyFrames = new Array<TextureRegion>(2);
// TextureRegion t1 = texture1Frames[x][y];
// t1.flip(true,false);
// TextureRegion t2 = texture2Frames[x][y];
// t2.flip(true,false);
// animationKeyFrames.add(t1);
// animationKeyFrames.add(t2);
//
// return new Animation(0.5f, animationKeyFrames, Animation.PlayMode.LOOP);
// }
//
// private int xpReward = 100;
// private int gpReward = 100;
//
// public int getXpReward() {
// return xpReward;
// }
//
// public void setXpReward(int xpReward) {
// this.xpReward = xpReward;
// }
//
// public int getGpReward() {
// return gpReward;
// }
//
// public void setGpReward(int gpReward) {
// this.gpReward = gpReward;
// }
//
// }
| import com.v5ent.game.entities.Monster;
import java.util.Hashtable; | package com.v5ent.game.battle;
/**
* Created by Administrator on 2016/12/11.
*/
public class Monsters {
static int hp =15;
static int ap =40;
static int dp =5;
static int xp =5;
static int gp =5; | // Path: core/src/com/v5ent/game/entities/Monster.java
// public class Monster extends Role {
// private static final String TAG = Monster.class.getSimpleName();
//
// public Monster(String entityId,int x,int y) {
// super(entityId);
// this.setCurrentDir(Direction.RIGHT);
// this.idleRightAnimation =loadAnimation(x,y);
// currentFrame =idleRightAnimation.getKeyFrame(0);
// // Define sprite size to be 1m x 1m in game world
// this.setSize(currentFrame.getRegionWidth(), currentFrame.getRegionHeight());
// // Set origin to sprite's center
// this.setOrigin(this.getWidth() / 2.0f, 0);
// //inventory
// }
// //Specific to two frame animations where each frame is stored in a separate texture
// protected Animation loadAnimation(int x,int y){
//
// TextureRegion[][] texture1Frames = TextureRegion.split(Assets.instance.MONSTERS0, 16, 16);
// TextureRegion[][] texture2Frames = TextureRegion.split(Assets.instance.MONSTERS1, 16, 16);
//
// Array<TextureRegion> animationKeyFrames = new Array<TextureRegion>(2);
// TextureRegion t1 = texture1Frames[x][y];
// t1.flip(true,false);
// TextureRegion t2 = texture2Frames[x][y];
// t2.flip(true,false);
// animationKeyFrames.add(t1);
// animationKeyFrames.add(t2);
//
// return new Animation(0.5f, animationKeyFrames, Animation.PlayMode.LOOP);
// }
//
// private int xpReward = 100;
// private int gpReward = 100;
//
// public int getXpReward() {
// return xpReward;
// }
//
// public void setXpReward(int xpReward) {
// this.xpReward = xpReward;
// }
//
// public int getGpReward() {
// return gpReward;
// }
//
// public void setGpReward(int gpReward) {
// this.gpReward = gpReward;
// }
//
// }
// Path: core/src/com/v5ent/game/battle/Monsters.java
import com.v5ent.game.entities.Monster;
import java.util.Hashtable;
package com.v5ent.game.battle;
/**
* Created by Administrator on 2016/12/11.
*/
public class Monsters {
static int hp =15;
static int ap =40;
static int dp =5;
static int xp =5;
static int gp =5; | public static Monster initData(Monster monster){ |
Mignet/Inspiration | core/src/com/v5ent/game/battle/MonsterFactory.java | // Path: core/src/com/v5ent/game/entities/Monster.java
// public class Monster extends Role {
// private static final String TAG = Monster.class.getSimpleName();
//
// public Monster(String entityId,int x,int y) {
// super(entityId);
// this.setCurrentDir(Direction.RIGHT);
// this.idleRightAnimation =loadAnimation(x,y);
// currentFrame =idleRightAnimation.getKeyFrame(0);
// // Define sprite size to be 1m x 1m in game world
// this.setSize(currentFrame.getRegionWidth(), currentFrame.getRegionHeight());
// // Set origin to sprite's center
// this.setOrigin(this.getWidth() / 2.0f, 0);
// //inventory
// }
// //Specific to two frame animations where each frame is stored in a separate texture
// protected Animation loadAnimation(int x,int y){
//
// TextureRegion[][] texture1Frames = TextureRegion.split(Assets.instance.MONSTERS0, 16, 16);
// TextureRegion[][] texture2Frames = TextureRegion.split(Assets.instance.MONSTERS1, 16, 16);
//
// Array<TextureRegion> animationKeyFrames = new Array<TextureRegion>(2);
// TextureRegion t1 = texture1Frames[x][y];
// t1.flip(true,false);
// TextureRegion t2 = texture2Frames[x][y];
// t2.flip(true,false);
// animationKeyFrames.add(t1);
// animationKeyFrames.add(t2);
//
// return new Animation(0.5f, animationKeyFrames, Animation.PlayMode.LOOP);
// }
//
// private int xpReward = 100;
// private int gpReward = 100;
//
// public int getXpReward() {
// return xpReward;
// }
//
// public void setXpReward(int xpReward) {
// this.xpReward = xpReward;
// }
//
// public int getGpReward() {
// return gpReward;
// }
//
// public void setGpReward(int gpReward) {
// this.gpReward = gpReward;
// }
//
// }
| import java.util.Hashtable;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Json;
import com.v5ent.game.entities.Monster; | package com.v5ent.game.battle;
public class MonsterFactory {
private static Json json = new Json();
public static enum MonsterType{
MONSTER001,MONSTER002,MONSTER003,MONSTER004,MONSTER005,
MONSTER006,MONSTER007,MONSTER008,MONSTER009,MONSTER010,
MONSTER011,MONSTER012,MONSTER013,MONSTER014,MONSTER015,
MONSTER016,MONSTER017,MONSTER018,MONSTER019,MONSTER020,
MONSTER021,MONSTER022,MONSTER023,MONSTER024,MONSTER025,
MONSTER026,MONSTER027,MONSTER028,MONSTER029,MONSTER030,
MONSTER031,MONSTER032,MONSTER033,MONSTER034,MONSTER035,
MONSTER036,MONSTER037,MONSTER038,MONSTER039,MONSTER040,
MONSTER041, MONSTER042,
NONE
}
private static MonsterFactory instance = null; | // Path: core/src/com/v5ent/game/entities/Monster.java
// public class Monster extends Role {
// private static final String TAG = Monster.class.getSimpleName();
//
// public Monster(String entityId,int x,int y) {
// super(entityId);
// this.setCurrentDir(Direction.RIGHT);
// this.idleRightAnimation =loadAnimation(x,y);
// currentFrame =idleRightAnimation.getKeyFrame(0);
// // Define sprite size to be 1m x 1m in game world
// this.setSize(currentFrame.getRegionWidth(), currentFrame.getRegionHeight());
// // Set origin to sprite's center
// this.setOrigin(this.getWidth() / 2.0f, 0);
// //inventory
// }
// //Specific to two frame animations where each frame is stored in a separate texture
// protected Animation loadAnimation(int x,int y){
//
// TextureRegion[][] texture1Frames = TextureRegion.split(Assets.instance.MONSTERS0, 16, 16);
// TextureRegion[][] texture2Frames = TextureRegion.split(Assets.instance.MONSTERS1, 16, 16);
//
// Array<TextureRegion> animationKeyFrames = new Array<TextureRegion>(2);
// TextureRegion t1 = texture1Frames[x][y];
// t1.flip(true,false);
// TextureRegion t2 = texture2Frames[x][y];
// t2.flip(true,false);
// animationKeyFrames.add(t1);
// animationKeyFrames.add(t2);
//
// return new Animation(0.5f, animationKeyFrames, Animation.PlayMode.LOOP);
// }
//
// private int xpReward = 100;
// private int gpReward = 100;
//
// public int getXpReward() {
// return xpReward;
// }
//
// public void setXpReward(int xpReward) {
// this.xpReward = xpReward;
// }
//
// public int getGpReward() {
// return gpReward;
// }
//
// public void setGpReward(int gpReward) {
// this.gpReward = gpReward;
// }
//
// }
// Path: core/src/com/v5ent/game/battle/MonsterFactory.java
import java.util.Hashtable;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Json;
import com.v5ent.game.entities.Monster;
package com.v5ent.game.battle;
public class MonsterFactory {
private static Json json = new Json();
public static enum MonsterType{
MONSTER001,MONSTER002,MONSTER003,MONSTER004,MONSTER005,
MONSTER006,MONSTER007,MONSTER008,MONSTER009,MONSTER010,
MONSTER011,MONSTER012,MONSTER013,MONSTER014,MONSTER015,
MONSTER016,MONSTER017,MONSTER018,MONSTER019,MONSTER020,
MONSTER021,MONSTER022,MONSTER023,MONSTER024,MONSTER025,
MONSTER026,MONSTER027,MONSTER028,MONSTER029,MONSTER030,
MONSTER031,MONSTER032,MONSTER033,MONSTER034,MONSTER035,
MONSTER036,MONSTER037,MONSTER038,MONSTER039,MONSTER040,
MONSTER041, MONSTER042,
NONE
}
private static MonsterFactory instance = null; | private Hashtable<String, Monster> entities; |
Mignet/Inspiration | desktop/src/com/v5ent/game/desktop/DesktopLauncher.java | // Path: core/src/com/v5ent/game/Inspiration.java
// public class Inspiration extends Game {
// public MainGameScreen mainGameScreen = null;
// public GameOverScreen gameOverScreen = null;
//
//
// @Override
// public void create() {
// //资源先加载
// Assets.instance.init(new AssetManager());
// mainGameScreen = new MainGameScreen(this);
// gameOverScreen = new GameOverScreen(this);
// setScreen(mainGameScreen);
// }
//
// @Override
// public void dispose() {
// Assets.instance.dispose();
// mainGameScreen.dispose();
// gameOverScreen.dispose();
// }
// }
| import com.badlogic.gdx.Application;
import com.badlogic.gdx.Files;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.v5ent.game.Inspiration; | package com.v5ent.game.desktop;
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration(); | // Path: core/src/com/v5ent/game/Inspiration.java
// public class Inspiration extends Game {
// public MainGameScreen mainGameScreen = null;
// public GameOverScreen gameOverScreen = null;
//
//
// @Override
// public void create() {
// //资源先加载
// Assets.instance.init(new AssetManager());
// mainGameScreen = new MainGameScreen(this);
// gameOverScreen = new GameOverScreen(this);
// setScreen(mainGameScreen);
// }
//
// @Override
// public void dispose() {
// Assets.instance.dispose();
// mainGameScreen.dispose();
// gameOverScreen.dispose();
// }
// }
// Path: desktop/src/com/v5ent/game/desktop/DesktopLauncher.java
import com.badlogic.gdx.Application;
import com.badlogic.gdx.Files;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.v5ent.game.Inspiration;
package com.v5ent.game.desktop;
public class DesktopLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration(); | cfg.title = "Inspiration"; |
Mignet/Inspiration | android/src/com/v5ent/game/AndroidLauncher.java | // Path: core/src/com/v5ent/game/Inspiration.java
// public class Inspiration extends Game {
// public MainGameScreen mainGameScreen = null;
// public GameOverScreen gameOverScreen = null;
//
//
// @Override
// public void create() {
// //资源先加载
// Assets.instance.init(new AssetManager());
// mainGameScreen = new MainGameScreen(this);
// gameOverScreen = new GameOverScreen(this);
// setScreen(mainGameScreen);
// }
//
// @Override
// public void dispose() {
// Assets.instance.dispose();
// mainGameScreen.dispose();
// gameOverScreen.dispose();
// }
// }
| import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.v5ent.game.Inspiration; | package com.v5ent.game;
public class AndroidLauncher extends AndroidApplication {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); | // Path: core/src/com/v5ent/game/Inspiration.java
// public class Inspiration extends Game {
// public MainGameScreen mainGameScreen = null;
// public GameOverScreen gameOverScreen = null;
//
//
// @Override
// public void create() {
// //资源先加载
// Assets.instance.init(new AssetManager());
// mainGameScreen = new MainGameScreen(this);
// gameOverScreen = new GameOverScreen(this);
// setScreen(mainGameScreen);
// }
//
// @Override
// public void dispose() {
// Assets.instance.dispose();
// mainGameScreen.dispose();
// gameOverScreen.dispose();
// }
// }
// Path: android/src/com/v5ent/game/AndroidLauncher.java
import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.v5ent.game.Inspiration;
package com.v5ent.game;
public class AndroidLauncher extends AndroidApplication {
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); | initialize(new Inspiration(), config); |
wildfly-extras/wildfly-camel-examples | camel-jpa/src/main/java/org/wildfly/camel/examples/jpa/service/OrderService.java | // Path: camel-jpa-spring/src/main/java/org/wildfly/camel/examples/jpa/model/Order.java
// @Entity(name = "orders")
// @NamedQuery(name = "pendingOrders", query = "SELECT o FROM orders o WHERE o.status = 'PENDING'")
// public class Order {
//
// @Id
// @GeneratedValue
// private int id;
// private String item;
// private int amount;
// private String description;
// private String status = "PENDING";
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getItem() {
// return item;
// }
//
// public void setItem(String item) {
// this.item = item;
// }
//
// public int getAmount() {
// return amount;
// }
//
// public void setAmount(int amount) {
// this.amount = amount;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getStatus() {
// return status;
// }
//
// public void setStatus(String status) {
// this.status = status;
// }
//
// }
| import javax.inject.Named;
import org.wildfly.camel.examples.jpa.model.Order;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger; | /*
* #%L
* Wildfly Camel :: Example :: Camel JPA
* %%
* Copyright (C) 2013 - 2014 RedHat
* %%
* 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.
* #L%
*/
package org.wildfly.camel.examples.jpa.service;
@Named
public class OrderService {
private final AtomicInteger counter = new AtomicInteger();
private final Random amount = new Random();
| // Path: camel-jpa-spring/src/main/java/org/wildfly/camel/examples/jpa/model/Order.java
// @Entity(name = "orders")
// @NamedQuery(name = "pendingOrders", query = "SELECT o FROM orders o WHERE o.status = 'PENDING'")
// public class Order {
//
// @Id
// @GeneratedValue
// private int id;
// private String item;
// private int amount;
// private String description;
// private String status = "PENDING";
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getItem() {
// return item;
// }
//
// public void setItem(String item) {
// this.item = item;
// }
//
// public int getAmount() {
// return amount;
// }
//
// public void setAmount(int amount) {
// this.amount = amount;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getStatus() {
// return status;
// }
//
// public void setStatus(String status) {
// this.status = status;
// }
//
// }
// Path: camel-jpa/src/main/java/org/wildfly/camel/examples/jpa/service/OrderService.java
import javax.inject.Named;
import org.wildfly.camel.examples.jpa.model.Order;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
/*
* #%L
* Wildfly Camel :: Example :: Camel JPA
* %%
* Copyright (C) 2013 - 2014 RedHat
* %%
* 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.
* #L%
*/
package org.wildfly.camel.examples.jpa.service;
@Named
public class OrderService {
private final AtomicInteger counter = new AtomicInteger();
private final Random amount = new Random();
| public Order generateOrder() { |
wildfly-extras/wildfly-camel-examples | itests/src/main/java/org/wildfly/camel/examples/test/jpa/AbstractJPAExampleTest.java | // Path: itests/src/main/java/org/wildfly/camel/examples/test/common/FileConsumerTestSupport.java
// public abstract class FileConsumerTestSupport {
//
// @Test
// public void testFileProcessed() throws Exception {
// boolean logMessagePresent = ServerLogReader.awaitLogMessage(getExpectedLogMessage(), 10000);
// Assert.assertTrue(logMessagePresent);
// }
//
// protected abstract String getExpectedLogMessage();
// protected abstract String getContextName();
// }
//
// Path: itests/src/main/java/org/wildfly/camel/examples/test/common/ServerLogReader.java
// public class ServerLogReader {
// private static final Path SERVER_LOG = Paths.get(System.getProperty("jboss.home.dir"), "standalone/log/server.log");
//
// /**
// * @param message The log message to match on
// * @param timeout The timeout period in milliseconds for the log message to appear
// * @return true if the log message was found else false
// */
// public static boolean awaitLogMessage(String message, long timeout) {
// long start = System.currentTimeMillis();
// do {
// try {
// List<String> logLines = Files.readAllLines(SERVER_LOG);
// if (logLines.stream().filter(line -> line.matches(message)).count() > 0) {
// return true;
// }
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// try {
// Thread.sleep(100L);
// } catch (InterruptedException e) {
// Thread.currentThread().interrupt();
// return false;
// }
// } while (!((System.currentTimeMillis() - start) >= timeout));
// return false;
// }
// }
| import org.junit.Assert;
import org.junit.Test;
import org.wildfly.camel.examples.test.common.FileConsumerTestSupport;
import org.wildfly.camel.examples.test.common.ServerLogReader;
import org.wildfly.camel.test.common.http.HttpRequest; | /*
* #%L
* Wildfly Camel :: Testsuite
* %%
* Copyright (C) 2013 - 2017 RedHat
* %%
* 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.
* #L%
*/
package org.wildfly.camel.examples.test.jpa;
public abstract class AbstractJPAExampleTest extends FileConsumerTestSupport {
@Test
public void testFileProcessed() throws Exception { | // Path: itests/src/main/java/org/wildfly/camel/examples/test/common/FileConsumerTestSupport.java
// public abstract class FileConsumerTestSupport {
//
// @Test
// public void testFileProcessed() throws Exception {
// boolean logMessagePresent = ServerLogReader.awaitLogMessage(getExpectedLogMessage(), 10000);
// Assert.assertTrue(logMessagePresent);
// }
//
// protected abstract String getExpectedLogMessage();
// protected abstract String getContextName();
// }
//
// Path: itests/src/main/java/org/wildfly/camel/examples/test/common/ServerLogReader.java
// public class ServerLogReader {
// private static final Path SERVER_LOG = Paths.get(System.getProperty("jboss.home.dir"), "standalone/log/server.log");
//
// /**
// * @param message The log message to match on
// * @param timeout The timeout period in milliseconds for the log message to appear
// * @return true if the log message was found else false
// */
// public static boolean awaitLogMessage(String message, long timeout) {
// long start = System.currentTimeMillis();
// do {
// try {
// List<String> logLines = Files.readAllLines(SERVER_LOG);
// if (logLines.stream().filter(line -> line.matches(message)).count() > 0) {
// return true;
// }
// } catch (Exception e) {
// e.printStackTrace();
// return false;
// }
// try {
// Thread.sleep(100L);
// } catch (InterruptedException e) {
// Thread.currentThread().interrupt();
// return false;
// }
// } while (!((System.currentTimeMillis() - start) >= timeout));
// return false;
// }
// }
// Path: itests/src/main/java/org/wildfly/camel/examples/test/jpa/AbstractJPAExampleTest.java
import org.junit.Assert;
import org.junit.Test;
import org.wildfly.camel.examples.test.common.FileConsumerTestSupport;
import org.wildfly.camel.examples.test.common.ServerLogReader;
import org.wildfly.camel.test.common.http.HttpRequest;
/*
* #%L
* Wildfly Camel :: Testsuite
* %%
* Copyright (C) 2013 - 2017 RedHat
* %%
* 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.
* #L%
*/
package org.wildfly.camel.examples.test.jpa;
public abstract class AbstractJPAExampleTest extends FileConsumerTestSupport {
@Test
public void testFileProcessed() throws Exception { | ServerLogReader.awaitLogMessage(getExpectedLogMessage(), 10000); |
wildfly-extras/wildfly-camel-examples | camel-jms-tx/src/main/java/org/wildfly/camel/examples/jms/transacted/OrdersServlet.java | // Path: camel-jms-tx/src/main/java/org/wildfly/camel/examples/jms/transacted/data/OrderRepository.java
// public class OrderRepository {
//
// @Inject
// private EntityManager entityManager;
//
// /**
// * Find all customer records
// *
// * @return A list of customers
// */
// public List<Order> findAllOrders() {
// CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
// CriteriaQuery<Order> query = criteriaBuilder.createQuery(Order.class);
// query.select(query.from(Order.class));
//
// return entityManager.createQuery(query).getResultList();
// }
// }
//
// Path: camel-jms-tx/src/main/java/org/wildfly/camel/examples/jms/transacted/model/Order.java
// @XmlRootElement(name = "order")
// @XmlAccessorType(XmlAccessType.FIELD)
// @Entity
// @Table(name = "orders")
// public class Order implements Serializable {
//
// private static final long serialVersionUID = -2372350530824400584L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private Long id;
// private String productName;
// private String productSku;
// private Integer quantity;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getProductName() {
// return productName;
// }
//
// public void setProductName(String productName) {
// this.productName = productName;
// }
//
// public String getProductSku() {
// return productSku;
// }
//
// public void setProductSku(String productSku) {
// this.productSku = productSku;
// }
//
// public Integer getQuantity() {
// return quantity;
// }
//
// public void setQuantity(Integer quantity) {
// this.quantity = quantity;
// }
// }
| import org.wildfly.camel.examples.jms.transacted.data.OrderRepository;
import org.wildfly.camel.examples.jms.transacted.model.Order;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List; | /*
* #%L
* Wildfly Camel :: Example :: Camel Transacted JMS
* %%
* Copyright (C) 2013 - 2014 RedHat
* %%
* 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.
* #L%
*/
package org.wildfly.camel.examples.jms.transacted;
@SuppressWarnings("serial")
@WebServlet(name = "HttpServiceServlet", urlPatterns = {"/orders"}, loadOnStartup = 1)
public class OrdersServlet extends HttpServlet {
@Inject | // Path: camel-jms-tx/src/main/java/org/wildfly/camel/examples/jms/transacted/data/OrderRepository.java
// public class OrderRepository {
//
// @Inject
// private EntityManager entityManager;
//
// /**
// * Find all customer records
// *
// * @return A list of customers
// */
// public List<Order> findAllOrders() {
// CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
// CriteriaQuery<Order> query = criteriaBuilder.createQuery(Order.class);
// query.select(query.from(Order.class));
//
// return entityManager.createQuery(query).getResultList();
// }
// }
//
// Path: camel-jms-tx/src/main/java/org/wildfly/camel/examples/jms/transacted/model/Order.java
// @XmlRootElement(name = "order")
// @XmlAccessorType(XmlAccessType.FIELD)
// @Entity
// @Table(name = "orders")
// public class Order implements Serializable {
//
// private static final long serialVersionUID = -2372350530824400584L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private Long id;
// private String productName;
// private String productSku;
// private Integer quantity;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getProductName() {
// return productName;
// }
//
// public void setProductName(String productName) {
// this.productName = productName;
// }
//
// public String getProductSku() {
// return productSku;
// }
//
// public void setProductSku(String productSku) {
// this.productSku = productSku;
// }
//
// public Integer getQuantity() {
// return quantity;
// }
//
// public void setQuantity(Integer quantity) {
// this.quantity = quantity;
// }
// }
// Path: camel-jms-tx/src/main/java/org/wildfly/camel/examples/jms/transacted/OrdersServlet.java
import org.wildfly.camel.examples.jms.transacted.data.OrderRepository;
import org.wildfly.camel.examples.jms.transacted.model.Order;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/*
* #%L
* Wildfly Camel :: Example :: Camel Transacted JMS
* %%
* Copyright (C) 2013 - 2014 RedHat
* %%
* 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.
* #L%
*/
package org.wildfly.camel.examples.jms.transacted;
@SuppressWarnings("serial")
@WebServlet(name = "HttpServiceServlet", urlPatterns = {"/orders"}, loadOnStartup = 1)
public class OrdersServlet extends HttpServlet {
@Inject | private OrderRepository orderRepository; |
wildfly-extras/wildfly-camel-examples | camel-jms-tx/src/main/java/org/wildfly/camel/examples/jms/transacted/OrdersServlet.java | // Path: camel-jms-tx/src/main/java/org/wildfly/camel/examples/jms/transacted/data/OrderRepository.java
// public class OrderRepository {
//
// @Inject
// private EntityManager entityManager;
//
// /**
// * Find all customer records
// *
// * @return A list of customers
// */
// public List<Order> findAllOrders() {
// CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
// CriteriaQuery<Order> query = criteriaBuilder.createQuery(Order.class);
// query.select(query.from(Order.class));
//
// return entityManager.createQuery(query).getResultList();
// }
// }
//
// Path: camel-jms-tx/src/main/java/org/wildfly/camel/examples/jms/transacted/model/Order.java
// @XmlRootElement(name = "order")
// @XmlAccessorType(XmlAccessType.FIELD)
// @Entity
// @Table(name = "orders")
// public class Order implements Serializable {
//
// private static final long serialVersionUID = -2372350530824400584L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private Long id;
// private String productName;
// private String productSku;
// private Integer quantity;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getProductName() {
// return productName;
// }
//
// public void setProductName(String productName) {
// this.productName = productName;
// }
//
// public String getProductSku() {
// return productSku;
// }
//
// public void setProductSku(String productSku) {
// this.productSku = productSku;
// }
//
// public Integer getQuantity() {
// return quantity;
// }
//
// public void setQuantity(Integer quantity) {
// this.quantity = quantity;
// }
// }
| import org.wildfly.camel.examples.jms.transacted.data.OrderRepository;
import org.wildfly.camel.examples.jms.transacted.model.Order;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List; | /*
* #%L
* Wildfly Camel :: Example :: Camel Transacted JMS
* %%
* Copyright (C) 2013 - 2014 RedHat
* %%
* 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.
* #L%
*/
package org.wildfly.camel.examples.jms.transacted;
@SuppressWarnings("serial")
@WebServlet(name = "HttpServiceServlet", urlPatterns = {"/orders"}, loadOnStartup = 1)
public class OrdersServlet extends HttpServlet {
@Inject
private OrderRepository orderRepository;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Gets all orders saved to the in-memory database 'orders' table | // Path: camel-jms-tx/src/main/java/org/wildfly/camel/examples/jms/transacted/data/OrderRepository.java
// public class OrderRepository {
//
// @Inject
// private EntityManager entityManager;
//
// /**
// * Find all customer records
// *
// * @return A list of customers
// */
// public List<Order> findAllOrders() {
// CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
// CriteriaQuery<Order> query = criteriaBuilder.createQuery(Order.class);
// query.select(query.from(Order.class));
//
// return entityManager.createQuery(query).getResultList();
// }
// }
//
// Path: camel-jms-tx/src/main/java/org/wildfly/camel/examples/jms/transacted/model/Order.java
// @XmlRootElement(name = "order")
// @XmlAccessorType(XmlAccessType.FIELD)
// @Entity
// @Table(name = "orders")
// public class Order implements Serializable {
//
// private static final long serialVersionUID = -2372350530824400584L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private Long id;
// private String productName;
// private String productSku;
// private Integer quantity;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getProductName() {
// return productName;
// }
//
// public void setProductName(String productName) {
// this.productName = productName;
// }
//
// public String getProductSku() {
// return productSku;
// }
//
// public void setProductSku(String productSku) {
// this.productSku = productSku;
// }
//
// public Integer getQuantity() {
// return quantity;
// }
//
// public void setQuantity(Integer quantity) {
// this.quantity = quantity;
// }
// }
// Path: camel-jms-tx/src/main/java/org/wildfly/camel/examples/jms/transacted/OrdersServlet.java
import org.wildfly.camel.examples.jms.transacted.data.OrderRepository;
import org.wildfly.camel.examples.jms.transacted.model.Order;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/*
* #%L
* Wildfly Camel :: Example :: Camel Transacted JMS
* %%
* Copyright (C) 2013 - 2014 RedHat
* %%
* 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.
* #L%
*/
package org.wildfly.camel.examples.jms.transacted;
@SuppressWarnings("serial")
@WebServlet(name = "HttpServiceServlet", urlPatterns = {"/orders"}, loadOnStartup = 1)
public class OrdersServlet extends HttpServlet {
@Inject
private OrderRepository orderRepository;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Gets all orders saved to the in-memory database 'orders' table | List<Order> orders = orderRepository.findAllOrders(); |
wildfly-extras/wildfly-camel-examples | camel-jms-tx/src/main/java/org/wildfly/camel/examples/jms/transacted/JmsRouteBuilder.java | // Path: camel-jms-tx/src/main/java/org/wildfly/camel/examples/jms/transacted/model/Order.java
// @XmlRootElement(name = "order")
// @XmlAccessorType(XmlAccessType.FIELD)
// @Entity
// @Table(name = "orders")
// public class Order implements Serializable {
//
// private static final long serialVersionUID = -2372350530824400584L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private Long id;
// private String productName;
// private String productSku;
// private Integer quantity;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getProductName() {
// return productName;
// }
//
// public void setProductName(String productName) {
// this.productName = productName;
// }
//
// public String getProductSku() {
// return productSku;
// }
//
// public void setProductSku(String productSku) {
// this.productSku = productSku;
// }
//
// public Integer getQuantity() {
// return quantity;
// }
//
// public void setQuantity(Integer quantity) {
// this.quantity = quantity;
// }
// }
| import javax.enterprise.context.ApplicationScoped;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.dataformat.JaxbDataFormat;
import org.wildfly.camel.examples.jms.transacted.model.Order; | /*
* #%L
* Wildfly Camel :: Example :: Camel Transacted JMS
* %%
* Copyright (C) 2013 - 2014 RedHat
* %%
* 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.
* #L%
*/
package org.wildfly.camel.examples.jms.transacted;
@ApplicationScoped
public class JmsRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
/**
* Configure JAXB so that it can discover model classes.
*/
JaxbDataFormat jaxbDataFormat = new JaxbDataFormat(); | // Path: camel-jms-tx/src/main/java/org/wildfly/camel/examples/jms/transacted/model/Order.java
// @XmlRootElement(name = "order")
// @XmlAccessorType(XmlAccessType.FIELD)
// @Entity
// @Table(name = "orders")
// public class Order implements Serializable {
//
// private static final long serialVersionUID = -2372350530824400584L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private Long id;
// private String productName;
// private String productSku;
// private Integer quantity;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getProductName() {
// return productName;
// }
//
// public void setProductName(String productName) {
// this.productName = productName;
// }
//
// public String getProductSku() {
// return productSku;
// }
//
// public void setProductSku(String productSku) {
// this.productSku = productSku;
// }
//
// public Integer getQuantity() {
// return quantity;
// }
//
// public void setQuantity(Integer quantity) {
// this.quantity = quantity;
// }
// }
// Path: camel-jms-tx/src/main/java/org/wildfly/camel/examples/jms/transacted/JmsRouteBuilder.java
import javax.enterprise.context.ApplicationScoped;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.dataformat.JaxbDataFormat;
import org.wildfly.camel.examples.jms.transacted.model.Order;
/*
* #%L
* Wildfly Camel :: Example :: Camel Transacted JMS
* %%
* Copyright (C) 2013 - 2014 RedHat
* %%
* 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.
* #L%
*/
package org.wildfly.camel.examples.jms.transacted;
@ApplicationScoped
public class JmsRouteBuilder extends RouteBuilder {
@Override
public void configure() throws Exception {
/**
* Configure JAXB so that it can discover model classes.
*/
JaxbDataFormat jaxbDataFormat = new JaxbDataFormat(); | jaxbDataFormat.setContextPath(Order.class.getPackage().getName()); |
wildfly-extras/wildfly-camel-examples | camel-jpa/src/main/java/org/wildfly/camel/examples/jpa/RestAPIRouteBuilder.java | // Path: camel-jpa-spring/src/main/java/org/wildfly/camel/examples/jpa/model/Order.java
// @Entity(name = "orders")
// @NamedQuery(name = "pendingOrders", query = "SELECT o FROM orders o WHERE o.status = 'PENDING'")
// public class Order {
//
// @Id
// @GeneratedValue
// private int id;
// private String item;
// private int amount;
// private String description;
// private String status = "PENDING";
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getItem() {
// return item;
// }
//
// public void setItem(String item) {
// this.item = item;
// }
//
// public int getAmount() {
// return amount;
// }
//
// public void setAmount(int amount) {
// this.amount = amount;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getStatus() {
// return status;
// }
//
// public void setStatus(String status) {
// this.status = status;
// }
//
// }
| import org.apache.camel.model.rest.RestBindingMode;
import org.wildfly.camel.examples.jpa.model.Order;
import javax.enterprise.context.ApplicationScoped;
import org.apache.camel.builder.RouteBuilder; | /*
* #%L
* Wildfly Camel :: Example :: Camel JPA
* %%
* Copyright (C) 2013 - 2014 RedHat
* %%
* 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.
* #L%
*/
package org.wildfly.camel.examples.jpa;
@ApplicationScoped
public class RestAPIRouteBuilder extends RouteBuilder {
public void configure() throws Exception {
restConfiguration()
.contextPath("/rest/api")
.apiContextPath("/api-doc")
.apiProperty("api.title", "Camel REST API")
.apiProperty("api.version", "1.0")
.apiProperty("cors", "true")
.apiContextRouteId("doc-api")
.component("undertow")
.bindingMode(RestBindingMode.json);
rest("/books").description("Books REST service")
.get("/").description("The list of all the books")
.route() | // Path: camel-jpa-spring/src/main/java/org/wildfly/camel/examples/jpa/model/Order.java
// @Entity(name = "orders")
// @NamedQuery(name = "pendingOrders", query = "SELECT o FROM orders o WHERE o.status = 'PENDING'")
// public class Order {
//
// @Id
// @GeneratedValue
// private int id;
// private String item;
// private int amount;
// private String description;
// private String status = "PENDING";
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getItem() {
// return item;
// }
//
// public void setItem(String item) {
// this.item = item;
// }
//
// public int getAmount() {
// return amount;
// }
//
// public void setAmount(int amount) {
// this.amount = amount;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getStatus() {
// return status;
// }
//
// public void setStatus(String status) {
// this.status = status;
// }
//
// }
// Path: camel-jpa/src/main/java/org/wildfly/camel/examples/jpa/RestAPIRouteBuilder.java
import org.apache.camel.model.rest.RestBindingMode;
import org.wildfly.camel.examples.jpa.model.Order;
import javax.enterprise.context.ApplicationScoped;
import org.apache.camel.builder.RouteBuilder;
/*
* #%L
* Wildfly Camel :: Example :: Camel JPA
* %%
* Copyright (C) 2013 - 2014 RedHat
* %%
* 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.
* #L%
*/
package org.wildfly.camel.examples.jpa;
@ApplicationScoped
public class RestAPIRouteBuilder extends RouteBuilder {
public void configure() throws Exception {
restConfiguration()
.contextPath("/rest/api")
.apiContextPath("/api-doc")
.apiProperty("api.title", "Camel REST API")
.apiProperty("api.version", "1.0")
.apiProperty("cors", "true")
.apiContextRouteId("doc-api")
.component("undertow")
.bindingMode(RestBindingMode.json);
rest("/books").description("Books REST service")
.get("/").description("The list of all the books")
.route() | .toF("jpa:%s?nativeQuery=select distinct description from orders", Order.class.getName()) |
wildfly-extras/wildfly-camel-examples | itests/src/main/java/org/wildfly/camel/examples/test/cxf/CxfWsCdiSecureExampleTest.java | // Path: itests/src/main/java/org/wildfly/camel/examples/test/common/SecurityUtils.java
// public class SecurityUtils {
//
// public static SSLConnectionSocketFactory createSocketFactory(Path truststoreFile, Path keystoreFile, String password)
// throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException,
// IOException, UnrecoverableKeyException {
// final char[] pwd = password.toCharArray();
// SSLContextBuilder sslcontextBuilder = SSLContexts.custom()
// .loadTrustMaterial(truststoreFile.toFile(), pwd, TrustSelfSignedStrategy.INSTANCE)
// ;
// if (keystoreFile != null) {
// sslcontextBuilder.loadKeyMaterial(keystoreFile.toFile(), pwd, pwd);
// }
//
// sslcontextBuilder.setProtocol("TLSv1.2");
//
// return new SSLConnectionSocketFactory(sslcontextBuilder.build(), new HostnameVerifier() {
// @Override
// public boolean verify(final String s, final SSLSession sslSession) {
// return true;
// }
// });
// }
// }
| import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.camel.examples.test.common.SecurityUtils;
import org.wildfly.camel.test.common.utils.EnvironmentUtils;
import org.wildfly.camel.test.common.utils.FileUtils;
import org.wildfly.camel.test.common.utils.UserManager;
import org.wildfly.camel.test.common.utils.WildFlyCli; | Assert.assertEquals(403, response.getStatusLine().getStatusCode());
}
}
}
@Test
public void greetClientCert() throws Exception {
try (CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(createTrustedClientCertSocketFactory(WILDFLY_HOME)).build()) {
HttpPost request = new HttpPost(CXF_ENDPOINT_URI);
request.setHeader("Content-Type", "text/xml");
request.setHeader("soapaction", "\"urn:greet\"");
request.setEntity(
new StringEntity(String.format(WS_MESSAGE_TEMPLATE, "Hi", "Joe"), StandardCharsets.UTF_8));
try (CloseableHttpResponse response = httpclient.execute(request)) {
Assert.assertEquals(200, response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity, StandardCharsets.UTF_8);
Assert.assertTrue(body.contains("Hi Joe"));
}
}
}
private static SSLConnectionSocketFactory createTrustedClientCertSocketFactory(final Path wildflyHome)
throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException,
IOException, UnrecoverableKeyException {
final Path truststoreFile = resolveConfigFile(CLIENT_TRUSTSTORE);
final Path keystoreFile = resolveConfigFile(CLIENT_KEYSTORE); | // Path: itests/src/main/java/org/wildfly/camel/examples/test/common/SecurityUtils.java
// public class SecurityUtils {
//
// public static SSLConnectionSocketFactory createSocketFactory(Path truststoreFile, Path keystoreFile, String password)
// throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException,
// IOException, UnrecoverableKeyException {
// final char[] pwd = password.toCharArray();
// SSLContextBuilder sslcontextBuilder = SSLContexts.custom()
// .loadTrustMaterial(truststoreFile.toFile(), pwd, TrustSelfSignedStrategy.INSTANCE)
// ;
// if (keystoreFile != null) {
// sslcontextBuilder.loadKeyMaterial(keystoreFile.toFile(), pwd, pwd);
// }
//
// sslcontextBuilder.setProtocol("TLSv1.2");
//
// return new SSLConnectionSocketFactory(sslcontextBuilder.build(), new HostnameVerifier() {
// @Override
// public boolean verify(final String s, final SSLSession sslSession) {
// return true;
// }
// });
// }
// }
// Path: itests/src/main/java/org/wildfly/camel/examples/test/cxf/CxfWsCdiSecureExampleTest.java
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.camel.examples.test.common.SecurityUtils;
import org.wildfly.camel.test.common.utils.EnvironmentUtils;
import org.wildfly.camel.test.common.utils.FileUtils;
import org.wildfly.camel.test.common.utils.UserManager;
import org.wildfly.camel.test.common.utils.WildFlyCli;
Assert.assertEquals(403, response.getStatusLine().getStatusCode());
}
}
}
@Test
public void greetClientCert() throws Exception {
try (CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(createTrustedClientCertSocketFactory(WILDFLY_HOME)).build()) {
HttpPost request = new HttpPost(CXF_ENDPOINT_URI);
request.setHeader("Content-Type", "text/xml");
request.setHeader("soapaction", "\"urn:greet\"");
request.setEntity(
new StringEntity(String.format(WS_MESSAGE_TEMPLATE, "Hi", "Joe"), StandardCharsets.UTF_8));
try (CloseableHttpResponse response = httpclient.execute(request)) {
Assert.assertEquals(200, response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity, StandardCharsets.UTF_8);
Assert.assertTrue(body.contains("Hi Joe"));
}
}
}
private static SSLConnectionSocketFactory createTrustedClientCertSocketFactory(final Path wildflyHome)
throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException,
IOException, UnrecoverableKeyException {
final Path truststoreFile = resolveConfigFile(CLIENT_TRUSTSTORE);
final Path keystoreFile = resolveConfigFile(CLIENT_KEYSTORE); | return SecurityUtils.createSocketFactory(truststoreFile, keystoreFile, CLIENT_CERT_KEYSTORE_PASSWORD); |
wildfly-extras/wildfly-camel-examples | camel-jms/src/main/java/org/wildfly/camel/examples/jms/JmsServlet.java | // Path: camel-jms-spring/src/main/java/org/wildfly/camel/examples/jms/OrderGenerator.java
// public static final String[] COUNTRIES = {"UK", "US", "Other"};
| import static org.wildfly.camel.examples.jms.OrderGenerator.COUNTRIES;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map; | /*
* #%L
* Wildfly Camel :: Example :: Camel JMS
* %%
* Copyright (C) 2013 - 2014 RedHat
* %%
* 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.
* #L%
*/
package org.wildfly.camel.examples.jms;
@SuppressWarnings("serial")
@WebServlet(name = "HttpServiceServlet", urlPatterns = {"/orders/*"}, loadOnStartup = 1)
public class JmsServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Work out a count of order files processed for each country
Map<String, Integer> orderCounts = new HashMap<>();
| // Path: camel-jms-spring/src/main/java/org/wildfly/camel/examples/jms/OrderGenerator.java
// public static final String[] COUNTRIES = {"UK", "US", "Other"};
// Path: camel-jms/src/main/java/org/wildfly/camel/examples/jms/JmsServlet.java
import static org.wildfly.camel.examples.jms.OrderGenerator.COUNTRIES;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
/*
* #%L
* Wildfly Camel :: Example :: Camel JMS
* %%
* Copyright (C) 2013 - 2014 RedHat
* %%
* 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.
* #L%
*/
package org.wildfly.camel.examples.jms;
@SuppressWarnings("serial")
@WebServlet(name = "HttpServiceServlet", urlPatterns = {"/orders/*"}, loadOnStartup = 1)
public class JmsServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Work out a count of order files processed for each country
Map<String, Integer> orderCounts = new HashMap<>();
| for (String country : COUNTRIES) { |
wildfly-extras/wildfly-camel-examples | camel-jpa-spring/src/main/java/org/wildfly/camel/examples/jpa/service/OrderService.java | // Path: camel-jpa-spring/src/main/java/org/wildfly/camel/examples/jpa/model/Order.java
// @Entity(name = "orders")
// @NamedQuery(name = "pendingOrders", query = "SELECT o FROM orders o WHERE o.status = 'PENDING'")
// public class Order {
//
// @Id
// @GeneratedValue
// private int id;
// private String item;
// private int amount;
// private String description;
// private String status = "PENDING";
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getItem() {
// return item;
// }
//
// public void setItem(String item) {
// this.item = item;
// }
//
// public int getAmount() {
// return amount;
// }
//
// public void setAmount(int amount) {
// this.amount = amount;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getStatus() {
// return status;
// }
//
// public void setStatus(String status) {
// this.status = status;
// }
//
// }
| import org.wildfly.camel.examples.jpa.model.Order;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger; | /*
* #%L
* Wildfly Camel :: Example :: Camel JPA Spring
* %%
* Copyright (C) 2013 - 2017 RedHat
* %%
* 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.
* #L%
*/
package org.wildfly.camel.examples.jpa.service;
public class OrderService {
private final AtomicInteger counter = new AtomicInteger();
private final Random amount = new Random();
| // Path: camel-jpa-spring/src/main/java/org/wildfly/camel/examples/jpa/model/Order.java
// @Entity(name = "orders")
// @NamedQuery(name = "pendingOrders", query = "SELECT o FROM orders o WHERE o.status = 'PENDING'")
// public class Order {
//
// @Id
// @GeneratedValue
// private int id;
// private String item;
// private int amount;
// private String description;
// private String status = "PENDING";
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getItem() {
// return item;
// }
//
// public void setItem(String item) {
// this.item = item;
// }
//
// public int getAmount() {
// return amount;
// }
//
// public void setAmount(int amount) {
// this.amount = amount;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getStatus() {
// return status;
// }
//
// public void setStatus(String status) {
// this.status = status;
// }
//
// }
// Path: camel-jpa-spring/src/main/java/org/wildfly/camel/examples/jpa/service/OrderService.java
import org.wildfly.camel.examples.jpa.model.Order;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
/*
* #%L
* Wildfly Camel :: Example :: Camel JPA Spring
* %%
* Copyright (C) 2013 - 2017 RedHat
* %%
* 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.
* #L%
*/
package org.wildfly.camel.examples.jpa.service;
public class OrderService {
private final AtomicInteger counter = new AtomicInteger();
private final Random amount = new Random();
| public Order generateOrder() { |
wildfly-extras/wildfly-camel-examples | itests/src/main/java/org/wildfly/camel/examples/test/activemq/ActiveMQExampleTest.java | // Path: itests/src/main/java/org/wildfly/camel/examples/test/jms/AbstractJMSExampleTest.java
// public abstract class AbstractJMSExampleTest extends FileConsumerTestSupport {
//
// private static String ORDERS_QUEUE = "OrdersQueue";
// private static String ORDERS_QUEUE_JNDI = "java:/jms/queue/OrdersQueue";
//
// static class JmsQueueSetup implements ServerSetupTask {
//
// @Override
// public void setup(ManagementClient managementClient, String containerId) throws Exception {
// JMSUtils.createJmsQueue(ORDERS_QUEUE, ORDERS_QUEUE_JNDI, managementClient.getControllerClient());
// }
//
// @Override
// public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
// JMSUtils.removeJmsQueue(ORDERS_QUEUE, managementClient.getControllerClient());
// }
// }
//
// @Override
// protected String getExpectedLogMessage() {
// return String.format(".*%s.*Sending order to (the UK|another country|the US)$", getContextName());
// }
// }
| import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.runner.RunWith;
import org.wildfly.camel.examples.test.jms.AbstractJMSExampleTest;
import org.wildfly.camel.test.common.utils.DMRUtils;
import org.wildfly.camel.test.common.utils.WildFlyCli;
import java.io.File;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.ResourceAdapterArchive; | /*
* #%L
* Wildfly Camel :: Testsuite
* %%
* Copyright (C) 2013 - 2014 RedHat
* %%
* 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.
* #L%
*/
package org.wildfly.camel.examples.test.activemq;
@RunAsClient
@RunWith(Arquillian.class)
@ServerSetup({ActiveMQExampleTest.ActiveMQRarSetupTask.class}) | // Path: itests/src/main/java/org/wildfly/camel/examples/test/jms/AbstractJMSExampleTest.java
// public abstract class AbstractJMSExampleTest extends FileConsumerTestSupport {
//
// private static String ORDERS_QUEUE = "OrdersQueue";
// private static String ORDERS_QUEUE_JNDI = "java:/jms/queue/OrdersQueue";
//
// static class JmsQueueSetup implements ServerSetupTask {
//
// @Override
// public void setup(ManagementClient managementClient, String containerId) throws Exception {
// JMSUtils.createJmsQueue(ORDERS_QUEUE, ORDERS_QUEUE_JNDI, managementClient.getControllerClient());
// }
//
// @Override
// public void tearDown(ManagementClient managementClient, String containerId) throws Exception {
// JMSUtils.removeJmsQueue(ORDERS_QUEUE, managementClient.getControllerClient());
// }
// }
//
// @Override
// protected String getExpectedLogMessage() {
// return String.format(".*%s.*Sending order to (the UK|another country|the US)$", getContextName());
// }
// }
// Path: itests/src/main/java/org/wildfly/camel/examples/test/activemq/ActiveMQExampleTest.java
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.runner.RunWith;
import org.wildfly.camel.examples.test.jms.AbstractJMSExampleTest;
import org.wildfly.camel.test.common.utils.DMRUtils;
import org.wildfly.camel.test.common.utils.WildFlyCli;
import java.io.File;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.ResourceAdapterArchive;
/*
* #%L
* Wildfly Camel :: Testsuite
* %%
* Copyright (C) 2013 - 2014 RedHat
* %%
* 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.
* #L%
*/
package org.wildfly.camel.examples.test.activemq;
@RunAsClient
@RunWith(Arquillian.class)
@ServerSetup({ActiveMQExampleTest.ActiveMQRarSetupTask.class}) | public class ActiveMQExampleTest extends AbstractJMSExampleTest { |
wildfly-extras/wildfly-camel-examples | camel-jms-tx-spring/src/main/java/org/wildfly/camel/examples/jms/transacted/OrdersServlet.java | // Path: camel-jms-tx/src/main/java/org/wildfly/camel/examples/jms/transacted/model/Order.java
// @XmlRootElement(name = "order")
// @XmlAccessorType(XmlAccessType.FIELD)
// @Entity
// @Table(name = "orders")
// public class Order implements Serializable {
//
// private static final long serialVersionUID = -2372350530824400584L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private Long id;
// private String productName;
// private String productSku;
// private Integer quantity;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getProductName() {
// return productName;
// }
//
// public void setProductName(String productName) {
// this.productName = productName;
// }
//
// public String getProductSku() {
// return productSku;
// }
//
// public void setProductSku(String productSku) {
// this.productSku = productSku;
// }
//
// public Integer getQuantity() {
// return quantity;
// }
//
// public void setQuantity(Integer quantity) {
// this.quantity = quantity;
// }
// }
| import javax.servlet.http.HttpServletResponse;
import org.apache.camel.CamelContext;
import org.apache.camel.component.jpa.JpaComponent;
import org.wildfly.camel.examples.jms.transacted.model.Order;
import java.io.IOException;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest; | /*
* #%L
* Wildfly Camel :: Example :: Camel Transacted JMS Spring
* %%
* Copyright (C) 2013 - 2017 RedHat
* %%
* 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.
* #L%
*/
package org.wildfly.camel.examples.jms.transacted;
@SuppressWarnings("serial")
@WebServlet(name = "HttpServiceServlet", urlPatterns = {"/orders"}, loadOnStartup = 1)
public class OrdersServlet extends HttpServlet {
@Resource(lookup = "java:jboss/camel/context/jms-tx-spring-camel-context")
private CamelContext camelContext;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Gets all orders saved to the in-memory database 'orders' table
JpaComponent component = camelContext.getComponent("jpa", JpaComponent.class);
EntityManagerFactory entityManagerFactory = component.getEntityManagerFactory();
EntityManager entityManager = entityManagerFactory.createEntityManager();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); | // Path: camel-jms-tx/src/main/java/org/wildfly/camel/examples/jms/transacted/model/Order.java
// @XmlRootElement(name = "order")
// @XmlAccessorType(XmlAccessType.FIELD)
// @Entity
// @Table(name = "orders")
// public class Order implements Serializable {
//
// private static final long serialVersionUID = -2372350530824400584L;
//
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// private Long id;
// private String productName;
// private String productSku;
// private Integer quantity;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getProductName() {
// return productName;
// }
//
// public void setProductName(String productName) {
// this.productName = productName;
// }
//
// public String getProductSku() {
// return productSku;
// }
//
// public void setProductSku(String productSku) {
// this.productSku = productSku;
// }
//
// public Integer getQuantity() {
// return quantity;
// }
//
// public void setQuantity(Integer quantity) {
// this.quantity = quantity;
// }
// }
// Path: camel-jms-tx-spring/src/main/java/org/wildfly/camel/examples/jms/transacted/OrdersServlet.java
import javax.servlet.http.HttpServletResponse;
import org.apache.camel.CamelContext;
import org.apache.camel.component.jpa.JpaComponent;
import org.wildfly.camel.examples.jms.transacted.model.Order;
import java.io.IOException;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
/*
* #%L
* Wildfly Camel :: Example :: Camel Transacted JMS Spring
* %%
* Copyright (C) 2013 - 2017 RedHat
* %%
* 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.
* #L%
*/
package org.wildfly.camel.examples.jms.transacted;
@SuppressWarnings("serial")
@WebServlet(name = "HttpServiceServlet", urlPatterns = {"/orders"}, loadOnStartup = 1)
public class OrdersServlet extends HttpServlet {
@Resource(lookup = "java:jboss/camel/context/jms-tx-spring-camel-context")
private CamelContext camelContext;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Gets all orders saved to the in-memory database 'orders' table
JpaComponent component = camelContext.getComponent("jpa", JpaComponent.class);
EntityManagerFactory entityManagerFactory = component.getEntityManagerFactory();
EntityManager entityManager = entityManagerFactory.createEntityManager();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); | CriteriaQuery<Order> query = criteriaBuilder.createQuery(Order.class); |
wildfly-extras/wildfly-camel-examples | camel-jpa-spring/src/main/java/org/wildfly/camel/examples/jpa/processor/OrderProcessedProcessor.java | // Path: camel-jpa-spring/src/main/java/org/wildfly/camel/examples/jpa/model/Order.java
// @Entity(name = "orders")
// @NamedQuery(name = "pendingOrders", query = "SELECT o FROM orders o WHERE o.status = 'PENDING'")
// public class Order {
//
// @Id
// @GeneratedValue
// private int id;
// private String item;
// private int amount;
// private String description;
// private String status = "PENDING";
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getItem() {
// return item;
// }
//
// public void setItem(String item) {
// this.item = item;
// }
//
// public int getAmount() {
// return amount;
// }
//
// public void setAmount(int amount) {
// this.amount = amount;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getStatus() {
// return status;
// }
//
// public void setStatus(String status) {
// this.status = status;
// }
//
// }
| import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.wildfly.camel.examples.jpa.model.Order; | /*
* #%L
* Wildfly Camel :: Example :: Camel JPA Spring
* %%
* Copyright (C) 2013 - 2017 RedHat
* %%
* 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.
* #L%
*/
package org.wildfly.camel.examples.jpa.processor;
public class OrderProcessedProcessor implements Processor {
@Override
public void process(Exchange exchange) throws Exception { | // Path: camel-jpa-spring/src/main/java/org/wildfly/camel/examples/jpa/model/Order.java
// @Entity(name = "orders")
// @NamedQuery(name = "pendingOrders", query = "SELECT o FROM orders o WHERE o.status = 'PENDING'")
// public class Order {
//
// @Id
// @GeneratedValue
// private int id;
// private String item;
// private int amount;
// private String description;
// private String status = "PENDING";
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getItem() {
// return item;
// }
//
// public void setItem(String item) {
// this.item = item;
// }
//
// public int getAmount() {
// return amount;
// }
//
// public void setAmount(int amount) {
// this.amount = amount;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getStatus() {
// return status;
// }
//
// public void setStatus(String status) {
// this.status = status;
// }
//
// }
// Path: camel-jpa-spring/src/main/java/org/wildfly/camel/examples/jpa/processor/OrderProcessedProcessor.java
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.wildfly.camel.examples.jpa.model.Order;
/*
* #%L
* Wildfly Camel :: Example :: Camel JPA Spring
* %%
* Copyright (C) 2013 - 2017 RedHat
* %%
* 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.
* #L%
*/
package org.wildfly.camel.examples.jpa.processor;
public class OrderProcessedProcessor implements Processor {
@Override
public void process(Exchange exchange) throws Exception { | Order order = exchange.getIn().getBody(Order.class); |
wildfly-extras/wildfly-camel-examples | camel-jpa-spring/src/main/java/org/wildfly/camel/examples/jpa/processor/JpaResultProcessor.java | // Path: camel-jpa-spring/src/main/java/org/wildfly/camel/examples/jpa/model/Order.java
// @Entity(name = "orders")
// @NamedQuery(name = "pendingOrders", query = "SELECT o FROM orders o WHERE o.status = 'PENDING'")
// public class Order {
//
// @Id
// @GeneratedValue
// private int id;
// private String item;
// private int amount;
// private String description;
// private String status = "PENDING";
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getItem() {
// return item;
// }
//
// public void setItem(String item) {
// this.item = item;
// }
//
// public int getAmount() {
// return amount;
// }
//
// public void setAmount(int amount) {
// this.amount = amount;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getStatus() {
// return status;
// }
//
// public void setStatus(String status) {
// this.status = status;
// }
//
// }
| import org.apache.camel.Processor;
import org.wildfly.camel.examples.jpa.model.Order;
import java.util.List;
import org.apache.camel.Exchange; | /*
* #%L
* Wildfly Camel :: Example :: Camel JPA Spring
* %%
* Copyright (C) 2013 - 2017 RedHat
* %%
* 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.
* #L%
*/
package org.wildfly.camel.examples.jpa.processor;
public class JpaResultProcessor implements Processor {
@SuppressWarnings("unchecked")
@Override
public void process(Exchange exchange) throws Exception { | // Path: camel-jpa-spring/src/main/java/org/wildfly/camel/examples/jpa/model/Order.java
// @Entity(name = "orders")
// @NamedQuery(name = "pendingOrders", query = "SELECT o FROM orders o WHERE o.status = 'PENDING'")
// public class Order {
//
// @Id
// @GeneratedValue
// private int id;
// private String item;
// private int amount;
// private String description;
// private String status = "PENDING";
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getItem() {
// return item;
// }
//
// public void setItem(String item) {
// this.item = item;
// }
//
// public int getAmount() {
// return amount;
// }
//
// public void setAmount(int amount) {
// this.amount = amount;
// }
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public String getStatus() {
// return status;
// }
//
// public void setStatus(String status) {
// this.status = status;
// }
//
// }
// Path: camel-jpa-spring/src/main/java/org/wildfly/camel/examples/jpa/processor/JpaResultProcessor.java
import org.apache.camel.Processor;
import org.wildfly.camel.examples.jpa.model.Order;
import java.util.List;
import org.apache.camel.Exchange;
/*
* #%L
* Wildfly Camel :: Example :: Camel JPA Spring
* %%
* Copyright (C) 2013 - 2017 RedHat
* %%
* 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.
* #L%
*/
package org.wildfly.camel.examples.jpa.processor;
public class JpaResultProcessor implements Processor {
@SuppressWarnings("unchecked")
@Override
public void process(Exchange exchange) throws Exception { | List<Order> orders = exchange.getIn().getBody(List.class); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.