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
documaster/noark-extraction-validator
noark-extraction-validator/src/main/java/com/documaster/validator/config/delegates/ReportConfiguration.java
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/validators/DirectoryValidator.java // public class DirectoryValidator implements IValueValidator<File> { // // @Override // public void validate(String name, File value) throws ParameterException { // // if (!value.exists() || !value.isDirectory()) { // // String errorMessage = MessageFormat.format( // "{0}: Invalid/missing directory ({1}).", name, value.getAbsolutePath()); // // throw new ParameterException(errorMessage); // } // } // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/exceptions/ReportingException.java // public class ReportingException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public ReportingException(String message) { // // super(message); // } // // public ReportingException(Throwable throwable) { // // super(throwable); // } // // public ReportingException(String message, Throwable throwable) { // // super(message, throwable); // } // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/reporting/ReportType.java // public enum ReportType { // // EXCEL_XLS, EXCEL_XLSX, XML // }
import java.io.File; import java.util.ArrayList; import java.util.List; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.beust.jcommander.converters.FileConverter; import com.documaster.validator.config.validators.DirectoryValidator; import com.documaster.validator.exceptions.ReportingException; import com.documaster.validator.reporting.ReportType; import static com.documaster.validator.reporting.ReportType.EXCEL_XLSX;
/** * Noark Extraction Validator * Copyright (C) 2016, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.config.delegates; public class ReportConfiguration implements Delegate { private static List<ReportType> defaultReportTypes; private static final String OUTPUT_DIR = "-output-dir"; @Parameter( names = OUTPUT_DIR, description = "The validation report output directory",
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/validators/DirectoryValidator.java // public class DirectoryValidator implements IValueValidator<File> { // // @Override // public void validate(String name, File value) throws ParameterException { // // if (!value.exists() || !value.isDirectory()) { // // String errorMessage = MessageFormat.format( // "{0}: Invalid/missing directory ({1}).", name, value.getAbsolutePath()); // // throw new ParameterException(errorMessage); // } // } // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/exceptions/ReportingException.java // public class ReportingException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public ReportingException(String message) { // // super(message); // } // // public ReportingException(Throwable throwable) { // // super(throwable); // } // // public ReportingException(String message, Throwable throwable) { // // super(message, throwable); // } // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/reporting/ReportType.java // public enum ReportType { // // EXCEL_XLS, EXCEL_XLSX, XML // } // Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/delegates/ReportConfiguration.java import java.io.File; import java.util.ArrayList; import java.util.List; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.beust.jcommander.converters.FileConverter; import com.documaster.validator.config.validators.DirectoryValidator; import com.documaster.validator.exceptions.ReportingException; import com.documaster.validator.reporting.ReportType; import static com.documaster.validator.reporting.ReportType.EXCEL_XLSX; /** * Noark Extraction Validator * Copyright (C) 2016, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.config.delegates; public class ReportConfiguration implements Delegate { private static List<ReportType> defaultReportTypes; private static final String OUTPUT_DIR = "-output-dir"; @Parameter( names = OUTPUT_DIR, description = "The validation report output directory",
converter = FileConverter.class, validateValueWith = DirectoryValidator.class)
documaster/noark-extraction-validator
noark-extraction-validator/src/main/java/com/documaster/validator/config/delegates/ReportConfiguration.java
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/validators/DirectoryValidator.java // public class DirectoryValidator implements IValueValidator<File> { // // @Override // public void validate(String name, File value) throws ParameterException { // // if (!value.exists() || !value.isDirectory()) { // // String errorMessage = MessageFormat.format( // "{0}: Invalid/missing directory ({1}).", name, value.getAbsolutePath()); // // throw new ParameterException(errorMessage); // } // } // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/exceptions/ReportingException.java // public class ReportingException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public ReportingException(String message) { // // super(message); // } // // public ReportingException(Throwable throwable) { // // super(throwable); // } // // public ReportingException(String message, Throwable throwable) { // // super(message, throwable); // } // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/reporting/ReportType.java // public enum ReportType { // // EXCEL_XLS, EXCEL_XLSX, XML // }
import java.io.File; import java.util.ArrayList; import java.util.List; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.beust.jcommander.converters.FileConverter; import com.documaster.validator.config.validators.DirectoryValidator; import com.documaster.validator.exceptions.ReportingException; import com.documaster.validator.reporting.ReportType; import static com.documaster.validator.reporting.ReportType.EXCEL_XLSX;
} public void setOutputTypes(List<ReportType> outputTypes) { this.outputTypes = outputTypes; } public boolean isInMemoryXlsxReport() { return inMemoryXlsxReport; } public void setInMemoryXlsxReport(boolean inMemoryXlsxReport) { this.inMemoryXlsxReport = inMemoryXlsxReport; } @Override public void validate() { for (ReportType reportType : outputTypes) { switch (reportType) { case EXCEL_XLS: case EXCEL_XLSX: case XML: if (outputDir == null) { throw new ParameterException(OUTPUT_DIR + " must be specified for " + reportType); } break; default:
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/validators/DirectoryValidator.java // public class DirectoryValidator implements IValueValidator<File> { // // @Override // public void validate(String name, File value) throws ParameterException { // // if (!value.exists() || !value.isDirectory()) { // // String errorMessage = MessageFormat.format( // "{0}: Invalid/missing directory ({1}).", name, value.getAbsolutePath()); // // throw new ParameterException(errorMessage); // } // } // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/exceptions/ReportingException.java // public class ReportingException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public ReportingException(String message) { // // super(message); // } // // public ReportingException(Throwable throwable) { // // super(throwable); // } // // public ReportingException(String message, Throwable throwable) { // // super(message, throwable); // } // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/reporting/ReportType.java // public enum ReportType { // // EXCEL_XLS, EXCEL_XLSX, XML // } // Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/delegates/ReportConfiguration.java import java.io.File; import java.util.ArrayList; import java.util.List; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.beust.jcommander.converters.FileConverter; import com.documaster.validator.config.validators.DirectoryValidator; import com.documaster.validator.exceptions.ReportingException; import com.documaster.validator.reporting.ReportType; import static com.documaster.validator.reporting.ReportType.EXCEL_XLSX; } public void setOutputTypes(List<ReportType> outputTypes) { this.outputTypes = outputTypes; } public boolean isInMemoryXlsxReport() { return inMemoryXlsxReport; } public void setInMemoryXlsxReport(boolean inMemoryXlsxReport) { this.inMemoryXlsxReport = inMemoryXlsxReport; } @Override public void validate() { for (ReportType reportType : outputTypes) { switch (reportType) { case EXCEL_XLS: case EXCEL_XLSX: case XML: if (outputDir == null) { throw new ParameterException(OUTPUT_DIR + " must be specified for " + reportType); } break; default:
throw new ReportingException("Unknown report type: " + reportType);
documaster/noark-extraction-validator
noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/rules/Rule.java
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/ValidationGroup.java // @XmlType(name = "group") // @XmlEnum // public enum ValidationGroup { // // @XmlEnumValue("arkivstruktur") // ARCHIVE_STRUCTURE("arkivstruktur", "AS"), // // @XmlEnumValue("loependejournal") // RUNNING_JOURNAL("loependejournal", "LJ"), // // @XmlEnumValue("offentligjournal") // PUBLIC_JOURNAL("offentligjournal", "OJ"), // // @XmlEnumValue("arkivuttrekk") // TRANSFER_EXPORTS("addml", "AU"), // // @XmlEnumValue("endringslogg") // CHANGE_LOG("endringslogg", "EL"), // // @XmlEnumValue("package") // PACKAGE("package", "P"), // // @XmlEnumValue("exceptions") // EXCEPTIONS("exceptions", "E"); // // private final String name; // private final String prefix; // // ValidationGroup(String name, String prefix) { // // this.name = name; // this.prefix = prefix; // } // // public String getName() { // // return name; // } // // public String getGroupPrefix() { // // return prefix; // } // // public String getNextGroupId(ValidationCollector collector) { // // return prefix + (collector.getTotalResultCountIn(name) + 1); // } // }
import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import com.documaster.validator.validation.noark5.provider.ValidationGroup; import org.apache.commons.lang.StringUtils;
/** * Noark Extraction Validator * Copyright (C) 2017, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.validation.noark5.provider.rules; public class Rule { @XmlAttribute(required = true, name = "id") protected String id; @XmlElement(required = true, name = "title") protected String title; @XmlElement(required = true, name = "description") protected String description; @XmlElement(required = true, name = "group")
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/ValidationGroup.java // @XmlType(name = "group") // @XmlEnum // public enum ValidationGroup { // // @XmlEnumValue("arkivstruktur") // ARCHIVE_STRUCTURE("arkivstruktur", "AS"), // // @XmlEnumValue("loependejournal") // RUNNING_JOURNAL("loependejournal", "LJ"), // // @XmlEnumValue("offentligjournal") // PUBLIC_JOURNAL("offentligjournal", "OJ"), // // @XmlEnumValue("arkivuttrekk") // TRANSFER_EXPORTS("addml", "AU"), // // @XmlEnumValue("endringslogg") // CHANGE_LOG("endringslogg", "EL"), // // @XmlEnumValue("package") // PACKAGE("package", "P"), // // @XmlEnumValue("exceptions") // EXCEPTIONS("exceptions", "E"); // // private final String name; // private final String prefix; // // ValidationGroup(String name, String prefix) { // // this.name = name; // this.prefix = prefix; // } // // public String getName() { // // return name; // } // // public String getGroupPrefix() { // // return prefix; // } // // public String getNextGroupId(ValidationCollector collector) { // // return prefix + (collector.getTotalResultCountIn(name) + 1); // } // } // Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/rules/Rule.java import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import com.documaster.validator.validation.noark5.provider.ValidationGroup; import org.apache.commons.lang.StringUtils; /** * Noark Extraction Validator * Copyright (C) 2017, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.validation.noark5.provider.rules; public class Rule { @XmlAttribute(required = true, name = "id") protected String id; @XmlElement(required = true, name = "title") protected String title; @XmlElement(required = true, name = "description") protected String description; @XmlElement(required = true, name = "group")
protected ValidationGroup group;
documaster/noark-extraction-validator
noark-extraction-validator/src/main/java/com/documaster/validator/storage/model/ItemDef.java
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/exceptions/ConversionException.java // public class ConversionException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public ConversionException(String message) { // // super(message); // } // // public ConversionException(Throwable throwable) { // // super(throwable); // } // // public ConversionException(String message, Throwable throwable) { // // super(message, throwable); // } // }
import java.util.HashMap; import java.util.Map; import com.documaster.validator.exceptions.ConversionException; import org.apache.commons.lang.Validate;
/** * Returns the name of the reference fields for this item definition. */ public String getReferenceName() { return Field.REFERENCE_PREFIX + name; } Integer getNextId() { return ++recordCount; } private void createInternalFields() { getFields().put(Field.TYPE, new Field(Field.TYPE, Field.FieldType.getFromJavaType(String.class))); getFields() .put(Field.INTERNAL_ID, new Field(Field.INTERNAL_ID, Field.FieldType.getFromJavaType(Integer.class))); getFields().put( Field.INTERNAL_PARENT_ID, new Field(Field.INTERNAL_PARENT_ID, Field.FieldType.getFromJavaType(Integer.class))); } private static String generateGroupName(Class<?> cls) { Class<?> rootCls = getRootClassOf(cls); int lastOccurrenceOfDot = rootCls.getPackage().getName().lastIndexOf("."); if (lastOccurrenceOfDot == -1) {
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/exceptions/ConversionException.java // public class ConversionException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public ConversionException(String message) { // // super(message); // } // // public ConversionException(Throwable throwable) { // // super(throwable); // } // // public ConversionException(String message, Throwable throwable) { // // super(message, throwable); // } // } // Path: noark-extraction-validator/src/main/java/com/documaster/validator/storage/model/ItemDef.java import java.util.HashMap; import java.util.Map; import com.documaster.validator.exceptions.ConversionException; import org.apache.commons.lang.Validate; /** * Returns the name of the reference fields for this item definition. */ public String getReferenceName() { return Field.REFERENCE_PREFIX + name; } Integer getNextId() { return ++recordCount; } private void createInternalFields() { getFields().put(Field.TYPE, new Field(Field.TYPE, Field.FieldType.getFromJavaType(String.class))); getFields() .put(Field.INTERNAL_ID, new Field(Field.INTERNAL_ID, Field.FieldType.getFromJavaType(Integer.class))); getFields().put( Field.INTERNAL_PARENT_ID, new Field(Field.INTERNAL_PARENT_ID, Field.FieldType.getFromJavaType(Integer.class))); } private static String generateGroupName(Class<?> cls) { Class<?> rootCls = getRootClassOf(cls); int lastOccurrenceOfDot = rootCls.getPackage().getName().lastIndexOf("."); if (lastOccurrenceOfDot == -1) {
throw new ConversionException("Cannot build a group name for a class without a package: "
documaster/noark-extraction-validator
noark-extraction-validator/src/main/java/com/documaster/validator/config/delegates/StorageConfiguration.java
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/exceptions/ReportingException.java // public class ReportingException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public ReportingException(String message) { // // super(message); // } // // public ReportingException(Throwable throwable) { // // super(throwable); // } // // public ReportingException(String message, Throwable throwable) { // // super(message, throwable); // } // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/storage/core/Storage.java // public abstract class Storage { // // private static final Logger LOGGER = LoggerFactory.getLogger(Storage.class); // // private static Storage instance; // // private StorageWriter writerThread; // // private LinkedBlockingQueue<Persistable> queue = new LinkedBlockingQueue<>(); // // /** // * < item definition full name , set of unique field names > // */ // protected Map<String, Set<String>> uniqueFields; // // protected Storage() { // // Prevent instantiation // } // // /** // * Creates a new concrete {@link Storage} instance via the {@link StorageFactory}, establishes a connection // * to the storage provider, and runs a separate thread that listens for actions. // * // * @param config // * The {@link StorageConfiguration} with which to instantiate the {@link Storage}. // * @param uniqueFields // * The name of the unique field in each table // */ // public static void init(StorageConfiguration config, Map<String, Set<String>> uniqueFields) throws Exception { // // LOGGER.info("Initializing storage ..."); // // instance = StorageFactory.createPersistence(config); // instance.uniqueFields = uniqueFields; // } // // public static Storage get() { // // return instance; // } // // /** // * Starts the {@link Storage}'s writer. // */ // public void startWriter() { // // writerThread = new StorageWriter(); // writerThread.start(); // } // // private boolean isWriteAvailable() { // // return writerThread != null && writerThread.isAlive(); // } // // /** // * Queues the specified {@link Persistable} object for writing. // * <p/> // * Writing a {@link StorageWriter#SHUTDOWN_SIGNAL} will send a shutdown signal to the writer. // */ // public void write(Persistable obj) { // // if (!isWriteAvailable()) { // throw new StorageException( // "The Storage writer is not listening. Most probably the writer " // + "thread encountered an unexpected error. Please verify the logs for more information."); // } // // queue.offer(obj); // } // // Persistable nextInWriteQueue() throws InterruptedException { // // return queue.take(); // } // // /** // * Sends a shut down signal to the {@link Storage}'s writer, waits for it to exit, and returns its exit status. // * // * @return <b>true</b> if the writer exists and no exceptions occurred during execution; <b>false</b> otherwise. // */ // public boolean stopWriter() { // // if (writerThread != null && isWriteAvailable()) { // // Send shut down signal to writer // write(StorageWriter.SHUTDOWN_SIGNAL); // // // Wait for the listener to exit // try { // writerThread.join(); // } catch (InterruptedException ex) { // // Ignore... someone else has interrupted the writer // } // } // // return writerThread != null && writerThread.getLastException() == null; // } // // public Exception getLastWriterException() { // // return writerThread.getLastException(); // } // // /** // * Establishes a connection to the implementation's storage provider. // */ // public abstract void connect() throws Exception; // // /** // * Indicates whether a connection is established and {@link Storage#fetch} can be invoked to retrieve data from the // * {@link Storage} implementation. // */ // public abstract boolean isReadAvailable(); // // /** // * Destroys the connection to the implementation's storage provider. // */ // public abstract void destroy(); // // protected abstract void writeItemDef(ItemDef itemDef) throws Exception; // // protected abstract void writeItem(Item item) throws Exception; // // /** // * Fetches the results of the specified query mapped as a list of {@link BaseItem}s. // */ // public abstract List<BaseItem> fetch(String query) throws Exception; // // public enum StorageType { // // HSQLDB_IN_MEMORY, HSQLDB_FILE, HSQLDB_SERVER // } // }
import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.documaster.validator.exceptions.ReportingException; import com.documaster.validator.storage.core.Storage;
/** * Noark Extraction Validator * Copyright (C) 2016, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.config.delegates; public class StorageConfiguration implements Delegate { private static final String STORAGE = "-storage"; @Parameter(names = STORAGE, description = "The storage type")
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/exceptions/ReportingException.java // public class ReportingException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public ReportingException(String message) { // // super(message); // } // // public ReportingException(Throwable throwable) { // // super(throwable); // } // // public ReportingException(String message, Throwable throwable) { // // super(message, throwable); // } // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/storage/core/Storage.java // public abstract class Storage { // // private static final Logger LOGGER = LoggerFactory.getLogger(Storage.class); // // private static Storage instance; // // private StorageWriter writerThread; // // private LinkedBlockingQueue<Persistable> queue = new LinkedBlockingQueue<>(); // // /** // * < item definition full name , set of unique field names > // */ // protected Map<String, Set<String>> uniqueFields; // // protected Storage() { // // Prevent instantiation // } // // /** // * Creates a new concrete {@link Storage} instance via the {@link StorageFactory}, establishes a connection // * to the storage provider, and runs a separate thread that listens for actions. // * // * @param config // * The {@link StorageConfiguration} with which to instantiate the {@link Storage}. // * @param uniqueFields // * The name of the unique field in each table // */ // public static void init(StorageConfiguration config, Map<String, Set<String>> uniqueFields) throws Exception { // // LOGGER.info("Initializing storage ..."); // // instance = StorageFactory.createPersistence(config); // instance.uniqueFields = uniqueFields; // } // // public static Storage get() { // // return instance; // } // // /** // * Starts the {@link Storage}'s writer. // */ // public void startWriter() { // // writerThread = new StorageWriter(); // writerThread.start(); // } // // private boolean isWriteAvailable() { // // return writerThread != null && writerThread.isAlive(); // } // // /** // * Queues the specified {@link Persistable} object for writing. // * <p/> // * Writing a {@link StorageWriter#SHUTDOWN_SIGNAL} will send a shutdown signal to the writer. // */ // public void write(Persistable obj) { // // if (!isWriteAvailable()) { // throw new StorageException( // "The Storage writer is not listening. Most probably the writer " // + "thread encountered an unexpected error. Please verify the logs for more information."); // } // // queue.offer(obj); // } // // Persistable nextInWriteQueue() throws InterruptedException { // // return queue.take(); // } // // /** // * Sends a shut down signal to the {@link Storage}'s writer, waits for it to exit, and returns its exit status. // * // * @return <b>true</b> if the writer exists and no exceptions occurred during execution; <b>false</b> otherwise. // */ // public boolean stopWriter() { // // if (writerThread != null && isWriteAvailable()) { // // Send shut down signal to writer // write(StorageWriter.SHUTDOWN_SIGNAL); // // // Wait for the listener to exit // try { // writerThread.join(); // } catch (InterruptedException ex) { // // Ignore... someone else has interrupted the writer // } // } // // return writerThread != null && writerThread.getLastException() == null; // } // // public Exception getLastWriterException() { // // return writerThread.getLastException(); // } // // /** // * Establishes a connection to the implementation's storage provider. // */ // public abstract void connect() throws Exception; // // /** // * Indicates whether a connection is established and {@link Storage#fetch} can be invoked to retrieve data from the // * {@link Storage} implementation. // */ // public abstract boolean isReadAvailable(); // // /** // * Destroys the connection to the implementation's storage provider. // */ // public abstract void destroy(); // // protected abstract void writeItemDef(ItemDef itemDef) throws Exception; // // protected abstract void writeItem(Item item) throws Exception; // // /** // * Fetches the results of the specified query mapped as a list of {@link BaseItem}s. // */ // public abstract List<BaseItem> fetch(String query) throws Exception; // // public enum StorageType { // // HSQLDB_IN_MEMORY, HSQLDB_FILE, HSQLDB_SERVER // } // } // Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/delegates/StorageConfiguration.java import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.documaster.validator.exceptions.ReportingException; import com.documaster.validator.storage.core.Storage; /** * Noark Extraction Validator * Copyright (C) 2016, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.config.delegates; public class StorageConfiguration implements Delegate { private static final String STORAGE = "-storage"; @Parameter(names = STORAGE, description = "The storage type")
private Storage.StorageType storageType = Storage.StorageType.HSQLDB_IN_MEMORY;
documaster/noark-extraction-validator
noark-extraction-validator/src/main/java/com/documaster/validator/config/delegates/StorageConfiguration.java
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/exceptions/ReportingException.java // public class ReportingException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public ReportingException(String message) { // // super(message); // } // // public ReportingException(Throwable throwable) { // // super(throwable); // } // // public ReportingException(String message, Throwable throwable) { // // super(message, throwable); // } // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/storage/core/Storage.java // public abstract class Storage { // // private static final Logger LOGGER = LoggerFactory.getLogger(Storage.class); // // private static Storage instance; // // private StorageWriter writerThread; // // private LinkedBlockingQueue<Persistable> queue = new LinkedBlockingQueue<>(); // // /** // * < item definition full name , set of unique field names > // */ // protected Map<String, Set<String>> uniqueFields; // // protected Storage() { // // Prevent instantiation // } // // /** // * Creates a new concrete {@link Storage} instance via the {@link StorageFactory}, establishes a connection // * to the storage provider, and runs a separate thread that listens for actions. // * // * @param config // * The {@link StorageConfiguration} with which to instantiate the {@link Storage}. // * @param uniqueFields // * The name of the unique field in each table // */ // public static void init(StorageConfiguration config, Map<String, Set<String>> uniqueFields) throws Exception { // // LOGGER.info("Initializing storage ..."); // // instance = StorageFactory.createPersistence(config); // instance.uniqueFields = uniqueFields; // } // // public static Storage get() { // // return instance; // } // // /** // * Starts the {@link Storage}'s writer. // */ // public void startWriter() { // // writerThread = new StorageWriter(); // writerThread.start(); // } // // private boolean isWriteAvailable() { // // return writerThread != null && writerThread.isAlive(); // } // // /** // * Queues the specified {@link Persistable} object for writing. // * <p/> // * Writing a {@link StorageWriter#SHUTDOWN_SIGNAL} will send a shutdown signal to the writer. // */ // public void write(Persistable obj) { // // if (!isWriteAvailable()) { // throw new StorageException( // "The Storage writer is not listening. Most probably the writer " // + "thread encountered an unexpected error. Please verify the logs for more information."); // } // // queue.offer(obj); // } // // Persistable nextInWriteQueue() throws InterruptedException { // // return queue.take(); // } // // /** // * Sends a shut down signal to the {@link Storage}'s writer, waits for it to exit, and returns its exit status. // * // * @return <b>true</b> if the writer exists and no exceptions occurred during execution; <b>false</b> otherwise. // */ // public boolean stopWriter() { // // if (writerThread != null && isWriteAvailable()) { // // Send shut down signal to writer // write(StorageWriter.SHUTDOWN_SIGNAL); // // // Wait for the listener to exit // try { // writerThread.join(); // } catch (InterruptedException ex) { // // Ignore... someone else has interrupted the writer // } // } // // return writerThread != null && writerThread.getLastException() == null; // } // // public Exception getLastWriterException() { // // return writerThread.getLastException(); // } // // /** // * Establishes a connection to the implementation's storage provider. // */ // public abstract void connect() throws Exception; // // /** // * Indicates whether a connection is established and {@link Storage#fetch} can be invoked to retrieve data from the // * {@link Storage} implementation. // */ // public abstract boolean isReadAvailable(); // // /** // * Destroys the connection to the implementation's storage provider. // */ // public abstract void destroy(); // // protected abstract void writeItemDef(ItemDef itemDef) throws Exception; // // protected abstract void writeItem(Item item) throws Exception; // // /** // * Fetches the results of the specified query mapped as a list of {@link BaseItem}s. // */ // public abstract List<BaseItem> fetch(String query) throws Exception; // // public enum StorageType { // // HSQLDB_IN_MEMORY, HSQLDB_FILE, HSQLDB_SERVER // } // }
import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.documaster.validator.exceptions.ReportingException; import com.documaster.validator.storage.core.Storage;
public void setServerLocation(String serverLocation) { this.serverLocation = serverLocation; } @Override public void validate() { if (storageType == null) { throw new ParameterException(STORAGE + " must be specified."); } switch (storageType) { case HSQLDB_SERVER: if (serverLocation == null) { throw new ParameterException(SERVER_LOCATION + " must be specified"); } case HSQLDB_FILE: if (databaseDirLocation == null) { throw new ParameterException(DATABASE_DIR_LOCATION + " must be specified"); } case HSQLDB_IN_MEMORY: if (databaseName == null) { throw new ParameterException(DATABASE_NAME + " must be specified"); } break; default:
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/exceptions/ReportingException.java // public class ReportingException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public ReportingException(String message) { // // super(message); // } // // public ReportingException(Throwable throwable) { // // super(throwable); // } // // public ReportingException(String message, Throwable throwable) { // // super(message, throwable); // } // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/storage/core/Storage.java // public abstract class Storage { // // private static final Logger LOGGER = LoggerFactory.getLogger(Storage.class); // // private static Storage instance; // // private StorageWriter writerThread; // // private LinkedBlockingQueue<Persistable> queue = new LinkedBlockingQueue<>(); // // /** // * < item definition full name , set of unique field names > // */ // protected Map<String, Set<String>> uniqueFields; // // protected Storage() { // // Prevent instantiation // } // // /** // * Creates a new concrete {@link Storage} instance via the {@link StorageFactory}, establishes a connection // * to the storage provider, and runs a separate thread that listens for actions. // * // * @param config // * The {@link StorageConfiguration} with which to instantiate the {@link Storage}. // * @param uniqueFields // * The name of the unique field in each table // */ // public static void init(StorageConfiguration config, Map<String, Set<String>> uniqueFields) throws Exception { // // LOGGER.info("Initializing storage ..."); // // instance = StorageFactory.createPersistence(config); // instance.uniqueFields = uniqueFields; // } // // public static Storage get() { // // return instance; // } // // /** // * Starts the {@link Storage}'s writer. // */ // public void startWriter() { // // writerThread = new StorageWriter(); // writerThread.start(); // } // // private boolean isWriteAvailable() { // // return writerThread != null && writerThread.isAlive(); // } // // /** // * Queues the specified {@link Persistable} object for writing. // * <p/> // * Writing a {@link StorageWriter#SHUTDOWN_SIGNAL} will send a shutdown signal to the writer. // */ // public void write(Persistable obj) { // // if (!isWriteAvailable()) { // throw new StorageException( // "The Storage writer is not listening. Most probably the writer " // + "thread encountered an unexpected error. Please verify the logs for more information."); // } // // queue.offer(obj); // } // // Persistable nextInWriteQueue() throws InterruptedException { // // return queue.take(); // } // // /** // * Sends a shut down signal to the {@link Storage}'s writer, waits for it to exit, and returns its exit status. // * // * @return <b>true</b> if the writer exists and no exceptions occurred during execution; <b>false</b> otherwise. // */ // public boolean stopWriter() { // // if (writerThread != null && isWriteAvailable()) { // // Send shut down signal to writer // write(StorageWriter.SHUTDOWN_SIGNAL); // // // Wait for the listener to exit // try { // writerThread.join(); // } catch (InterruptedException ex) { // // Ignore... someone else has interrupted the writer // } // } // // return writerThread != null && writerThread.getLastException() == null; // } // // public Exception getLastWriterException() { // // return writerThread.getLastException(); // } // // /** // * Establishes a connection to the implementation's storage provider. // */ // public abstract void connect() throws Exception; // // /** // * Indicates whether a connection is established and {@link Storage#fetch} can be invoked to retrieve data from the // * {@link Storage} implementation. // */ // public abstract boolean isReadAvailable(); // // /** // * Destroys the connection to the implementation's storage provider. // */ // public abstract void destroy(); // // protected abstract void writeItemDef(ItemDef itemDef) throws Exception; // // protected abstract void writeItem(Item item) throws Exception; // // /** // * Fetches the results of the specified query mapped as a list of {@link BaseItem}s. // */ // public abstract List<BaseItem> fetch(String query) throws Exception; // // public enum StorageType { // // HSQLDB_IN_MEMORY, HSQLDB_FILE, HSQLDB_SERVER // } // } // Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/delegates/StorageConfiguration.java import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import com.documaster.validator.exceptions.ReportingException; import com.documaster.validator.storage.core.Storage; public void setServerLocation(String serverLocation) { this.serverLocation = serverLocation; } @Override public void validate() { if (storageType == null) { throw new ParameterException(STORAGE + " must be specified."); } switch (storageType) { case HSQLDB_SERVER: if (serverLocation == null) { throw new ParameterException(SERVER_LOCATION + " must be specified"); } case HSQLDB_FILE: if (databaseDirLocation == null) { throw new ParameterException(DATABASE_DIR_LOCATION + " must be specified"); } case HSQLDB_IN_MEMORY: if (databaseName == null) { throw new ParameterException(DATABASE_NAME + " must be specified"); } break; default:
throw new ReportingException("Unknown storage type: " + storageType);
documaster/noark-extraction-validator
noark-extraction-validator/src/main/java/com/documaster/validator/validation/utils/AbstractReusableXMLHandler.java
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/storage/model/BaseItem.java // public class BaseItem { // // private Map<String, Object> values; // // public Map<String, Object> getValues() { // // if (values == null) { // values = new LinkedHashMap<>(); // } // return values; // } // // public BaseItem add(String name, Object value) { // // getValues().put(name.toLowerCase(), value); // return this; // } // // @Override // public String toString() { // // StringBuilder builder = new StringBuilder("Item ["); // // for (Map.Entry<String, Object> entry : values.entrySet()) { // builder.append(String.format(" {%s, %s} ", entry.getKey(), entry.getValue())); // } // // builder.append(" ]"); // // return builder.toString(); // } // }
import java.util.Comparator; import java.util.List; import com.documaster.validator.storage.model.BaseItem; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler;
/** * Noark Extraction Validator * Copyright (C) 2017, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.validation.utils; /** * A reusable {@link DefaultHandler} implementation that adds a contract for retrieving the encountered exceptions as a * sorted list of {@link BaseItem}s. */ public abstract class AbstractReusableXMLHandler extends DefaultHandler { /** * Indicates whether the handler encountered any exceptions during parsing. */ public abstract boolean hasExceptions(); /** * Returns a summary of the encountered exceptions as {@link BaseItem}s. */
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/storage/model/BaseItem.java // public class BaseItem { // // private Map<String, Object> values; // // public Map<String, Object> getValues() { // // if (values == null) { // values = new LinkedHashMap<>(); // } // return values; // } // // public BaseItem add(String name, Object value) { // // getValues().put(name.toLowerCase(), value); // return this; // } // // @Override // public String toString() { // // StringBuilder builder = new StringBuilder("Item ["); // // for (Map.Entry<String, Object> entry : values.entrySet()) { // builder.append(String.format(" {%s, %s} ", entry.getKey(), entry.getValue())); // } // // builder.append(" ]"); // // return builder.toString(); // } // } // Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/utils/AbstractReusableXMLHandler.java import java.util.Comparator; import java.util.List; import com.documaster.validator.storage.model.BaseItem; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; /** * Noark Extraction Validator * Copyright (C) 2017, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.validation.utils; /** * A reusable {@link DefaultHandler} implementation that adds a contract for retrieving the encountered exceptions as a * sorted list of {@link BaseItem}s. */ public abstract class AbstractReusableXMLHandler extends DefaultHandler { /** * Indicates whether the handler encountered any exceptions during parsing. */ public abstract boolean hasExceptions(); /** * Returns a summary of the encountered exceptions as {@link BaseItem}s. */
public abstract List<BaseItem> getSummaryOfExceptionsAsItems();
documaster/noark-extraction-validator
noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/ValidationProvider.java
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/rules/Check.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement(name = "check") // public class Check extends Rule { // // @XmlElement(required = true, name = "queries") // protected Data data; // // public Data getData() { // // return data; // } // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/rules/Test.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement(name = "test") // public class Test extends Rule { // // @XmlElement(required = true, name = "queries") // protected ValidationData data; // // public ValidationData getData() { // // return data; // } // }
import java.util.Collections; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import com.documaster.validator.validation.noark5.provider.rules.Check; import com.documaster.validator.validation.noark5.provider.rules.Test;
/** * Noark Extraction Validator * Copyright (C) 2016, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.validation.noark5.provider; @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "validation") public class ValidationProvider { @XmlElement(required = true, name = "target") protected List<String> targets; @XmlElement(required = true, name = "test")
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/rules/Check.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement(name = "check") // public class Check extends Rule { // // @XmlElement(required = true, name = "queries") // protected Data data; // // public Data getData() { // // return data; // } // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/rules/Test.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement(name = "test") // public class Test extends Rule { // // @XmlElement(required = true, name = "queries") // protected ValidationData data; // // public ValidationData getData() { // // return data; // } // } // Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/ValidationProvider.java import java.util.Collections; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import com.documaster.validator.validation.noark5.provider.rules.Check; import com.documaster.validator.validation.noark5.provider.rules.Test; /** * Noark Extraction Validator * Copyright (C) 2016, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.validation.noark5.provider; @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "validation") public class ValidationProvider { @XmlElement(required = true, name = "target") protected List<String> targets; @XmlElement(required = true, name = "test")
protected List<Test> tests;
documaster/noark-extraction-validator
noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/ValidationProvider.java
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/rules/Check.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement(name = "check") // public class Check extends Rule { // // @XmlElement(required = true, name = "queries") // protected Data data; // // public Data getData() { // // return data; // } // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/rules/Test.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement(name = "test") // public class Test extends Rule { // // @XmlElement(required = true, name = "queries") // protected ValidationData data; // // public ValidationData getData() { // // return data; // } // }
import java.util.Collections; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import com.documaster.validator.validation.noark5.provider.rules.Check; import com.documaster.validator.validation.noark5.provider.rules.Test;
/** * Noark Extraction Validator * Copyright (C) 2016, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.validation.noark5.provider; @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "validation") public class ValidationProvider { @XmlElement(required = true, name = "target") protected List<String> targets; @XmlElement(required = true, name = "test") protected List<Test> tests; @XmlElement(required = true, name = "check")
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/rules/Check.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement(name = "check") // public class Check extends Rule { // // @XmlElement(required = true, name = "queries") // protected Data data; // // public Data getData() { // // return data; // } // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/rules/Test.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement(name = "test") // public class Test extends Rule { // // @XmlElement(required = true, name = "queries") // protected ValidationData data; // // public ValidationData getData() { // // return data; // } // } // Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/ValidationProvider.java import java.util.Collections; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import com.documaster.validator.validation.noark5.provider.rules.Check; import com.documaster.validator.validation.noark5.provider.rules.Test; /** * Noark Extraction Validator * Copyright (C) 2016, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.validation.noark5.provider; @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "validation") public class ValidationProvider { @XmlElement(required = true, name = "target") protected List<String> targets; @XmlElement(required = true, name = "test") protected List<Test> tests; @XmlElement(required = true, name = "check")
protected List<Check> checks;
documaster/noark-extraction-validator
noark-extraction-validator/src/main/java/com/documaster/validator/validation/collector/ValidationResult.java
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/storage/model/BaseItem.java // public class BaseItem { // // private Map<String, Object> values; // // public Map<String, Object> getValues() { // // if (values == null) { // values = new LinkedHashMap<>(); // } // return values; // } // // public BaseItem add(String name, Object value) { // // getValues().put(name.toLowerCase(), value); // return this; // } // // @Override // public String toString() { // // StringBuilder builder = new StringBuilder("Item ["); // // for (Map.Entry<String, Object> entry : values.entrySet()) { // builder.append(String.format(" {%s, %s} ", entry.getKey(), entry.getValue())); // } // // builder.append(" ]"); // // return builder.toString(); // } // }
import java.util.ArrayList; import java.util.List; import com.documaster.validator.storage.model.BaseItem;
/** * Noark Extraction Validator * Copyright (C) 2017, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.validation.collector; public class ValidationResult { private String id; private String title; private String description; private String groupName;
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/storage/model/BaseItem.java // public class BaseItem { // // private Map<String, Object> values; // // public Map<String, Object> getValues() { // // if (values == null) { // values = new LinkedHashMap<>(); // } // return values; // } // // public BaseItem add(String name, Object value) { // // getValues().put(name.toLowerCase(), value); // return this; // } // // @Override // public String toString() { // // StringBuilder builder = new StringBuilder("Item ["); // // for (Map.Entry<String, Object> entry : values.entrySet()) { // builder.append(String.format(" {%s, %s} ", entry.getKey(), entry.getValue())); // } // // builder.append(" ]"); // // return builder.toString(); // } // } // Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/collector/ValidationResult.java import java.util.ArrayList; import java.util.List; import com.documaster.validator.storage.model.BaseItem; /** * Noark Extraction Validator * Copyright (C) 2017, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.validation.collector; public class ValidationResult { private String id; private String title; private String description; private String groupName;
private List<BaseItem> summary = new ArrayList<>();
documaster/noark-extraction-validator
noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/rules/Test.java
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/data/ValidationData.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement(name = "queries") // public class ValidationData extends Data { // // @XmlElement(name = "warnings") // private String warningsRequest; // // @XmlElement(name = "errors") // private String errorsRequest; // // public String getWarningsRequest() { // // return warningsRequest; // } // // public String getErrorsRequest() { // // return errorsRequest; // } // }
import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import com.documaster.validator.validation.noark5.provider.data.ValidationData;
/** * Noark Extraction Validator * Copyright (C) 2017, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.validation.noark5.provider.rules; @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "test") public class Test extends Rule { @XmlElement(required = true, name = "queries")
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/data/ValidationData.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement(name = "queries") // public class ValidationData extends Data { // // @XmlElement(name = "warnings") // private String warningsRequest; // // @XmlElement(name = "errors") // private String errorsRequest; // // public String getWarningsRequest() { // // return warningsRequest; // } // // public String getErrorsRequest() { // // return errorsRequest; // } // } // Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/rules/Test.java import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import com.documaster.validator.validation.noark5.provider.data.ValidationData; /** * Noark Extraction Validator * Copyright (C) 2017, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.validation.noark5.provider.rules; @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "test") public class Test extends Rule { @XmlElement(required = true, name = "queries")
protected ValidationData data;
documaster/noark-extraction-validator
noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/rules/Check.java
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/data/Data.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement(name = "queries") // public class Data { // // @XmlElement(required = true, name = "info") // private String infoRequest; // // public String getInfoRequest() { // // return infoRequest; // } // }
import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import com.documaster.validator.validation.noark5.provider.data.Data;
/** * Noark Extraction Validator * Copyright (C) 2016, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.validation.noark5.provider.rules; @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "check") public class Check extends Rule { @XmlElement(required = true, name = "queries")
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/data/Data.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlRootElement(name = "queries") // public class Data { // // @XmlElement(required = true, name = "info") // private String infoRequest; // // public String getInfoRequest() { // // return infoRequest; // } // } // Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/noark5/provider/rules/Check.java import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import com.documaster.validator.validation.noark5.provider.data.Data; /** * Noark Extraction Validator * Copyright (C) 2016, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.validation.noark5.provider.rules; @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "check") public class Check extends Rule { @XmlElement(required = true, name = "queries")
protected Data data;
documaster/noark-extraction-validator
noark-extraction-validator/src/main/java/com/documaster/validator/reporting/excel/ExcelUtils.java
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/exceptions/ReportingException.java // public class ReportingException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public ReportingException(String message) { // // super(message); // } // // public ReportingException(Throwable throwable) { // // super(throwable); // } // // public ReportingException(String message, Throwable throwable) { // // super(message, throwable); // } // }
import java.text.MessageFormat; import java.util.EnumSet; import com.documaster.validator.exceptions.ReportingException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.Hyperlink; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.streaming.SXSSFSheet;
style.setAlignment(CellStyle.ALIGN_LEFT); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); return style; } public static void addBorderToStyle(EnumSet<BorderPosition> borderPositions, IndexedColors color, CellStyle style) { for (BorderPosition position : borderPositions) { switch (position) { case TOP: style.setBorderTop(CellStyle.BORDER_THIN); style.setTopBorderColor(color.getIndex()); break; case BOTTOM: style.setBorderBottom(CellStyle.BORDER_THIN); style.setBottomBorderColor(color.getIndex()); break; case LEFT: style.setBorderLeft(CellStyle.BORDER_THIN); style.setLeftBorderColor(color.getIndex()); break; case RIGHT: style.setBorderRight(CellStyle.BORDER_THIN); style.setRightBorderColor(color.getIndex()); break; default:
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/exceptions/ReportingException.java // public class ReportingException extends RuntimeException { // // private static final long serialVersionUID = 1L; // // public ReportingException(String message) { // // super(message); // } // // public ReportingException(Throwable throwable) { // // super(throwable); // } // // public ReportingException(String message, Throwable throwable) { // // super(message, throwable); // } // } // Path: noark-extraction-validator/src/main/java/com/documaster/validator/reporting/excel/ExcelUtils.java import java.text.MessageFormat; import java.util.EnumSet; import com.documaster.validator.exceptions.ReportingException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.Hyperlink; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.streaming.SXSSFSheet; style.setAlignment(CellStyle.ALIGN_LEFT); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); return style; } public static void addBorderToStyle(EnumSet<BorderPosition> borderPositions, IndexedColors color, CellStyle style) { for (BorderPosition position : borderPositions) { switch (position) { case TOP: style.setBorderTop(CellStyle.BORDER_THIN); style.setTopBorderColor(color.getIndex()); break; case BOTTOM: style.setBorderBottom(CellStyle.BORDER_THIN); style.setBottomBorderColor(color.getIndex()); break; case LEFT: style.setBorderLeft(CellStyle.BORDER_THIN); style.setLeftBorderColor(color.getIndex()); break; case RIGHT: style.setBorderRight(CellStyle.BORDER_THIN); style.setRightBorderColor(color.getIndex()); break; default:
throw new ReportingException("Unknown border position: " + position);
documaster/noark-extraction-validator
noark-extraction-validator/src/main/java/com/documaster/validator/validation/ValidatorType.java
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/commands/Noark53Command.java // @Parameters(commandNames = Noark53Command.COMMAND_NAME, // commandDescription = "Validates a Noark 5.3 extraction package.") // public class Noark53Command extends Noark5Command { // // public static final String COMMAND_NAME = "noark53"; // private static final String NOARK_VERSION = "5.3"; // // public Noark53Command() { // // super(COMMAND_NAME, NOARK_VERSION); // } // // public Noark53Command(JCommander argParser) { // // super(argParser, COMMAND_NAME, NOARK_VERSION); // } // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/commands/Noark54Command.java // @Parameters(commandNames = Noark54Command.COMMAND_NAME, // commandDescription = "Validates a Noark 5.4 extraction package.") // public class Noark54Command extends Noark5Command { // // public static final String COMMAND_NAME = "noark54"; // private static final String NOARK_VERSION = "5.4"; // // public Noark54Command() { // // super(COMMAND_NAME, NOARK_VERSION); // } // // public Noark54Command(JCommander argParser) { // // super(argParser, COMMAND_NAME, NOARK_VERSION); // } // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/commands/Noark55Command.java // @Parameters(commandNames = Noark55Command.COMMAND_NAME, // commandDescription = "Validates a Noark 5.5 extraction package.") // public class Noark55Command extends Noark5Command { // // public static final String COMMAND_NAME = "noark55"; // private static final String NOARK_VERSION = "5.5"; // // public Noark55Command() { // // super(COMMAND_NAME, NOARK_VERSION); // } // // public Noark55Command(JCommander argParser) { // // super(argParser, COMMAND_NAME, NOARK_VERSION); // } // }
import java.util.HashMap; import java.util.Map; import com.documaster.validator.config.commands.Noark53Command; import com.documaster.validator.config.commands.Noark54Command; import com.documaster.validator.config.commands.Noark55Command;
/** * Noark Extraction Validator * Copyright (C) 2016, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.validation; public enum ValidatorType { NOARK53(Noark53Command.COMMAND_NAME),
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/commands/Noark53Command.java // @Parameters(commandNames = Noark53Command.COMMAND_NAME, // commandDescription = "Validates a Noark 5.3 extraction package.") // public class Noark53Command extends Noark5Command { // // public static final String COMMAND_NAME = "noark53"; // private static final String NOARK_VERSION = "5.3"; // // public Noark53Command() { // // super(COMMAND_NAME, NOARK_VERSION); // } // // public Noark53Command(JCommander argParser) { // // super(argParser, COMMAND_NAME, NOARK_VERSION); // } // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/commands/Noark54Command.java // @Parameters(commandNames = Noark54Command.COMMAND_NAME, // commandDescription = "Validates a Noark 5.4 extraction package.") // public class Noark54Command extends Noark5Command { // // public static final String COMMAND_NAME = "noark54"; // private static final String NOARK_VERSION = "5.4"; // // public Noark54Command() { // // super(COMMAND_NAME, NOARK_VERSION); // } // // public Noark54Command(JCommander argParser) { // // super(argParser, COMMAND_NAME, NOARK_VERSION); // } // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/commands/Noark55Command.java // @Parameters(commandNames = Noark55Command.COMMAND_NAME, // commandDescription = "Validates a Noark 5.5 extraction package.") // public class Noark55Command extends Noark5Command { // // public static final String COMMAND_NAME = "noark55"; // private static final String NOARK_VERSION = "5.5"; // // public Noark55Command() { // // super(COMMAND_NAME, NOARK_VERSION); // } // // public Noark55Command(JCommander argParser) { // // super(argParser, COMMAND_NAME, NOARK_VERSION); // } // } // Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/ValidatorType.java import java.util.HashMap; import java.util.Map; import com.documaster.validator.config.commands.Noark53Command; import com.documaster.validator.config.commands.Noark54Command; import com.documaster.validator.config.commands.Noark55Command; /** * Noark Extraction Validator * Copyright (C) 2016, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.validation; public enum ValidatorType { NOARK53(Noark53Command.COMMAND_NAME),
NOARK54(Noark54Command.COMMAND_NAME),
documaster/noark-extraction-validator
noark-extraction-validator/src/main/java/com/documaster/validator/validation/ValidatorType.java
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/commands/Noark53Command.java // @Parameters(commandNames = Noark53Command.COMMAND_NAME, // commandDescription = "Validates a Noark 5.3 extraction package.") // public class Noark53Command extends Noark5Command { // // public static final String COMMAND_NAME = "noark53"; // private static final String NOARK_VERSION = "5.3"; // // public Noark53Command() { // // super(COMMAND_NAME, NOARK_VERSION); // } // // public Noark53Command(JCommander argParser) { // // super(argParser, COMMAND_NAME, NOARK_VERSION); // } // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/commands/Noark54Command.java // @Parameters(commandNames = Noark54Command.COMMAND_NAME, // commandDescription = "Validates a Noark 5.4 extraction package.") // public class Noark54Command extends Noark5Command { // // public static final String COMMAND_NAME = "noark54"; // private static final String NOARK_VERSION = "5.4"; // // public Noark54Command() { // // super(COMMAND_NAME, NOARK_VERSION); // } // // public Noark54Command(JCommander argParser) { // // super(argParser, COMMAND_NAME, NOARK_VERSION); // } // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/commands/Noark55Command.java // @Parameters(commandNames = Noark55Command.COMMAND_NAME, // commandDescription = "Validates a Noark 5.5 extraction package.") // public class Noark55Command extends Noark5Command { // // public static final String COMMAND_NAME = "noark55"; // private static final String NOARK_VERSION = "5.5"; // // public Noark55Command() { // // super(COMMAND_NAME, NOARK_VERSION); // } // // public Noark55Command(JCommander argParser) { // // super(argParser, COMMAND_NAME, NOARK_VERSION); // } // }
import java.util.HashMap; import java.util.Map; import com.documaster.validator.config.commands.Noark53Command; import com.documaster.validator.config.commands.Noark54Command; import com.documaster.validator.config.commands.Noark55Command;
/** * Noark Extraction Validator * Copyright (C) 2016, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.validation; public enum ValidatorType { NOARK53(Noark53Command.COMMAND_NAME), NOARK54(Noark54Command.COMMAND_NAME),
// Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/commands/Noark53Command.java // @Parameters(commandNames = Noark53Command.COMMAND_NAME, // commandDescription = "Validates a Noark 5.3 extraction package.") // public class Noark53Command extends Noark5Command { // // public static final String COMMAND_NAME = "noark53"; // private static final String NOARK_VERSION = "5.3"; // // public Noark53Command() { // // super(COMMAND_NAME, NOARK_VERSION); // } // // public Noark53Command(JCommander argParser) { // // super(argParser, COMMAND_NAME, NOARK_VERSION); // } // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/commands/Noark54Command.java // @Parameters(commandNames = Noark54Command.COMMAND_NAME, // commandDescription = "Validates a Noark 5.4 extraction package.") // public class Noark54Command extends Noark5Command { // // public static final String COMMAND_NAME = "noark54"; // private static final String NOARK_VERSION = "5.4"; // // public Noark54Command() { // // super(COMMAND_NAME, NOARK_VERSION); // } // // public Noark54Command(JCommander argParser) { // // super(argParser, COMMAND_NAME, NOARK_VERSION); // } // } // // Path: noark-extraction-validator/src/main/java/com/documaster/validator/config/commands/Noark55Command.java // @Parameters(commandNames = Noark55Command.COMMAND_NAME, // commandDescription = "Validates a Noark 5.5 extraction package.") // public class Noark55Command extends Noark5Command { // // public static final String COMMAND_NAME = "noark55"; // private static final String NOARK_VERSION = "5.5"; // // public Noark55Command() { // // super(COMMAND_NAME, NOARK_VERSION); // } // // public Noark55Command(JCommander argParser) { // // super(argParser, COMMAND_NAME, NOARK_VERSION); // } // } // Path: noark-extraction-validator/src/main/java/com/documaster/validator/validation/ValidatorType.java import java.util.HashMap; import java.util.Map; import com.documaster.validator.config.commands.Noark53Command; import com.documaster.validator.config.commands.Noark54Command; import com.documaster.validator.config.commands.Noark55Command; /** * Noark Extraction Validator * Copyright (C) 2016, Documaster AS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.documaster.validator.validation; public enum ValidatorType { NOARK53(Noark53Command.COMMAND_NAME), NOARK54(Noark54Command.COMMAND_NAME),
NOARK55(Noark55Command.COMMAND_NAME);
MovingBlocks/TerasologyLauncher
src/test/java/org/terasology/launcher/game/TestGameStarter.java
// Path: src/main/java/org/terasology/launcher/util/JavaHeapSize.java // public enum JavaHeapSize { // // NOT_USED("", "heapsize_notUsed"), // MB_256("256m", "heapsize_mb_256"), // MB_512("512m", "heapsize_mb_512"), // MB_768("768m", "heapsize_mb_768"), // GB_1("1g", "heapsize_gb_1"), // GB_1_5("1536m", "heapsize_gb_1_5"), // GB_2("2g", "heapsize_gb_2"), // GB_2_5("2560m", "heapsize_gb_2_5"), // GB_3("3g", "heapsize_gb_3"), // GB_4("4g", "heapsize_gb_4"), // GB_5("5g", "heapsize_gb_5"), // GB_6("6g", "heapsize_gb_6"), // GB_7("7g", "heapsize_gb_7"), // GB_8("8g", "heapsize_gb_8"), // GB_9("9g", "heapsize_gb_9"), // GB_10("10g", "heapsize_gb_10"), // GB_11("11g", "heapsize_gb_11"), // GB_12("12g", "heapsize_gb_12"), // GB_13("13g", "heapsize_gb_13"), // GB_14("14g", "heapsize_gb_14"), // GB_15("15g", "heapsize_gb_15"), // GB_16("16g", "heapsize_gb_16"); // // private final String sizeParameter; // private final String labelKey; // // JavaHeapSize(String sizeParameter, String labelKey) { // this.sizeParameter = sizeParameter; // this.labelKey = labelKey; // } // // public final boolean isUsed() { // return this != NOT_USED; // } // // public final String getSizeParameter() { // return sizeParameter; // } // // @Override // public final String toString() { // return BundleUtils.getLabel(labelKey); // } // } // // Path: src/test/java/org/terasology/launcher/Matchers.java // public static <T> Matcher<Iterable<? super T>> hasItemsFrom(Collection<T> items) { // /* org.hamcrest.Matchers.hasItems(T...) takes variable arguments, so if // * we want to match against a list, we reimplement it. // */ // return new AllOf<>(items.stream().map( // IsIterableContaining::hasItem // ).collect(Collectors.toUnmodifiableList())); // }
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.event.Level; import org.terasology.launcher.util.JavaHeapSize; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Path; import java.util.List; import java.util.stream.Stream; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.terasology.launcher.Matchers.hasItemsFrom;
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.game; public class TestGameStarter { static final String JAVA_ARG_1 = "-client"; static final String JAVA_ARG_2 = "--enable-preview"; static final String GAME_ARG_1 = "--no-splash"; static final String GAME_DIR = "game"; static final String GAME_DATA_DIR = "game_data";
// Path: src/main/java/org/terasology/launcher/util/JavaHeapSize.java // public enum JavaHeapSize { // // NOT_USED("", "heapsize_notUsed"), // MB_256("256m", "heapsize_mb_256"), // MB_512("512m", "heapsize_mb_512"), // MB_768("768m", "heapsize_mb_768"), // GB_1("1g", "heapsize_gb_1"), // GB_1_5("1536m", "heapsize_gb_1_5"), // GB_2("2g", "heapsize_gb_2"), // GB_2_5("2560m", "heapsize_gb_2_5"), // GB_3("3g", "heapsize_gb_3"), // GB_4("4g", "heapsize_gb_4"), // GB_5("5g", "heapsize_gb_5"), // GB_6("6g", "heapsize_gb_6"), // GB_7("7g", "heapsize_gb_7"), // GB_8("8g", "heapsize_gb_8"), // GB_9("9g", "heapsize_gb_9"), // GB_10("10g", "heapsize_gb_10"), // GB_11("11g", "heapsize_gb_11"), // GB_12("12g", "heapsize_gb_12"), // GB_13("13g", "heapsize_gb_13"), // GB_14("14g", "heapsize_gb_14"), // GB_15("15g", "heapsize_gb_15"), // GB_16("16g", "heapsize_gb_16"); // // private final String sizeParameter; // private final String labelKey; // // JavaHeapSize(String sizeParameter, String labelKey) { // this.sizeParameter = sizeParameter; // this.labelKey = labelKey; // } // // public final boolean isUsed() { // return this != NOT_USED; // } // // public final String getSizeParameter() { // return sizeParameter; // } // // @Override // public final String toString() { // return BundleUtils.getLabel(labelKey); // } // } // // Path: src/test/java/org/terasology/launcher/Matchers.java // public static <T> Matcher<Iterable<? super T>> hasItemsFrom(Collection<T> items) { // /* org.hamcrest.Matchers.hasItems(T...) takes variable arguments, so if // * we want to match against a list, we reimplement it. // */ // return new AllOf<>(items.stream().map( // IsIterableContaining::hasItem // ).collect(Collectors.toUnmodifiableList())); // } // Path: src/test/java/org/terasology/launcher/game/TestGameStarter.java import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.event.Level; import org.terasology.launcher.util.JavaHeapSize; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Path; import java.util.List; import java.util.stream.Stream; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.terasology.launcher.Matchers.hasItemsFrom; // Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.game; public class TestGameStarter { static final String JAVA_ARG_1 = "-client"; static final String JAVA_ARG_2 = "--enable-preview"; static final String GAME_ARG_1 = "--no-splash"; static final String GAME_DIR = "game"; static final String GAME_DATA_DIR = "game_data";
static final JavaHeapSize HEAP_MIN = JavaHeapSize.NOT_USED;
MovingBlocks/TerasologyLauncher
src/test/java/org/terasology/launcher/game/TestGameStarter.java
// Path: src/main/java/org/terasology/launcher/util/JavaHeapSize.java // public enum JavaHeapSize { // // NOT_USED("", "heapsize_notUsed"), // MB_256("256m", "heapsize_mb_256"), // MB_512("512m", "heapsize_mb_512"), // MB_768("768m", "heapsize_mb_768"), // GB_1("1g", "heapsize_gb_1"), // GB_1_5("1536m", "heapsize_gb_1_5"), // GB_2("2g", "heapsize_gb_2"), // GB_2_5("2560m", "heapsize_gb_2_5"), // GB_3("3g", "heapsize_gb_3"), // GB_4("4g", "heapsize_gb_4"), // GB_5("5g", "heapsize_gb_5"), // GB_6("6g", "heapsize_gb_6"), // GB_7("7g", "heapsize_gb_7"), // GB_8("8g", "heapsize_gb_8"), // GB_9("9g", "heapsize_gb_9"), // GB_10("10g", "heapsize_gb_10"), // GB_11("11g", "heapsize_gb_11"), // GB_12("12g", "heapsize_gb_12"), // GB_13("13g", "heapsize_gb_13"), // GB_14("14g", "heapsize_gb_14"), // GB_15("15g", "heapsize_gb_15"), // GB_16("16g", "heapsize_gb_16"); // // private final String sizeParameter; // private final String labelKey; // // JavaHeapSize(String sizeParameter, String labelKey) { // this.sizeParameter = sizeParameter; // this.labelKey = labelKey; // } // // public final boolean isUsed() { // return this != NOT_USED; // } // // public final String getSizeParameter() { // return sizeParameter; // } // // @Override // public final String toString() { // return BundleUtils.getLabel(labelKey); // } // } // // Path: src/test/java/org/terasology/launcher/Matchers.java // public static <T> Matcher<Iterable<? super T>> hasItemsFrom(Collection<T> items) { // /* org.hamcrest.Matchers.hasItems(T...) takes variable arguments, so if // * we want to match against a list, we reimplement it. // */ // return new AllOf<>(items.stream().map( // IsIterableContaining::hasItem // ).collect(Collectors.toUnmodifiableList())); // }
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.event.Level; import org.terasology.launcher.util.JavaHeapSize; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Path; import java.util.List; import java.util.stream.Stream; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.terasology.launcher.Matchers.hasItemsFrom;
GameStarter starter = newStarter(); assertNotNull(starter); } @Test public void testJre() throws IOException { GameStarter task = newStarter(); // This is the sort of test where the code under test and the expectation are just copies // of the same source. But since there's a plan to separate the launcher runtime from the // game runtime, the runtime location seemed like a good thing to specify in its own test. assertTrue(task.getRuntimePath().startsWith(Path.of(System.getProperty("java.home")))); } static Stream<Arguments> provideJarPaths() { return Stream.of( Arguments.of(Path.of("libs", "Terasology.jar")), Arguments.of(Path.of("Terasology-5.2.0-SNAPSHOT", "lib", "Terasology.jar")) ); } @ParameterizedTest @MethodSource("provideJarPaths") public void testBuildProcess(Path jarRelativePath) throws IOException { GameStarter starter = newStarter(jarRelativePath); ProcessBuilder processBuilder = starter.processBuilder; final Path gameJar = gamePath.resolve(jarRelativePath); assertNotNull(processBuilder.directory()); assertEquals(gamePath, processBuilder.directory().toPath()); assertThat(processBuilder.command(), hasItem(gameJar.toString()));
// Path: src/main/java/org/terasology/launcher/util/JavaHeapSize.java // public enum JavaHeapSize { // // NOT_USED("", "heapsize_notUsed"), // MB_256("256m", "heapsize_mb_256"), // MB_512("512m", "heapsize_mb_512"), // MB_768("768m", "heapsize_mb_768"), // GB_1("1g", "heapsize_gb_1"), // GB_1_5("1536m", "heapsize_gb_1_5"), // GB_2("2g", "heapsize_gb_2"), // GB_2_5("2560m", "heapsize_gb_2_5"), // GB_3("3g", "heapsize_gb_3"), // GB_4("4g", "heapsize_gb_4"), // GB_5("5g", "heapsize_gb_5"), // GB_6("6g", "heapsize_gb_6"), // GB_7("7g", "heapsize_gb_7"), // GB_8("8g", "heapsize_gb_8"), // GB_9("9g", "heapsize_gb_9"), // GB_10("10g", "heapsize_gb_10"), // GB_11("11g", "heapsize_gb_11"), // GB_12("12g", "heapsize_gb_12"), // GB_13("13g", "heapsize_gb_13"), // GB_14("14g", "heapsize_gb_14"), // GB_15("15g", "heapsize_gb_15"), // GB_16("16g", "heapsize_gb_16"); // // private final String sizeParameter; // private final String labelKey; // // JavaHeapSize(String sizeParameter, String labelKey) { // this.sizeParameter = sizeParameter; // this.labelKey = labelKey; // } // // public final boolean isUsed() { // return this != NOT_USED; // } // // public final String getSizeParameter() { // return sizeParameter; // } // // @Override // public final String toString() { // return BundleUtils.getLabel(labelKey); // } // } // // Path: src/test/java/org/terasology/launcher/Matchers.java // public static <T> Matcher<Iterable<? super T>> hasItemsFrom(Collection<T> items) { // /* org.hamcrest.Matchers.hasItems(T...) takes variable arguments, so if // * we want to match against a list, we reimplement it. // */ // return new AllOf<>(items.stream().map( // IsIterableContaining::hasItem // ).collect(Collectors.toUnmodifiableList())); // } // Path: src/test/java/org/terasology/launcher/game/TestGameStarter.java import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.event.Level; import org.terasology.launcher.util.JavaHeapSize; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Path; import java.util.List; import java.util.stream.Stream; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.terasology.launcher.Matchers.hasItemsFrom; GameStarter starter = newStarter(); assertNotNull(starter); } @Test public void testJre() throws IOException { GameStarter task = newStarter(); // This is the sort of test where the code under test and the expectation are just copies // of the same source. But since there's a plan to separate the launcher runtime from the // game runtime, the runtime location seemed like a good thing to specify in its own test. assertTrue(task.getRuntimePath().startsWith(Path.of(System.getProperty("java.home")))); } static Stream<Arguments> provideJarPaths() { return Stream.of( Arguments.of(Path.of("libs", "Terasology.jar")), Arguments.of(Path.of("Terasology-5.2.0-SNAPSHOT", "lib", "Terasology.jar")) ); } @ParameterizedTest @MethodSource("provideJarPaths") public void testBuildProcess(Path jarRelativePath) throws IOException { GameStarter starter = newStarter(jarRelativePath); ProcessBuilder processBuilder = starter.processBuilder; final Path gameJar = gamePath.resolve(jarRelativePath); assertNotNull(processBuilder.directory()); assertEquals(gamePath, processBuilder.directory().toPath()); assertThat(processBuilder.command(), hasItem(gameJar.toString()));
assertThat(processBuilder.command(), hasItemsFrom(gameParams));
MovingBlocks/TerasologyLauncher
src/test/java/org/terasology/launcher/repositories/JenkinsRepositoryAdapterTest.java
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // }
import com.google.gson.Gson; import com.vdurmont.semver4j.Semver; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.net.MalformedURLException; import java.net.URL; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue;
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.repositories; @DisplayName("JenkinsRepositoryAdapter#fetchReleases() should") class JenkinsRepositoryAdapterTest { static Gson gson; static Jenkins.ApiResult validResult; static URL expectedArtifactUrl; static List<Jenkins.ApiResult> incompleteResults; @BeforeAll static void setup() throws MalformedURLException { gson = new Gson(); validResult = gson.fromJson(JenkinsPayload.V2.validPayload(), Jenkins.ApiResult.class); incompleteResults = JenkinsPayload.V2.incompletePayloads().stream() .map(json -> gson.fromJson(json, Jenkins.ApiResult.class)) .collect(Collectors.toList()); expectedArtifactUrl = new URL("http://jenkins.terasology.io/teraorg/job/Nanoware/job/Omega/job/develop/1/" + "artifact/" + "distros/omega/build/distributions/TerasologyOmega.zip"); } static Stream<Arguments> incompleteResults() { return incompleteResults.stream().map(Arguments::of); } @Test @DisplayName("handle null Jenkins response gracefully") void handleNullJenkinsResponseGracefully() { final JenkinsClient nullClient = new StubJenkinsClient(url -> null, url -> null);
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // } // Path: src/test/java/org/terasology/launcher/repositories/JenkinsRepositoryAdapterTest.java import com.google.gson.Gson; import com.vdurmont.semver4j.Semver; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.net.MalformedURLException; import java.net.URL; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; // Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.repositories; @DisplayName("JenkinsRepositoryAdapter#fetchReleases() should") class JenkinsRepositoryAdapterTest { static Gson gson; static Jenkins.ApiResult validResult; static URL expectedArtifactUrl; static List<Jenkins.ApiResult> incompleteResults; @BeforeAll static void setup() throws MalformedURLException { gson = new Gson(); validResult = gson.fromJson(JenkinsPayload.V2.validPayload(), Jenkins.ApiResult.class); incompleteResults = JenkinsPayload.V2.incompletePayloads().stream() .map(json -> gson.fromJson(json, Jenkins.ApiResult.class)) .collect(Collectors.toList()); expectedArtifactUrl = new URL("http://jenkins.terasology.io/teraorg/job/Nanoware/job/Omega/job/develop/1/" + "artifact/" + "distros/omega/build/distributions/TerasologyOmega.zip"); } static Stream<Arguments> incompleteResults() { return incompleteResults.stream().map(Arguments::of); } @Test @DisplayName("handle null Jenkins response gracefully") void handleNullJenkinsResponseGracefully() { final JenkinsClient nullClient = new StubJenkinsClient(url -> null, url -> null);
final JenkinsRepositoryAdapter adapter = new JenkinsRepositoryAdapter(Profile.OMEGA, Build.STABLE, nullClient);
MovingBlocks/TerasologyLauncher
src/test/java/org/terasology/launcher/repositories/JenkinsRepositoryAdapterTest.java
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // }
import com.google.gson.Gson; import com.vdurmont.semver4j.Semver; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.net.MalformedURLException; import java.net.URL; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue;
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.repositories; @DisplayName("JenkinsRepositoryAdapter#fetchReleases() should") class JenkinsRepositoryAdapterTest { static Gson gson; static Jenkins.ApiResult validResult; static URL expectedArtifactUrl; static List<Jenkins.ApiResult> incompleteResults; @BeforeAll static void setup() throws MalformedURLException { gson = new Gson(); validResult = gson.fromJson(JenkinsPayload.V2.validPayload(), Jenkins.ApiResult.class); incompleteResults = JenkinsPayload.V2.incompletePayloads().stream() .map(json -> gson.fromJson(json, Jenkins.ApiResult.class)) .collect(Collectors.toList()); expectedArtifactUrl = new URL("http://jenkins.terasology.io/teraorg/job/Nanoware/job/Omega/job/develop/1/" + "artifact/" + "distros/omega/build/distributions/TerasologyOmega.zip"); } static Stream<Arguments> incompleteResults() { return incompleteResults.stream().map(Arguments::of); } @Test @DisplayName("handle null Jenkins response gracefully") void handleNullJenkinsResponseGracefully() { final JenkinsClient nullClient = new StubJenkinsClient(url -> null, url -> null);
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // } // Path: src/test/java/org/terasology/launcher/repositories/JenkinsRepositoryAdapterTest.java import com.google.gson.Gson; import com.vdurmont.semver4j.Semver; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.net.MalformedURLException; import java.net.URL; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; // Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.repositories; @DisplayName("JenkinsRepositoryAdapter#fetchReleases() should") class JenkinsRepositoryAdapterTest { static Gson gson; static Jenkins.ApiResult validResult; static URL expectedArtifactUrl; static List<Jenkins.ApiResult> incompleteResults; @BeforeAll static void setup() throws MalformedURLException { gson = new Gson(); validResult = gson.fromJson(JenkinsPayload.V2.validPayload(), Jenkins.ApiResult.class); incompleteResults = JenkinsPayload.V2.incompletePayloads().stream() .map(json -> gson.fromJson(json, Jenkins.ApiResult.class)) .collect(Collectors.toList()); expectedArtifactUrl = new URL("http://jenkins.terasology.io/teraorg/job/Nanoware/job/Omega/job/develop/1/" + "artifact/" + "distros/omega/build/distributions/TerasologyOmega.zip"); } static Stream<Arguments> incompleteResults() { return incompleteResults.stream().map(Arguments::of); } @Test @DisplayName("handle null Jenkins response gracefully") void handleNullJenkinsResponseGracefully() { final JenkinsClient nullClient = new StubJenkinsClient(url -> null, url -> null);
final JenkinsRepositoryAdapter adapter = new JenkinsRepositoryAdapter(Profile.OMEGA, Build.STABLE, nullClient);
MovingBlocks/TerasologyLauncher
src/test/java/org/terasology/launcher/repositories/JenkinsRepositoryAdapterTest.java
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // }
import com.google.gson.Gson; import com.vdurmont.semver4j.Semver; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.net.MalformedURLException; import java.net.URL; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue;
@Test @DisplayName("skip builds without version info") void skipBuildsWithoutVersionInfo() { Properties emptyVersionInfo = new Properties(); final JenkinsClient stubClient = new StubJenkinsClient(url -> validResult, url -> emptyVersionInfo); final JenkinsRepositoryAdapter adapter = new JenkinsRepositoryAdapter(Profile.OMEGA, Build.STABLE, stubClient); assertTrue(adapter.fetchReleases().isEmpty()); } @Test @DisplayName("process valid response correctly") void processValidResponseCorrectly() { String displayVersion = "alpha 42 (preview)"; Semver engineVersion = new Semver("5.0.1-SNAPSHOT", Semver.SemverType.IVY); Properties versionInfo = new Properties(); versionInfo.setProperty("buildNumber", validResult.builds[0].number); versionInfo.setProperty("displayVersion", displayVersion); versionInfo.setProperty("engineVersion", engineVersion.getValue()); final JenkinsClient stubClient = new StubJenkinsClient(url -> validResult, url -> versionInfo); // The Jenkins adapter should append the build number to the display version to ensure that the version string // is unique for two different builds. This is necessary because the display version generated by the CI build // is the same of subsequent builds... final String expectedVersion = displayVersion + "+" + validResult.builds[0].number;
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // } // Path: src/test/java/org/terasology/launcher/repositories/JenkinsRepositoryAdapterTest.java import com.google.gson.Gson; import com.vdurmont.semver4j.Semver; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.net.MalformedURLException; import java.net.URL; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @Test @DisplayName("skip builds without version info") void skipBuildsWithoutVersionInfo() { Properties emptyVersionInfo = new Properties(); final JenkinsClient stubClient = new StubJenkinsClient(url -> validResult, url -> emptyVersionInfo); final JenkinsRepositoryAdapter adapter = new JenkinsRepositoryAdapter(Profile.OMEGA, Build.STABLE, stubClient); assertTrue(adapter.fetchReleases().isEmpty()); } @Test @DisplayName("process valid response correctly") void processValidResponseCorrectly() { String displayVersion = "alpha 42 (preview)"; Semver engineVersion = new Semver("5.0.1-SNAPSHOT", Semver.SemverType.IVY); Properties versionInfo = new Properties(); versionInfo.setProperty("buildNumber", validResult.builds[0].number); versionInfo.setProperty("displayVersion", displayVersion); versionInfo.setProperty("engineVersion", engineVersion.getValue()); final JenkinsClient stubClient = new StubJenkinsClient(url -> validResult, url -> versionInfo); // The Jenkins adapter should append the build number to the display version to ensure that the version string // is unique for two different builds. This is necessary because the display version generated by the CI build // is the same of subsequent builds... final String expectedVersion = displayVersion + "+" + validResult.builds[0].number;
final GameIdentifier id = new GameIdentifier(expectedVersion, Build.STABLE, Profile.OMEGA);
MovingBlocks/TerasologyLauncher
src/test/java/org/terasology/launcher/repositories/JenkinsRepositoryAdapterTest.java
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // }
import com.google.gson.Gson; import com.vdurmont.semver4j.Semver; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.net.MalformedURLException; import java.net.URL; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue;
@Test @DisplayName("skip builds without version info") void skipBuildsWithoutVersionInfo() { Properties emptyVersionInfo = new Properties(); final JenkinsClient stubClient = new StubJenkinsClient(url -> validResult, url -> emptyVersionInfo); final JenkinsRepositoryAdapter adapter = new JenkinsRepositoryAdapter(Profile.OMEGA, Build.STABLE, stubClient); assertTrue(adapter.fetchReleases().isEmpty()); } @Test @DisplayName("process valid response correctly") void processValidResponseCorrectly() { String displayVersion = "alpha 42 (preview)"; Semver engineVersion = new Semver("5.0.1-SNAPSHOT", Semver.SemverType.IVY); Properties versionInfo = new Properties(); versionInfo.setProperty("buildNumber", validResult.builds[0].number); versionInfo.setProperty("displayVersion", displayVersion); versionInfo.setProperty("engineVersion", engineVersion.getValue()); final JenkinsClient stubClient = new StubJenkinsClient(url -> validResult, url -> versionInfo); // The Jenkins adapter should append the build number to the display version to ensure that the version string // is unique for two different builds. This is necessary because the display version generated by the CI build // is the same of subsequent builds... final String expectedVersion = displayVersion + "+" + validResult.builds[0].number; final GameIdentifier id = new GameIdentifier(expectedVersion, Build.STABLE, Profile.OMEGA);
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // } // Path: src/test/java/org/terasology/launcher/repositories/JenkinsRepositoryAdapterTest.java import com.google.gson.Gson; import com.vdurmont.semver4j.Semver; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.net.MalformedURLException; import java.net.URL; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @Test @DisplayName("skip builds without version info") void skipBuildsWithoutVersionInfo() { Properties emptyVersionInfo = new Properties(); final JenkinsClient stubClient = new StubJenkinsClient(url -> validResult, url -> emptyVersionInfo); final JenkinsRepositoryAdapter adapter = new JenkinsRepositoryAdapter(Profile.OMEGA, Build.STABLE, stubClient); assertTrue(adapter.fetchReleases().isEmpty()); } @Test @DisplayName("process valid response correctly") void processValidResponseCorrectly() { String displayVersion = "alpha 42 (preview)"; Semver engineVersion = new Semver("5.0.1-SNAPSHOT", Semver.SemverType.IVY); Properties versionInfo = new Properties(); versionInfo.setProperty("buildNumber", validResult.builds[0].number); versionInfo.setProperty("displayVersion", displayVersion); versionInfo.setProperty("engineVersion", engineVersion.getValue()); final JenkinsClient stubClient = new StubJenkinsClient(url -> validResult, url -> versionInfo); // The Jenkins adapter should append the build number to the display version to ensure that the version string // is unique for two different builds. This is necessary because the display version generated by the CI build // is the same of subsequent builds... final String expectedVersion = displayVersion + "+" + validResult.builds[0].number; final GameIdentifier id = new GameIdentifier(expectedVersion, Build.STABLE, Profile.OMEGA);
final ReleaseMetadata releaseMetadata = new ReleaseMetadata("", new Date(1604285977306L));
MovingBlocks/TerasologyLauncher
src/test/java/org/terasology/launcher/repositories/JenkinsRepositoryAdapterTest.java
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // }
import com.google.gson.Gson; import com.vdurmont.semver4j.Semver; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.net.MalformedURLException; import java.net.URL; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue;
@DisplayName("skip builds without version info") void skipBuildsWithoutVersionInfo() { Properties emptyVersionInfo = new Properties(); final JenkinsClient stubClient = new StubJenkinsClient(url -> validResult, url -> emptyVersionInfo); final JenkinsRepositoryAdapter adapter = new JenkinsRepositoryAdapter(Profile.OMEGA, Build.STABLE, stubClient); assertTrue(adapter.fetchReleases().isEmpty()); } @Test @DisplayName("process valid response correctly") void processValidResponseCorrectly() { String displayVersion = "alpha 42 (preview)"; Semver engineVersion = new Semver("5.0.1-SNAPSHOT", Semver.SemverType.IVY); Properties versionInfo = new Properties(); versionInfo.setProperty("buildNumber", validResult.builds[0].number); versionInfo.setProperty("displayVersion", displayVersion); versionInfo.setProperty("engineVersion", engineVersion.getValue()); final JenkinsClient stubClient = new StubJenkinsClient(url -> validResult, url -> versionInfo); // The Jenkins adapter should append the build number to the display version to ensure that the version string // is unique for two different builds. This is necessary because the display version generated by the CI build // is the same of subsequent builds... final String expectedVersion = displayVersion + "+" + validResult.builds[0].number; final GameIdentifier id = new GameIdentifier(expectedVersion, Build.STABLE, Profile.OMEGA); final ReleaseMetadata releaseMetadata = new ReleaseMetadata("", new Date(1604285977306L));
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // } // Path: src/test/java/org/terasology/launcher/repositories/JenkinsRepositoryAdapterTest.java import com.google.gson.Gson; import com.vdurmont.semver4j.Semver; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.net.MalformedURLException; import java.net.URL; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @DisplayName("skip builds without version info") void skipBuildsWithoutVersionInfo() { Properties emptyVersionInfo = new Properties(); final JenkinsClient stubClient = new StubJenkinsClient(url -> validResult, url -> emptyVersionInfo); final JenkinsRepositoryAdapter adapter = new JenkinsRepositoryAdapter(Profile.OMEGA, Build.STABLE, stubClient); assertTrue(adapter.fetchReleases().isEmpty()); } @Test @DisplayName("process valid response correctly") void processValidResponseCorrectly() { String displayVersion = "alpha 42 (preview)"; Semver engineVersion = new Semver("5.0.1-SNAPSHOT", Semver.SemverType.IVY); Properties versionInfo = new Properties(); versionInfo.setProperty("buildNumber", validResult.builds[0].number); versionInfo.setProperty("displayVersion", displayVersion); versionInfo.setProperty("engineVersion", engineVersion.getValue()); final JenkinsClient stubClient = new StubJenkinsClient(url -> validResult, url -> versionInfo); // The Jenkins adapter should append the build number to the display version to ensure that the version string // is unique for two different builds. This is necessary because the display version generated by the CI build // is the same of subsequent builds... final String expectedVersion = displayVersion + "+" + validResult.builds[0].number; final GameIdentifier id = new GameIdentifier(expectedVersion, Build.STABLE, Profile.OMEGA); final ReleaseMetadata releaseMetadata = new ReleaseMetadata("", new Date(1604285977306L));
final GameRelease expected = new GameRelease(id, expectedArtifactUrl, releaseMetadata);
MovingBlocks/TerasologyLauncher
src/main/java/org/terasology/launcher/game/RunGameTask.java
// Path: src/main/java/org/terasology/launcher/ui/FxTimer.java // public final class FxTimer { // private final Duration actionTime; // private final Timeline timeline; // private final Runnable action; // // private long seq; // // // private FxTimer(java.time.Duration actionTime, java.time.Duration period, Runnable action, int cycles) { // this.actionTime = Duration.millis(actionTime.toMillis()); // this.timeline = new Timeline(); // this.action = action; // // timeline.getKeyFrames().add(new KeyFrame(this.actionTime)); // used as placeholder // if (period != actionTime) { // timeline.getKeyFrames().add(new KeyFrame(Duration.millis(period.toMillis()))); // } // // timeline.setCycleCount(cycles); // } // // /** // * Prepares a (stopped) timer that lasts for {@code delay} and whose action runs when timer <em>ends</em>. // */ // public static FxTimer create(java.time.Duration delay, Runnable action) { // return new FxTimer(delay, delay, action, 1); // } // // /** // * Equivalent to {@code create(delay, action).restart()}. // */ // public static FxTimer runLater(java.time.Duration delay, Runnable action) { // FxTimer timer = create(delay, action); // timer.restart(); // return timer; // } // // public void restart() { // stop(); // long expected = seq; // timeline.getKeyFrames().set(0, new KeyFrame(actionTime, ae -> { // if (seq == expected) { // action.run(); // } // })); // timeline.play(); // } // // public void stop() { // timeline.stop(); // ++seq; // } // }
import com.google.common.base.MoreObjects; import javafx.concurrent.Task; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.event.Level; import org.terasology.launcher.ui.FxTimer; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.time.Duration; import java.util.concurrent.Callable; import java.util.function.Predicate; import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Verify.verify; import static com.google.common.base.Verify.verifyNotNull;
// Copyright 2020 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.game; /** * Starts and manages a game process. * <p> * Many of the characteristics of this task are described in {@link GameService}, as it's the expected access point to * this. * <p> * (An individual {@link Task} lasts as long as the process does, the {@link javafx.concurrent.Service Service} * provides a stable reference that doesn't have to be updated with each new task.) * <p> * Beware javafx's treatment of exceptions that come up in {@link Task Tasks}. An uncaught exception will be stored * in its {@link #exceptionProperty()} and never see its way to an executor's uncaught exception handler. It won't be * until you call this object's {@link #get()} that it will be thrown again. */ class RunGameTask extends Task<Boolean> { static final int EXIT_CODE_OK = 0; /** * The output of the process is tested against this for a sign that it launched successfully. * <p> * (We don't yet have a formal protocol about this with Terasology, so it won't show up if its minimum log level is * higher than {@link Level#INFO INFO}. But the default is to include {@link Level#INFO INFO}, so this should often * work.) */ static final Predicate<String> START_MATCH = Pattern.compile("TerasologyEngine.+Initialization completed") .asPredicate(); /** * How long a process has to live in order for us to call it successful. * <p> * If there's no output with {@link #START_MATCH} and it hasn't crashed after being up this long, it's probably * okay. */ static final Duration SURVIVAL_THRESHOLD = Duration.ofSeconds(10); private static final Logger logger = LoggerFactory.getLogger(RunGameTask.class); protected final Callable<Process> starter; /** * Indicates whether we have set the {@link Task#updateValue value} of this Task yet. * <p> * The value is stored in a {@link javafx.beans.property.SimpleObjectProperty property} we can't directly * access from this task's thread, so it remembers it here. */ private boolean valueSet;
// Path: src/main/java/org/terasology/launcher/ui/FxTimer.java // public final class FxTimer { // private final Duration actionTime; // private final Timeline timeline; // private final Runnable action; // // private long seq; // // // private FxTimer(java.time.Duration actionTime, java.time.Duration period, Runnable action, int cycles) { // this.actionTime = Duration.millis(actionTime.toMillis()); // this.timeline = new Timeline(); // this.action = action; // // timeline.getKeyFrames().add(new KeyFrame(this.actionTime)); // used as placeholder // if (period != actionTime) { // timeline.getKeyFrames().add(new KeyFrame(Duration.millis(period.toMillis()))); // } // // timeline.setCycleCount(cycles); // } // // /** // * Prepares a (stopped) timer that lasts for {@code delay} and whose action runs when timer <em>ends</em>. // */ // public static FxTimer create(java.time.Duration delay, Runnable action) { // return new FxTimer(delay, delay, action, 1); // } // // /** // * Equivalent to {@code create(delay, action).restart()}. // */ // public static FxTimer runLater(java.time.Duration delay, Runnable action) { // FxTimer timer = create(delay, action); // timer.restart(); // return timer; // } // // public void restart() { // stop(); // long expected = seq; // timeline.getKeyFrames().set(0, new KeyFrame(actionTime, ae -> { // if (seq == expected) { // action.run(); // } // })); // timeline.play(); // } // // public void stop() { // timeline.stop(); // ++seq; // } // } // Path: src/main/java/org/terasology/launcher/game/RunGameTask.java import com.google.common.base.MoreObjects; import javafx.concurrent.Task; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.event.Level; import org.terasology.launcher.ui.FxTimer; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.time.Duration; import java.util.concurrent.Callable; import java.util.function.Predicate; import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Verify.verify; import static com.google.common.base.Verify.verifyNotNull; // Copyright 2020 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.game; /** * Starts and manages a game process. * <p> * Many of the characteristics of this task are described in {@link GameService}, as it's the expected access point to * this. * <p> * (An individual {@link Task} lasts as long as the process does, the {@link javafx.concurrent.Service Service} * provides a stable reference that doesn't have to be updated with each new task.) * <p> * Beware javafx's treatment of exceptions that come up in {@link Task Tasks}. An uncaught exception will be stored * in its {@link #exceptionProperty()} and never see its way to an executor's uncaught exception handler. It won't be * until you call this object's {@link #get()} that it will be thrown again. */ class RunGameTask extends Task<Boolean> { static final int EXIT_CODE_OK = 0; /** * The output of the process is tested against this for a sign that it launched successfully. * <p> * (We don't yet have a formal protocol about this with Terasology, so it won't show up if its minimum log level is * higher than {@link Level#INFO INFO}. But the default is to include {@link Level#INFO INFO}, so this should often * work.) */ static final Predicate<String> START_MATCH = Pattern.compile("TerasologyEngine.+Initialization completed") .asPredicate(); /** * How long a process has to live in order for us to call it successful. * <p> * If there's no output with {@link #START_MATCH} and it hasn't crashed after being up this long, it's probably * okay. */ static final Duration SURVIVAL_THRESHOLD = Duration.ofSeconds(10); private static final Logger logger = LoggerFactory.getLogger(RunGameTask.class); protected final Callable<Process> starter; /** * Indicates whether we have set the {@link Task#updateValue value} of this Task yet. * <p> * The value is stored in a {@link javafx.beans.property.SimpleObjectProperty property} we can't directly * access from this task's thread, so it remembers it here. */ private boolean valueSet;
private FxTimer successTimer;
MovingBlocks/TerasologyLauncher
src/test/java/org/terasology/launcher/game/MockProcesses.java
// Path: src/test/java/org/terasology/launcher/StringIteratorInputStream.java // public class StringIteratorInputStream extends InputStream { // static final int COOLDOWN_LENGTH = 1; // // int cooldown; // private final Iterator<String> source; // private byte[] currentLine; // private int byteIndex; // // public StringIteratorInputStream(Iterator<String> source) { // this.source = source; // resetCooldown(); // } // // @Override // public int available() { // if (currentLine == null) { // // Playing hard-to-get with StreamDecoder.read. If it finishes a read // // and still has room in its buffer, it'll check if we're ready again // // right away. When we say we still aren't ready yet, it backs off. // if (cooldown > 0) { // cooldown -= 1; // return 0; // } // if (!loadNextLine()) { // // there's no more to be had. for real this time! // return 0; // } // } // return availableInCurrentLine(); // } // // @Override // public int read() { // if (currentLine == null) { // var gotNext = loadNextLine(); // if (!gotNext) { // return -1; // } // } // var c = currentLine[byteIndex]; // byteIndex++; // if (byteIndex >= currentLine.length) { // currentLine = null; // resetCooldown(); // } // return c; // } // // @Override // public int read(final byte[] b, final int off, final int len) throws IOException { // if (len == 0) { // return 0; // } // // Even if available() says we're empty, our superclass wants us to try // // to come up with at least one byte, blocking if necessary. Otherwise // // StreamDecoder.readBytes says "Underlying input stream returned zero bytes" // // and implodes. // @SuppressWarnings("UnstableApiUsage") var availableLength = // Ints.constrainToRange(availableInCurrentLine(), 1, len); // return super.read(b, off, availableLength); // } // // protected int availableInCurrentLine() { // if (currentLine == null) { // return 0; // } else { // return currentLine.length - byteIndex; // } // } // // private void resetCooldown() { // cooldown = COOLDOWN_LENGTH; // } // // /** // * @return true when it succeeds in getting the next line, false when the input source has no more // */ // private boolean loadNextLine() { // try { // final String nextString = source.next(); // currentLine = nextString.getBytes(); // } catch (NoSuchElementException e) { // return false; // } finally { // byteIndex = 0; // } // return true; // } // }
import org.apache.commons.io.input.NullInputStream; import org.terasology.launcher.StringIteratorInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; import java.util.Random; import java.util.concurrent.Callable;
if (this.pid == 0) { this.pid = new Random().nextLong(); } return this.pid; } @Override public int exitValue() { return 0; } @Override public void destroy() { throw new UnsupportedOperationException(); } } static class OneLineAtATimeProcess extends HappyGameProcess { private final Iterator<String> lines; OneLineAtATimeProcess(Iterator<String> lines) { this.lines = lines; } @Override public InputStream getInputStream() { // 🤔 If RunGameTask had a way to do // Iterator<String> lines = adapt(process) // and we could provide a different adapter for our mock process than a system // process, we could probably do without StringIteratorInputStream. ?
// Path: src/test/java/org/terasology/launcher/StringIteratorInputStream.java // public class StringIteratorInputStream extends InputStream { // static final int COOLDOWN_LENGTH = 1; // // int cooldown; // private final Iterator<String> source; // private byte[] currentLine; // private int byteIndex; // // public StringIteratorInputStream(Iterator<String> source) { // this.source = source; // resetCooldown(); // } // // @Override // public int available() { // if (currentLine == null) { // // Playing hard-to-get with StreamDecoder.read. If it finishes a read // // and still has room in its buffer, it'll check if we're ready again // // right away. When we say we still aren't ready yet, it backs off. // if (cooldown > 0) { // cooldown -= 1; // return 0; // } // if (!loadNextLine()) { // // there's no more to be had. for real this time! // return 0; // } // } // return availableInCurrentLine(); // } // // @Override // public int read() { // if (currentLine == null) { // var gotNext = loadNextLine(); // if (!gotNext) { // return -1; // } // } // var c = currentLine[byteIndex]; // byteIndex++; // if (byteIndex >= currentLine.length) { // currentLine = null; // resetCooldown(); // } // return c; // } // // @Override // public int read(final byte[] b, final int off, final int len) throws IOException { // if (len == 0) { // return 0; // } // // Even if available() says we're empty, our superclass wants us to try // // to come up with at least one byte, blocking if necessary. Otherwise // // StreamDecoder.readBytes says "Underlying input stream returned zero bytes" // // and implodes. // @SuppressWarnings("UnstableApiUsage") var availableLength = // Ints.constrainToRange(availableInCurrentLine(), 1, len); // return super.read(b, off, availableLength); // } // // protected int availableInCurrentLine() { // if (currentLine == null) { // return 0; // } else { // return currentLine.length - byteIndex; // } // } // // private void resetCooldown() { // cooldown = COOLDOWN_LENGTH; // } // // /** // * @return true when it succeeds in getting the next line, false when the input source has no more // */ // private boolean loadNextLine() { // try { // final String nextString = source.next(); // currentLine = nextString.getBytes(); // } catch (NoSuchElementException e) { // return false; // } finally { // byteIndex = 0; // } // return true; // } // } // Path: src/test/java/org/terasology/launcher/game/MockProcesses.java import org.apache.commons.io.input.NullInputStream; import org.terasology.launcher.StringIteratorInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; import java.util.Random; import java.util.concurrent.Callable; if (this.pid == 0) { this.pid = new Random().nextLong(); } return this.pid; } @Override public int exitValue() { return 0; } @Override public void destroy() { throw new UnsupportedOperationException(); } } static class OneLineAtATimeProcess extends HappyGameProcess { private final Iterator<String> lines; OneLineAtATimeProcess(Iterator<String> lines) { this.lines = lines; } @Override public InputStream getInputStream() { // 🤔 If RunGameTask had a way to do // Iterator<String> lines = adapt(process) // and we could provide a different adapter for our mock process than a system // process, we could probably do without StringIteratorInputStream. ?
return new StringIteratorInputStream(lines);
MovingBlocks/TerasologyLauncher
src/main/java/org/terasology/launcher/ui/ChangelogViewController.java
// Path: src/main/java/org/terasology/launcher/util/BundleUtils.java // public final class BundleUtils { // // private static final Logger logger = LoggerFactory.getLogger(BundleUtils.class); // // private static final String LABELS_BUNDLE = "org.terasology.launcher.bundle.LabelsBundle"; // private static final String MESSAGE_BUNDLE = "org.terasology.launcher.bundle.MessageBundle"; // private static final String URI_BUNDLE = "org.terasology.launcher.bundle.URIBundle"; // private static final String IMAGE_BUNDLE = "org.terasology.launcher.bundle.ImageBundle"; // private static final String FXML_BUNDLE = "org.terasology.launcher.bundle.FXMLBundle"; // // private BundleUtils() { // } // // public static String getLabel(String key) { // return getLabel(Languages.getCurrentLocale(), key); // } // // public static String getLabel(Locale locale, String key) { // try { // String label = ResourceBundle.getBundle(LABELS_BUNDLE, locale).getString(key); // if (label.length() == 0) { // throw new IllegalArgumentException(); // } // return label; // } catch (MissingResourceException | IllegalArgumentException e) { // logger.error("Missing label translation! key={}, locale={}", key, locale); // return ResourceBundle.getBundle(LABELS_BUNDLE, Languages.DEFAULT_LOCALE).getString(key); // } // } // // public static String getMessage(String key, Object... arguments) { // String pattern; // try { // pattern = ResourceBundle.getBundle(MESSAGE_BUNDLE, Languages.getCurrentLocale()).getString(key); // if (pattern.length() == 0) { // throw new IllegalArgumentException(); // } // } catch (MissingResourceException | IllegalArgumentException e) { // logger.error("Missing message translation! key={}, locale={}", key, Languages.getCurrentLocale()); // pattern = ResourceBundle.getBundle(MESSAGE_BUNDLE, Languages.DEFAULT_LOCALE).getString(key); // } // final MessageFormat messageFormat = new MessageFormat(pattern, Languages.getCurrentLocale()); // return messageFormat.format(arguments, new StringBuffer(), null).toString(); // } // // public static URI getURI(String key) { // final String uriStr = ResourceBundle.getBundle(URI_BUNDLE, Languages.getCurrentLocale()).getString(key); // try { // return new URI(uriStr); // } catch (URISyntaxException e) { // logger.error("Could not create URI '{}' for key '{}'!", uriStr, key, e); // } // return null; // } // // /** // * Loads a JavaFX {@code Image} from the image path specified by the key in the image bundle file. // * // * @param key the key as specified in the image bundle file // * @return the JavaFX image // * @throws MissingResourceException if no resource for the specified key can be found // */ // public static Image getFxImage(String key) throws MissingResourceException { // final String imagePath = ResourceBundle.getBundle(IMAGE_BUNDLE, Languages.getCurrentLocale()).getString(key); // return new Image(BundleUtils.class.getResource(imagePath).toExternalForm()); // } // // public static FXMLLoader getFXMLLoader(String key) { // return new FXMLLoader(getFXMLUrl(key), ResourceBundle.getBundle("org.terasology.launcher.bundle.LabelsBundle", Languages.getCurrentLocale())); // } // // public static URL getFXMLUrl(String key) { // final String url = ResourceBundle.getBundle(FXML_BUNDLE, Languages.getCurrentLocale()).getString(key); // return BundleUtils.class.getResource(url); // } // // public static URL getFXMLUrl(String key, String relative) { // final String url = ResourceBundle.getBundle(FXML_BUNDLE, Languages.getCurrentLocale()).getString(key); // return BundleUtils.class.getResource(url + '/' + relative); // } // // public static String getStylesheet(String key) { // return ResourceBundle.getBundle(FXML_BUNDLE, Languages.getCurrentLocale()).getString(key); // } // }
import com.vladsch.flexmark.ext.emoji.EmojiExtension; import com.vladsch.flexmark.html.HtmlRenderer; import com.vladsch.flexmark.parser.Parser; import com.vladsch.flexmark.util.ast.Node; import com.vladsch.flexmark.util.data.MutableDataSet; import javafx.fxml.FXML; import javafx.scene.effect.BlendMode; import javafx.scene.web.WebView; import org.terasology.launcher.util.BundleUtils; import java.util.Arrays;
// Copyright 2020 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.ui; public class ChangelogViewController { @FXML private WebView changelogView; private HtmlRenderer renderer; private Parser parser; public ChangelogViewController() { MutableDataSet options = new MutableDataSet(); options.set(Parser.EXTENSIONS, Arrays.asList(EmojiExtension.create())); parser = Parser.builder(options).build(); renderer = HtmlRenderer.builder(options).build(); } /** * Update the displayed changelog based on the selected package. * * @param changes list of changes */ void update(final String changes) { changelogView.getEngine().loadContent(makeHtml(changes)); changelogView.setBlendMode(BlendMode.LIGHTEN);
// Path: src/main/java/org/terasology/launcher/util/BundleUtils.java // public final class BundleUtils { // // private static final Logger logger = LoggerFactory.getLogger(BundleUtils.class); // // private static final String LABELS_BUNDLE = "org.terasology.launcher.bundle.LabelsBundle"; // private static final String MESSAGE_BUNDLE = "org.terasology.launcher.bundle.MessageBundle"; // private static final String URI_BUNDLE = "org.terasology.launcher.bundle.URIBundle"; // private static final String IMAGE_BUNDLE = "org.terasology.launcher.bundle.ImageBundle"; // private static final String FXML_BUNDLE = "org.terasology.launcher.bundle.FXMLBundle"; // // private BundleUtils() { // } // // public static String getLabel(String key) { // return getLabel(Languages.getCurrentLocale(), key); // } // // public static String getLabel(Locale locale, String key) { // try { // String label = ResourceBundle.getBundle(LABELS_BUNDLE, locale).getString(key); // if (label.length() == 0) { // throw new IllegalArgumentException(); // } // return label; // } catch (MissingResourceException | IllegalArgumentException e) { // logger.error("Missing label translation! key={}, locale={}", key, locale); // return ResourceBundle.getBundle(LABELS_BUNDLE, Languages.DEFAULT_LOCALE).getString(key); // } // } // // public static String getMessage(String key, Object... arguments) { // String pattern; // try { // pattern = ResourceBundle.getBundle(MESSAGE_BUNDLE, Languages.getCurrentLocale()).getString(key); // if (pattern.length() == 0) { // throw new IllegalArgumentException(); // } // } catch (MissingResourceException | IllegalArgumentException e) { // logger.error("Missing message translation! key={}, locale={}", key, Languages.getCurrentLocale()); // pattern = ResourceBundle.getBundle(MESSAGE_BUNDLE, Languages.DEFAULT_LOCALE).getString(key); // } // final MessageFormat messageFormat = new MessageFormat(pattern, Languages.getCurrentLocale()); // return messageFormat.format(arguments, new StringBuffer(), null).toString(); // } // // public static URI getURI(String key) { // final String uriStr = ResourceBundle.getBundle(URI_BUNDLE, Languages.getCurrentLocale()).getString(key); // try { // return new URI(uriStr); // } catch (URISyntaxException e) { // logger.error("Could not create URI '{}' for key '{}'!", uriStr, key, e); // } // return null; // } // // /** // * Loads a JavaFX {@code Image} from the image path specified by the key in the image bundle file. // * // * @param key the key as specified in the image bundle file // * @return the JavaFX image // * @throws MissingResourceException if no resource for the specified key can be found // */ // public static Image getFxImage(String key) throws MissingResourceException { // final String imagePath = ResourceBundle.getBundle(IMAGE_BUNDLE, Languages.getCurrentLocale()).getString(key); // return new Image(BundleUtils.class.getResource(imagePath).toExternalForm()); // } // // public static FXMLLoader getFXMLLoader(String key) { // return new FXMLLoader(getFXMLUrl(key), ResourceBundle.getBundle("org.terasology.launcher.bundle.LabelsBundle", Languages.getCurrentLocale())); // } // // public static URL getFXMLUrl(String key) { // final String url = ResourceBundle.getBundle(FXML_BUNDLE, Languages.getCurrentLocale()).getString(key); // return BundleUtils.class.getResource(url); // } // // public static URL getFXMLUrl(String key, String relative) { // final String url = ResourceBundle.getBundle(FXML_BUNDLE, Languages.getCurrentLocale()).getString(key); // return BundleUtils.class.getResource(url + '/' + relative); // } // // public static String getStylesheet(String key) { // return ResourceBundle.getBundle(FXML_BUNDLE, Languages.getCurrentLocale()).getString(key); // } // } // Path: src/main/java/org/terasology/launcher/ui/ChangelogViewController.java import com.vladsch.flexmark.ext.emoji.EmojiExtension; import com.vladsch.flexmark.html.HtmlRenderer; import com.vladsch.flexmark.parser.Parser; import com.vladsch.flexmark.util.ast.Node; import com.vladsch.flexmark.util.data.MutableDataSet; import javafx.fxml.FXML; import javafx.scene.effect.BlendMode; import javafx.scene.web.WebView; import org.terasology.launcher.util.BundleUtils; import java.util.Arrays; // Copyright 2020 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.ui; public class ChangelogViewController { @FXML private WebView changelogView; private HtmlRenderer renderer; private Parser parser; public ChangelogViewController() { MutableDataSet options = new MutableDataSet(); options.set(Parser.EXTENSIONS, Arrays.asList(EmojiExtension.create())); parser = Parser.builder(options).build(); renderer = HtmlRenderer.builder(options).build(); } /** * Update the displayed changelog based on the selected package. * * @param changes list of changes */ void update(final String changes) { changelogView.getEngine().loadContent(makeHtml(changes)); changelogView.setBlendMode(BlendMode.LIGHTEN);
changelogView.getEngine().setUserStyleSheetLocation(BundleUtils.getFXMLUrl("css_webview").toExternalForm());
MovingBlocks/TerasologyLauncher
src/main/java/org/terasology/launcher/repositories/RepositoryManager.java
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // }
import com.google.common.collect.Sets; import com.google.gson.Gson; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import java.util.List; import java.util.Set; import java.util.stream.Collectors;
// Copyright 2020 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.repositories; public class RepositoryManager { private final Set<GameRelease> releases; public RepositoryManager() { JenkinsClient client = new JenkinsClient(new Gson());
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // Path: src/main/java/org/terasology/launcher/repositories/RepositoryManager.java import com.google.common.collect.Sets; import com.google.gson.Gson; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import java.util.List; import java.util.Set; import java.util.stream.Collectors; // Copyright 2020 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.repositories; public class RepositoryManager { private final Set<GameRelease> releases; public RepositoryManager() { JenkinsClient client = new JenkinsClient(new Gson());
ReleaseRepository omegaNightly = new JenkinsRepositoryAdapter(Profile.OMEGA, Build.NIGHTLY, client);
MovingBlocks/TerasologyLauncher
src/main/java/org/terasology/launcher/repositories/RepositoryManager.java
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // }
import com.google.common.collect.Sets; import com.google.gson.Gson; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import java.util.List; import java.util.Set; import java.util.stream.Collectors;
// Copyright 2020 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.repositories; public class RepositoryManager { private final Set<GameRelease> releases; public RepositoryManager() { JenkinsClient client = new JenkinsClient(new Gson());
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // Path: src/main/java/org/terasology/launcher/repositories/RepositoryManager.java import com.google.common.collect.Sets; import com.google.gson.Gson; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import java.util.List; import java.util.Set; import java.util.stream.Collectors; // Copyright 2020 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.repositories; public class RepositoryManager { private final Set<GameRelease> releases; public RepositoryManager() { JenkinsClient client = new JenkinsClient(new Gson());
ReleaseRepository omegaNightly = new JenkinsRepositoryAdapter(Profile.OMEGA, Build.NIGHTLY, client);
MovingBlocks/TerasologyLauncher
src/test/java/org/terasology/launcher/util/TestLauncherDirectoryUtils.java
// Path: src/main/java/org/terasology/launcher/util/LauncherDirectoryUtils.java // public static boolean containsFiles(Path directory) { // if (directory == null || !Files.exists(directory) || !Files.isDirectory(directory)) { // return false; // } // // try (Stream<Path> stream = Files.list(directory)) { // return stream.anyMatch(file -> Files.isRegularFile(file) || Files.isDirectory(file) && containsFiles(file)); // } catch (IOException e) { // return false; // } // } // // Path: src/main/java/org/terasology/launcher/util/LauncherDirectoryUtils.java // public static boolean containsGameData(final Path gameInstallationPath) { // boolean containsGameData = false; // if (FileUtils.isReadableDir(gameInstallationPath)) { // try (Stream<Path> stream = Files.list(gameInstallationPath)) { // containsGameData = stream.anyMatch(child -> Files.isDirectory(child) // && isGameDataDirectoryName(child.getFileName().toString()) && containsFiles(child)); // } catch (IOException e) { // logger.error("Failed to check if folder contains game data", e); // } // } // return containsGameData; // }
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.terasology.launcher.util.LauncherDirectoryUtils.containsFiles; import static org.terasology.launcher.util.LauncherDirectoryUtils.containsGameData;
// Copyright 2020 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.util; class TestLauncherDirectoryUtils { @TempDir Path tempFolder; @Test void testDirectoryWithFiles() throws IOException { Path file = tempFolder.resolve("File"); assertNotNull(Files.createFile(file));
// Path: src/main/java/org/terasology/launcher/util/LauncherDirectoryUtils.java // public static boolean containsFiles(Path directory) { // if (directory == null || !Files.exists(directory) || !Files.isDirectory(directory)) { // return false; // } // // try (Stream<Path> stream = Files.list(directory)) { // return stream.anyMatch(file -> Files.isRegularFile(file) || Files.isDirectory(file) && containsFiles(file)); // } catch (IOException e) { // return false; // } // } // // Path: src/main/java/org/terasology/launcher/util/LauncherDirectoryUtils.java // public static boolean containsGameData(final Path gameInstallationPath) { // boolean containsGameData = false; // if (FileUtils.isReadableDir(gameInstallationPath)) { // try (Stream<Path> stream = Files.list(gameInstallationPath)) { // containsGameData = stream.anyMatch(child -> Files.isDirectory(child) // && isGameDataDirectoryName(child.getFileName().toString()) && containsFiles(child)); // } catch (IOException e) { // logger.error("Failed to check if folder contains game data", e); // } // } // return containsGameData; // } // Path: src/test/java/org/terasology/launcher/util/TestLauncherDirectoryUtils.java import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.terasology.launcher.util.LauncherDirectoryUtils.containsFiles; import static org.terasology.launcher.util.LauncherDirectoryUtils.containsGameData; // Copyright 2020 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.util; class TestLauncherDirectoryUtils { @TempDir Path tempFolder; @Test void testDirectoryWithFiles() throws IOException { Path file = tempFolder.resolve("File"); assertNotNull(Files.createFile(file));
assertTrue(containsFiles(tempFolder));
MovingBlocks/TerasologyLauncher
src/test/java/org/terasology/launcher/util/TestLauncherDirectoryUtils.java
// Path: src/main/java/org/terasology/launcher/util/LauncherDirectoryUtils.java // public static boolean containsFiles(Path directory) { // if (directory == null || !Files.exists(directory) || !Files.isDirectory(directory)) { // return false; // } // // try (Stream<Path> stream = Files.list(directory)) { // return stream.anyMatch(file -> Files.isRegularFile(file) || Files.isDirectory(file) && containsFiles(file)); // } catch (IOException e) { // return false; // } // } // // Path: src/main/java/org/terasology/launcher/util/LauncherDirectoryUtils.java // public static boolean containsGameData(final Path gameInstallationPath) { // boolean containsGameData = false; // if (FileUtils.isReadableDir(gameInstallationPath)) { // try (Stream<Path> stream = Files.list(gameInstallationPath)) { // containsGameData = stream.anyMatch(child -> Files.isDirectory(child) // && isGameDataDirectoryName(child.getFileName().toString()) && containsFiles(child)); // } catch (IOException e) { // logger.error("Failed to check if folder contains game data", e); // } // } // return containsGameData; // }
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.terasology.launcher.util.LauncherDirectoryUtils.containsFiles; import static org.terasology.launcher.util.LauncherDirectoryUtils.containsGameData;
// Copyright 2020 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.util; class TestLauncherDirectoryUtils { @TempDir Path tempFolder; @Test void testDirectoryWithFiles() throws IOException { Path file = tempFolder.resolve("File"); assertNotNull(Files.createFile(file)); assertTrue(containsFiles(tempFolder)); } @Test void testEmptyDirectory() throws IOException { assertFalse(containsFiles(tempFolder)); } @Test void testGameDirectory() throws IOException { Path savesDirectory = tempFolder.resolve(GameDataDirectoryNames.SAVES.getName()); Path saveFile = savesDirectory.resolve("saveFile"); Files.createDirectories(savesDirectory); Files.createFile(saveFile);
// Path: src/main/java/org/terasology/launcher/util/LauncherDirectoryUtils.java // public static boolean containsFiles(Path directory) { // if (directory == null || !Files.exists(directory) || !Files.isDirectory(directory)) { // return false; // } // // try (Stream<Path> stream = Files.list(directory)) { // return stream.anyMatch(file -> Files.isRegularFile(file) || Files.isDirectory(file) && containsFiles(file)); // } catch (IOException e) { // return false; // } // } // // Path: src/main/java/org/terasology/launcher/util/LauncherDirectoryUtils.java // public static boolean containsGameData(final Path gameInstallationPath) { // boolean containsGameData = false; // if (FileUtils.isReadableDir(gameInstallationPath)) { // try (Stream<Path> stream = Files.list(gameInstallationPath)) { // containsGameData = stream.anyMatch(child -> Files.isDirectory(child) // && isGameDataDirectoryName(child.getFileName().toString()) && containsFiles(child)); // } catch (IOException e) { // logger.error("Failed to check if folder contains game data", e); // } // } // return containsGameData; // } // Path: src/test/java/org/terasology/launcher/util/TestLauncherDirectoryUtils.java import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.terasology.launcher.util.LauncherDirectoryUtils.containsFiles; import static org.terasology.launcher.util.LauncherDirectoryUtils.containsGameData; // Copyright 2020 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.util; class TestLauncherDirectoryUtils { @TempDir Path tempFolder; @Test void testDirectoryWithFiles() throws IOException { Path file = tempFolder.resolve("File"); assertNotNull(Files.createFile(file)); assertTrue(containsFiles(tempFolder)); } @Test void testEmptyDirectory() throws IOException { assertFalse(containsFiles(tempFolder)); } @Test void testGameDirectory() throws IOException { Path savesDirectory = tempFolder.resolve(GameDataDirectoryNames.SAVES.getName()); Path saveFile = savesDirectory.resolve("saveFile"); Files.createDirectories(savesDirectory); Files.createFile(saveFile);
assertTrue(containsGameData(tempFolder));
MovingBlocks/TerasologyLauncher
src/main/java/org/terasology/launcher/util/DownloadUtils.java
// Path: src/main/java/org/terasology/launcher/tasks/ProgressListener.java // public interface ProgressListener { // // void update(); // // void update(int progress); // // boolean isCancelled(); // // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.tasks.ProgressListener; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URISyntaxException; import java.net.URL; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; import java.util.concurrent.CompletableFuture;
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.util; public final class DownloadUtils { private static final Logger logger = LoggerFactory.getLogger(DownloadUtils.class); private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(30); private static final Duration READ_TIMEOUT = Duration.ofMinutes(5); private DownloadUtils() { }
// Path: src/main/java/org/terasology/launcher/tasks/ProgressListener.java // public interface ProgressListener { // // void update(); // // void update(int progress); // // boolean isCancelled(); // // } // Path: src/main/java/org/terasology/launcher/util/DownloadUtils.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.tasks.ProgressListener; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URISyntaxException; import java.net.URL; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.file.Files; import java.nio.file.Path; import java.time.Duration; import java.util.concurrent.CompletableFuture; // Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.util; public final class DownloadUtils { private static final Logger logger = LoggerFactory.getLogger(DownloadUtils.class); private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(30); private static final Duration READ_TIMEOUT = Duration.ofMinutes(5); private DownloadUtils() { }
public static CompletableFuture<Void> downloadToFile(URL downloadURL, Path file, ProgressListener listener) throws DownloadException {
MovingBlocks/TerasologyLauncher
src/main/java/org/terasology/launcher/util/FileUtils.java
// Path: src/main/java/org/terasology/launcher/util/visitor/ArchiveCopyVisitor.java // public class ArchiveCopyVisitor extends SimpleFileVisitor<Path> { // // /** // * Directory to which the files are copied. // */ // private final Path targetLocation; // // public ArchiveCopyVisitor(final Path targetLocation) { // this.targetLocation = targetLocation; // } // // @Override // public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { // final Path destFile = Paths.get(targetLocation.toString() + file.toString()); // Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { // final Path dirToCreate = Paths.get(targetLocation.toString() + dir.toString()); // if (Files.notExists(dirToCreate)) { // Files.createDirectories(dirToCreate); // } // return FileVisitResult.CONTINUE; // } // } // // Path: src/main/java/org/terasology/launcher/util/visitor/DeleteFileVisitor.java // public class DeleteFileVisitor extends SimpleFileVisitor<Path> { // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // Files.delete(file); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { // Files.delete(dir); // return FileVisitResult.CONTINUE; // } // } // // Path: src/main/java/org/terasology/launcher/util/visitor/LocalCopyVisitor.java // public class LocalCopyVisitor extends SimpleFileVisitor<Path> { // // /** // * Directory to copy from. // */ // private final Path sourceDirectory; // // /** // * Directory to copy to. // */ // private final Path targetDirectory; // // public LocalCopyVisitor(final Path sourceDirectory, final Path targetDirectory) { // this.sourceDirectory = sourceDirectory; // this.targetDirectory = targetDirectory; // } // // @Override // public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { // Files.copy(file, targetDirectory.resolve(sourceDirectory.relativize(file)), StandardCopyOption.REPLACE_EXISTING); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { // final Path dirToCreate = targetDirectory.resolve(sourceDirectory.relativize(dir)); // if (Files.notExists(dirToCreate)) { // Files.createDirectories(dirToCreate); // } // return FileVisitResult.CONTINUE; // } // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.util.visitor.ArchiveCopyVisitor; import org.terasology.launcher.util.visitor.DeleteFileVisitor; import org.terasology.launcher.util.visitor.LocalCopyVisitor; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.stream.Stream;
// Copyright 2020 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.util; public final class FileUtils { private static final Logger logger = LoggerFactory.getLogger(FileUtils.class); private FileUtils() { } /** * Deletes the specified file or directory. If the path is a directory it is removed recursively. * * @param path Path to delete * @throws IOException if something goes wrong */ public static void delete(final Path path) throws IOException {
// Path: src/main/java/org/terasology/launcher/util/visitor/ArchiveCopyVisitor.java // public class ArchiveCopyVisitor extends SimpleFileVisitor<Path> { // // /** // * Directory to which the files are copied. // */ // private final Path targetLocation; // // public ArchiveCopyVisitor(final Path targetLocation) { // this.targetLocation = targetLocation; // } // // @Override // public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { // final Path destFile = Paths.get(targetLocation.toString() + file.toString()); // Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { // final Path dirToCreate = Paths.get(targetLocation.toString() + dir.toString()); // if (Files.notExists(dirToCreate)) { // Files.createDirectories(dirToCreate); // } // return FileVisitResult.CONTINUE; // } // } // // Path: src/main/java/org/terasology/launcher/util/visitor/DeleteFileVisitor.java // public class DeleteFileVisitor extends SimpleFileVisitor<Path> { // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // Files.delete(file); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { // Files.delete(dir); // return FileVisitResult.CONTINUE; // } // } // // Path: src/main/java/org/terasology/launcher/util/visitor/LocalCopyVisitor.java // public class LocalCopyVisitor extends SimpleFileVisitor<Path> { // // /** // * Directory to copy from. // */ // private final Path sourceDirectory; // // /** // * Directory to copy to. // */ // private final Path targetDirectory; // // public LocalCopyVisitor(final Path sourceDirectory, final Path targetDirectory) { // this.sourceDirectory = sourceDirectory; // this.targetDirectory = targetDirectory; // } // // @Override // public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { // Files.copy(file, targetDirectory.resolve(sourceDirectory.relativize(file)), StandardCopyOption.REPLACE_EXISTING); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { // final Path dirToCreate = targetDirectory.resolve(sourceDirectory.relativize(dir)); // if (Files.notExists(dirToCreate)) { // Files.createDirectories(dirToCreate); // } // return FileVisitResult.CONTINUE; // } // } // Path: src/main/java/org/terasology/launcher/util/FileUtils.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.util.visitor.ArchiveCopyVisitor; import org.terasology.launcher.util.visitor.DeleteFileVisitor; import org.terasology.launcher.util.visitor.LocalCopyVisitor; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.stream.Stream; // Copyright 2020 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.util; public final class FileUtils { private static final Logger logger = LoggerFactory.getLogger(FileUtils.class); private FileUtils() { } /** * Deletes the specified file or directory. If the path is a directory it is removed recursively. * * @param path Path to delete * @throws IOException if something goes wrong */ public static void delete(final Path path) throws IOException {
Files.walkFileTree(path, new DeleteFileVisitor());
MovingBlocks/TerasologyLauncher
src/main/java/org/terasology/launcher/util/FileUtils.java
// Path: src/main/java/org/terasology/launcher/util/visitor/ArchiveCopyVisitor.java // public class ArchiveCopyVisitor extends SimpleFileVisitor<Path> { // // /** // * Directory to which the files are copied. // */ // private final Path targetLocation; // // public ArchiveCopyVisitor(final Path targetLocation) { // this.targetLocation = targetLocation; // } // // @Override // public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { // final Path destFile = Paths.get(targetLocation.toString() + file.toString()); // Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { // final Path dirToCreate = Paths.get(targetLocation.toString() + dir.toString()); // if (Files.notExists(dirToCreate)) { // Files.createDirectories(dirToCreate); // } // return FileVisitResult.CONTINUE; // } // } // // Path: src/main/java/org/terasology/launcher/util/visitor/DeleteFileVisitor.java // public class DeleteFileVisitor extends SimpleFileVisitor<Path> { // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // Files.delete(file); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { // Files.delete(dir); // return FileVisitResult.CONTINUE; // } // } // // Path: src/main/java/org/terasology/launcher/util/visitor/LocalCopyVisitor.java // public class LocalCopyVisitor extends SimpleFileVisitor<Path> { // // /** // * Directory to copy from. // */ // private final Path sourceDirectory; // // /** // * Directory to copy to. // */ // private final Path targetDirectory; // // public LocalCopyVisitor(final Path sourceDirectory, final Path targetDirectory) { // this.sourceDirectory = sourceDirectory; // this.targetDirectory = targetDirectory; // } // // @Override // public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { // Files.copy(file, targetDirectory.resolve(sourceDirectory.relativize(file)), StandardCopyOption.REPLACE_EXISTING); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { // final Path dirToCreate = targetDirectory.resolve(sourceDirectory.relativize(dir)); // if (Files.notExists(dirToCreate)) { // Files.createDirectories(dirToCreate); // } // return FileVisitResult.CONTINUE; // } // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.util.visitor.ArchiveCopyVisitor; import org.terasology.launcher.util.visitor.DeleteFileVisitor; import org.terasology.launcher.util.visitor.LocalCopyVisitor; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.stream.Stream;
* @throws IOException if something goes wrong */ static void deleteDirectoryContent(final Path directory) throws IOException { try (Stream<Path> stream = Files.list(directory)) { stream.forEach(path -> { try { Files.walkFileTree(path, new DeleteFileVisitor()); } catch (IOException e) { logger.error("Failed to delete '{}'", path, e); } }); } } /** * Extracts the specified ZIP file to the specified location. * * @param archive the ZIP file to extract * @param outputLocation where to extract to * @return true if successful */ public static boolean extractZipTo(final Path archive, final Path outputLocation) { logger.trace("Extracting '{}' to '{}'", archive, outputLocation); try { if (Files.notExists(outputLocation)) { Files.createDirectories(outputLocation); } try (FileSystem fileSystem = FileSystems.newFileSystem(archive, ((ClassLoader) null))) { for (Path rootDirectory : fileSystem.getRootDirectories()) {
// Path: src/main/java/org/terasology/launcher/util/visitor/ArchiveCopyVisitor.java // public class ArchiveCopyVisitor extends SimpleFileVisitor<Path> { // // /** // * Directory to which the files are copied. // */ // private final Path targetLocation; // // public ArchiveCopyVisitor(final Path targetLocation) { // this.targetLocation = targetLocation; // } // // @Override // public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { // final Path destFile = Paths.get(targetLocation.toString() + file.toString()); // Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { // final Path dirToCreate = Paths.get(targetLocation.toString() + dir.toString()); // if (Files.notExists(dirToCreate)) { // Files.createDirectories(dirToCreate); // } // return FileVisitResult.CONTINUE; // } // } // // Path: src/main/java/org/terasology/launcher/util/visitor/DeleteFileVisitor.java // public class DeleteFileVisitor extends SimpleFileVisitor<Path> { // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // Files.delete(file); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { // Files.delete(dir); // return FileVisitResult.CONTINUE; // } // } // // Path: src/main/java/org/terasology/launcher/util/visitor/LocalCopyVisitor.java // public class LocalCopyVisitor extends SimpleFileVisitor<Path> { // // /** // * Directory to copy from. // */ // private final Path sourceDirectory; // // /** // * Directory to copy to. // */ // private final Path targetDirectory; // // public LocalCopyVisitor(final Path sourceDirectory, final Path targetDirectory) { // this.sourceDirectory = sourceDirectory; // this.targetDirectory = targetDirectory; // } // // @Override // public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { // Files.copy(file, targetDirectory.resolve(sourceDirectory.relativize(file)), StandardCopyOption.REPLACE_EXISTING); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { // final Path dirToCreate = targetDirectory.resolve(sourceDirectory.relativize(dir)); // if (Files.notExists(dirToCreate)) { // Files.createDirectories(dirToCreate); // } // return FileVisitResult.CONTINUE; // } // } // Path: src/main/java/org/terasology/launcher/util/FileUtils.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.util.visitor.ArchiveCopyVisitor; import org.terasology.launcher.util.visitor.DeleteFileVisitor; import org.terasology.launcher.util.visitor.LocalCopyVisitor; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.stream.Stream; * @throws IOException if something goes wrong */ static void deleteDirectoryContent(final Path directory) throws IOException { try (Stream<Path> stream = Files.list(directory)) { stream.forEach(path -> { try { Files.walkFileTree(path, new DeleteFileVisitor()); } catch (IOException e) { logger.error("Failed to delete '{}'", path, e); } }); } } /** * Extracts the specified ZIP file to the specified location. * * @param archive the ZIP file to extract * @param outputLocation where to extract to * @return true if successful */ public static boolean extractZipTo(final Path archive, final Path outputLocation) { logger.trace("Extracting '{}' to '{}'", archive, outputLocation); try { if (Files.notExists(outputLocation)) { Files.createDirectories(outputLocation); } try (FileSystem fileSystem = FileSystems.newFileSystem(archive, ((ClassLoader) null))) { for (Path rootDirectory : fileSystem.getRootDirectories()) {
Files.walkFileTree(rootDirectory, new ArchiveCopyVisitor(outputLocation));
MovingBlocks/TerasologyLauncher
src/main/java/org/terasology/launcher/util/FileUtils.java
// Path: src/main/java/org/terasology/launcher/util/visitor/ArchiveCopyVisitor.java // public class ArchiveCopyVisitor extends SimpleFileVisitor<Path> { // // /** // * Directory to which the files are copied. // */ // private final Path targetLocation; // // public ArchiveCopyVisitor(final Path targetLocation) { // this.targetLocation = targetLocation; // } // // @Override // public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { // final Path destFile = Paths.get(targetLocation.toString() + file.toString()); // Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { // final Path dirToCreate = Paths.get(targetLocation.toString() + dir.toString()); // if (Files.notExists(dirToCreate)) { // Files.createDirectories(dirToCreate); // } // return FileVisitResult.CONTINUE; // } // } // // Path: src/main/java/org/terasology/launcher/util/visitor/DeleteFileVisitor.java // public class DeleteFileVisitor extends SimpleFileVisitor<Path> { // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // Files.delete(file); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { // Files.delete(dir); // return FileVisitResult.CONTINUE; // } // } // // Path: src/main/java/org/terasology/launcher/util/visitor/LocalCopyVisitor.java // public class LocalCopyVisitor extends SimpleFileVisitor<Path> { // // /** // * Directory to copy from. // */ // private final Path sourceDirectory; // // /** // * Directory to copy to. // */ // private final Path targetDirectory; // // public LocalCopyVisitor(final Path sourceDirectory, final Path targetDirectory) { // this.sourceDirectory = sourceDirectory; // this.targetDirectory = targetDirectory; // } // // @Override // public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { // Files.copy(file, targetDirectory.resolve(sourceDirectory.relativize(file)), StandardCopyOption.REPLACE_EXISTING); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { // final Path dirToCreate = targetDirectory.resolve(sourceDirectory.relativize(dir)); // if (Files.notExists(dirToCreate)) { // Files.createDirectories(dirToCreate); // } // return FileVisitResult.CONTINUE; // } // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.util.visitor.ArchiveCopyVisitor; import org.terasology.launcher.util.visitor.DeleteFileVisitor; import org.terasology.launcher.util.visitor.LocalCopyVisitor; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.stream.Stream;
try { if (Files.notExists(outputLocation)) { Files.createDirectories(outputLocation); } try (FileSystem fileSystem = FileSystems.newFileSystem(archive, ((ClassLoader) null))) { for (Path rootDirectory : fileSystem.getRootDirectories()) { Files.walkFileTree(rootDirectory, new ArchiveCopyVisitor(outputLocation)); } } return true; } catch (IOException e) { logger.error("Could not extract zip archive '{}' to '{}'!", archive, outputLocation, e); return false; } } /** * Copy the whole folder recursively to the specified destination. * * @param source the folder to copy * @param destination where to copy to * @throws IOException if copying fails */ public static void copyFolder(final Path source, final Path destination) throws IOException { if (Files.notExists(source)) { logger.error("Source file doesn't exists! '{}'", source); return; }
// Path: src/main/java/org/terasology/launcher/util/visitor/ArchiveCopyVisitor.java // public class ArchiveCopyVisitor extends SimpleFileVisitor<Path> { // // /** // * Directory to which the files are copied. // */ // private final Path targetLocation; // // public ArchiveCopyVisitor(final Path targetLocation) { // this.targetLocation = targetLocation; // } // // @Override // public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { // final Path destFile = Paths.get(targetLocation.toString() + file.toString()); // Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { // final Path dirToCreate = Paths.get(targetLocation.toString() + dir.toString()); // if (Files.notExists(dirToCreate)) { // Files.createDirectories(dirToCreate); // } // return FileVisitResult.CONTINUE; // } // } // // Path: src/main/java/org/terasology/launcher/util/visitor/DeleteFileVisitor.java // public class DeleteFileVisitor extends SimpleFileVisitor<Path> { // // @Override // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // Files.delete(file); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { // Files.delete(dir); // return FileVisitResult.CONTINUE; // } // } // // Path: src/main/java/org/terasology/launcher/util/visitor/LocalCopyVisitor.java // public class LocalCopyVisitor extends SimpleFileVisitor<Path> { // // /** // * Directory to copy from. // */ // private final Path sourceDirectory; // // /** // * Directory to copy to. // */ // private final Path targetDirectory; // // public LocalCopyVisitor(final Path sourceDirectory, final Path targetDirectory) { // this.sourceDirectory = sourceDirectory; // this.targetDirectory = targetDirectory; // } // // @Override // public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { // Files.copy(file, targetDirectory.resolve(sourceDirectory.relativize(file)), StandardCopyOption.REPLACE_EXISTING); // return FileVisitResult.CONTINUE; // } // // @Override // public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { // final Path dirToCreate = targetDirectory.resolve(sourceDirectory.relativize(dir)); // if (Files.notExists(dirToCreate)) { // Files.createDirectories(dirToCreate); // } // return FileVisitResult.CONTINUE; // } // } // Path: src/main/java/org/terasology/launcher/util/FileUtils.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.util.visitor.ArchiveCopyVisitor; import org.terasology.launcher.util.visitor.DeleteFileVisitor; import org.terasology.launcher.util.visitor.LocalCopyVisitor; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.stream.Stream; try { if (Files.notExists(outputLocation)) { Files.createDirectories(outputLocation); } try (FileSystem fileSystem = FileSystems.newFileSystem(archive, ((ClassLoader) null))) { for (Path rootDirectory : fileSystem.getRootDirectories()) { Files.walkFileTree(rootDirectory, new ArchiveCopyVisitor(outputLocation)); } } return true; } catch (IOException e) { logger.error("Could not extract zip archive '{}' to '{}'!", archive, outputLocation, e); return false; } } /** * Copy the whole folder recursively to the specified destination. * * @param source the folder to copy * @param destination where to copy to * @throws IOException if copying fails */ public static void copyFolder(final Path source, final Path destination) throws IOException { if (Files.notExists(source)) { logger.error("Source file doesn't exists! '{}'", source); return; }
Files.walkFileTree(source, new LocalCopyVisitor(source, destination));
MovingBlocks/TerasologyLauncher
src/main/java/org/terasology/launcher/repositories/GithubRepositoryAdapter.java
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // }
import com.vdurmont.semver4j.Semver; import com.vdurmont.semver4j.SemverException; import org.kohsuke.github.GHAsset; import org.kohsuke.github.GHRelease; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GitHub; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.io.IOException; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors;
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.repositories; public class GithubRepositoryAdapter implements ReleaseRepository { private static final Logger logger = LoggerFactory.getLogger(GithubRepositoryAdapter.class); private GitHub github; public GithubRepositoryAdapter() { try { github = GitHub.connectAnonymously(); logger.debug("Github rate limit: {}", github.getRateLimit()); } catch (IOException e) { e.printStackTrace(); } }
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // } // Path: src/main/java/org/terasology/launcher/repositories/GithubRepositoryAdapter.java import com.vdurmont.semver4j.Semver; import com.vdurmont.semver4j.SemverException; import org.kohsuke.github.GHAsset; import org.kohsuke.github.GHRelease; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GitHub; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.io.IOException; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; // Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.repositories; public class GithubRepositoryAdapter implements ReleaseRepository { private static final Logger logger = LoggerFactory.getLogger(GithubRepositoryAdapter.class); private GitHub github; public GithubRepositoryAdapter() { try { github = GitHub.connectAnonymously(); logger.debug("Github rate limit: {}", github.getRateLimit()); } catch (IOException e) { e.printStackTrace(); } }
static GameRelease fromGithubRelease(GHRelease ghRelease) {
MovingBlocks/TerasologyLauncher
src/main/java/org/terasology/launcher/repositories/GithubRepositoryAdapter.java
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // }
import com.vdurmont.semver4j.Semver; import com.vdurmont.semver4j.SemverException; import org.kohsuke.github.GHAsset; import org.kohsuke.github.GHRelease; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GitHub; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.io.IOException; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors;
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.repositories; public class GithubRepositoryAdapter implements ReleaseRepository { private static final Logger logger = LoggerFactory.getLogger(GithubRepositoryAdapter.class); private GitHub github; public GithubRepositoryAdapter() { try { github = GitHub.connectAnonymously(); logger.debug("Github rate limit: {}", github.getRateLimit()); } catch (IOException e) { e.printStackTrace(); } } static GameRelease fromGithubRelease(GHRelease ghRelease) {
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // } // Path: src/main/java/org/terasology/launcher/repositories/GithubRepositoryAdapter.java import com.vdurmont.semver4j.Semver; import com.vdurmont.semver4j.SemverException; import org.kohsuke.github.GHAsset; import org.kohsuke.github.GHRelease; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GitHub; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.io.IOException; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; // Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.repositories; public class GithubRepositoryAdapter implements ReleaseRepository { private static final Logger logger = LoggerFactory.getLogger(GithubRepositoryAdapter.class); private GitHub github; public GithubRepositoryAdapter() { try { github = GitHub.connectAnonymously(); logger.debug("Github rate limit: {}", github.getRateLimit()); } catch (IOException e) { e.printStackTrace(); } } static GameRelease fromGithubRelease(GHRelease ghRelease) {
final Profile profile = Profile.OMEGA;
MovingBlocks/TerasologyLauncher
src/main/java/org/terasology/launcher/repositories/GithubRepositoryAdapter.java
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // }
import com.vdurmont.semver4j.Semver; import com.vdurmont.semver4j.SemverException; import org.kohsuke.github.GHAsset; import org.kohsuke.github.GHRelease; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GitHub; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.io.IOException; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors;
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.repositories; public class GithubRepositoryAdapter implements ReleaseRepository { private static final Logger logger = LoggerFactory.getLogger(GithubRepositoryAdapter.class); private GitHub github; public GithubRepositoryAdapter() { try { github = GitHub.connectAnonymously(); logger.debug("Github rate limit: {}", github.getRateLimit()); } catch (IOException e) { e.printStackTrace(); } } static GameRelease fromGithubRelease(GHRelease ghRelease) { final Profile profile = Profile.OMEGA;
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // } // Path: src/main/java/org/terasology/launcher/repositories/GithubRepositoryAdapter.java import com.vdurmont.semver4j.Semver; import com.vdurmont.semver4j.SemverException; import org.kohsuke.github.GHAsset; import org.kohsuke.github.GHRelease; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GitHub; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.io.IOException; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; // Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.repositories; public class GithubRepositoryAdapter implements ReleaseRepository { private static final Logger logger = LoggerFactory.getLogger(GithubRepositoryAdapter.class); private GitHub github; public GithubRepositoryAdapter() { try { github = GitHub.connectAnonymously(); logger.debug("Github rate limit: {}", github.getRateLimit()); } catch (IOException e) { e.printStackTrace(); } } static GameRelease fromGithubRelease(GHRelease ghRelease) { final Profile profile = Profile.OMEGA;
final Build build = ghRelease.isPrerelease() ? Build.NIGHTLY : Build.STABLE;
MovingBlocks/TerasologyLauncher
src/main/java/org/terasology/launcher/repositories/GithubRepositoryAdapter.java
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // }
import com.vdurmont.semver4j.Semver; import com.vdurmont.semver4j.SemverException; import org.kohsuke.github.GHAsset; import org.kohsuke.github.GHRelease; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GitHub; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.io.IOException; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors;
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.repositories; public class GithubRepositoryAdapter implements ReleaseRepository { private static final Logger logger = LoggerFactory.getLogger(GithubRepositoryAdapter.class); private GitHub github; public GithubRepositoryAdapter() { try { github = GitHub.connectAnonymously(); logger.debug("Github rate limit: {}", github.getRateLimit()); } catch (IOException e) { e.printStackTrace(); } } static GameRelease fromGithubRelease(GHRelease ghRelease) { final Profile profile = Profile.OMEGA; final Build build = ghRelease.isPrerelease() ? Build.NIGHTLY : Build.STABLE; final String tagName = ghRelease.getTagName(); try { final Semver engineVersion; if (tagName.startsWith("v")) { engineVersion = new Semver(tagName.substring(1)); } else { engineVersion = new Semver(tagName); } final Optional<GHAsset> gameAsset = ghRelease.assets().stream().filter(asset -> asset.getName().matches("Terasology.*zip")).findFirst(); final URL url = new URL(gameAsset.map(GHAsset::getBrowserDownloadUrl).orElseThrow(() -> new IOException("Missing game asset."))); final String changelog = ghRelease.getBody();
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // } // Path: src/main/java/org/terasology/launcher/repositories/GithubRepositoryAdapter.java import com.vdurmont.semver4j.Semver; import com.vdurmont.semver4j.SemverException; import org.kohsuke.github.GHAsset; import org.kohsuke.github.GHRelease; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GitHub; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.io.IOException; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; // Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.repositories; public class GithubRepositoryAdapter implements ReleaseRepository { private static final Logger logger = LoggerFactory.getLogger(GithubRepositoryAdapter.class); private GitHub github; public GithubRepositoryAdapter() { try { github = GitHub.connectAnonymously(); logger.debug("Github rate limit: {}", github.getRateLimit()); } catch (IOException e) { e.printStackTrace(); } } static GameRelease fromGithubRelease(GHRelease ghRelease) { final Profile profile = Profile.OMEGA; final Build build = ghRelease.isPrerelease() ? Build.NIGHTLY : Build.STABLE; final String tagName = ghRelease.getTagName(); try { final Semver engineVersion; if (tagName.startsWith("v")) { engineVersion = new Semver(tagName.substring(1)); } else { engineVersion = new Semver(tagName); } final Optional<GHAsset> gameAsset = ghRelease.assets().stream().filter(asset -> asset.getName().matches("Terasology.*zip")).findFirst(); final URL url = new URL(gameAsset.map(GHAsset::getBrowserDownloadUrl).orElseThrow(() -> new IOException("Missing game asset."))); final String changelog = ghRelease.getBody();
GameIdentifier id = new GameIdentifier(engineVersion.toString(), build, profile);
MovingBlocks/TerasologyLauncher
src/main/java/org/terasology/launcher/repositories/GithubRepositoryAdapter.java
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // }
import com.vdurmont.semver4j.Semver; import com.vdurmont.semver4j.SemverException; import org.kohsuke.github.GHAsset; import org.kohsuke.github.GHRelease; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GitHub; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.io.IOException; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors;
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.repositories; public class GithubRepositoryAdapter implements ReleaseRepository { private static final Logger logger = LoggerFactory.getLogger(GithubRepositoryAdapter.class); private GitHub github; public GithubRepositoryAdapter() { try { github = GitHub.connectAnonymously(); logger.debug("Github rate limit: {}", github.getRateLimit()); } catch (IOException e) { e.printStackTrace(); } } static GameRelease fromGithubRelease(GHRelease ghRelease) { final Profile profile = Profile.OMEGA; final Build build = ghRelease.isPrerelease() ? Build.NIGHTLY : Build.STABLE; final String tagName = ghRelease.getTagName(); try { final Semver engineVersion; if (tagName.startsWith("v")) { engineVersion = new Semver(tagName.substring(1)); } else { engineVersion = new Semver(tagName); } final Optional<GHAsset> gameAsset = ghRelease.assets().stream().filter(asset -> asset.getName().matches("Terasology.*zip")).findFirst(); final URL url = new URL(gameAsset.map(GHAsset::getBrowserDownloadUrl).orElseThrow(() -> new IOException("Missing game asset."))); final String changelog = ghRelease.getBody(); GameIdentifier id = new GameIdentifier(engineVersion.toString(), build, profile);
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // } // Path: src/main/java/org/terasology/launcher/repositories/GithubRepositoryAdapter.java import com.vdurmont.semver4j.Semver; import com.vdurmont.semver4j.SemverException; import org.kohsuke.github.GHAsset; import org.kohsuke.github.GHRelease; import org.kohsuke.github.GHRepository; import org.kohsuke.github.GitHub; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.io.IOException; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; // Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.repositories; public class GithubRepositoryAdapter implements ReleaseRepository { private static final Logger logger = LoggerFactory.getLogger(GithubRepositoryAdapter.class); private GitHub github; public GithubRepositoryAdapter() { try { github = GitHub.connectAnonymously(); logger.debug("Github rate limit: {}", github.getRateLimit()); } catch (IOException e) { e.printStackTrace(); } } static GameRelease fromGithubRelease(GHRelease ghRelease) { final Profile profile = Profile.OMEGA; final Build build = ghRelease.isPrerelease() ? Build.NIGHTLY : Build.STABLE; final String tagName = ghRelease.getTagName(); try { final Semver engineVersion; if (tagName.startsWith("v")) { engineVersion = new Semver(tagName.substring(1)); } else { engineVersion = new Semver(tagName); } final Optional<GHAsset> gameAsset = ghRelease.assets().stream().filter(asset -> asset.getName().matches("Terasology.*zip")).findFirst(); final URL url = new URL(gameAsset.map(GHAsset::getBrowserDownloadUrl).orElseThrow(() -> new IOException("Missing game asset."))); final String changelog = ghRelease.getBody(); GameIdentifier id = new GameIdentifier(engineVersion.toString(), build, profile);
ReleaseMetadata metadata = new ReleaseMetadata(changelog, ghRelease.getPublished_at());
MovingBlocks/TerasologyLauncher
src/main/java/org/terasology/launcher/game/GameStarter.java
// Path: src/main/java/org/terasology/launcher/util/JavaHeapSize.java // public enum JavaHeapSize { // // NOT_USED("", "heapsize_notUsed"), // MB_256("256m", "heapsize_mb_256"), // MB_512("512m", "heapsize_mb_512"), // MB_768("768m", "heapsize_mb_768"), // GB_1("1g", "heapsize_gb_1"), // GB_1_5("1536m", "heapsize_gb_1_5"), // GB_2("2g", "heapsize_gb_2"), // GB_2_5("2560m", "heapsize_gb_2_5"), // GB_3("3g", "heapsize_gb_3"), // GB_4("4g", "heapsize_gb_4"), // GB_5("5g", "heapsize_gb_5"), // GB_6("6g", "heapsize_gb_6"), // GB_7("7g", "heapsize_gb_7"), // GB_8("8g", "heapsize_gb_8"), // GB_9("9g", "heapsize_gb_9"), // GB_10("10g", "heapsize_gb_10"), // GB_11("11g", "heapsize_gb_11"), // GB_12("12g", "heapsize_gb_12"), // GB_13("13g", "heapsize_gb_13"), // GB_14("14g", "heapsize_gb_14"), // GB_15("15g", "heapsize_gb_15"), // GB_16("16g", "heapsize_gb_16"); // // private final String sizeParameter; // private final String labelKey; // // JavaHeapSize(String sizeParameter, String labelKey) { // this.sizeParameter = sizeParameter; // this.labelKey = labelKey; // } // // public final boolean isUsed() { // return this != NOT_USED; // } // // public final String getSizeParameter() { // return sizeParameter; // } // // @Override // public final String toString() { // return BundleUtils.getLabel(labelKey); // } // } // // Path: src/main/java/org/terasology/launcher/util/Platform.java // public final class Platform { // // private static final Platform PLATFORM = new Platform(); // // private String os; // private String arch; // // /** // * Constructs platform information for the current host system. // * Simplifies operating system name to one of `linux`, `mac`, `windows` if applicable. // * Simplifies operating system architecture to one of `32` and `64` if applicable. // */ // private Platform() { // final String platformOs = System.getProperty("os.name").toLowerCase(); // // TODO: consider using regex // if (platformOs.startsWith("linux")) { // os = "linux"; // } else if (platformOs.startsWith("mac os")) { // os = "mac"; // } else if (platformOs.startsWith("windows")) { // os = "windows"; // } else { // os = platformOs; // } // // final String platformArch = System.getProperty("os.arch"); // if (platformArch.equals("x86_64") || platformArch.equals("amd64")) { // arch = "64"; // } else if (platformArch.equals("x86") || platformArch.equals("i386")) { // arch = "32"; // } else { // arch = platformArch; // } // } // // /** // * @return the simplified operating system name as platform os // */ // public String getOs() { // return os; // } // // /** // * @return the simplified operating system architecture as platform arch // */ // public String getArch() { // return arch; // } // // public boolean isLinux() { // return os.equals("linux"); // } // // public boolean isMac() { // return os.equals("mac"); // } // // public boolean isWindows() { // return os.equals("windows"); // } // // public String toString() { // return "OS '" + os + "', arch '" + arch + "'"; // } // // /** // * Get information on the host platform the launcher is currently running on. // * // * @return the platform // */ // public static Platform getPlatform() { // return PLATFORM; // } // }
import com.vdurmont.semver4j.Semver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.event.Level; import org.terasology.launcher.util.JavaHeapSize; import org.terasology.launcher.util.Platform; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable;
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.game; /** * Takes the game and runtime options, provides something that will launch a process. * * @see <a href="https://docs.oracle.com/en/java/javase/14/docs/specs/man/java.html#overview-of-java-options">java command manual</a> */ class GameStarter implements Callable<Process> { private static final Logger logger = LoggerFactory.getLogger(GameStarter.class); final ProcessBuilder processBuilder; private final Semver engineVersion; /** * @param installation the directory under which we will find {@code libs/Terasology.jar}, also used as the process's * working directory * @param gameDataDirectory {@code -homedir}, the directory where Terasology's data files (saves & etc) are kept * @param heapMin java's {@code -Xms} * @param heapMax java's {@code -Xmx} * @param javaParams additional arguments for the {@code java} command line * @param gameParams additional arguments for the Terasology command line * @param logLevel the minimum level of log events Terasology will include on its output stream to us */
// Path: src/main/java/org/terasology/launcher/util/JavaHeapSize.java // public enum JavaHeapSize { // // NOT_USED("", "heapsize_notUsed"), // MB_256("256m", "heapsize_mb_256"), // MB_512("512m", "heapsize_mb_512"), // MB_768("768m", "heapsize_mb_768"), // GB_1("1g", "heapsize_gb_1"), // GB_1_5("1536m", "heapsize_gb_1_5"), // GB_2("2g", "heapsize_gb_2"), // GB_2_5("2560m", "heapsize_gb_2_5"), // GB_3("3g", "heapsize_gb_3"), // GB_4("4g", "heapsize_gb_4"), // GB_5("5g", "heapsize_gb_5"), // GB_6("6g", "heapsize_gb_6"), // GB_7("7g", "heapsize_gb_7"), // GB_8("8g", "heapsize_gb_8"), // GB_9("9g", "heapsize_gb_9"), // GB_10("10g", "heapsize_gb_10"), // GB_11("11g", "heapsize_gb_11"), // GB_12("12g", "heapsize_gb_12"), // GB_13("13g", "heapsize_gb_13"), // GB_14("14g", "heapsize_gb_14"), // GB_15("15g", "heapsize_gb_15"), // GB_16("16g", "heapsize_gb_16"); // // private final String sizeParameter; // private final String labelKey; // // JavaHeapSize(String sizeParameter, String labelKey) { // this.sizeParameter = sizeParameter; // this.labelKey = labelKey; // } // // public final boolean isUsed() { // return this != NOT_USED; // } // // public final String getSizeParameter() { // return sizeParameter; // } // // @Override // public final String toString() { // return BundleUtils.getLabel(labelKey); // } // } // // Path: src/main/java/org/terasology/launcher/util/Platform.java // public final class Platform { // // private static final Platform PLATFORM = new Platform(); // // private String os; // private String arch; // // /** // * Constructs platform information for the current host system. // * Simplifies operating system name to one of `linux`, `mac`, `windows` if applicable. // * Simplifies operating system architecture to one of `32` and `64` if applicable. // */ // private Platform() { // final String platformOs = System.getProperty("os.name").toLowerCase(); // // TODO: consider using regex // if (platformOs.startsWith("linux")) { // os = "linux"; // } else if (platformOs.startsWith("mac os")) { // os = "mac"; // } else if (platformOs.startsWith("windows")) { // os = "windows"; // } else { // os = platformOs; // } // // final String platformArch = System.getProperty("os.arch"); // if (platformArch.equals("x86_64") || platformArch.equals("amd64")) { // arch = "64"; // } else if (platformArch.equals("x86") || platformArch.equals("i386")) { // arch = "32"; // } else { // arch = platformArch; // } // } // // /** // * @return the simplified operating system name as platform os // */ // public String getOs() { // return os; // } // // /** // * @return the simplified operating system architecture as platform arch // */ // public String getArch() { // return arch; // } // // public boolean isLinux() { // return os.equals("linux"); // } // // public boolean isMac() { // return os.equals("mac"); // } // // public boolean isWindows() { // return os.equals("windows"); // } // // public String toString() { // return "OS '" + os + "', arch '" + arch + "'"; // } // // /** // * Get information on the host platform the launcher is currently running on. // * // * @return the platform // */ // public static Platform getPlatform() { // return PLATFORM; // } // } // Path: src/main/java/org/terasology/launcher/game/GameStarter.java import com.vdurmont.semver4j.Semver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.event.Level; import org.terasology.launcher.util.JavaHeapSize; import org.terasology.launcher.util.Platform; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; // Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.game; /** * Takes the game and runtime options, provides something that will launch a process. * * @see <a href="https://docs.oracle.com/en/java/javase/14/docs/specs/man/java.html#overview-of-java-options">java command manual</a> */ class GameStarter implements Callable<Process> { private static final Logger logger = LoggerFactory.getLogger(GameStarter.class); final ProcessBuilder processBuilder; private final Semver engineVersion; /** * @param installation the directory under which we will find {@code libs/Terasology.jar}, also used as the process's * working directory * @param gameDataDirectory {@code -homedir}, the directory where Terasology's data files (saves & etc) are kept * @param heapMin java's {@code -Xms} * @param heapMax java's {@code -Xmx} * @param javaParams additional arguments for the {@code java} command line * @param gameParams additional arguments for the Terasology command line * @param logLevel the minimum level of log events Terasology will include on its output stream to us */
GameStarter(Installation installation, Path gameDataDirectory, JavaHeapSize heapMin, JavaHeapSize heapMax,
MovingBlocks/TerasologyLauncher
src/main/java/org/terasology/launcher/game/GameStarter.java
// Path: src/main/java/org/terasology/launcher/util/JavaHeapSize.java // public enum JavaHeapSize { // // NOT_USED("", "heapsize_notUsed"), // MB_256("256m", "heapsize_mb_256"), // MB_512("512m", "heapsize_mb_512"), // MB_768("768m", "heapsize_mb_768"), // GB_1("1g", "heapsize_gb_1"), // GB_1_5("1536m", "heapsize_gb_1_5"), // GB_2("2g", "heapsize_gb_2"), // GB_2_5("2560m", "heapsize_gb_2_5"), // GB_3("3g", "heapsize_gb_3"), // GB_4("4g", "heapsize_gb_4"), // GB_5("5g", "heapsize_gb_5"), // GB_6("6g", "heapsize_gb_6"), // GB_7("7g", "heapsize_gb_7"), // GB_8("8g", "heapsize_gb_8"), // GB_9("9g", "heapsize_gb_9"), // GB_10("10g", "heapsize_gb_10"), // GB_11("11g", "heapsize_gb_11"), // GB_12("12g", "heapsize_gb_12"), // GB_13("13g", "heapsize_gb_13"), // GB_14("14g", "heapsize_gb_14"), // GB_15("15g", "heapsize_gb_15"), // GB_16("16g", "heapsize_gb_16"); // // private final String sizeParameter; // private final String labelKey; // // JavaHeapSize(String sizeParameter, String labelKey) { // this.sizeParameter = sizeParameter; // this.labelKey = labelKey; // } // // public final boolean isUsed() { // return this != NOT_USED; // } // // public final String getSizeParameter() { // return sizeParameter; // } // // @Override // public final String toString() { // return BundleUtils.getLabel(labelKey); // } // } // // Path: src/main/java/org/terasology/launcher/util/Platform.java // public final class Platform { // // private static final Platform PLATFORM = new Platform(); // // private String os; // private String arch; // // /** // * Constructs platform information for the current host system. // * Simplifies operating system name to one of `linux`, `mac`, `windows` if applicable. // * Simplifies operating system architecture to one of `32` and `64` if applicable. // */ // private Platform() { // final String platformOs = System.getProperty("os.name").toLowerCase(); // // TODO: consider using regex // if (platformOs.startsWith("linux")) { // os = "linux"; // } else if (platformOs.startsWith("mac os")) { // os = "mac"; // } else if (platformOs.startsWith("windows")) { // os = "windows"; // } else { // os = platformOs; // } // // final String platformArch = System.getProperty("os.arch"); // if (platformArch.equals("x86_64") || platformArch.equals("amd64")) { // arch = "64"; // } else if (platformArch.equals("x86") || platformArch.equals("i386")) { // arch = "32"; // } else { // arch = platformArch; // } // } // // /** // * @return the simplified operating system name as platform os // */ // public String getOs() { // return os; // } // // /** // * @return the simplified operating system architecture as platform arch // */ // public String getArch() { // return arch; // } // // public boolean isLinux() { // return os.equals("linux"); // } // // public boolean isMac() { // return os.equals("mac"); // } // // public boolean isWindows() { // return os.equals("windows"); // } // // public String toString() { // return "OS '" + os + "', arch '" + arch + "'"; // } // // /** // * Get information on the host platform the launcher is currently running on. // * // * @return the platform // */ // public static Platform getPlatform() { // return PLATFORM; // } // }
import com.vdurmont.semver4j.Semver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.event.Level; import org.terasology.launcher.util.JavaHeapSize; import org.terasology.launcher.util.Platform; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable;
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.game; /** * Takes the game and runtime options, provides something that will launch a process. * * @see <a href="https://docs.oracle.com/en/java/javase/14/docs/specs/man/java.html#overview-of-java-options">java command manual</a> */ class GameStarter implements Callable<Process> { private static final Logger logger = LoggerFactory.getLogger(GameStarter.class); final ProcessBuilder processBuilder; private final Semver engineVersion; /** * @param installation the directory under which we will find {@code libs/Terasology.jar}, also used as the process's * working directory * @param gameDataDirectory {@code -homedir}, the directory where Terasology's data files (saves & etc) are kept * @param heapMin java's {@code -Xms} * @param heapMax java's {@code -Xmx} * @param javaParams additional arguments for the {@code java} command line * @param gameParams additional arguments for the Terasology command line * @param logLevel the minimum level of log events Terasology will include on its output stream to us */ GameStarter(Installation installation, Path gameDataDirectory, JavaHeapSize heapMin, JavaHeapSize heapMax, List<String> javaParams, List<String> gameParams, Level logLevel) throws IOException { engineVersion = installation.getEngineVersion(); var gamePath = installation.path;
// Path: src/main/java/org/terasology/launcher/util/JavaHeapSize.java // public enum JavaHeapSize { // // NOT_USED("", "heapsize_notUsed"), // MB_256("256m", "heapsize_mb_256"), // MB_512("512m", "heapsize_mb_512"), // MB_768("768m", "heapsize_mb_768"), // GB_1("1g", "heapsize_gb_1"), // GB_1_5("1536m", "heapsize_gb_1_5"), // GB_2("2g", "heapsize_gb_2"), // GB_2_5("2560m", "heapsize_gb_2_5"), // GB_3("3g", "heapsize_gb_3"), // GB_4("4g", "heapsize_gb_4"), // GB_5("5g", "heapsize_gb_5"), // GB_6("6g", "heapsize_gb_6"), // GB_7("7g", "heapsize_gb_7"), // GB_8("8g", "heapsize_gb_8"), // GB_9("9g", "heapsize_gb_9"), // GB_10("10g", "heapsize_gb_10"), // GB_11("11g", "heapsize_gb_11"), // GB_12("12g", "heapsize_gb_12"), // GB_13("13g", "heapsize_gb_13"), // GB_14("14g", "heapsize_gb_14"), // GB_15("15g", "heapsize_gb_15"), // GB_16("16g", "heapsize_gb_16"); // // private final String sizeParameter; // private final String labelKey; // // JavaHeapSize(String sizeParameter, String labelKey) { // this.sizeParameter = sizeParameter; // this.labelKey = labelKey; // } // // public final boolean isUsed() { // return this != NOT_USED; // } // // public final String getSizeParameter() { // return sizeParameter; // } // // @Override // public final String toString() { // return BundleUtils.getLabel(labelKey); // } // } // // Path: src/main/java/org/terasology/launcher/util/Platform.java // public final class Platform { // // private static final Platform PLATFORM = new Platform(); // // private String os; // private String arch; // // /** // * Constructs platform information for the current host system. // * Simplifies operating system name to one of `linux`, `mac`, `windows` if applicable. // * Simplifies operating system architecture to one of `32` and `64` if applicable. // */ // private Platform() { // final String platformOs = System.getProperty("os.name").toLowerCase(); // // TODO: consider using regex // if (platformOs.startsWith("linux")) { // os = "linux"; // } else if (platformOs.startsWith("mac os")) { // os = "mac"; // } else if (platformOs.startsWith("windows")) { // os = "windows"; // } else { // os = platformOs; // } // // final String platformArch = System.getProperty("os.arch"); // if (platformArch.equals("x86_64") || platformArch.equals("amd64")) { // arch = "64"; // } else if (platformArch.equals("x86") || platformArch.equals("i386")) { // arch = "32"; // } else { // arch = platformArch; // } // } // // /** // * @return the simplified operating system name as platform os // */ // public String getOs() { // return os; // } // // /** // * @return the simplified operating system architecture as platform arch // */ // public String getArch() { // return arch; // } // // public boolean isLinux() { // return os.equals("linux"); // } // // public boolean isMac() { // return os.equals("mac"); // } // // public boolean isWindows() { // return os.equals("windows"); // } // // public String toString() { // return "OS '" + os + "', arch '" + arch + "'"; // } // // /** // * Get information on the host platform the launcher is currently running on. // * // * @return the platform // */ // public static Platform getPlatform() { // return PLATFORM; // } // } // Path: src/main/java/org/terasology/launcher/game/GameStarter.java import com.vdurmont.semver4j.Semver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.event.Level; import org.terasology.launcher.util.JavaHeapSize; import org.terasology.launcher.util.Platform; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; // Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.game; /** * Takes the game and runtime options, provides something that will launch a process. * * @see <a href="https://docs.oracle.com/en/java/javase/14/docs/specs/man/java.html#overview-of-java-options">java command manual</a> */ class GameStarter implements Callable<Process> { private static final Logger logger = LoggerFactory.getLogger(GameStarter.class); final ProcessBuilder processBuilder; private final Semver engineVersion; /** * @param installation the directory under which we will find {@code libs/Terasology.jar}, also used as the process's * working directory * @param gameDataDirectory {@code -homedir}, the directory where Terasology's data files (saves & etc) are kept * @param heapMin java's {@code -Xms} * @param heapMax java's {@code -Xmx} * @param javaParams additional arguments for the {@code java} command line * @param gameParams additional arguments for the Terasology command line * @param logLevel the minimum level of log events Terasology will include on its output stream to us */ GameStarter(Installation installation, Path gameDataDirectory, JavaHeapSize heapMin, JavaHeapSize heapMax, List<String> javaParams, List<String> gameParams, Level logLevel) throws IOException { engineVersion = installation.getEngineVersion(); var gamePath = installation.path;
final boolean isMac = Platform.getPlatform().isMac();
MovingBlocks/TerasologyLauncher
src/main/java/org/terasology/launcher/repositories/JenkinsRepositoryAdapter.java
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors;
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.repositories; /** * Repository adapter for http://jenkins.terasology.io. * <p> * On the new Jenkins we can make use of the {@code versionInfo.properties} file to get the display name for the release * along other metadata (for instance, the corresponding engine version). * <p> * However, this means that we are doing {@code n + 1} API calls for fetching {@code n} release packages on each * launcher start. */ class JenkinsRepositoryAdapter implements ReleaseRepository { private static final Logger logger = LoggerFactory.getLogger(JenkinsRepositoryAdapter.class); private static final String BASE_URL = "http://jenkins.terasology.io/teraorg/job/Terasology/"; private static final String API_FILTER = "api/json?tree=" + "builds[" + "number," + "timestamp," + "result," + "artifacts[fileName,relativePath]," + "url]"; private static final String TERASOLOGY_ZIP_PATTERN = "Terasology.*zip"; private final JenkinsClient client;
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // } // Path: src/main/java/org/terasology/launcher/repositories/JenkinsRepositoryAdapter.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; // Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.repositories; /** * Repository adapter for http://jenkins.terasology.io. * <p> * On the new Jenkins we can make use of the {@code versionInfo.properties} file to get the display name for the release * along other metadata (for instance, the corresponding engine version). * <p> * However, this means that we are doing {@code n + 1} API calls for fetching {@code n} release packages on each * launcher start. */ class JenkinsRepositoryAdapter implements ReleaseRepository { private static final Logger logger = LoggerFactory.getLogger(JenkinsRepositoryAdapter.class); private static final String BASE_URL = "http://jenkins.terasology.io/teraorg/job/Terasology/"; private static final String API_FILTER = "api/json?tree=" + "builds[" + "number," + "timestamp," + "result," + "artifacts[fileName,relativePath]," + "url]"; private static final String TERASOLOGY_ZIP_PATTERN = "Terasology.*zip"; private final JenkinsClient client;
private final Build buildProfile;
MovingBlocks/TerasologyLauncher
src/main/java/org/terasology/launcher/repositories/JenkinsRepositoryAdapter.java
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors;
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.repositories; /** * Repository adapter for http://jenkins.terasology.io. * <p> * On the new Jenkins we can make use of the {@code versionInfo.properties} file to get the display name for the release * along other metadata (for instance, the corresponding engine version). * <p> * However, this means that we are doing {@code n + 1} API calls for fetching {@code n} release packages on each * launcher start. */ class JenkinsRepositoryAdapter implements ReleaseRepository { private static final Logger logger = LoggerFactory.getLogger(JenkinsRepositoryAdapter.class); private static final String BASE_URL = "http://jenkins.terasology.io/teraorg/job/Terasology/"; private static final String API_FILTER = "api/json?tree=" + "builds[" + "number," + "timestamp," + "result," + "artifacts[fileName,relativePath]," + "url]"; private static final String TERASOLOGY_ZIP_PATTERN = "Terasology.*zip"; private final JenkinsClient client; private final Build buildProfile;
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // } // Path: src/main/java/org/terasology/launcher/repositories/JenkinsRepositoryAdapter.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; // Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.repositories; /** * Repository adapter for http://jenkins.terasology.io. * <p> * On the new Jenkins we can make use of the {@code versionInfo.properties} file to get the display name for the release * along other metadata (for instance, the corresponding engine version). * <p> * However, this means that we are doing {@code n + 1} API calls for fetching {@code n} release packages on each * launcher start. */ class JenkinsRepositoryAdapter implements ReleaseRepository { private static final Logger logger = LoggerFactory.getLogger(JenkinsRepositoryAdapter.class); private static final String BASE_URL = "http://jenkins.terasology.io/teraorg/job/Terasology/"; private static final String API_FILTER = "api/json?tree=" + "builds[" + "number," + "timestamp," + "result," + "artifacts[fileName,relativePath]," + "url]"; private static final String TERASOLOGY_ZIP_PATTERN = "Terasology.*zip"; private final JenkinsClient client; private final Build buildProfile;
private final Profile profile;
MovingBlocks/TerasologyLauncher
src/main/java/org/terasology/launcher/repositories/JenkinsRepositoryAdapter.java
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors;
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.repositories; /** * Repository adapter for http://jenkins.terasology.io. * <p> * On the new Jenkins we can make use of the {@code versionInfo.properties} file to get the display name for the release * along other metadata (for instance, the corresponding engine version). * <p> * However, this means that we are doing {@code n + 1} API calls for fetching {@code n} release packages on each * launcher start. */ class JenkinsRepositoryAdapter implements ReleaseRepository { private static final Logger logger = LoggerFactory.getLogger(JenkinsRepositoryAdapter.class); private static final String BASE_URL = "http://jenkins.terasology.io/teraorg/job/Terasology/"; private static final String API_FILTER = "api/json?tree=" + "builds[" + "number," + "timestamp," + "result," + "artifacts[fileName,relativePath]," + "url]"; private static final String TERASOLOGY_ZIP_PATTERN = "Terasology.*zip"; private final JenkinsClient client; private final Build buildProfile; private final Profile profile; private final URL apiUrl; JenkinsRepositoryAdapter(Profile profile, Build buildProfile, JenkinsClient client) { this.client = client; this.buildProfile = buildProfile; this.profile = profile; this.apiUrl = unsafeToUrl(BASE_URL + job(profileToJobName(profile)) + job(buildProfileToJobName(buildProfile)) + API_FILTER); }
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // } // Path: src/main/java/org/terasology/launcher/repositories/JenkinsRepositoryAdapter.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; // Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.repositories; /** * Repository adapter for http://jenkins.terasology.io. * <p> * On the new Jenkins we can make use of the {@code versionInfo.properties} file to get the display name for the release * along other metadata (for instance, the corresponding engine version). * <p> * However, this means that we are doing {@code n + 1} API calls for fetching {@code n} release packages on each * launcher start. */ class JenkinsRepositoryAdapter implements ReleaseRepository { private static final Logger logger = LoggerFactory.getLogger(JenkinsRepositoryAdapter.class); private static final String BASE_URL = "http://jenkins.terasology.io/teraorg/job/Terasology/"; private static final String API_FILTER = "api/json?tree=" + "builds[" + "number," + "timestamp," + "result," + "artifacts[fileName,relativePath]," + "url]"; private static final String TERASOLOGY_ZIP_PATTERN = "Terasology.*zip"; private final JenkinsClient client; private final Build buildProfile; private final Profile profile; private final URL apiUrl; JenkinsRepositoryAdapter(Profile profile, Build buildProfile, JenkinsClient client) { this.client = client; this.buildProfile = buildProfile; this.profile = profile; this.apiUrl = unsafeToUrl(BASE_URL + job(profileToJobName(profile)) + job(buildProfileToJobName(buildProfile)) + API_FILTER); }
public List<GameRelease> fetchReleases() {
MovingBlocks/TerasologyLauncher
src/main/java/org/terasology/launcher/repositories/JenkinsRepositoryAdapter.java
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors;
this.profile = profile; this.apiUrl = unsafeToUrl(BASE_URL + job(profileToJobName(profile)) + job(buildProfileToJobName(buildProfile)) + API_FILTER); } public List<GameRelease> fetchReleases() { final List<GameRelease> pkgList = new LinkedList<>(); logger.debug("fetching releases from '{}'", apiUrl); final Jenkins.ApiResult result; try { result = client.request(apiUrl); } catch (InterruptedException e) { logger.warn("Interrupted while fetching packages from: {}", apiUrl, e); return Collections.emptyList(); } if (result != null && result.builds != null) { for (Jenkins.Build build : result.builds) { computeReleaseFrom(build).ifPresent(pkgList::add); } } else { logger.warn("Failed to fetch packages from: {}", apiUrl); } return pkgList; } private Optional<GameRelease> computeReleaseFrom(Jenkins.Build jenkinsBuildInfo) { if (hasAcceptableResult(jenkinsBuildInfo)) { final URL url = client.getArtifactUrl(jenkinsBuildInfo, TERASOLOGY_ZIP_PATTERN);
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // } // Path: src/main/java/org/terasology/launcher/repositories/JenkinsRepositoryAdapter.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; this.profile = profile; this.apiUrl = unsafeToUrl(BASE_URL + job(profileToJobName(profile)) + job(buildProfileToJobName(buildProfile)) + API_FILTER); } public List<GameRelease> fetchReleases() { final List<GameRelease> pkgList = new LinkedList<>(); logger.debug("fetching releases from '{}'", apiUrl); final Jenkins.ApiResult result; try { result = client.request(apiUrl); } catch (InterruptedException e) { logger.warn("Interrupted while fetching packages from: {}", apiUrl, e); return Collections.emptyList(); } if (result != null && result.builds != null) { for (Jenkins.Build build : result.builds) { computeReleaseFrom(build).ifPresent(pkgList::add); } } else { logger.warn("Failed to fetch packages from: {}", apiUrl); } return pkgList; } private Optional<GameRelease> computeReleaseFrom(Jenkins.Build jenkinsBuildInfo) { if (hasAcceptableResult(jenkinsBuildInfo)) { final URL url = client.getArtifactUrl(jenkinsBuildInfo, TERASOLOGY_ZIP_PATTERN);
final ReleaseMetadata metadata = computeReleaseMetadataFrom(jenkinsBuildInfo);
MovingBlocks/TerasologyLauncher
src/main/java/org/terasology/launcher/repositories/JenkinsRepositoryAdapter.java
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors;
this.apiUrl = unsafeToUrl(BASE_URL + job(profileToJobName(profile)) + job(buildProfileToJobName(buildProfile)) + API_FILTER); } public List<GameRelease> fetchReleases() { final List<GameRelease> pkgList = new LinkedList<>(); logger.debug("fetching releases from '{}'", apiUrl); final Jenkins.ApiResult result; try { result = client.request(apiUrl); } catch (InterruptedException e) { logger.warn("Interrupted while fetching packages from: {}", apiUrl, e); return Collections.emptyList(); } if (result != null && result.builds != null) { for (Jenkins.Build build : result.builds) { computeReleaseFrom(build).ifPresent(pkgList::add); } } else { logger.warn("Failed to fetch packages from: {}", apiUrl); } return pkgList; } private Optional<GameRelease> computeReleaseFrom(Jenkins.Build jenkinsBuildInfo) { if (hasAcceptableResult(jenkinsBuildInfo)) { final URL url = client.getArtifactUrl(jenkinsBuildInfo, TERASOLOGY_ZIP_PATTERN); final ReleaseMetadata metadata = computeReleaseMetadataFrom(jenkinsBuildInfo);
// Path: src/main/java/org/terasology/launcher/model/Build.java // public enum Build { // STABLE, // NIGHTLY // } // // Path: src/main/java/org/terasology/launcher/model/GameIdentifier.java // public class GameIdentifier { // // private static final Logger logger = LoggerFactory.getLogger(GameIdentifier.class); // // final String displayVersion; // final Build build; // final Profile profile; // // public GameIdentifier(String displayVersion, Build build, Profile profile) { // this.displayVersion = displayVersion; // this.build = build; // this.profile = profile; // } // // public String getDisplayVersion() { // return displayVersion; // } // // public Build getBuild() { // return build; // } // // public Profile getProfile() { // return profile; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // GameIdentifier that = (GameIdentifier) o; // return displayVersion.equals(that.displayVersion) // && build == that.build // && profile == that.profile; // } // // @Override // public int hashCode() { // return Objects.hash(displayVersion, build, profile); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("version", displayVersion) // .add("build", build) // .add("profile", profile) // .toString(); // } // } // // Path: src/main/java/org/terasology/launcher/model/GameRelease.java // public class GameRelease { // final GameIdentifier id; // final ReleaseMetadata releaseMetadata; // final URL url; // // public GameRelease(GameIdentifier id, URL url, ReleaseMetadata releaseMetadata) { // this.id = id; // this.url = url; // this.releaseMetadata = releaseMetadata; // } // // public GameIdentifier getId() { // return id; // } // // public URL getUrl() { // return url; // } // // /** // * The changelog associated with the game release // */ // public String getChangelog() { // return releaseMetadata.getChangelog(); // } // // public Date getTimestamp() { // return releaseMetadata.getTimestamp(); // } // // @Override // public String toString() { // return id.getDisplayVersion(); // } // } // // Path: src/main/java/org/terasology/launcher/model/Profile.java // public enum Profile { // OMEGA, // ENGINE // } // // Path: src/main/java/org/terasology/launcher/model/ReleaseMetadata.java // public class ReleaseMetadata { // private final String changelog; // private final Date timestamp; // // public ReleaseMetadata(String changelog, Date timestamp) { // this.changelog = changelog; // this.timestamp = timestamp; // } // // /** // * The change log of this release as a single markdown string. // */ // public String getChangelog() { // return changelog; // } // // /** // * The timestamp of the CI run that built this release. // */ // public Date getTimestamp() { // return timestamp; // } // } // Path: src/main/java/org/terasology/launcher/repositories/JenkinsRepositoryAdapter.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.model.Build; import org.terasology.launcher.model.GameIdentifier; import org.terasology.launcher.model.GameRelease; import org.terasology.launcher.model.Profile; import org.terasology.launcher.model.ReleaseMetadata; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; this.apiUrl = unsafeToUrl(BASE_URL + job(profileToJobName(profile)) + job(buildProfileToJobName(buildProfile)) + API_FILTER); } public List<GameRelease> fetchReleases() { final List<GameRelease> pkgList = new LinkedList<>(); logger.debug("fetching releases from '{}'", apiUrl); final Jenkins.ApiResult result; try { result = client.request(apiUrl); } catch (InterruptedException e) { logger.warn("Interrupted while fetching packages from: {}", apiUrl, e); return Collections.emptyList(); } if (result != null && result.builds != null) { for (Jenkins.Build build : result.builds) { computeReleaseFrom(build).ifPresent(pkgList::add); } } else { logger.warn("Failed to fetch packages from: {}", apiUrl); } return pkgList; } private Optional<GameRelease> computeReleaseFrom(Jenkins.Build jenkinsBuildInfo) { if (hasAcceptableResult(jenkinsBuildInfo)) { final URL url = client.getArtifactUrl(jenkinsBuildInfo, TERASOLOGY_ZIP_PATTERN); final ReleaseMetadata metadata = computeReleaseMetadataFrom(jenkinsBuildInfo);
final Optional<GameIdentifier> id = computeIdentifierFrom(jenkinsBuildInfo);
MovingBlocks/TerasologyLauncher
src/main/java/org/terasology/launcher/settings/LauncherSettingsValidator.java
// Path: src/main/java/org/terasology/launcher/util/JavaHeapSize.java // public enum JavaHeapSize { // // NOT_USED("", "heapsize_notUsed"), // MB_256("256m", "heapsize_mb_256"), // MB_512("512m", "heapsize_mb_512"), // MB_768("768m", "heapsize_mb_768"), // GB_1("1g", "heapsize_gb_1"), // GB_1_5("1536m", "heapsize_gb_1_5"), // GB_2("2g", "heapsize_gb_2"), // GB_2_5("2560m", "heapsize_gb_2_5"), // GB_3("3g", "heapsize_gb_3"), // GB_4("4g", "heapsize_gb_4"), // GB_5("5g", "heapsize_gb_5"), // GB_6("6g", "heapsize_gb_6"), // GB_7("7g", "heapsize_gb_7"), // GB_8("8g", "heapsize_gb_8"), // GB_9("9g", "heapsize_gb_9"), // GB_10("10g", "heapsize_gb_10"), // GB_11("11g", "heapsize_gb_11"), // GB_12("12g", "heapsize_gb_12"), // GB_13("13g", "heapsize_gb_13"), // GB_14("14g", "heapsize_gb_14"), // GB_15("15g", "heapsize_gb_15"), // GB_16("16g", "heapsize_gb_16"); // // private final String sizeParameter; // private final String labelKey; // // JavaHeapSize(String sizeParameter, String labelKey) { // this.sizeParameter = sizeParameter; // this.labelKey = labelKey; // } // // public final boolean isUsed() { // return this != NOT_USED; // } // // public final String getSizeParameter() { // return sizeParameter; // } // // @Override // public final String toString() { // return BundleUtils.getLabel(labelKey); // } // }
import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.util.JavaHeapSize; import java.util.Arrays; import java.util.List; import java.util.Set;
// Copyright 2020 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.settings; /** * Provides methods to check launcher settings and correct if invalid. */ public final class LauncherSettingsValidator { private static final Logger logger = LoggerFactory.getLogger(LauncherSettingsValidator.class); private static final Set<String> DEPRECATED_PARAMETERS = Sets.newHashSet("-XX:+UseParNewGC", "-XX:+UseConcMarkSweepGC", "-XX:ParallelGCThreads=10"); private static final List<SettingsValidationRule> RULES = Arrays.asList( // Rule for max heap size new SettingsValidationRule(
// Path: src/main/java/org/terasology/launcher/util/JavaHeapSize.java // public enum JavaHeapSize { // // NOT_USED("", "heapsize_notUsed"), // MB_256("256m", "heapsize_mb_256"), // MB_512("512m", "heapsize_mb_512"), // MB_768("768m", "heapsize_mb_768"), // GB_1("1g", "heapsize_gb_1"), // GB_1_5("1536m", "heapsize_gb_1_5"), // GB_2("2g", "heapsize_gb_2"), // GB_2_5("2560m", "heapsize_gb_2_5"), // GB_3("3g", "heapsize_gb_3"), // GB_4("4g", "heapsize_gb_4"), // GB_5("5g", "heapsize_gb_5"), // GB_6("6g", "heapsize_gb_6"), // GB_7("7g", "heapsize_gb_7"), // GB_8("8g", "heapsize_gb_8"), // GB_9("9g", "heapsize_gb_9"), // GB_10("10g", "heapsize_gb_10"), // GB_11("11g", "heapsize_gb_11"), // GB_12("12g", "heapsize_gb_12"), // GB_13("13g", "heapsize_gb_13"), // GB_14("14g", "heapsize_gb_14"), // GB_15("15g", "heapsize_gb_15"), // GB_16("16g", "heapsize_gb_16"); // // private final String sizeParameter; // private final String labelKey; // // JavaHeapSize(String sizeParameter, String labelKey) { // this.sizeParameter = sizeParameter; // this.labelKey = labelKey; // } // // public final boolean isUsed() { // return this != NOT_USED; // } // // public final String getSizeParameter() { // return sizeParameter; // } // // @Override // public final String toString() { // return BundleUtils.getLabel(labelKey); // } // } // Path: src/main/java/org/terasology/launcher/settings/LauncherSettingsValidator.java import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.launcher.util.JavaHeapSize; import java.util.Arrays; import java.util.List; import java.util.Set; // Copyright 2020 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.launcher.settings; /** * Provides methods to check launcher settings and correct if invalid. */ public final class LauncherSettingsValidator { private static final Logger logger = LoggerFactory.getLogger(LauncherSettingsValidator.class); private static final Set<String> DEPRECATED_PARAMETERS = Sets.newHashSet("-XX:+UseParNewGC", "-XX:+UseConcMarkSweepGC", "-XX:ParallelGCThreads=10"); private static final List<SettingsValidationRule> RULES = Arrays.asList( // Rule for max heap size new SettingsValidationRule(
s -> !(System.getProperty("os.arch").equals("x86") && s.maxHeapSize.get().compareTo(JavaHeapSize.GB_1_5) > 0),
smartcat-labs/ranger
src/main/java/io/smartcat/ranger/core/RangeValueLocalDateTime.java
// Path: src/main/java/io/smartcat/ranger/distribution/UniformDistribution.java // public class UniformDistribution implements Distribution { // // private Random random = new Random(); // // @Override // public int nextInt(int bound) { // return random.nextInt(bound); // } // // @Override // public int nextInt(int lower, int upper) { // return random.ints(1, lower, upper).findFirst().getAsInt(); // } // // @Override // public long nextLong(long bound) { // return random.longs(1, 0, bound).findFirst().getAsLong(); // } // // @Override // public long nextLong(long lower, long upper) { // return random.longs(1, lower, upper).findFirst().getAsLong(); // } // // @Override // public double nextDouble(double lower, double upper) { // return random.doubles(1, lower, upper).findFirst().getAsDouble(); // } // // @Override // public boolean nextBoolean() { // return random.nextBoolean(); // } // }
import java.time.LocalDateTime; import java.time.ZoneOffset; import io.smartcat.ranger.distribution.Distribution; import io.smartcat.ranger.distribution.UniformDistribution;
package io.smartcat.ranger.core; /** * Randomly generates {@link LocalDateTime} value within specified range. */ public class RangeValueLocalDateTime extends Value<LocalDateTime> { private final LocalDateTime beginning; private final LocalDateTime end; private final boolean useEdgeCases; private final Distribution distribution; private boolean beginningEdgeCaseUsed = false; private boolean endEdgeCaseUsed = false; /** * Constructs range value with specified <code>range</code>. <code>useEdgeCases</code> is set to <code>true</code> * and <code>distribution</code> is set to {@link UniformDistribution}. * * @param beginning The beginning of the range. * @param end The end of the range. */ public RangeValueLocalDateTime(LocalDateTime beginning, LocalDateTime end) { this(beginning, end, true); } /** * Constructs range value with specified <code>range</code> and <code>useEdgeCases</code>. <code>distribution</code> * is set to {@link UniformDistribution}. * * @param beginning The beginning of the range. * @param end The end of the range. * @param useEdgeCases Indicates whether to create edge cases as first two values or not. */ public RangeValueLocalDateTime(LocalDateTime beginning, LocalDateTime end, boolean useEdgeCases) {
// Path: src/main/java/io/smartcat/ranger/distribution/UniformDistribution.java // public class UniformDistribution implements Distribution { // // private Random random = new Random(); // // @Override // public int nextInt(int bound) { // return random.nextInt(bound); // } // // @Override // public int nextInt(int lower, int upper) { // return random.ints(1, lower, upper).findFirst().getAsInt(); // } // // @Override // public long nextLong(long bound) { // return random.longs(1, 0, bound).findFirst().getAsLong(); // } // // @Override // public long nextLong(long lower, long upper) { // return random.longs(1, lower, upper).findFirst().getAsLong(); // } // // @Override // public double nextDouble(double lower, double upper) { // return random.doubles(1, lower, upper).findFirst().getAsDouble(); // } // // @Override // public boolean nextBoolean() { // return random.nextBoolean(); // } // } // Path: src/main/java/io/smartcat/ranger/core/RangeValueLocalDateTime.java import java.time.LocalDateTime; import java.time.ZoneOffset; import io.smartcat.ranger.distribution.Distribution; import io.smartcat.ranger.distribution.UniformDistribution; package io.smartcat.ranger.core; /** * Randomly generates {@link LocalDateTime} value within specified range. */ public class RangeValueLocalDateTime extends Value<LocalDateTime> { private final LocalDateTime beginning; private final LocalDateTime end; private final boolean useEdgeCases; private final Distribution distribution; private boolean beginningEdgeCaseUsed = false; private boolean endEdgeCaseUsed = false; /** * Constructs range value with specified <code>range</code>. <code>useEdgeCases</code> is set to <code>true</code> * and <code>distribution</code> is set to {@link UniformDistribution}. * * @param beginning The beginning of the range. * @param end The end of the range. */ public RangeValueLocalDateTime(LocalDateTime beginning, LocalDateTime end) { this(beginning, end, true); } /** * Constructs range value with specified <code>range</code> and <code>useEdgeCases</code>. <code>distribution</code> * is set to {@link UniformDistribution}. * * @param beginning The beginning of the range. * @param end The end of the range. * @param useEdgeCases Indicates whether to create edge cases as first two values or not. */ public RangeValueLocalDateTime(LocalDateTime beginning, LocalDateTime end, boolean useEdgeCases) {
this(beginning, end, useEdgeCases, new UniformDistribution());
smartcat-labs/ranger
src/main/java/io/smartcat/ranger/ObjectGeneratorBuilder.java
// Path: src/main/java/io/smartcat/ranger/core/ConstantValue.java // public class ConstantValue<T> extends Value<T> { // // /** // * Constructs constant value which will always return specified <code>value</code>. // * // * @param value Value to be returned. // */ // public ConstantValue(T value) { // this.val = value; // } // // /** // * Helper method to construct {@link ConstantValue}. // * // * @param value Value to be returned by created constant value. // * @param <T> Type this value would evaluate to. // * // * @return An instance of {@link ConstantValue}. // */ // public static <T> ConstantValue<T> of(T value) { // return new ConstantValue<T>(value); // } // }
import java.util.LinkedHashMap; import java.util.Map; import com.fasterxml.jackson.databind.ObjectMapper; import io.smartcat.ranger.core.CompositeValue; import io.smartcat.ranger.core.ConstantValue; import io.smartcat.ranger.core.TypeConverterValue; import io.smartcat.ranger.core.Value;
package io.smartcat.ranger; /** * Builder for {@link ObjectGenerator}. */ public class ObjectGeneratorBuilder { private final Map<String, Value<?>> propertyValues; /** * Constructs {@link ObjectGeneratorBuilder}. */ public ObjectGeneratorBuilder() { this.propertyValues = new LinkedHashMap<>(); } /** * Sets the value to be used for generating values for property. * * @param property Name of the property. * @param value Value to be used for generating values. * @param <V> Type of object which value will be generate. * @return This builder. */ @SuppressWarnings({ "rawtypes" }) public <V> ObjectGeneratorBuilder prop(String property, V value) { propertyValues.put(property,
// Path: src/main/java/io/smartcat/ranger/core/ConstantValue.java // public class ConstantValue<T> extends Value<T> { // // /** // * Constructs constant value which will always return specified <code>value</code>. // * // * @param value Value to be returned. // */ // public ConstantValue(T value) { // this.val = value; // } // // /** // * Helper method to construct {@link ConstantValue}. // * // * @param value Value to be returned by created constant value. // * @param <T> Type this value would evaluate to. // * // * @return An instance of {@link ConstantValue}. // */ // public static <T> ConstantValue<T> of(T value) { // return new ConstantValue<T>(value); // } // } // Path: src/main/java/io/smartcat/ranger/ObjectGeneratorBuilder.java import java.util.LinkedHashMap; import java.util.Map; import com.fasterxml.jackson.databind.ObjectMapper; import io.smartcat.ranger.core.CompositeValue; import io.smartcat.ranger.core.ConstantValue; import io.smartcat.ranger.core.TypeConverterValue; import io.smartcat.ranger.core.Value; package io.smartcat.ranger; /** * Builder for {@link ObjectGenerator}. */ public class ObjectGeneratorBuilder { private final Map<String, Value<?>> propertyValues; /** * Constructs {@link ObjectGeneratorBuilder}. */ public ObjectGeneratorBuilder() { this.propertyValues = new LinkedHashMap<>(); } /** * Sets the value to be used for generating values for property. * * @param property Name of the property. * @param value Value to be used for generating values. * @param <V> Type of object which value will be generate. * @return This builder. */ @SuppressWarnings({ "rawtypes" }) public <V> ObjectGeneratorBuilder prop(String property, V value) { propertyValues.put(property,
value instanceof ObjectGenerator ? ((ObjectGenerator) value).value : ConstantValue.of(value));
smartcat-labs/ranger
src/main/java/io/smartcat/ranger/core/RangeValue.java
// Path: src/main/java/io/smartcat/ranger/distribution/UniformDistribution.java // public class UniformDistribution implements Distribution { // // private Random random = new Random(); // // @Override // public int nextInt(int bound) { // return random.nextInt(bound); // } // // @Override // public int nextInt(int lower, int upper) { // return random.ints(1, lower, upper).findFirst().getAsInt(); // } // // @Override // public long nextLong(long bound) { // return random.longs(1, 0, bound).findFirst().getAsLong(); // } // // @Override // public long nextLong(long lower, long upper) { // return random.longs(1, lower, upper).findFirst().getAsLong(); // } // // @Override // public double nextDouble(double lower, double upper) { // return random.doubles(1, lower, upper).findFirst().getAsDouble(); // } // // @Override // public boolean nextBoolean() { // return random.nextBoolean(); // } // }
import io.smartcat.ranger.distribution.Distribution; import io.smartcat.ranger.distribution.UniformDistribution;
if (range == null) { throw new IllegalArgumentException("Range cannot be null."); } if (!range.isIncreasing()) { throw new InvalidRangeBoundsException("End of the range must be greater than the beginning of the range."); } if (distribution == null) { throw new IllegalArgumentException("Distribution cannot be null."); } this.beginning = range.getBeginning(); this.end = range.getEnd(); this.useEdgeCases = useEdgeCases; this.distribution = distribution; } /** * Default value for <code>useEdgeCases</code> property. * * @return Default value for <code>useEdgeCases</code> property. */ public static boolean defaultUseEdgeCases() { return false; } /** * Default value for <code>distribution</code> property. * * @return Default value for <code>distribution</code> property. */ public static Distribution defaultDistrbution() {
// Path: src/main/java/io/smartcat/ranger/distribution/UniformDistribution.java // public class UniformDistribution implements Distribution { // // private Random random = new Random(); // // @Override // public int nextInt(int bound) { // return random.nextInt(bound); // } // // @Override // public int nextInt(int lower, int upper) { // return random.ints(1, lower, upper).findFirst().getAsInt(); // } // // @Override // public long nextLong(long bound) { // return random.longs(1, 0, bound).findFirst().getAsLong(); // } // // @Override // public long nextLong(long lower, long upper) { // return random.longs(1, lower, upper).findFirst().getAsLong(); // } // // @Override // public double nextDouble(double lower, double upper) { // return random.doubles(1, lower, upper).findFirst().getAsDouble(); // } // // @Override // public boolean nextBoolean() { // return random.nextBoolean(); // } // } // Path: src/main/java/io/smartcat/ranger/core/RangeValue.java import io.smartcat.ranger.distribution.Distribution; import io.smartcat.ranger.distribution.UniformDistribution; if (range == null) { throw new IllegalArgumentException("Range cannot be null."); } if (!range.isIncreasing()) { throw new InvalidRangeBoundsException("End of the range must be greater than the beginning of the range."); } if (distribution == null) { throw new IllegalArgumentException("Distribution cannot be null."); } this.beginning = range.getBeginning(); this.end = range.getEnd(); this.useEdgeCases = useEdgeCases; this.distribution = distribution; } /** * Default value for <code>useEdgeCases</code> property. * * @return Default value for <code>useEdgeCases</code> property. */ public static boolean defaultUseEdgeCases() { return false; } /** * Default value for <code>distribution</code> property. * * @return Default value for <code>distribution</code> property. */ public static Distribution defaultDistrbution() {
return new UniformDistribution();
smartcat-labs/ranger
src/main/java/io/smartcat/ranger/parser/ConfigurationParser.java
// Path: src/main/java/io/smartcat/ranger/core/ConstantValue.java // public class ConstantValue<T> extends Value<T> { // // /** // * Constructs constant value which will always return specified <code>value</code>. // * // * @param value Value to be returned. // */ // public ConstantValue(T value) { // this.val = value; // } // // /** // * Helper method to construct {@link ConstantValue}. // * // * @param value Value to be returned by created constant value. // * @param <T> Type this value would evaluate to. // * // * @return An instance of {@link ConstantValue}. // */ // public static <T> ConstantValue<T> of(T value) { // return new ConstantValue<T>(value); // } // } // // Path: src/main/java/io/smartcat/ranger/core/ValueProxy.java // public class ValueProxy<T> extends Value<T> { // // private Value<T> delegate; // // /** // * Constructs proxy without delegate. // */ // public ValueProxy() { // } // // /** // * Constructs proxy with specified <code>delegate</code>. // * // * @param delegate Value which will be evaluated and cached. // */ // public ValueProxy(Value<T> delegate) { // setDelegate(delegate); // } // // /** // * Sets value to this proxy. // * // * @param delegate Value which will be evaluated and cached. // */ // public void setDelegate(Value<T> delegate) { // if (delegate == null) { // throw new IllegalArgumentException("Delegate cannot be null."); // } // this.delegate = delegate; // } // // @Override // public void reset() { // super.reset(); // checkDelegate(); // delegate.reset(); // } // // @Override // protected void eval() { // checkDelegate(); // val = delegate.get(); // } // // private void checkDelegate() { // if (delegate == null) { // throw new DelegateNotSetException(); // } // } // // /** // * Signals that delegate is not set. // */ // public static class DelegateNotSetException extends RuntimeException { // // private static final long serialVersionUID = 6257779717961934851L; // // /** // * Constructs {@link DelegateNotSetException} with default message. // */ // public DelegateNotSetException() { // super("Delegate not set for ValueProxy."); // } // } // }
import io.smartcat.ranger.ObjectGenerator; import io.smartcat.ranger.core.CompositeValue; import io.smartcat.ranger.core.ConstantValue; import io.smartcat.ranger.core.TypeConverterValue; import io.smartcat.ranger.core.Value; import io.smartcat.ranger.core.ValueProxy; import org.parboiled.Parboiled; import org.parboiled.parserunners.ReportingParseRunner; import org.parboiled.support.ParsingResult; import java.util.HashMap; import java.util.Map;
package io.smartcat.ranger.parser; /** * Constructs {@link ObjectGenerator} out of parsed configuration. */ public class ConfigurationParser { private static final String VALUES = "values"; private static final String OUTPUT = "output"; private final Map<String, Object> values; private final Object outputExpression;
// Path: src/main/java/io/smartcat/ranger/core/ConstantValue.java // public class ConstantValue<T> extends Value<T> { // // /** // * Constructs constant value which will always return specified <code>value</code>. // * // * @param value Value to be returned. // */ // public ConstantValue(T value) { // this.val = value; // } // // /** // * Helper method to construct {@link ConstantValue}. // * // * @param value Value to be returned by created constant value. // * @param <T> Type this value would evaluate to. // * // * @return An instance of {@link ConstantValue}. // */ // public static <T> ConstantValue<T> of(T value) { // return new ConstantValue<T>(value); // } // } // // Path: src/main/java/io/smartcat/ranger/core/ValueProxy.java // public class ValueProxy<T> extends Value<T> { // // private Value<T> delegate; // // /** // * Constructs proxy without delegate. // */ // public ValueProxy() { // } // // /** // * Constructs proxy with specified <code>delegate</code>. // * // * @param delegate Value which will be evaluated and cached. // */ // public ValueProxy(Value<T> delegate) { // setDelegate(delegate); // } // // /** // * Sets value to this proxy. // * // * @param delegate Value which will be evaluated and cached. // */ // public void setDelegate(Value<T> delegate) { // if (delegate == null) { // throw new IllegalArgumentException("Delegate cannot be null."); // } // this.delegate = delegate; // } // // @Override // public void reset() { // super.reset(); // checkDelegate(); // delegate.reset(); // } // // @Override // protected void eval() { // checkDelegate(); // val = delegate.get(); // } // // private void checkDelegate() { // if (delegate == null) { // throw new DelegateNotSetException(); // } // } // // /** // * Signals that delegate is not set. // */ // public static class DelegateNotSetException extends RuntimeException { // // private static final long serialVersionUID = 6257779717961934851L; // // /** // * Constructs {@link DelegateNotSetException} with default message. // */ // public DelegateNotSetException() { // super("Delegate not set for ValueProxy."); // } // } // } // Path: src/main/java/io/smartcat/ranger/parser/ConfigurationParser.java import io.smartcat.ranger.ObjectGenerator; import io.smartcat.ranger.core.CompositeValue; import io.smartcat.ranger.core.ConstantValue; import io.smartcat.ranger.core.TypeConverterValue; import io.smartcat.ranger.core.Value; import io.smartcat.ranger.core.ValueProxy; import org.parboiled.Parboiled; import org.parboiled.parserunners.ReportingParseRunner; import org.parboiled.support.ParsingResult; import java.util.HashMap; import java.util.Map; package io.smartcat.ranger.parser; /** * Constructs {@link ObjectGenerator} out of parsed configuration. */ public class ConfigurationParser { private static final String VALUES = "values"; private static final String OUTPUT = "output"; private final Map<String, Object> values; private final Object outputExpression;
private Map<String, ValueProxy<?>> proxyValues;
smartcat-labs/ranger
src/main/java/io/smartcat/ranger/parser/ConfigurationParser.java
// Path: src/main/java/io/smartcat/ranger/core/ConstantValue.java // public class ConstantValue<T> extends Value<T> { // // /** // * Constructs constant value which will always return specified <code>value</code>. // * // * @param value Value to be returned. // */ // public ConstantValue(T value) { // this.val = value; // } // // /** // * Helper method to construct {@link ConstantValue}. // * // * @param value Value to be returned by created constant value. // * @param <T> Type this value would evaluate to. // * // * @return An instance of {@link ConstantValue}. // */ // public static <T> ConstantValue<T> of(T value) { // return new ConstantValue<T>(value); // } // } // // Path: src/main/java/io/smartcat/ranger/core/ValueProxy.java // public class ValueProxy<T> extends Value<T> { // // private Value<T> delegate; // // /** // * Constructs proxy without delegate. // */ // public ValueProxy() { // } // // /** // * Constructs proxy with specified <code>delegate</code>. // * // * @param delegate Value which will be evaluated and cached. // */ // public ValueProxy(Value<T> delegate) { // setDelegate(delegate); // } // // /** // * Sets value to this proxy. // * // * @param delegate Value which will be evaluated and cached. // */ // public void setDelegate(Value<T> delegate) { // if (delegate == null) { // throw new IllegalArgumentException("Delegate cannot be null."); // } // this.delegate = delegate; // } // // @Override // public void reset() { // super.reset(); // checkDelegate(); // delegate.reset(); // } // // @Override // protected void eval() { // checkDelegate(); // val = delegate.get(); // } // // private void checkDelegate() { // if (delegate == null) { // throw new DelegateNotSetException(); // } // } // // /** // * Signals that delegate is not set. // */ // public static class DelegateNotSetException extends RuntimeException { // // private static final long serialVersionUID = 6257779717961934851L; // // /** // * Constructs {@link DelegateNotSetException} with default message. // */ // public DelegateNotSetException() { // super("Delegate not set for ValueProxy."); // } // } // }
import io.smartcat.ranger.ObjectGenerator; import io.smartcat.ranger.core.CompositeValue; import io.smartcat.ranger.core.ConstantValue; import io.smartcat.ranger.core.TypeConverterValue; import io.smartcat.ranger.core.Value; import io.smartcat.ranger.core.ValueProxy; import org.parboiled.Parboiled; import org.parboiled.parserunners.ReportingParseRunner; import org.parboiled.support.ParsingResult; import java.util.HashMap; import java.util.Map;
@SuppressWarnings("unchecked") private Value<?> parse(String parentName, Object def) { if (def instanceof Map) { return parseCompositeValue(parentName, (Map<String, Object>) def); } else { return parseSimpleValue(parentName, def); } } @SuppressWarnings({ "rawtypes", "unchecked" }) private Value<?> parseCompositeValue(String parentName, Map<String, Object> def) { Map<String, Value<?>> values = new HashMap<>(); for (String property : def.keySet()) { String fullName = parentName + "." + property; Value<?> val = parse(fullName, def.get(property)); ValueProxy proxy = proxyValues.get(fullName); proxy.setDelegate(val); values.put(property, proxy); } return new CompositeValue(values); } private Value<?> parseSimpleValue(String parentName, Object def) { // handle String as expression and all other types as primitives if (def instanceof String) { parser.setParentName(stripOffLastReference(parentName)); ParsingResult<Value<?>> result = parseRunner.run((String) def); return result.valueStack.pop(); } else {
// Path: src/main/java/io/smartcat/ranger/core/ConstantValue.java // public class ConstantValue<T> extends Value<T> { // // /** // * Constructs constant value which will always return specified <code>value</code>. // * // * @param value Value to be returned. // */ // public ConstantValue(T value) { // this.val = value; // } // // /** // * Helper method to construct {@link ConstantValue}. // * // * @param value Value to be returned by created constant value. // * @param <T> Type this value would evaluate to. // * // * @return An instance of {@link ConstantValue}. // */ // public static <T> ConstantValue<T> of(T value) { // return new ConstantValue<T>(value); // } // } // // Path: src/main/java/io/smartcat/ranger/core/ValueProxy.java // public class ValueProxy<T> extends Value<T> { // // private Value<T> delegate; // // /** // * Constructs proxy without delegate. // */ // public ValueProxy() { // } // // /** // * Constructs proxy with specified <code>delegate</code>. // * // * @param delegate Value which will be evaluated and cached. // */ // public ValueProxy(Value<T> delegate) { // setDelegate(delegate); // } // // /** // * Sets value to this proxy. // * // * @param delegate Value which will be evaluated and cached. // */ // public void setDelegate(Value<T> delegate) { // if (delegate == null) { // throw new IllegalArgumentException("Delegate cannot be null."); // } // this.delegate = delegate; // } // // @Override // public void reset() { // super.reset(); // checkDelegate(); // delegate.reset(); // } // // @Override // protected void eval() { // checkDelegate(); // val = delegate.get(); // } // // private void checkDelegate() { // if (delegate == null) { // throw new DelegateNotSetException(); // } // } // // /** // * Signals that delegate is not set. // */ // public static class DelegateNotSetException extends RuntimeException { // // private static final long serialVersionUID = 6257779717961934851L; // // /** // * Constructs {@link DelegateNotSetException} with default message. // */ // public DelegateNotSetException() { // super("Delegate not set for ValueProxy."); // } // } // } // Path: src/main/java/io/smartcat/ranger/parser/ConfigurationParser.java import io.smartcat.ranger.ObjectGenerator; import io.smartcat.ranger.core.CompositeValue; import io.smartcat.ranger.core.ConstantValue; import io.smartcat.ranger.core.TypeConverterValue; import io.smartcat.ranger.core.Value; import io.smartcat.ranger.core.ValueProxy; import org.parboiled.Parboiled; import org.parboiled.parserunners.ReportingParseRunner; import org.parboiled.support.ParsingResult; import java.util.HashMap; import java.util.Map; @SuppressWarnings("unchecked") private Value<?> parse(String parentName, Object def) { if (def instanceof Map) { return parseCompositeValue(parentName, (Map<String, Object>) def); } else { return parseSimpleValue(parentName, def); } } @SuppressWarnings({ "rawtypes", "unchecked" }) private Value<?> parseCompositeValue(String parentName, Map<String, Object> def) { Map<String, Value<?>> values = new HashMap<>(); for (String property : def.keySet()) { String fullName = parentName + "." + property; Value<?> val = parse(fullName, def.get(property)); ValueProxy proxy = proxyValues.get(fullName); proxy.setDelegate(val); values.put(property, proxy); } return new CompositeValue(values); } private Value<?> parseSimpleValue(String parentName, Object def) { // handle String as expression and all other types as primitives if (def instanceof String) { parser.setParentName(stripOffLastReference(parentName)); ParsingResult<Value<?>> result = parseRunner.run((String) def); return result.valueStack.pop(); } else {
return ConstantValue.of(def);
smartcat-labs/ranger
src/main/java/io/smartcat/ranger/core/RandomContentStringValue.java
// Path: src/main/java/io/smartcat/ranger/distribution/UniformDistribution.java // public class UniformDistribution implements Distribution { // // private Random random = new Random(); // // @Override // public int nextInt(int bound) { // return random.nextInt(bound); // } // // @Override // public int nextInt(int lower, int upper) { // return random.ints(1, lower, upper).findFirst().getAsInt(); // } // // @Override // public long nextLong(long bound) { // return random.longs(1, 0, bound).findFirst().getAsLong(); // } // // @Override // public long nextLong(long lower, long upper) { // return random.longs(1, lower, upper).findFirst().getAsLong(); // } // // @Override // public double nextDouble(double lower, double upper) { // return random.doubles(1, lower, upper).findFirst().getAsDouble(); // } // // @Override // public boolean nextBoolean() { // return random.nextBoolean(); // } // }
import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import io.smartcat.ranger.distribution.Distribution; import io.smartcat.ranger.distribution.UniformDistribution;
package io.smartcat.ranger.core; /** * Generates random strings of specified <code>length</code> and from specified character ranges. */ public class RandomContentStringValue extends Value<String> { private static final List<Range<Character>> DEFAULT_RANGES = Arrays.asList(new Range<Character>('a', 'z'), new Range<Character>('A', 'Z'), new Range<Character>('0', '9')); private final Value<Integer> lengthValue; private final List<Character> possibleCharacters; private final Distribution distribution; /** * Constructs random content string value with specified <code>lengthValue</code> and default character range. * * @param lengthValue Value that returns integer which represents length of generated string. It should never * generate length that is less than 1. */ public RandomContentStringValue(Value<Integer> lengthValue) { this(lengthValue, DEFAULT_RANGES); } /** * Constructs random content string value with specified <code>lengthValue</code> and specified * <code>charRanges</code>. * * @param lengthValue Value that returns integer which represents length of generated string. It should never * generate length that is less than 1. * @param charRanges Ranges of characters from which string will be constructed. */ public RandomContentStringValue(Value<Integer> lengthValue, List<Range<Character>> charRanges) { if (lengthValue == null) { throw new IllegalArgumentException("lengthValue cannot be null."); } this.lengthValue = lengthValue; Set<Character> chars = new HashSet<>(); for (Range<Character> range : charRanges) { if (!range.isIncreasing()) { throw new IllegalArgumentException("All ranges must be increasing."); } for (Character c = range.getBeginning(); c <= range.getEnd(); c++) { chars.add(c); } } possibleCharacters = new ArrayList<>(chars);
// Path: src/main/java/io/smartcat/ranger/distribution/UniformDistribution.java // public class UniformDistribution implements Distribution { // // private Random random = new Random(); // // @Override // public int nextInt(int bound) { // return random.nextInt(bound); // } // // @Override // public int nextInt(int lower, int upper) { // return random.ints(1, lower, upper).findFirst().getAsInt(); // } // // @Override // public long nextLong(long bound) { // return random.longs(1, 0, bound).findFirst().getAsLong(); // } // // @Override // public long nextLong(long lower, long upper) { // return random.longs(1, lower, upper).findFirst().getAsLong(); // } // // @Override // public double nextDouble(double lower, double upper) { // return random.doubles(1, lower, upper).findFirst().getAsDouble(); // } // // @Override // public boolean nextBoolean() { // return random.nextBoolean(); // } // } // Path: src/main/java/io/smartcat/ranger/core/RandomContentStringValue.java import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import io.smartcat.ranger.distribution.Distribution; import io.smartcat.ranger.distribution.UniformDistribution; package io.smartcat.ranger.core; /** * Generates random strings of specified <code>length</code> and from specified character ranges. */ public class RandomContentStringValue extends Value<String> { private static final List<Range<Character>> DEFAULT_RANGES = Arrays.asList(new Range<Character>('a', 'z'), new Range<Character>('A', 'Z'), new Range<Character>('0', '9')); private final Value<Integer> lengthValue; private final List<Character> possibleCharacters; private final Distribution distribution; /** * Constructs random content string value with specified <code>lengthValue</code> and default character range. * * @param lengthValue Value that returns integer which represents length of generated string. It should never * generate length that is less than 1. */ public RandomContentStringValue(Value<Integer> lengthValue) { this(lengthValue, DEFAULT_RANGES); } /** * Constructs random content string value with specified <code>lengthValue</code> and specified * <code>charRanges</code>. * * @param lengthValue Value that returns integer which represents length of generated string. It should never * generate length that is less than 1. * @param charRanges Ranges of characters from which string will be constructed. */ public RandomContentStringValue(Value<Integer> lengthValue, List<Range<Character>> charRanges) { if (lengthValue == null) { throw new IllegalArgumentException("lengthValue cannot be null."); } this.lengthValue = lengthValue; Set<Character> chars = new HashSet<>(); for (Range<Character> range : charRanges) { if (!range.isIncreasing()) { throw new IllegalArgumentException("All ranges must be increasing."); } for (Character c = range.getBeginning(); c <= range.getEnd(); c++) { chars.add(c); } } possibleCharacters = new ArrayList<>(chars);
distribution = new UniformDistribution();
smartcat-labs/ranger
src/main/java/io/smartcat/ranger/core/RandomLengthListValue.java
// Path: src/main/java/io/smartcat/ranger/distribution/UniformDistribution.java // public class UniformDistribution implements Distribution { // // private Random random = new Random(); // // @Override // public int nextInt(int bound) { // return random.nextInt(bound); // } // // @Override // public int nextInt(int lower, int upper) { // return random.ints(1, lower, upper).findFirst().getAsInt(); // } // // @Override // public long nextLong(long bound) { // return random.longs(1, 0, bound).findFirst().getAsLong(); // } // // @Override // public long nextLong(long lower, long upper) { // return random.longs(1, lower, upper).findFirst().getAsLong(); // } // // @Override // public double nextDouble(double lower, double upper) { // return random.doubles(1, lower, upper).findFirst().getAsDouble(); // } // // @Override // public boolean nextBoolean() { // return random.nextBoolean(); // } // }
import io.smartcat.ranger.distribution.Distribution; import io.smartcat.ranger.distribution.UniformDistribution; import java.util.ArrayList; import java.util.Collections; import java.util.List;
package io.smartcat.ranger.core; /** * Generates random length list out of specified values. * * @param <T> Type which evaluated list will contain. */ public class RandomLengthListValue<T> extends Value<List<T>> { private final int minLength; private final int maxLength; private Value<T> elementGenerator; private final Distribution distribution; /** * Constructs random length list value out of specified values. * * @param minLength Minimum list length * @param maxLength Maximum list length * @param elementGenerator Element generator */ public RandomLengthListValue(int minLength, int maxLength, Value<T> elementGenerator) {
// Path: src/main/java/io/smartcat/ranger/distribution/UniformDistribution.java // public class UniformDistribution implements Distribution { // // private Random random = new Random(); // // @Override // public int nextInt(int bound) { // return random.nextInt(bound); // } // // @Override // public int nextInt(int lower, int upper) { // return random.ints(1, lower, upper).findFirst().getAsInt(); // } // // @Override // public long nextLong(long bound) { // return random.longs(1, 0, bound).findFirst().getAsLong(); // } // // @Override // public long nextLong(long lower, long upper) { // return random.longs(1, lower, upper).findFirst().getAsLong(); // } // // @Override // public double nextDouble(double lower, double upper) { // return random.doubles(1, lower, upper).findFirst().getAsDouble(); // } // // @Override // public boolean nextBoolean() { // return random.nextBoolean(); // } // } // Path: src/main/java/io/smartcat/ranger/core/RandomLengthListValue.java import io.smartcat.ranger.distribution.Distribution; import io.smartcat.ranger.distribution.UniformDistribution; import java.util.ArrayList; import java.util.Collections; import java.util.List; package io.smartcat.ranger.core; /** * Generates random length list out of specified values. * * @param <T> Type which evaluated list will contain. */ public class RandomLengthListValue<T> extends Value<List<T>> { private final int minLength; private final int maxLength; private Value<T> elementGenerator; private final Distribution distribution; /** * Constructs random length list value out of specified values. * * @param minLength Minimum list length * @param maxLength Maximum list length * @param elementGenerator Element generator */ public RandomLengthListValue(int minLength, int maxLength, Value<T> elementGenerator) {
this(minLength, maxLength, elementGenerator, new UniformDistribution());
smartcat-labs/ranger
src/main/java/io/smartcat/ranger/core/DiscreteValue.java
// Path: src/main/java/io/smartcat/ranger/distribution/UniformDistribution.java // public class UniformDistribution implements Distribution { // // private Random random = new Random(); // // @Override // public int nextInt(int bound) { // return random.nextInt(bound); // } // // @Override // public int nextInt(int lower, int upper) { // return random.ints(1, lower, upper).findFirst().getAsInt(); // } // // @Override // public long nextLong(long bound) { // return random.longs(1, 0, bound).findFirst().getAsLong(); // } // // @Override // public long nextLong(long lower, long upper) { // return random.longs(1, lower, upper).findFirst().getAsLong(); // } // // @Override // public double nextDouble(double lower, double upper) { // return random.doubles(1, lower, upper).findFirst().getAsDouble(); // } // // @Override // public boolean nextBoolean() { // return random.nextBoolean(); // } // }
import java.util.ArrayList; import java.util.List; import io.smartcat.ranger.distribution.Distribution; import io.smartcat.ranger.distribution.UniformDistribution;
package io.smartcat.ranger.core; /** * Randomly selects one of the provided values following the specified distribution. * * @param <T> Type this value would evaluate to. */ public class DiscreteValue<T> extends Value<T> { private final List<Value<T>> values; private final Distribution distribution; /** * Constructs discrete value with specified <code>values</code>, <code>distribution</code> is set to Uniform * distribution. * * @param values List of possible values. */ public DiscreteValue(List<Value<T>> values) {
// Path: src/main/java/io/smartcat/ranger/distribution/UniformDistribution.java // public class UniformDistribution implements Distribution { // // private Random random = new Random(); // // @Override // public int nextInt(int bound) { // return random.nextInt(bound); // } // // @Override // public int nextInt(int lower, int upper) { // return random.ints(1, lower, upper).findFirst().getAsInt(); // } // // @Override // public long nextLong(long bound) { // return random.longs(1, 0, bound).findFirst().getAsLong(); // } // // @Override // public long nextLong(long lower, long upper) { // return random.longs(1, lower, upper).findFirst().getAsLong(); // } // // @Override // public double nextDouble(double lower, double upper) { // return random.doubles(1, lower, upper).findFirst().getAsDouble(); // } // // @Override // public boolean nextBoolean() { // return random.nextBoolean(); // } // } // Path: src/main/java/io/smartcat/ranger/core/DiscreteValue.java import java.util.ArrayList; import java.util.List; import io.smartcat.ranger.distribution.Distribution; import io.smartcat.ranger.distribution.UniformDistribution; package io.smartcat.ranger.core; /** * Randomly selects one of the provided values following the specified distribution. * * @param <T> Type this value would evaluate to. */ public class DiscreteValue<T> extends Value<T> { private final List<Value<T>> values; private final Distribution distribution; /** * Constructs discrete value with specified <code>values</code>, <code>distribution</code> is set to Uniform * distribution. * * @param values List of possible values. */ public DiscreteValue(List<Value<T>> values) {
this(values, new UniformDistribution());
mk23/jmxproxy
src/test/java/com/github/mk23/jmxproxy/jmx/tests/ConnectionCredentialsTest.java
// Path: src/main/java/com/github/mk23/jmxproxy/jmx/ConnectionCredentials.java // public class ConnectionCredentials { // @NotEmpty // @JsonProperty // private final String username; // // @NotEmpty // @JsonProperty // private final String password; // // private final String combined; // // private final boolean enabled; // // /** // * <p>Default disabled constructor.</p> // * // * Creates a disabled credential object used for anonymous agent access. // */ // public ConnectionCredentials() { // username = null; // password = null; // combined = null; // // enabled = false; // } // // /** // * <p>Default constructor.</p> // * // * Sets the instance username and password {@link String}s from provided parameters. // * Builds a single combined credential string for the hashCode computation. // * // * @param username username {@link String} for the new credential instance. // * @param password password {@link String} for the new credential instance. // */ // public ConnectionCredentials( // @JsonProperty("username") final String username, // @JsonProperty("password") final String password // ) { // if (username == null || password == null) { // this.username = null; // this.password = null; // this.combined = null; // // this.enabled = false; // } else { // this.username = username; // this.password = password; // this.combined = username + "\0" + password; // // this.enabled = true; // } // } // // /** // * <p>Getter for username.</p> // * // * Fetches the stored username {@link String}. // * // * @return username string. // */ // public final String getUsername() { // return username; // } // // /** // * <p>Getter for password.</p> // * // * Fetches the stored password {@link String}. // * // * @return password string. // */ // public final String getPassword() { // return password; // } // // /** // * <p>Getter for enabled.</p> // * // * Fetches enabled status for this credential object. // * // * @return enabled boolean. // */ // public final boolean isEnabled() { // return enabled; // } // // /** {@inheritDoc} */ // @Override // public final boolean equals(final Object obj) { // if (obj != null && !(obj instanceof ConnectionCredentials)) { // return false; // } // // ConnectionCredentials peer = (obj != null) ? (ConnectionCredentials) obj : new ConnectionCredentials(); // // if (!enabled) { // return !peer.isEnabled(); // } // // return username.equals(peer.getUsername()) && password.equals(peer.getPassword()); // } // // /** {@inheritDoc} */ // @Override // public final int hashCode() { // return combined != null ? combined.hashCode() : 0; // } // }
import com.github.mk23.jmxproxy.jmx.ConnectionCredentials; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse;
package com.github.mk23.jmxproxy.jmx.tests; public class ConnectionCredentialsTest { @Rule public TestName name = new TestName(); @Before public void printTestName() { System.out.println(" -> " + name.getMethodName()); } @Test public void checkAuthenticatedEquals() throws Exception {
// Path: src/main/java/com/github/mk23/jmxproxy/jmx/ConnectionCredentials.java // public class ConnectionCredentials { // @NotEmpty // @JsonProperty // private final String username; // // @NotEmpty // @JsonProperty // private final String password; // // private final String combined; // // private final boolean enabled; // // /** // * <p>Default disabled constructor.</p> // * // * Creates a disabled credential object used for anonymous agent access. // */ // public ConnectionCredentials() { // username = null; // password = null; // combined = null; // // enabled = false; // } // // /** // * <p>Default constructor.</p> // * // * Sets the instance username and password {@link String}s from provided parameters. // * Builds a single combined credential string for the hashCode computation. // * // * @param username username {@link String} for the new credential instance. // * @param password password {@link String} for the new credential instance. // */ // public ConnectionCredentials( // @JsonProperty("username") final String username, // @JsonProperty("password") final String password // ) { // if (username == null || password == null) { // this.username = null; // this.password = null; // this.combined = null; // // this.enabled = false; // } else { // this.username = username; // this.password = password; // this.combined = username + "\0" + password; // // this.enabled = true; // } // } // // /** // * <p>Getter for username.</p> // * // * Fetches the stored username {@link String}. // * // * @return username string. // */ // public final String getUsername() { // return username; // } // // /** // * <p>Getter for password.</p> // * // * Fetches the stored password {@link String}. // * // * @return password string. // */ // public final String getPassword() { // return password; // } // // /** // * <p>Getter for enabled.</p> // * // * Fetches enabled status for this credential object. // * // * @return enabled boolean. // */ // public final boolean isEnabled() { // return enabled; // } // // /** {@inheritDoc} */ // @Override // public final boolean equals(final Object obj) { // if (obj != null && !(obj instanceof ConnectionCredentials)) { // return false; // } // // ConnectionCredentials peer = (obj != null) ? (ConnectionCredentials) obj : new ConnectionCredentials(); // // if (!enabled) { // return !peer.isEnabled(); // } // // return username.equals(peer.getUsername()) && password.equals(peer.getPassword()); // } // // /** {@inheritDoc} */ // @Override // public final int hashCode() { // return combined != null ? combined.hashCode() : 0; // } // } // Path: src/test/java/com/github/mk23/jmxproxy/jmx/tests/ConnectionCredentialsTest.java import com.github.mk23.jmxproxy.jmx.ConnectionCredentials; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; package com.github.mk23.jmxproxy.jmx.tests; public class ConnectionCredentialsTest { @Rule public TestName name = new TestName(); @Before public void printTestName() { System.out.println(" -> " + name.getMethodName()); } @Test public void checkAuthenticatedEquals() throws Exception {
final ConnectionCredentials auth1 = new ConnectionCredentials(new String("user"), new String("pass"));
mk23/jmxproxy
src/test/java/com/github/mk23/jmxproxy/util/tests/HistoryTest.java
// Path: src/main/java/com/github/mk23/jmxproxy/util/History.java // public class History<T> { // private List<T> objects; // private int length; // private int pointer; // private boolean wrapped; // // /** // * <p>Default constructor.</p> // * // * Initializes the {@link Object} store {@link List} to the given history size. // * // * @param length number of {@link Object} values to keep in history. // */ // public History(final int length) { // this.length = length; // // pointer = -1; // objects = new ArrayList<T>(Collections.nCopies(length, (T) null)); // } // // /** // * <p>Adds a item to the store.</p> // * // * Adds a new item to the history store. If the number of items exceeds the size // * of the store, the oldest item is overwritten. // * // * @param item newest item to add to the store. // */ // public final void add(final T item) { // wrapped = ++pointer == length; // pointer = pointer % length; // // objects.set(pointer, item); // } // // /** // * <p>Gets the latest item from the history store.</p> // * // * Gets the latest single item from the history store. // * // * @return Latest item from the history store or null if empty. // */ // public final T getLast() { // return pointer < 0 ? null : objects.get(pointer % length); // } // // /** // * <p>Gets the full item history from the store.</p> // * // * Gets the full item history from the store as a {@link List}. // * // * @return {@link List} of the full history. May be empty if history has no items. // */ // public final List<T> get() { // return get(length); // } // // /** // * <p>Gets a limited item history from the store.</p> // * // * Gets a limited history from the store as a {@link List}, based // * on requested item count. If the specified count is less than 0 or greater than // * the number of entries, a full history is returned instead. // * // * @param limit number of items to retreive from the history store. // * // * @return {@link List} of the requested slice of history. May be empty if history has no items. // */ // public final List<T> get(final int limit) { // if (pointer < 0) { // return Collections.emptyList(); // } // // int head = pointer + length * Boolean.compare(wrapped, false); // int size = Math.min(limit > 0 ? limit : Integer.MAX_VALUE, Math.min(head + 1, length)); // List<T> rval = new ArrayList<T>(size); // // for (int i = 0; i < size; i++) { // rval.add(objects.get((head - i) % length)); // } // // return rval; // } // }
import com.github.mk23.jmxproxy.util.History; import java.util.ArrayList; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue;
package com.github.mk23.jmxproxy.util.tests; public class HistoryTest { @Rule public TestName name = new TestName(); @Before public void printTestName() { System.out.println(" -> " + name.getMethodName()); } @Test public void check0Single() throws Exception {
// Path: src/main/java/com/github/mk23/jmxproxy/util/History.java // public class History<T> { // private List<T> objects; // private int length; // private int pointer; // private boolean wrapped; // // /** // * <p>Default constructor.</p> // * // * Initializes the {@link Object} store {@link List} to the given history size. // * // * @param length number of {@link Object} values to keep in history. // */ // public History(final int length) { // this.length = length; // // pointer = -1; // objects = new ArrayList<T>(Collections.nCopies(length, (T) null)); // } // // /** // * <p>Adds a item to the store.</p> // * // * Adds a new item to the history store. If the number of items exceeds the size // * of the store, the oldest item is overwritten. // * // * @param item newest item to add to the store. // */ // public final void add(final T item) { // wrapped = ++pointer == length; // pointer = pointer % length; // // objects.set(pointer, item); // } // // /** // * <p>Gets the latest item from the history store.</p> // * // * Gets the latest single item from the history store. // * // * @return Latest item from the history store or null if empty. // */ // public final T getLast() { // return pointer < 0 ? null : objects.get(pointer % length); // } // // /** // * <p>Gets the full item history from the store.</p> // * // * Gets the full item history from the store as a {@link List}. // * // * @return {@link List} of the full history. May be empty if history has no items. // */ // public final List<T> get() { // return get(length); // } // // /** // * <p>Gets a limited item history from the store.</p> // * // * Gets a limited history from the store as a {@link List}, based // * on requested item count. If the specified count is less than 0 or greater than // * the number of entries, a full history is returned instead. // * // * @param limit number of items to retreive from the history store. // * // * @return {@link List} of the requested slice of history. May be empty if history has no items. // */ // public final List<T> get(final int limit) { // if (pointer < 0) { // return Collections.emptyList(); // } // // int head = pointer + length * Boolean.compare(wrapped, false); // int size = Math.min(limit > 0 ? limit : Integer.MAX_VALUE, Math.min(head + 1, length)); // List<T> rval = new ArrayList<T>(size); // // for (int i = 0; i < size; i++) { // rval.add(objects.get((head - i) % length)); // } // // return rval; // } // } // Path: src/test/java/com/github/mk23/jmxproxy/util/tests/HistoryTest.java import com.github.mk23.jmxproxy.util.History; import java.util.ArrayList; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; package com.github.mk23.jmxproxy.util.tests; public class HistoryTest { @Rule public TestName name = new TestName(); @Before public void printTestName() { System.out.println(" -> " + name.getMethodName()); } @Test public void check0Single() throws Exception {
History<String> history = new History<String>(3);
mk23/jmxproxy
src/test/java/com/github/mk23/jmxproxy/jmx/tests/TimeoutRMISocketFactoryTest.java
// Path: src/main/java/com/github/mk23/jmxproxy/jmx/TimeoutRMISocketFactory.java // public class TimeoutRMISocketFactory extends RMISocketFactory { // private static final Logger LOG = LoggerFactory.getLogger(TimeoutRMISocketFactory.class); // // private int timeout; // // /** // * <p>Default constructor.</p> // * // * Initializes the timeout to the specified value in milliseconds. // * // * @param timeout milliseconds to pass to Socket's connect() method. // */ // public TimeoutRMISocketFactory(final int timeout) { // super(); // // this.timeout = timeout; // } // // /** // * <p>Setter for timeout.</p> // * // * Resets the timeout to the specified milliseconds value. // * // * @param timeout milliseconds to pass to Socket's connect() method. // * // * @return Modified TimeoutRMISocketFactory for setter chaining. // */ // public final TimeoutRMISocketFactory setTimeout(final int timeout) { // this.timeout = timeout; // return this; // } // // /** {@inheritDoc} */ // @Override // public final Socket createSocket(final String host, final int port) throws IOException { // LOG.debug("creating new socket with " + timeout + "ms timeout"); // // Socket socket = new Socket(); // socket.connect(new InetSocketAddress(host, port), timeout); // // return socket; // } // // /** {@inheritDoc} */ // @Override // public final ServerSocket createServerSocket(final int port) throws IOException { // return new ServerSocket(port); // } // }
import com.github.mk23.jmxproxy.jmx.TimeoutRMISocketFactory; import java.net.BindException; import java.net.ConnectException; import java.net.SocketTimeoutException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TestName; import static org.junit.Assert.assertNotNull;
package com.github.mk23.jmxproxy.jmx.tests; public class TimeoutRMISocketFactoryTest { private final String validHost = "localhost"; private final String invalidHost = "192.0.2.1"; private final int serverPort = Integer.getInteger("com.sun.management.jmxremote.port"); private final int connectTimeout = 500; @Rule public ExpectedException thrown = ExpectedException.none(); @Rule public TestName name = new TestName(); @Before public void printTestName() { System.out.println(" -> " + name.getMethodName()); } @Test public void checkClientValidHostValidPort() throws Exception {
// Path: src/main/java/com/github/mk23/jmxproxy/jmx/TimeoutRMISocketFactory.java // public class TimeoutRMISocketFactory extends RMISocketFactory { // private static final Logger LOG = LoggerFactory.getLogger(TimeoutRMISocketFactory.class); // // private int timeout; // // /** // * <p>Default constructor.</p> // * // * Initializes the timeout to the specified value in milliseconds. // * // * @param timeout milliseconds to pass to Socket's connect() method. // */ // public TimeoutRMISocketFactory(final int timeout) { // super(); // // this.timeout = timeout; // } // // /** // * <p>Setter for timeout.</p> // * // * Resets the timeout to the specified milliseconds value. // * // * @param timeout milliseconds to pass to Socket's connect() method. // * // * @return Modified TimeoutRMISocketFactory for setter chaining. // */ // public final TimeoutRMISocketFactory setTimeout(final int timeout) { // this.timeout = timeout; // return this; // } // // /** {@inheritDoc} */ // @Override // public final Socket createSocket(final String host, final int port) throws IOException { // LOG.debug("creating new socket with " + timeout + "ms timeout"); // // Socket socket = new Socket(); // socket.connect(new InetSocketAddress(host, port), timeout); // // return socket; // } // // /** {@inheritDoc} */ // @Override // public final ServerSocket createServerSocket(final int port) throws IOException { // return new ServerSocket(port); // } // } // Path: src/test/java/com/github/mk23/jmxproxy/jmx/tests/TimeoutRMISocketFactoryTest.java import com.github.mk23.jmxproxy.jmx.TimeoutRMISocketFactory; import java.net.BindException; import java.net.ConnectException; import java.net.SocketTimeoutException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TestName; import static org.junit.Assert.assertNotNull; package com.github.mk23.jmxproxy.jmx.tests; public class TimeoutRMISocketFactoryTest { private final String validHost = "localhost"; private final String invalidHost = "192.0.2.1"; private final int serverPort = Integer.getInteger("com.sun.management.jmxremote.port"); private final int connectTimeout = 500; @Rule public ExpectedException thrown = ExpectedException.none(); @Rule public TestName name = new TestName(); @Before public void printTestName() { System.out.println(" -> " + name.getMethodName()); } @Test public void checkClientValidHostValidPort() throws Exception {
final TimeoutRMISocketFactory sf = new TimeoutRMISocketFactory(connectTimeout);
mk23/jmxproxy
src/main/java/com/github/mk23/jmxproxy/core/MBean.java
// Path: src/main/java/com/github/mk23/jmxproxy/util/History.java // public class History<T> { // private List<T> objects; // private int length; // private int pointer; // private boolean wrapped; // // /** // * <p>Default constructor.</p> // * // * Initializes the {@link Object} store {@link List} to the given history size. // * // * @param length number of {@link Object} values to keep in history. // */ // public History(final int length) { // this.length = length; // // pointer = -1; // objects = new ArrayList<T>(Collections.nCopies(length, (T) null)); // } // // /** // * <p>Adds a item to the store.</p> // * // * Adds a new item to the history store. If the number of items exceeds the size // * of the store, the oldest item is overwritten. // * // * @param item newest item to add to the store. // */ // public final void add(final T item) { // wrapped = ++pointer == length; // pointer = pointer % length; // // objects.set(pointer, item); // } // // /** // * <p>Gets the latest item from the history store.</p> // * // * Gets the latest single item from the history store. // * // * @return Latest item from the history store or null if empty. // */ // public final T getLast() { // return pointer < 0 ? null : objects.get(pointer % length); // } // // /** // * <p>Gets the full item history from the store.</p> // * // * Gets the full item history from the store as a {@link List}. // * // * @return {@link List} of the full history. May be empty if history has no items. // */ // public final List<T> get() { // return get(length); // } // // /** // * <p>Gets a limited item history from the store.</p> // * // * Gets a limited history from the store as a {@link List}, based // * on requested item count. If the specified count is less than 0 or greater than // * the number of entries, a full history is returned instead. // * // * @param limit number of items to retreive from the history store. // * // * @return {@link List} of the requested slice of history. May be empty if history has no items. // */ // public final List<T> get(final int limit) { // if (pointer < 0) { // return Collections.emptyList(); // } // // int head = pointer + length * Boolean.compare(wrapped, false); // int size = Math.min(limit > 0 ? limit : Integer.MAX_VALUE, Math.min(head + 1, length)); // List<T> rval = new ArrayList<T>(size); // // for (int i = 0; i < size; i++) { // rval.add(objects.get((head - i) % length)); // } // // return rval; // } // }
import com.github.mk23.jmxproxy.util.History; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonSerializable; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set;
package com.github.mk23.jmxproxy.core; /** * <p>JMX MBean tracker and serializer.</p> * * Maintains a map of JMX {@link Attribute} names and a {@link History} of * their values. Implements JsonSerializable interface to convert the * stored map into JSON. * * @see <a href="https://fasterxml.github.io/jackson-databind/javadoc/2.6/com/fasterxml/jackson/databind/JsonSerializable.html">com.fasterxml.jackson.databind.JsonSerializable</a> * * @since 2018-02-08 * @author mk23 * @version 3.4.0 */ public class MBean implements JsonSerializable { private final int historySize;
// Path: src/main/java/com/github/mk23/jmxproxy/util/History.java // public class History<T> { // private List<T> objects; // private int length; // private int pointer; // private boolean wrapped; // // /** // * <p>Default constructor.</p> // * // * Initializes the {@link Object} store {@link List} to the given history size. // * // * @param length number of {@link Object} values to keep in history. // */ // public History(final int length) { // this.length = length; // // pointer = -1; // objects = new ArrayList<T>(Collections.nCopies(length, (T) null)); // } // // /** // * <p>Adds a item to the store.</p> // * // * Adds a new item to the history store. If the number of items exceeds the size // * of the store, the oldest item is overwritten. // * // * @param item newest item to add to the store. // */ // public final void add(final T item) { // wrapped = ++pointer == length; // pointer = pointer % length; // // objects.set(pointer, item); // } // // /** // * <p>Gets the latest item from the history store.</p> // * // * Gets the latest single item from the history store. // * // * @return Latest item from the history store or null if empty. // */ // public final T getLast() { // return pointer < 0 ? null : objects.get(pointer % length); // } // // /** // * <p>Gets the full item history from the store.</p> // * // * Gets the full item history from the store as a {@link List}. // * // * @return {@link List} of the full history. May be empty if history has no items. // */ // public final List<T> get() { // return get(length); // } // // /** // * <p>Gets a limited item history from the store.</p> // * // * Gets a limited history from the store as a {@link List}, based // * on requested item count. If the specified count is less than 0 or greater than // * the number of entries, a full history is returned instead. // * // * @param limit number of items to retreive from the history store. // * // * @return {@link List} of the requested slice of history. May be empty if history has no items. // */ // public final List<T> get(final int limit) { // if (pointer < 0) { // return Collections.emptyList(); // } // // int head = pointer + length * Boolean.compare(wrapped, false); // int size = Math.min(limit > 0 ? limit : Integer.MAX_VALUE, Math.min(head + 1, length)); // List<T> rval = new ArrayList<T>(size); // // for (int i = 0; i < size; i++) { // rval.add(objects.get((head - i) % length)); // } // // return rval; // } // } // Path: src/main/java/com/github/mk23/jmxproxy/core/MBean.java import com.github.mk23.jmxproxy.util.History; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonSerializable; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; package com.github.mk23.jmxproxy.core; /** * <p>JMX MBean tracker and serializer.</p> * * Maintains a map of JMX {@link Attribute} names and a {@link History} of * their values. Implements JsonSerializable interface to convert the * stored map into JSON. * * @see <a href="https://fasterxml.github.io/jackson-databind/javadoc/2.6/com/fasterxml/jackson/databind/JsonSerializable.html">com.fasterxml.jackson.databind.JsonSerializable</a> * * @since 2018-02-08 * @author mk23 * @version 3.4.0 */ public class MBean implements JsonSerializable { private final int historySize;
private final Map<String, History<Attribute>> attributes;
yushiwo/Universal-Image-Selector
android-imageselector-lib/src/main/java/com/netease/imageSelector/adapter/DeletePreviewPagerAdapter.java
// Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/model/LocalMedia.java // public class LocalMedia implements Serializable { // private String path; // private long duration; // private long lastUpdateAt; // // // public LocalMedia(String path, long lastUpdateAt, long duration) { // this.path = path; // this.duration = duration; // this.lastUpdateAt = lastUpdateAt; // } // // public LocalMedia(String path) { // this.path = path; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // // public long getLastUpdateAt() { // return lastUpdateAt; // } // // public void setLastUpdateAt(long lastUpdateAt) { // this.lastUpdateAt = lastUpdateAt; // } // // public long getDuration() { // return duration; // } // public void setDuration(long duration) { // this.duration = duration; // } // } // // Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/view/ImagePreviewFragment.java // public class ImagePreviewFragment extends Fragment { // public static final String PATH = "path"; // // public static ImagePreviewFragment getInstance(String path) { // ImagePreviewFragment fragment = new ImagePreviewFragment(); // Bundle bundle = new Bundle(); // bundle.putString(PATH, path); // fragment.setArguments(bundle); // return fragment; // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View contentView = inflater.inflate(R.layout.fragment_image_preview, container, false); // final ImageView imageView = (ImageView) contentView.findViewById(R.id.preview_image); // final PhotoViewAttacher mAttacher = new PhotoViewAttacher(imageView); // Glide.with(container.getContext()) // // .load(new File(getArguments().getString(PATH))) // .load(getArguments().getString(PATH)) // .asBitmap() // .into(new SimpleTarget<Bitmap>(480, 800) { // @Override // public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { // imageView.setImageBitmap(resource); // mAttacher.update(); // } // }); // mAttacher.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() { // @Override // public void onViewTap(View view, float x, float y) { // ImagePreviewActivity activity = (ImagePreviewActivity) getActivity(); // activity.switchBarVisibility(); // } // }); // return contentView; // } // }
import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.util.Log; import com.netease.imageSelector.model.LocalMedia; import com.netease.imageSelector.view.ImagePreviewFragment; import java.util.ArrayList;
package com.netease.imageSelector.adapter; /** * @author hzzhengrui * @Date 16/10/17 * @Description */ public class DeletePreviewPagerAdapter extends FragmentStatePagerAdapter { private ArrayList<Fragment> mFragmentList;
// Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/model/LocalMedia.java // public class LocalMedia implements Serializable { // private String path; // private long duration; // private long lastUpdateAt; // // // public LocalMedia(String path, long lastUpdateAt, long duration) { // this.path = path; // this.duration = duration; // this.lastUpdateAt = lastUpdateAt; // } // // public LocalMedia(String path) { // this.path = path; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // // public long getLastUpdateAt() { // return lastUpdateAt; // } // // public void setLastUpdateAt(long lastUpdateAt) { // this.lastUpdateAt = lastUpdateAt; // } // // public long getDuration() { // return duration; // } // public void setDuration(long duration) { // this.duration = duration; // } // } // // Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/view/ImagePreviewFragment.java // public class ImagePreviewFragment extends Fragment { // public static final String PATH = "path"; // // public static ImagePreviewFragment getInstance(String path) { // ImagePreviewFragment fragment = new ImagePreviewFragment(); // Bundle bundle = new Bundle(); // bundle.putString(PATH, path); // fragment.setArguments(bundle); // return fragment; // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View contentView = inflater.inflate(R.layout.fragment_image_preview, container, false); // final ImageView imageView = (ImageView) contentView.findViewById(R.id.preview_image); // final PhotoViewAttacher mAttacher = new PhotoViewAttacher(imageView); // Glide.with(container.getContext()) // // .load(new File(getArguments().getString(PATH))) // .load(getArguments().getString(PATH)) // .asBitmap() // .into(new SimpleTarget<Bitmap>(480, 800) { // @Override // public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { // imageView.setImageBitmap(resource); // mAttacher.update(); // } // }); // mAttacher.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() { // @Override // public void onViewTap(View view, float x, float y) { // ImagePreviewActivity activity = (ImagePreviewActivity) getActivity(); // activity.switchBarVisibility(); // } // }); // return contentView; // } // } // Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/adapter/DeletePreviewPagerAdapter.java import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.util.Log; import com.netease.imageSelector.model.LocalMedia; import com.netease.imageSelector.view.ImagePreviewFragment; import java.util.ArrayList; package com.netease.imageSelector.adapter; /** * @author hzzhengrui * @Date 16/10/17 * @Description */ public class DeletePreviewPagerAdapter extends FragmentStatePagerAdapter { private ArrayList<Fragment> mFragmentList;
public DeletePreviewPagerAdapter(FragmentManager fm, ArrayList<LocalMedia> mDatas) {
yushiwo/Universal-Image-Selector
android-imageselector-lib/src/main/java/com/netease/imageSelector/adapter/DeletePreviewPagerAdapter.java
// Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/model/LocalMedia.java // public class LocalMedia implements Serializable { // private String path; // private long duration; // private long lastUpdateAt; // // // public LocalMedia(String path, long lastUpdateAt, long duration) { // this.path = path; // this.duration = duration; // this.lastUpdateAt = lastUpdateAt; // } // // public LocalMedia(String path) { // this.path = path; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // // public long getLastUpdateAt() { // return lastUpdateAt; // } // // public void setLastUpdateAt(long lastUpdateAt) { // this.lastUpdateAt = lastUpdateAt; // } // // public long getDuration() { // return duration; // } // public void setDuration(long duration) { // this.duration = duration; // } // } // // Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/view/ImagePreviewFragment.java // public class ImagePreviewFragment extends Fragment { // public static final String PATH = "path"; // // public static ImagePreviewFragment getInstance(String path) { // ImagePreviewFragment fragment = new ImagePreviewFragment(); // Bundle bundle = new Bundle(); // bundle.putString(PATH, path); // fragment.setArguments(bundle); // return fragment; // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View contentView = inflater.inflate(R.layout.fragment_image_preview, container, false); // final ImageView imageView = (ImageView) contentView.findViewById(R.id.preview_image); // final PhotoViewAttacher mAttacher = new PhotoViewAttacher(imageView); // Glide.with(container.getContext()) // // .load(new File(getArguments().getString(PATH))) // .load(getArguments().getString(PATH)) // .asBitmap() // .into(new SimpleTarget<Bitmap>(480, 800) { // @Override // public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { // imageView.setImageBitmap(resource); // mAttacher.update(); // } // }); // mAttacher.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() { // @Override // public void onViewTap(View view, float x, float y) { // ImagePreviewActivity activity = (ImagePreviewActivity) getActivity(); // activity.switchBarVisibility(); // } // }); // return contentView; // } // }
import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.util.Log; import com.netease.imageSelector.model.LocalMedia; import com.netease.imageSelector.view.ImagePreviewFragment; import java.util.ArrayList;
package com.netease.imageSelector.adapter; /** * @author hzzhengrui * @Date 16/10/17 * @Description */ public class DeletePreviewPagerAdapter extends FragmentStatePagerAdapter { private ArrayList<Fragment> mFragmentList; public DeletePreviewPagerAdapter(FragmentManager fm, ArrayList<LocalMedia> mDatas) { super(fm); updateData(mDatas); } public void updateData(ArrayList<LocalMedia> dataList) { ArrayList<Fragment> fragments = new ArrayList<>(); for (int i = 0, size = dataList.size(); i < size; i++) { Log.e("FPagerAdapter1", dataList.get(i).toString());
// Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/model/LocalMedia.java // public class LocalMedia implements Serializable { // private String path; // private long duration; // private long lastUpdateAt; // // // public LocalMedia(String path, long lastUpdateAt, long duration) { // this.path = path; // this.duration = duration; // this.lastUpdateAt = lastUpdateAt; // } // // public LocalMedia(String path) { // this.path = path; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // // public long getLastUpdateAt() { // return lastUpdateAt; // } // // public void setLastUpdateAt(long lastUpdateAt) { // this.lastUpdateAt = lastUpdateAt; // } // // public long getDuration() { // return duration; // } // public void setDuration(long duration) { // this.duration = duration; // } // } // // Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/view/ImagePreviewFragment.java // public class ImagePreviewFragment extends Fragment { // public static final String PATH = "path"; // // public static ImagePreviewFragment getInstance(String path) { // ImagePreviewFragment fragment = new ImagePreviewFragment(); // Bundle bundle = new Bundle(); // bundle.putString(PATH, path); // fragment.setArguments(bundle); // return fragment; // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View contentView = inflater.inflate(R.layout.fragment_image_preview, container, false); // final ImageView imageView = (ImageView) contentView.findViewById(R.id.preview_image); // final PhotoViewAttacher mAttacher = new PhotoViewAttacher(imageView); // Glide.with(container.getContext()) // // .load(new File(getArguments().getString(PATH))) // .load(getArguments().getString(PATH)) // .asBitmap() // .into(new SimpleTarget<Bitmap>(480, 800) { // @Override // public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { // imageView.setImageBitmap(resource); // mAttacher.update(); // } // }); // mAttacher.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() { // @Override // public void onViewTap(View view, float x, float y) { // ImagePreviewActivity activity = (ImagePreviewActivity) getActivity(); // activity.switchBarVisibility(); // } // }); // return contentView; // } // } // Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/adapter/DeletePreviewPagerAdapter.java import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.util.Log; import com.netease.imageSelector.model.LocalMedia; import com.netease.imageSelector.view.ImagePreviewFragment; import java.util.ArrayList; package com.netease.imageSelector.adapter; /** * @author hzzhengrui * @Date 16/10/17 * @Description */ public class DeletePreviewPagerAdapter extends FragmentStatePagerAdapter { private ArrayList<Fragment> mFragmentList; public DeletePreviewPagerAdapter(FragmentManager fm, ArrayList<LocalMedia> mDatas) { super(fm); updateData(mDatas); } public void updateData(ArrayList<LocalMedia> dataList) { ArrayList<Fragment> fragments = new ArrayList<>(); for (int i = 0, size = dataList.size(); i < size; i++) { Log.e("FPagerAdapter1", dataList.get(i).toString());
fragments.add(ImagePreviewFragment.getInstance(dataList.get(i).getPath()));
yushiwo/Universal-Image-Selector
android-imageselector-lib/src/main/java/com/netease/imageSelector/utils/FileUtils.java
// Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/ImageSelectorProxy.java // public class ImageSelectorProxy implements IProxy{ // // private static final String ERROR_NOT_INIT = "ImageSelector must be init with configuration before using"; // // private static ImageSelectorProxy sInstance; // // ImageSelectorConfiguration configuration; // // public static ImageSelectorProxy getInstance(){ // if (sInstance == null) { // synchronized (ImageSelector.class) { // if (sInstance == null) { // sInstance = new ImageSelectorProxy(); // } // } // } // return sInstance; // } // // /** // * 设置图片选择器的配置 // * @param configuration // */ // public void setConfiguration(ImageSelectorConfiguration configuration){ // this.configuration = configuration; // } // // private void checkConfiguration() { // if (configuration == null) { // throw new IllegalStateException(ERROR_NOT_INIT); // } // } // // @Override // public int getMaxSelectNum() { // checkConfiguration(); // return configuration.maxSelectNum; // } // // @Override // public int getSpanCount() { // checkConfiguration(); // return configuration.spanCount; // } // // @Override // public int getSelectMode() { // checkConfiguration(); // return configuration.selectMode; // } // // @Override // public boolean isEnablePreview() { // checkConfiguration(); // return configuration.isEnablePreview; // } // // @Override // public boolean isShowCamera() { // checkConfiguration(); // return configuration.isShowCamera; // } // // @Override // public boolean isEnableCorp() { // checkConfiguration(); // return configuration.isEnableCrop; // } // // @Override // public Drawable getImageOnLoading(Resources res) { // checkConfiguration(); // return configuration.imageResOnLoading != 0 ? res.getDrawable(configuration.imageResOnLoading) : configuration.imageOnLoading; // } // // @Override // public Drawable getImageOnError(Resources res) { // checkConfiguration(); // return configuration.imageResOnError != 0 ? res.getDrawable(configuration.imageResOnError) : configuration.imageOnError; // } // // @Override // public int getTitleBarColor(Resources res) { // checkConfiguration(); // return res.getColor(configuration.titleBarColor); // } // // @Override // public int getStatusBarColor(Resources res) { // checkConfiguration(); // return res.getColor(configuration.statusBarColor); // } // // @Override // public float getTitleHeight() { // checkConfiguration(); // return configuration.titleHeight; // } // // @Override // public String getImageSaveDirectory(Resources res) { // checkConfiguration(); // return configuration.imageSaveDirectoryRes != -1 ? res.getString(configuration.imageSaveDirectoryRes) : configuration.imageSaveDirectory; // } // // @Override // public Drawable getImageBack(Resources res) { // checkConfiguration(); // return configuration.imageResBack != -1 ? res.getDrawable(configuration.imageResBack) : configuration.imageBack; // } // }
import android.content.Context; import android.os.Environment; import com.netease.imageSelector.ImageSelectorProxy; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale;
package com.netease.imageSelector.utils; /** * Created by dee on 15/11/20. */ public class FileUtils { public static final String POSTFIX = ".JPEG"; public static String APP_NAME = "ImageSelector"; public static String CAMERA_PATH = "/" + APP_NAME + "/CameraImage/"; public static String CROP_PATH = "/" + APP_NAME + "/CropImage/"; public static File createCameraFile(Context context) {
// Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/ImageSelectorProxy.java // public class ImageSelectorProxy implements IProxy{ // // private static final String ERROR_NOT_INIT = "ImageSelector must be init with configuration before using"; // // private static ImageSelectorProxy sInstance; // // ImageSelectorConfiguration configuration; // // public static ImageSelectorProxy getInstance(){ // if (sInstance == null) { // synchronized (ImageSelector.class) { // if (sInstance == null) { // sInstance = new ImageSelectorProxy(); // } // } // } // return sInstance; // } // // /** // * 设置图片选择器的配置 // * @param configuration // */ // public void setConfiguration(ImageSelectorConfiguration configuration){ // this.configuration = configuration; // } // // private void checkConfiguration() { // if (configuration == null) { // throw new IllegalStateException(ERROR_NOT_INIT); // } // } // // @Override // public int getMaxSelectNum() { // checkConfiguration(); // return configuration.maxSelectNum; // } // // @Override // public int getSpanCount() { // checkConfiguration(); // return configuration.spanCount; // } // // @Override // public int getSelectMode() { // checkConfiguration(); // return configuration.selectMode; // } // // @Override // public boolean isEnablePreview() { // checkConfiguration(); // return configuration.isEnablePreview; // } // // @Override // public boolean isShowCamera() { // checkConfiguration(); // return configuration.isShowCamera; // } // // @Override // public boolean isEnableCorp() { // checkConfiguration(); // return configuration.isEnableCrop; // } // // @Override // public Drawable getImageOnLoading(Resources res) { // checkConfiguration(); // return configuration.imageResOnLoading != 0 ? res.getDrawable(configuration.imageResOnLoading) : configuration.imageOnLoading; // } // // @Override // public Drawable getImageOnError(Resources res) { // checkConfiguration(); // return configuration.imageResOnError != 0 ? res.getDrawable(configuration.imageResOnError) : configuration.imageOnError; // } // // @Override // public int getTitleBarColor(Resources res) { // checkConfiguration(); // return res.getColor(configuration.titleBarColor); // } // // @Override // public int getStatusBarColor(Resources res) { // checkConfiguration(); // return res.getColor(configuration.statusBarColor); // } // // @Override // public float getTitleHeight() { // checkConfiguration(); // return configuration.titleHeight; // } // // @Override // public String getImageSaveDirectory(Resources res) { // checkConfiguration(); // return configuration.imageSaveDirectoryRes != -1 ? res.getString(configuration.imageSaveDirectoryRes) : configuration.imageSaveDirectory; // } // // @Override // public Drawable getImageBack(Resources res) { // checkConfiguration(); // return configuration.imageResBack != -1 ? res.getDrawable(configuration.imageResBack) : configuration.imageBack; // } // } // Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/utils/FileUtils.java import android.content.Context; import android.os.Environment; import com.netease.imageSelector.ImageSelectorProxy; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; package com.netease.imageSelector.utils; /** * Created by dee on 15/11/20. */ public class FileUtils { public static final String POSTFIX = ".JPEG"; public static String APP_NAME = "ImageSelector"; public static String CAMERA_PATH = "/" + APP_NAME + "/CameraImage/"; public static String CROP_PATH = "/" + APP_NAME + "/CropImage/"; public static File createCameraFile(Context context) {
APP_NAME = ImageSelectorProxy.getInstance().getImageSaveDirectory(context.getResources());
yushiwo/Universal-Image-Selector
android-imageselector-lib/src/main/java/com/netease/imageSelector/utils/LocalMediaLoader.java
// Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/model/LocalMedia.java // public class LocalMedia implements Serializable { // private String path; // private long duration; // private long lastUpdateAt; // // // public LocalMedia(String path, long lastUpdateAt, long duration) { // this.path = path; // this.duration = duration; // this.lastUpdateAt = lastUpdateAt; // } // // public LocalMedia(String path) { // this.path = path; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // // public long getLastUpdateAt() { // return lastUpdateAt; // } // // public void setLastUpdateAt(long lastUpdateAt) { // this.lastUpdateAt = lastUpdateAt; // } // // public long getDuration() { // return duration; // } // public void setDuration(long duration) { // this.duration = duration; // } // } // // Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/model/LocalMediaFolder.java // public class LocalMediaFolder implements Serializable { // private String name; // private String path; // private String firstImagePath; // private int imageNum; // private List<LocalMedia> images = new ArrayList<LocalMedia>(); // // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // // public String getFirstImagePath() { // return firstImagePath; // } // // public void setFirstImagePath(String firstImagePath) { // this.firstImagePath = firstImagePath; // } // // public int getImageNum() { // return imageNum; // } // // public void setImageNum(int imageNum) { // this.imageNum = imageNum; // } // // public List<LocalMedia> getImages() { // return images; // } // // public void setImages(List<LocalMedia> images) { // this.images = images; // } // }
import android.database.Cursor; import android.os.Bundle; import android.provider.MediaStore; import android.support.v4.app.FragmentActivity; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import com.netease.imageSelector.R; import com.netease.imageSelector.model.LocalMedia; import com.netease.imageSelector.model.LocalMediaFolder; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List;
public LocalMediaLoader(FragmentActivity activity, int type) { this.activity = activity; this.type = type; } HashSet<String> mDirPaths = new HashSet<String>(); public void loadAllImage(final LocalMediaLoadListener imageLoadListener) { activity.getSupportLoaderManager().initLoader(type, null, new LoaderManager.LoaderCallbacks<Cursor>() { @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { CursorLoader cursorLoader = null; if (id == TYPE_IMAGE) { cursorLoader = new CursorLoader( activity, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION, MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?", new String[]{"image/jpeg", "image/png"}, IMAGE_PROJECTION[2] + " DESC"); } else if (id == TYPE_VIDEO) { cursorLoader = new CursorLoader( activity, MediaStore.Video.Media.EXTERNAL_CONTENT_URI, VIDEO_PROJECTION, null, null, VIDEO_PROJECTION[2] + " DESC"); } return cursorLoader; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // 目录列表
// Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/model/LocalMedia.java // public class LocalMedia implements Serializable { // private String path; // private long duration; // private long lastUpdateAt; // // // public LocalMedia(String path, long lastUpdateAt, long duration) { // this.path = path; // this.duration = duration; // this.lastUpdateAt = lastUpdateAt; // } // // public LocalMedia(String path) { // this.path = path; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // // public long getLastUpdateAt() { // return lastUpdateAt; // } // // public void setLastUpdateAt(long lastUpdateAt) { // this.lastUpdateAt = lastUpdateAt; // } // // public long getDuration() { // return duration; // } // public void setDuration(long duration) { // this.duration = duration; // } // } // // Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/model/LocalMediaFolder.java // public class LocalMediaFolder implements Serializable { // private String name; // private String path; // private String firstImagePath; // private int imageNum; // private List<LocalMedia> images = new ArrayList<LocalMedia>(); // // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // // public String getFirstImagePath() { // return firstImagePath; // } // // public void setFirstImagePath(String firstImagePath) { // this.firstImagePath = firstImagePath; // } // // public int getImageNum() { // return imageNum; // } // // public void setImageNum(int imageNum) { // this.imageNum = imageNum; // } // // public List<LocalMedia> getImages() { // return images; // } // // public void setImages(List<LocalMedia> images) { // this.images = images; // } // } // Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/utils/LocalMediaLoader.java import android.database.Cursor; import android.os.Bundle; import android.provider.MediaStore; import android.support.v4.app.FragmentActivity; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import com.netease.imageSelector.R; import com.netease.imageSelector.model.LocalMedia; import com.netease.imageSelector.model.LocalMediaFolder; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; public LocalMediaLoader(FragmentActivity activity, int type) { this.activity = activity; this.type = type; } HashSet<String> mDirPaths = new HashSet<String>(); public void loadAllImage(final LocalMediaLoadListener imageLoadListener) { activity.getSupportLoaderManager().initLoader(type, null, new LoaderManager.LoaderCallbacks<Cursor>() { @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { CursorLoader cursorLoader = null; if (id == TYPE_IMAGE) { cursorLoader = new CursorLoader( activity, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION, MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?", new String[]{"image/jpeg", "image/png"}, IMAGE_PROJECTION[2] + " DESC"); } else if (id == TYPE_VIDEO) { cursorLoader = new CursorLoader( activity, MediaStore.Video.Media.EXTERNAL_CONTENT_URI, VIDEO_PROJECTION, null, null, VIDEO_PROJECTION[2] + " DESC"); } return cursorLoader; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // 目录列表
ArrayList<LocalMediaFolder> imageFolders = new ArrayList<LocalMediaFolder>();
yushiwo/Universal-Image-Selector
android-imageselector-lib/src/main/java/com/netease/imageSelector/utils/LocalMediaLoader.java
// Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/model/LocalMedia.java // public class LocalMedia implements Serializable { // private String path; // private long duration; // private long lastUpdateAt; // // // public LocalMedia(String path, long lastUpdateAt, long duration) { // this.path = path; // this.duration = duration; // this.lastUpdateAt = lastUpdateAt; // } // // public LocalMedia(String path) { // this.path = path; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // // public long getLastUpdateAt() { // return lastUpdateAt; // } // // public void setLastUpdateAt(long lastUpdateAt) { // this.lastUpdateAt = lastUpdateAt; // } // // public long getDuration() { // return duration; // } // public void setDuration(long duration) { // this.duration = duration; // } // } // // Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/model/LocalMediaFolder.java // public class LocalMediaFolder implements Serializable { // private String name; // private String path; // private String firstImagePath; // private int imageNum; // private List<LocalMedia> images = new ArrayList<LocalMedia>(); // // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // // public String getFirstImagePath() { // return firstImagePath; // } // // public void setFirstImagePath(String firstImagePath) { // this.firstImagePath = firstImagePath; // } // // public int getImageNum() { // return imageNum; // } // // public void setImageNum(int imageNum) { // this.imageNum = imageNum; // } // // public List<LocalMedia> getImages() { // return images; // } // // public void setImages(List<LocalMedia> images) { // this.images = images; // } // }
import android.database.Cursor; import android.os.Bundle; import android.provider.MediaStore; import android.support.v4.app.FragmentActivity; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import com.netease.imageSelector.R; import com.netease.imageSelector.model.LocalMedia; import com.netease.imageSelector.model.LocalMediaFolder; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List;
} HashSet<String> mDirPaths = new HashSet<String>(); public void loadAllImage(final LocalMediaLoadListener imageLoadListener) { activity.getSupportLoaderManager().initLoader(type, null, new LoaderManager.LoaderCallbacks<Cursor>() { @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { CursorLoader cursorLoader = null; if (id == TYPE_IMAGE) { cursorLoader = new CursorLoader( activity, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION, MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?", new String[]{"image/jpeg", "image/png"}, IMAGE_PROJECTION[2] + " DESC"); } else if (id == TYPE_VIDEO) { cursorLoader = new CursorLoader( activity, MediaStore.Video.Media.EXTERNAL_CONTENT_URI, VIDEO_PROJECTION, null, null, VIDEO_PROJECTION[2] + " DESC"); } return cursorLoader; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // 目录列表 ArrayList<LocalMediaFolder> imageFolders = new ArrayList<LocalMediaFolder>(); // 所有图片目录 LocalMediaFolder allImageFolder = new LocalMediaFolder(); // 所有图片列表
// Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/model/LocalMedia.java // public class LocalMedia implements Serializable { // private String path; // private long duration; // private long lastUpdateAt; // // // public LocalMedia(String path, long lastUpdateAt, long duration) { // this.path = path; // this.duration = duration; // this.lastUpdateAt = lastUpdateAt; // } // // public LocalMedia(String path) { // this.path = path; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // // public long getLastUpdateAt() { // return lastUpdateAt; // } // // public void setLastUpdateAt(long lastUpdateAt) { // this.lastUpdateAt = lastUpdateAt; // } // // public long getDuration() { // return duration; // } // public void setDuration(long duration) { // this.duration = duration; // } // } // // Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/model/LocalMediaFolder.java // public class LocalMediaFolder implements Serializable { // private String name; // private String path; // private String firstImagePath; // private int imageNum; // private List<LocalMedia> images = new ArrayList<LocalMedia>(); // // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // // public String getFirstImagePath() { // return firstImagePath; // } // // public void setFirstImagePath(String firstImagePath) { // this.firstImagePath = firstImagePath; // } // // public int getImageNum() { // return imageNum; // } // // public void setImageNum(int imageNum) { // this.imageNum = imageNum; // } // // public List<LocalMedia> getImages() { // return images; // } // // public void setImages(List<LocalMedia> images) { // this.images = images; // } // } // Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/utils/LocalMediaLoader.java import android.database.Cursor; import android.os.Bundle; import android.provider.MediaStore; import android.support.v4.app.FragmentActivity; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import com.netease.imageSelector.R; import com.netease.imageSelector.model.LocalMedia; import com.netease.imageSelector.model.LocalMediaFolder; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; } HashSet<String> mDirPaths = new HashSet<String>(); public void loadAllImage(final LocalMediaLoadListener imageLoadListener) { activity.getSupportLoaderManager().initLoader(type, null, new LoaderManager.LoaderCallbacks<Cursor>() { @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { CursorLoader cursorLoader = null; if (id == TYPE_IMAGE) { cursorLoader = new CursorLoader( activity, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION, MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?", new String[]{"image/jpeg", "image/png"}, IMAGE_PROJECTION[2] + " DESC"); } else if (id == TYPE_VIDEO) { cursorLoader = new CursorLoader( activity, MediaStore.Video.Media.EXTERNAL_CONTENT_URI, VIDEO_PROJECTION, null, null, VIDEO_PROJECTION[2] + " DESC"); } return cursorLoader; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // 目录列表 ArrayList<LocalMediaFolder> imageFolders = new ArrayList<LocalMediaFolder>(); // 所有图片目录 LocalMediaFolder allImageFolder = new LocalMediaFolder(); // 所有图片列表
List<LocalMedia> allImages = new ArrayList<LocalMedia>();
yushiwo/Universal-Image-Selector
android-imageselector-lib/src/main/java/com/netease/imageSelector/adapter/SimplePreviewPagerAdapter.java
// Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/model/LocalMedia.java // public class LocalMedia implements Serializable { // private String path; // private long duration; // private long lastUpdateAt; // // // public LocalMedia(String path, long lastUpdateAt, long duration) { // this.path = path; // this.duration = duration; // this.lastUpdateAt = lastUpdateAt; // } // // public LocalMedia(String path) { // this.path = path; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // // public long getLastUpdateAt() { // return lastUpdateAt; // } // // public void setLastUpdateAt(long lastUpdateAt) { // this.lastUpdateAt = lastUpdateAt; // } // // public long getDuration() { // return duration; // } // public void setDuration(long duration) { // this.duration = duration; // } // } // // Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/view/ImagePreviewFragment.java // public class ImagePreviewFragment extends Fragment { // public static final String PATH = "path"; // // public static ImagePreviewFragment getInstance(String path) { // ImagePreviewFragment fragment = new ImagePreviewFragment(); // Bundle bundle = new Bundle(); // bundle.putString(PATH, path); // fragment.setArguments(bundle); // return fragment; // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View contentView = inflater.inflate(R.layout.fragment_image_preview, container, false); // final ImageView imageView = (ImageView) contentView.findViewById(R.id.preview_image); // final PhotoViewAttacher mAttacher = new PhotoViewAttacher(imageView); // Glide.with(container.getContext()) // // .load(new File(getArguments().getString(PATH))) // .load(getArguments().getString(PATH)) // .asBitmap() // .into(new SimpleTarget<Bitmap>(480, 800) { // @Override // public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { // imageView.setImageBitmap(resource); // mAttacher.update(); // } // }); // mAttacher.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() { // @Override // public void onViewTap(View view, float x, float y) { // ImagePreviewActivity activity = (ImagePreviewActivity) getActivity(); // activity.switchBarVisibility(); // } // }); // return contentView; // } // }
import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import com.netease.imageSelector.model.LocalMedia; import com.netease.imageSelector.view.ImagePreviewFragment; import java.util.ArrayList;
package com.netease.imageSelector.adapter; /** * @author hzzhengrui * @Date 16/10/17 * @Description */ public class SimplePreviewPagerAdapter extends FragmentStatePagerAdapter { ArrayList<LocalMedia> mDatas; public SimplePreviewPagerAdapter(FragmentManager fm, ArrayList<LocalMedia> mDatas) { super(fm); this.mDatas = mDatas; } @Override public Fragment getItem(int position) {
// Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/model/LocalMedia.java // public class LocalMedia implements Serializable { // private String path; // private long duration; // private long lastUpdateAt; // // // public LocalMedia(String path, long lastUpdateAt, long duration) { // this.path = path; // this.duration = duration; // this.lastUpdateAt = lastUpdateAt; // } // // public LocalMedia(String path) { // this.path = path; // } // // public String getPath() { // return path; // } // // public void setPath(String path) { // this.path = path; // } // // public long getLastUpdateAt() { // return lastUpdateAt; // } // // public void setLastUpdateAt(long lastUpdateAt) { // this.lastUpdateAt = lastUpdateAt; // } // // public long getDuration() { // return duration; // } // public void setDuration(long duration) { // this.duration = duration; // } // } // // Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/view/ImagePreviewFragment.java // public class ImagePreviewFragment extends Fragment { // public static final String PATH = "path"; // // public static ImagePreviewFragment getInstance(String path) { // ImagePreviewFragment fragment = new ImagePreviewFragment(); // Bundle bundle = new Bundle(); // bundle.putString(PATH, path); // fragment.setArguments(bundle); // return fragment; // } // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View contentView = inflater.inflate(R.layout.fragment_image_preview, container, false); // final ImageView imageView = (ImageView) contentView.findViewById(R.id.preview_image); // final PhotoViewAttacher mAttacher = new PhotoViewAttacher(imageView); // Glide.with(container.getContext()) // // .load(new File(getArguments().getString(PATH))) // .load(getArguments().getString(PATH)) // .asBitmap() // .into(new SimpleTarget<Bitmap>(480, 800) { // @Override // public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { // imageView.setImageBitmap(resource); // mAttacher.update(); // } // }); // mAttacher.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() { // @Override // public void onViewTap(View view, float x, float y) { // ImagePreviewActivity activity = (ImagePreviewActivity) getActivity(); // activity.switchBarVisibility(); // } // }); // return contentView; // } // } // Path: android-imageselector-lib/src/main/java/com/netease/imageSelector/adapter/SimplePreviewPagerAdapter.java import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import com.netease.imageSelector.model.LocalMedia; import com.netease.imageSelector.view.ImagePreviewFragment; import java.util.ArrayList; package com.netease.imageSelector.adapter; /** * @author hzzhengrui * @Date 16/10/17 * @Description */ public class SimplePreviewPagerAdapter extends FragmentStatePagerAdapter { ArrayList<LocalMedia> mDatas; public SimplePreviewPagerAdapter(FragmentManager fm, ArrayList<LocalMedia> mDatas) { super(fm); this.mDatas = mDatas; } @Override public Fragment getItem(int position) {
return ImagePreviewFragment.getInstance(mDatas.get(position).getPath());
DevOpsStudio/Re-Collector
src/test/java/org/graylog/collector/inputs/eventlog/WindowsEventlogHandlerTest.java
// Path: src/main/java/org/graylog/collector/MessageBuilder.java // public class MessageBuilder { // private final long ownerId = Thread.currentThread().getId(); // // private String message; // private String source; // private DateTime timestamp; // private Message.Level level; // private String input; // private Set<String> outputs; // private MessageFields fields = new MessageFields(); // // public MessageBuilder() { // } // // private MessageBuilder(String message, String source, DateTime timestamp, Message.Level level, String input, Set<String> outputs, MessageFields fields) { // this.message = message; // this.source = source; // this.timestamp = timestamp; // this.level = level; // this.input = input; // this.outputs = outputs; // this.fields = fields; // } // // public MessageBuilder message(String message) { // checkOwnership(); // this.message = message; // return this; // } // // public MessageBuilder source(String source) { // checkOwnership(); // this.source = source; // return this; // } // // public MessageBuilder timestamp(DateTime timestamp) { // checkOwnership(); // this.timestamp = timestamp; // return this; // } // // public MessageBuilder level(Message.Level level) { // checkOwnership(); // this.level = level; // return this; // } // // public MessageBuilder input(String input) { // checkOwnership(); // this.input = input; // return this; // } // // public MessageBuilder outputs(Set<String> outputs) { // checkOwnership(); // if (outputs == null) { // this.outputs = null; // } else { // this.outputs = ImmutableSet.copyOf(outputs); // } // return this; // } // // public MessageBuilder fields(MessageFields fields) { // checkOwnership(); // this.fields = fields; // return this; // } // // public MessageBuilder addField(String key, int value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, long value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, boolean value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, String value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public Message build() { // checkNotNull(message, "Message should not be null!"); // checkNotNull(source, "Message source should not be null!"); // checkNotNull(timestamp, "Message timestamp should not be null!"); // checkNotNull(input, "Message input should not be null!"); // checkNotNull(outputs, "Message outputs should not be null!"); // // if (fields == null) { // return new Message(message, source, timestamp, level, input, outputs); // } else { // return new Message(message, source, timestamp, level, input, outputs, fields); // } // } // // public MessageBuilder copy() { // return new MessageBuilder(message, source, timestamp, level, input, outputs, fields.copy()); // } // // private void checkOwnership() { // final long currentId = Thread.currentThread().getId(); // checkState(ownerId == currentId, "Modification only allowed by owning thread. (owner=" + ownerId + " current=" + currentId + ")"); // } // } // // Path: src/main/java/org/graylog/collector/buffer/Buffer.java // public interface Buffer { // void insert(Message message); // // Message remove(); // }
import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.graylog.collector.Message; import org.graylog.collector.MessageBuilder; import org.graylog.collector.buffer.Buffer; import org.hyperic.sigar.win32.EventLogRecord; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.junit.Before; import org.junit.Test; import java.util.List; import java.util.Map;
/** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.inputs.eventlog; public class WindowsEventlogHandlerTest { private static class TestBuffer implements Buffer { private final List<Message> messages = Lists.newArrayList(); @Override public void insert(final Message message) { messages.add(message); } @Override public Message remove() { return null; } public void clear() { messages.clear(); } public List<Message> getMessages() { return messages; } } private TestBuffer buffer;
// Path: src/main/java/org/graylog/collector/MessageBuilder.java // public class MessageBuilder { // private final long ownerId = Thread.currentThread().getId(); // // private String message; // private String source; // private DateTime timestamp; // private Message.Level level; // private String input; // private Set<String> outputs; // private MessageFields fields = new MessageFields(); // // public MessageBuilder() { // } // // private MessageBuilder(String message, String source, DateTime timestamp, Message.Level level, String input, Set<String> outputs, MessageFields fields) { // this.message = message; // this.source = source; // this.timestamp = timestamp; // this.level = level; // this.input = input; // this.outputs = outputs; // this.fields = fields; // } // // public MessageBuilder message(String message) { // checkOwnership(); // this.message = message; // return this; // } // // public MessageBuilder source(String source) { // checkOwnership(); // this.source = source; // return this; // } // // public MessageBuilder timestamp(DateTime timestamp) { // checkOwnership(); // this.timestamp = timestamp; // return this; // } // // public MessageBuilder level(Message.Level level) { // checkOwnership(); // this.level = level; // return this; // } // // public MessageBuilder input(String input) { // checkOwnership(); // this.input = input; // return this; // } // // public MessageBuilder outputs(Set<String> outputs) { // checkOwnership(); // if (outputs == null) { // this.outputs = null; // } else { // this.outputs = ImmutableSet.copyOf(outputs); // } // return this; // } // // public MessageBuilder fields(MessageFields fields) { // checkOwnership(); // this.fields = fields; // return this; // } // // public MessageBuilder addField(String key, int value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, long value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, boolean value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, String value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public Message build() { // checkNotNull(message, "Message should not be null!"); // checkNotNull(source, "Message source should not be null!"); // checkNotNull(timestamp, "Message timestamp should not be null!"); // checkNotNull(input, "Message input should not be null!"); // checkNotNull(outputs, "Message outputs should not be null!"); // // if (fields == null) { // return new Message(message, source, timestamp, level, input, outputs); // } else { // return new Message(message, source, timestamp, level, input, outputs, fields); // } // } // // public MessageBuilder copy() { // return new MessageBuilder(message, source, timestamp, level, input, outputs, fields.copy()); // } // // private void checkOwnership() { // final long currentId = Thread.currentThread().getId(); // checkState(ownerId == currentId, "Modification only allowed by owning thread. (owner=" + ownerId + " current=" + currentId + ")"); // } // } // // Path: src/main/java/org/graylog/collector/buffer/Buffer.java // public interface Buffer { // void insert(Message message); // // Message remove(); // } // Path: src/test/java/org/graylog/collector/inputs/eventlog/WindowsEventlogHandlerTest.java import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.graylog.collector.Message; import org.graylog.collector.MessageBuilder; import org.graylog.collector.buffer.Buffer; import org.hyperic.sigar.win32.EventLogRecord; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.junit.Before; import org.junit.Test; import java.util.List; import java.util.Map; /** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.inputs.eventlog; public class WindowsEventlogHandlerTest { private static class TestBuffer implements Buffer { private final List<Message> messages = Lists.newArrayList(); @Override public void insert(final Message message) { messages.add(message); } @Override public Message remove() { return null; } public void clear() { messages.clear(); } public List<Message> getMessages() { return messages; } } private TestBuffer buffer;
private MessageBuilder messageBuilder;
DevOpsStudio/Re-Collector
src/main/java/org/graylog/collector/serverapi/RestAdapterProvider.java
// Path: src/main/java/org/graylog/collector/CollectorVersion.java // public class CollectorVersion { // public static final CollectorVersion CURRENT; // static Logger LOG = Logger.getLogger(CollectorVersion.class.getName()); // // static { // String version = "NONE"; // String commitId = "NONE"; // String commitIdShort = "NONE"; // String timestamp = "NONE"; // // final InputStream stream = CollectorVersion.class.getResourceAsStream("/collector-version.properties"); // final Properties properties = new Properties(); // // try { // properties.load(stream); // // version = properties.getProperty("version"); // commitId = properties.getProperty("commit-id"); // timestamp = properties.getProperty("timestamp"); // // if (!isNullOrEmpty(commitId) && !"NONE".equals(commitId)) { // commitIdShort = commitId.substring(0, 7); // } // } catch (IOException ignored) { // LOG.info("Can not Load The Properties"); // } // // CURRENT = new CollectorVersion(version, commitId, commitIdShort, timestamp); // } // // private final String version; // private final String commitId; // private final String commitIdShort; // private final String timestamp; // // public CollectorVersion(String version, String commitId, String commitIdShort, String timestamp) { // this.version = version; // this.commitId = commitId; // this.commitIdShort = commitIdShort; // this.timestamp = timestamp; // } // // public String version() { // return version; // } // // public String commitId() { // return commitId; // } // // public String commitIdShort() { // return commitIdShort; // } // // public String timestamp() { // return timestamp; // } // // @Override // public String toString() { // return "v" + version + "(commit" + commitIdShort() + ")"; // } // }
import com.fasterxml.jackson.databind.ObjectMapper; import org.graylog.collector.CollectorVersion; import org.graylog.collector.annotations.GraylogServerURL; import retrofit.RequestInterceptor; import retrofit.RestAdapter; import retrofit.converter.JacksonConverter; import javax.inject.Inject; import javax.inject.Provider;
/** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.serverapi; public class RestAdapterProvider implements Provider<RestAdapter> { private final String graylogServerURL; @Inject public RestAdapterProvider(@GraylogServerURL String graylogServerURL) { this.graylogServerURL = graylogServerURL; } @Override public RestAdapter get() { return new RestAdapter.Builder() .setEndpoint(graylogServerURL) .setConverter(new JacksonConverter(new ObjectMapper())) .setRequestInterceptor(request -> {
// Path: src/main/java/org/graylog/collector/CollectorVersion.java // public class CollectorVersion { // public static final CollectorVersion CURRENT; // static Logger LOG = Logger.getLogger(CollectorVersion.class.getName()); // // static { // String version = "NONE"; // String commitId = "NONE"; // String commitIdShort = "NONE"; // String timestamp = "NONE"; // // final InputStream stream = CollectorVersion.class.getResourceAsStream("/collector-version.properties"); // final Properties properties = new Properties(); // // try { // properties.load(stream); // // version = properties.getProperty("version"); // commitId = properties.getProperty("commit-id"); // timestamp = properties.getProperty("timestamp"); // // if (!isNullOrEmpty(commitId) && !"NONE".equals(commitId)) { // commitIdShort = commitId.substring(0, 7); // } // } catch (IOException ignored) { // LOG.info("Can not Load The Properties"); // } // // CURRENT = new CollectorVersion(version, commitId, commitIdShort, timestamp); // } // // private final String version; // private final String commitId; // private final String commitIdShort; // private final String timestamp; // // public CollectorVersion(String version, String commitId, String commitIdShort, String timestamp) { // this.version = version; // this.commitId = commitId; // this.commitIdShort = commitIdShort; // this.timestamp = timestamp; // } // // public String version() { // return version; // } // // public String commitId() { // return commitId; // } // // public String commitIdShort() { // return commitIdShort; // } // // public String timestamp() { // return timestamp; // } // // @Override // public String toString() { // return "v" + version + "(commit" + commitIdShort() + ")"; // } // } // Path: src/main/java/org/graylog/collector/serverapi/RestAdapterProvider.java import com.fasterxml.jackson.databind.ObjectMapper; import org.graylog.collector.CollectorVersion; import org.graylog.collector.annotations.GraylogServerURL; import retrofit.RequestInterceptor; import retrofit.RestAdapter; import retrofit.converter.JacksonConverter; import javax.inject.Inject; import javax.inject.Provider; /** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.serverapi; public class RestAdapterProvider implements Provider<RestAdapter> { private final String graylogServerURL; @Inject public RestAdapterProvider(@GraylogServerURL String graylogServerURL) { this.graylogServerURL = graylogServerURL; } @Override public RestAdapter get() { return new RestAdapter.Builder() .setEndpoint(graylogServerURL) .setConverter(new JacksonConverter(new ObjectMapper())) .setRequestInterceptor(request -> {
request.addHeader("User-Agent", "LogInsight Collector " + CollectorVersion.CURRENT);
DevOpsStudio/Re-Collector
src/main/java/org/graylog/collector/inputs/eventlog/WindowsEventlogHandler.java
// Path: src/main/java/org/graylog/collector/MessageBuilder.java // public class MessageBuilder { // private final long ownerId = Thread.currentThread().getId(); // // private String message; // private String source; // private DateTime timestamp; // private Message.Level level; // private String input; // private Set<String> outputs; // private MessageFields fields = new MessageFields(); // // public MessageBuilder() { // } // // private MessageBuilder(String message, String source, DateTime timestamp, Message.Level level, String input, Set<String> outputs, MessageFields fields) { // this.message = message; // this.source = source; // this.timestamp = timestamp; // this.level = level; // this.input = input; // this.outputs = outputs; // this.fields = fields; // } // // public MessageBuilder message(String message) { // checkOwnership(); // this.message = message; // return this; // } // // public MessageBuilder source(String source) { // checkOwnership(); // this.source = source; // return this; // } // // public MessageBuilder timestamp(DateTime timestamp) { // checkOwnership(); // this.timestamp = timestamp; // return this; // } // // public MessageBuilder level(Message.Level level) { // checkOwnership(); // this.level = level; // return this; // } // // public MessageBuilder input(String input) { // checkOwnership(); // this.input = input; // return this; // } // // public MessageBuilder outputs(Set<String> outputs) { // checkOwnership(); // if (outputs == null) { // this.outputs = null; // } else { // this.outputs = ImmutableSet.copyOf(outputs); // } // return this; // } // // public MessageBuilder fields(MessageFields fields) { // checkOwnership(); // this.fields = fields; // return this; // } // // public MessageBuilder addField(String key, int value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, long value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, boolean value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, String value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public Message build() { // checkNotNull(message, "Message should not be null!"); // checkNotNull(source, "Message source should not be null!"); // checkNotNull(timestamp, "Message timestamp should not be null!"); // checkNotNull(input, "Message input should not be null!"); // checkNotNull(outputs, "Message outputs should not be null!"); // // if (fields == null) { // return new Message(message, source, timestamp, level, input, outputs); // } else { // return new Message(message, source, timestamp, level, input, outputs, fields); // } // } // // public MessageBuilder copy() { // return new MessageBuilder(message, source, timestamp, level, input, outputs, fields.copy()); // } // // private void checkOwnership() { // final long currentId = Thread.currentThread().getId(); // checkState(ownerId == currentId, "Modification only allowed by owning thread. (owner=" + ownerId + " current=" + currentId + ")"); // } // } // // Path: src/main/java/org/graylog/collector/buffer/Buffer.java // public interface Buffer { // void insert(Message message); // // Message remove(); // }
import org.graylog.collector.Message; import org.graylog.collector.MessageBuilder; import org.graylog.collector.buffer.Buffer; import org.hyperic.sigar.win32.EventLogNotification; import org.hyperic.sigar.win32.EventLogRecord; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.google.common.base.Strings.isNullOrEmpty;
/** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.inputs.eventlog; public class WindowsEventlogHandler implements EventLogNotification { private static final Logger LOG = LoggerFactory.getLogger(WindowsEventlogHandler.class);
// Path: src/main/java/org/graylog/collector/MessageBuilder.java // public class MessageBuilder { // private final long ownerId = Thread.currentThread().getId(); // // private String message; // private String source; // private DateTime timestamp; // private Message.Level level; // private String input; // private Set<String> outputs; // private MessageFields fields = new MessageFields(); // // public MessageBuilder() { // } // // private MessageBuilder(String message, String source, DateTime timestamp, Message.Level level, String input, Set<String> outputs, MessageFields fields) { // this.message = message; // this.source = source; // this.timestamp = timestamp; // this.level = level; // this.input = input; // this.outputs = outputs; // this.fields = fields; // } // // public MessageBuilder message(String message) { // checkOwnership(); // this.message = message; // return this; // } // // public MessageBuilder source(String source) { // checkOwnership(); // this.source = source; // return this; // } // // public MessageBuilder timestamp(DateTime timestamp) { // checkOwnership(); // this.timestamp = timestamp; // return this; // } // // public MessageBuilder level(Message.Level level) { // checkOwnership(); // this.level = level; // return this; // } // // public MessageBuilder input(String input) { // checkOwnership(); // this.input = input; // return this; // } // // public MessageBuilder outputs(Set<String> outputs) { // checkOwnership(); // if (outputs == null) { // this.outputs = null; // } else { // this.outputs = ImmutableSet.copyOf(outputs); // } // return this; // } // // public MessageBuilder fields(MessageFields fields) { // checkOwnership(); // this.fields = fields; // return this; // } // // public MessageBuilder addField(String key, int value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, long value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, boolean value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, String value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public Message build() { // checkNotNull(message, "Message should not be null!"); // checkNotNull(source, "Message source should not be null!"); // checkNotNull(timestamp, "Message timestamp should not be null!"); // checkNotNull(input, "Message input should not be null!"); // checkNotNull(outputs, "Message outputs should not be null!"); // // if (fields == null) { // return new Message(message, source, timestamp, level, input, outputs); // } else { // return new Message(message, source, timestamp, level, input, outputs, fields); // } // } // // public MessageBuilder copy() { // return new MessageBuilder(message, source, timestamp, level, input, outputs, fields.copy()); // } // // private void checkOwnership() { // final long currentId = Thread.currentThread().getId(); // checkState(ownerId == currentId, "Modification only allowed by owning thread. (owner=" + ownerId + " current=" + currentId + ")"); // } // } // // Path: src/main/java/org/graylog/collector/buffer/Buffer.java // public interface Buffer { // void insert(Message message); // // Message remove(); // } // Path: src/main/java/org/graylog/collector/inputs/eventlog/WindowsEventlogHandler.java import org.graylog.collector.Message; import org.graylog.collector.MessageBuilder; import org.graylog.collector.buffer.Buffer; import org.hyperic.sigar.win32.EventLogNotification; import org.hyperic.sigar.win32.EventLogRecord; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.google.common.base.Strings.isNullOrEmpty; /** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.inputs.eventlog; public class WindowsEventlogHandler implements EventLogNotification { private static final Logger LOG = LoggerFactory.getLogger(WindowsEventlogHandler.class);
private final MessageBuilder messageBuilder;
DevOpsStudio/Re-Collector
src/main/java/org/graylog/collector/inputs/eventlog/WindowsEventlogHandler.java
// Path: src/main/java/org/graylog/collector/MessageBuilder.java // public class MessageBuilder { // private final long ownerId = Thread.currentThread().getId(); // // private String message; // private String source; // private DateTime timestamp; // private Message.Level level; // private String input; // private Set<String> outputs; // private MessageFields fields = new MessageFields(); // // public MessageBuilder() { // } // // private MessageBuilder(String message, String source, DateTime timestamp, Message.Level level, String input, Set<String> outputs, MessageFields fields) { // this.message = message; // this.source = source; // this.timestamp = timestamp; // this.level = level; // this.input = input; // this.outputs = outputs; // this.fields = fields; // } // // public MessageBuilder message(String message) { // checkOwnership(); // this.message = message; // return this; // } // // public MessageBuilder source(String source) { // checkOwnership(); // this.source = source; // return this; // } // // public MessageBuilder timestamp(DateTime timestamp) { // checkOwnership(); // this.timestamp = timestamp; // return this; // } // // public MessageBuilder level(Message.Level level) { // checkOwnership(); // this.level = level; // return this; // } // // public MessageBuilder input(String input) { // checkOwnership(); // this.input = input; // return this; // } // // public MessageBuilder outputs(Set<String> outputs) { // checkOwnership(); // if (outputs == null) { // this.outputs = null; // } else { // this.outputs = ImmutableSet.copyOf(outputs); // } // return this; // } // // public MessageBuilder fields(MessageFields fields) { // checkOwnership(); // this.fields = fields; // return this; // } // // public MessageBuilder addField(String key, int value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, long value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, boolean value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, String value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public Message build() { // checkNotNull(message, "Message should not be null!"); // checkNotNull(source, "Message source should not be null!"); // checkNotNull(timestamp, "Message timestamp should not be null!"); // checkNotNull(input, "Message input should not be null!"); // checkNotNull(outputs, "Message outputs should not be null!"); // // if (fields == null) { // return new Message(message, source, timestamp, level, input, outputs); // } else { // return new Message(message, source, timestamp, level, input, outputs, fields); // } // } // // public MessageBuilder copy() { // return new MessageBuilder(message, source, timestamp, level, input, outputs, fields.copy()); // } // // private void checkOwnership() { // final long currentId = Thread.currentThread().getId(); // checkState(ownerId == currentId, "Modification only allowed by owning thread. (owner=" + ownerId + " current=" + currentId + ")"); // } // } // // Path: src/main/java/org/graylog/collector/buffer/Buffer.java // public interface Buffer { // void insert(Message message); // // Message remove(); // }
import org.graylog.collector.Message; import org.graylog.collector.MessageBuilder; import org.graylog.collector.buffer.Buffer; import org.hyperic.sigar.win32.EventLogNotification; import org.hyperic.sigar.win32.EventLogRecord; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.google.common.base.Strings.isNullOrEmpty;
/** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.inputs.eventlog; public class WindowsEventlogHandler implements EventLogNotification { private static final Logger LOG = LoggerFactory.getLogger(WindowsEventlogHandler.class); private final MessageBuilder messageBuilder;
// Path: src/main/java/org/graylog/collector/MessageBuilder.java // public class MessageBuilder { // private final long ownerId = Thread.currentThread().getId(); // // private String message; // private String source; // private DateTime timestamp; // private Message.Level level; // private String input; // private Set<String> outputs; // private MessageFields fields = new MessageFields(); // // public MessageBuilder() { // } // // private MessageBuilder(String message, String source, DateTime timestamp, Message.Level level, String input, Set<String> outputs, MessageFields fields) { // this.message = message; // this.source = source; // this.timestamp = timestamp; // this.level = level; // this.input = input; // this.outputs = outputs; // this.fields = fields; // } // // public MessageBuilder message(String message) { // checkOwnership(); // this.message = message; // return this; // } // // public MessageBuilder source(String source) { // checkOwnership(); // this.source = source; // return this; // } // // public MessageBuilder timestamp(DateTime timestamp) { // checkOwnership(); // this.timestamp = timestamp; // return this; // } // // public MessageBuilder level(Message.Level level) { // checkOwnership(); // this.level = level; // return this; // } // // public MessageBuilder input(String input) { // checkOwnership(); // this.input = input; // return this; // } // // public MessageBuilder outputs(Set<String> outputs) { // checkOwnership(); // if (outputs == null) { // this.outputs = null; // } else { // this.outputs = ImmutableSet.copyOf(outputs); // } // return this; // } // // public MessageBuilder fields(MessageFields fields) { // checkOwnership(); // this.fields = fields; // return this; // } // // public MessageBuilder addField(String key, int value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, long value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, boolean value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, String value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public Message build() { // checkNotNull(message, "Message should not be null!"); // checkNotNull(source, "Message source should not be null!"); // checkNotNull(timestamp, "Message timestamp should not be null!"); // checkNotNull(input, "Message input should not be null!"); // checkNotNull(outputs, "Message outputs should not be null!"); // // if (fields == null) { // return new Message(message, source, timestamp, level, input, outputs); // } else { // return new Message(message, source, timestamp, level, input, outputs, fields); // } // } // // public MessageBuilder copy() { // return new MessageBuilder(message, source, timestamp, level, input, outputs, fields.copy()); // } // // private void checkOwnership() { // final long currentId = Thread.currentThread().getId(); // checkState(ownerId == currentId, "Modification only allowed by owning thread. (owner=" + ownerId + " current=" + currentId + ")"); // } // } // // Path: src/main/java/org/graylog/collector/buffer/Buffer.java // public interface Buffer { // void insert(Message message); // // Message remove(); // } // Path: src/main/java/org/graylog/collector/inputs/eventlog/WindowsEventlogHandler.java import org.graylog.collector.Message; import org.graylog.collector.MessageBuilder; import org.graylog.collector.buffer.Buffer; import org.hyperic.sigar.win32.EventLogNotification; import org.hyperic.sigar.win32.EventLogRecord; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.google.common.base.Strings.isNullOrEmpty; /** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.inputs.eventlog; public class WindowsEventlogHandler implements EventLogNotification { private static final Logger LOG = LoggerFactory.getLogger(WindowsEventlogHandler.class); private final MessageBuilder messageBuilder;
private final Buffer buffer;
DevOpsStudio/Re-Collector
src/main/java/org/graylog/collector/file/ChunkReader.java
// Path: src/main/java/org/graylog/collector/inputs/file/FileInput.java // public class FileInput extends InputService { // public enum InitialReadPosition { // START, // END // } // // public interface Factory extends InputService.Factory<FileInput, FileInputConfiguration> { // FileInput create(FileInputConfiguration configuration); // } // // private final FileInputConfiguration configuration; // private final Buffer buffer; // private final FileObserver fileObserver; // private final String collectorHostName; // private FileReaderService readerService; // // @Inject // public FileInput(@Assisted FileInputConfiguration inputConfiguration, Buffer buffer, FileObserver fileObserver, // @CollectorHostName String collectorHostName) { // this.configuration = inputConfiguration; // this.buffer = buffer; // this.fileObserver = fileObserver; // this.collectorHostName = collectorHostName; // } // // @Override // public String getId() { // return configuration.getId(); // } // // @Override // public Set<String> getOutputs() { // return configuration.getOutputs(); // } // // @Override // protected void doStart() { // // TODO needs to be an absolute path because otherwise the FileObserver does weird things. Investigate what's wrong with it. // final MessageBuilder messageBuilder = new MessageBuilder() // .input(getId()) // .outputs(getOutputs()) // .source(collectorHostName) // .fields(configuration.getMessageFields()); // final PathSet pathSet = configuration.getPathSet(); // readerService = new FileReaderService( // pathSet, // configuration.getCharset(), // InitialReadPosition.END, // this, // messageBuilder, // configuration.createContentSplitter(), // buffer, // configuration.getReaderBufferSize(), // configuration.getReaderInterval(), // fileObserver // ); // // readerService.startAsync().awaitRunning(); // notifyStarted(); // } // // @Override // protected void doStop() { // readerService.stopAsync().awaitTerminated(); // notifyStopped(); // } // // @Override // public void setReaderFinished(ChunkReader chunkReader) { // // TODO Check if needed and for what it was used. // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // FileInput fileInput = (FileInput) o; // // return configuration.equals(fileInput.configuration); // // } // // @Override // public int hashCode() { // return configuration.hashCode(); // } // // @Override // public String toString() { // return ConfigurationUtils.toString(configuration, this); // } // }
import com.google.common.base.Preconditions; import com.google.common.primitives.Ints; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.graylog.collector.inputs.Input; import org.graylog.collector.inputs.file.FileInput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousFileChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.util.Objects; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean;
/** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.file; public class ChunkReader implements Runnable { private static final Logger log = LoggerFactory.getLogger(ChunkReader.class); private final Input fileInput; private final Path path; private final AsynchronousFileChannel fileChannel; private final BlockingQueue<FileChunk> chunks; private final int initialChunkSize; private final ChunkReaderScheduler chunkReaderScheduler; private int lastReadSize = 0; // TODO for adaptive read sizing private long position = 0; private AtomicBoolean locked = new AtomicBoolean(false); private FileChunk queuedChunk; private long chunkId = 0; private Object fileKey; public ChunkReader(Input fileInput, Path path, AsynchronousFileChannel fileChannel, BlockingQueue<FileChunk> chunks, int initialChunkSize,
// Path: src/main/java/org/graylog/collector/inputs/file/FileInput.java // public class FileInput extends InputService { // public enum InitialReadPosition { // START, // END // } // // public interface Factory extends InputService.Factory<FileInput, FileInputConfiguration> { // FileInput create(FileInputConfiguration configuration); // } // // private final FileInputConfiguration configuration; // private final Buffer buffer; // private final FileObserver fileObserver; // private final String collectorHostName; // private FileReaderService readerService; // // @Inject // public FileInput(@Assisted FileInputConfiguration inputConfiguration, Buffer buffer, FileObserver fileObserver, // @CollectorHostName String collectorHostName) { // this.configuration = inputConfiguration; // this.buffer = buffer; // this.fileObserver = fileObserver; // this.collectorHostName = collectorHostName; // } // // @Override // public String getId() { // return configuration.getId(); // } // // @Override // public Set<String> getOutputs() { // return configuration.getOutputs(); // } // // @Override // protected void doStart() { // // TODO needs to be an absolute path because otherwise the FileObserver does weird things. Investigate what's wrong with it. // final MessageBuilder messageBuilder = new MessageBuilder() // .input(getId()) // .outputs(getOutputs()) // .source(collectorHostName) // .fields(configuration.getMessageFields()); // final PathSet pathSet = configuration.getPathSet(); // readerService = new FileReaderService( // pathSet, // configuration.getCharset(), // InitialReadPosition.END, // this, // messageBuilder, // configuration.createContentSplitter(), // buffer, // configuration.getReaderBufferSize(), // configuration.getReaderInterval(), // fileObserver // ); // // readerService.startAsync().awaitRunning(); // notifyStarted(); // } // // @Override // protected void doStop() { // readerService.stopAsync().awaitTerminated(); // notifyStopped(); // } // // @Override // public void setReaderFinished(ChunkReader chunkReader) { // // TODO Check if needed and for what it was used. // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // FileInput fileInput = (FileInput) o; // // return configuration.equals(fileInput.configuration); // // } // // @Override // public int hashCode() { // return configuration.hashCode(); // } // // @Override // public String toString() { // return ConfigurationUtils.toString(configuration, this); // } // } // Path: src/main/java/org/graylog/collector/file/ChunkReader.java import com.google.common.base.Preconditions; import com.google.common.primitives.Ints; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.graylog.collector.inputs.Input; import org.graylog.collector.inputs.file.FileInput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousFileChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import java.util.Objects; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; /** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.file; public class ChunkReader implements Runnable { private static final Logger log = LoggerFactory.getLogger(ChunkReader.class); private final Input fileInput; private final Path path; private final AsynchronousFileChannel fileChannel; private final BlockingQueue<FileChunk> chunks; private final int initialChunkSize; private final ChunkReaderScheduler chunkReaderScheduler; private int lastReadSize = 0; // TODO for adaptive read sizing private long position = 0; private AtomicBoolean locked = new AtomicBoolean(false); private FileChunk queuedChunk; private long chunkId = 0; private Object fileKey; public ChunkReader(Input fileInput, Path path, AsynchronousFileChannel fileChannel, BlockingQueue<FileChunk> chunks, int initialChunkSize,
FileInput.InitialReadPosition initialReadPosition,
DevOpsStudio/Re-Collector
src/main/java/org/graylog/collector/inputs/db/DatabaseInputConfiguration.java
// Path: src/main/java/org/graylog/collector/inputs/InputService.java // public abstract class InputService extends AbstractService implements Input { // }
import com.google.inject.assistedinject.Assisted; import com.typesafe.config.Config; import org.graylog.collector.config.ConfigurationUtils; import org.graylog.collector.config.constraints.IsOneOf; import org.graylog.collector.inputs.InputConfiguration; import org.graylog.collector.inputs.InputService; import org.hibernate.validator.constraints.NotBlank; import javax.inject.Inject; import javax.validation.constraints.NotNull; import java.util.Collections; import java.util.HashMap; import java.util.Map;
} if (config.hasPath("sql")) { this.sql = config.getString("sql"); } if (config.hasPath("key-type")) { this.keytype = config.getString("key-type"); } if (config.hasPath("id-field")) { this.idfield = config.getString("id-field"); } if (config.hasPath("db-driver-path")) { this.dbDriverPath = config.getString("db-driver-path"); } if (config.hasPath("init-sql")) { this.initSql = config.getString("init-sql"); } if (config.hasPath("db-user")) { this.dbUser = config.getString("db-user"); } if (config.hasPath("db-password")) { this.dbPassword = config.getString("db-password"); } if (config.hasPath("db-sync-time")) { this.dbSyncTime = config.getInt("db-sync-time"); } else { this.dbSyncTime = 1; } } @Override
// Path: src/main/java/org/graylog/collector/inputs/InputService.java // public abstract class InputService extends AbstractService implements Input { // } // Path: src/main/java/org/graylog/collector/inputs/db/DatabaseInputConfiguration.java import com.google.inject.assistedinject.Assisted; import com.typesafe.config.Config; import org.graylog.collector.config.ConfigurationUtils; import org.graylog.collector.config.constraints.IsOneOf; import org.graylog.collector.inputs.InputConfiguration; import org.graylog.collector.inputs.InputService; import org.hibernate.validator.constraints.NotBlank; import javax.inject.Inject; import javax.validation.constraints.NotNull; import java.util.Collections; import java.util.HashMap; import java.util.Map; } if (config.hasPath("sql")) { this.sql = config.getString("sql"); } if (config.hasPath("key-type")) { this.keytype = config.getString("key-type"); } if (config.hasPath("id-field")) { this.idfield = config.getString("id-field"); } if (config.hasPath("db-driver-path")) { this.dbDriverPath = config.getString("db-driver-path"); } if (config.hasPath("init-sql")) { this.initSql = config.getString("init-sql"); } if (config.hasPath("db-user")) { this.dbUser = config.getString("db-user"); } if (config.hasPath("db-password")) { this.dbPassword = config.getString("db-password"); } if (config.hasPath("db-sync-time")) { this.dbSyncTime = config.getInt("db-sync-time"); } else { this.dbSyncTime = 1; } } @Override
public InputService createInput() {
DevOpsStudio/Re-Collector
src/main/java/org/graylog/collector/inputs/eventlog/WindowsEventlogInputConfiguration.java
// Path: src/main/java/org/graylog/collector/inputs/InputService.java // public abstract class InputService extends AbstractService implements Input { // }
import com.google.inject.assistedinject.Assisted; import com.typesafe.config.Config; import org.graylog.collector.config.ConfigurationUtils; import org.graylog.collector.inputs.InputConfiguration; import org.graylog.collector.inputs.InputService; import javax.inject.Inject; import javax.validation.constraints.NotNull; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit;
@Inject public WindowsEventlogInputConfiguration(@Assisted String id, @Assisted Config config, WindowsEventlogInput.Factory inputFactory) { super(id, config); this.inputFactory = inputFactory; if (config.hasPath("source-name")) { this.sourceName = config.getString("source-name"); } else { this.sourceName = "Application"; } if (config.hasPath("poll-interval")) { this.pollInterval = config.getDuration("poll-interval", TimeUnit.MILLISECONDS); } else { this.pollInterval = 1000L; } } public String getSourceName() { return sourceName; } public long getPollInterval() { return pollInterval; } @Override
// Path: src/main/java/org/graylog/collector/inputs/InputService.java // public abstract class InputService extends AbstractService implements Input { // } // Path: src/main/java/org/graylog/collector/inputs/eventlog/WindowsEventlogInputConfiguration.java import com.google.inject.assistedinject.Assisted; import com.typesafe.config.Config; import org.graylog.collector.config.ConfigurationUtils; import org.graylog.collector.inputs.InputConfiguration; import org.graylog.collector.inputs.InputService; import javax.inject.Inject; import javax.validation.constraints.NotNull; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; @Inject public WindowsEventlogInputConfiguration(@Assisted String id, @Assisted Config config, WindowsEventlogInput.Factory inputFactory) { super(id, config); this.inputFactory = inputFactory; if (config.hasPath("source-name")) { this.sourceName = config.getString("source-name"); } else { this.sourceName = "Application"; } if (config.hasPath("poll-interval")) { this.pollInterval = config.getDuration("poll-interval", TimeUnit.MILLISECONDS); } else { this.pollInterval = 1000L; } } public String getSourceName() { return sourceName; } public long getPollInterval() { return pollInterval; } @Override
public InputService createInput() {
DevOpsStudio/Re-Collector
src/main/java/org/graylog/collector/config/ConfigurationRegistry.java
// Path: src/main/java/org/graylog/collector/inputs/InputService.java // public abstract class InputService extends AbstractService implements Input { // } // // Path: src/main/java/org/graylog/collector/outputs/Output.java // public interface Output { // String getId(); // // Set<String> getInputs(); // // void write(Message message); // // interface Factory<T extends Output, C extends Configuration> { // T create(C configuration); // } // } // // Path: src/main/java/org/graylog/collector/outputs/OutputConfiguration.java // public abstract class OutputConfiguration implements Configuration { // public interface Factory<C extends OutputConfiguration> { // C create(String id, Config config); // } // // @NotBlank // private final String id; // // @NotNull // private Set<String> inputs = Sets.newHashSet(); // // public OutputConfiguration(String id, Config config) { // this.id = id; // // if (config.hasPath("inputs")) { // this.inputs = Sets.newHashSet(Splitter.on(",").omitEmptyStrings().trimResults().split(config.getString("inputs"))); // } // } // // public abstract OutputService createOutput(); // // @Override // public String getId() { // return id; // } // // public Set<String> getInputs() { // return inputs; // } // // @Override // public Map<String, String> toStringValues() { // return Collections.unmodifiableMap(new HashMap<String, String>() { // { // put("id", getId()); // put("inputs", Joiner.on(",").join(getInputs())); // } // }); // } // } // // Path: src/main/java/org/graylog/collector/outputs/OutputService.java // public abstract class OutputService extends AbstractService implements Output { // }
import javax.inject.Inject; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.util.concurrent.Service; import com.typesafe.config.Config; import com.typesafe.config.ConfigException; import com.typesafe.config.ConfigObject; import com.typesafe.config.ConfigValue; import org.graylog.collector.inputs.Input; import org.graylog.collector.inputs.InputConfiguration; import org.graylog.collector.inputs.InputService; import org.graylog.collector.outputs.Output; import org.graylog.collector.outputs.OutputConfiguration; import org.graylog.collector.outputs.OutputService;
/** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.config; public class ConfigurationRegistry { private final Set<Service> services = Sets.newHashSet(); private final Set<Input> inputs = Sets.newHashSet();
// Path: src/main/java/org/graylog/collector/inputs/InputService.java // public abstract class InputService extends AbstractService implements Input { // } // // Path: src/main/java/org/graylog/collector/outputs/Output.java // public interface Output { // String getId(); // // Set<String> getInputs(); // // void write(Message message); // // interface Factory<T extends Output, C extends Configuration> { // T create(C configuration); // } // } // // Path: src/main/java/org/graylog/collector/outputs/OutputConfiguration.java // public abstract class OutputConfiguration implements Configuration { // public interface Factory<C extends OutputConfiguration> { // C create(String id, Config config); // } // // @NotBlank // private final String id; // // @NotNull // private Set<String> inputs = Sets.newHashSet(); // // public OutputConfiguration(String id, Config config) { // this.id = id; // // if (config.hasPath("inputs")) { // this.inputs = Sets.newHashSet(Splitter.on(",").omitEmptyStrings().trimResults().split(config.getString("inputs"))); // } // } // // public abstract OutputService createOutput(); // // @Override // public String getId() { // return id; // } // // public Set<String> getInputs() { // return inputs; // } // // @Override // public Map<String, String> toStringValues() { // return Collections.unmodifiableMap(new HashMap<String, String>() { // { // put("id", getId()); // put("inputs", Joiner.on(",").join(getInputs())); // } // }); // } // } // // Path: src/main/java/org/graylog/collector/outputs/OutputService.java // public abstract class OutputService extends AbstractService implements Output { // } // Path: src/main/java/org/graylog/collector/config/ConfigurationRegistry.java import javax.inject.Inject; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.util.concurrent.Service; import com.typesafe.config.Config; import com.typesafe.config.ConfigException; import com.typesafe.config.ConfigObject; import com.typesafe.config.ConfigValue; import org.graylog.collector.inputs.Input; import org.graylog.collector.inputs.InputConfiguration; import org.graylog.collector.inputs.InputService; import org.graylog.collector.outputs.Output; import org.graylog.collector.outputs.OutputConfiguration; import org.graylog.collector.outputs.OutputService; /** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.config; public class ConfigurationRegistry { private final Set<Service> services = Sets.newHashSet(); private final Set<Input> inputs = Sets.newHashSet();
private final Set<Output> outputs = Sets.newHashSet();
DevOpsStudio/Re-Collector
src/main/java/org/graylog/collector/config/ConfigurationRegistry.java
// Path: src/main/java/org/graylog/collector/inputs/InputService.java // public abstract class InputService extends AbstractService implements Input { // } // // Path: src/main/java/org/graylog/collector/outputs/Output.java // public interface Output { // String getId(); // // Set<String> getInputs(); // // void write(Message message); // // interface Factory<T extends Output, C extends Configuration> { // T create(C configuration); // } // } // // Path: src/main/java/org/graylog/collector/outputs/OutputConfiguration.java // public abstract class OutputConfiguration implements Configuration { // public interface Factory<C extends OutputConfiguration> { // C create(String id, Config config); // } // // @NotBlank // private final String id; // // @NotNull // private Set<String> inputs = Sets.newHashSet(); // // public OutputConfiguration(String id, Config config) { // this.id = id; // // if (config.hasPath("inputs")) { // this.inputs = Sets.newHashSet(Splitter.on(",").omitEmptyStrings().trimResults().split(config.getString("inputs"))); // } // } // // public abstract OutputService createOutput(); // // @Override // public String getId() { // return id; // } // // public Set<String> getInputs() { // return inputs; // } // // @Override // public Map<String, String> toStringValues() { // return Collections.unmodifiableMap(new HashMap<String, String>() { // { // put("id", getId()); // put("inputs", Joiner.on(",").join(getInputs())); // } // }); // } // } // // Path: src/main/java/org/graylog/collector/outputs/OutputService.java // public abstract class OutputService extends AbstractService implements Output { // }
import javax.inject.Inject; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.util.concurrent.Service; import com.typesafe.config.Config; import com.typesafe.config.ConfigException; import com.typesafe.config.ConfigObject; import com.typesafe.config.ConfigValue; import org.graylog.collector.inputs.Input; import org.graylog.collector.inputs.InputConfiguration; import org.graylog.collector.inputs.InputService; import org.graylog.collector.outputs.Output; import org.graylog.collector.outputs.OutputConfiguration; import org.graylog.collector.outputs.OutputService;
/** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.config; public class ConfigurationRegistry { private final Set<Service> services = Sets.newHashSet(); private final Set<Input> inputs = Sets.newHashSet(); private final Set<Output> outputs = Sets.newHashSet(); private final Map<String, InputConfiguration.Factory<? extends InputConfiguration>> inputConfigFactories;
// Path: src/main/java/org/graylog/collector/inputs/InputService.java // public abstract class InputService extends AbstractService implements Input { // } // // Path: src/main/java/org/graylog/collector/outputs/Output.java // public interface Output { // String getId(); // // Set<String> getInputs(); // // void write(Message message); // // interface Factory<T extends Output, C extends Configuration> { // T create(C configuration); // } // } // // Path: src/main/java/org/graylog/collector/outputs/OutputConfiguration.java // public abstract class OutputConfiguration implements Configuration { // public interface Factory<C extends OutputConfiguration> { // C create(String id, Config config); // } // // @NotBlank // private final String id; // // @NotNull // private Set<String> inputs = Sets.newHashSet(); // // public OutputConfiguration(String id, Config config) { // this.id = id; // // if (config.hasPath("inputs")) { // this.inputs = Sets.newHashSet(Splitter.on(",").omitEmptyStrings().trimResults().split(config.getString("inputs"))); // } // } // // public abstract OutputService createOutput(); // // @Override // public String getId() { // return id; // } // // public Set<String> getInputs() { // return inputs; // } // // @Override // public Map<String, String> toStringValues() { // return Collections.unmodifiableMap(new HashMap<String, String>() { // { // put("id", getId()); // put("inputs", Joiner.on(",").join(getInputs())); // } // }); // } // } // // Path: src/main/java/org/graylog/collector/outputs/OutputService.java // public abstract class OutputService extends AbstractService implements Output { // } // Path: src/main/java/org/graylog/collector/config/ConfigurationRegistry.java import javax.inject.Inject; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.util.concurrent.Service; import com.typesafe.config.Config; import com.typesafe.config.ConfigException; import com.typesafe.config.ConfigObject; import com.typesafe.config.ConfigValue; import org.graylog.collector.inputs.Input; import org.graylog.collector.inputs.InputConfiguration; import org.graylog.collector.inputs.InputService; import org.graylog.collector.outputs.Output; import org.graylog.collector.outputs.OutputConfiguration; import org.graylog.collector.outputs.OutputService; /** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.config; public class ConfigurationRegistry { private final Set<Service> services = Sets.newHashSet(); private final Set<Input> inputs = Sets.newHashSet(); private final Set<Output> outputs = Sets.newHashSet(); private final Map<String, InputConfiguration.Factory<? extends InputConfiguration>> inputConfigFactories;
private final Map<String, OutputConfiguration.Factory<? extends OutputConfiguration>> outputConfigFactories;
DevOpsStudio/Re-Collector
src/main/java/org/graylog/collector/config/ConfigurationRegistry.java
// Path: src/main/java/org/graylog/collector/inputs/InputService.java // public abstract class InputService extends AbstractService implements Input { // } // // Path: src/main/java/org/graylog/collector/outputs/Output.java // public interface Output { // String getId(); // // Set<String> getInputs(); // // void write(Message message); // // interface Factory<T extends Output, C extends Configuration> { // T create(C configuration); // } // } // // Path: src/main/java/org/graylog/collector/outputs/OutputConfiguration.java // public abstract class OutputConfiguration implements Configuration { // public interface Factory<C extends OutputConfiguration> { // C create(String id, Config config); // } // // @NotBlank // private final String id; // // @NotNull // private Set<String> inputs = Sets.newHashSet(); // // public OutputConfiguration(String id, Config config) { // this.id = id; // // if (config.hasPath("inputs")) { // this.inputs = Sets.newHashSet(Splitter.on(",").omitEmptyStrings().trimResults().split(config.getString("inputs"))); // } // } // // public abstract OutputService createOutput(); // // @Override // public String getId() { // return id; // } // // public Set<String> getInputs() { // return inputs; // } // // @Override // public Map<String, String> toStringValues() { // return Collections.unmodifiableMap(new HashMap<String, String>() { // { // put("id", getId()); // put("inputs", Joiner.on(",").join(getInputs())); // } // }); // } // } // // Path: src/main/java/org/graylog/collector/outputs/OutputService.java // public abstract class OutputService extends AbstractService implements Output { // }
import javax.inject.Inject; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.util.concurrent.Service; import com.typesafe.config.Config; import com.typesafe.config.ConfigException; import com.typesafe.config.ConfigObject; import com.typesafe.config.ConfigValue; import org.graylog.collector.inputs.Input; import org.graylog.collector.inputs.InputConfiguration; import org.graylog.collector.inputs.InputService; import org.graylog.collector.outputs.Output; import org.graylog.collector.outputs.OutputConfiguration; import org.graylog.collector.outputs.OutputService;
Map<String, OutputConfiguration.Factory<? extends OutputConfiguration>> outputConfigs) { this.inputConfigFactories = inputConfigs; this.outputConfigFactories = outputConfigs; this.validator = new ConfigurationValidator(); try { processConfig(config); } catch (ConfigException e) { errors.add(new ConfigurationError(e.getMessage())); } } private void processConfig(Config config) { final Config inputs = config.getConfig("inputs"); final Config outputs = config.getConfig("outputs"); buildInputs(inputs); buildOutputs(outputs); errors.addAll(validator.getErrors()); } private void buildInputs(final Config inputConfigs) { final Map<String, InputConfiguration.Factory<? extends InputConfiguration>> factories = ConfigurationRegistry.this.inputConfigFactories; dispatchConfig(inputConfigs, (type, id, config) -> { if (factories.containsKey(type)) { final InputConfiguration cfg = factories.get(type).create(id, config); if (validator.isValid(cfg)) {
// Path: src/main/java/org/graylog/collector/inputs/InputService.java // public abstract class InputService extends AbstractService implements Input { // } // // Path: src/main/java/org/graylog/collector/outputs/Output.java // public interface Output { // String getId(); // // Set<String> getInputs(); // // void write(Message message); // // interface Factory<T extends Output, C extends Configuration> { // T create(C configuration); // } // } // // Path: src/main/java/org/graylog/collector/outputs/OutputConfiguration.java // public abstract class OutputConfiguration implements Configuration { // public interface Factory<C extends OutputConfiguration> { // C create(String id, Config config); // } // // @NotBlank // private final String id; // // @NotNull // private Set<String> inputs = Sets.newHashSet(); // // public OutputConfiguration(String id, Config config) { // this.id = id; // // if (config.hasPath("inputs")) { // this.inputs = Sets.newHashSet(Splitter.on(",").omitEmptyStrings().trimResults().split(config.getString("inputs"))); // } // } // // public abstract OutputService createOutput(); // // @Override // public String getId() { // return id; // } // // public Set<String> getInputs() { // return inputs; // } // // @Override // public Map<String, String> toStringValues() { // return Collections.unmodifiableMap(new HashMap<String, String>() { // { // put("id", getId()); // put("inputs", Joiner.on(",").join(getInputs())); // } // }); // } // } // // Path: src/main/java/org/graylog/collector/outputs/OutputService.java // public abstract class OutputService extends AbstractService implements Output { // } // Path: src/main/java/org/graylog/collector/config/ConfigurationRegistry.java import javax.inject.Inject; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.util.concurrent.Service; import com.typesafe.config.Config; import com.typesafe.config.ConfigException; import com.typesafe.config.ConfigObject; import com.typesafe.config.ConfigValue; import org.graylog.collector.inputs.Input; import org.graylog.collector.inputs.InputConfiguration; import org.graylog.collector.inputs.InputService; import org.graylog.collector.outputs.Output; import org.graylog.collector.outputs.OutputConfiguration; import org.graylog.collector.outputs.OutputService; Map<String, OutputConfiguration.Factory<? extends OutputConfiguration>> outputConfigs) { this.inputConfigFactories = inputConfigs; this.outputConfigFactories = outputConfigs; this.validator = new ConfigurationValidator(); try { processConfig(config); } catch (ConfigException e) { errors.add(new ConfigurationError(e.getMessage())); } } private void processConfig(Config config) { final Config inputs = config.getConfig("inputs"); final Config outputs = config.getConfig("outputs"); buildInputs(inputs); buildOutputs(outputs); errors.addAll(validator.getErrors()); } private void buildInputs(final Config inputConfigs) { final Map<String, InputConfiguration.Factory<? extends InputConfiguration>> factories = ConfigurationRegistry.this.inputConfigFactories; dispatchConfig(inputConfigs, (type, id, config) -> { if (factories.containsKey(type)) { final InputConfiguration cfg = factories.get(type).create(id, config); if (validator.isValid(cfg)) {
final InputService input = cfg.createInput();
DevOpsStudio/Re-Collector
src/main/java/org/graylog/collector/config/ConfigurationRegistry.java
// Path: src/main/java/org/graylog/collector/inputs/InputService.java // public abstract class InputService extends AbstractService implements Input { // } // // Path: src/main/java/org/graylog/collector/outputs/Output.java // public interface Output { // String getId(); // // Set<String> getInputs(); // // void write(Message message); // // interface Factory<T extends Output, C extends Configuration> { // T create(C configuration); // } // } // // Path: src/main/java/org/graylog/collector/outputs/OutputConfiguration.java // public abstract class OutputConfiguration implements Configuration { // public interface Factory<C extends OutputConfiguration> { // C create(String id, Config config); // } // // @NotBlank // private final String id; // // @NotNull // private Set<String> inputs = Sets.newHashSet(); // // public OutputConfiguration(String id, Config config) { // this.id = id; // // if (config.hasPath("inputs")) { // this.inputs = Sets.newHashSet(Splitter.on(",").omitEmptyStrings().trimResults().split(config.getString("inputs"))); // } // } // // public abstract OutputService createOutput(); // // @Override // public String getId() { // return id; // } // // public Set<String> getInputs() { // return inputs; // } // // @Override // public Map<String, String> toStringValues() { // return Collections.unmodifiableMap(new HashMap<String, String>() { // { // put("id", getId()); // put("inputs", Joiner.on(",").join(getInputs())); // } // }); // } // } // // Path: src/main/java/org/graylog/collector/outputs/OutputService.java // public abstract class OutputService extends AbstractService implements Output { // }
import javax.inject.Inject; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.util.concurrent.Service; import com.typesafe.config.Config; import com.typesafe.config.ConfigException; import com.typesafe.config.ConfigObject; import com.typesafe.config.ConfigValue; import org.graylog.collector.inputs.Input; import org.graylog.collector.inputs.InputConfiguration; import org.graylog.collector.inputs.InputService; import org.graylog.collector.outputs.Output; import org.graylog.collector.outputs.OutputConfiguration; import org.graylog.collector.outputs.OutputService;
} private void buildInputs(final Config inputConfigs) { final Map<String, InputConfiguration.Factory<? extends InputConfiguration>> factories = ConfigurationRegistry.this.inputConfigFactories; dispatchConfig(inputConfigs, (type, id, config) -> { if (factories.containsKey(type)) { final InputConfiguration cfg = factories.get(type).create(id, config); if (validator.isValid(cfg)) { final InputService input = cfg.createInput(); services.add(input); inputs.add(input); } } else { errors.add(new ConfigurationError("Unknown input type \"" + type + "\" for " + id)); } }); } private void buildOutputs(Config outputConfigs) { final Map<String, OutputConfiguration.Factory<? extends OutputConfiguration>> factories = ConfigurationRegistry.this.outputConfigFactories; dispatchConfig(outputConfigs, new ConfigCallback() { @Override public void call(String type, String id, Config config) { if (factories.containsKey(type)) { final OutputConfiguration cfg = factories.get(type).create(id, config); if (validator.isValid(cfg)) {
// Path: src/main/java/org/graylog/collector/inputs/InputService.java // public abstract class InputService extends AbstractService implements Input { // } // // Path: src/main/java/org/graylog/collector/outputs/Output.java // public interface Output { // String getId(); // // Set<String> getInputs(); // // void write(Message message); // // interface Factory<T extends Output, C extends Configuration> { // T create(C configuration); // } // } // // Path: src/main/java/org/graylog/collector/outputs/OutputConfiguration.java // public abstract class OutputConfiguration implements Configuration { // public interface Factory<C extends OutputConfiguration> { // C create(String id, Config config); // } // // @NotBlank // private final String id; // // @NotNull // private Set<String> inputs = Sets.newHashSet(); // // public OutputConfiguration(String id, Config config) { // this.id = id; // // if (config.hasPath("inputs")) { // this.inputs = Sets.newHashSet(Splitter.on(",").omitEmptyStrings().trimResults().split(config.getString("inputs"))); // } // } // // public abstract OutputService createOutput(); // // @Override // public String getId() { // return id; // } // // public Set<String> getInputs() { // return inputs; // } // // @Override // public Map<String, String> toStringValues() { // return Collections.unmodifiableMap(new HashMap<String, String>() { // { // put("id", getId()); // put("inputs", Joiner.on(",").join(getInputs())); // } // }); // } // } // // Path: src/main/java/org/graylog/collector/outputs/OutputService.java // public abstract class OutputService extends AbstractService implements Output { // } // Path: src/main/java/org/graylog/collector/config/ConfigurationRegistry.java import javax.inject.Inject; import java.util.List; import java.util.Map; import java.util.Set; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.util.concurrent.Service; import com.typesafe.config.Config; import com.typesafe.config.ConfigException; import com.typesafe.config.ConfigObject; import com.typesafe.config.ConfigValue; import org.graylog.collector.inputs.Input; import org.graylog.collector.inputs.InputConfiguration; import org.graylog.collector.inputs.InputService; import org.graylog.collector.outputs.Output; import org.graylog.collector.outputs.OutputConfiguration; import org.graylog.collector.outputs.OutputService; } private void buildInputs(final Config inputConfigs) { final Map<String, InputConfiguration.Factory<? extends InputConfiguration>> factories = ConfigurationRegistry.this.inputConfigFactories; dispatchConfig(inputConfigs, (type, id, config) -> { if (factories.containsKey(type)) { final InputConfiguration cfg = factories.get(type).create(id, config); if (validator.isValid(cfg)) { final InputService input = cfg.createInput(); services.add(input); inputs.add(input); } } else { errors.add(new ConfigurationError("Unknown input type \"" + type + "\" for " + id)); } }); } private void buildOutputs(Config outputConfigs) { final Map<String, OutputConfiguration.Factory<? extends OutputConfiguration>> factories = ConfigurationRegistry.this.outputConfigFactories; dispatchConfig(outputConfigs, new ConfigCallback() { @Override public void call(String type, String id, Config config) { if (factories.containsKey(type)) { final OutputConfiguration cfg = factories.get(type).create(id, config); if (validator.isValid(cfg)) {
final OutputService output = cfg.createOutput();
DevOpsStudio/Re-Collector
src/main/java/org/graylog/collector/services/CollectorServiceManager.java
// Path: src/main/java/org/graylog/collector/config/ConfigurationRegistry.java // public class ConfigurationRegistry { // private final Set<Service> services = Sets.newHashSet(); // private final Set<Input> inputs = Sets.newHashSet(); // private final Set<Output> outputs = Sets.newHashSet(); // // private final Map<String, InputConfiguration.Factory<? extends InputConfiguration>> inputConfigFactories; // private final Map<String, OutputConfiguration.Factory<? extends OutputConfiguration>> outputConfigFactories; // // private final List<ConfigurationError> errors = Lists.newArrayList(); // private final ConfigurationValidator validator; // // @Inject // public ConfigurationRegistry(Config config, // Map<String, InputConfiguration.Factory<? extends InputConfiguration>> inputConfigs, // Map<String, OutputConfiguration.Factory<? extends OutputConfiguration>> outputConfigs) { // this.inputConfigFactories = inputConfigs; // this.outputConfigFactories = outputConfigs; // this.validator = new ConfigurationValidator(); // // try { // processConfig(config); // } catch (ConfigException e) { // errors.add(new ConfigurationError(e.getMessage())); // } // } // // private void processConfig(Config config) { // final Config inputs = config.getConfig("inputs"); // final Config outputs = config.getConfig("outputs"); // // buildInputs(inputs); // buildOutputs(outputs); // // errors.addAll(validator.getErrors()); // } // // private void buildInputs(final Config inputConfigs) { // final Map<String, InputConfiguration.Factory<? extends InputConfiguration>> factories = ConfigurationRegistry.this.inputConfigFactories; // // dispatchConfig(inputConfigs, (type, id, config) -> { // if (factories.containsKey(type)) { // final InputConfiguration cfg = factories.get(type).create(id, config); // // if (validator.isValid(cfg)) { // final InputService input = cfg.createInput(); // services.add(input); // inputs.add(input); // } // } else { // errors.add(new ConfigurationError("Unknown input type \"" + type + "\" for " + id)); // } // }); // } // // private void buildOutputs(Config outputConfigs) { // final Map<String, OutputConfiguration.Factory<? extends OutputConfiguration>> factories = ConfigurationRegistry.this.outputConfigFactories; // // dispatchConfig(outputConfigs, new ConfigCallback() { // @Override // public void call(String type, String id, Config config) { // if (factories.containsKey(type)) { // final OutputConfiguration cfg = factories.get(type).create(id, config); // // if (validator.isValid(cfg)) { // final OutputService output = cfg.createOutput(); // services.add(output); // outputs.add(output); // } // } else { // errors.add(new ConfigurationError("Unknown output type \"" + type + "\" for " + id)); // } // } // }); // } // // private void dispatchConfig(Config config, ConfigCallback callback) { // for (Map.Entry<String, ConfigValue> entry : config.root().entrySet()) { // final String id = entry.getKey(); // // try { // final Config entryConfig = ((ConfigObject) entry.getValue()).toConfig(); // final String type = entryConfig.getString("type"); // // if (Strings.isNullOrEmpty(type)) { // errors.add(new ConfigurationError("Missing type field for " + id + " (" + entryConfig + ")")); // continue; // } // // callback.call(type, id, entryConfig); // } catch (ConfigException e) { // errors.add(new ConfigurationError("[" + id + "] " + e.getMessage())); // } // } // } // // public boolean isValid() { // return errors.isEmpty(); // } // // public List<ConfigurationError> getErrors() { // return errors; // } // // public Set<Service> getServices() { // return services; // } // // public Set<Input> getInputs() { // return inputs; // } // // public Set<Output> getOutputs() { // return outputs; // } // // private interface ConfigCallback { // void call(String type, String id, Config config); // } // }
import com.google.common.collect.ImmutableMultimap; import com.google.common.util.concurrent.Service; import com.google.common.util.concurrent.ServiceManager; import org.graylog.collector.config.ConfigurationRegistry; import javax.inject.Inject;
/** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.services; public class CollectorServiceManager { private final ServiceManager serviceManager;
// Path: src/main/java/org/graylog/collector/config/ConfigurationRegistry.java // public class ConfigurationRegistry { // private final Set<Service> services = Sets.newHashSet(); // private final Set<Input> inputs = Sets.newHashSet(); // private final Set<Output> outputs = Sets.newHashSet(); // // private final Map<String, InputConfiguration.Factory<? extends InputConfiguration>> inputConfigFactories; // private final Map<String, OutputConfiguration.Factory<? extends OutputConfiguration>> outputConfigFactories; // // private final List<ConfigurationError> errors = Lists.newArrayList(); // private final ConfigurationValidator validator; // // @Inject // public ConfigurationRegistry(Config config, // Map<String, InputConfiguration.Factory<? extends InputConfiguration>> inputConfigs, // Map<String, OutputConfiguration.Factory<? extends OutputConfiguration>> outputConfigs) { // this.inputConfigFactories = inputConfigs; // this.outputConfigFactories = outputConfigs; // this.validator = new ConfigurationValidator(); // // try { // processConfig(config); // } catch (ConfigException e) { // errors.add(new ConfigurationError(e.getMessage())); // } // } // // private void processConfig(Config config) { // final Config inputs = config.getConfig("inputs"); // final Config outputs = config.getConfig("outputs"); // // buildInputs(inputs); // buildOutputs(outputs); // // errors.addAll(validator.getErrors()); // } // // private void buildInputs(final Config inputConfigs) { // final Map<String, InputConfiguration.Factory<? extends InputConfiguration>> factories = ConfigurationRegistry.this.inputConfigFactories; // // dispatchConfig(inputConfigs, (type, id, config) -> { // if (factories.containsKey(type)) { // final InputConfiguration cfg = factories.get(type).create(id, config); // // if (validator.isValid(cfg)) { // final InputService input = cfg.createInput(); // services.add(input); // inputs.add(input); // } // } else { // errors.add(new ConfigurationError("Unknown input type \"" + type + "\" for " + id)); // } // }); // } // // private void buildOutputs(Config outputConfigs) { // final Map<String, OutputConfiguration.Factory<? extends OutputConfiguration>> factories = ConfigurationRegistry.this.outputConfigFactories; // // dispatchConfig(outputConfigs, new ConfigCallback() { // @Override // public void call(String type, String id, Config config) { // if (factories.containsKey(type)) { // final OutputConfiguration cfg = factories.get(type).create(id, config); // // if (validator.isValid(cfg)) { // final OutputService output = cfg.createOutput(); // services.add(output); // outputs.add(output); // } // } else { // errors.add(new ConfigurationError("Unknown output type \"" + type + "\" for " + id)); // } // } // }); // } // // private void dispatchConfig(Config config, ConfigCallback callback) { // for (Map.Entry<String, ConfigValue> entry : config.root().entrySet()) { // final String id = entry.getKey(); // // try { // final Config entryConfig = ((ConfigObject) entry.getValue()).toConfig(); // final String type = entryConfig.getString("type"); // // if (Strings.isNullOrEmpty(type)) { // errors.add(new ConfigurationError("Missing type field for " + id + " (" + entryConfig + ")")); // continue; // } // // callback.call(type, id, entryConfig); // } catch (ConfigException e) { // errors.add(new ConfigurationError("[" + id + "] " + e.getMessage())); // } // } // } // // public boolean isValid() { // return errors.isEmpty(); // } // // public List<ConfigurationError> getErrors() { // return errors; // } // // public Set<Service> getServices() { // return services; // } // // public Set<Input> getInputs() { // return inputs; // } // // public Set<Output> getOutputs() { // return outputs; // } // // private interface ConfigCallback { // void call(String type, String id, Config config); // } // } // Path: src/main/java/org/graylog/collector/services/CollectorServiceManager.java import com.google.common.collect.ImmutableMultimap; import com.google.common.util.concurrent.Service; import com.google.common.util.concurrent.ServiceManager; import org.graylog.collector.config.ConfigurationRegistry; import javax.inject.Inject; /** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.services; public class CollectorServiceManager { private final ServiceManager serviceManager;
private final ConfigurationRegistry configuration;
DevOpsStudio/Re-Collector
src/main/java/org/graylog/collector/services/ServiceManagerProvider.java
// Path: src/main/java/org/graylog/collector/config/ConfigurationRegistry.java // public class ConfigurationRegistry { // private final Set<Service> services = Sets.newHashSet(); // private final Set<Input> inputs = Sets.newHashSet(); // private final Set<Output> outputs = Sets.newHashSet(); // // private final Map<String, InputConfiguration.Factory<? extends InputConfiguration>> inputConfigFactories; // private final Map<String, OutputConfiguration.Factory<? extends OutputConfiguration>> outputConfigFactories; // // private final List<ConfigurationError> errors = Lists.newArrayList(); // private final ConfigurationValidator validator; // // @Inject // public ConfigurationRegistry(Config config, // Map<String, InputConfiguration.Factory<? extends InputConfiguration>> inputConfigs, // Map<String, OutputConfiguration.Factory<? extends OutputConfiguration>> outputConfigs) { // this.inputConfigFactories = inputConfigs; // this.outputConfigFactories = outputConfigs; // this.validator = new ConfigurationValidator(); // // try { // processConfig(config); // } catch (ConfigException e) { // errors.add(new ConfigurationError(e.getMessage())); // } // } // // private void processConfig(Config config) { // final Config inputs = config.getConfig("inputs"); // final Config outputs = config.getConfig("outputs"); // // buildInputs(inputs); // buildOutputs(outputs); // // errors.addAll(validator.getErrors()); // } // // private void buildInputs(final Config inputConfigs) { // final Map<String, InputConfiguration.Factory<? extends InputConfiguration>> factories = ConfigurationRegistry.this.inputConfigFactories; // // dispatchConfig(inputConfigs, (type, id, config) -> { // if (factories.containsKey(type)) { // final InputConfiguration cfg = factories.get(type).create(id, config); // // if (validator.isValid(cfg)) { // final InputService input = cfg.createInput(); // services.add(input); // inputs.add(input); // } // } else { // errors.add(new ConfigurationError("Unknown input type \"" + type + "\" for " + id)); // } // }); // } // // private void buildOutputs(Config outputConfigs) { // final Map<String, OutputConfiguration.Factory<? extends OutputConfiguration>> factories = ConfigurationRegistry.this.outputConfigFactories; // // dispatchConfig(outputConfigs, new ConfigCallback() { // @Override // public void call(String type, String id, Config config) { // if (factories.containsKey(type)) { // final OutputConfiguration cfg = factories.get(type).create(id, config); // // if (validator.isValid(cfg)) { // final OutputService output = cfg.createOutput(); // services.add(output); // outputs.add(output); // } // } else { // errors.add(new ConfigurationError("Unknown output type \"" + type + "\" for " + id)); // } // } // }); // } // // private void dispatchConfig(Config config, ConfigCallback callback) { // for (Map.Entry<String, ConfigValue> entry : config.root().entrySet()) { // final String id = entry.getKey(); // // try { // final Config entryConfig = ((ConfigObject) entry.getValue()).toConfig(); // final String type = entryConfig.getString("type"); // // if (Strings.isNullOrEmpty(type)) { // errors.add(new ConfigurationError("Missing type field for " + id + " (" + entryConfig + ")")); // continue; // } // // callback.call(type, id, entryConfig); // } catch (ConfigException e) { // errors.add(new ConfigurationError("[" + id + "] " + e.getMessage())); // } // } // } // // public boolean isValid() { // return errors.isEmpty(); // } // // public List<ConfigurationError> getErrors() { // return errors; // } // // public Set<Service> getServices() { // return services; // } // // public Set<Input> getInputs() { // return inputs; // } // // public Set<Output> getOutputs() { // return outputs; // } // // private interface ConfigCallback { // void call(String type, String id, Config config); // } // }
import com.google.common.collect.ImmutableSet; import com.google.common.util.concurrent.Service; import com.google.common.util.concurrent.ServiceManager; import com.google.inject.Provider; import org.graylog.collector.config.ConfigurationRegistry; import javax.inject.Inject; import java.util.Set;
/** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.services; public class ServiceManagerProvider implements Provider<ServiceManager> { private final Set<Service> services;
// Path: src/main/java/org/graylog/collector/config/ConfigurationRegistry.java // public class ConfigurationRegistry { // private final Set<Service> services = Sets.newHashSet(); // private final Set<Input> inputs = Sets.newHashSet(); // private final Set<Output> outputs = Sets.newHashSet(); // // private final Map<String, InputConfiguration.Factory<? extends InputConfiguration>> inputConfigFactories; // private final Map<String, OutputConfiguration.Factory<? extends OutputConfiguration>> outputConfigFactories; // // private final List<ConfigurationError> errors = Lists.newArrayList(); // private final ConfigurationValidator validator; // // @Inject // public ConfigurationRegistry(Config config, // Map<String, InputConfiguration.Factory<? extends InputConfiguration>> inputConfigs, // Map<String, OutputConfiguration.Factory<? extends OutputConfiguration>> outputConfigs) { // this.inputConfigFactories = inputConfigs; // this.outputConfigFactories = outputConfigs; // this.validator = new ConfigurationValidator(); // // try { // processConfig(config); // } catch (ConfigException e) { // errors.add(new ConfigurationError(e.getMessage())); // } // } // // private void processConfig(Config config) { // final Config inputs = config.getConfig("inputs"); // final Config outputs = config.getConfig("outputs"); // // buildInputs(inputs); // buildOutputs(outputs); // // errors.addAll(validator.getErrors()); // } // // private void buildInputs(final Config inputConfigs) { // final Map<String, InputConfiguration.Factory<? extends InputConfiguration>> factories = ConfigurationRegistry.this.inputConfigFactories; // // dispatchConfig(inputConfigs, (type, id, config) -> { // if (factories.containsKey(type)) { // final InputConfiguration cfg = factories.get(type).create(id, config); // // if (validator.isValid(cfg)) { // final InputService input = cfg.createInput(); // services.add(input); // inputs.add(input); // } // } else { // errors.add(new ConfigurationError("Unknown input type \"" + type + "\" for " + id)); // } // }); // } // // private void buildOutputs(Config outputConfigs) { // final Map<String, OutputConfiguration.Factory<? extends OutputConfiguration>> factories = ConfigurationRegistry.this.outputConfigFactories; // // dispatchConfig(outputConfigs, new ConfigCallback() { // @Override // public void call(String type, String id, Config config) { // if (factories.containsKey(type)) { // final OutputConfiguration cfg = factories.get(type).create(id, config); // // if (validator.isValid(cfg)) { // final OutputService output = cfg.createOutput(); // services.add(output); // outputs.add(output); // } // } else { // errors.add(new ConfigurationError("Unknown output type \"" + type + "\" for " + id)); // } // } // }); // } // // private void dispatchConfig(Config config, ConfigCallback callback) { // for (Map.Entry<String, ConfigValue> entry : config.root().entrySet()) { // final String id = entry.getKey(); // // try { // final Config entryConfig = ((ConfigObject) entry.getValue()).toConfig(); // final String type = entryConfig.getString("type"); // // if (Strings.isNullOrEmpty(type)) { // errors.add(new ConfigurationError("Missing type field for " + id + " (" + entryConfig + ")")); // continue; // } // // callback.call(type, id, entryConfig); // } catch (ConfigException e) { // errors.add(new ConfigurationError("[" + id + "] " + e.getMessage())); // } // } // } // // public boolean isValid() { // return errors.isEmpty(); // } // // public List<ConfigurationError> getErrors() { // return errors; // } // // public Set<Service> getServices() { // return services; // } // // public Set<Input> getInputs() { // return inputs; // } // // public Set<Output> getOutputs() { // return outputs; // } // // private interface ConfigCallback { // void call(String type, String id, Config config); // } // } // Path: src/main/java/org/graylog/collector/services/ServiceManagerProvider.java import com.google.common.collect.ImmutableSet; import com.google.common.util.concurrent.Service; import com.google.common.util.concurrent.ServiceManager; import com.google.inject.Provider; import org.graylog.collector.config.ConfigurationRegistry; import javax.inject.Inject; import java.util.Set; /** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.services; public class ServiceManagerProvider implements Provider<ServiceManager> { private final Set<Service> services;
private final ConfigurationRegistry configuration;
DevOpsStudio/Re-Collector
src/main/java/org/graylog/collector/file/ChunkProcessor.java
// Path: src/main/java/org/graylog/collector/MessageBuilder.java // public class MessageBuilder { // private final long ownerId = Thread.currentThread().getId(); // // private String message; // private String source; // private DateTime timestamp; // private Message.Level level; // private String input; // private Set<String> outputs; // private MessageFields fields = new MessageFields(); // // public MessageBuilder() { // } // // private MessageBuilder(String message, String source, DateTime timestamp, Message.Level level, String input, Set<String> outputs, MessageFields fields) { // this.message = message; // this.source = source; // this.timestamp = timestamp; // this.level = level; // this.input = input; // this.outputs = outputs; // this.fields = fields; // } // // public MessageBuilder message(String message) { // checkOwnership(); // this.message = message; // return this; // } // // public MessageBuilder source(String source) { // checkOwnership(); // this.source = source; // return this; // } // // public MessageBuilder timestamp(DateTime timestamp) { // checkOwnership(); // this.timestamp = timestamp; // return this; // } // // public MessageBuilder level(Message.Level level) { // checkOwnership(); // this.level = level; // return this; // } // // public MessageBuilder input(String input) { // checkOwnership(); // this.input = input; // return this; // } // // public MessageBuilder outputs(Set<String> outputs) { // checkOwnership(); // if (outputs == null) { // this.outputs = null; // } else { // this.outputs = ImmutableSet.copyOf(outputs); // } // return this; // } // // public MessageBuilder fields(MessageFields fields) { // checkOwnership(); // this.fields = fields; // return this; // } // // public MessageBuilder addField(String key, int value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, long value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, boolean value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, String value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public Message build() { // checkNotNull(message, "Message should not be null!"); // checkNotNull(source, "Message source should not be null!"); // checkNotNull(timestamp, "Message timestamp should not be null!"); // checkNotNull(input, "Message input should not be null!"); // checkNotNull(outputs, "Message outputs should not be null!"); // // if (fields == null) { // return new Message(message, source, timestamp, level, input, outputs); // } else { // return new Message(message, source, timestamp, level, input, outputs, fields); // } // } // // public MessageBuilder copy() { // return new MessageBuilder(message, source, timestamp, level, input, outputs, fields.copy()); // } // // private void checkOwnership() { // final long currentId = Thread.currentThread().getId(); // checkState(ownerId == currentId, "Modification only allowed by owning thread. (owner=" + ownerId + " current=" + currentId + ")"); // } // } // // Path: src/main/java/org/graylog/collector/buffer/Buffer.java // public interface Buffer { // void insert(Message message); // // Message remove(); // } // // Path: src/main/java/org/graylog/collector/file/splitters/ContentSplitter.java // public abstract class ContentSplitter { // // public abstract Iterable<String> split(ByteBuf buffer, Charset charset, boolean includeRemainingData); // // public Iterable<String> split(ByteBuf buffer, Charset charset) { // return split(buffer, charset, false); // } // // public Iterable<String> splitRemaining(ByteBuf buffer, Charset charset) { // return split(buffer, charset, true); // } // }
import java.util.concurrent.TimeUnit; import com.google.common.util.concurrent.AbstractExecutionThreadService; import io.netty.buffer.ByteBuf; import org.graylog.collector.Message; import org.graylog.collector.MessageBuilder; import org.graylog.collector.buffer.Buffer; import org.graylog.collector.file.splitters.ContentSplitter; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.concurrent.BlockingQueue;
/** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.file; public class ChunkProcessor extends AbstractExecutionThreadService { private static final Logger log = LoggerFactory.getLogger(ChunkProcessor.class);
// Path: src/main/java/org/graylog/collector/MessageBuilder.java // public class MessageBuilder { // private final long ownerId = Thread.currentThread().getId(); // // private String message; // private String source; // private DateTime timestamp; // private Message.Level level; // private String input; // private Set<String> outputs; // private MessageFields fields = new MessageFields(); // // public MessageBuilder() { // } // // private MessageBuilder(String message, String source, DateTime timestamp, Message.Level level, String input, Set<String> outputs, MessageFields fields) { // this.message = message; // this.source = source; // this.timestamp = timestamp; // this.level = level; // this.input = input; // this.outputs = outputs; // this.fields = fields; // } // // public MessageBuilder message(String message) { // checkOwnership(); // this.message = message; // return this; // } // // public MessageBuilder source(String source) { // checkOwnership(); // this.source = source; // return this; // } // // public MessageBuilder timestamp(DateTime timestamp) { // checkOwnership(); // this.timestamp = timestamp; // return this; // } // // public MessageBuilder level(Message.Level level) { // checkOwnership(); // this.level = level; // return this; // } // // public MessageBuilder input(String input) { // checkOwnership(); // this.input = input; // return this; // } // // public MessageBuilder outputs(Set<String> outputs) { // checkOwnership(); // if (outputs == null) { // this.outputs = null; // } else { // this.outputs = ImmutableSet.copyOf(outputs); // } // return this; // } // // public MessageBuilder fields(MessageFields fields) { // checkOwnership(); // this.fields = fields; // return this; // } // // public MessageBuilder addField(String key, int value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, long value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, boolean value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, String value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public Message build() { // checkNotNull(message, "Message should not be null!"); // checkNotNull(source, "Message source should not be null!"); // checkNotNull(timestamp, "Message timestamp should not be null!"); // checkNotNull(input, "Message input should not be null!"); // checkNotNull(outputs, "Message outputs should not be null!"); // // if (fields == null) { // return new Message(message, source, timestamp, level, input, outputs); // } else { // return new Message(message, source, timestamp, level, input, outputs, fields); // } // } // // public MessageBuilder copy() { // return new MessageBuilder(message, source, timestamp, level, input, outputs, fields.copy()); // } // // private void checkOwnership() { // final long currentId = Thread.currentThread().getId(); // checkState(ownerId == currentId, "Modification only allowed by owning thread. (owner=" + ownerId + " current=" + currentId + ")"); // } // } // // Path: src/main/java/org/graylog/collector/buffer/Buffer.java // public interface Buffer { // void insert(Message message); // // Message remove(); // } // // Path: src/main/java/org/graylog/collector/file/splitters/ContentSplitter.java // public abstract class ContentSplitter { // // public abstract Iterable<String> split(ByteBuf buffer, Charset charset, boolean includeRemainingData); // // public Iterable<String> split(ByteBuf buffer, Charset charset) { // return split(buffer, charset, false); // } // // public Iterable<String> splitRemaining(ByteBuf buffer, Charset charset) { // return split(buffer, charset, true); // } // } // Path: src/main/java/org/graylog/collector/file/ChunkProcessor.java import java.util.concurrent.TimeUnit; import com.google.common.util.concurrent.AbstractExecutionThreadService; import io.netty.buffer.ByteBuf; import org.graylog.collector.Message; import org.graylog.collector.MessageBuilder; import org.graylog.collector.buffer.Buffer; import org.graylog.collector.file.splitters.ContentSplitter; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.concurrent.BlockingQueue; /** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.file; public class ChunkProcessor extends AbstractExecutionThreadService { private static final Logger log = LoggerFactory.getLogger(ChunkProcessor.class);
private final Buffer buffer;
DevOpsStudio/Re-Collector
src/main/java/org/graylog/collector/file/ChunkProcessor.java
// Path: src/main/java/org/graylog/collector/MessageBuilder.java // public class MessageBuilder { // private final long ownerId = Thread.currentThread().getId(); // // private String message; // private String source; // private DateTime timestamp; // private Message.Level level; // private String input; // private Set<String> outputs; // private MessageFields fields = new MessageFields(); // // public MessageBuilder() { // } // // private MessageBuilder(String message, String source, DateTime timestamp, Message.Level level, String input, Set<String> outputs, MessageFields fields) { // this.message = message; // this.source = source; // this.timestamp = timestamp; // this.level = level; // this.input = input; // this.outputs = outputs; // this.fields = fields; // } // // public MessageBuilder message(String message) { // checkOwnership(); // this.message = message; // return this; // } // // public MessageBuilder source(String source) { // checkOwnership(); // this.source = source; // return this; // } // // public MessageBuilder timestamp(DateTime timestamp) { // checkOwnership(); // this.timestamp = timestamp; // return this; // } // // public MessageBuilder level(Message.Level level) { // checkOwnership(); // this.level = level; // return this; // } // // public MessageBuilder input(String input) { // checkOwnership(); // this.input = input; // return this; // } // // public MessageBuilder outputs(Set<String> outputs) { // checkOwnership(); // if (outputs == null) { // this.outputs = null; // } else { // this.outputs = ImmutableSet.copyOf(outputs); // } // return this; // } // // public MessageBuilder fields(MessageFields fields) { // checkOwnership(); // this.fields = fields; // return this; // } // // public MessageBuilder addField(String key, int value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, long value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, boolean value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, String value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public Message build() { // checkNotNull(message, "Message should not be null!"); // checkNotNull(source, "Message source should not be null!"); // checkNotNull(timestamp, "Message timestamp should not be null!"); // checkNotNull(input, "Message input should not be null!"); // checkNotNull(outputs, "Message outputs should not be null!"); // // if (fields == null) { // return new Message(message, source, timestamp, level, input, outputs); // } else { // return new Message(message, source, timestamp, level, input, outputs, fields); // } // } // // public MessageBuilder copy() { // return new MessageBuilder(message, source, timestamp, level, input, outputs, fields.copy()); // } // // private void checkOwnership() { // final long currentId = Thread.currentThread().getId(); // checkState(ownerId == currentId, "Modification only allowed by owning thread. (owner=" + ownerId + " current=" + currentId + ")"); // } // } // // Path: src/main/java/org/graylog/collector/buffer/Buffer.java // public interface Buffer { // void insert(Message message); // // Message remove(); // } // // Path: src/main/java/org/graylog/collector/file/splitters/ContentSplitter.java // public abstract class ContentSplitter { // // public abstract Iterable<String> split(ByteBuf buffer, Charset charset, boolean includeRemainingData); // // public Iterable<String> split(ByteBuf buffer, Charset charset) { // return split(buffer, charset, false); // } // // public Iterable<String> splitRemaining(ByteBuf buffer, Charset charset) { // return split(buffer, charset, true); // } // }
import java.util.concurrent.TimeUnit; import com.google.common.util.concurrent.AbstractExecutionThreadService; import io.netty.buffer.ByteBuf; import org.graylog.collector.Message; import org.graylog.collector.MessageBuilder; import org.graylog.collector.buffer.Buffer; import org.graylog.collector.file.splitters.ContentSplitter; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.concurrent.BlockingQueue;
/** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.file; public class ChunkProcessor extends AbstractExecutionThreadService { private static final Logger log = LoggerFactory.getLogger(ChunkProcessor.class); private final Buffer buffer;
// Path: src/main/java/org/graylog/collector/MessageBuilder.java // public class MessageBuilder { // private final long ownerId = Thread.currentThread().getId(); // // private String message; // private String source; // private DateTime timestamp; // private Message.Level level; // private String input; // private Set<String> outputs; // private MessageFields fields = new MessageFields(); // // public MessageBuilder() { // } // // private MessageBuilder(String message, String source, DateTime timestamp, Message.Level level, String input, Set<String> outputs, MessageFields fields) { // this.message = message; // this.source = source; // this.timestamp = timestamp; // this.level = level; // this.input = input; // this.outputs = outputs; // this.fields = fields; // } // // public MessageBuilder message(String message) { // checkOwnership(); // this.message = message; // return this; // } // // public MessageBuilder source(String source) { // checkOwnership(); // this.source = source; // return this; // } // // public MessageBuilder timestamp(DateTime timestamp) { // checkOwnership(); // this.timestamp = timestamp; // return this; // } // // public MessageBuilder level(Message.Level level) { // checkOwnership(); // this.level = level; // return this; // } // // public MessageBuilder input(String input) { // checkOwnership(); // this.input = input; // return this; // } // // public MessageBuilder outputs(Set<String> outputs) { // checkOwnership(); // if (outputs == null) { // this.outputs = null; // } else { // this.outputs = ImmutableSet.copyOf(outputs); // } // return this; // } // // public MessageBuilder fields(MessageFields fields) { // checkOwnership(); // this.fields = fields; // return this; // } // // public MessageBuilder addField(String key, int value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, long value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, boolean value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, String value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public Message build() { // checkNotNull(message, "Message should not be null!"); // checkNotNull(source, "Message source should not be null!"); // checkNotNull(timestamp, "Message timestamp should not be null!"); // checkNotNull(input, "Message input should not be null!"); // checkNotNull(outputs, "Message outputs should not be null!"); // // if (fields == null) { // return new Message(message, source, timestamp, level, input, outputs); // } else { // return new Message(message, source, timestamp, level, input, outputs, fields); // } // } // // public MessageBuilder copy() { // return new MessageBuilder(message, source, timestamp, level, input, outputs, fields.copy()); // } // // private void checkOwnership() { // final long currentId = Thread.currentThread().getId(); // checkState(ownerId == currentId, "Modification only allowed by owning thread. (owner=" + ownerId + " current=" + currentId + ")"); // } // } // // Path: src/main/java/org/graylog/collector/buffer/Buffer.java // public interface Buffer { // void insert(Message message); // // Message remove(); // } // // Path: src/main/java/org/graylog/collector/file/splitters/ContentSplitter.java // public abstract class ContentSplitter { // // public abstract Iterable<String> split(ByteBuf buffer, Charset charset, boolean includeRemainingData); // // public Iterable<String> split(ByteBuf buffer, Charset charset) { // return split(buffer, charset, false); // } // // public Iterable<String> splitRemaining(ByteBuf buffer, Charset charset) { // return split(buffer, charset, true); // } // } // Path: src/main/java/org/graylog/collector/file/ChunkProcessor.java import java.util.concurrent.TimeUnit; import com.google.common.util.concurrent.AbstractExecutionThreadService; import io.netty.buffer.ByteBuf; import org.graylog.collector.Message; import org.graylog.collector.MessageBuilder; import org.graylog.collector.buffer.Buffer; import org.graylog.collector.file.splitters.ContentSplitter; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.concurrent.BlockingQueue; /** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.file; public class ChunkProcessor extends AbstractExecutionThreadService { private static final Logger log = LoggerFactory.getLogger(ChunkProcessor.class); private final Buffer buffer;
private final MessageBuilder messageBuilder;
DevOpsStudio/Re-Collector
src/main/java/org/graylog/collector/file/ChunkProcessor.java
// Path: src/main/java/org/graylog/collector/MessageBuilder.java // public class MessageBuilder { // private final long ownerId = Thread.currentThread().getId(); // // private String message; // private String source; // private DateTime timestamp; // private Message.Level level; // private String input; // private Set<String> outputs; // private MessageFields fields = new MessageFields(); // // public MessageBuilder() { // } // // private MessageBuilder(String message, String source, DateTime timestamp, Message.Level level, String input, Set<String> outputs, MessageFields fields) { // this.message = message; // this.source = source; // this.timestamp = timestamp; // this.level = level; // this.input = input; // this.outputs = outputs; // this.fields = fields; // } // // public MessageBuilder message(String message) { // checkOwnership(); // this.message = message; // return this; // } // // public MessageBuilder source(String source) { // checkOwnership(); // this.source = source; // return this; // } // // public MessageBuilder timestamp(DateTime timestamp) { // checkOwnership(); // this.timestamp = timestamp; // return this; // } // // public MessageBuilder level(Message.Level level) { // checkOwnership(); // this.level = level; // return this; // } // // public MessageBuilder input(String input) { // checkOwnership(); // this.input = input; // return this; // } // // public MessageBuilder outputs(Set<String> outputs) { // checkOwnership(); // if (outputs == null) { // this.outputs = null; // } else { // this.outputs = ImmutableSet.copyOf(outputs); // } // return this; // } // // public MessageBuilder fields(MessageFields fields) { // checkOwnership(); // this.fields = fields; // return this; // } // // public MessageBuilder addField(String key, int value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, long value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, boolean value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, String value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public Message build() { // checkNotNull(message, "Message should not be null!"); // checkNotNull(source, "Message source should not be null!"); // checkNotNull(timestamp, "Message timestamp should not be null!"); // checkNotNull(input, "Message input should not be null!"); // checkNotNull(outputs, "Message outputs should not be null!"); // // if (fields == null) { // return new Message(message, source, timestamp, level, input, outputs); // } else { // return new Message(message, source, timestamp, level, input, outputs, fields); // } // } // // public MessageBuilder copy() { // return new MessageBuilder(message, source, timestamp, level, input, outputs, fields.copy()); // } // // private void checkOwnership() { // final long currentId = Thread.currentThread().getId(); // checkState(ownerId == currentId, "Modification only allowed by owning thread. (owner=" + ownerId + " current=" + currentId + ")"); // } // } // // Path: src/main/java/org/graylog/collector/buffer/Buffer.java // public interface Buffer { // void insert(Message message); // // Message remove(); // } // // Path: src/main/java/org/graylog/collector/file/splitters/ContentSplitter.java // public abstract class ContentSplitter { // // public abstract Iterable<String> split(ByteBuf buffer, Charset charset, boolean includeRemainingData); // // public Iterable<String> split(ByteBuf buffer, Charset charset) { // return split(buffer, charset, false); // } // // public Iterable<String> splitRemaining(ByteBuf buffer, Charset charset) { // return split(buffer, charset, true); // } // }
import java.util.concurrent.TimeUnit; import com.google.common.util.concurrent.AbstractExecutionThreadService; import io.netty.buffer.ByteBuf; import org.graylog.collector.Message; import org.graylog.collector.MessageBuilder; import org.graylog.collector.buffer.Buffer; import org.graylog.collector.file.splitters.ContentSplitter; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.concurrent.BlockingQueue;
/** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.file; public class ChunkProcessor extends AbstractExecutionThreadService { private static final Logger log = LoggerFactory.getLogger(ChunkProcessor.class); private final Buffer buffer; private final MessageBuilder messageBuilder; private final BlockingQueue<FileChunk> chunkQueue;
// Path: src/main/java/org/graylog/collector/MessageBuilder.java // public class MessageBuilder { // private final long ownerId = Thread.currentThread().getId(); // // private String message; // private String source; // private DateTime timestamp; // private Message.Level level; // private String input; // private Set<String> outputs; // private MessageFields fields = new MessageFields(); // // public MessageBuilder() { // } // // private MessageBuilder(String message, String source, DateTime timestamp, Message.Level level, String input, Set<String> outputs, MessageFields fields) { // this.message = message; // this.source = source; // this.timestamp = timestamp; // this.level = level; // this.input = input; // this.outputs = outputs; // this.fields = fields; // } // // public MessageBuilder message(String message) { // checkOwnership(); // this.message = message; // return this; // } // // public MessageBuilder source(String source) { // checkOwnership(); // this.source = source; // return this; // } // // public MessageBuilder timestamp(DateTime timestamp) { // checkOwnership(); // this.timestamp = timestamp; // return this; // } // // public MessageBuilder level(Message.Level level) { // checkOwnership(); // this.level = level; // return this; // } // // public MessageBuilder input(String input) { // checkOwnership(); // this.input = input; // return this; // } // // public MessageBuilder outputs(Set<String> outputs) { // checkOwnership(); // if (outputs == null) { // this.outputs = null; // } else { // this.outputs = ImmutableSet.copyOf(outputs); // } // return this; // } // // public MessageBuilder fields(MessageFields fields) { // checkOwnership(); // this.fields = fields; // return this; // } // // public MessageBuilder addField(String key, int value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, long value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, boolean value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public MessageBuilder addField(String key, String value) { // checkOwnership(); // checkNotNull(fields); // this.fields.put(key, value); // return this; // } // // public Message build() { // checkNotNull(message, "Message should not be null!"); // checkNotNull(source, "Message source should not be null!"); // checkNotNull(timestamp, "Message timestamp should not be null!"); // checkNotNull(input, "Message input should not be null!"); // checkNotNull(outputs, "Message outputs should not be null!"); // // if (fields == null) { // return new Message(message, source, timestamp, level, input, outputs); // } else { // return new Message(message, source, timestamp, level, input, outputs, fields); // } // } // // public MessageBuilder copy() { // return new MessageBuilder(message, source, timestamp, level, input, outputs, fields.copy()); // } // // private void checkOwnership() { // final long currentId = Thread.currentThread().getId(); // checkState(ownerId == currentId, "Modification only allowed by owning thread. (owner=" + ownerId + " current=" + currentId + ")"); // } // } // // Path: src/main/java/org/graylog/collector/buffer/Buffer.java // public interface Buffer { // void insert(Message message); // // Message remove(); // } // // Path: src/main/java/org/graylog/collector/file/splitters/ContentSplitter.java // public abstract class ContentSplitter { // // public abstract Iterable<String> split(ByteBuf buffer, Charset charset, boolean includeRemainingData); // // public Iterable<String> split(ByteBuf buffer, Charset charset) { // return split(buffer, charset, false); // } // // public Iterable<String> splitRemaining(ByteBuf buffer, Charset charset) { // return split(buffer, charset, true); // } // } // Path: src/main/java/org/graylog/collector/file/ChunkProcessor.java import java.util.concurrent.TimeUnit; import com.google.common.util.concurrent.AbstractExecutionThreadService; import io.netty.buffer.ByteBuf; import org.graylog.collector.Message; import org.graylog.collector.MessageBuilder; import org.graylog.collector.buffer.Buffer; import org.graylog.collector.file.splitters.ContentSplitter; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.charset.Charset; import java.nio.file.Path; import java.util.concurrent.BlockingQueue; /** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.file; public class ChunkProcessor extends AbstractExecutionThreadService { private static final Logger log = LoggerFactory.getLogger(ChunkProcessor.class); private final Buffer buffer; private final MessageBuilder messageBuilder; private final BlockingQueue<FileChunk> chunkQueue;
private final ContentSplitter splitter;
DevOpsStudio/Re-Collector
src/main/java/org/graylog/collector/file/ChunkReaderScheduler.java
// Path: src/main/java/org/graylog/collector/inputs/file/FileInput.java // public class FileInput extends InputService { // public enum InitialReadPosition { // START, // END // } // // public interface Factory extends InputService.Factory<FileInput, FileInputConfiguration> { // FileInput create(FileInputConfiguration configuration); // } // // private final FileInputConfiguration configuration; // private final Buffer buffer; // private final FileObserver fileObserver; // private final String collectorHostName; // private FileReaderService readerService; // // @Inject // public FileInput(@Assisted FileInputConfiguration inputConfiguration, Buffer buffer, FileObserver fileObserver, // @CollectorHostName String collectorHostName) { // this.configuration = inputConfiguration; // this.buffer = buffer; // this.fileObserver = fileObserver; // this.collectorHostName = collectorHostName; // } // // @Override // public String getId() { // return configuration.getId(); // } // // @Override // public Set<String> getOutputs() { // return configuration.getOutputs(); // } // // @Override // protected void doStart() { // // TODO needs to be an absolute path because otherwise the FileObserver does weird things. Investigate what's wrong with it. // final MessageBuilder messageBuilder = new MessageBuilder() // .input(getId()) // .outputs(getOutputs()) // .source(collectorHostName) // .fields(configuration.getMessageFields()); // final PathSet pathSet = configuration.getPathSet(); // readerService = new FileReaderService( // pathSet, // configuration.getCharset(), // InitialReadPosition.END, // this, // messageBuilder, // configuration.createContentSplitter(), // buffer, // configuration.getReaderBufferSize(), // configuration.getReaderInterval(), // fileObserver // ); // // readerService.startAsync().awaitRunning(); // notifyStarted(); // } // // @Override // protected void doStop() { // readerService.stopAsync().awaitTerminated(); // notifyStopped(); // } // // @Override // public void setReaderFinished(ChunkReader chunkReader) { // // TODO Check if needed and for what it was used. // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // FileInput fileInput = (FileInput) o; // // return configuration.equals(fileInput.configuration); // // } // // @Override // public int hashCode() { // return configuration.hashCode(); // } // // @Override // public String toString() { // return ConfigurationUtils.toString(configuration, this); // } // }
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import com.google.common.collect.Maps; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.graylog.collector.inputs.Input; import org.graylog.collector.inputs.file.FileInput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.channels.AsynchronousFileChannel; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executors;
/** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.file; public class ChunkReaderScheduler { private static final Logger log = LoggerFactory.getLogger(ChunkReaderScheduler.class); private final Input input; private final int readerBufferSize; private final long readerInterval;
// Path: src/main/java/org/graylog/collector/inputs/file/FileInput.java // public class FileInput extends InputService { // public enum InitialReadPosition { // START, // END // } // // public interface Factory extends InputService.Factory<FileInput, FileInputConfiguration> { // FileInput create(FileInputConfiguration configuration); // } // // private final FileInputConfiguration configuration; // private final Buffer buffer; // private final FileObserver fileObserver; // private final String collectorHostName; // private FileReaderService readerService; // // @Inject // public FileInput(@Assisted FileInputConfiguration inputConfiguration, Buffer buffer, FileObserver fileObserver, // @CollectorHostName String collectorHostName) { // this.configuration = inputConfiguration; // this.buffer = buffer; // this.fileObserver = fileObserver; // this.collectorHostName = collectorHostName; // } // // @Override // public String getId() { // return configuration.getId(); // } // // @Override // public Set<String> getOutputs() { // return configuration.getOutputs(); // } // // @Override // protected void doStart() { // // TODO needs to be an absolute path because otherwise the FileObserver does weird things. Investigate what's wrong with it. // final MessageBuilder messageBuilder = new MessageBuilder() // .input(getId()) // .outputs(getOutputs()) // .source(collectorHostName) // .fields(configuration.getMessageFields()); // final PathSet pathSet = configuration.getPathSet(); // readerService = new FileReaderService( // pathSet, // configuration.getCharset(), // InitialReadPosition.END, // this, // messageBuilder, // configuration.createContentSplitter(), // buffer, // configuration.getReaderBufferSize(), // configuration.getReaderInterval(), // fileObserver // ); // // readerService.startAsync().awaitRunning(); // notifyStarted(); // } // // @Override // protected void doStop() { // readerService.stopAsync().awaitTerminated(); // notifyStopped(); // } // // @Override // public void setReaderFinished(ChunkReader chunkReader) { // // TODO Check if needed and for what it was used. // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // FileInput fileInput = (FileInput) o; // // return configuration.equals(fileInput.configuration); // // } // // @Override // public int hashCode() { // return configuration.hashCode(); // } // // @Override // public String toString() { // return ConfigurationUtils.toString(configuration, this); // } // } // Path: src/main/java/org/graylog/collector/file/ChunkReaderScheduler.java import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import com.google.common.collect.Maps; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.graylog.collector.inputs.Input; import org.graylog.collector.inputs.file.FileInput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.channels.AsynchronousFileChannel; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executors; /** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.file; public class ChunkReaderScheduler { private static final Logger log = LoggerFactory.getLogger(ChunkReaderScheduler.class); private final Input input; private final int readerBufferSize; private final long readerInterval;
private final FileInput.InitialReadPosition initialReadPosition;
DevOpsStudio/Re-Collector
src/main/java/org/graylog/collector/heartbeat/HeartbeatService.java
// Path: src/main/java/org/graylog/collector/utils/CollectorId.java // @Singleton // public class CollectorId { // private static final Logger LOG = LoggerFactory.getLogger(CollectorId.class); // // private final String id; // // @Inject // public CollectorId(CollectorIdConfiguration config) { // final String configuredCollectorId = config.getCollectorId(); // if (configuredCollectorId.startsWith("file:")) { // final String[] splittedConfig = configuredCollectorId.split("^file:"); // if (splittedConfig.length < 2) { // throw new RuntimeException("Invalid specified file location for collector id: " + configuredCollectorId); // } // this.id = readOrGenerate(splittedConfig[1]); // } else { // this.id = configuredCollectorId; // } // } // // private String readOrGenerate(String filename) { // try { // String read = read(filename); // // if (read == null || read.isEmpty()) { // return generate(filename); // } // // LOG.info("Collector ID: {}", read); // return read; // } catch (FileNotFoundException | NoSuchFileException e) { // return generate(filename); // } catch (IOException e) { // throw new RuntimeException("Unable to read node id from file: ", e); // } // } // // private String read(String filename) throws IOException { // final List<String> lines = Files.readAllLines(Paths.get(filename), StandardCharsets.UTF_8); // // return lines.size() > 0 ? lines.get(0) : ""; // } // // private String generate(String filename) { // String generated = this.randomId(); // LOG.info("No node ID file found. Generated: {}", generated); // // try { // persist(generated, filename); // } catch (IOException e1) { // LOG.debug("Could not persist node ID: ", e1); // throw new RuntimeException("Unable to persist node ID to " + filename, e1); // } // // return generated; // } // // private void persist(String nodeId, String filename) throws IOException { // final Path path = new File(filename).getAbsoluteFile().toPath(); // // if (path.getParent() != null) { // Files.createDirectories(path.getParent()); // } // // Files.write(path, nodeId.getBytes(Charsets.UTF_8)); // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // return id; // } // // // private String randomId() { // return UUID.randomUUID().toString(); // } // }
import com.google.common.util.concurrent.AbstractScheduledService; import com.typesafe.config.Config; import org.graylog.collector.utils.CollectorId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import retrofit.RetrofitError; import retrofit.client.Response; import javax.inject.Inject; import java.util.concurrent.TimeUnit;
/** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.heartbeat; public class HeartbeatService extends AbstractScheduledService { private static final Logger LOG = LoggerFactory.getLogger(HeartbeatService.class); private static final String heartbeatIntervalParameter = "heartbeat-interval"; private static final int defaultHeartbeatInterval = 5; private static final String enableRegistrationParameter = "enable-registration"; private final CollectorRegistrationService collectorRegistrationService; private final CollectorRegistrationRequest collectorRegistrationRequest; private final Config config; private final String collectorId; @Inject public HeartbeatService(CollectorRegistrationService collectorRegistrationService, CollectorRegistrationRequest collectorRegistrationRequest, Config config,
// Path: src/main/java/org/graylog/collector/utils/CollectorId.java // @Singleton // public class CollectorId { // private static final Logger LOG = LoggerFactory.getLogger(CollectorId.class); // // private final String id; // // @Inject // public CollectorId(CollectorIdConfiguration config) { // final String configuredCollectorId = config.getCollectorId(); // if (configuredCollectorId.startsWith("file:")) { // final String[] splittedConfig = configuredCollectorId.split("^file:"); // if (splittedConfig.length < 2) { // throw new RuntimeException("Invalid specified file location for collector id: " + configuredCollectorId); // } // this.id = readOrGenerate(splittedConfig[1]); // } else { // this.id = configuredCollectorId; // } // } // // private String readOrGenerate(String filename) { // try { // String read = read(filename); // // if (read == null || read.isEmpty()) { // return generate(filename); // } // // LOG.info("Collector ID: {}", read); // return read; // } catch (FileNotFoundException | NoSuchFileException e) { // return generate(filename); // } catch (IOException e) { // throw new RuntimeException("Unable to read node id from file: ", e); // } // } // // private String read(String filename) throws IOException { // final List<String> lines = Files.readAllLines(Paths.get(filename), StandardCharsets.UTF_8); // // return lines.size() > 0 ? lines.get(0) : ""; // } // // private String generate(String filename) { // String generated = this.randomId(); // LOG.info("No node ID file found. Generated: {}", generated); // // try { // persist(generated, filename); // } catch (IOException e1) { // LOG.debug("Could not persist node ID: ", e1); // throw new RuntimeException("Unable to persist node ID to " + filename, e1); // } // // return generated; // } // // private void persist(String nodeId, String filename) throws IOException { // final Path path = new File(filename).getAbsoluteFile().toPath(); // // if (path.getParent() != null) { // Files.createDirectories(path.getParent()); // } // // Files.write(path, nodeId.getBytes(Charsets.UTF_8)); // } // // /** // * {@inheritDoc} // */ // @Override // public String toString() { // return id; // } // // // private String randomId() { // return UUID.randomUUID().toString(); // } // } // Path: src/main/java/org/graylog/collector/heartbeat/HeartbeatService.java import com.google.common.util.concurrent.AbstractScheduledService; import com.typesafe.config.Config; import org.graylog.collector.utils.CollectorId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import retrofit.RetrofitError; import retrofit.client.Response; import javax.inject.Inject; import java.util.concurrent.TimeUnit; /** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.heartbeat; public class HeartbeatService extends AbstractScheduledService { private static final Logger LOG = LoggerFactory.getLogger(HeartbeatService.class); private static final String heartbeatIntervalParameter = "heartbeat-interval"; private static final int defaultHeartbeatInterval = 5; private static final String enableRegistrationParameter = "enable-registration"; private final CollectorRegistrationService collectorRegistrationService; private final CollectorRegistrationRequest collectorRegistrationRequest; private final Config config; private final String collectorId; @Inject public HeartbeatService(CollectorRegistrationService collectorRegistrationService, CollectorRegistrationRequest collectorRegistrationRequest, Config config,
CollectorId collectorId) {
DevOpsStudio/Re-Collector
src/main/java/org/graylog/collector/outputs/OutputRouter.java
// Path: src/main/java/org/graylog/collector/config/ConfigurationRegistry.java // public class ConfigurationRegistry { // private final Set<Service> services = Sets.newHashSet(); // private final Set<Input> inputs = Sets.newHashSet(); // private final Set<Output> outputs = Sets.newHashSet(); // // private final Map<String, InputConfiguration.Factory<? extends InputConfiguration>> inputConfigFactories; // private final Map<String, OutputConfiguration.Factory<? extends OutputConfiguration>> outputConfigFactories; // // private final List<ConfigurationError> errors = Lists.newArrayList(); // private final ConfigurationValidator validator; // // @Inject // public ConfigurationRegistry(Config config, // Map<String, InputConfiguration.Factory<? extends InputConfiguration>> inputConfigs, // Map<String, OutputConfiguration.Factory<? extends OutputConfiguration>> outputConfigs) { // this.inputConfigFactories = inputConfigs; // this.outputConfigFactories = outputConfigs; // this.validator = new ConfigurationValidator(); // // try { // processConfig(config); // } catch (ConfigException e) { // errors.add(new ConfigurationError(e.getMessage())); // } // } // // private void processConfig(Config config) { // final Config inputs = config.getConfig("inputs"); // final Config outputs = config.getConfig("outputs"); // // buildInputs(inputs); // buildOutputs(outputs); // // errors.addAll(validator.getErrors()); // } // // private void buildInputs(final Config inputConfigs) { // final Map<String, InputConfiguration.Factory<? extends InputConfiguration>> factories = ConfigurationRegistry.this.inputConfigFactories; // // dispatchConfig(inputConfigs, (type, id, config) -> { // if (factories.containsKey(type)) { // final InputConfiguration cfg = factories.get(type).create(id, config); // // if (validator.isValid(cfg)) { // final InputService input = cfg.createInput(); // services.add(input); // inputs.add(input); // } // } else { // errors.add(new ConfigurationError("Unknown input type \"" + type + "\" for " + id)); // } // }); // } // // private void buildOutputs(Config outputConfigs) { // final Map<String, OutputConfiguration.Factory<? extends OutputConfiguration>> factories = ConfigurationRegistry.this.outputConfigFactories; // // dispatchConfig(outputConfigs, new ConfigCallback() { // @Override // public void call(String type, String id, Config config) { // if (factories.containsKey(type)) { // final OutputConfiguration cfg = factories.get(type).create(id, config); // // if (validator.isValid(cfg)) { // final OutputService output = cfg.createOutput(); // services.add(output); // outputs.add(output); // } // } else { // errors.add(new ConfigurationError("Unknown output type \"" + type + "\" for " + id)); // } // } // }); // } // // private void dispatchConfig(Config config, ConfigCallback callback) { // for (Map.Entry<String, ConfigValue> entry : config.root().entrySet()) { // final String id = entry.getKey(); // // try { // final Config entryConfig = ((ConfigObject) entry.getValue()).toConfig(); // final String type = entryConfig.getString("type"); // // if (Strings.isNullOrEmpty(type)) { // errors.add(new ConfigurationError("Missing type field for " + id + " (" + entryConfig + ")")); // continue; // } // // callback.call(type, id, entryConfig); // } catch (ConfigException e) { // errors.add(new ConfigurationError("[" + id + "] " + e.getMessage())); // } // } // } // // public boolean isValid() { // return errors.isEmpty(); // } // // public List<ConfigurationError> getErrors() { // return errors; // } // // public Set<Service> getServices() { // return services; // } // // public Set<Input> getInputs() { // return inputs; // } // // public Set<Output> getOutputs() { // return outputs; // } // // private interface ConfigCallback { // void call(String type, String id, Config config); // } // }
import org.graylog.collector.Message; import org.graylog.collector.buffer.BufferConsumer; import org.graylog.collector.config.ConfigurationRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import java.util.Set;
/** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.outputs; public class OutputRouter implements BufferConsumer { private static final Logger LOG = LoggerFactory.getLogger(OutputRouter.class); private final Set<Output> outputs; @Inject
// Path: src/main/java/org/graylog/collector/config/ConfigurationRegistry.java // public class ConfigurationRegistry { // private final Set<Service> services = Sets.newHashSet(); // private final Set<Input> inputs = Sets.newHashSet(); // private final Set<Output> outputs = Sets.newHashSet(); // // private final Map<String, InputConfiguration.Factory<? extends InputConfiguration>> inputConfigFactories; // private final Map<String, OutputConfiguration.Factory<? extends OutputConfiguration>> outputConfigFactories; // // private final List<ConfigurationError> errors = Lists.newArrayList(); // private final ConfigurationValidator validator; // // @Inject // public ConfigurationRegistry(Config config, // Map<String, InputConfiguration.Factory<? extends InputConfiguration>> inputConfigs, // Map<String, OutputConfiguration.Factory<? extends OutputConfiguration>> outputConfigs) { // this.inputConfigFactories = inputConfigs; // this.outputConfigFactories = outputConfigs; // this.validator = new ConfigurationValidator(); // // try { // processConfig(config); // } catch (ConfigException e) { // errors.add(new ConfigurationError(e.getMessage())); // } // } // // private void processConfig(Config config) { // final Config inputs = config.getConfig("inputs"); // final Config outputs = config.getConfig("outputs"); // // buildInputs(inputs); // buildOutputs(outputs); // // errors.addAll(validator.getErrors()); // } // // private void buildInputs(final Config inputConfigs) { // final Map<String, InputConfiguration.Factory<? extends InputConfiguration>> factories = ConfigurationRegistry.this.inputConfigFactories; // // dispatchConfig(inputConfigs, (type, id, config) -> { // if (factories.containsKey(type)) { // final InputConfiguration cfg = factories.get(type).create(id, config); // // if (validator.isValid(cfg)) { // final InputService input = cfg.createInput(); // services.add(input); // inputs.add(input); // } // } else { // errors.add(new ConfigurationError("Unknown input type \"" + type + "\" for " + id)); // } // }); // } // // private void buildOutputs(Config outputConfigs) { // final Map<String, OutputConfiguration.Factory<? extends OutputConfiguration>> factories = ConfigurationRegistry.this.outputConfigFactories; // // dispatchConfig(outputConfigs, new ConfigCallback() { // @Override // public void call(String type, String id, Config config) { // if (factories.containsKey(type)) { // final OutputConfiguration cfg = factories.get(type).create(id, config); // // if (validator.isValid(cfg)) { // final OutputService output = cfg.createOutput(); // services.add(output); // outputs.add(output); // } // } else { // errors.add(new ConfigurationError("Unknown output type \"" + type + "\" for " + id)); // } // } // }); // } // // private void dispatchConfig(Config config, ConfigCallback callback) { // for (Map.Entry<String, ConfigValue> entry : config.root().entrySet()) { // final String id = entry.getKey(); // // try { // final Config entryConfig = ((ConfigObject) entry.getValue()).toConfig(); // final String type = entryConfig.getString("type"); // // if (Strings.isNullOrEmpty(type)) { // errors.add(new ConfigurationError("Missing type field for " + id + " (" + entryConfig + ")")); // continue; // } // // callback.call(type, id, entryConfig); // } catch (ConfigException e) { // errors.add(new ConfigurationError("[" + id + "] " + e.getMessage())); // } // } // } // // public boolean isValid() { // return errors.isEmpty(); // } // // public List<ConfigurationError> getErrors() { // return errors; // } // // public Set<Service> getServices() { // return services; // } // // public Set<Input> getInputs() { // return inputs; // } // // public Set<Output> getOutputs() { // return outputs; // } // // private interface ConfigCallback { // void call(String type, String id, Config config); // } // } // Path: src/main/java/org/graylog/collector/outputs/OutputRouter.java import org.graylog.collector.Message; import org.graylog.collector.buffer.BufferConsumer; import org.graylog.collector.config.ConfigurationRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import java.util.Set; /** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.outputs; public class OutputRouter implements BufferConsumer { private static final Logger LOG = LoggerFactory.getLogger(OutputRouter.class); private final Set<Output> outputs; @Inject
public OutputRouter(ConfigurationRegistry configuration) {
DevOpsStudio/Re-Collector
src/main/java/org/graylog/collector/cli/Main.java
// Path: src/main/java/org/graylog/collector/cli/commands/CollectorHelp.java // public class CollectorHelp extends Help implements CollectorCommand { // @Override // public void stop() { // // nothing to stop // } // } // // Path: src/main/java/org/graylog/collector/cli/commands/Run.java // @Command(name = "run", description = "Start the collector") // public class Run implements CollectorCommand { // private static final Logger LOG = LoggerFactory.getLogger(Run.class); // // @Option(name = "-f", description = "Path to configuration file.", required = true) // private final File configFile = null; // // private CollectorServiceManager serviceManager; // // @Override // public void run() { // LOG.info("Starting Collector v{} (commit {})", CollectorVersion.CURRENT.version(), CollectorVersion.CURRENT.commitIdShort()); // // showOsInfo(); // // final Injector injector = getInjector(); // serviceManager = injector.getInstance(CollectorServiceManager.class); // // validateConfiguration(serviceManager.getConfiguration()); // // serviceManager.start(); // // for (Map.Entry<Service.State, Service> entry : serviceManager.servicesByState().entries()) { // LOG.info("Service {}: {}", entry.getKey().toString(), entry.getValue().toString()); // } // // serviceManager.awaitStopped(); // } // // private void showOsInfo() { // try { // final OS os = OS.getOs(); // LOG.info("Running on {} {} {} ({})", os.getPlatformName(), os.getName(), os.getVersion(), os.getArch()); // } catch (Exception e) { // LOG.warn("Unable to get detailed platform information", e); // } // } // // @Override // public void stop() { // LOG.info("Stopping..."); // if (serviceManager != null) { // serviceManager.stop(); // } // } // // private Injector getInjector() { // Injector injector = null; // // try { // injector = CollectorInjector.createInjector(new ConfigurationModule(configFile), // new BufferModule(), // new InputsModule(), // new FileModule(), // new OutputsModule(), // new ServicesModule(), // new MetricsModule(), // new MemoryReporterModule(), // new ServerApiModule(), // new HeartbeatModule(), // new CollectorIdModule(), // new CollectorHostNameModule()); // } catch (Exception e) { // LOG.error("ERROR: {}", e.getMessage()); // LOG.debug("Detailed injection creation error", e); // doExit(); // } // // return injector; // } // // private void validateConfiguration(ConfigurationRegistry configurationRegistry) { // if (!configurationRegistry.isValid()) { // for (ConfigurationError error : configurationRegistry.getErrors()) { // LOG.error("Configuration Error: {}", error.getMesssage()); // } // // doExit(); // } // } // // private void doExit() { // LOG.info("Exit"); // System.exit(1); // } // }
import io.airlift.airline.Cli; import io.airlift.airline.ParseException; import org.graylog.collector.cli.commands.CollectorCommand; import org.graylog.collector.cli.commands.CollectorHelp; import org.graylog.collector.cli.commands.Run; import org.graylog.collector.cli.commands.Version; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.cli; public class Main { static { // Hijack java.util.logging, see https://logging.apache.org/log4j/log4j-2.2/log4j-jul/index.html System.setProperty("java.util.logging.manager", org.apache.logging.log4j.jul.LogManager.class.getCanonicalName()); } private static final Logger LOG = LoggerFactory.getLogger(Main.class); private static CollectorCommand command = null; public static void main(String[] args) { final Cli.CliBuilder<CollectorCommand> cliBuilder = Cli.<CollectorCommand>builder("graylog-collector") .withDescription("Graylog Collector")
// Path: src/main/java/org/graylog/collector/cli/commands/CollectorHelp.java // public class CollectorHelp extends Help implements CollectorCommand { // @Override // public void stop() { // // nothing to stop // } // } // // Path: src/main/java/org/graylog/collector/cli/commands/Run.java // @Command(name = "run", description = "Start the collector") // public class Run implements CollectorCommand { // private static final Logger LOG = LoggerFactory.getLogger(Run.class); // // @Option(name = "-f", description = "Path to configuration file.", required = true) // private final File configFile = null; // // private CollectorServiceManager serviceManager; // // @Override // public void run() { // LOG.info("Starting Collector v{} (commit {})", CollectorVersion.CURRENT.version(), CollectorVersion.CURRENT.commitIdShort()); // // showOsInfo(); // // final Injector injector = getInjector(); // serviceManager = injector.getInstance(CollectorServiceManager.class); // // validateConfiguration(serviceManager.getConfiguration()); // // serviceManager.start(); // // for (Map.Entry<Service.State, Service> entry : serviceManager.servicesByState().entries()) { // LOG.info("Service {}: {}", entry.getKey().toString(), entry.getValue().toString()); // } // // serviceManager.awaitStopped(); // } // // private void showOsInfo() { // try { // final OS os = OS.getOs(); // LOG.info("Running on {} {} {} ({})", os.getPlatformName(), os.getName(), os.getVersion(), os.getArch()); // } catch (Exception e) { // LOG.warn("Unable to get detailed platform information", e); // } // } // // @Override // public void stop() { // LOG.info("Stopping..."); // if (serviceManager != null) { // serviceManager.stop(); // } // } // // private Injector getInjector() { // Injector injector = null; // // try { // injector = CollectorInjector.createInjector(new ConfigurationModule(configFile), // new BufferModule(), // new InputsModule(), // new FileModule(), // new OutputsModule(), // new ServicesModule(), // new MetricsModule(), // new MemoryReporterModule(), // new ServerApiModule(), // new HeartbeatModule(), // new CollectorIdModule(), // new CollectorHostNameModule()); // } catch (Exception e) { // LOG.error("ERROR: {}", e.getMessage()); // LOG.debug("Detailed injection creation error", e); // doExit(); // } // // return injector; // } // // private void validateConfiguration(ConfigurationRegistry configurationRegistry) { // if (!configurationRegistry.isValid()) { // for (ConfigurationError error : configurationRegistry.getErrors()) { // LOG.error("Configuration Error: {}", error.getMesssage()); // } // // doExit(); // } // } // // private void doExit() { // LOG.info("Exit"); // System.exit(1); // } // } // Path: src/main/java/org/graylog/collector/cli/Main.java import io.airlift.airline.Cli; import io.airlift.airline.ParseException; import org.graylog.collector.cli.commands.CollectorCommand; import org.graylog.collector.cli.commands.CollectorHelp; import org.graylog.collector.cli.commands.Run; import org.graylog.collector.cli.commands.Version; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.cli; public class Main { static { // Hijack java.util.logging, see https://logging.apache.org/log4j/log4j-2.2/log4j-jul/index.html System.setProperty("java.util.logging.manager", org.apache.logging.log4j.jul.LogManager.class.getCanonicalName()); } private static final Logger LOG = LoggerFactory.getLogger(Main.class); private static CollectorCommand command = null; public static void main(String[] args) { final Cli.CliBuilder<CollectorCommand> cliBuilder = Cli.<CollectorCommand>builder("graylog-collector") .withDescription("Graylog Collector")
.withDefaultCommand(CollectorHelp.class)
DevOpsStudio/Re-Collector
src/main/java/org/graylog/collector/cli/Main.java
// Path: src/main/java/org/graylog/collector/cli/commands/CollectorHelp.java // public class CollectorHelp extends Help implements CollectorCommand { // @Override // public void stop() { // // nothing to stop // } // } // // Path: src/main/java/org/graylog/collector/cli/commands/Run.java // @Command(name = "run", description = "Start the collector") // public class Run implements CollectorCommand { // private static final Logger LOG = LoggerFactory.getLogger(Run.class); // // @Option(name = "-f", description = "Path to configuration file.", required = true) // private final File configFile = null; // // private CollectorServiceManager serviceManager; // // @Override // public void run() { // LOG.info("Starting Collector v{} (commit {})", CollectorVersion.CURRENT.version(), CollectorVersion.CURRENT.commitIdShort()); // // showOsInfo(); // // final Injector injector = getInjector(); // serviceManager = injector.getInstance(CollectorServiceManager.class); // // validateConfiguration(serviceManager.getConfiguration()); // // serviceManager.start(); // // for (Map.Entry<Service.State, Service> entry : serviceManager.servicesByState().entries()) { // LOG.info("Service {}: {}", entry.getKey().toString(), entry.getValue().toString()); // } // // serviceManager.awaitStopped(); // } // // private void showOsInfo() { // try { // final OS os = OS.getOs(); // LOG.info("Running on {} {} {} ({})", os.getPlatformName(), os.getName(), os.getVersion(), os.getArch()); // } catch (Exception e) { // LOG.warn("Unable to get detailed platform information", e); // } // } // // @Override // public void stop() { // LOG.info("Stopping..."); // if (serviceManager != null) { // serviceManager.stop(); // } // } // // private Injector getInjector() { // Injector injector = null; // // try { // injector = CollectorInjector.createInjector(new ConfigurationModule(configFile), // new BufferModule(), // new InputsModule(), // new FileModule(), // new OutputsModule(), // new ServicesModule(), // new MetricsModule(), // new MemoryReporterModule(), // new ServerApiModule(), // new HeartbeatModule(), // new CollectorIdModule(), // new CollectorHostNameModule()); // } catch (Exception e) { // LOG.error("ERROR: {}", e.getMessage()); // LOG.debug("Detailed injection creation error", e); // doExit(); // } // // return injector; // } // // private void validateConfiguration(ConfigurationRegistry configurationRegistry) { // if (!configurationRegistry.isValid()) { // for (ConfigurationError error : configurationRegistry.getErrors()) { // LOG.error("Configuration Error: {}", error.getMesssage()); // } // // doExit(); // } // } // // private void doExit() { // LOG.info("Exit"); // System.exit(1); // } // }
import io.airlift.airline.Cli; import io.airlift.airline.ParseException; import org.graylog.collector.cli.commands.CollectorCommand; import org.graylog.collector.cli.commands.CollectorHelp; import org.graylog.collector.cli.commands.Run; import org.graylog.collector.cli.commands.Version; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.cli; public class Main { static { // Hijack java.util.logging, see https://logging.apache.org/log4j/log4j-2.2/log4j-jul/index.html System.setProperty("java.util.logging.manager", org.apache.logging.log4j.jul.LogManager.class.getCanonicalName()); } private static final Logger LOG = LoggerFactory.getLogger(Main.class); private static CollectorCommand command = null; public static void main(String[] args) { final Cli.CliBuilder<CollectorCommand> cliBuilder = Cli.<CollectorCommand>builder("graylog-collector") .withDescription("Graylog Collector") .withDefaultCommand(CollectorHelp.class) .withCommand(CollectorHelp.class) .withCommand(Version.class)
// Path: src/main/java/org/graylog/collector/cli/commands/CollectorHelp.java // public class CollectorHelp extends Help implements CollectorCommand { // @Override // public void stop() { // // nothing to stop // } // } // // Path: src/main/java/org/graylog/collector/cli/commands/Run.java // @Command(name = "run", description = "Start the collector") // public class Run implements CollectorCommand { // private static final Logger LOG = LoggerFactory.getLogger(Run.class); // // @Option(name = "-f", description = "Path to configuration file.", required = true) // private final File configFile = null; // // private CollectorServiceManager serviceManager; // // @Override // public void run() { // LOG.info("Starting Collector v{} (commit {})", CollectorVersion.CURRENT.version(), CollectorVersion.CURRENT.commitIdShort()); // // showOsInfo(); // // final Injector injector = getInjector(); // serviceManager = injector.getInstance(CollectorServiceManager.class); // // validateConfiguration(serviceManager.getConfiguration()); // // serviceManager.start(); // // for (Map.Entry<Service.State, Service> entry : serviceManager.servicesByState().entries()) { // LOG.info("Service {}: {}", entry.getKey().toString(), entry.getValue().toString()); // } // // serviceManager.awaitStopped(); // } // // private void showOsInfo() { // try { // final OS os = OS.getOs(); // LOG.info("Running on {} {} {} ({})", os.getPlatformName(), os.getName(), os.getVersion(), os.getArch()); // } catch (Exception e) { // LOG.warn("Unable to get detailed platform information", e); // } // } // // @Override // public void stop() { // LOG.info("Stopping..."); // if (serviceManager != null) { // serviceManager.stop(); // } // } // // private Injector getInjector() { // Injector injector = null; // // try { // injector = CollectorInjector.createInjector(new ConfigurationModule(configFile), // new BufferModule(), // new InputsModule(), // new FileModule(), // new OutputsModule(), // new ServicesModule(), // new MetricsModule(), // new MemoryReporterModule(), // new ServerApiModule(), // new HeartbeatModule(), // new CollectorIdModule(), // new CollectorHostNameModule()); // } catch (Exception e) { // LOG.error("ERROR: {}", e.getMessage()); // LOG.debug("Detailed injection creation error", e); // doExit(); // } // // return injector; // } // // private void validateConfiguration(ConfigurationRegistry configurationRegistry) { // if (!configurationRegistry.isValid()) { // for (ConfigurationError error : configurationRegistry.getErrors()) { // LOG.error("Configuration Error: {}", error.getMesssage()); // } // // doExit(); // } // } // // private void doExit() { // LOG.info("Exit"); // System.exit(1); // } // } // Path: src/main/java/org/graylog/collector/cli/Main.java import io.airlift.airline.Cli; import io.airlift.airline.ParseException; import org.graylog.collector.cli.commands.CollectorCommand; import org.graylog.collector.cli.commands.CollectorHelp; import org.graylog.collector.cli.commands.Run; import org.graylog.collector.cli.commands.Version; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This file is part of Graylog. * * Graylog 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. * * Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog.collector.cli; public class Main { static { // Hijack java.util.logging, see https://logging.apache.org/log4j/log4j-2.2/log4j-jul/index.html System.setProperty("java.util.logging.manager", org.apache.logging.log4j.jul.LogManager.class.getCanonicalName()); } private static final Logger LOG = LoggerFactory.getLogger(Main.class); private static CollectorCommand command = null; public static void main(String[] args) { final Cli.CliBuilder<CollectorCommand> cliBuilder = Cli.<CollectorCommand>builder("graylog-collector") .withDescription("Graylog Collector") .withDefaultCommand(CollectorHelp.class) .withCommand(CollectorHelp.class) .withCommand(Version.class)
.withCommand(Run.class);
asrulhadi/wap
src/java/org/homeunix/wap/CodeInjection/buildWalkerTree_CodeInj.java
// Path: src/java/org/homeunix/wap/sqli/buildWalkerTree_sqli.java // public class buildWalkerTree_sqli { // // // *** CONSTRUCTORS // public buildWalkerTree_sqli(CommonTreeNodeStream nodes, String filename, Map mst, Map mift, Map mft, Map mftt, Map mtt, UntaintedTable mus, Map mlct, Map mct, Map mobjt, List files) throws IOException, RecognitionException { // try { // // Navegate into AST by walker tree // Sqli def = new Sqli(nodes, mst, mift, mft, mftt, mtt, mus, mlct, mct, mobjt, filename, files); // Sqli.prog_return prog = def.prog(); // } catch (RecognitionException ex) { // Logger.getLogger(buildWalkerTree_sqli.class.getName()).log(Level.SEVERE, null, ex); // } catch (Exception e) {} // // } // // } // // Path: src/java/org/homeunix/wap/table/tainted/UntaintedTable.java // public class UntaintedTable { // Map<String, Symbol> symbolsUntainted; // // /* CONSTRUCTOR */ // public UntaintedTable() { // symbolsUntainted = new LinkedHashMap<String, Symbol>(); // } // // // /* METHODS of the class*/ // // /* // * Give the Map that contain the untainted variables // */ // public Map getUntaintedMembers() { // return symbolsUntainted; // } // // /* // * Verify if a untainted variable exist in Map // */ // public Boolean existSymbol(String s) { // return symbolsUntainted.containsKey(s); // } // // /* // * Insert a untainted variable in Map // */ // public void insertUntaintSymbol(Symbol sym) { // symbolsUntainted.put(sym.getName(), sym); // } // // /* // * Remove a untainted variable from Map // */ // public void removeUntaintSymbol(Symbol sym) { // symbolsUntainted.remove(sym.getName()); // } // // public void copyToMUS(UntaintedTable m) { // m = mus // Iterator <Symbol> it = this.getUntaintedMembers().values().iterator(); // mus_aux // Symbol sym; // for(;it.hasNext();){ // sym = it.next(); // if (!sym.getName().equals("return")) // m.getUntaintedMembers().put(sym.getName(), sym); // } // } // // public void copyGlobalsToMUS(TaintedTable mts_princ , UntaintedTable mus_princ, MethodSymbol meth_sym_clone){ // for(Iterator <Symbol> it = meth_sym_clone.getGlobalVarsOfFunction().values().iterator(); it.hasNext();){ // Symbol sym = it.next(); // if (this.getUntaintedMembers().containsKey(sym.getName()) == true && mts_princ.getTaintedMembers().containsKey(sym.getName()) == true) { // if (mus_princ.existSymbol(sym.getName()) == false){ // // Se passou de tainted para untainted, colocar em untainted // mus_princ.insertUntaintSymbol(sym); // } // } // } // } // // // public UntaintedTable copyUntaintedTable() { // UntaintedTable tab = new UntaintedTable(); // for(Iterator <Symbol> it = this.getUntaintedMembers().values().iterator(); it.hasNext();){ // Symbol cs = it.next(); // try { // tab.getUntaintedMembers().put(cs.getName(), cs.clone()); // } catch (CloneNotSupportedException ex) { // Logger.getLogger(UntaintedTable.class.getName()).log(Level.SEVERE, null, ex); // } // } // return tab; // } // // public void cleanAll(){ // Collection <Symbol> c = this.symbolsUntainted.values(); // c.removeAll(c); // this.symbolsUntainted.clear(); // } // // }
import org.homeunix.wap.sqli.buildWalkerTree_sqli; import org.homeunix.wap.php.parser.CodeInjection; import org.homeunix.wap.table.tainted.UntaintedTable; import org.antlr.runtime.*; import org.antlr.runtime.tree.*; import java.io.*; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger;
/* * Class that build the AST and make walker tree to SQLI */ package org.homeunix.wap.CodeInjection; /** * * @author Iberia Medeiros */ public class buildWalkerTree_CodeInj { // *** CONSTRUCTORS public buildWalkerTree_CodeInj(CommonTreeNodeStream nodes, String filename, Map mst, Map mift, Map mft, Map mftt, Map mtt, UntaintedTable mus, Map mlct, Map mct, Map mobjt, List files) throws IOException { try { // Navegate into AST by walker tree CodeInjection def = new CodeInjection(nodes, mst, mift, mft, mftt, mtt, mus, mlct, mct, mobjt, filename, files); CodeInjection.prog_return prog = def.prog(); } catch (RecognitionException ex) {
// Path: src/java/org/homeunix/wap/sqli/buildWalkerTree_sqli.java // public class buildWalkerTree_sqli { // // // *** CONSTRUCTORS // public buildWalkerTree_sqli(CommonTreeNodeStream nodes, String filename, Map mst, Map mift, Map mft, Map mftt, Map mtt, UntaintedTable mus, Map mlct, Map mct, Map mobjt, List files) throws IOException, RecognitionException { // try { // // Navegate into AST by walker tree // Sqli def = new Sqli(nodes, mst, mift, mft, mftt, mtt, mus, mlct, mct, mobjt, filename, files); // Sqli.prog_return prog = def.prog(); // } catch (RecognitionException ex) { // Logger.getLogger(buildWalkerTree_sqli.class.getName()).log(Level.SEVERE, null, ex); // } catch (Exception e) {} // // } // // } // // Path: src/java/org/homeunix/wap/table/tainted/UntaintedTable.java // public class UntaintedTable { // Map<String, Symbol> symbolsUntainted; // // /* CONSTRUCTOR */ // public UntaintedTable() { // symbolsUntainted = new LinkedHashMap<String, Symbol>(); // } // // // /* METHODS of the class*/ // // /* // * Give the Map that contain the untainted variables // */ // public Map getUntaintedMembers() { // return symbolsUntainted; // } // // /* // * Verify if a untainted variable exist in Map // */ // public Boolean existSymbol(String s) { // return symbolsUntainted.containsKey(s); // } // // /* // * Insert a untainted variable in Map // */ // public void insertUntaintSymbol(Symbol sym) { // symbolsUntainted.put(sym.getName(), sym); // } // // /* // * Remove a untainted variable from Map // */ // public void removeUntaintSymbol(Symbol sym) { // symbolsUntainted.remove(sym.getName()); // } // // public void copyToMUS(UntaintedTable m) { // m = mus // Iterator <Symbol> it = this.getUntaintedMembers().values().iterator(); // mus_aux // Symbol sym; // for(;it.hasNext();){ // sym = it.next(); // if (!sym.getName().equals("return")) // m.getUntaintedMembers().put(sym.getName(), sym); // } // } // // public void copyGlobalsToMUS(TaintedTable mts_princ , UntaintedTable mus_princ, MethodSymbol meth_sym_clone){ // for(Iterator <Symbol> it = meth_sym_clone.getGlobalVarsOfFunction().values().iterator(); it.hasNext();){ // Symbol sym = it.next(); // if (this.getUntaintedMembers().containsKey(sym.getName()) == true && mts_princ.getTaintedMembers().containsKey(sym.getName()) == true) { // if (mus_princ.existSymbol(sym.getName()) == false){ // // Se passou de tainted para untainted, colocar em untainted // mus_princ.insertUntaintSymbol(sym); // } // } // } // } // // // public UntaintedTable copyUntaintedTable() { // UntaintedTable tab = new UntaintedTable(); // for(Iterator <Symbol> it = this.getUntaintedMembers().values().iterator(); it.hasNext();){ // Symbol cs = it.next(); // try { // tab.getUntaintedMembers().put(cs.getName(), cs.clone()); // } catch (CloneNotSupportedException ex) { // Logger.getLogger(UntaintedTable.class.getName()).log(Level.SEVERE, null, ex); // } // } // return tab; // } // // public void cleanAll(){ // Collection <Symbol> c = this.symbolsUntainted.values(); // c.removeAll(c); // this.symbolsUntainted.clear(); // } // // } // Path: src/java/org/homeunix/wap/CodeInjection/buildWalkerTree_CodeInj.java import org.homeunix.wap.sqli.buildWalkerTree_sqli; import org.homeunix.wap.php.parser.CodeInjection; import org.homeunix.wap.table.tainted.UntaintedTable; import org.antlr.runtime.*; import org.antlr.runtime.tree.*; import java.io.*; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /* * Class that build the AST and make walker tree to SQLI */ package org.homeunix.wap.CodeInjection; /** * * @author Iberia Medeiros */ public class buildWalkerTree_CodeInj { // *** CONSTRUCTORS public buildWalkerTree_CodeInj(CommonTreeNodeStream nodes, String filename, Map mst, Map mift, Map mft, Map mftt, Map mtt, UntaintedTable mus, Map mlct, Map mct, Map mobjt, List files) throws IOException { try { // Navegate into AST by walker tree CodeInjection def = new CodeInjection(nodes, mst, mift, mft, mftt, mtt, mus, mlct, mct, mobjt, filename, files); CodeInjection.prog_return prog = def.prog(); } catch (RecognitionException ex) {
Logger.getLogger(buildWalkerTree_sqli.class.getName()).log(Level.SEVERE, null, ex);
asrulhadi/wap
src/java/org/homeunix/wap/XSS/buildWalkerTree_XSS.java
// Path: src/java/org/homeunix/wap/sqli/buildWalkerTree_sqli.java // public class buildWalkerTree_sqli { // // // *** CONSTRUCTORS // public buildWalkerTree_sqli(CommonTreeNodeStream nodes, String filename, Map mst, Map mift, Map mft, Map mftt, Map mtt, UntaintedTable mus, Map mlct, Map mct, Map mobjt, List files) throws IOException, RecognitionException { // try { // // Navegate into AST by walker tree // Sqli def = new Sqli(nodes, mst, mift, mft, mftt, mtt, mus, mlct, mct, mobjt, filename, files); // Sqli.prog_return prog = def.prog(); // } catch (RecognitionException ex) { // Logger.getLogger(buildWalkerTree_sqli.class.getName()).log(Level.SEVERE, null, ex); // } catch (Exception e) {} // // } // // } // // Path: src/java/org/homeunix/wap/table/tainted/UntaintedTable.java // public class UntaintedTable { // Map<String, Symbol> symbolsUntainted; // // /* CONSTRUCTOR */ // public UntaintedTable() { // symbolsUntainted = new LinkedHashMap<String, Symbol>(); // } // // // /* METHODS of the class*/ // // /* // * Give the Map that contain the untainted variables // */ // public Map getUntaintedMembers() { // return symbolsUntainted; // } // // /* // * Verify if a untainted variable exist in Map // */ // public Boolean existSymbol(String s) { // return symbolsUntainted.containsKey(s); // } // // /* // * Insert a untainted variable in Map // */ // public void insertUntaintSymbol(Symbol sym) { // symbolsUntainted.put(sym.getName(), sym); // } // // /* // * Remove a untainted variable from Map // */ // public void removeUntaintSymbol(Symbol sym) { // symbolsUntainted.remove(sym.getName()); // } // // public void copyToMUS(UntaintedTable m) { // m = mus // Iterator <Symbol> it = this.getUntaintedMembers().values().iterator(); // mus_aux // Symbol sym; // for(;it.hasNext();){ // sym = it.next(); // if (!sym.getName().equals("return")) // m.getUntaintedMembers().put(sym.getName(), sym); // } // } // // public void copyGlobalsToMUS(TaintedTable mts_princ , UntaintedTable mus_princ, MethodSymbol meth_sym_clone){ // for(Iterator <Symbol> it = meth_sym_clone.getGlobalVarsOfFunction().values().iterator(); it.hasNext();){ // Symbol sym = it.next(); // if (this.getUntaintedMembers().containsKey(sym.getName()) == true && mts_princ.getTaintedMembers().containsKey(sym.getName()) == true) { // if (mus_princ.existSymbol(sym.getName()) == false){ // // Se passou de tainted para untainted, colocar em untainted // mus_princ.insertUntaintSymbol(sym); // } // } // } // } // // // public UntaintedTable copyUntaintedTable() { // UntaintedTable tab = new UntaintedTable(); // for(Iterator <Symbol> it = this.getUntaintedMembers().values().iterator(); it.hasNext();){ // Symbol cs = it.next(); // try { // tab.getUntaintedMembers().put(cs.getName(), cs.clone()); // } catch (CloneNotSupportedException ex) { // Logger.getLogger(UntaintedTable.class.getName()).log(Level.SEVERE, null, ex); // } // } // return tab; // } // // public void cleanAll(){ // Collection <Symbol> c = this.symbolsUntainted.values(); // c.removeAll(c); // this.symbolsUntainted.clear(); // } // // }
import org.homeunix.wap.php.parser.XSS; import org.homeunix.wap.sqli.buildWalkerTree_sqli; import org.homeunix.wap.table.tainted.UntaintedTable; import org.antlr.runtime.*; import org.antlr.runtime.tree.*; import java.io.*; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger;
/* * Class that build the AST and make walker tree to SQLI */ package org.homeunix.wap.XSS; /** * * @author Iberia Medeiros */ public class buildWalkerTree_XSS { // *** CONSTRUCTORS public buildWalkerTree_XSS(CommonTreeNodeStream nodes, String filename, Map mst, Map mift, Map mft, Map mftt, Map mtt, UntaintedTable mus, Map mlct, Map mct, Map mobjt, List files) throws IOException { try { // Navegate into AST by walker tree XSS def = new XSS(nodes, mst, mift, mft, mftt, mtt, mus, mlct, mct, mobjt, filename, files); XSS.prog_return prog = def.prog(); } catch (RecognitionException ex) {
// Path: src/java/org/homeunix/wap/sqli/buildWalkerTree_sqli.java // public class buildWalkerTree_sqli { // // // *** CONSTRUCTORS // public buildWalkerTree_sqli(CommonTreeNodeStream nodes, String filename, Map mst, Map mift, Map mft, Map mftt, Map mtt, UntaintedTable mus, Map mlct, Map mct, Map mobjt, List files) throws IOException, RecognitionException { // try { // // Navegate into AST by walker tree // Sqli def = new Sqli(nodes, mst, mift, mft, mftt, mtt, mus, mlct, mct, mobjt, filename, files); // Sqli.prog_return prog = def.prog(); // } catch (RecognitionException ex) { // Logger.getLogger(buildWalkerTree_sqli.class.getName()).log(Level.SEVERE, null, ex); // } catch (Exception e) {} // // } // // } // // Path: src/java/org/homeunix/wap/table/tainted/UntaintedTable.java // public class UntaintedTable { // Map<String, Symbol> symbolsUntainted; // // /* CONSTRUCTOR */ // public UntaintedTable() { // symbolsUntainted = new LinkedHashMap<String, Symbol>(); // } // // // /* METHODS of the class*/ // // /* // * Give the Map that contain the untainted variables // */ // public Map getUntaintedMembers() { // return symbolsUntainted; // } // // /* // * Verify if a untainted variable exist in Map // */ // public Boolean existSymbol(String s) { // return symbolsUntainted.containsKey(s); // } // // /* // * Insert a untainted variable in Map // */ // public void insertUntaintSymbol(Symbol sym) { // symbolsUntainted.put(sym.getName(), sym); // } // // /* // * Remove a untainted variable from Map // */ // public void removeUntaintSymbol(Symbol sym) { // symbolsUntainted.remove(sym.getName()); // } // // public void copyToMUS(UntaintedTable m) { // m = mus // Iterator <Symbol> it = this.getUntaintedMembers().values().iterator(); // mus_aux // Symbol sym; // for(;it.hasNext();){ // sym = it.next(); // if (!sym.getName().equals("return")) // m.getUntaintedMembers().put(sym.getName(), sym); // } // } // // public void copyGlobalsToMUS(TaintedTable mts_princ , UntaintedTable mus_princ, MethodSymbol meth_sym_clone){ // for(Iterator <Symbol> it = meth_sym_clone.getGlobalVarsOfFunction().values().iterator(); it.hasNext();){ // Symbol sym = it.next(); // if (this.getUntaintedMembers().containsKey(sym.getName()) == true && mts_princ.getTaintedMembers().containsKey(sym.getName()) == true) { // if (mus_princ.existSymbol(sym.getName()) == false){ // // Se passou de tainted para untainted, colocar em untainted // mus_princ.insertUntaintSymbol(sym); // } // } // } // } // // // public UntaintedTable copyUntaintedTable() { // UntaintedTable tab = new UntaintedTable(); // for(Iterator <Symbol> it = this.getUntaintedMembers().values().iterator(); it.hasNext();){ // Symbol cs = it.next(); // try { // tab.getUntaintedMembers().put(cs.getName(), cs.clone()); // } catch (CloneNotSupportedException ex) { // Logger.getLogger(UntaintedTable.class.getName()).log(Level.SEVERE, null, ex); // } // } // return tab; // } // // public void cleanAll(){ // Collection <Symbol> c = this.symbolsUntainted.values(); // c.removeAll(c); // this.symbolsUntainted.clear(); // } // // } // Path: src/java/org/homeunix/wap/XSS/buildWalkerTree_XSS.java import org.homeunix.wap.php.parser.XSS; import org.homeunix.wap.sqli.buildWalkerTree_sqli; import org.homeunix.wap.table.tainted.UntaintedTable; import org.antlr.runtime.*; import org.antlr.runtime.tree.*; import java.io.*; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /* * Class that build the AST and make walker tree to SQLI */ package org.homeunix.wap.XSS; /** * * @author Iberia Medeiros */ public class buildWalkerTree_XSS { // *** CONSTRUCTORS public buildWalkerTree_XSS(CommonTreeNodeStream nodes, String filename, Map mst, Map mift, Map mft, Map mftt, Map mtt, UntaintedTable mus, Map mlct, Map mct, Map mobjt, List files) throws IOException { try { // Navegate into AST by walker tree XSS def = new XSS(nodes, mst, mift, mft, mftt, mtt, mus, mlct, mct, mobjt, filename, files); XSS.prog_return prog = def.prog(); } catch (RecognitionException ex) {
Logger.getLogger(buildWalkerTree_sqli.class.getName()).log(Level.SEVERE, null, ex);
flyingrub/TamTime
app/src/main/java/flying/grub/tamtime/adapter/OneRouteAdapter.java
// Path: app/src/main/java/flying/grub/tamtime/data/map/Stop.java // public class Stop { // private int _id; // private int cityway_id; // private int tam_id; // private StopZone stopZone; // private Direction direction; // private ArrayList<Time> times; // // public Stop(int _id, int cityway_id, int tam_id, StopZone stopZone, Direction direction) { // this._id = _id; // this.cityway_id = cityway_id; // this.tam_id = tam_id; // this.stopZone = stopZone; // this.direction = direction; // this.times = new ArrayList<>(); // } // // public int get_id() { // return _id; // } // // public int getCityway_id() { // return cityway_id; // } // // public int getTam_id() { // return tam_id; // } // // public Direction getDirection() { // return direction; // } // // public StopZone getStopZone() { // return stopZone; // } // // public ArrayList<Time> getTimes() { // while (times.size() < 3) { // times.add(new Time("-", 0, 0)); // } // return times; // } // // public void setTimes(ArrayList<Time> times) { // this.times = times; // } // // @Override // public String toString() { // return "Stop{" + // "_id=" + _id + // ", cityway_id=" + cityway_id + // ", tam_id=" + tam_id + // ", stopZone=" + stopZone.getName() + // ", direction=" + direction.getName() + // ", times=" + times + // '}'; // } // // } // // Path: app/src/main/java/flying/grub/tamtime/data/real_time/Time.java // public class Time { // String waitingTime; // int hour; // int minute; // // public Time(String waitingTime, int hour, int minute) { // this.waitingTime = waitingTime; // this.hour = hour; // this.minute = minute; // } // // public String getWaitingTime() { // return waitingTime; // } // }
import android.content.Context; import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import java.util.ArrayList; import flying.grub.tamtime.R; import flying.grub.tamtime.data.map.Stop; import flying.grub.tamtime.data.real_time.Time;
package flying.grub.tamtime.adapter; public class OneRouteAdapter extends RecyclerView.Adapter<OneRouteAdapter.ViewHolder> { private static final String TAG = OneRouteAdapter.class.getSimpleName(); public OnItemClickListener mItemClickListener;
// Path: app/src/main/java/flying/grub/tamtime/data/map/Stop.java // public class Stop { // private int _id; // private int cityway_id; // private int tam_id; // private StopZone stopZone; // private Direction direction; // private ArrayList<Time> times; // // public Stop(int _id, int cityway_id, int tam_id, StopZone stopZone, Direction direction) { // this._id = _id; // this.cityway_id = cityway_id; // this.tam_id = tam_id; // this.stopZone = stopZone; // this.direction = direction; // this.times = new ArrayList<>(); // } // // public int get_id() { // return _id; // } // // public int getCityway_id() { // return cityway_id; // } // // public int getTam_id() { // return tam_id; // } // // public Direction getDirection() { // return direction; // } // // public StopZone getStopZone() { // return stopZone; // } // // public ArrayList<Time> getTimes() { // while (times.size() < 3) { // times.add(new Time("-", 0, 0)); // } // return times; // } // // public void setTimes(ArrayList<Time> times) { // this.times = times; // } // // @Override // public String toString() { // return "Stop{" + // "_id=" + _id + // ", cityway_id=" + cityway_id + // ", tam_id=" + tam_id + // ", stopZone=" + stopZone.getName() + // ", direction=" + direction.getName() + // ", times=" + times + // '}'; // } // // } // // Path: app/src/main/java/flying/grub/tamtime/data/real_time/Time.java // public class Time { // String waitingTime; // int hour; // int minute; // // public Time(String waitingTime, int hour, int minute) { // this.waitingTime = waitingTime; // this.hour = hour; // this.minute = minute; // } // // public String getWaitingTime() { // return waitingTime; // } // } // Path: app/src/main/java/flying/grub/tamtime/adapter/OneRouteAdapter.java import android.content.Context; import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import java.util.ArrayList; import flying.grub.tamtime.R; import flying.grub.tamtime.data.map.Stop; import flying.grub.tamtime.data.real_time.Time; package flying.grub.tamtime.adapter; public class OneRouteAdapter extends RecyclerView.Adapter<OneRouteAdapter.ViewHolder> { private static final String TAG = OneRouteAdapter.class.getSimpleName(); public OnItemClickListener mItemClickListener;
private ArrayList<Stop> stops;
flyingrub/TamTime
app/src/main/java/flying/grub/tamtime/adapter/OneRouteAdapter.java
// Path: app/src/main/java/flying/grub/tamtime/data/map/Stop.java // public class Stop { // private int _id; // private int cityway_id; // private int tam_id; // private StopZone stopZone; // private Direction direction; // private ArrayList<Time> times; // // public Stop(int _id, int cityway_id, int tam_id, StopZone stopZone, Direction direction) { // this._id = _id; // this.cityway_id = cityway_id; // this.tam_id = tam_id; // this.stopZone = stopZone; // this.direction = direction; // this.times = new ArrayList<>(); // } // // public int get_id() { // return _id; // } // // public int getCityway_id() { // return cityway_id; // } // // public int getTam_id() { // return tam_id; // } // // public Direction getDirection() { // return direction; // } // // public StopZone getStopZone() { // return stopZone; // } // // public ArrayList<Time> getTimes() { // while (times.size() < 3) { // times.add(new Time("-", 0, 0)); // } // return times; // } // // public void setTimes(ArrayList<Time> times) { // this.times = times; // } // // @Override // public String toString() { // return "Stop{" + // "_id=" + _id + // ", cityway_id=" + cityway_id + // ", tam_id=" + tam_id + // ", stopZone=" + stopZone.getName() + // ", direction=" + direction.getName() + // ", times=" + times + // '}'; // } // // } // // Path: app/src/main/java/flying/grub/tamtime/data/real_time/Time.java // public class Time { // String waitingTime; // int hour; // int minute; // // public Time(String waitingTime, int hour, int minute) { // this.waitingTime = waitingTime; // this.hour = hour; // this.minute = minute; // } // // public String getWaitingTime() { // return waitingTime; // } // }
import android.content.Context; import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import java.util.ArrayList; import flying.grub.tamtime.R; import flying.grub.tamtime.data.map.Stop; import flying.grub.tamtime.data.real_time.Time;
this.mItemClickListener = mItemClickListener; } public OneRouteAdapter(ArrayList<Stop> stops, Context context) { this.context = context; this.stops = stops; this.isTheoritical = false; } public OneRouteAdapter(ArrayList<Stop> stops, Context context, boolean isTheoritical) { this(stops, context); this.isTheoritical = isTheoritical; } @Override public OneRouteAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_one_line, parent, false); ViewHolder vh = new ViewHolder(v); return vh; } @Override public void onBindViewHolder(ViewHolder holder, final int position) { // - get element from your dataset at this position // - replace the contents of the view with that element Stop stop = stops.get(position); holder.stop.setText(stop.getStopZone().getName());
// Path: app/src/main/java/flying/grub/tamtime/data/map/Stop.java // public class Stop { // private int _id; // private int cityway_id; // private int tam_id; // private StopZone stopZone; // private Direction direction; // private ArrayList<Time> times; // // public Stop(int _id, int cityway_id, int tam_id, StopZone stopZone, Direction direction) { // this._id = _id; // this.cityway_id = cityway_id; // this.tam_id = tam_id; // this.stopZone = stopZone; // this.direction = direction; // this.times = new ArrayList<>(); // } // // public int get_id() { // return _id; // } // // public int getCityway_id() { // return cityway_id; // } // // public int getTam_id() { // return tam_id; // } // // public Direction getDirection() { // return direction; // } // // public StopZone getStopZone() { // return stopZone; // } // // public ArrayList<Time> getTimes() { // while (times.size() < 3) { // times.add(new Time("-", 0, 0)); // } // return times; // } // // public void setTimes(ArrayList<Time> times) { // this.times = times; // } // // @Override // public String toString() { // return "Stop{" + // "_id=" + _id + // ", cityway_id=" + cityway_id + // ", tam_id=" + tam_id + // ", stopZone=" + stopZone.getName() + // ", direction=" + direction.getName() + // ", times=" + times + // '}'; // } // // } // // Path: app/src/main/java/flying/grub/tamtime/data/real_time/Time.java // public class Time { // String waitingTime; // int hour; // int minute; // // public Time(String waitingTime, int hour, int minute) { // this.waitingTime = waitingTime; // this.hour = hour; // this.minute = minute; // } // // public String getWaitingTime() { // return waitingTime; // } // } // Path: app/src/main/java/flying/grub/tamtime/adapter/OneRouteAdapter.java import android.content.Context; import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import java.util.ArrayList; import flying.grub.tamtime.R; import flying.grub.tamtime.data.map.Stop; import flying.grub.tamtime.data.real_time.Time; this.mItemClickListener = mItemClickListener; } public OneRouteAdapter(ArrayList<Stop> stops, Context context) { this.context = context; this.stops = stops; this.isTheoritical = false; } public OneRouteAdapter(ArrayList<Stop> stops, Context context, boolean isTheoritical) { this(stops, context); this.isTheoritical = isTheoritical; } @Override public OneRouteAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_one_line, parent, false); ViewHolder vh = new ViewHolder(v); return vh; } @Override public void onBindViewHolder(ViewHolder holder, final int position) { // - get element from your dataset at this position // - replace the contents of the view with that element Stop stop = stops.get(position); holder.stop.setText(stop.getStopZone().getName());
ArrayList<Time> times = stop.getTimes(); // Request 3 next times
flyingrub/TamTime
app/src/main/java/flying/grub/tamtime/adapter/AllStopAdapter.java
// Path: app/src/main/java/flying/grub/tamtime/data/map/StopZone.java // public class StopZone { // private int _id; // private int cityway_id; // private int tam_id; // private String name; // private String search_name; // private ArrayList<Line> lines; // private ArrayList<Stop> stops; // // private Location location; // private ArrayList<Report> reportList; // private float distanceFromUser; // // public StopZone(String name, int _id, int tam_id, int cityway_id, String search_name, double lat, double lon){ // this.lines = new ArrayList<>(); // this.reportList = new ArrayList<>(); // this.name = name; // this.cityway_id = cityway_id; // this._id = _id; // this.tam_id = tam_id; // this.search_name = search_name; // this.location = new Location(name); // this.location.setLongitude(lon); // this.location.setLatitude(lat); // this.stops = new ArrayList<>(); // } // // public void addLine(Line line) { // if (!this.lines.contains(line)) { // this.lines.add(line); // } // } // // public void addStop(Stop stop) { // this.stops.add(stop); // } // // public String getName() { // return name; // } // // public ArrayList<Line> getLines() { // return this.lines; // } // // public int getID() { // return this._id; // } // // public void addReport(Report report) { // this.reportList.add(report); // } // // public ArrayList<Report> getReports() { // ArrayList<Report> res = new ArrayList<>(); // Calendar date = Calendar.getInstance(); // for (Report r : this.reportList) { // if (r.isValid(date)) res.add(r); // } // Collections.reverse(res); // the last is the oldest now. // return res; // } // // public void removeReport(Report rep) { // this.reportList.remove(rep); // } // // public void calcDistanceFromUser(Location user) { // distanceFromUser = user.distanceTo(this.location); // } // // public String getNormalisedName() { // return search_name; // } // // public float getDistanceFromUser() { // return distanceFromUser; // } // // public ArrayList<Stop> getStops(Line line) { // ArrayList<Stop> res = new ArrayList<>(); // for (Stop stop : stops) { // if (stop.getDirection().getLine().getCityway_id() == line.getCityway_id()) { // res.add(stop); // } // } // return res; // } // // public ArrayList<Stop> getStops() { // return stops; // } // // @Override // public String toString() { // return "StopZone{" + // "name='" + name + '\'' + // ", lines=" + lines + // ", stops=" + stops + // '}'; // } // }
import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import flying.grub.tamtime.R; import flying.grub.tamtime.data.map.StopZone;
package flying.grub.tamtime.adapter; public class AllStopAdapter extends RecyclerView.Adapter<AllStopAdapter.ViewHolder> { public OnItemClickListener mItemClickListener;
// Path: app/src/main/java/flying/grub/tamtime/data/map/StopZone.java // public class StopZone { // private int _id; // private int cityway_id; // private int tam_id; // private String name; // private String search_name; // private ArrayList<Line> lines; // private ArrayList<Stop> stops; // // private Location location; // private ArrayList<Report> reportList; // private float distanceFromUser; // // public StopZone(String name, int _id, int tam_id, int cityway_id, String search_name, double lat, double lon){ // this.lines = new ArrayList<>(); // this.reportList = new ArrayList<>(); // this.name = name; // this.cityway_id = cityway_id; // this._id = _id; // this.tam_id = tam_id; // this.search_name = search_name; // this.location = new Location(name); // this.location.setLongitude(lon); // this.location.setLatitude(lat); // this.stops = new ArrayList<>(); // } // // public void addLine(Line line) { // if (!this.lines.contains(line)) { // this.lines.add(line); // } // } // // public void addStop(Stop stop) { // this.stops.add(stop); // } // // public String getName() { // return name; // } // // public ArrayList<Line> getLines() { // return this.lines; // } // // public int getID() { // return this._id; // } // // public void addReport(Report report) { // this.reportList.add(report); // } // // public ArrayList<Report> getReports() { // ArrayList<Report> res = new ArrayList<>(); // Calendar date = Calendar.getInstance(); // for (Report r : this.reportList) { // if (r.isValid(date)) res.add(r); // } // Collections.reverse(res); // the last is the oldest now. // return res; // } // // public void removeReport(Report rep) { // this.reportList.remove(rep); // } // // public void calcDistanceFromUser(Location user) { // distanceFromUser = user.distanceTo(this.location); // } // // public String getNormalisedName() { // return search_name; // } // // public float getDistanceFromUser() { // return distanceFromUser; // } // // public ArrayList<Stop> getStops(Line line) { // ArrayList<Stop> res = new ArrayList<>(); // for (Stop stop : stops) { // if (stop.getDirection().getLine().getCityway_id() == line.getCityway_id()) { // res.add(stop); // } // } // return res; // } // // public ArrayList<Stop> getStops() { // return stops; // } // // @Override // public String toString() { // return "StopZone{" + // "name='" + name + '\'' + // ", lines=" + lines + // ", stops=" + stops + // '}'; // } // } // Path: app/src/main/java/flying/grub/tamtime/adapter/AllStopAdapter.java import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import flying.grub.tamtime.R; import flying.grub.tamtime.data.map.StopZone; package flying.grub.tamtime.adapter; public class AllStopAdapter extends RecyclerView.Adapter<AllStopAdapter.ViewHolder> { public OnItemClickListener mItemClickListener;
private ArrayList<StopZone> stops;
flyingrub/TamTime
app/src/main/java/flying/grub/tamtime/adapter/OneStopAdapter.java
// Path: app/src/main/java/flying/grub/tamtime/data/map/Stop.java // public class Stop { // private int _id; // private int cityway_id; // private int tam_id; // private StopZone stopZone; // private Direction direction; // private ArrayList<Time> times; // // public Stop(int _id, int cityway_id, int tam_id, StopZone stopZone, Direction direction) { // this._id = _id; // this.cityway_id = cityway_id; // this.tam_id = tam_id; // this.stopZone = stopZone; // this.direction = direction; // this.times = new ArrayList<>(); // } // // public int get_id() { // return _id; // } // // public int getCityway_id() { // return cityway_id; // } // // public int getTam_id() { // return tam_id; // } // // public Direction getDirection() { // return direction; // } // // public StopZone getStopZone() { // return stopZone; // } // // public ArrayList<Time> getTimes() { // while (times.size() < 3) { // times.add(new Time("-", 0, 0)); // } // return times; // } // // public void setTimes(ArrayList<Time> times) { // this.times = times; // } // // @Override // public String toString() { // return "Stop{" + // "_id=" + _id + // ", cityway_id=" + cityway_id + // ", tam_id=" + tam_id + // ", stopZone=" + stopZone.getName() + // ", direction=" + direction.getName() + // ", times=" + times + // '}'; // } // // } // // Path: app/src/main/java/flying/grub/tamtime/data/real_time/Time.java // public class Time { // String waitingTime; // int hour; // int minute; // // public Time(String waitingTime, int hour, int minute) { // this.waitingTime = waitingTime; // this.hour = hour; // this.minute = minute; // } // // public String getWaitingTime() { // return waitingTime; // } // }
import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import flying.grub.tamtime.R; import flying.grub.tamtime.data.map.Stop; import flying.grub.tamtime.data.real_time.Time;
package flying.grub.tamtime.adapter; public class OneStopAdapter extends RecyclerView.Adapter<OneStopAdapter.ViewHolder> { public OnItemClickListener mItemClickListener;
// Path: app/src/main/java/flying/grub/tamtime/data/map/Stop.java // public class Stop { // private int _id; // private int cityway_id; // private int tam_id; // private StopZone stopZone; // private Direction direction; // private ArrayList<Time> times; // // public Stop(int _id, int cityway_id, int tam_id, StopZone stopZone, Direction direction) { // this._id = _id; // this.cityway_id = cityway_id; // this.tam_id = tam_id; // this.stopZone = stopZone; // this.direction = direction; // this.times = new ArrayList<>(); // } // // public int get_id() { // return _id; // } // // public int getCityway_id() { // return cityway_id; // } // // public int getTam_id() { // return tam_id; // } // // public Direction getDirection() { // return direction; // } // // public StopZone getStopZone() { // return stopZone; // } // // public ArrayList<Time> getTimes() { // while (times.size() < 3) { // times.add(new Time("-", 0, 0)); // } // return times; // } // // public void setTimes(ArrayList<Time> times) { // this.times = times; // } // // @Override // public String toString() { // return "Stop{" + // "_id=" + _id + // ", cityway_id=" + cityway_id + // ", tam_id=" + tam_id + // ", stopZone=" + stopZone.getName() + // ", direction=" + direction.getName() + // ", times=" + times + // '}'; // } // // } // // Path: app/src/main/java/flying/grub/tamtime/data/real_time/Time.java // public class Time { // String waitingTime; // int hour; // int minute; // // public Time(String waitingTime, int hour, int minute) { // this.waitingTime = waitingTime; // this.hour = hour; // this.minute = minute; // } // // public String getWaitingTime() { // return waitingTime; // } // } // Path: app/src/main/java/flying/grub/tamtime/adapter/OneStopAdapter.java import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import flying.grub.tamtime.R; import flying.grub.tamtime.data.map.Stop; import flying.grub.tamtime.data.real_time.Time; package flying.grub.tamtime.adapter; public class OneStopAdapter extends RecyclerView.Adapter<OneStopAdapter.ViewHolder> { public OnItemClickListener mItemClickListener;
public ArrayList<Stop> stops;
flyingrub/TamTime
app/src/main/java/flying/grub/tamtime/adapter/OneStopAdapter.java
// Path: app/src/main/java/flying/grub/tamtime/data/map/Stop.java // public class Stop { // private int _id; // private int cityway_id; // private int tam_id; // private StopZone stopZone; // private Direction direction; // private ArrayList<Time> times; // // public Stop(int _id, int cityway_id, int tam_id, StopZone stopZone, Direction direction) { // this._id = _id; // this.cityway_id = cityway_id; // this.tam_id = tam_id; // this.stopZone = stopZone; // this.direction = direction; // this.times = new ArrayList<>(); // } // // public int get_id() { // return _id; // } // // public int getCityway_id() { // return cityway_id; // } // // public int getTam_id() { // return tam_id; // } // // public Direction getDirection() { // return direction; // } // // public StopZone getStopZone() { // return stopZone; // } // // public ArrayList<Time> getTimes() { // while (times.size() < 3) { // times.add(new Time("-", 0, 0)); // } // return times; // } // // public void setTimes(ArrayList<Time> times) { // this.times = times; // } // // @Override // public String toString() { // return "Stop{" + // "_id=" + _id + // ", cityway_id=" + cityway_id + // ", tam_id=" + tam_id + // ", stopZone=" + stopZone.getName() + // ", direction=" + direction.getName() + // ", times=" + times + // '}'; // } // // } // // Path: app/src/main/java/flying/grub/tamtime/data/real_time/Time.java // public class Time { // String waitingTime; // int hour; // int minute; // // public Time(String waitingTime, int hour, int minute) { // this.waitingTime = waitingTime; // this.hour = hour; // this.minute = minute; // } // // public String getWaitingTime() { // return waitingTime; // } // }
import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import flying.grub.tamtime.R; import flying.grub.tamtime.data.map.Stop; import flying.grub.tamtime.data.real_time.Time;
package flying.grub.tamtime.adapter; public class OneStopAdapter extends RecyclerView.Adapter<OneStopAdapter.ViewHolder> { public OnItemClickListener mItemClickListener; public ArrayList<Stop> stops; public OneStopAdapter(ArrayList<Stop> stops) { this.stops = stops; } public interface OnItemClickListener { void onItemClick(View view, int position); } public void SetOnItemClickListener(final OnItemClickListener mItemClickListener) { this.mItemClickListener = mItemClickListener; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // create a new view View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_card_stop, parent, false); // set the view's size, margins, paddings and layout parameters ViewHolder vh = new ViewHolder(v); return vh; } @Override public void onBindViewHolder(ViewHolder holder, int position) { Stop stop = stops.get(position); holder.direction.setText(stop.getDirection().getName());
// Path: app/src/main/java/flying/grub/tamtime/data/map/Stop.java // public class Stop { // private int _id; // private int cityway_id; // private int tam_id; // private StopZone stopZone; // private Direction direction; // private ArrayList<Time> times; // // public Stop(int _id, int cityway_id, int tam_id, StopZone stopZone, Direction direction) { // this._id = _id; // this.cityway_id = cityway_id; // this.tam_id = tam_id; // this.stopZone = stopZone; // this.direction = direction; // this.times = new ArrayList<>(); // } // // public int get_id() { // return _id; // } // // public int getCityway_id() { // return cityway_id; // } // // public int getTam_id() { // return tam_id; // } // // public Direction getDirection() { // return direction; // } // // public StopZone getStopZone() { // return stopZone; // } // // public ArrayList<Time> getTimes() { // while (times.size() < 3) { // times.add(new Time("-", 0, 0)); // } // return times; // } // // public void setTimes(ArrayList<Time> times) { // this.times = times; // } // // @Override // public String toString() { // return "Stop{" + // "_id=" + _id + // ", cityway_id=" + cityway_id + // ", tam_id=" + tam_id + // ", stopZone=" + stopZone.getName() + // ", direction=" + direction.getName() + // ", times=" + times + // '}'; // } // // } // // Path: app/src/main/java/flying/grub/tamtime/data/real_time/Time.java // public class Time { // String waitingTime; // int hour; // int minute; // // public Time(String waitingTime, int hour, int minute) { // this.waitingTime = waitingTime; // this.hour = hour; // this.minute = minute; // } // // public String getWaitingTime() { // return waitingTime; // } // } // Path: app/src/main/java/flying/grub/tamtime/adapter/OneStopAdapter.java import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import flying.grub.tamtime.R; import flying.grub.tamtime.data.map.Stop; import flying.grub.tamtime.data.real_time.Time; package flying.grub.tamtime.adapter; public class OneStopAdapter extends RecyclerView.Adapter<OneStopAdapter.ViewHolder> { public OnItemClickListener mItemClickListener; public ArrayList<Stop> stops; public OneStopAdapter(ArrayList<Stop> stops) { this.stops = stops; } public interface OnItemClickListener { void onItemClick(View view, int position); } public void SetOnItemClickListener(final OnItemClickListener mItemClickListener) { this.mItemClickListener = mItemClickListener; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // create a new view View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_card_stop, parent, false); // set the view's size, margins, paddings and layout parameters ViewHolder vh = new ViewHolder(v); return vh; } @Override public void onBindViewHolder(ViewHolder holder, int position) { Stop stop = stops.get(position); holder.direction.setText(stop.getDirection().getName());
ArrayList<Time> times = stop.getTimes(); // Request 3 next times
flyingrub/TamTime
app/src/main/java/flying/grub/tamtime/adapter/AllStopReportAdapter.java
// Path: app/src/main/java/flying/grub/tamtime/data/map/StopZone.java // public class StopZone { // private int _id; // private int cityway_id; // private int tam_id; // private String name; // private String search_name; // private ArrayList<Line> lines; // private ArrayList<Stop> stops; // // private Location location; // private ArrayList<Report> reportList; // private float distanceFromUser; // // public StopZone(String name, int _id, int tam_id, int cityway_id, String search_name, double lat, double lon){ // this.lines = new ArrayList<>(); // this.reportList = new ArrayList<>(); // this.name = name; // this.cityway_id = cityway_id; // this._id = _id; // this.tam_id = tam_id; // this.search_name = search_name; // this.location = new Location(name); // this.location.setLongitude(lon); // this.location.setLatitude(lat); // this.stops = new ArrayList<>(); // } // // public void addLine(Line line) { // if (!this.lines.contains(line)) { // this.lines.add(line); // } // } // // public void addStop(Stop stop) { // this.stops.add(stop); // } // // public String getName() { // return name; // } // // public ArrayList<Line> getLines() { // return this.lines; // } // // public int getID() { // return this._id; // } // // public void addReport(Report report) { // this.reportList.add(report); // } // // public ArrayList<Report> getReports() { // ArrayList<Report> res = new ArrayList<>(); // Calendar date = Calendar.getInstance(); // for (Report r : this.reportList) { // if (r.isValid(date)) res.add(r); // } // Collections.reverse(res); // the last is the oldest now. // return res; // } // // public void removeReport(Report rep) { // this.reportList.remove(rep); // } // // public void calcDistanceFromUser(Location user) { // distanceFromUser = user.distanceTo(this.location); // } // // public String getNormalisedName() { // return search_name; // } // // public float getDistanceFromUser() { // return distanceFromUser; // } // // public ArrayList<Stop> getStops(Line line) { // ArrayList<Stop> res = new ArrayList<>(); // for (Stop stop : stops) { // if (stop.getDirection().getLine().getCityway_id() == line.getCityway_id()) { // res.add(stop); // } // } // return res; // } // // public ArrayList<Stop> getStops() { // return stops; // } // // @Override // public String toString() { // return "StopZone{" + // "name='" + name + '\'' + // ", lines=" + lines + // ", stops=" + stops + // '}'; // } // }
import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import flying.grub.tamtime.R; import flying.grub.tamtime.data.map.StopZone;
package flying.grub.tamtime.adapter; public class AllStopReportAdapter extends RecyclerView.Adapter<AllStopReportAdapter.ViewHolder> { public OnItemClickListener itemClickListener;
// Path: app/src/main/java/flying/grub/tamtime/data/map/StopZone.java // public class StopZone { // private int _id; // private int cityway_id; // private int tam_id; // private String name; // private String search_name; // private ArrayList<Line> lines; // private ArrayList<Stop> stops; // // private Location location; // private ArrayList<Report> reportList; // private float distanceFromUser; // // public StopZone(String name, int _id, int tam_id, int cityway_id, String search_name, double lat, double lon){ // this.lines = new ArrayList<>(); // this.reportList = new ArrayList<>(); // this.name = name; // this.cityway_id = cityway_id; // this._id = _id; // this.tam_id = tam_id; // this.search_name = search_name; // this.location = new Location(name); // this.location.setLongitude(lon); // this.location.setLatitude(lat); // this.stops = new ArrayList<>(); // } // // public void addLine(Line line) { // if (!this.lines.contains(line)) { // this.lines.add(line); // } // } // // public void addStop(Stop stop) { // this.stops.add(stop); // } // // public String getName() { // return name; // } // // public ArrayList<Line> getLines() { // return this.lines; // } // // public int getID() { // return this._id; // } // // public void addReport(Report report) { // this.reportList.add(report); // } // // public ArrayList<Report> getReports() { // ArrayList<Report> res = new ArrayList<>(); // Calendar date = Calendar.getInstance(); // for (Report r : this.reportList) { // if (r.isValid(date)) res.add(r); // } // Collections.reverse(res); // the last is the oldest now. // return res; // } // // public void removeReport(Report rep) { // this.reportList.remove(rep); // } // // public void calcDistanceFromUser(Location user) { // distanceFromUser = user.distanceTo(this.location); // } // // public String getNormalisedName() { // return search_name; // } // // public float getDistanceFromUser() { // return distanceFromUser; // } // // public ArrayList<Stop> getStops(Line line) { // ArrayList<Stop> res = new ArrayList<>(); // for (Stop stop : stops) { // if (stop.getDirection().getLine().getCityway_id() == line.getCityway_id()) { // res.add(stop); // } // } // return res; // } // // public ArrayList<Stop> getStops() { // return stops; // } // // @Override // public String toString() { // return "StopZone{" + // "name='" + name + '\'' + // ", lines=" + lines + // ", stops=" + stops + // '}'; // } // } // Path: app/src/main/java/flying/grub/tamtime/adapter/AllStopReportAdapter.java import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; import flying.grub.tamtime.R; import flying.grub.tamtime.data.map.StopZone; package flying.grub.tamtime.adapter; public class AllStopReportAdapter extends RecyclerView.Adapter<AllStopReportAdapter.ViewHolder> { public OnItemClickListener itemClickListener;
private ArrayList<StopZone> stops;
flyingrub/TamTime
app/src/main/java/flying/grub/tamtime/data/map/TamMap.java
// Path: app/src/main/java/flying/grub/tamtime/data/Data.java // public class Data { // // private static final String TAG = Data.class.getSimpleName(); // // private DisruptEventHandler disruptEventHandler; // private ReportEvent reportEvent; // private RealTimes realTimes; // private TamMap map; // private RealTimeToUpdate toUpdate; // // private static Data data; // // private Data() { // data = this; // } // // public void init(Context context) { // reportEvent = new ReportEvent(context); // disruptEventHandler = new DisruptEventHandler(context); // realTimes = new RealTimes(context); // map = new TamMap(context); // } // // public static synchronized Data getData() { // if (data == null) { // return new Data(); // } else { // return data; // } // } // // public void update() { // if (toUpdate != null) { // if (toUpdate.isLine()) { // realTimes.updateLine(toUpdate.getLine()); // } else { // realTimes.updateStops(toUpdate.getStops()); // } // } // reportEvent.getReports(); // //disruptEventHandler.getReports(); // } // // public DisruptEventHandler getDisruptEventHandler() { // return disruptEventHandler; // } // // public TamMap getMap() { // return map; // } // // public void setToUpdate(RealTimeToUpdate toUpdate) { // this.toUpdate = toUpdate; // update(); // } // // public RealTimes getRealTimes() { // return realTimes; // } // // public ReportEvent getReportEvent() { // return reportEvent; // } // } // // Path: app/src/main/java/flying/grub/tamtime/data/real_time/Time.java // public class Time { // String waitingTime; // int hour; // int minute; // // public Time(String waitingTime, int hour, int minute) { // this.waitingTime = waitingTime; // this.hour = hour; // this.minute = minute; // } // // public String getWaitingTime() { // return waitingTime; // } // }
import android.content.Context; import android.location.Location; import java.text.Normalizer; import java.util.ArrayList; import flying.grub.tamtime.data.Data; import flying.grub.tamtime.data.real_time.Time;
public ArrayList<Line> getLines() { return lines; } public ArrayList<StopZone> getStopZones() { return stopZones; } public StopZone getStopZoneById(int id) { for (StopZone stp : this.stopZones) { if (stp.getID() == id) return stp; } return null; } public ArrayList<StopZone> getAllNearStops() { ArrayList<StopZone> res = new ArrayList<>(); for (StopZone s : stopZones) { if (s.getDistanceFromUser() <= 500) { // in meter res.add(s); } } return res; } public ArrayList<Stop> getStops() { return stops; }
// Path: app/src/main/java/flying/grub/tamtime/data/Data.java // public class Data { // // private static final String TAG = Data.class.getSimpleName(); // // private DisruptEventHandler disruptEventHandler; // private ReportEvent reportEvent; // private RealTimes realTimes; // private TamMap map; // private RealTimeToUpdate toUpdate; // // private static Data data; // // private Data() { // data = this; // } // // public void init(Context context) { // reportEvent = new ReportEvent(context); // disruptEventHandler = new DisruptEventHandler(context); // realTimes = new RealTimes(context); // map = new TamMap(context); // } // // public static synchronized Data getData() { // if (data == null) { // return new Data(); // } else { // return data; // } // } // // public void update() { // if (toUpdate != null) { // if (toUpdate.isLine()) { // realTimes.updateLine(toUpdate.getLine()); // } else { // realTimes.updateStops(toUpdate.getStops()); // } // } // reportEvent.getReports(); // //disruptEventHandler.getReports(); // } // // public DisruptEventHandler getDisruptEventHandler() { // return disruptEventHandler; // } // // public TamMap getMap() { // return map; // } // // public void setToUpdate(RealTimeToUpdate toUpdate) { // this.toUpdate = toUpdate; // update(); // } // // public RealTimes getRealTimes() { // return realTimes; // } // // public ReportEvent getReportEvent() { // return reportEvent; // } // } // // Path: app/src/main/java/flying/grub/tamtime/data/real_time/Time.java // public class Time { // String waitingTime; // int hour; // int minute; // // public Time(String waitingTime, int hour, int minute) { // this.waitingTime = waitingTime; // this.hour = hour; // this.minute = minute; // } // // public String getWaitingTime() { // return waitingTime; // } // } // Path: app/src/main/java/flying/grub/tamtime/data/map/TamMap.java import android.content.Context; import android.location.Location; import java.text.Normalizer; import java.util.ArrayList; import flying.grub.tamtime.data.Data; import flying.grub.tamtime.data.real_time.Time; public ArrayList<Line> getLines() { return lines; } public ArrayList<StopZone> getStopZones() { return stopZones; } public StopZone getStopZoneById(int id) { for (StopZone stp : this.stopZones) { if (stp.getID() == id) return stp; } return null; } public ArrayList<StopZone> getAllNearStops() { ArrayList<StopZone> res = new ArrayList<>(); for (StopZone s : stopZones) { if (s.getDistanceFromUser() <= 500) { // in meter res.add(s); } } return res; } public ArrayList<Stop> getStops() { return stops; }
public void addTimeToStop(int tam_id, int cityway_id, ArrayList<Time> times) {
flyingrub/TamTime
app/src/main/java/flying/grub/tamtime/data/map/TamMap.java
// Path: app/src/main/java/flying/grub/tamtime/data/Data.java // public class Data { // // private static final String TAG = Data.class.getSimpleName(); // // private DisruptEventHandler disruptEventHandler; // private ReportEvent reportEvent; // private RealTimes realTimes; // private TamMap map; // private RealTimeToUpdate toUpdate; // // private static Data data; // // private Data() { // data = this; // } // // public void init(Context context) { // reportEvent = new ReportEvent(context); // disruptEventHandler = new DisruptEventHandler(context); // realTimes = new RealTimes(context); // map = new TamMap(context); // } // // public static synchronized Data getData() { // if (data == null) { // return new Data(); // } else { // return data; // } // } // // public void update() { // if (toUpdate != null) { // if (toUpdate.isLine()) { // realTimes.updateLine(toUpdate.getLine()); // } else { // realTimes.updateStops(toUpdate.getStops()); // } // } // reportEvent.getReports(); // //disruptEventHandler.getReports(); // } // // public DisruptEventHandler getDisruptEventHandler() { // return disruptEventHandler; // } // // public TamMap getMap() { // return map; // } // // public void setToUpdate(RealTimeToUpdate toUpdate) { // this.toUpdate = toUpdate; // update(); // } // // public RealTimes getRealTimes() { // return realTimes; // } // // public ReportEvent getReportEvent() { // return reportEvent; // } // } // // Path: app/src/main/java/flying/grub/tamtime/data/real_time/Time.java // public class Time { // String waitingTime; // int hour; // int minute; // // public Time(String waitingTime, int hour, int minute) { // this.waitingTime = waitingTime; // this.hour = hour; // this.minute = minute; // } // // public String getWaitingTime() { // return waitingTime; // } // }
import android.content.Context; import android.location.Location; import java.text.Normalizer; import java.util.ArrayList; import flying.grub.tamtime.data.Data; import flying.grub.tamtime.data.real_time.Time;
public StopZone getStopZoneById(int id) { for (StopZone stp : this.stopZones) { if (stp.getID() == id) return stp; } return null; } public ArrayList<StopZone> getAllNearStops() { ArrayList<StopZone> res = new ArrayList<>(); for (StopZone s : stopZones) { if (s.getDistanceFromUser() <= 500) { // in meter res.add(s); } } return res; } public ArrayList<Stop> getStops() { return stops; } public void addTimeToStop(int tam_id, int cityway_id, ArrayList<Time> times) { if (tam_id == -1) { addTimeToStopByCitywayId(cityway_id, times); } else { addTimeToStopByTamId(tam_id, times); } } private void addTimeToStopByTamId(int id, ArrayList<Time> times) {
// Path: app/src/main/java/flying/grub/tamtime/data/Data.java // public class Data { // // private static final String TAG = Data.class.getSimpleName(); // // private DisruptEventHandler disruptEventHandler; // private ReportEvent reportEvent; // private RealTimes realTimes; // private TamMap map; // private RealTimeToUpdate toUpdate; // // private static Data data; // // private Data() { // data = this; // } // // public void init(Context context) { // reportEvent = new ReportEvent(context); // disruptEventHandler = new DisruptEventHandler(context); // realTimes = new RealTimes(context); // map = new TamMap(context); // } // // public static synchronized Data getData() { // if (data == null) { // return new Data(); // } else { // return data; // } // } // // public void update() { // if (toUpdate != null) { // if (toUpdate.isLine()) { // realTimes.updateLine(toUpdate.getLine()); // } else { // realTimes.updateStops(toUpdate.getStops()); // } // } // reportEvent.getReports(); // //disruptEventHandler.getReports(); // } // // public DisruptEventHandler getDisruptEventHandler() { // return disruptEventHandler; // } // // public TamMap getMap() { // return map; // } // // public void setToUpdate(RealTimeToUpdate toUpdate) { // this.toUpdate = toUpdate; // update(); // } // // public RealTimes getRealTimes() { // return realTimes; // } // // public ReportEvent getReportEvent() { // return reportEvent; // } // } // // Path: app/src/main/java/flying/grub/tamtime/data/real_time/Time.java // public class Time { // String waitingTime; // int hour; // int minute; // // public Time(String waitingTime, int hour, int minute) { // this.waitingTime = waitingTime; // this.hour = hour; // this.minute = minute; // } // // public String getWaitingTime() { // return waitingTime; // } // } // Path: app/src/main/java/flying/grub/tamtime/data/map/TamMap.java import android.content.Context; import android.location.Location; import java.text.Normalizer; import java.util.ArrayList; import flying.grub.tamtime.data.Data; import flying.grub.tamtime.data.real_time.Time; public StopZone getStopZoneById(int id) { for (StopZone stp : this.stopZones) { if (stp.getID() == id) return stp; } return null; } public ArrayList<StopZone> getAllNearStops() { ArrayList<StopZone> res = new ArrayList<>(); for (StopZone s : stopZones) { if (s.getDistanceFromUser() <= 500) { // in meter res.add(s); } } return res; } public ArrayList<Stop> getStops() { return stops; } public void addTimeToStop(int tam_id, int cityway_id, ArrayList<Time> times) { if (tam_id == -1) { addTimeToStopByCitywayId(cityway_id, times); } else { addTimeToStopByTamId(tam_id, times); } } private void addTimeToStopByTamId(int id, ArrayList<Time> times) {
for (int i = 0; i < Data.getData().getMap().getStops().size(); i++) {
flyingrub/TamTime
app/src/main/java/flying/grub/tamtime/activity/AboutActivity.java
// Path: app/src/main/java/flying/grub/tamtime/layout/Indicator.java // public class Indicator extends View implements ViewPager.OnPageChangeListener { // private Context context; // private float pageNumber; // private int selected; // private static final int SIZE_LARGE = 10; // private static final int SIZE_SMALL = 7; // private static final float PADDING = 40; // // public Indicator(Context context) { // super(context); // this.context = context; // } // // public Indicator(Context context, AttributeSet attrs) { // super(context, attrs); // this.context = context; // } // // public void setPageNumber(int pageNumber) { // this.pageNumber = pageNumber; // } // // @Override // public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // // } // // @Override // public void onPageSelected(int position) { // selected = position; // invalidate(); // } // // @Override // public void onPageScrollStateChanged(int state) { // // } // // @Override // protected void onDraw(Canvas canvas) { // super.onDraw(canvas); // // float center = getWidth()/2; // float height = getHeight(); // float first = center - ((int)pageNumber / 2 ) * PADDING; // if (pageNumber % 2 == 0) { // first += PADDING /2; // } // // Paint paint = new Paint(); // paint.setFlags(Paint.ANTI_ALIAS_FLAG); // paint.setColor(context.getResources().getColor(R.color.windowBackground)); // for (int i = 0; i < pageNumber; i++) { // if (i == selected) { // canvas.drawCircle(first + i * PADDING, height/2, SIZE_LARGE, paint); // } else { // canvas.drawCircle(first + i * PADDING, height/2, SIZE_SMALL, paint); // } // } // } // }
import android.content.Context; import android.os.Bundle; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import flying.grub.tamtime.R; import flying.grub.tamtime.layout.Indicator;
package flying.grub.tamtime.activity; public class AboutActivity extends AppCompatActivity { private ViewPager viewPager;
// Path: app/src/main/java/flying/grub/tamtime/layout/Indicator.java // public class Indicator extends View implements ViewPager.OnPageChangeListener { // private Context context; // private float pageNumber; // private int selected; // private static final int SIZE_LARGE = 10; // private static final int SIZE_SMALL = 7; // private static final float PADDING = 40; // // public Indicator(Context context) { // super(context); // this.context = context; // } // // public Indicator(Context context, AttributeSet attrs) { // super(context, attrs); // this.context = context; // } // // public void setPageNumber(int pageNumber) { // this.pageNumber = pageNumber; // } // // @Override // public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // // } // // @Override // public void onPageSelected(int position) { // selected = position; // invalidate(); // } // // @Override // public void onPageScrollStateChanged(int state) { // // } // // @Override // protected void onDraw(Canvas canvas) { // super.onDraw(canvas); // // float center = getWidth()/2; // float height = getHeight(); // float first = center - ((int)pageNumber / 2 ) * PADDING; // if (pageNumber % 2 == 0) { // first += PADDING /2; // } // // Paint paint = new Paint(); // paint.setFlags(Paint.ANTI_ALIAS_FLAG); // paint.setColor(context.getResources().getColor(R.color.windowBackground)); // for (int i = 0; i < pageNumber; i++) { // if (i == selected) { // canvas.drawCircle(first + i * PADDING, height/2, SIZE_LARGE, paint); // } else { // canvas.drawCircle(first + i * PADDING, height/2, SIZE_SMALL, paint); // } // } // } // } // Path: app/src/main/java/flying/grub/tamtime/activity/AboutActivity.java import android.content.Context; import android.os.Bundle; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import flying.grub.tamtime.R; import flying.grub.tamtime.layout.Indicator; package flying.grub.tamtime.activity; public class AboutActivity extends AppCompatActivity { private ViewPager viewPager;
private Indicator indicator;
flyingrub/TamTime
app/src/main/java/flying/grub/tamtime/adapter/SeachResultAdapter.java
// Path: app/src/main/java/flying/grub/tamtime/data/map/StopZone.java // public class StopZone { // private int _id; // private int cityway_id; // private int tam_id; // private String name; // private String search_name; // private ArrayList<Line> lines; // private ArrayList<Stop> stops; // // private Location location; // private ArrayList<Report> reportList; // private float distanceFromUser; // // public StopZone(String name, int _id, int tam_id, int cityway_id, String search_name, double lat, double lon){ // this.lines = new ArrayList<>(); // this.reportList = new ArrayList<>(); // this.name = name; // this.cityway_id = cityway_id; // this._id = _id; // this.tam_id = tam_id; // this.search_name = search_name; // this.location = new Location(name); // this.location.setLongitude(lon); // this.location.setLatitude(lat); // this.stops = new ArrayList<>(); // } // // public void addLine(Line line) { // if (!this.lines.contains(line)) { // this.lines.add(line); // } // } // // public void addStop(Stop stop) { // this.stops.add(stop); // } // // public String getName() { // return name; // } // // public ArrayList<Line> getLines() { // return this.lines; // } // // public int getID() { // return this._id; // } // // public void addReport(Report report) { // this.reportList.add(report); // } // // public ArrayList<Report> getReports() { // ArrayList<Report> res = new ArrayList<>(); // Calendar date = Calendar.getInstance(); // for (Report r : this.reportList) { // if (r.isValid(date)) res.add(r); // } // Collections.reverse(res); // the last is the oldest now. // return res; // } // // public void removeReport(Report rep) { // this.reportList.remove(rep); // } // // public void calcDistanceFromUser(Location user) { // distanceFromUser = user.distanceTo(this.location); // } // // public String getNormalisedName() { // return search_name; // } // // public float getDistanceFromUser() { // return distanceFromUser; // } // // public ArrayList<Stop> getStops(Line line) { // ArrayList<Stop> res = new ArrayList<>(); // for (Stop stop : stops) { // if (stop.getDirection().getLine().getCityway_id() == line.getCityway_id()) { // res.add(stop); // } // } // return res; // } // // public ArrayList<Stop> getStops() { // return stops; // } // // @Override // public String toString() { // return "StopZone{" + // "name='" + name + '\'' + // ", lines=" + lines + // ", stops=" + stops + // '}'; // } // }
import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import flying.grub.tamtime.R; import flying.grub.tamtime.data.map.StopZone;
package flying.grub.tamtime.adapter; public class SeachResultAdapter extends RecyclerView.Adapter<SeachResultAdapter.ViewHolder> { public OnItemClickListener mItemClickListener;
// Path: app/src/main/java/flying/grub/tamtime/data/map/StopZone.java // public class StopZone { // private int _id; // private int cityway_id; // private int tam_id; // private String name; // private String search_name; // private ArrayList<Line> lines; // private ArrayList<Stop> stops; // // private Location location; // private ArrayList<Report> reportList; // private float distanceFromUser; // // public StopZone(String name, int _id, int tam_id, int cityway_id, String search_name, double lat, double lon){ // this.lines = new ArrayList<>(); // this.reportList = new ArrayList<>(); // this.name = name; // this.cityway_id = cityway_id; // this._id = _id; // this.tam_id = tam_id; // this.search_name = search_name; // this.location = new Location(name); // this.location.setLongitude(lon); // this.location.setLatitude(lat); // this.stops = new ArrayList<>(); // } // // public void addLine(Line line) { // if (!this.lines.contains(line)) { // this.lines.add(line); // } // } // // public void addStop(Stop stop) { // this.stops.add(stop); // } // // public String getName() { // return name; // } // // public ArrayList<Line> getLines() { // return this.lines; // } // // public int getID() { // return this._id; // } // // public void addReport(Report report) { // this.reportList.add(report); // } // // public ArrayList<Report> getReports() { // ArrayList<Report> res = new ArrayList<>(); // Calendar date = Calendar.getInstance(); // for (Report r : this.reportList) { // if (r.isValid(date)) res.add(r); // } // Collections.reverse(res); // the last is the oldest now. // return res; // } // // public void removeReport(Report rep) { // this.reportList.remove(rep); // } // // public void calcDistanceFromUser(Location user) { // distanceFromUser = user.distanceTo(this.location); // } // // public String getNormalisedName() { // return search_name; // } // // public float getDistanceFromUser() { // return distanceFromUser; // } // // public ArrayList<Stop> getStops(Line line) { // ArrayList<Stop> res = new ArrayList<>(); // for (Stop stop : stops) { // if (stop.getDirection().getLine().getCityway_id() == line.getCityway_id()) { // res.add(stop); // } // } // return res; // } // // public ArrayList<Stop> getStops() { // return stops; // } // // @Override // public String toString() { // return "StopZone{" + // "name='" + name + '\'' + // ", lines=" + lines + // ", stops=" + stops + // '}'; // } // } // Path: app/src/main/java/flying/grub/tamtime/adapter/SeachResultAdapter.java import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import flying.grub.tamtime.R; import flying.grub.tamtime.data.map.StopZone; package flying.grub.tamtime.adapter; public class SeachResultAdapter extends RecyclerView.Adapter<SeachResultAdapter.ViewHolder> { public OnItemClickListener mItemClickListener;
private ArrayList<StopZone> stops;
flyingrub/TamTime
app/src/main/java/flying/grub/tamtime/adapter/AllDirectionStopLine.java
// Path: app/src/main/java/flying/grub/tamtime/data/map/Stop.java // public class Stop { // private int _id; // private int cityway_id; // private int tam_id; // private StopZone stopZone; // private Direction direction; // private ArrayList<Time> times; // // public Stop(int _id, int cityway_id, int tam_id, StopZone stopZone, Direction direction) { // this._id = _id; // this.cityway_id = cityway_id; // this.tam_id = tam_id; // this.stopZone = stopZone; // this.direction = direction; // this.times = new ArrayList<>(); // } // // public int get_id() { // return _id; // } // // public int getCityway_id() { // return cityway_id; // } // // public int getTam_id() { // return tam_id; // } // // public Direction getDirection() { // return direction; // } // // public StopZone getStopZone() { // return stopZone; // } // // public ArrayList<Time> getTimes() { // while (times.size() < 3) { // times.add(new Time("-", 0, 0)); // } // return times; // } // // public void setTimes(ArrayList<Time> times) { // this.times = times; // } // // @Override // public String toString() { // return "Stop{" + // "_id=" + _id + // ", cityway_id=" + cityway_id + // ", tam_id=" + tam_id + // ", stopZone=" + stopZone.getName() + // ", direction=" + direction.getName() + // ", times=" + times + // '}'; // } // // } // // Path: app/src/main/java/flying/grub/tamtime/data/real_time/Time.java // public class Time { // String waitingTime; // int hour; // int minute; // // public Time(String waitingTime, int hour, int minute) { // this.waitingTime = waitingTime; // this.hour = hour; // this.minute = minute; // } // // public String getWaitingTime() { // return waitingTime; // } // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import java.util.ArrayList; import flying.grub.tamtime.R; import flying.grub.tamtime.data.map.Stop; import flying.grub.tamtime.data.real_time.Time;
package flying.grub.tamtime.adapter; public class AllDirectionStopLine extends RecyclerView.Adapter<AllDirectionStopLine.ViewHolder> { private static final String TAG = OneRouteAdapter.class.getSimpleName(); public OnItemClickListener mItemClickListener;
// Path: app/src/main/java/flying/grub/tamtime/data/map/Stop.java // public class Stop { // private int _id; // private int cityway_id; // private int tam_id; // private StopZone stopZone; // private Direction direction; // private ArrayList<Time> times; // // public Stop(int _id, int cityway_id, int tam_id, StopZone stopZone, Direction direction) { // this._id = _id; // this.cityway_id = cityway_id; // this.tam_id = tam_id; // this.stopZone = stopZone; // this.direction = direction; // this.times = new ArrayList<>(); // } // // public int get_id() { // return _id; // } // // public int getCityway_id() { // return cityway_id; // } // // public int getTam_id() { // return tam_id; // } // // public Direction getDirection() { // return direction; // } // // public StopZone getStopZone() { // return stopZone; // } // // public ArrayList<Time> getTimes() { // while (times.size() < 3) { // times.add(new Time("-", 0, 0)); // } // return times; // } // // public void setTimes(ArrayList<Time> times) { // this.times = times; // } // // @Override // public String toString() { // return "Stop{" + // "_id=" + _id + // ", cityway_id=" + cityway_id + // ", tam_id=" + tam_id + // ", stopZone=" + stopZone.getName() + // ", direction=" + direction.getName() + // ", times=" + times + // '}'; // } // // } // // Path: app/src/main/java/flying/grub/tamtime/data/real_time/Time.java // public class Time { // String waitingTime; // int hour; // int minute; // // public Time(String waitingTime, int hour, int minute) { // this.waitingTime = waitingTime; // this.hour = hour; // this.minute = minute; // } // // public String getWaitingTime() { // return waitingTime; // } // } // Path: app/src/main/java/flying/grub/tamtime/adapter/AllDirectionStopLine.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import java.util.ArrayList; import flying.grub.tamtime.R; import flying.grub.tamtime.data.map.Stop; import flying.grub.tamtime.data.real_time.Time; package flying.grub.tamtime.adapter; public class AllDirectionStopLine extends RecyclerView.Adapter<AllDirectionStopLine.ViewHolder> { private static final String TAG = OneRouteAdapter.class.getSimpleName(); public OnItemClickListener mItemClickListener;
private ArrayList<Stop> stops;
flyingrub/TamTime
app/src/main/java/flying/grub/tamtime/adapter/AllDirectionStopLine.java
// Path: app/src/main/java/flying/grub/tamtime/data/map/Stop.java // public class Stop { // private int _id; // private int cityway_id; // private int tam_id; // private StopZone stopZone; // private Direction direction; // private ArrayList<Time> times; // // public Stop(int _id, int cityway_id, int tam_id, StopZone stopZone, Direction direction) { // this._id = _id; // this.cityway_id = cityway_id; // this.tam_id = tam_id; // this.stopZone = stopZone; // this.direction = direction; // this.times = new ArrayList<>(); // } // // public int get_id() { // return _id; // } // // public int getCityway_id() { // return cityway_id; // } // // public int getTam_id() { // return tam_id; // } // // public Direction getDirection() { // return direction; // } // // public StopZone getStopZone() { // return stopZone; // } // // public ArrayList<Time> getTimes() { // while (times.size() < 3) { // times.add(new Time("-", 0, 0)); // } // return times; // } // // public void setTimes(ArrayList<Time> times) { // this.times = times; // } // // @Override // public String toString() { // return "Stop{" + // "_id=" + _id + // ", cityway_id=" + cityway_id + // ", tam_id=" + tam_id + // ", stopZone=" + stopZone.getName() + // ", direction=" + direction.getName() + // ", times=" + times + // '}'; // } // // } // // Path: app/src/main/java/flying/grub/tamtime/data/real_time/Time.java // public class Time { // String waitingTime; // int hour; // int minute; // // public Time(String waitingTime, int hour, int minute) { // this.waitingTime = waitingTime; // this.hour = hour; // this.minute = minute; // } // // public String getWaitingTime() { // return waitingTime; // } // }
import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import java.util.ArrayList; import flying.grub.tamtime.R; import flying.grub.tamtime.data.map.Stop; import flying.grub.tamtime.data.real_time.Time;
this.mItemClickListener = mItemClickListener; } public AllDirectionStopLine(ArrayList<Stop> stops, Context context) { this.context = context; this.stops = stops; this.isTheoritical = false; } public AllDirectionStopLine(ArrayList<Stop> stops, Context context, boolean isTheoritical) { this(stops, context); this.isTheoritical = isTheoritical; } @Override public AllDirectionStopLine.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_one_line, parent, false); ViewHolder vh = new ViewHolder(v); return vh; } @Override public void onBindViewHolder(ViewHolder holder, final int position) { // - get element from your dataset at this position // - replace the contents of the view with that element Stop stop = stops.get(position); holder.stop.setText(stop.getDirection().getName());
// Path: app/src/main/java/flying/grub/tamtime/data/map/Stop.java // public class Stop { // private int _id; // private int cityway_id; // private int tam_id; // private StopZone stopZone; // private Direction direction; // private ArrayList<Time> times; // // public Stop(int _id, int cityway_id, int tam_id, StopZone stopZone, Direction direction) { // this._id = _id; // this.cityway_id = cityway_id; // this.tam_id = tam_id; // this.stopZone = stopZone; // this.direction = direction; // this.times = new ArrayList<>(); // } // // public int get_id() { // return _id; // } // // public int getCityway_id() { // return cityway_id; // } // // public int getTam_id() { // return tam_id; // } // // public Direction getDirection() { // return direction; // } // // public StopZone getStopZone() { // return stopZone; // } // // public ArrayList<Time> getTimes() { // while (times.size() < 3) { // times.add(new Time("-", 0, 0)); // } // return times; // } // // public void setTimes(ArrayList<Time> times) { // this.times = times; // } // // @Override // public String toString() { // return "Stop{" + // "_id=" + _id + // ", cityway_id=" + cityway_id + // ", tam_id=" + tam_id + // ", stopZone=" + stopZone.getName() + // ", direction=" + direction.getName() + // ", times=" + times + // '}'; // } // // } // // Path: app/src/main/java/flying/grub/tamtime/data/real_time/Time.java // public class Time { // String waitingTime; // int hour; // int minute; // // public Time(String waitingTime, int hour, int minute) { // this.waitingTime = waitingTime; // this.hour = hour; // this.minute = minute; // } // // public String getWaitingTime() { // return waitingTime; // } // } // Path: app/src/main/java/flying/grub/tamtime/adapter/AllDirectionStopLine.java import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import java.util.ArrayList; import flying.grub.tamtime.R; import flying.grub.tamtime.data.map.Stop; import flying.grub.tamtime.data.real_time.Time; this.mItemClickListener = mItemClickListener; } public AllDirectionStopLine(ArrayList<Stop> stops, Context context) { this.context = context; this.stops = stops; this.isTheoritical = false; } public AllDirectionStopLine(ArrayList<Stop> stops, Context context, boolean isTheoritical) { this(stops, context); this.isTheoritical = isTheoritical; } @Override public AllDirectionStopLine.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_one_line, parent, false); ViewHolder vh = new ViewHolder(v); return vh; } @Override public void onBindViewHolder(ViewHolder holder, final int position) { // - get element from your dataset at this position // - replace the contents of the view with that element Stop stop = stops.get(position); holder.stop.setText(stop.getDirection().getName());
ArrayList<Time> times = stop.getTimes(); // Request 3 next times
flyingrub/TamTime
app/src/main/java/flying/grub/tamtime/data/dirsruption/DisruptEvent.java
// Path: app/src/main/java/flying/grub/tamtime/data/Data.java // public class Data { // // private static final String TAG = Data.class.getSimpleName(); // // private DisruptEventHandler disruptEventHandler; // private ReportEvent reportEvent; // private RealTimes realTimes; // private TamMap map; // private RealTimeToUpdate toUpdate; // // private static Data data; // // private Data() { // data = this; // } // // public void init(Context context) { // reportEvent = new ReportEvent(context); // disruptEventHandler = new DisruptEventHandler(context); // realTimes = new RealTimes(context); // map = new TamMap(context); // } // // public static synchronized Data getData() { // if (data == null) { // return new Data(); // } else { // return data; // } // } // // public void update() { // if (toUpdate != null) { // if (toUpdate.isLine()) { // realTimes.updateLine(toUpdate.getLine()); // } else { // realTimes.updateStops(toUpdate.getStops()); // } // } // reportEvent.getReports(); // //disruptEventHandler.getReports(); // } // // public DisruptEventHandler getDisruptEventHandler() { // return disruptEventHandler; // } // // public TamMap getMap() { // return map; // } // // public void setToUpdate(RealTimeToUpdate toUpdate) { // this.toUpdate = toUpdate; // update(); // } // // public RealTimes getRealTimes() { // return realTimes; // } // // public ReportEvent getReportEvent() { // return reportEvent; // } // } // // Path: app/src/main/java/flying/grub/tamtime/data/map/Line.java // public class Line { // private String shortName; // private int id; // private int tam_id; // private int cityway_id; // private int urbanLine; // private ArrayList<Direction> directions; // // private ArrayList<DisruptEvent> disruptEventList; // // public Line(String shortName, int id, int tamID, int citywayID, int urbanLine) { // this.shortName = shortName; // this.id = id; // this.tam_id = tamID; // this.cityway_id = citywayID; // this.urbanLine = urbanLine; // this.directions = new ArrayList<>(); // this.disruptEventList = new ArrayList<>(); // } // // // Get // public Direction getRoute(String direction){ // for (int i = 0; i< directions.size(); i++){ // if (directions.get(i).equals(direction)) { // return directions.get(i); // } // } // return null; // } // // public int getTam_id() { // return tam_id; // } // // public int getCityway_id() { // // return cityway_id; // } // // public int getUrbanLine() { // // return urbanLine; // } // // @Override // public String toString() { // return "Line{" + // "shortName='" + shortName + '\'' + // ", id=" + id + // ", tam_id=" + tam_id + // ", cityway_id=" + cityway_id + // ", directions=" + directions + // ", disruptEventList=" + disruptEventList + // '}'; // } // // public int getId() { // return id; // } // // public ArrayList<Direction> getDirections() { // return this.directions; // } // // public void addRoute(Direction r) { // this.directions.add(r); // } // // public int getDirectionsCount(){ // return this.directions.size(); // } // // public String getShortName(){ // return this.shortName; // } // // public int getLineNum(){ // return this.id; // } // // public ArrayList<DisruptEvent> getDisruptEventList() { // return disruptEventList; // } // // public void removeDisruptEvent(DisruptEvent event) { // this.disruptEventList.remove(event); // } // // public void addDisruptEvent(DisruptEvent event) { // this.disruptEventList.add(event); // } // }
import java.util.Calendar; import flying.grub.tamtime.data.Data; import flying.grub.tamtime.data.map.Line;
package flying.grub.tamtime.data.dirsruption; public class DisruptEvent { private Line line; private Calendar beginDate; private Calendar endDate; private String title; public DisruptEvent(Line line, Calendar begD, Calendar endD, String title) {
// Path: app/src/main/java/flying/grub/tamtime/data/Data.java // public class Data { // // private static final String TAG = Data.class.getSimpleName(); // // private DisruptEventHandler disruptEventHandler; // private ReportEvent reportEvent; // private RealTimes realTimes; // private TamMap map; // private RealTimeToUpdate toUpdate; // // private static Data data; // // private Data() { // data = this; // } // // public void init(Context context) { // reportEvent = new ReportEvent(context); // disruptEventHandler = new DisruptEventHandler(context); // realTimes = new RealTimes(context); // map = new TamMap(context); // } // // public static synchronized Data getData() { // if (data == null) { // return new Data(); // } else { // return data; // } // } // // public void update() { // if (toUpdate != null) { // if (toUpdate.isLine()) { // realTimes.updateLine(toUpdate.getLine()); // } else { // realTimes.updateStops(toUpdate.getStops()); // } // } // reportEvent.getReports(); // //disruptEventHandler.getReports(); // } // // public DisruptEventHandler getDisruptEventHandler() { // return disruptEventHandler; // } // // public TamMap getMap() { // return map; // } // // public void setToUpdate(RealTimeToUpdate toUpdate) { // this.toUpdate = toUpdate; // update(); // } // // public RealTimes getRealTimes() { // return realTimes; // } // // public ReportEvent getReportEvent() { // return reportEvent; // } // } // // Path: app/src/main/java/flying/grub/tamtime/data/map/Line.java // public class Line { // private String shortName; // private int id; // private int tam_id; // private int cityway_id; // private int urbanLine; // private ArrayList<Direction> directions; // // private ArrayList<DisruptEvent> disruptEventList; // // public Line(String shortName, int id, int tamID, int citywayID, int urbanLine) { // this.shortName = shortName; // this.id = id; // this.tam_id = tamID; // this.cityway_id = citywayID; // this.urbanLine = urbanLine; // this.directions = new ArrayList<>(); // this.disruptEventList = new ArrayList<>(); // } // // // Get // public Direction getRoute(String direction){ // for (int i = 0; i< directions.size(); i++){ // if (directions.get(i).equals(direction)) { // return directions.get(i); // } // } // return null; // } // // public int getTam_id() { // return tam_id; // } // // public int getCityway_id() { // // return cityway_id; // } // // public int getUrbanLine() { // // return urbanLine; // } // // @Override // public String toString() { // return "Line{" + // "shortName='" + shortName + '\'' + // ", id=" + id + // ", tam_id=" + tam_id + // ", cityway_id=" + cityway_id + // ", directions=" + directions + // ", disruptEventList=" + disruptEventList + // '}'; // } // // public int getId() { // return id; // } // // public ArrayList<Direction> getDirections() { // return this.directions; // } // // public void addRoute(Direction r) { // this.directions.add(r); // } // // public int getDirectionsCount(){ // return this.directions.size(); // } // // public String getShortName(){ // return this.shortName; // } // // public int getLineNum(){ // return this.id; // } // // public ArrayList<DisruptEvent> getDisruptEventList() { // return disruptEventList; // } // // public void removeDisruptEvent(DisruptEvent event) { // this.disruptEventList.remove(event); // } // // public void addDisruptEvent(DisruptEvent event) { // this.disruptEventList.add(event); // } // } // Path: app/src/main/java/flying/grub/tamtime/data/dirsruption/DisruptEvent.java import java.util.Calendar; import flying.grub.tamtime.data.Data; import flying.grub.tamtime.data.map.Line; package flying.grub.tamtime.data.dirsruption; public class DisruptEvent { private Line line; private Calendar beginDate; private Calendar endDate; private String title; public DisruptEvent(Line line, Calendar begD, Calendar endD, String title) {
Data.getData().getDisruptEventHandler().addDisruptEvent(this);