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
honeybadger-io/honeybadger-java
honeybadger-java/src/main/java/io/honeybadger/reporter/config/MapConfigContext.java
// Path: honeybadger-java/src/main/java/io/honeybadger/util/HBCollectionUtils.java // public final class HBCollectionUtils { // private HBCollectionUtils() { } // // /** // * Checks a collection to see if it is null or empty. // * @param collection Collection to check // * @return true if null or empty // */ // public static boolean isPresent(final Collection<?> collection) { // return collection != null && !collection.isEmpty(); // } // // /** // * Parses a comma separated string into a collection of values. // * This is not a real CSV parser. This is a toy used for processing // * configuration values that should never have embedded commas or // * quotation marks. // * // * @param csv CSV string input // * @return a collection of values base on CSV // */ // public static Collection<String> parseNaiveCsvString(final String csv) { // if (!HBStringUtils.isPresent(csv)) { // return Collections.emptyList(); // } // // final String[] values = csv.split("(\\s*),(\\s*)"); // return Arrays.asList(values); // } // }
import io.honeybadger.util.HBCollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URI; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set;
if (value instanceof Number) return ((Number)value).intValue(); String port = normalizeEmptyAndNullAndDefaultToStringValue(key); try { return Integer.parseInt(port); } catch (NumberFormatException e) { logger.warn("Error converting system property to integer. Property: {}", key); return null; } } private Set<String> parseCsvStringSetOrPassOnObject(final Object key) { Object value = backingMap.get(key); if (value == null) return null; if (value instanceof Collection) { @SuppressWarnings("unchecked") Collection<String> collection = (Collection<String>)Collections.checkedCollection( (Collection)value, String.class); return new HashSet<>(collection); } if (value instanceof String) { String stringValue = normalizeEmptyAndNullAndDefaultToStringValue(key); if (stringValue == null) return null; HashSet<String> set = new HashSet<>();
// Path: honeybadger-java/src/main/java/io/honeybadger/util/HBCollectionUtils.java // public final class HBCollectionUtils { // private HBCollectionUtils() { } // // /** // * Checks a collection to see if it is null or empty. // * @param collection Collection to check // * @return true if null or empty // */ // public static boolean isPresent(final Collection<?> collection) { // return collection != null && !collection.isEmpty(); // } // // /** // * Parses a comma separated string into a collection of values. // * This is not a real CSV parser. This is a toy used for processing // * configuration values that should never have embedded commas or // * quotation marks. // * // * @param csv CSV string input // * @return a collection of values base on CSV // */ // public static Collection<String> parseNaiveCsvString(final String csv) { // if (!HBStringUtils.isPresent(csv)) { // return Collections.emptyList(); // } // // final String[] values = csv.split("(\\s*),(\\s*)"); // return Arrays.asList(values); // } // } // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/MapConfigContext.java import io.honeybadger.util.HBCollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URI; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; if (value instanceof Number) return ((Number)value).intValue(); String port = normalizeEmptyAndNullAndDefaultToStringValue(key); try { return Integer.parseInt(port); } catch (NumberFormatException e) { logger.warn("Error converting system property to integer. Property: {}", key); return null; } } private Set<String> parseCsvStringSetOrPassOnObject(final Object key) { Object value = backingMap.get(key); if (value == null) return null; if (value instanceof Collection) { @SuppressWarnings("unchecked") Collection<String> collection = (Collection<String>)Collections.checkedCollection( (Collection)value, String.class); return new HashSet<>(collection); } if (value instanceof String) { String stringValue = normalizeEmptyAndNullAndDefaultToStringValue(key); if (stringValue == null) return null; HashSet<String> set = new HashSet<>();
set.addAll(HBCollectionUtils.parseNaiveCsvString(stringValue));
honeybadger-io/honeybadger-java
honeybadger-java/src/main/java/io/honeybadger/reporter/dto/Cause.java
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // }
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import io.honeybadger.reporter.config.ConfigContext; import java.io.Serializable; import java.util.Objects;
package io.honeybadger.reporter.dto; /** * This class represents a single exception in a serious of chained * exceptions. * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ @JsonInclude(JsonInclude.Include.NON_NULL) public class Cause implements Serializable { private static final long serialVersionUID = -6876640270344752492L; @JsonProperty("class") private final String className; private final String message; private final Backtrace backtrace;
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/dto/Cause.java import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import io.honeybadger.reporter.config.ConfigContext; import java.io.Serializable; import java.util.Objects; package io.honeybadger.reporter.dto; /** * This class represents a single exception in a serious of chained * exceptions. * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ @JsonInclude(JsonInclude.Include.NON_NULL) public class Cause implements Serializable { private static final long serialVersionUID = -6876640270344752492L; @JsonProperty("class") private final String className; private final String message; private final Backtrace backtrace;
public Cause(final ConfigContext config, final Throwable error) {
honeybadger-io/honeybadger-java
honeybadger-java/src/main/java/io/honeybadger/reporter/dto/Causes.java
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // }
import com.fasterxml.jackson.annotation.JsonInclude; import io.honeybadger.reporter.config.ConfigContext; import java.io.Serializable; import java.util.LinkedList;
package io.honeybadger.reporter.dto; /** * An ordered collection of chained exceptions. * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ @JsonInclude(JsonInclude.Include.NON_NULL) @SuppressWarnings("JdkObsolete") // Reason: subtle interface change if we change LinkedList to ArrayList public class Causes extends LinkedList<Cause> implements Serializable { private static final long serialVersionUID = -5359764114506595006L; private static final int MAX_CAUSES = 100;
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/dto/Causes.java import com.fasterxml.jackson.annotation.JsonInclude; import io.honeybadger.reporter.config.ConfigContext; import java.io.Serializable; import java.util.LinkedList; package io.honeybadger.reporter.dto; /** * An ordered collection of chained exceptions. * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ @JsonInclude(JsonInclude.Include.NON_NULL) @SuppressWarnings("JdkObsolete") // Reason: subtle interface change if we change LinkedList to ArrayList public class Causes extends LinkedList<Cause> implements Serializable { private static final long serialVersionUID = -5359764114506595006L; private static final int MAX_CAUSES = 100;
public Causes(final ConfigContext config, final Throwable rootError) {
honeybadger-io/honeybadger-java
honeybadger-java/src/main/java/io/honeybadger/reporter/dto/Memory.java
// Path: honeybadger-java/src/main/java/io/honeybadger/util/HBStringUtils.java // public static boolean isPresent(final String string) { // return string != null && !string.isEmpty(); // }
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import org.slf4j.LoggerFactory; import java.io.File; import java.io.Serializable; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.OperatingSystemMXBean; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Scanner; import static io.honeybadger.util.HBStringUtils.isPresent;
@JsonProperty("vm_total") final Number vmTotal, @JsonProperty("vm_heap") final Number vmHeap, @JsonProperty("vm_nonheap") final Number vmNonheap) { this.total = total; this.free = free; this.buffers = buffers; this.cached = cached; this.freeTotal = freeTotal; this.vmFree = vmFree; this.vmMax = vmMax; this.vmTotal = vmTotal; this.vmHeap = vmHeap; this.vmNonheap = vmNonheap; } static Map<String, Long> findLinuxMemInfo(final File memInfoFile) { final HashMap<String, Long> memInfo = new HashMap<>(50); final long mebibyteMultiplier = 1024L; if (memInfoFile.exists() && memInfoFile.isFile() && memInfoFile.canRead()) { try (Scanner scanner = new Scanner(memInfoFile, StandardCharsets.US_ASCII.name())) { while (scanner.hasNext()) { final String line = scanner.nextLine(); final String[] fields = line.split("(:?)\\s+", 3); final String name = fields[0]; final String kbValue = fields[1]; final Long mbValue = Long.parseLong(kbValue) / mebibyteMultiplier;
// Path: honeybadger-java/src/main/java/io/honeybadger/util/HBStringUtils.java // public static boolean isPresent(final String string) { // return string != null && !string.isEmpty(); // } // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/dto/Memory.java import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import org.slf4j.LoggerFactory; import java.io.File; import java.io.Serializable; import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean; import java.lang.management.OperatingSystemMXBean; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Scanner; import static io.honeybadger.util.HBStringUtils.isPresent; @JsonProperty("vm_total") final Number vmTotal, @JsonProperty("vm_heap") final Number vmHeap, @JsonProperty("vm_nonheap") final Number vmNonheap) { this.total = total; this.free = free; this.buffers = buffers; this.cached = cached; this.freeTotal = freeTotal; this.vmFree = vmFree; this.vmMax = vmMax; this.vmTotal = vmTotal; this.vmHeap = vmHeap; this.vmNonheap = vmNonheap; } static Map<String, Long> findLinuxMemInfo(final File memInfoFile) { final HashMap<String, Long> memInfo = new HashMap<>(50); final long mebibyteMultiplier = 1024L; if (memInfoFile.exists() && memInfoFile.isFile() && memInfoFile.canRead()) { try (Scanner scanner = new Scanner(memInfoFile, StandardCharsets.US_ASCII.name())) { while (scanner.hasNext()) { final String line = scanner.nextLine(); final String[] fields = line.split("(:?)\\s+", 3); final String name = fields[0]; final String kbValue = fields[1]; final Long mbValue = Long.parseLong(kbValue) / mebibyteMultiplier;
if (!isPresent(name) || !isPresent(kbValue)) {
honeybadger-io/honeybadger-java
honeybadger-java/src/main/java/io/honeybadger/reporter/dto/Params.java
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // }
import com.fasterxml.jackson.annotation.JacksonInject; import com.fasterxml.jackson.annotation.JsonCreator; import io.honeybadger.reporter.config.ConfigContext; import java.io.Serializable; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set;
package io.honeybadger.reporter.dto; /** * Class representing parameters requested when an exception occurred. * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ public class Params extends LinkedHashMap<String, String> implements Serializable { private static final long serialVersionUID = -5633548926144410598L; private final Set<String> excludedValues; public Params(final Set<String> excludedValues) { this.excludedValues = excludedValues; } @JsonCreator
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/dto/Params.java import com.fasterxml.jackson.annotation.JacksonInject; import com.fasterxml.jackson.annotation.JsonCreator; import io.honeybadger.reporter.config.ConfigContext; import java.io.Serializable; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; package io.honeybadger.reporter.dto; /** * Class representing parameters requested when an exception occurred. * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ public class Params extends LinkedHashMap<String, String> implements Serializable { private static final long serialVersionUID = -5633548926144410598L; private final Set<String> excludedValues; public Params(final Set<String> excludedValues) { this.excludedValues = excludedValues; } @JsonCreator
public Params(final @JacksonInject("config") ConfigContext config) {
honeybadger-io/honeybadger-java
honeybadger-java/src/main/java/io/honeybadger/reporter/NoticeReporter.java
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // }
import io.honeybadger.reporter.config.ConfigContext;
package io.honeybadger.reporter; /** * Interface representing error reporting behavior. * * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ public interface NoticeReporter { /** * Send any Java {@link java.lang.Throwable} to the Honeybadger error * reporting interface. * * @param error error to report * @return UUID of error created, if there was a problem null */ NoticeReportResult reportError(Throwable error); /** * Send any Java {@link java.lang.Throwable} to the Honeybadger error * reporting interface. * * @param error error to report * @param request Object to parse for request properties * @return UUID of error created, if there was a problem or ignored null */ NoticeReportResult reportError(Throwable error, Object request); /** * Send any Java {@link java.lang.Throwable} to the Honeybadger error * reporting interface with the associated tags. * * @param error error to report * @param request Object to parse for request properties * @param message message to report instead of message associated with exception * @return UUID of error created, if there was a problem or ignored null */ NoticeReportResult reportError(Throwable error, Object request, String message); /** * Send any Java {@link java.lang.Throwable} to the Honeybadger error * reporting interface with the associated tags. * * @param error error to report * @param request Object to parse for request properties * @param message message to report instead of message associated with exception * @param tags tag values (duplicates will be removed) * @return UUID of error created, if there was a problem or ignored null */ NoticeReportResult reportError(Throwable error, Object request, String message, Iterable<String> tags); /** * @return The configuration used in the reporter */
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/NoticeReporter.java import io.honeybadger.reporter.config.ConfigContext; package io.honeybadger.reporter; /** * Interface representing error reporting behavior. * * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ public interface NoticeReporter { /** * Send any Java {@link java.lang.Throwable} to the Honeybadger error * reporting interface. * * @param error error to report * @return UUID of error created, if there was a problem null */ NoticeReportResult reportError(Throwable error); /** * Send any Java {@link java.lang.Throwable} to the Honeybadger error * reporting interface. * * @param error error to report * @param request Object to parse for request properties * @return UUID of error created, if there was a problem or ignored null */ NoticeReportResult reportError(Throwable error, Object request); /** * Send any Java {@link java.lang.Throwable} to the Honeybadger error * reporting interface with the associated tags. * * @param error error to report * @param request Object to parse for request properties * @param message message to report instead of message associated with exception * @return UUID of error created, if there was a problem or ignored null */ NoticeReportResult reportError(Throwable error, Object request, String message); /** * Send any Java {@link java.lang.Throwable} to the Honeybadger error * reporting interface with the associated tags. * * @param error error to report * @param request Object to parse for request properties * @param message message to report instead of message associated with exception * @param tags tag values (duplicates will be removed) * @return UUID of error created, if there was a problem or ignored null */ NoticeReportResult reportError(Throwable error, Object request, String message, Iterable<String> tags); /** * @return The configuration used in the reporter */
ConfigContext getConfig();
honeybadger-io/honeybadger-java
honeybadger-java/src/test/java/io/honeybadger/reporter/FeedbackFormTest.java
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/StandardConfigContext.java // public class StandardConfigContext extends BaseChainedConfigContext { // /** // * A new configuration context with default values prepopulated. // */ // public StandardConfigContext() { // super(); // } // // /** // * A new configuration context with default values present, but overwritten // * by the passed map of configuration values. // * // * @param configuration map with keys that correspond to the sys prop keys documented // */ // public StandardConfigContext(final Map<String, ?> configuration) { // super(); // overwriteWithContext(new MapConfigContext(configuration)); // } // // /** // * A new configuration context with the default values present. Only the // * API key is set. // * // * @param apiKey Honeybadger API key // */ // public StandardConfigContext(final String apiKey) { // if (apiKey == null) throw new IllegalArgumentException( // "API key must not be null"); // if (apiKey.isEmpty()) throw new IllegalArgumentException( // "API key must not be empty"); // // setApiKey(apiKey); // } // }
import io.honeybadger.reporter.config.StandardConfigContext; import org.junit.Test; import java.io.StringWriter; import java.util.UUID; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull;
package io.honeybadger.reporter; public class FeedbackFormTest { @Test public void feedbackFormRendersTemplate() throws Exception { StringWriter writer = new StringWriter(); String id = new UUID(12L, 36L).toString();
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/StandardConfigContext.java // public class StandardConfigContext extends BaseChainedConfigContext { // /** // * A new configuration context with default values prepopulated. // */ // public StandardConfigContext() { // super(); // } // // /** // * A new configuration context with default values present, but overwritten // * by the passed map of configuration values. // * // * @param configuration map with keys that correspond to the sys prop keys documented // */ // public StandardConfigContext(final Map<String, ?> configuration) { // super(); // overwriteWithContext(new MapConfigContext(configuration)); // } // // /** // * A new configuration context with the default values present. Only the // * API key is set. // * // * @param apiKey Honeybadger API key // */ // public StandardConfigContext(final String apiKey) { // if (apiKey == null) throw new IllegalArgumentException( // "API key must not be null"); // if (apiKey.isEmpty()) throw new IllegalArgumentException( // "API key must not be empty"); // // setApiKey(apiKey); // } // } // Path: honeybadger-java/src/test/java/io/honeybadger/reporter/FeedbackFormTest.java import io.honeybadger.reporter.config.StandardConfigContext; import org.junit.Test; import java.io.StringWriter; import java.util.UUID; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; package io.honeybadger.reporter; public class FeedbackFormTest { @Test public void feedbackFormRendersTemplate() throws Exception { StringWriter writer = new StringWriter(); String id = new UUID(12L, 36L).toString();
StandardConfigContext config = new StandardConfigContext();
honeybadger-io/honeybadger-java
honeybadger-java/src/main/java/io/honeybadger/reporter/dto/Backtrace.java
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // }
import com.fasterxml.jackson.annotation.JacksonInject; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import io.honeybadger.reporter.config.ConfigContext; import java.io.Serializable; import java.util.ArrayList;
package io.honeybadger.reporter.dto; /** * Class representing an ordered collection of backtrace elements. * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ @JsonInclude(JsonInclude.Include.NON_NULL) public class Backtrace extends ArrayList<BacktraceElement> implements Serializable { private static final long serialVersionUID = 5788866962863555294L;
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/dto/Backtrace.java import com.fasterxml.jackson.annotation.JacksonInject; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import io.honeybadger.reporter.config.ConfigContext; import java.io.Serializable; import java.util.ArrayList; package io.honeybadger.reporter.dto; /** * Class representing an ordered collection of backtrace elements. * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ @JsonInclude(JsonInclude.Include.NON_NULL) public class Backtrace extends ArrayList<BacktraceElement> implements Serializable { private static final long serialVersionUID = 5788866962863555294L;
private final ConfigContext config;
honeybadger-io/honeybadger-java
honeybadger-java/src/main/java/io/honeybadger/reporter/HoneybadgerCLI.java
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/StandardConfigContext.java // public class StandardConfigContext extends BaseChainedConfigContext { // /** // * A new configuration context with default values prepopulated. // */ // public StandardConfigContext() { // super(); // } // // /** // * A new configuration context with default values present, but overwritten // * by the passed map of configuration values. // * // * @param configuration map with keys that correspond to the sys prop keys documented // */ // public StandardConfigContext(final Map<String, ?> configuration) { // super(); // overwriteWithContext(new MapConfigContext(configuration)); // } // // /** // * A new configuration context with the default values present. Only the // * API key is set. // * // * @param apiKey Honeybadger API key // */ // public StandardConfigContext(final String apiKey) { // if (apiKey == null) throw new IllegalArgumentException( // "API key must not be null"); // if (apiKey.isEmpty()) throw new IllegalArgumentException( // "API key must not be empty"); // // setApiKey(apiKey); // } // }
import io.honeybadger.reporter.config.StandardConfigContext; import java.util.ArrayList; import java.util.List; import java.util.Scanner;
package io.honeybadger.reporter; /** * Simple CLI utility that will allow you to post an error message to * Honeybadger. * * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.0 */ public final class HoneybadgerCLI { private HoneybadgerCLI() { } @SuppressWarnings("DefaultCharset") public static void main(final String[] argv) { Scanner in = new Scanner(System.in); System.out.print("What is your Honeybadger API key: ");
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/StandardConfigContext.java // public class StandardConfigContext extends BaseChainedConfigContext { // /** // * A new configuration context with default values prepopulated. // */ // public StandardConfigContext() { // super(); // } // // /** // * A new configuration context with default values present, but overwritten // * by the passed map of configuration values. // * // * @param configuration map with keys that correspond to the sys prop keys documented // */ // public StandardConfigContext(final Map<String, ?> configuration) { // super(); // overwriteWithContext(new MapConfigContext(configuration)); // } // // /** // * A new configuration context with the default values present. Only the // * API key is set. // * // * @param apiKey Honeybadger API key // */ // public StandardConfigContext(final String apiKey) { // if (apiKey == null) throw new IllegalArgumentException( // "API key must not be null"); // if (apiKey.isEmpty()) throw new IllegalArgumentException( // "API key must not be empty"); // // setApiKey(apiKey); // } // } // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/HoneybadgerCLI.java import io.honeybadger.reporter.config.StandardConfigContext; import java.util.ArrayList; import java.util.List; import java.util.Scanner; package io.honeybadger.reporter; /** * Simple CLI utility that will allow you to post an error message to * Honeybadger. * * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.0 */ public final class HoneybadgerCLI { private HoneybadgerCLI() { } @SuppressWarnings("DefaultCharset") public static void main(final String[] argv) { Scanner in = new Scanner(System.in); System.out.print("What is your Honeybadger API key: ");
StandardConfigContext config = new StandardConfigContext();
honeybadger-io/honeybadger-java
honeybadger-java/src/main/java/io/honeybadger/reporter/dto/Details.java
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // }
import com.fasterxml.jackson.annotation.JacksonInject; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import io.honeybadger.reporter.config.ConfigContext; import org.slf4j.MDC; import java.io.Serializable; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.TreeMap;
package io.honeybadger.reporter.dto; /** * Class representing metadata and run-time state. * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ @JsonInclude(JsonInclude.Include.NON_NULL) public class Details extends LinkedHashMap<String, Map<String, String>> implements Serializable { private static final long serialVersionUID = -6238693264237448645L;
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/dto/Details.java import com.fasterxml.jackson.annotation.JacksonInject; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import io.honeybadger.reporter.config.ConfigContext; import org.slf4j.MDC; import java.io.Serializable; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.TreeMap; package io.honeybadger.reporter.dto; /** * Class representing metadata and run-time state. * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ @JsonInclude(JsonInclude.Include.NON_NULL) public class Details extends LinkedHashMap<String, Map<String, String>> implements Serializable { private static final long serialVersionUID = -6238693264237448645L;
private final ConfigContext config;
honeybadger-io/honeybadger-java
honeybadger-java/src/main/java/io/honeybadger/reporter/NoticeReportResult.java
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/dto/Notice.java // @JsonInclude(JsonInclude.Include.NON_NULL) // @JsonIgnoreProperties({"environment", "created_at", "message", "token", "fault_id", // "application_trace", "backtrace", "deploy", "url"}) // public class Notice implements Serializable { // private static final long serialVersionUID = 1661111694538362413L; // private Long id = null; // private final ConfigContext config; // // private Notifier notifier = new Notifier(); // private ServerDetails server; // private Details details; // // This is defined as serializable so that it can use APIs that the // // implementers may not have available like the Servlet API // private Request request; // private NoticeDetails error; // // public Notice(final ConfigContext config) { // this.config = config; // this.server = new ServerDetails(config); // this.details = new Details(this.config); // this.details.addDefaultDetails(); // } // // @JsonCreator // public Notice(@JacksonInject("config") final ConfigContext config, // @JsonProperty("id") final Long id, // @JsonProperty("web_environment") final CgiData webEnvironment, // @JsonProperty("request") final Request request) { // this.config = config; // this.id = id; // this.server = new ServerDetails(config); // this.request = request; // this.request.setCgiData(webEnvironment); // } // // public Notifier getNotifier() { // return notifier; // } // // public Notice setNotifier(final Notifier notifier) { // this.notifier = notifier; // return this; // } // // public NoticeDetails getError() { // return error; // } // // public Notice setError(final NoticeDetails error) { // this.error = error; // return this; // } // // public Notice setServer(final ServerDetails server) { // this.server = server; // return this; // } // // public ServerDetails getServer() { // return server; // } // // public Details getDetails() { // return details; // } // // public Notice setDetails(final Details details) { // this.details = details; // return this; // } // // public Request getRequest() { // return request; // } // // public Notice setRequest(final Request request) { // this.request = request; // return this; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || !(o instanceof Notice)) return false; // Notice notice = (Notice) o; // return Objects.equals(config, notice.config) && // Objects.equals(notifier, notice.notifier) && // Objects.equals(server, notice.server) && // Objects.equals(details, notice.details) && // Objects.equals(request, notice.request) && // Objects.equals(error, notice.error); // } // // @Override // public int hashCode() { // return Objects.hash(config, notifier, server, details, request, error); // } // // public Long getId() { // return id; // } // }
import io.honeybadger.reporter.dto.Notice; import java.util.Objects; import java.util.UUID;
package io.honeybadger.reporter; /** * Data object representing that results of an error submission to the * Honeybadger API. */ public class NoticeReportResult { private final UUID id;
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/dto/Notice.java // @JsonInclude(JsonInclude.Include.NON_NULL) // @JsonIgnoreProperties({"environment", "created_at", "message", "token", "fault_id", // "application_trace", "backtrace", "deploy", "url"}) // public class Notice implements Serializable { // private static final long serialVersionUID = 1661111694538362413L; // private Long id = null; // private final ConfigContext config; // // private Notifier notifier = new Notifier(); // private ServerDetails server; // private Details details; // // This is defined as serializable so that it can use APIs that the // // implementers may not have available like the Servlet API // private Request request; // private NoticeDetails error; // // public Notice(final ConfigContext config) { // this.config = config; // this.server = new ServerDetails(config); // this.details = new Details(this.config); // this.details.addDefaultDetails(); // } // // @JsonCreator // public Notice(@JacksonInject("config") final ConfigContext config, // @JsonProperty("id") final Long id, // @JsonProperty("web_environment") final CgiData webEnvironment, // @JsonProperty("request") final Request request) { // this.config = config; // this.id = id; // this.server = new ServerDetails(config); // this.request = request; // this.request.setCgiData(webEnvironment); // } // // public Notifier getNotifier() { // return notifier; // } // // public Notice setNotifier(final Notifier notifier) { // this.notifier = notifier; // return this; // } // // public NoticeDetails getError() { // return error; // } // // public Notice setError(final NoticeDetails error) { // this.error = error; // return this; // } // // public Notice setServer(final ServerDetails server) { // this.server = server; // return this; // } // // public ServerDetails getServer() { // return server; // } // // public Details getDetails() { // return details; // } // // public Notice setDetails(final Details details) { // this.details = details; // return this; // } // // public Request getRequest() { // return request; // } // // public Notice setRequest(final Request request) { // this.request = request; // return this; // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || !(o instanceof Notice)) return false; // Notice notice = (Notice) o; // return Objects.equals(config, notice.config) && // Objects.equals(notifier, notice.notifier) && // Objects.equals(server, notice.server) && // Objects.equals(details, notice.details) && // Objects.equals(request, notice.request) && // Objects.equals(error, notice.error); // } // // @Override // public int hashCode() { // return Objects.hash(config, notifier, server, details, request, error); // } // // public Long getId() { // return id; // } // } // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/NoticeReportResult.java import io.honeybadger.reporter.dto.Notice; import java.util.Objects; import java.util.UUID; package io.honeybadger.reporter; /** * Data object representing that results of an error submission to the * Honeybadger API. */ public class NoticeReportResult { private final UUID id;
private final Notice notice;
honeybadger-io/honeybadger-java
honeybadger-java/src/test/java/io/honeybadger/reporter/util/HBCollectionUtilsTest.java
// Path: honeybadger-java/src/main/java/io/honeybadger/util/HBCollectionUtils.java // public final class HBCollectionUtils { // private HBCollectionUtils() { } // // /** // * Checks a collection to see if it is null or empty. // * @param collection Collection to check // * @return true if null or empty // */ // public static boolean isPresent(final Collection<?> collection) { // return collection != null && !collection.isEmpty(); // } // // /** // * Parses a comma separated string into a collection of values. // * This is not a real CSV parser. This is a toy used for processing // * configuration values that should never have embedded commas or // * quotation marks. // * // * @param csv CSV string input // * @return a collection of values base on CSV // */ // public static Collection<String> parseNaiveCsvString(final String csv) { // if (!HBStringUtils.isPresent(csv)) { // return Collections.emptyList(); // } // // final String[] values = csv.split("(\\s*),(\\s*)"); // return Arrays.asList(values); // } // }
import io.honeybadger.util.HBCollectionUtils; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
package io.honeybadger.reporter.util; public class HBCollectionUtilsTest { @Test public void canParseEmptyCSV() { String csv = "";
// Path: honeybadger-java/src/main/java/io/honeybadger/util/HBCollectionUtils.java // public final class HBCollectionUtils { // private HBCollectionUtils() { } // // /** // * Checks a collection to see if it is null or empty. // * @param collection Collection to check // * @return true if null or empty // */ // public static boolean isPresent(final Collection<?> collection) { // return collection != null && !collection.isEmpty(); // } // // /** // * Parses a comma separated string into a collection of values. // * This is not a real CSV parser. This is a toy used for processing // * configuration values that should never have embedded commas or // * quotation marks. // * // * @param csv CSV string input // * @return a collection of values base on CSV // */ // public static Collection<String> parseNaiveCsvString(final String csv) { // if (!HBStringUtils.isPresent(csv)) { // return Collections.emptyList(); // } // // final String[] values = csv.split("(\\s*),(\\s*)"); // return Arrays.asList(values); // } // } // Path: honeybadger-java/src/test/java/io/honeybadger/reporter/util/HBCollectionUtilsTest.java import io.honeybadger.util.HBCollectionUtils; import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; package io.honeybadger.reporter.util; public class HBCollectionUtilsTest { @Test public void canParseEmptyCSV() { String csv = "";
Collection<String> actual = HBCollectionUtils.parseNaiveCsvString(csv);
honeybadger-io/honeybadger-java
honeybadger-java/src/main/java/io/honeybadger/reporter/dto/PlayHttpRequestFactory.java
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // }
import io.honeybadger.reporter.config.ConfigContext; import org.apache.http.HttpHeaders; import play.mvc.Http; import play.mvc.Security; import java.util.Iterator; import java.util.Optional;
package io.honeybadger.reporter.dto; /** * Factory class that creates a {@link Request} based on a * {@link play.mvc.Http.Request}. * * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ public final class PlayHttpRequestFactory { private PlayHttpRequestFactory() { }
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/dto/PlayHttpRequestFactory.java import io.honeybadger.reporter.config.ConfigContext; import org.apache.http.HttpHeaders; import play.mvc.Http; import play.mvc.Security; import java.util.Iterator; import java.util.Optional; package io.honeybadger.reporter.dto; /** * Factory class that creates a {@link Request} based on a * {@link play.mvc.Http.Request}. * * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ public final class PlayHttpRequestFactory { private PlayHttpRequestFactory() { }
public static Request create(final ConfigContext config,
honeybadger-io/honeybadger-java
honeybadger-java/src/test/java/io/honeybadger/reporter/dto/BacktraceElementTest.java
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // }
import io.honeybadger.reporter.config.ConfigContext; import org.junit.Test; import javax.annotation.concurrent.NotThreadSafe; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package io.honeybadger.reporter.dto; @NotThreadSafe public class BacktraceElementTest { private final static String METHOD_NAME = "io.honeybadger.dog.food.ClassName:methodName"; private final static String APP_PACKAGE = "io.honeybadger"; @Test public void canCalculateContextWhenNoAppPackageIsSet() {
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // Path: honeybadger-java/src/test/java/io/honeybadger/reporter/dto/BacktraceElementTest.java import io.honeybadger.reporter.config.ConfigContext; import org.junit.Test; import javax.annotation.concurrent.NotThreadSafe; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package io.honeybadger.reporter.dto; @NotThreadSafe public class BacktraceElementTest { private final static String METHOD_NAME = "io.honeybadger.dog.food.ClassName:methodName"; private final static String APP_PACKAGE = "io.honeybadger"; @Test public void canCalculateContextWhenNoAppPackageIsSet() {
ConfigContext config = mock(ConfigContext.class);
honeybadger-io/honeybadger-java
honeybadger-java/src/test/java/io/honeybadger/reporter/HoneyBadgerReporterTest.java
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/SystemSettingsConfigContext.java // public class SystemSettingsConfigContext extends BaseChainedConfigContext { // /** // * Populate configuration from defaults, environment variables and system // * properties. // */ // public SystemSettingsConfigContext() { // // load defaults // super(); // // overwrite with environment variables // overwriteWithContext(new MapConfigContext(System.getenv())); // // overwrite with system properties // overwriteWithContext(new MapConfigContext(System.getProperties())); // } // // /** // * Populate configuration from defaults, environment variables, system // * properties and an addition context passed in. // * // * @param context additional context to layer on top // */ // public SystemSettingsConfigContext(final ConfigContext context) { // // load all of the chained defaults // this(); // // now load in an additional context // overwriteWithContext(context); // } // } // // Path: honeybadger-java/src/test/java/org/apache/http/client/fluent/FakeResponse.java // public class FakeResponse extends Response { // public FakeResponse(HttpResponse httpResponse) { // super(httpResponse); // } // }
import io.honeybadger.reporter.config.ConfigContext; import io.honeybadger.reporter.config.SystemSettingsConfigContext; import org.apache.http.HttpVersion; import org.apache.http.client.fluent.FakeResponse; import org.apache.http.client.fluent.Response; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.protocol.BasicHttpContext; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import static org.junit.Assert.assertEquals;
package io.honeybadger.reporter; public class HoneyBadgerReporterTest { private final Logger logger = LoggerFactory.getLogger(getClass()); class ExceptionThrowingReporter extends HoneybadgerReporter { int attemptCount = 0;
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/SystemSettingsConfigContext.java // public class SystemSettingsConfigContext extends BaseChainedConfigContext { // /** // * Populate configuration from defaults, environment variables and system // * properties. // */ // public SystemSettingsConfigContext() { // // load defaults // super(); // // overwrite with environment variables // overwriteWithContext(new MapConfigContext(System.getenv())); // // overwrite with system properties // overwriteWithContext(new MapConfigContext(System.getProperties())); // } // // /** // * Populate configuration from defaults, environment variables, system // * properties and an addition context passed in. // * // * @param context additional context to layer on top // */ // public SystemSettingsConfigContext(final ConfigContext context) { // // load all of the chained defaults // this(); // // now load in an additional context // overwriteWithContext(context); // } // } // // Path: honeybadger-java/src/test/java/org/apache/http/client/fluent/FakeResponse.java // public class FakeResponse extends Response { // public FakeResponse(HttpResponse httpResponse) { // super(httpResponse); // } // } // Path: honeybadger-java/src/test/java/io/honeybadger/reporter/HoneyBadgerReporterTest.java import io.honeybadger.reporter.config.ConfigContext; import io.honeybadger.reporter.config.SystemSettingsConfigContext; import org.apache.http.HttpVersion; import org.apache.http.client.fluent.FakeResponse; import org.apache.http.client.fluent.Response; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.protocol.BasicHttpContext; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import static org.junit.Assert.assertEquals; package io.honeybadger.reporter; public class HoneyBadgerReporterTest { private final Logger logger = LoggerFactory.getLogger(getClass()); class ExceptionThrowingReporter extends HoneybadgerReporter { int attemptCount = 0;
public ExceptionThrowingReporter(ConfigContext configContext) {
honeybadger-io/honeybadger-java
honeybadger-java/src/test/java/io/honeybadger/reporter/HoneyBadgerReporterTest.java
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/SystemSettingsConfigContext.java // public class SystemSettingsConfigContext extends BaseChainedConfigContext { // /** // * Populate configuration from defaults, environment variables and system // * properties. // */ // public SystemSettingsConfigContext() { // // load defaults // super(); // // overwrite with environment variables // overwriteWithContext(new MapConfigContext(System.getenv())); // // overwrite with system properties // overwriteWithContext(new MapConfigContext(System.getProperties())); // } // // /** // * Populate configuration from defaults, environment variables, system // * properties and an addition context passed in. // * // * @param context additional context to layer on top // */ // public SystemSettingsConfigContext(final ConfigContext context) { // // load all of the chained defaults // this(); // // now load in an additional context // overwriteWithContext(context); // } // } // // Path: honeybadger-java/src/test/java/org/apache/http/client/fluent/FakeResponse.java // public class FakeResponse extends Response { // public FakeResponse(HttpResponse httpResponse) { // super(httpResponse); // } // }
import io.honeybadger.reporter.config.ConfigContext; import io.honeybadger.reporter.config.SystemSettingsConfigContext; import org.apache.http.HttpVersion; import org.apache.http.client.fluent.FakeResponse; import org.apache.http.client.fluent.Response; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.protocol.BasicHttpContext; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import static org.junit.Assert.assertEquals;
package io.honeybadger.reporter; public class HoneyBadgerReporterTest { private final Logger logger = LoggerFactory.getLogger(getClass()); class ExceptionThrowingReporter extends HoneybadgerReporter { int attemptCount = 0; public ExceptionThrowingReporter(ConfigContext configContext) { super(configContext); } @Override protected Response sendToHoneybadger(final String jsonError) throws IOException { attemptCount = attemptCount + 1; logger.info("We Tried: " + attemptCount); throw new IOException("staged IO exception"); } } class BadResponseGivingReporter extends HoneybadgerReporter { int attemptCount = 0; public BadResponseGivingReporter(ConfigContext configContext) { super(configContext); } @Override protected Response sendToHoneybadger(final String jsonError) throws IOException { attemptCount = attemptCount + 1; logger.info("We Tried: " + attemptCount);
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/SystemSettingsConfigContext.java // public class SystemSettingsConfigContext extends BaseChainedConfigContext { // /** // * Populate configuration from defaults, environment variables and system // * properties. // */ // public SystemSettingsConfigContext() { // // load defaults // super(); // // overwrite with environment variables // overwriteWithContext(new MapConfigContext(System.getenv())); // // overwrite with system properties // overwriteWithContext(new MapConfigContext(System.getProperties())); // } // // /** // * Populate configuration from defaults, environment variables, system // * properties and an addition context passed in. // * // * @param context additional context to layer on top // */ // public SystemSettingsConfigContext(final ConfigContext context) { // // load all of the chained defaults // this(); // // now load in an additional context // overwriteWithContext(context); // } // } // // Path: honeybadger-java/src/test/java/org/apache/http/client/fluent/FakeResponse.java // public class FakeResponse extends Response { // public FakeResponse(HttpResponse httpResponse) { // super(httpResponse); // } // } // Path: honeybadger-java/src/test/java/io/honeybadger/reporter/HoneyBadgerReporterTest.java import io.honeybadger.reporter.config.ConfigContext; import io.honeybadger.reporter.config.SystemSettingsConfigContext; import org.apache.http.HttpVersion; import org.apache.http.client.fluent.FakeResponse; import org.apache.http.client.fluent.Response; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.protocol.BasicHttpContext; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import static org.junit.Assert.assertEquals; package io.honeybadger.reporter; public class HoneyBadgerReporterTest { private final Logger logger = LoggerFactory.getLogger(getClass()); class ExceptionThrowingReporter extends HoneybadgerReporter { int attemptCount = 0; public ExceptionThrowingReporter(ConfigContext configContext) { super(configContext); } @Override protected Response sendToHoneybadger(final String jsonError) throws IOException { attemptCount = attemptCount + 1; logger.info("We Tried: " + attemptCount); throw new IOException("staged IO exception"); } } class BadResponseGivingReporter extends HoneybadgerReporter { int attemptCount = 0; public BadResponseGivingReporter(ConfigContext configContext) { super(configContext); } @Override protected Response sendToHoneybadger(final String jsonError) throws IOException { attemptCount = attemptCount + 1; logger.info("We Tried: " + attemptCount);
return new FakeResponse(
honeybadger-io/honeybadger-java
honeybadger-java/src/test/java/io/honeybadger/reporter/HoneyBadgerReporterTest.java
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/SystemSettingsConfigContext.java // public class SystemSettingsConfigContext extends BaseChainedConfigContext { // /** // * Populate configuration from defaults, environment variables and system // * properties. // */ // public SystemSettingsConfigContext() { // // load defaults // super(); // // overwrite with environment variables // overwriteWithContext(new MapConfigContext(System.getenv())); // // overwrite with system properties // overwriteWithContext(new MapConfigContext(System.getProperties())); // } // // /** // * Populate configuration from defaults, environment variables, system // * properties and an addition context passed in. // * // * @param context additional context to layer on top // */ // public SystemSettingsConfigContext(final ConfigContext context) { // // load all of the chained defaults // this(); // // now load in an additional context // overwriteWithContext(context); // } // } // // Path: honeybadger-java/src/test/java/org/apache/http/client/fluent/FakeResponse.java // public class FakeResponse extends Response { // public FakeResponse(HttpResponse httpResponse) { // super(httpResponse); // } // }
import io.honeybadger.reporter.config.ConfigContext; import io.honeybadger.reporter.config.SystemSettingsConfigContext; import org.apache.http.HttpVersion; import org.apache.http.client.fluent.FakeResponse; import org.apache.http.client.fluent.Response; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.protocol.BasicHttpContext; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import static org.junit.Assert.assertEquals;
attemptCount = attemptCount + 1; logger.info("We Tried: " + attemptCount); throw new IOException("staged IO exception"); } } class BadResponseGivingReporter extends HoneybadgerReporter { int attemptCount = 0; public BadResponseGivingReporter(ConfigContext configContext) { super(configContext); } @Override protected Response sendToHoneybadger(final String jsonError) throws IOException { attemptCount = attemptCount + 1; logger.info("We Tried: " + attemptCount); return new FakeResponse( new DefaultHttpResponseFactory().newHttpResponse( HttpVersion.HTTP_1_1, 500, new BasicHttpContext() ) ); } } @Test public void retriesUpTo3TimesWithDefaultConfig() throws Exception {
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/SystemSettingsConfigContext.java // public class SystemSettingsConfigContext extends BaseChainedConfigContext { // /** // * Populate configuration from defaults, environment variables and system // * properties. // */ // public SystemSettingsConfigContext() { // // load defaults // super(); // // overwrite with environment variables // overwriteWithContext(new MapConfigContext(System.getenv())); // // overwrite with system properties // overwriteWithContext(new MapConfigContext(System.getProperties())); // } // // /** // * Populate configuration from defaults, environment variables, system // * properties and an addition context passed in. // * // * @param context additional context to layer on top // */ // public SystemSettingsConfigContext(final ConfigContext context) { // // load all of the chained defaults // this(); // // now load in an additional context // overwriteWithContext(context); // } // } // // Path: honeybadger-java/src/test/java/org/apache/http/client/fluent/FakeResponse.java // public class FakeResponse extends Response { // public FakeResponse(HttpResponse httpResponse) { // super(httpResponse); // } // } // Path: honeybadger-java/src/test/java/io/honeybadger/reporter/HoneyBadgerReporterTest.java import io.honeybadger.reporter.config.ConfigContext; import io.honeybadger.reporter.config.SystemSettingsConfigContext; import org.apache.http.HttpVersion; import org.apache.http.client.fluent.FakeResponse; import org.apache.http.client.fluent.Response; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.protocol.BasicHttpContext; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import static org.junit.Assert.assertEquals; attemptCount = attemptCount + 1; logger.info("We Tried: " + attemptCount); throw new IOException("staged IO exception"); } } class BadResponseGivingReporter extends HoneybadgerReporter { int attemptCount = 0; public BadResponseGivingReporter(ConfigContext configContext) { super(configContext); } @Override protected Response sendToHoneybadger(final String jsonError) throws IOException { attemptCount = attemptCount + 1; logger.info("We Tried: " + attemptCount); return new FakeResponse( new DefaultHttpResponseFactory().newHttpResponse( HttpVersion.HTTP_1_1, 500, new BasicHttpContext() ) ); } } @Test public void retriesUpTo3TimesWithDefaultConfig() throws Exception {
ConfigContext config = new SystemSettingsConfigContext().setApiKey("dummy");
honeybadger-io/honeybadger-java
honeybadger-java/src/main/java/io/honeybadger/reporter/dto/ServerDetails.java
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // }
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.honeybadger.reporter.config.ConfigContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.lang.management.ManagementFactory; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Objects; import java.util.TimeZone;
package io.honeybadger.reporter.dto; /** * Server details at the time an error occurred. * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"environment_name", "hostname", "project_root", "pid", "time", "stats", ""}) public class ServerDetails implements Serializable { private static final long serialVersionUID = 4689643321013504425L; private static Logger logger = LoggerFactory.getLogger(ServerDetails.class); @JsonProperty("environment_name") private final String environmentName; private final String hostname; @JsonProperty("project_root") private final String projectRoot; private final Integer pid; private final String time; private final Stats stats;
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/dto/ServerDetails.java import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.honeybadger.reporter.config.ConfigContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.lang.management.ManagementFactory; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Objects; import java.util.TimeZone; package io.honeybadger.reporter.dto; /** * Server details at the time an error occurred. * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"environment_name", "hostname", "project_root", "pid", "time", "stats", ""}) public class ServerDetails implements Serializable { private static final long serialVersionUID = 4689643321013504425L; private static Logger logger = LoggerFactory.getLogger(ServerDetails.class); @JsonProperty("environment_name") private final String environmentName; private final String hostname; @JsonProperty("project_root") private final String projectRoot; private final Integer pid; private final String time; private final Stats stats;
public ServerDetails(final ConfigContext context) {
honeybadger-io/honeybadger-java
honeybadger-java/src/test/java/io/honeybadger/reporter/util/HBStringUtilsTest.java
// Path: honeybadger-java/src/main/java/io/honeybadger/util/HBStringUtils.java // public final class HBStringUtils { // private HBStringUtils() { } // // /** // * Removes a single character from the end of a string if it matches. // * @param input String to remove from, if null returns null // * @param c character to match // * @return Original string minus matched character // */ // public static String stripTrailingChar(final String input, final char c) { // if (input == null) return null; // if (input.isEmpty()) return input; // // char[] charArray = input.toCharArray(); // // if (charArray[charArray.length - 1] == c) { // return new String(Arrays.copyOf(charArray, charArray.length - 1)); // } else { // return input; // } // } // // /** // * Checks a string to see if it is null or empty. // * @param string String to check // * @return true if null or empty // */ // public static boolean isPresent(final String string) { // return string != null && !string.isEmpty(); // } // }
import io.honeybadger.util.HBStringUtils; import org.junit.Test; import static org.junit.Assert.assertEquals;
package io.honeybadger.reporter.util; public class HBStringUtilsTest { @Test public void canTrimTrailingDot() { String instance = "foo.";
// Path: honeybadger-java/src/main/java/io/honeybadger/util/HBStringUtils.java // public final class HBStringUtils { // private HBStringUtils() { } // // /** // * Removes a single character from the end of a string if it matches. // * @param input String to remove from, if null returns null // * @param c character to match // * @return Original string minus matched character // */ // public static String stripTrailingChar(final String input, final char c) { // if (input == null) return null; // if (input.isEmpty()) return input; // // char[] charArray = input.toCharArray(); // // if (charArray[charArray.length - 1] == c) { // return new String(Arrays.copyOf(charArray, charArray.length - 1)); // } else { // return input; // } // } // // /** // * Checks a string to see if it is null or empty. // * @param string String to check // * @return true if null or empty // */ // public static boolean isPresent(final String string) { // return string != null && !string.isEmpty(); // } // } // Path: honeybadger-java/src/test/java/io/honeybadger/reporter/util/HBStringUtilsTest.java import io.honeybadger.util.HBStringUtils; import org.junit.Test; import static org.junit.Assert.assertEquals; package io.honeybadger.reporter.util; public class HBStringUtilsTest { @Test public void canTrimTrailingDot() { String instance = "foo.";
String out = HBStringUtils.stripTrailingChar(instance, '.');
honeybadger-io/honeybadger-java
honeybadger-java/src/main/java/io/honeybadger/reporter/dto/HttpServletRequestFactory.java
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // }
import io.honeybadger.reporter.config.ConfigContext; import org.apache.http.HttpHeaders; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.security.Principal; import java.util.Enumeration;
package io.honeybadger.reporter.dto; /** * Factory class that creates a {@link Request} based on a * {@link javax.servlet.http.HttpServletRequest}. * * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ public final class HttpServletRequestFactory { private HttpServletRequestFactory() { }
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/dto/HttpServletRequestFactory.java import io.honeybadger.reporter.config.ConfigContext; import org.apache.http.HttpHeaders; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.security.Principal; import java.util.Enumeration; package io.honeybadger.reporter.dto; /** * Factory class that creates a {@link Request} based on a * {@link javax.servlet.http.HttpServletRequest}. * * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ public final class HttpServletRequestFactory { private HttpServletRequestFactory() { }
public static Request create(final ConfigContext config,
honeybadger-io/honeybadger-java
honeybadger-java/src/main/java/io/honeybadger/reporter/dto/BacktraceElement.java
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // }
import com.fasterxml.jackson.annotation.JacksonInject; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import io.honeybadger.reporter.config.ConfigContext; import java.io.Serializable; import java.util.Objects;
package io.honeybadger.reporter.dto; /** * One single line on a backtrace. * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ @JsonInclude(JsonInclude.Include.NON_NULL) public class BacktraceElement implements Serializable { private static final long serialVersionUID = -4455225669072193184L; /** * Enum representing all of the valid context values on the Honeybadger API. */ enum Context { /** Backtrace not-belonging to the calling application. **/ ALL("all"), /** Backtrace belonging to the calling application. **/ APP("app"); private final String name; Context(final String name) { this.name = name; } String getName() { return this.name; } } @JacksonInject("config")
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/dto/BacktraceElement.java import com.fasterxml.jackson.annotation.JacksonInject; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import io.honeybadger.reporter.config.ConfigContext; import java.io.Serializable; import java.util.Objects; package io.honeybadger.reporter.dto; /** * One single line on a backtrace. * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ @JsonInclude(JsonInclude.Include.NON_NULL) public class BacktraceElement implements Serializable { private static final long serialVersionUID = -4455225669072193184L; /** * Enum representing all of the valid context values on the Honeybadger API. */ enum Context { /** Backtrace not-belonging to the calling application. **/ ALL("all"), /** Backtrace belonging to the calling application. **/ APP("app"); private final String name; Context(final String name) { this.name = name; } String getName() { return this.name; } } @JacksonInject("config")
private final ConfigContext config;
honeybadger-io/honeybadger-java
honeybadger-java/src/test/java/io/honeybadger/reporter/dto/ParamsTest.java
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/StandardConfigContext.java // public class StandardConfigContext extends BaseChainedConfigContext { // /** // * A new configuration context with default values prepopulated. // */ // public StandardConfigContext() { // super(); // } // // /** // * A new configuration context with default values present, but overwritten // * by the passed map of configuration values. // * // * @param configuration map with keys that correspond to the sys prop keys documented // */ // public StandardConfigContext(final Map<String, ?> configuration) { // super(); // overwriteWithContext(new MapConfigContext(configuration)); // } // // /** // * A new configuration context with the default values present. Only the // * API key is set. // * // * @param apiKey Honeybadger API key // */ // public StandardConfigContext(final String apiKey) { // if (apiKey == null) throw new IllegalArgumentException( // "API key must not be null"); // if (apiKey.isEmpty()) throw new IllegalArgumentException( // "API key must not be empty"); // // setApiKey(apiKey); // } // }
import io.honeybadger.reporter.config.ConfigContext; import io.honeybadger.reporter.config.StandardConfigContext; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue;
package io.honeybadger.reporter.dto; public class ParamsTest { @Test public void willExcludeUnwantedParams() {
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/StandardConfigContext.java // public class StandardConfigContext extends BaseChainedConfigContext { // /** // * A new configuration context with default values prepopulated. // */ // public StandardConfigContext() { // super(); // } // // /** // * A new configuration context with default values present, but overwritten // * by the passed map of configuration values. // * // * @param configuration map with keys that correspond to the sys prop keys documented // */ // public StandardConfigContext(final Map<String, ?> configuration) { // super(); // overwriteWithContext(new MapConfigContext(configuration)); // } // // /** // * A new configuration context with the default values present. Only the // * API key is set. // * // * @param apiKey Honeybadger API key // */ // public StandardConfigContext(final String apiKey) { // if (apiKey == null) throw new IllegalArgumentException( // "API key must not be null"); // if (apiKey.isEmpty()) throw new IllegalArgumentException( // "API key must not be empty"); // // setApiKey(apiKey); // } // } // Path: honeybadger-java/src/test/java/io/honeybadger/reporter/dto/ParamsTest.java import io.honeybadger.reporter.config.ConfigContext; import io.honeybadger.reporter.config.StandardConfigContext; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; package io.honeybadger.reporter.dto; public class ParamsTest { @Test public void willExcludeUnwantedParams() {
ConfigContext config = new StandardConfigContext();
honeybadger-io/honeybadger-java
honeybadger-java/src/test/java/io/honeybadger/reporter/dto/ParamsTest.java
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/StandardConfigContext.java // public class StandardConfigContext extends BaseChainedConfigContext { // /** // * A new configuration context with default values prepopulated. // */ // public StandardConfigContext() { // super(); // } // // /** // * A new configuration context with default values present, but overwritten // * by the passed map of configuration values. // * // * @param configuration map with keys that correspond to the sys prop keys documented // */ // public StandardConfigContext(final Map<String, ?> configuration) { // super(); // overwriteWithContext(new MapConfigContext(configuration)); // } // // /** // * A new configuration context with the default values present. Only the // * API key is set. // * // * @param apiKey Honeybadger API key // */ // public StandardConfigContext(final String apiKey) { // if (apiKey == null) throw new IllegalArgumentException( // "API key must not be null"); // if (apiKey.isEmpty()) throw new IllegalArgumentException( // "API key must not be empty"); // // setApiKey(apiKey); // } // }
import io.honeybadger.reporter.config.ConfigContext; import io.honeybadger.reporter.config.StandardConfigContext; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue;
package io.honeybadger.reporter.dto; public class ParamsTest { @Test public void willExcludeUnwantedParams() {
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/StandardConfigContext.java // public class StandardConfigContext extends BaseChainedConfigContext { // /** // * A new configuration context with default values prepopulated. // */ // public StandardConfigContext() { // super(); // } // // /** // * A new configuration context with default values present, but overwritten // * by the passed map of configuration values. // * // * @param configuration map with keys that correspond to the sys prop keys documented // */ // public StandardConfigContext(final Map<String, ?> configuration) { // super(); // overwriteWithContext(new MapConfigContext(configuration)); // } // // /** // * A new configuration context with the default values present. Only the // * API key is set. // * // * @param apiKey Honeybadger API key // */ // public StandardConfigContext(final String apiKey) { // if (apiKey == null) throw new IllegalArgumentException( // "API key must not be null"); // if (apiKey.isEmpty()) throw new IllegalArgumentException( // "API key must not be empty"); // // setApiKey(apiKey); // } // } // Path: honeybadger-java/src/test/java/io/honeybadger/reporter/dto/ParamsTest.java import io.honeybadger.reporter.config.ConfigContext; import io.honeybadger.reporter.config.StandardConfigContext; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; package io.honeybadger.reporter.dto; public class ParamsTest { @Test public void willExcludeUnwantedParams() {
ConfigContext config = new StandardConfigContext();
honeybadger-io/honeybadger-java
honeybadger-java/src/main/java/io/honeybadger/reporter/HoneybadgerUncaughtExceptionHandler.java
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/SystemSettingsConfigContext.java // public class SystemSettingsConfigContext extends BaseChainedConfigContext { // /** // * Populate configuration from defaults, environment variables and system // * properties. // */ // public SystemSettingsConfigContext() { // // load defaults // super(); // // overwrite with environment variables // overwriteWithContext(new MapConfigContext(System.getenv())); // // overwrite with system properties // overwriteWithContext(new MapConfigContext(System.getProperties())); // } // // /** // * Populate configuration from defaults, environment variables, system // * properties and an addition context passed in. // * // * @param context additional context to layer on top // */ // public SystemSettingsConfigContext(final ConfigContext context) { // // load all of the chained defaults // this(); // // now load in an additional context // overwriteWithContext(context); // } // }
import io.honeybadger.reporter.config.ConfigContext; import io.honeybadger.reporter.config.SystemSettingsConfigContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package io.honeybadger.reporter; /** * Exception handler class that sends errors to Honey Badger by default. * * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.0 */ public class HoneybadgerUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { private ConfigContext config; private NoticeReporter reporter; private Logger logger = LoggerFactory.getLogger(getClass()); public HoneybadgerUncaughtExceptionHandler() {
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/SystemSettingsConfigContext.java // public class SystemSettingsConfigContext extends BaseChainedConfigContext { // /** // * Populate configuration from defaults, environment variables and system // * properties. // */ // public SystemSettingsConfigContext() { // // load defaults // super(); // // overwrite with environment variables // overwriteWithContext(new MapConfigContext(System.getenv())); // // overwrite with system properties // overwriteWithContext(new MapConfigContext(System.getProperties())); // } // // /** // * Populate configuration from defaults, environment variables, system // * properties and an addition context passed in. // * // * @param context additional context to layer on top // */ // public SystemSettingsConfigContext(final ConfigContext context) { // // load all of the chained defaults // this(); // // now load in an additional context // overwriteWithContext(context); // } // } // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/HoneybadgerUncaughtExceptionHandler.java import io.honeybadger.reporter.config.ConfigContext; import io.honeybadger.reporter.config.SystemSettingsConfigContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package io.honeybadger.reporter; /** * Exception handler class that sends errors to Honey Badger by default. * * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.0 */ public class HoneybadgerUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { private ConfigContext config; private NoticeReporter reporter; private Logger logger = LoggerFactory.getLogger(getClass()); public HoneybadgerUncaughtExceptionHandler() {
this(new SystemSettingsConfigContext());
honeybadger-io/honeybadger-java
honeybadger-java/src/main/java/io/honeybadger/reporter/dto/Notice.java
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // }
import com.fasterxml.jackson.annotation.JacksonInject; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import io.honeybadger.reporter.config.ConfigContext; import java.io.Serializable; import java.util.Objects;
package io.honeybadger.reporter.dto; /** * Class representing an error that is reported to the Honeybadger API. * * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties({"environment", "created_at", "message", "token", "fault_id", "application_trace", "backtrace", "deploy", "url"}) public class Notice implements Serializable { private static final long serialVersionUID = 1661111694538362413L; private Long id = null;
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/dto/Notice.java import com.fasterxml.jackson.annotation.JacksonInject; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import io.honeybadger.reporter.config.ConfigContext; import java.io.Serializable; import java.util.Objects; package io.honeybadger.reporter.dto; /** * Class representing an error that is reported to the Honeybadger API. * * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties({"environment", "created_at", "message", "token", "fault_id", "application_trace", "backtrace", "deploy", "url"}) public class Notice implements Serializable { private static final long serialVersionUID = 1661111694538362413L; private Long id = null;
private final ConfigContext config;
honeybadger-io/honeybadger-java
honeybadger-java/src/main/java/io/honeybadger/reporter/dto/NoticeDetails.java
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // }
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.honeybadger.reporter.config.ConfigContext; import java.io.Serializable; import java.util.Collections; import java.util.Objects; import java.util.Set;
package io.honeybadger.reporter.dto; /** * Details of the error being reported to the Honeybadger API. * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"class", "message", "tags", "backtrace", "causes"}) public class NoticeDetails implements Serializable { private static final long serialVersionUID = -3055963787038629496L; @JsonProperty("class") private final String className; private final String message; private final Set<String> tags; private final Backtrace backtrace; private final Causes causes; @SuppressWarnings("unchecked")
// Path: honeybadger-java/src/main/java/io/honeybadger/reporter/config/ConfigContext.java // public interface ConfigContext { // /** @return name of environment */ // String getEnvironment(); // // /** @return Honeybadger URL to use */ // URI getHoneybadgerUrl(); // // /** @return Honeybadger API key to use */ // String getApiKey(); // // /** @return Set of system properties to not include */ // Set<String> getExcludedSysProps(); // // /** @return Set of parameters to not include */ // Set<String> getExcludedParams(); // // /** @return Set of exception classes to ignore */ // Set<String> getExcludedClasses(); // // /** @return String that maps a package to an application */ // String getApplicationPackage(); // // /** @return Honeybadger Read API key */ // String getHoneybadgerReadApiKey(); // // /** @return Do we display the feedback form? */ // Boolean isFeedbackFormDisplayed(); // // /** @return The path to the feedback form template */ // String getFeedbackFormPath(); // // /** @return Host of proxy server to send traffic through */ // String getHttpProxyHost(); // // /** @return Port of proxy server to send traffic through */ // Integer getHttpProxyPort(); // // /** @return Optional configuration parameter to adjust number of attempts to retry sending an error // * report in the event of a network timeout or other transmission exception. Defaults to 3. */ // Integer getMaximumErrorReportingRetries(); // // /** @return Timeout for socket connection within HTTP client */ // Integer getSocketTimeout(); // // /** @return Timeout for initial connect within HTTP client */ // Integer getConnectTimeout(); // } // Path: honeybadger-java/src/main/java/io/honeybadger/reporter/dto/NoticeDetails.java import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import io.honeybadger.reporter.config.ConfigContext; import java.io.Serializable; import java.util.Collections; import java.util.Objects; import java.util.Set; package io.honeybadger.reporter.dto; /** * Details of the error being reported to the Honeybadger API. * @author <a href="https://github.com/dekobon">Elijah Zupancic</a> * @since 1.0.9 */ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({"class", "message", "tags", "backtrace", "causes"}) public class NoticeDetails implements Serializable { private static final long serialVersionUID = -3055963787038629496L; @JsonProperty("class") private final String className; private final String message; private final Set<String> tags; private final Backtrace backtrace; private final Causes causes; @SuppressWarnings("unchecked")
public NoticeDetails(final ConfigContext config, final Throwable error) {
Indoqa/solr-spatial-corridor
src/main/java/com/indoqa/solr/spatial/corridor/processor/LinestringHashUpdateProcessorFactory.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/HashGeometry.java // public class HashGeometry { // // private String hash; // private String geometry; // // public String getHash() { // return hash; // } // // public void setHash(String hash) { // this.hash = hash; // } // // public String getGeometry() { // return geometry; // } // // public void setGeometry(String geometry) { // this.geometry = geometry; // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // }
import com.indoqa.solr.spatial.corridor.HashGeometry; import com.indoqa.solr.spatial.corridor.LineStringUtils; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.util.NamedList; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.response.SolrQueryResponse; import org.apache.solr.update.AddUpdateCommand; import org.apache.solr.update.processor.UpdateRequestProcessor; import org.apache.solr.update.processor.UpdateRequestProcessorFactory; import java.io.IOException; import static org.apache.solr.common.SolrException.ErrorCode.SERVER_ERROR;
this.radiusInMeters, next); } private class LinestringHashUpdateProcessor extends UpdateRequestProcessor { final String linestringFieldName; final String hashFieldName; final String linestringPolygonName; private Integer radiusInMeters; public LinestringHashUpdateProcessor(final String linestringFieldName, final String hashFieldName, final String linestringPolygonName, final Integer radiusInMeters, final UpdateRequestProcessor next) { super(next); this.linestringFieldName = linestringFieldName; this.hashFieldName = hashFieldName; this.radiusInMeters = radiusInMeters; this.linestringPolygonName = linestringPolygonName; } @Override public void processAdd(AddUpdateCommand cmd) throws IOException { final SolrInputDocument doc = cmd.getSolrInputDocument(); if (doc.containsKey(this.linestringFieldName)) { if (!doc.containsKey(this.hashFieldName) || !doc.containsKey(this.linestringPolygonName)) {
// Path: src/main/java/com/indoqa/solr/spatial/corridor/HashGeometry.java // public class HashGeometry { // // private String hash; // private String geometry; // // public String getHash() { // return hash; // } // // public void setHash(String hash) { // this.hash = hash; // } // // public String getGeometry() { // return geometry; // } // // public void setGeometry(String geometry) { // this.geometry = geometry; // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // } // Path: src/main/java/com/indoqa/solr/spatial/corridor/processor/LinestringHashUpdateProcessorFactory.java import com.indoqa.solr.spatial.corridor.HashGeometry; import com.indoqa.solr.spatial.corridor.LineStringUtils; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.util.NamedList; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.response.SolrQueryResponse; import org.apache.solr.update.AddUpdateCommand; import org.apache.solr.update.processor.UpdateRequestProcessor; import org.apache.solr.update.processor.UpdateRequestProcessorFactory; import java.io.IOException; import static org.apache.solr.common.SolrException.ErrorCode.SERVER_ERROR; this.radiusInMeters, next); } private class LinestringHashUpdateProcessor extends UpdateRequestProcessor { final String linestringFieldName; final String hashFieldName; final String linestringPolygonName; private Integer radiusInMeters; public LinestringHashUpdateProcessor(final String linestringFieldName, final String hashFieldName, final String linestringPolygonName, final Integer radiusInMeters, final UpdateRequestProcessor next) { super(next); this.linestringFieldName = linestringFieldName; this.hashFieldName = hashFieldName; this.radiusInMeters = radiusInMeters; this.linestringPolygonName = linestringPolygonName; } @Override public void processAdd(AddUpdateCommand cmd) throws IOException { final SolrInputDocument doc = cmd.getSolrInputDocument(); if (doc.containsKey(this.linestringFieldName)) { if (!doc.containsKey(this.hashFieldName) || !doc.containsKey(this.linestringPolygonName)) {
HashGeometry hashGeometry = calculateHash(doc.getFieldValue(linestringFieldName));
Indoqa/solr-spatial-corridor
src/main/java/com/indoqa/solr/spatial/corridor/processor/LinestringHashUpdateProcessorFactory.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/HashGeometry.java // public class HashGeometry { // // private String hash; // private String geometry; // // public String getHash() { // return hash; // } // // public void setHash(String hash) { // this.hash = hash; // } // // public String getGeometry() { // return geometry; // } // // public void setGeometry(String geometry) { // this.geometry = geometry; // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // }
import com.indoqa.solr.spatial.corridor.HashGeometry; import com.indoqa.solr.spatial.corridor.LineStringUtils; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.util.NamedList; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.response.SolrQueryResponse; import org.apache.solr.update.AddUpdateCommand; import org.apache.solr.update.processor.UpdateRequestProcessor; import org.apache.solr.update.processor.UpdateRequestProcessorFactory; import java.io.IOException; import static org.apache.solr.common.SolrException.ErrorCode.SERVER_ERROR;
private Integer radiusInMeters; public LinestringHashUpdateProcessor(final String linestringFieldName, final String hashFieldName, final String linestringPolygonName, final Integer radiusInMeters, final UpdateRequestProcessor next) { super(next); this.linestringFieldName = linestringFieldName; this.hashFieldName = hashFieldName; this.radiusInMeters = radiusInMeters; this.linestringPolygonName = linestringPolygonName; } @Override public void processAdd(AddUpdateCommand cmd) throws IOException { final SolrInputDocument doc = cmd.getSolrInputDocument(); if (doc.containsKey(this.linestringFieldName)) { if (!doc.containsKey(this.hashFieldName) || !doc.containsKey(this.linestringPolygonName)) { HashGeometry hashGeometry = calculateHash(doc.getFieldValue(linestringFieldName)); doc.addField(this.hashFieldName, hashGeometry.getHash()); doc.addField(this.linestringPolygonName, hashGeometry.getGeometry()); } } super.processAdd(cmd); } private HashGeometry calculateHash(Object fieldValue) {
// Path: src/main/java/com/indoqa/solr/spatial/corridor/HashGeometry.java // public class HashGeometry { // // private String hash; // private String geometry; // // public String getHash() { // return hash; // } // // public void setHash(String hash) { // this.hash = hash; // } // // public String getGeometry() { // return geometry; // } // // public void setGeometry(String geometry) { // this.geometry = geometry; // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // } // Path: src/main/java/com/indoqa/solr/spatial/corridor/processor/LinestringHashUpdateProcessorFactory.java import com.indoqa.solr.spatial.corridor.HashGeometry; import com.indoqa.solr.spatial.corridor.LineStringUtils; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.util.NamedList; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.response.SolrQueryResponse; import org.apache.solr.update.AddUpdateCommand; import org.apache.solr.update.processor.UpdateRequestProcessor; import org.apache.solr.update.processor.UpdateRequestProcessorFactory; import java.io.IOException; import static org.apache.solr.common.SolrException.ErrorCode.SERVER_ERROR; private Integer radiusInMeters; public LinestringHashUpdateProcessor(final String linestringFieldName, final String hashFieldName, final String linestringPolygonName, final Integer radiusInMeters, final UpdateRequestProcessor next) { super(next); this.linestringFieldName = linestringFieldName; this.hashFieldName = hashFieldName; this.radiusInMeters = radiusInMeters; this.linestringPolygonName = linestringPolygonName; } @Override public void processAdd(AddUpdateCommand cmd) throws IOException { final SolrInputDocument doc = cmd.getSolrInputDocument(); if (doc.containsKey(this.linestringFieldName)) { if (!doc.containsKey(this.hashFieldName) || !doc.containsKey(this.linestringPolygonName)) { HashGeometry hashGeometry = calculateHash(doc.getFieldValue(linestringFieldName)); doc.addField(this.hashFieldName, hashGeometry.getHash()); doc.addField(this.linestringPolygonName, hashGeometry.getGeometry()); } } super.processAdd(cmd); } private HashGeometry calculateHash(Object fieldValue) {
return LineStringUtils.cacheLineStringGetHashGeometry(fieldValue.toString(), this.radiusInMeters);
Indoqa/solr-spatial-corridor
src/test/java/com/indoqa/solr/spatial/corridor/direction/TestDirectionPoints.java
// Path: src/test/java/com/indoqa/solr/spatial/corridor/EmbeddedSolrInfrastructureRule.java // public class EmbeddedSolrInfrastructureRule extends ExternalResource { // // private SolrClient solrClient; // private boolean initialized; // // public SolrClient getSolrClient() { // return this.solrClient; // } // // @Override // protected void after() { // try { // this.solrClient.close(); // } catch (Exception e) { // // ignore // } // // if (this.solrClient instanceof EmbeddedSolrServer) { // EmbeddedSolrServer embeddedSolrServer = (EmbeddedSolrServer) this.solrClient; // embeddedSolrServer.getCoreContainer().shutdown(); // } // } // // @Override // protected void before() throws Throwable { // if (this.initialized) { // return; // } // // this.solrClient = EmbeddedSolrServerBuilder.build("file://./target/test-core", "solr/test"); // // this.initialized = true; // } // } // // Path: src/test/java/com/indoqa/solr/spatial/corridor/TestGeoPoint.java // public class TestGeoPoint { // private double lat; // private double lon; // // public TestGeoPoint(double lat, double lon) { // this.lat = lat; // this.lon = lon; // } // // public static TestGeoPoint geo(double lat, double lon) { // return new TestGeoPoint(lat, lon); // } // // @Override // public String toString() { // return Double.toString(lat) + " " + Double.toString(lon); // } // // public double getLat() { // return lat; // } // // public void setLat(double lat) { // this.lat = lat; // } // // public double getLon() { // return lon; // } // // public void setLon(double lon) { // this.lon = lon; // } // }
import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import com.indoqa.solr.spatial.corridor.EmbeddedSolrInfrastructureRule; import com.indoqa.solr.spatial.corridor.TestGeoPoint; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.SolrInputField;
/* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.direction; public class TestDirectionPoints { private static final String SOLR_FIELD_ID = "id"; private static final String SOLR_FIELD_GEO_POINTS = "geoPoints"; private static final String SOLR_FIELD_GEO_DIRECTION = "geoDirection"; private static final String SOLR_FIELD_LATLON = "latLon"; private static final String SOLR_FIELD_LATLON_0 = "latLon_0_coordinate"; private static final String SOLR_FIELD_LATLON_1 = "latLon_1_coordinate"; private static final String DOCUMENT_ID_1 = "route1"; private static final String DOCUMENT_ID_2 = "route2"; @ClassRule
// Path: src/test/java/com/indoqa/solr/spatial/corridor/EmbeddedSolrInfrastructureRule.java // public class EmbeddedSolrInfrastructureRule extends ExternalResource { // // private SolrClient solrClient; // private boolean initialized; // // public SolrClient getSolrClient() { // return this.solrClient; // } // // @Override // protected void after() { // try { // this.solrClient.close(); // } catch (Exception e) { // // ignore // } // // if (this.solrClient instanceof EmbeddedSolrServer) { // EmbeddedSolrServer embeddedSolrServer = (EmbeddedSolrServer) this.solrClient; // embeddedSolrServer.getCoreContainer().shutdown(); // } // } // // @Override // protected void before() throws Throwable { // if (this.initialized) { // return; // } // // this.solrClient = EmbeddedSolrServerBuilder.build("file://./target/test-core", "solr/test"); // // this.initialized = true; // } // } // // Path: src/test/java/com/indoqa/solr/spatial/corridor/TestGeoPoint.java // public class TestGeoPoint { // private double lat; // private double lon; // // public TestGeoPoint(double lat, double lon) { // this.lat = lat; // this.lon = lon; // } // // public static TestGeoPoint geo(double lat, double lon) { // return new TestGeoPoint(lat, lon); // } // // @Override // public String toString() { // return Double.toString(lat) + " " + Double.toString(lon); // } // // public double getLat() { // return lat; // } // // public void setLat(double lat) { // this.lat = lat; // } // // public double getLon() { // return lon; // } // // public void setLon(double lon) { // this.lon = lon; // } // } // Path: src/test/java/com/indoqa/solr/spatial/corridor/direction/TestDirectionPoints.java import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import com.indoqa.solr.spatial.corridor.EmbeddedSolrInfrastructureRule; import com.indoqa.solr.spatial.corridor.TestGeoPoint; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.SolrInputField; /* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.direction; public class TestDirectionPoints { private static final String SOLR_FIELD_ID = "id"; private static final String SOLR_FIELD_GEO_POINTS = "geoPoints"; private static final String SOLR_FIELD_GEO_DIRECTION = "geoDirection"; private static final String SOLR_FIELD_LATLON = "latLon"; private static final String SOLR_FIELD_LATLON_0 = "latLon_0_coordinate"; private static final String SOLR_FIELD_LATLON_1 = "latLon_1_coordinate"; private static final String DOCUMENT_ID_1 = "route1"; private static final String DOCUMENT_ID_2 = "route2"; @ClassRule
public static EmbeddedSolrInfrastructureRule infrastructureRule = new EmbeddedSolrInfrastructureRule();
Indoqa/solr-spatial-corridor
src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/wkt/WktUtils.java // public class WktUtils { // // private static final Logger LOGGER = LoggerFactory.getLogger(WktUtils.class); // // private static final GeometryFactory geometryFactory = new GeometryFactory(); // // public static LineString parseLineString(String corridorLineString) { // String rawCoordinates = StringUtils.substringBetween(corridorLineString, "LINESTRING(", ")"); // if (rawCoordinates == null || rawCoordinates.trim().isEmpty()) { // LOGGER.warn("Linestring without coordinates found: '{}'", corridorLineString); // return geometryFactory.createLineString((Coordinate[]) null); // } // String[] coordinates = rawCoordinates.trim().split(","); // // Coordinate[] wktCoordinates = Arrays.stream(coordinates).map(WktUtils::createCoordinate).toArray(Coordinate[]::new); // return geometryFactory.createLineString(wktCoordinates); // } // // public static Point parsePoint(String pointString) { // String rawPoints = StringUtils.substringBetween(pointString, "POINT(", ")"); // if (rawPoints == null) { // throw new IllegalArgumentException("Parameter must be a valid WKT Point!"); // } // // Coordinate coordinate = createCoordinate(rawPoints); // return geometryFactory.createPoint(coordinate); // } // // private static Coordinate createCoordinate(String rawCoordinates) { // String[] points = rawCoordinates.trim().split(" "); // // Coordinate coordinate = new Coordinate(); // coordinate.x = Double.parseDouble(points[0]); // coordinate.y = Double.parseDouble(points[1]); // geometryFactory.getPrecisionModel().makePrecise(coordinate); // return coordinate; // } // }
import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.CaffeineSpec; import com.github.benmanes.caffeine.cache.LoadingCache; import com.indoqa.solr.spatial.corridor.wkt.WktUtils; import org.locationtech.jts.geom.LineString; import org.locationtech.jts.io.ParseException; import org.locationtech.jts.io.WKTReader; import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.digest.DigestUtils; import java.util.concurrent.TimeUnit;
if (cached != null) { return cached; } } String key = calculateHash(value); return cache.get(key, s -> parseWktLinestring(value)); } public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ if(linestring == null){ return null; } String key = calculateHash(linestring); LineString parsedLineString = parseWktLinestring(linestring); cache.put(key, parsedLineString); HashGeometry result = new HashGeometry(); // meters /((PI/180)x6378137) result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); result.setHash(key); return result; } public static void purgeCache() { cache.invalidateAll(); cache.cleanUp(); } private static LineString parseWktLinestring(String corridorLineString) {
// Path: src/main/java/com/indoqa/solr/spatial/corridor/wkt/WktUtils.java // public class WktUtils { // // private static final Logger LOGGER = LoggerFactory.getLogger(WktUtils.class); // // private static final GeometryFactory geometryFactory = new GeometryFactory(); // // public static LineString parseLineString(String corridorLineString) { // String rawCoordinates = StringUtils.substringBetween(corridorLineString, "LINESTRING(", ")"); // if (rawCoordinates == null || rawCoordinates.trim().isEmpty()) { // LOGGER.warn("Linestring without coordinates found: '{}'", corridorLineString); // return geometryFactory.createLineString((Coordinate[]) null); // } // String[] coordinates = rawCoordinates.trim().split(","); // // Coordinate[] wktCoordinates = Arrays.stream(coordinates).map(WktUtils::createCoordinate).toArray(Coordinate[]::new); // return geometryFactory.createLineString(wktCoordinates); // } // // public static Point parsePoint(String pointString) { // String rawPoints = StringUtils.substringBetween(pointString, "POINT(", ")"); // if (rawPoints == null) { // throw new IllegalArgumentException("Parameter must be a valid WKT Point!"); // } // // Coordinate coordinate = createCoordinate(rawPoints); // return geometryFactory.createPoint(coordinate); // } // // private static Coordinate createCoordinate(String rawCoordinates) { // String[] points = rawCoordinates.trim().split(" "); // // Coordinate coordinate = new Coordinate(); // coordinate.x = Double.parseDouble(points[0]); // coordinate.y = Double.parseDouble(points[1]); // geometryFactory.getPrecisionModel().makePrecise(coordinate); // return coordinate; // } // } // Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.CaffeineSpec; import com.github.benmanes.caffeine.cache.LoadingCache; import com.indoqa.solr.spatial.corridor.wkt.WktUtils; import org.locationtech.jts.geom.LineString; import org.locationtech.jts.io.ParseException; import org.locationtech.jts.io.WKTReader; import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.digest.DigestUtils; import java.util.concurrent.TimeUnit; if (cached != null) { return cached; } } String key = calculateHash(value); return cache.get(key, s -> parseWktLinestring(value)); } public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ if(linestring == null){ return null; } String key = calculateHash(linestring); LineString parsedLineString = parseWktLinestring(linestring); cache.put(key, parsedLineString); HashGeometry result = new HashGeometry(); // meters /((PI/180)x6378137) result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); result.setHash(key); return result; } public static void purgeCache() { cache.invalidateAll(); cache.cleanUp(); } private static LineString parseWktLinestring(String corridorLineString) {
return WktUtils.parseLineString(corridorLineString);
Indoqa/solr-spatial-corridor
src/main/java/com/indoqa/solr/spatial/corridor/direction/InDirectionValueSourceParser.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringValueSource.java // public class LineStringValueSource extends ValueSource { // // private String linestringFieldName; // // public LineStringValueSource(String linestringFieldName) { // this.linestringFieldName = linestringFieldName; // } // // @Override // public String description() { // return "retrieve raw linestring even for tokenized fields"; // } // // @Override // public boolean equals(Object o) { // return false; // } // // @SuppressWarnings("rawtypes") // @Override // public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { // return new LineStringFunctionValues(this.linestringFieldName, readerContext); // } // // @Override // public int hashCode() { // return ("linestring" + this.linestringFieldName).hashCode(); // } // // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/wkt/WktUtils.java // public class WktUtils { // // private static final Logger LOGGER = LoggerFactory.getLogger(WktUtils.class); // // private static final GeometryFactory geometryFactory = new GeometryFactory(); // // public static LineString parseLineString(String corridorLineString) { // String rawCoordinates = StringUtils.substringBetween(corridorLineString, "LINESTRING(", ")"); // if (rawCoordinates == null || rawCoordinates.trim().isEmpty()) { // LOGGER.warn("Linestring without coordinates found: '{}'", corridorLineString); // return geometryFactory.createLineString((Coordinate[]) null); // } // String[] coordinates = rawCoordinates.trim().split(","); // // Coordinate[] wktCoordinates = Arrays.stream(coordinates).map(WktUtils::createCoordinate).toArray(Coordinate[]::new); // return geometryFactory.createLineString(wktCoordinates); // } // // public static Point parsePoint(String pointString) { // String rawPoints = StringUtils.substringBetween(pointString, "POINT(", ")"); // if (rawPoints == null) { // throw new IllegalArgumentException("Parameter must be a valid WKT Point!"); // } // // Coordinate coordinate = createCoordinate(rawPoints); // return geometryFactory.createPoint(coordinate); // } // // private static Coordinate createCoordinate(String rawCoordinates) { // String[] points = rawCoordinates.trim().split(" "); // // Coordinate coordinate = new Coordinate(); // coordinate.x = Double.parseDouble(points[0]); // coordinate.y = Double.parseDouble(points[1]); // geometryFactory.getPrecisionModel().makePrecise(coordinate); // return coordinate; // } // }
import com.indoqa.solr.spatial.corridor.LineStringValueSource; import com.indoqa.solr.spatial.corridor.wkt.WktUtils; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.Point; import org.locationtech.jts.io.WKTReader; import org.apache.lucene.queries.function.ValueSource; import org.apache.solr.search.FunctionQParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.ValueSourceParser; import java.util.ArrayList; import java.util.List;
/* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.direction; public class InDirectionValueSourceParser extends ValueSourceParser { private final WKTReader wktReader; private final GeometryFactory geometryFactory; public InDirectionValueSourceParser(){ super(); this.wktReader = new WKTReader(); this.geometryFactory = new GeometryFactory(); } @Override public ValueSource parse(FunctionQParser fp) throws SyntaxError { List<Point> queryPoints = new ArrayList<>(); String[] queryPointParameters = fp.getParams().getParams("corridor.point"); for (String queryPointParameter : queryPointParameters) {
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringValueSource.java // public class LineStringValueSource extends ValueSource { // // private String linestringFieldName; // // public LineStringValueSource(String linestringFieldName) { // this.linestringFieldName = linestringFieldName; // } // // @Override // public String description() { // return "retrieve raw linestring even for tokenized fields"; // } // // @Override // public boolean equals(Object o) { // return false; // } // // @SuppressWarnings("rawtypes") // @Override // public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { // return new LineStringFunctionValues(this.linestringFieldName, readerContext); // } // // @Override // public int hashCode() { // return ("linestring" + this.linestringFieldName).hashCode(); // } // // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/wkt/WktUtils.java // public class WktUtils { // // private static final Logger LOGGER = LoggerFactory.getLogger(WktUtils.class); // // private static final GeometryFactory geometryFactory = new GeometryFactory(); // // public static LineString parseLineString(String corridorLineString) { // String rawCoordinates = StringUtils.substringBetween(corridorLineString, "LINESTRING(", ")"); // if (rawCoordinates == null || rawCoordinates.trim().isEmpty()) { // LOGGER.warn("Linestring without coordinates found: '{}'", corridorLineString); // return geometryFactory.createLineString((Coordinate[]) null); // } // String[] coordinates = rawCoordinates.trim().split(","); // // Coordinate[] wktCoordinates = Arrays.stream(coordinates).map(WktUtils::createCoordinate).toArray(Coordinate[]::new); // return geometryFactory.createLineString(wktCoordinates); // } // // public static Point parsePoint(String pointString) { // String rawPoints = StringUtils.substringBetween(pointString, "POINT(", ")"); // if (rawPoints == null) { // throw new IllegalArgumentException("Parameter must be a valid WKT Point!"); // } // // Coordinate coordinate = createCoordinate(rawPoints); // return geometryFactory.createPoint(coordinate); // } // // private static Coordinate createCoordinate(String rawCoordinates) { // String[] points = rawCoordinates.trim().split(" "); // // Coordinate coordinate = new Coordinate(); // coordinate.x = Double.parseDouble(points[0]); // coordinate.y = Double.parseDouble(points[1]); // geometryFactory.getPrecisionModel().makePrecise(coordinate); // return coordinate; // } // } // Path: src/main/java/com/indoqa/solr/spatial/corridor/direction/InDirectionValueSourceParser.java import com.indoqa.solr.spatial.corridor.LineStringValueSource; import com.indoqa.solr.spatial.corridor.wkt.WktUtils; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.Point; import org.locationtech.jts.io.WKTReader; import org.apache.lucene.queries.function.ValueSource; import org.apache.solr.search.FunctionQParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.ValueSourceParser; import java.util.ArrayList; import java.util.List; /* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.direction; public class InDirectionValueSourceParser extends ValueSourceParser { private final WKTReader wktReader; private final GeometryFactory geometryFactory; public InDirectionValueSourceParser(){ super(); this.wktReader = new WKTReader(); this.geometryFactory = new GeometryFactory(); } @Override public ValueSource parse(FunctionQParser fp) throws SyntaxError { List<Point> queryPoints = new ArrayList<>(); String[] queryPointParameters = fp.getParams().getParams("corridor.point"); for (String queryPointParameter : queryPointParameters) {
queryPoints.add(WktUtils.parsePoint(queryPointParameter));
Indoqa/solr-spatial-corridor
src/main/java/com/indoqa/solr/spatial/corridor/direction/InDirectionValueSourceParser.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringValueSource.java // public class LineStringValueSource extends ValueSource { // // private String linestringFieldName; // // public LineStringValueSource(String linestringFieldName) { // this.linestringFieldName = linestringFieldName; // } // // @Override // public String description() { // return "retrieve raw linestring even for tokenized fields"; // } // // @Override // public boolean equals(Object o) { // return false; // } // // @SuppressWarnings("rawtypes") // @Override // public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { // return new LineStringFunctionValues(this.linestringFieldName, readerContext); // } // // @Override // public int hashCode() { // return ("linestring" + this.linestringFieldName).hashCode(); // } // // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/wkt/WktUtils.java // public class WktUtils { // // private static final Logger LOGGER = LoggerFactory.getLogger(WktUtils.class); // // private static final GeometryFactory geometryFactory = new GeometryFactory(); // // public static LineString parseLineString(String corridorLineString) { // String rawCoordinates = StringUtils.substringBetween(corridorLineString, "LINESTRING(", ")"); // if (rawCoordinates == null || rawCoordinates.trim().isEmpty()) { // LOGGER.warn("Linestring without coordinates found: '{}'", corridorLineString); // return geometryFactory.createLineString((Coordinate[]) null); // } // String[] coordinates = rawCoordinates.trim().split(","); // // Coordinate[] wktCoordinates = Arrays.stream(coordinates).map(WktUtils::createCoordinate).toArray(Coordinate[]::new); // return geometryFactory.createLineString(wktCoordinates); // } // // public static Point parsePoint(String pointString) { // String rawPoints = StringUtils.substringBetween(pointString, "POINT(", ")"); // if (rawPoints == null) { // throw new IllegalArgumentException("Parameter must be a valid WKT Point!"); // } // // Coordinate coordinate = createCoordinate(rawPoints); // return geometryFactory.createPoint(coordinate); // } // // private static Coordinate createCoordinate(String rawCoordinates) { // String[] points = rawCoordinates.trim().split(" "); // // Coordinate coordinate = new Coordinate(); // coordinate.x = Double.parseDouble(points[0]); // coordinate.y = Double.parseDouble(points[1]); // geometryFactory.getPrecisionModel().makePrecise(coordinate); // return coordinate; // } // }
import com.indoqa.solr.spatial.corridor.LineStringValueSource; import com.indoqa.solr.spatial.corridor.wkt.WktUtils; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.Point; import org.locationtech.jts.io.WKTReader; import org.apache.lucene.queries.function.ValueSource; import org.apache.solr.search.FunctionQParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.ValueSourceParser; import java.util.ArrayList; import java.util.List;
/* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.direction; public class InDirectionValueSourceParser extends ValueSourceParser { private final WKTReader wktReader; private final GeometryFactory geometryFactory; public InDirectionValueSourceParser(){ super(); this.wktReader = new WKTReader(); this.geometryFactory = new GeometryFactory(); } @Override public ValueSource parse(FunctionQParser fp) throws SyntaxError { List<Point> queryPoints = new ArrayList<>(); String[] queryPointParameters = fp.getParams().getParams("corridor.point"); for (String queryPointParameter : queryPointParameters) { queryPoints.add(WktUtils.parsePoint(queryPointParameter)); }
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringValueSource.java // public class LineStringValueSource extends ValueSource { // // private String linestringFieldName; // // public LineStringValueSource(String linestringFieldName) { // this.linestringFieldName = linestringFieldName; // } // // @Override // public String description() { // return "retrieve raw linestring even for tokenized fields"; // } // // @Override // public boolean equals(Object o) { // return false; // } // // @SuppressWarnings("rawtypes") // @Override // public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { // return new LineStringFunctionValues(this.linestringFieldName, readerContext); // } // // @Override // public int hashCode() { // return ("linestring" + this.linestringFieldName).hashCode(); // } // // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/wkt/WktUtils.java // public class WktUtils { // // private static final Logger LOGGER = LoggerFactory.getLogger(WktUtils.class); // // private static final GeometryFactory geometryFactory = new GeometryFactory(); // // public static LineString parseLineString(String corridorLineString) { // String rawCoordinates = StringUtils.substringBetween(corridorLineString, "LINESTRING(", ")"); // if (rawCoordinates == null || rawCoordinates.trim().isEmpty()) { // LOGGER.warn("Linestring without coordinates found: '{}'", corridorLineString); // return geometryFactory.createLineString((Coordinate[]) null); // } // String[] coordinates = rawCoordinates.trim().split(","); // // Coordinate[] wktCoordinates = Arrays.stream(coordinates).map(WktUtils::createCoordinate).toArray(Coordinate[]::new); // return geometryFactory.createLineString(wktCoordinates); // } // // public static Point parsePoint(String pointString) { // String rawPoints = StringUtils.substringBetween(pointString, "POINT(", ")"); // if (rawPoints == null) { // throw new IllegalArgumentException("Parameter must be a valid WKT Point!"); // } // // Coordinate coordinate = createCoordinate(rawPoints); // return geometryFactory.createPoint(coordinate); // } // // private static Coordinate createCoordinate(String rawCoordinates) { // String[] points = rawCoordinates.trim().split(" "); // // Coordinate coordinate = new Coordinate(); // coordinate.x = Double.parseDouble(points[0]); // coordinate.y = Double.parseDouble(points[1]); // geometryFactory.getPrecisionModel().makePrecise(coordinate); // return coordinate; // } // } // Path: src/main/java/com/indoqa/solr/spatial/corridor/direction/InDirectionValueSourceParser.java import com.indoqa.solr.spatial.corridor.LineStringValueSource; import com.indoqa.solr.spatial.corridor.wkt.WktUtils; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.Point; import org.locationtech.jts.io.WKTReader; import org.apache.lucene.queries.function.ValueSource; import org.apache.solr.search.FunctionQParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.ValueSourceParser; import java.util.ArrayList; import java.util.List; /* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.direction; public class InDirectionValueSourceParser extends ValueSourceParser { private final WKTReader wktReader; private final GeometryFactory geometryFactory; public InDirectionValueSourceParser(){ super(); this.wktReader = new WKTReader(); this.geometryFactory = new GeometryFactory(); } @Override public ValueSource parse(FunctionQParser fp) throws SyntaxError { List<Point> queryPoints = new ArrayList<>(); String[] queryPointParameters = fp.getParams().getParams("corridor.point"); for (String queryPointParameter : queryPointParameters) { queryPoints.add(WktUtils.parsePoint(queryPointParameter)); }
LineStringValueSource routeValueSource = new LineStringValueSource(fp.parseArg());
Indoqa/solr-spatial-corridor
src/main/java/com/indoqa/solr/spatial/corridor/direction/DirectionValueSource.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/debug/DebugValues.java // public interface DebugValues { // // void add(String key, String value); // void add(String key, boolean value); // void add(String key, Number value); // // void addAngleDifference(String key, String value); // void addAngleDifference(String key, Number value); // void addAngleDifference(String key, Coordinate coordinate); // // void addSingleAngleDifference(String key, Number value); // // String toJson(); // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/debug/NoOpDebugValues.java // public class NoOpDebugValues implements DebugValues { // // public static NoOpDebugValues NOOP_DEBUG_VALUES = new NoOpDebugValues(); // // private NoOpDebugValues() { // super(); // } // // @Override // public void add(String key, String value) { // // } // // @Override // public void add(String key, boolean value) { // // } // // @Override // public void add(String key, Number value) { // // } // // @Override // public void addAngleDifference(String key, String value) { // // } // // @Override // public void addAngleDifference(String key, Number value) { // // } // // @Override // public void addAngleDifference(String key, Coordinate coordinate) { // // } // // @Override // public void addSingleAngleDifference(String distance, Number distance1) { // // } // // @Override // public String toJson() { // return null; // } // }
import org.locationtech.jts.geom.LineString; import org.locationtech.jts.geom.Point; import org.locationtech.jts.linearref.LinearLocation; import org.locationtech.jts.linearref.LocationIndexedLine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; import java.util.Map; import com.indoqa.solr.spatial.corridor.LineStringUtils; import org.apache.commons.lang3.ObjectUtils; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.queries.function.FunctionValues; import org.apache.lucene.queries.function.ValueSource; import org.apache.lucene.queries.function.docvalues.DoubleDocValues; import com.indoqa.solr.spatial.corridor.debug.DebugValues; import com.indoqa.solr.spatial.corridor.debug.NoOpDebugValues; import org.locationtech.jts.geom.Coordinate;
return true; } public List<Point> getQueryPoints() { return this.queryPoints; } @SuppressWarnings("rawtypes") @Override public final FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { FunctionValues locationValues = this.routeValueSource.getValues(context, readerContext); FunctionValues hashValues = this.routeHashValueSource.getValues(context, readerContext); return this.getFunctionValues(locationValues, hashValues); } protected FunctionValues getFunctionValues(FunctionValues locationValues, FunctionValues hashValues) { return new InverseCorridorDocValues(this, locationValues, hashValues); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.routeValueSource == null ? 0 : this.routeValueSource.hashCode()); result = prime * result + (this.routeHashValueSource == null ? 0 : this.routeHashValueSource.hashCode()); result = prime * result + (this.queryPoints == null ? 0 : this.queryPoints.hashCode()); result = prime * result + (this.description() == null ? 0 : this.description().hashCode()); return result; }
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/debug/DebugValues.java // public interface DebugValues { // // void add(String key, String value); // void add(String key, boolean value); // void add(String key, Number value); // // void addAngleDifference(String key, String value); // void addAngleDifference(String key, Number value); // void addAngleDifference(String key, Coordinate coordinate); // // void addSingleAngleDifference(String key, Number value); // // String toJson(); // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/debug/NoOpDebugValues.java // public class NoOpDebugValues implements DebugValues { // // public static NoOpDebugValues NOOP_DEBUG_VALUES = new NoOpDebugValues(); // // private NoOpDebugValues() { // super(); // } // // @Override // public void add(String key, String value) { // // } // // @Override // public void add(String key, boolean value) { // // } // // @Override // public void add(String key, Number value) { // // } // // @Override // public void addAngleDifference(String key, String value) { // // } // // @Override // public void addAngleDifference(String key, Number value) { // // } // // @Override // public void addAngleDifference(String key, Coordinate coordinate) { // // } // // @Override // public void addSingleAngleDifference(String distance, Number distance1) { // // } // // @Override // public String toJson() { // return null; // } // } // Path: src/main/java/com/indoqa/solr/spatial/corridor/direction/DirectionValueSource.java import org.locationtech.jts.geom.LineString; import org.locationtech.jts.geom.Point; import org.locationtech.jts.linearref.LinearLocation; import org.locationtech.jts.linearref.LocationIndexedLine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; import java.util.Map; import com.indoqa.solr.spatial.corridor.LineStringUtils; import org.apache.commons.lang3.ObjectUtils; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.queries.function.FunctionValues; import org.apache.lucene.queries.function.ValueSource; import org.apache.lucene.queries.function.docvalues.DoubleDocValues; import com.indoqa.solr.spatial.corridor.debug.DebugValues; import com.indoqa.solr.spatial.corridor.debug.NoOpDebugValues; import org.locationtech.jts.geom.Coordinate; return true; } public List<Point> getQueryPoints() { return this.queryPoints; } @SuppressWarnings("rawtypes") @Override public final FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { FunctionValues locationValues = this.routeValueSource.getValues(context, readerContext); FunctionValues hashValues = this.routeHashValueSource.getValues(context, readerContext); return this.getFunctionValues(locationValues, hashValues); } protected FunctionValues getFunctionValues(FunctionValues locationValues, FunctionValues hashValues) { return new InverseCorridorDocValues(this, locationValues, hashValues); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.routeValueSource == null ? 0 : this.routeValueSource.hashCode()); result = prime * result + (this.routeHashValueSource == null ? 0 : this.routeHashValueSource.hashCode()); result = prime * result + (this.queryPoints == null ? 0 : this.queryPoints.hashCode()); result = prime * result + (this.description() == null ? 0 : this.description().hashCode()); return result; }
protected double getValue(DebugValues debugValues, LineString lineString) {
Indoqa/solr-spatial-corridor
src/main/java/com/indoqa/solr/spatial/corridor/direction/DirectionValueSource.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/debug/DebugValues.java // public interface DebugValues { // // void add(String key, String value); // void add(String key, boolean value); // void add(String key, Number value); // // void addAngleDifference(String key, String value); // void addAngleDifference(String key, Number value); // void addAngleDifference(String key, Coordinate coordinate); // // void addSingleAngleDifference(String key, Number value); // // String toJson(); // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/debug/NoOpDebugValues.java // public class NoOpDebugValues implements DebugValues { // // public static NoOpDebugValues NOOP_DEBUG_VALUES = new NoOpDebugValues(); // // private NoOpDebugValues() { // super(); // } // // @Override // public void add(String key, String value) { // // } // // @Override // public void add(String key, boolean value) { // // } // // @Override // public void add(String key, Number value) { // // } // // @Override // public void addAngleDifference(String key, String value) { // // } // // @Override // public void addAngleDifference(String key, Number value) { // // } // // @Override // public void addAngleDifference(String key, Coordinate coordinate) { // // } // // @Override // public void addSingleAngleDifference(String distance, Number distance1) { // // } // // @Override // public String toJson() { // return null; // } // }
import org.locationtech.jts.geom.LineString; import org.locationtech.jts.geom.Point; import org.locationtech.jts.linearref.LinearLocation; import org.locationtech.jts.linearref.LocationIndexedLine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; import java.util.Map; import com.indoqa.solr.spatial.corridor.LineStringUtils; import org.apache.commons.lang3.ObjectUtils; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.queries.function.FunctionValues; import org.apache.lucene.queries.function.ValueSource; import org.apache.lucene.queries.function.docvalues.DoubleDocValues; import com.indoqa.solr.spatial.corridor.debug.DebugValues; import com.indoqa.solr.spatial.corridor.debug.NoOpDebugValues; import org.locationtech.jts.geom.Coordinate;
FunctionValues hashValues = this.routeHashValueSource.getValues(context, readerContext); return this.getFunctionValues(locationValues, hashValues); } protected FunctionValues getFunctionValues(FunctionValues locationValues, FunctionValues hashValues) { return new InverseCorridorDocValues(this, locationValues, hashValues); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.routeValueSource == null ? 0 : this.routeValueSource.hashCode()); result = prime * result + (this.routeHashValueSource == null ? 0 : this.routeHashValueSource.hashCode()); result = prime * result + (this.queryPoints == null ? 0 : this.queryPoints.hashCode()); result = prime * result + (this.description() == null ? 0 : this.description().hashCode()); return result; } protected double getValue(DebugValues debugValues, LineString lineString) { return AngleUtils.getAngleDifference(debugValues, lineString, this.queryPoints, this.pointsMaxDistanceToRoute); } protected final class InverseCorridorDocValues extends DoubleDocValues { private FunctionValues routeValues; private FunctionValues hashValues; private DebugValues debugValues; protected InverseCorridorDocValues(ValueSource vs, FunctionValues routeValues, FunctionValues hashValues) {
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/debug/DebugValues.java // public interface DebugValues { // // void add(String key, String value); // void add(String key, boolean value); // void add(String key, Number value); // // void addAngleDifference(String key, String value); // void addAngleDifference(String key, Number value); // void addAngleDifference(String key, Coordinate coordinate); // // void addSingleAngleDifference(String key, Number value); // // String toJson(); // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/debug/NoOpDebugValues.java // public class NoOpDebugValues implements DebugValues { // // public static NoOpDebugValues NOOP_DEBUG_VALUES = new NoOpDebugValues(); // // private NoOpDebugValues() { // super(); // } // // @Override // public void add(String key, String value) { // // } // // @Override // public void add(String key, boolean value) { // // } // // @Override // public void add(String key, Number value) { // // } // // @Override // public void addAngleDifference(String key, String value) { // // } // // @Override // public void addAngleDifference(String key, Number value) { // // } // // @Override // public void addAngleDifference(String key, Coordinate coordinate) { // // } // // @Override // public void addSingleAngleDifference(String distance, Number distance1) { // // } // // @Override // public String toJson() { // return null; // } // } // Path: src/main/java/com/indoqa/solr/spatial/corridor/direction/DirectionValueSource.java import org.locationtech.jts.geom.LineString; import org.locationtech.jts.geom.Point; import org.locationtech.jts.linearref.LinearLocation; import org.locationtech.jts.linearref.LocationIndexedLine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; import java.util.Map; import com.indoqa.solr.spatial.corridor.LineStringUtils; import org.apache.commons.lang3.ObjectUtils; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.queries.function.FunctionValues; import org.apache.lucene.queries.function.ValueSource; import org.apache.lucene.queries.function.docvalues.DoubleDocValues; import com.indoqa.solr.spatial.corridor.debug.DebugValues; import com.indoqa.solr.spatial.corridor.debug.NoOpDebugValues; import org.locationtech.jts.geom.Coordinate; FunctionValues hashValues = this.routeHashValueSource.getValues(context, readerContext); return this.getFunctionValues(locationValues, hashValues); } protected FunctionValues getFunctionValues(FunctionValues locationValues, FunctionValues hashValues) { return new InverseCorridorDocValues(this, locationValues, hashValues); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.routeValueSource == null ? 0 : this.routeValueSource.hashCode()); result = prime * result + (this.routeHashValueSource == null ? 0 : this.routeHashValueSource.hashCode()); result = prime * result + (this.queryPoints == null ? 0 : this.queryPoints.hashCode()); result = prime * result + (this.description() == null ? 0 : this.description().hashCode()); return result; } protected double getValue(DebugValues debugValues, LineString lineString) { return AngleUtils.getAngleDifference(debugValues, lineString, this.queryPoints, this.pointsMaxDistanceToRoute); } protected final class InverseCorridorDocValues extends DoubleDocValues { private FunctionValues routeValues; private FunctionValues hashValues; private DebugValues debugValues; protected InverseCorridorDocValues(ValueSource vs, FunctionValues routeValues, FunctionValues hashValues) {
this(vs, routeValues, hashValues, NoOpDebugValues.NOOP_DEBUG_VALUES);
Indoqa/solr-spatial-corridor
src/main/java/com/indoqa/solr/spatial/corridor/direction/DirectionValueSource.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/debug/DebugValues.java // public interface DebugValues { // // void add(String key, String value); // void add(String key, boolean value); // void add(String key, Number value); // // void addAngleDifference(String key, String value); // void addAngleDifference(String key, Number value); // void addAngleDifference(String key, Coordinate coordinate); // // void addSingleAngleDifference(String key, Number value); // // String toJson(); // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/debug/NoOpDebugValues.java // public class NoOpDebugValues implements DebugValues { // // public static NoOpDebugValues NOOP_DEBUG_VALUES = new NoOpDebugValues(); // // private NoOpDebugValues() { // super(); // } // // @Override // public void add(String key, String value) { // // } // // @Override // public void add(String key, boolean value) { // // } // // @Override // public void add(String key, Number value) { // // } // // @Override // public void addAngleDifference(String key, String value) { // // } // // @Override // public void addAngleDifference(String key, Number value) { // // } // // @Override // public void addAngleDifference(String key, Coordinate coordinate) { // // } // // @Override // public void addSingleAngleDifference(String distance, Number distance1) { // // } // // @Override // public String toJson() { // return null; // } // }
import org.locationtech.jts.geom.LineString; import org.locationtech.jts.geom.Point; import org.locationtech.jts.linearref.LinearLocation; import org.locationtech.jts.linearref.LocationIndexedLine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; import java.util.Map; import com.indoqa.solr.spatial.corridor.LineStringUtils; import org.apache.commons.lang3.ObjectUtils; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.queries.function.FunctionValues; import org.apache.lucene.queries.function.ValueSource; import org.apache.lucene.queries.function.docvalues.DoubleDocValues; import com.indoqa.solr.spatial.corridor.debug.DebugValues; import com.indoqa.solr.spatial.corridor.debug.NoOpDebugValues; import org.locationtech.jts.geom.Coordinate;
protected final class InverseCorridorDocValues extends DoubleDocValues { private FunctionValues routeValues; private FunctionValues hashValues; private DebugValues debugValues; protected InverseCorridorDocValues(ValueSource vs, FunctionValues routeValues, FunctionValues hashValues) { this(vs, routeValues, hashValues, NoOpDebugValues.NOOP_DEBUG_VALUES); } protected InverseCorridorDocValues(ValueSource vs, FunctionValues routeValues, FunctionValues hashValues, DebugValues debugValues) { super(vs); this.routeValues = routeValues; this.hashValues = hashValues; this.debugValues = debugValues; } @Override public double doubleVal(int docId) throws IOException { String routeAsString = this.routeValues.strVal(docId); String routeAsHash = this.hashValues.strVal(docId); try { if (routeAsString == null || routeAsString.isEmpty()) { this.debugValues.add("routeAsString", "empty"); return -1; }
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/debug/DebugValues.java // public interface DebugValues { // // void add(String key, String value); // void add(String key, boolean value); // void add(String key, Number value); // // void addAngleDifference(String key, String value); // void addAngleDifference(String key, Number value); // void addAngleDifference(String key, Coordinate coordinate); // // void addSingleAngleDifference(String key, Number value); // // String toJson(); // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/debug/NoOpDebugValues.java // public class NoOpDebugValues implements DebugValues { // // public static NoOpDebugValues NOOP_DEBUG_VALUES = new NoOpDebugValues(); // // private NoOpDebugValues() { // super(); // } // // @Override // public void add(String key, String value) { // // } // // @Override // public void add(String key, boolean value) { // // } // // @Override // public void add(String key, Number value) { // // } // // @Override // public void addAngleDifference(String key, String value) { // // } // // @Override // public void addAngleDifference(String key, Number value) { // // } // // @Override // public void addAngleDifference(String key, Coordinate coordinate) { // // } // // @Override // public void addSingleAngleDifference(String distance, Number distance1) { // // } // // @Override // public String toJson() { // return null; // } // } // Path: src/main/java/com/indoqa/solr/spatial/corridor/direction/DirectionValueSource.java import org.locationtech.jts.geom.LineString; import org.locationtech.jts.geom.Point; import org.locationtech.jts.linearref.LinearLocation; import org.locationtech.jts.linearref.LocationIndexedLine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; import java.util.Map; import com.indoqa.solr.spatial.corridor.LineStringUtils; import org.apache.commons.lang3.ObjectUtils; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.queries.function.FunctionValues; import org.apache.lucene.queries.function.ValueSource; import org.apache.lucene.queries.function.docvalues.DoubleDocValues; import com.indoqa.solr.spatial.corridor.debug.DebugValues; import com.indoqa.solr.spatial.corridor.debug.NoOpDebugValues; import org.locationtech.jts.geom.Coordinate; protected final class InverseCorridorDocValues extends DoubleDocValues { private FunctionValues routeValues; private FunctionValues hashValues; private DebugValues debugValues; protected InverseCorridorDocValues(ValueSource vs, FunctionValues routeValues, FunctionValues hashValues) { this(vs, routeValues, hashValues, NoOpDebugValues.NOOP_DEBUG_VALUES); } protected InverseCorridorDocValues(ValueSource vs, FunctionValues routeValues, FunctionValues hashValues, DebugValues debugValues) { super(vs); this.routeValues = routeValues; this.hashValues = hashValues; this.debugValues = debugValues; } @Override public double doubleVal(int docId) throws IOException { String routeAsString = this.routeValues.strVal(docId); String routeAsHash = this.hashValues.strVal(docId); try { if (routeAsString == null || routeAsString.isEmpty()) { this.debugValues.add("routeAsString", "empty"); return -1; }
LineString route = LineStringUtils.parseOrGet(routeAsString, routeAsHash);
Indoqa/solr-spatial-corridor
src/main/java/com/indoqa/solr/spatial/corridor/direction/InDirectionDebugValueSourceParser.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringValueSource.java // public class LineStringValueSource extends ValueSource { // // private String linestringFieldName; // // public LineStringValueSource(String linestringFieldName) { // this.linestringFieldName = linestringFieldName; // } // // @Override // public String description() { // return "retrieve raw linestring even for tokenized fields"; // } // // @Override // public boolean equals(Object o) { // return false; // } // // @SuppressWarnings("rawtypes") // @Override // public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { // return new LineStringFunctionValues(this.linestringFieldName, readerContext); // } // // @Override // public int hashCode() { // return ("linestring" + this.linestringFieldName).hashCode(); // } // // }
import java.util.List; import com.indoqa.solr.spatial.corridor.LineStringValueSource; import org.locationtech.jts.geom.Point; import org.apache.lucene.queries.function.ValueSource;
/* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.direction; public class InDirectionDebugValueSourceParser extends InDirectionValueSourceParser { @Override
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringValueSource.java // public class LineStringValueSource extends ValueSource { // // private String linestringFieldName; // // public LineStringValueSource(String linestringFieldName) { // this.linestringFieldName = linestringFieldName; // } // // @Override // public String description() { // return "retrieve raw linestring even for tokenized fields"; // } // // @Override // public boolean equals(Object o) { // return false; // } // // @SuppressWarnings("rawtypes") // @Override // public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { // return new LineStringFunctionValues(this.linestringFieldName, readerContext); // } // // @Override // public int hashCode() { // return ("linestring" + this.linestringFieldName).hashCode(); // } // // } // Path: src/main/java/com/indoqa/solr/spatial/corridor/direction/InDirectionDebugValueSourceParser.java import java.util.List; import com.indoqa.solr.spatial.corridor.LineStringValueSource; import org.locationtech.jts.geom.Point; import org.apache.lucene.queries.function.ValueSource; /* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.direction; public class InDirectionDebugValueSourceParser extends InDirectionValueSourceParser { @Override
protected ValueSource createValueSource(List<Point> queryPoints, LineStringValueSource routeValueSource,
Indoqa/solr-spatial-corridor
src/test/java/com/indoqa/solr/spatial/corridor/query/points/TestPointsDistance.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/HashGeometry.java // public class HashGeometry { // // private String hash; // private String geometry; // // public String getHash() { // return hash; // } // // public void setHash(String hash) { // this.hash = hash; // } // // public String getGeometry() { // return geometry; // } // // public void setGeometry(String geometry) { // this.geometry = geometry; // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // } // // Path: src/test/java/com/indoqa/solr/spatial/corridor/EmbeddedSolrInfrastructureRule.java // public class EmbeddedSolrInfrastructureRule extends ExternalResource { // // private SolrClient solrClient; // private boolean initialized; // // public SolrClient getSolrClient() { // return this.solrClient; // } // // @Override // protected void after() { // try { // this.solrClient.close(); // } catch (Exception e) { // // ignore // } // // if (this.solrClient instanceof EmbeddedSolrServer) { // EmbeddedSolrServer embeddedSolrServer = (EmbeddedSolrServer) this.solrClient; // embeddedSolrServer.getCoreContainer().shutdown(); // } // } // // @Override // protected void before() throws Throwable { // if (this.initialized) { // return; // } // // this.solrClient = EmbeddedSolrServerBuilder.build("file://./target/test-core", "solr/test"); // // this.initialized = true; // } // }
import org.junit.Test; import com.indoqa.solr.spatial.corridor.EmbeddedSolrInfrastructureRule; import static org.junit.Assert.assertEquals; import java.io.IOException; import com.indoqa.solr.spatial.corridor.HashGeometry; import com.indoqa.solr.spatial.corridor.LineStringUtils; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrInputDocument; import org.junit.After; import org.junit.Before; import org.junit.ClassRule;
/* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.query.points; public class TestPointsDistance { private static final String SOLR_FIELD_ID = "id"; private static final String SOLR_FIELD_POINT_POSITION = "position"; private static final String DOCUMENT_ID_1 = "id-1"; private static final String DOCUMENT_ID_2 = "id-2"; @ClassRule
// Path: src/main/java/com/indoqa/solr/spatial/corridor/HashGeometry.java // public class HashGeometry { // // private String hash; // private String geometry; // // public String getHash() { // return hash; // } // // public void setHash(String hash) { // this.hash = hash; // } // // public String getGeometry() { // return geometry; // } // // public void setGeometry(String geometry) { // this.geometry = geometry; // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // } // // Path: src/test/java/com/indoqa/solr/spatial/corridor/EmbeddedSolrInfrastructureRule.java // public class EmbeddedSolrInfrastructureRule extends ExternalResource { // // private SolrClient solrClient; // private boolean initialized; // // public SolrClient getSolrClient() { // return this.solrClient; // } // // @Override // protected void after() { // try { // this.solrClient.close(); // } catch (Exception e) { // // ignore // } // // if (this.solrClient instanceof EmbeddedSolrServer) { // EmbeddedSolrServer embeddedSolrServer = (EmbeddedSolrServer) this.solrClient; // embeddedSolrServer.getCoreContainer().shutdown(); // } // } // // @Override // protected void before() throws Throwable { // if (this.initialized) { // return; // } // // this.solrClient = EmbeddedSolrServerBuilder.build("file://./target/test-core", "solr/test"); // // this.initialized = true; // } // } // Path: src/test/java/com/indoqa/solr/spatial/corridor/query/points/TestPointsDistance.java import org.junit.Test; import com.indoqa.solr.spatial.corridor.EmbeddedSolrInfrastructureRule; import static org.junit.Assert.assertEquals; import java.io.IOException; import com.indoqa.solr.spatial.corridor.HashGeometry; import com.indoqa.solr.spatial.corridor.LineStringUtils; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrInputDocument; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; /* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.query.points; public class TestPointsDistance { private static final String SOLR_FIELD_ID = "id"; private static final String SOLR_FIELD_POINT_POSITION = "position"; private static final String DOCUMENT_ID_1 = "id-1"; private static final String DOCUMENT_ID_2 = "id-2"; @ClassRule
public static EmbeddedSolrInfrastructureRule infrastructureRule = new EmbeddedSolrInfrastructureRule();
Indoqa/solr-spatial-corridor
src/test/java/com/indoqa/solr/spatial/corridor/query/points/TestPointsDistance.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/HashGeometry.java // public class HashGeometry { // // private String hash; // private String geometry; // // public String getHash() { // return hash; // } // // public void setHash(String hash) { // this.hash = hash; // } // // public String getGeometry() { // return geometry; // } // // public void setGeometry(String geometry) { // this.geometry = geometry; // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // } // // Path: src/test/java/com/indoqa/solr/spatial/corridor/EmbeddedSolrInfrastructureRule.java // public class EmbeddedSolrInfrastructureRule extends ExternalResource { // // private SolrClient solrClient; // private boolean initialized; // // public SolrClient getSolrClient() { // return this.solrClient; // } // // @Override // protected void after() { // try { // this.solrClient.close(); // } catch (Exception e) { // // ignore // } // // if (this.solrClient instanceof EmbeddedSolrServer) { // EmbeddedSolrServer embeddedSolrServer = (EmbeddedSolrServer) this.solrClient; // embeddedSolrServer.getCoreContainer().shutdown(); // } // } // // @Override // protected void before() throws Throwable { // if (this.initialized) { // return; // } // // this.solrClient = EmbeddedSolrServerBuilder.build("file://./target/test-core", "solr/test"); // // this.initialized = true; // } // }
import org.junit.Test; import com.indoqa.solr.spatial.corridor.EmbeddedSolrInfrastructureRule; import static org.junit.Assert.assertEquals; import java.io.IOException; import com.indoqa.solr.spatial.corridor.HashGeometry; import com.indoqa.solr.spatial.corridor.LineStringUtils; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrInputDocument; import org.junit.After; import org.junit.Before; import org.junit.ClassRule;
} @Test public void pointsFarAwaySmallDistance() throws SolrServerException, IOException { SolrQuery query = new SolrQuery("{!frange l=0 u=0.002}pointsDistance(geo, geoHash)"); query.setRows(Integer.MAX_VALUE); query.add("corridor.point", "POINT(16.41 48.19)"); QueryResponse response = infrastructureRule.getSolrClient().query(query); assertEquals(0, response.getResults().getNumFound()); } @Test public void pointsPositionMatch() throws SolrServerException, IOException { SolrQuery query = new SolrQuery("{!frange l=0 u=0.01}pointsDistance(geo, geoHash)"); query.setRows(Integer.MAX_VALUE); query.add("corridor.point", "POINT(16.41618 48.19288)"); query.addField(SOLR_FIELD_ID); query.addField(SOLR_FIELD_POINT_POSITION + ":pointsPosition(geo, geoHash)"); QueryResponse response = infrastructureRule.getSolrClient().query(query); assertEquals(1, response.getResults().getNumFound()); assertEquals(DOCUMENT_ID_1, response.getResults().get(0).getFieldValue(SOLR_FIELD_ID)); assertEquals(0.0475, (double) response.getResults().get(0).getFieldValue(SOLR_FIELD_POINT_POSITION), 0.00009); } @Test public void pointsCacheCleanup() throws SolrServerException, IOException { pointsExactMatch();
// Path: src/main/java/com/indoqa/solr/spatial/corridor/HashGeometry.java // public class HashGeometry { // // private String hash; // private String geometry; // // public String getHash() { // return hash; // } // // public void setHash(String hash) { // this.hash = hash; // } // // public String getGeometry() { // return geometry; // } // // public void setGeometry(String geometry) { // this.geometry = geometry; // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // } // // Path: src/test/java/com/indoqa/solr/spatial/corridor/EmbeddedSolrInfrastructureRule.java // public class EmbeddedSolrInfrastructureRule extends ExternalResource { // // private SolrClient solrClient; // private boolean initialized; // // public SolrClient getSolrClient() { // return this.solrClient; // } // // @Override // protected void after() { // try { // this.solrClient.close(); // } catch (Exception e) { // // ignore // } // // if (this.solrClient instanceof EmbeddedSolrServer) { // EmbeddedSolrServer embeddedSolrServer = (EmbeddedSolrServer) this.solrClient; // embeddedSolrServer.getCoreContainer().shutdown(); // } // } // // @Override // protected void before() throws Throwable { // if (this.initialized) { // return; // } // // this.solrClient = EmbeddedSolrServerBuilder.build("file://./target/test-core", "solr/test"); // // this.initialized = true; // } // } // Path: src/test/java/com/indoqa/solr/spatial/corridor/query/points/TestPointsDistance.java import org.junit.Test; import com.indoqa.solr.spatial.corridor.EmbeddedSolrInfrastructureRule; import static org.junit.Assert.assertEquals; import java.io.IOException; import com.indoqa.solr.spatial.corridor.HashGeometry; import com.indoqa.solr.spatial.corridor.LineStringUtils; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrInputDocument; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; } @Test public void pointsFarAwaySmallDistance() throws SolrServerException, IOException { SolrQuery query = new SolrQuery("{!frange l=0 u=0.002}pointsDistance(geo, geoHash)"); query.setRows(Integer.MAX_VALUE); query.add("corridor.point", "POINT(16.41 48.19)"); QueryResponse response = infrastructureRule.getSolrClient().query(query); assertEquals(0, response.getResults().getNumFound()); } @Test public void pointsPositionMatch() throws SolrServerException, IOException { SolrQuery query = new SolrQuery("{!frange l=0 u=0.01}pointsDistance(geo, geoHash)"); query.setRows(Integer.MAX_VALUE); query.add("corridor.point", "POINT(16.41618 48.19288)"); query.addField(SOLR_FIELD_ID); query.addField(SOLR_FIELD_POINT_POSITION + ":pointsPosition(geo, geoHash)"); QueryResponse response = infrastructureRule.getSolrClient().query(query); assertEquals(1, response.getResults().getNumFound()); assertEquals(DOCUMENT_ID_1, response.getResults().get(0).getFieldValue(SOLR_FIELD_ID)); assertEquals(0.0475, (double) response.getResults().get(0).getFieldValue(SOLR_FIELD_POINT_POSITION), 0.00009); } @Test public void pointsCacheCleanup() throws SolrServerException, IOException { pointsExactMatch();
LineStringUtils.purgeCache();
Indoqa/solr-spatial-corridor
src/main/java/com/indoqa/solr/spatial/corridor/direction/InDirectionPointsValueSourceParser.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringValueSource.java // public class LineStringValueSource extends ValueSource { // // private String linestringFieldName; // // public LineStringValueSource(String linestringFieldName) { // this.linestringFieldName = linestringFieldName; // } // // @Override // public String description() { // return "retrieve raw linestring even for tokenized fields"; // } // // @Override // public boolean equals(Object o) { // return false; // } // // @SuppressWarnings("rawtypes") // @Override // public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { // return new LineStringFunctionValues(this.linestringFieldName, readerContext); // } // // @Override // public int hashCode() { // return ("linestring" + this.linestringFieldName).hashCode(); // } // // }
import com.indoqa.solr.spatial.corridor.LineStringUtils; import com.indoqa.solr.spatial.corridor.LineStringValueSource; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.LineString; import org.locationtech.jts.io.WKTReader; import org.apache.lucene.queries.function.ValueSource; import org.apache.solr.search.FunctionQParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.ValueSourceParser;
/* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.direction; public class InDirectionPointsValueSourceParser extends ValueSourceParser { private final WKTReader wktReader; private final GeometryFactory geometryFactory; public InDirectionPointsValueSourceParser() { super(); this.wktReader = new WKTReader(); this.geometryFactory = new GeometryFactory(); } @Override public ValueSource parse(FunctionQParser fp) throws SyntaxError { String route = fp.getParam("corridor.route");
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringValueSource.java // public class LineStringValueSource extends ValueSource { // // private String linestringFieldName; // // public LineStringValueSource(String linestringFieldName) { // this.linestringFieldName = linestringFieldName; // } // // @Override // public String description() { // return "retrieve raw linestring even for tokenized fields"; // } // // @Override // public boolean equals(Object o) { // return false; // } // // @SuppressWarnings("rawtypes") // @Override // public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { // return new LineStringFunctionValues(this.linestringFieldName, readerContext); // } // // @Override // public int hashCode() { // return ("linestring" + this.linestringFieldName).hashCode(); // } // // } // Path: src/main/java/com/indoqa/solr/spatial/corridor/direction/InDirectionPointsValueSourceParser.java import com.indoqa.solr.spatial.corridor.LineStringUtils; import com.indoqa.solr.spatial.corridor.LineStringValueSource; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.LineString; import org.locationtech.jts.io.WKTReader; import org.apache.lucene.queries.function.ValueSource; import org.apache.solr.search.FunctionQParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.ValueSourceParser; /* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.direction; public class InDirectionPointsValueSourceParser extends ValueSourceParser { private final WKTReader wktReader; private final GeometryFactory geometryFactory; public InDirectionPointsValueSourceParser() { super(); this.wktReader = new WKTReader(); this.geometryFactory = new GeometryFactory(); } @Override public ValueSource parse(FunctionQParser fp) throws SyntaxError { String route = fp.getParam("corridor.route");
LineString lineString = LineStringUtils.parseOrGet(route, String.valueOf(route.hashCode()));
Indoqa/solr-spatial-corridor
src/main/java/com/indoqa/solr/spatial/corridor/direction/InDirectionPointsValueSourceParser.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringValueSource.java // public class LineStringValueSource extends ValueSource { // // private String linestringFieldName; // // public LineStringValueSource(String linestringFieldName) { // this.linestringFieldName = linestringFieldName; // } // // @Override // public String description() { // return "retrieve raw linestring even for tokenized fields"; // } // // @Override // public boolean equals(Object o) { // return false; // } // // @SuppressWarnings("rawtypes") // @Override // public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { // return new LineStringFunctionValues(this.linestringFieldName, readerContext); // } // // @Override // public int hashCode() { // return ("linestring" + this.linestringFieldName).hashCode(); // } // // }
import com.indoqa.solr.spatial.corridor.LineStringUtils; import com.indoqa.solr.spatial.corridor.LineStringValueSource; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.LineString; import org.locationtech.jts.io.WKTReader; import org.apache.lucene.queries.function.ValueSource; import org.apache.solr.search.FunctionQParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.ValueSourceParser;
/* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.direction; public class InDirectionPointsValueSourceParser extends ValueSourceParser { private final WKTReader wktReader; private final GeometryFactory geometryFactory; public InDirectionPointsValueSourceParser() { super(); this.wktReader = new WKTReader(); this.geometryFactory = new GeometryFactory(); } @Override public ValueSource parse(FunctionQParser fp) throws SyntaxError { String route = fp.getParam("corridor.route"); LineString lineString = LineStringUtils.parseOrGet(route, String.valueOf(route.hashCode()));
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringValueSource.java // public class LineStringValueSource extends ValueSource { // // private String linestringFieldName; // // public LineStringValueSource(String linestringFieldName) { // this.linestringFieldName = linestringFieldName; // } // // @Override // public String description() { // return "retrieve raw linestring even for tokenized fields"; // } // // @Override // public boolean equals(Object o) { // return false; // } // // @SuppressWarnings("rawtypes") // @Override // public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { // return new LineStringFunctionValues(this.linestringFieldName, readerContext); // } // // @Override // public int hashCode() { // return ("linestring" + this.linestringFieldName).hashCode(); // } // // } // Path: src/main/java/com/indoqa/solr/spatial/corridor/direction/InDirectionPointsValueSourceParser.java import com.indoqa.solr.spatial.corridor.LineStringUtils; import com.indoqa.solr.spatial.corridor.LineStringValueSource; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.LineString; import org.locationtech.jts.io.WKTReader; import org.apache.lucene.queries.function.ValueSource; import org.apache.solr.search.FunctionQParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.ValueSourceParser; /* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.direction; public class InDirectionPointsValueSourceParser extends ValueSourceParser { private final WKTReader wktReader; private final GeometryFactory geometryFactory; public InDirectionPointsValueSourceParser() { super(); this.wktReader = new WKTReader(); this.geometryFactory = new GeometryFactory(); } @Override public ValueSource parse(FunctionQParser fp) throws SyntaxError { String route = fp.getParam("corridor.route"); LineString lineString = LineStringUtils.parseOrGet(route, String.valueOf(route.hashCode()));
ValueSource locationValueSource = new LineStringValueSource(fp.parseArg());
Indoqa/solr-spatial-corridor
src/main/java/com/indoqa/solr/spatial/corridor/query/points/AbstractPointsQueryCorridorValueSource.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // }
import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; import java.util.Map; import com.indoqa.solr.spatial.corridor.LineStringUtils; import org.apache.commons.lang3.ObjectUtils; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.queries.function.FunctionValues; import org.apache.lucene.queries.function.ValueSource; import org.apache.lucene.queries.function.docvalues.DoubleDocValues; import org.locationtech.jts.geom.LineString; import org.locationtech.jts.geom.Point; import org.slf4j.Logger;
result = prime * result + (this.routeValueSource == null ? 0 : this.routeValueSource.hashCode()); result = prime * result + (this.queryPoints == null ? 0 : this.queryPoints.hashCode()); result = prime * result + (this.description() == null ? 0 : this.description().hashCode()); return result; } protected abstract double getValue(LineString lineString); private final class InverseCorridorDocValues extends DoubleDocValues { private FunctionValues routeValues; private FunctionValues hashValues; protected InverseCorridorDocValues(ValueSource vs, FunctionValues routeValues, FunctionValues hashValues) { super(vs); this.routeValues = routeValues; this.hashValues = hashValues; } @Override public double doubleVal(int docId) throws IOException { String routeAsString = this.routeValues.strVal(docId); String routeAsHash = this.hashValues.strVal(docId); try{ if (routeAsString == null || routeAsString.isEmpty()) { return Double.MAX_VALUE; }
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // } // Path: src/main/java/com/indoqa/solr/spatial/corridor/query/points/AbstractPointsQueryCorridorValueSource.java import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; import java.util.Map; import com.indoqa.solr.spatial.corridor.LineStringUtils; import org.apache.commons.lang3.ObjectUtils; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.queries.function.FunctionValues; import org.apache.lucene.queries.function.ValueSource; import org.apache.lucene.queries.function.docvalues.DoubleDocValues; import org.locationtech.jts.geom.LineString; import org.locationtech.jts.geom.Point; import org.slf4j.Logger; result = prime * result + (this.routeValueSource == null ? 0 : this.routeValueSource.hashCode()); result = prime * result + (this.queryPoints == null ? 0 : this.queryPoints.hashCode()); result = prime * result + (this.description() == null ? 0 : this.description().hashCode()); return result; } protected abstract double getValue(LineString lineString); private final class InverseCorridorDocValues extends DoubleDocValues { private FunctionValues routeValues; private FunctionValues hashValues; protected InverseCorridorDocValues(ValueSource vs, FunctionValues routeValues, FunctionValues hashValues) { super(vs); this.routeValues = routeValues; this.hashValues = hashValues; } @Override public double doubleVal(int docId) throws IOException { String routeAsString = this.routeValues.strVal(docId); String routeAsHash = this.hashValues.strVal(docId); try{ if (routeAsString == null || routeAsString.isEmpty()) { return Double.MAX_VALUE; }
LineString route = LineStringUtils.parseOrGet(routeAsString, routeAsHash);
Indoqa/solr-spatial-corridor
src/main/java/com/indoqa/solr/spatial/corridor/direction/DirectionValueSourceParser.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/wkt/WktUtils.java // public class WktUtils { // // private static final Logger LOGGER = LoggerFactory.getLogger(WktUtils.class); // // private static final GeometryFactory geometryFactory = new GeometryFactory(); // // public static LineString parseLineString(String corridorLineString) { // String rawCoordinates = StringUtils.substringBetween(corridorLineString, "LINESTRING(", ")"); // if (rawCoordinates == null || rawCoordinates.trim().isEmpty()) { // LOGGER.warn("Linestring without coordinates found: '{}'", corridorLineString); // return geometryFactory.createLineString((Coordinate[]) null); // } // String[] coordinates = rawCoordinates.trim().split(","); // // Coordinate[] wktCoordinates = Arrays.stream(coordinates).map(WktUtils::createCoordinate).toArray(Coordinate[]::new); // return geometryFactory.createLineString(wktCoordinates); // } // // public static Point parsePoint(String pointString) { // String rawPoints = StringUtils.substringBetween(pointString, "POINT(", ")"); // if (rawPoints == null) { // throw new IllegalArgumentException("Parameter must be a valid WKT Point!"); // } // // Coordinate coordinate = createCoordinate(rawPoints); // return geometryFactory.createPoint(coordinate); // } // // private static Coordinate createCoordinate(String rawCoordinates) { // String[] points = rawCoordinates.trim().split(" "); // // Coordinate coordinate = new Coordinate(); // coordinate.x = Double.parseDouble(points[0]); // coordinate.y = Double.parseDouble(points[1]); // geometryFactory.getPrecisionModel().makePrecise(coordinate); // return coordinate; // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringValueSource.java // public class LineStringValueSource extends ValueSource { // // private String linestringFieldName; // // public LineStringValueSource(String linestringFieldName) { // this.linestringFieldName = linestringFieldName; // } // // @Override // public String description() { // return "retrieve raw linestring even for tokenized fields"; // } // // @Override // public boolean equals(Object o) { // return false; // } // // @SuppressWarnings("rawtypes") // @Override // public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { // return new LineStringFunctionValues(this.linestringFieldName, readerContext); // } // // @Override // public int hashCode() { // return ("linestring" + this.linestringFieldName).hashCode(); // } // // }
import org.locationtech.jts.geom.Point; import org.locationtech.jts.io.ParseException; import org.locationtech.jts.io.WKTReader; import java.util.ArrayList; import java.util.List; import com.indoqa.solr.spatial.corridor.wkt.WktUtils; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.GeometryFactory; import org.apache.commons.lang3.StringUtils; import org.apache.lucene.queries.function.ValueSource; import org.apache.solr.schema.StrFieldSource; import org.apache.solr.search.FunctionQParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.ValueSourceParser; import com.indoqa.solr.spatial.corridor.LineStringValueSource;
/* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.direction; public class DirectionValueSourceParser extends ValueSourceParser { private final WKTReader wktReader; private final GeometryFactory geometryFactory; public DirectionValueSourceParser(){ super(); this.wktReader = new WKTReader(); this.geometryFactory = new GeometryFactory(); } @Override public ValueSource parse(FunctionQParser fp) throws SyntaxError { List<Point> queryPoints = new ArrayList<>(); String[] queryPointParameters = fp.getParams().getParams("corridor.point"); for (String queryPointParameter : queryPointParameters) {
// Path: src/main/java/com/indoqa/solr/spatial/corridor/wkt/WktUtils.java // public class WktUtils { // // private static final Logger LOGGER = LoggerFactory.getLogger(WktUtils.class); // // private static final GeometryFactory geometryFactory = new GeometryFactory(); // // public static LineString parseLineString(String corridorLineString) { // String rawCoordinates = StringUtils.substringBetween(corridorLineString, "LINESTRING(", ")"); // if (rawCoordinates == null || rawCoordinates.trim().isEmpty()) { // LOGGER.warn("Linestring without coordinates found: '{}'", corridorLineString); // return geometryFactory.createLineString((Coordinate[]) null); // } // String[] coordinates = rawCoordinates.trim().split(","); // // Coordinate[] wktCoordinates = Arrays.stream(coordinates).map(WktUtils::createCoordinate).toArray(Coordinate[]::new); // return geometryFactory.createLineString(wktCoordinates); // } // // public static Point parsePoint(String pointString) { // String rawPoints = StringUtils.substringBetween(pointString, "POINT(", ")"); // if (rawPoints == null) { // throw new IllegalArgumentException("Parameter must be a valid WKT Point!"); // } // // Coordinate coordinate = createCoordinate(rawPoints); // return geometryFactory.createPoint(coordinate); // } // // private static Coordinate createCoordinate(String rawCoordinates) { // String[] points = rawCoordinates.trim().split(" "); // // Coordinate coordinate = new Coordinate(); // coordinate.x = Double.parseDouble(points[0]); // coordinate.y = Double.parseDouble(points[1]); // geometryFactory.getPrecisionModel().makePrecise(coordinate); // return coordinate; // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringValueSource.java // public class LineStringValueSource extends ValueSource { // // private String linestringFieldName; // // public LineStringValueSource(String linestringFieldName) { // this.linestringFieldName = linestringFieldName; // } // // @Override // public String description() { // return "retrieve raw linestring even for tokenized fields"; // } // // @Override // public boolean equals(Object o) { // return false; // } // // @SuppressWarnings("rawtypes") // @Override // public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { // return new LineStringFunctionValues(this.linestringFieldName, readerContext); // } // // @Override // public int hashCode() { // return ("linestring" + this.linestringFieldName).hashCode(); // } // // } // Path: src/main/java/com/indoqa/solr/spatial/corridor/direction/DirectionValueSourceParser.java import org.locationtech.jts.geom.Point; import org.locationtech.jts.io.ParseException; import org.locationtech.jts.io.WKTReader; import java.util.ArrayList; import java.util.List; import com.indoqa.solr.spatial.corridor.wkt.WktUtils; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.GeometryFactory; import org.apache.commons.lang3.StringUtils; import org.apache.lucene.queries.function.ValueSource; import org.apache.solr.schema.StrFieldSource; import org.apache.solr.search.FunctionQParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.ValueSourceParser; import com.indoqa.solr.spatial.corridor.LineStringValueSource; /* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.direction; public class DirectionValueSourceParser extends ValueSourceParser { private final WKTReader wktReader; private final GeometryFactory geometryFactory; public DirectionValueSourceParser(){ super(); this.wktReader = new WKTReader(); this.geometryFactory = new GeometryFactory(); } @Override public ValueSource parse(FunctionQParser fp) throws SyntaxError { List<Point> queryPoints = new ArrayList<>(); String[] queryPointParameters = fp.getParams().getParams("corridor.point"); for (String queryPointParameter : queryPointParameters) {
queryPoints.add(WktUtils.parsePoint(queryPointParameter));
Indoqa/solr-spatial-corridor
src/main/java/com/indoqa/solr/spatial/corridor/direction/DirectionValueSourceParser.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/wkt/WktUtils.java // public class WktUtils { // // private static final Logger LOGGER = LoggerFactory.getLogger(WktUtils.class); // // private static final GeometryFactory geometryFactory = new GeometryFactory(); // // public static LineString parseLineString(String corridorLineString) { // String rawCoordinates = StringUtils.substringBetween(corridorLineString, "LINESTRING(", ")"); // if (rawCoordinates == null || rawCoordinates.trim().isEmpty()) { // LOGGER.warn("Linestring without coordinates found: '{}'", corridorLineString); // return geometryFactory.createLineString((Coordinate[]) null); // } // String[] coordinates = rawCoordinates.trim().split(","); // // Coordinate[] wktCoordinates = Arrays.stream(coordinates).map(WktUtils::createCoordinate).toArray(Coordinate[]::new); // return geometryFactory.createLineString(wktCoordinates); // } // // public static Point parsePoint(String pointString) { // String rawPoints = StringUtils.substringBetween(pointString, "POINT(", ")"); // if (rawPoints == null) { // throw new IllegalArgumentException("Parameter must be a valid WKT Point!"); // } // // Coordinate coordinate = createCoordinate(rawPoints); // return geometryFactory.createPoint(coordinate); // } // // private static Coordinate createCoordinate(String rawCoordinates) { // String[] points = rawCoordinates.trim().split(" "); // // Coordinate coordinate = new Coordinate(); // coordinate.x = Double.parseDouble(points[0]); // coordinate.y = Double.parseDouble(points[1]); // geometryFactory.getPrecisionModel().makePrecise(coordinate); // return coordinate; // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringValueSource.java // public class LineStringValueSource extends ValueSource { // // private String linestringFieldName; // // public LineStringValueSource(String linestringFieldName) { // this.linestringFieldName = linestringFieldName; // } // // @Override // public String description() { // return "retrieve raw linestring even for tokenized fields"; // } // // @Override // public boolean equals(Object o) { // return false; // } // // @SuppressWarnings("rawtypes") // @Override // public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { // return new LineStringFunctionValues(this.linestringFieldName, readerContext); // } // // @Override // public int hashCode() { // return ("linestring" + this.linestringFieldName).hashCode(); // } // // }
import org.locationtech.jts.geom.Point; import org.locationtech.jts.io.ParseException; import org.locationtech.jts.io.WKTReader; import java.util.ArrayList; import java.util.List; import com.indoqa.solr.spatial.corridor.wkt.WktUtils; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.GeometryFactory; import org.apache.commons.lang3.StringUtils; import org.apache.lucene.queries.function.ValueSource; import org.apache.solr.schema.StrFieldSource; import org.apache.solr.search.FunctionQParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.ValueSourceParser; import com.indoqa.solr.spatial.corridor.LineStringValueSource;
/* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.direction; public class DirectionValueSourceParser extends ValueSourceParser { private final WKTReader wktReader; private final GeometryFactory geometryFactory; public DirectionValueSourceParser(){ super(); this.wktReader = new WKTReader(); this.geometryFactory = new GeometryFactory(); } @Override public ValueSource parse(FunctionQParser fp) throws SyntaxError { List<Point> queryPoints = new ArrayList<>(); String[] queryPointParameters = fp.getParams().getParams("corridor.point"); for (String queryPointParameter : queryPointParameters) { queryPoints.add(WktUtils.parsePoint(queryPointParameter)); } double pointsMaxDistanceToRoute = fp.getParams().getDouble("corridor.pointsMaxDistanceToRoute", 0.01);
// Path: src/main/java/com/indoqa/solr/spatial/corridor/wkt/WktUtils.java // public class WktUtils { // // private static final Logger LOGGER = LoggerFactory.getLogger(WktUtils.class); // // private static final GeometryFactory geometryFactory = new GeometryFactory(); // // public static LineString parseLineString(String corridorLineString) { // String rawCoordinates = StringUtils.substringBetween(corridorLineString, "LINESTRING(", ")"); // if (rawCoordinates == null || rawCoordinates.trim().isEmpty()) { // LOGGER.warn("Linestring without coordinates found: '{}'", corridorLineString); // return geometryFactory.createLineString((Coordinate[]) null); // } // String[] coordinates = rawCoordinates.trim().split(","); // // Coordinate[] wktCoordinates = Arrays.stream(coordinates).map(WktUtils::createCoordinate).toArray(Coordinate[]::new); // return geometryFactory.createLineString(wktCoordinates); // } // // public static Point parsePoint(String pointString) { // String rawPoints = StringUtils.substringBetween(pointString, "POINT(", ")"); // if (rawPoints == null) { // throw new IllegalArgumentException("Parameter must be a valid WKT Point!"); // } // // Coordinate coordinate = createCoordinate(rawPoints); // return geometryFactory.createPoint(coordinate); // } // // private static Coordinate createCoordinate(String rawCoordinates) { // String[] points = rawCoordinates.trim().split(" "); // // Coordinate coordinate = new Coordinate(); // coordinate.x = Double.parseDouble(points[0]); // coordinate.y = Double.parseDouble(points[1]); // geometryFactory.getPrecisionModel().makePrecise(coordinate); // return coordinate; // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringValueSource.java // public class LineStringValueSource extends ValueSource { // // private String linestringFieldName; // // public LineStringValueSource(String linestringFieldName) { // this.linestringFieldName = linestringFieldName; // } // // @Override // public String description() { // return "retrieve raw linestring even for tokenized fields"; // } // // @Override // public boolean equals(Object o) { // return false; // } // // @SuppressWarnings("rawtypes") // @Override // public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { // return new LineStringFunctionValues(this.linestringFieldName, readerContext); // } // // @Override // public int hashCode() { // return ("linestring" + this.linestringFieldName).hashCode(); // } // // } // Path: src/main/java/com/indoqa/solr/spatial/corridor/direction/DirectionValueSourceParser.java import org.locationtech.jts.geom.Point; import org.locationtech.jts.io.ParseException; import org.locationtech.jts.io.WKTReader; import java.util.ArrayList; import java.util.List; import com.indoqa.solr.spatial.corridor.wkt.WktUtils; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.GeometryFactory; import org.apache.commons.lang3.StringUtils; import org.apache.lucene.queries.function.ValueSource; import org.apache.solr.schema.StrFieldSource; import org.apache.solr.search.FunctionQParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.ValueSourceParser; import com.indoqa.solr.spatial.corridor.LineStringValueSource; /* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.direction; public class DirectionValueSourceParser extends ValueSourceParser { private final WKTReader wktReader; private final GeometryFactory geometryFactory; public DirectionValueSourceParser(){ super(); this.wktReader = new WKTReader(); this.geometryFactory = new GeometryFactory(); } @Override public ValueSource parse(FunctionQParser fp) throws SyntaxError { List<Point> queryPoints = new ArrayList<>(); String[] queryPointParameters = fp.getParams().getParams("corridor.point"); for (String queryPointParameter : queryPointParameters) { queryPoints.add(WktUtils.parsePoint(queryPointParameter)); } double pointsMaxDistanceToRoute = fp.getParams().getDouble("corridor.pointsMaxDistanceToRoute", 0.01);
return this.createValueSource(queryPoints, new LineStringValueSource(fp.parseArg()), fp.parseValueSource(), pointsMaxDistanceToRoute);
Indoqa/solr-spatial-corridor
src/main/java/com/indoqa/solr/spatial/corridor/query/circle/CircleDistanceValueSourceParser.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringValueSource.java // public class LineStringValueSource extends ValueSource { // // private String linestringFieldName; // // public LineStringValueSource(String linestringFieldName) { // this.linestringFieldName = linestringFieldName; // } // // @Override // public String description() { // return "retrieve raw linestring even for tokenized fields"; // } // // @Override // public boolean equals(Object o) { // return false; // } // // @SuppressWarnings("rawtypes") // @Override // public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { // return new LineStringFunctionValues(this.linestringFieldName, readerContext); // } // // @Override // public int hashCode() { // return ("linestring" + this.linestringFieldName).hashCode(); // } // // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/wkt/WktUtils.java // public class WktUtils { // // private static final Logger LOGGER = LoggerFactory.getLogger(WktUtils.class); // // private static final GeometryFactory geometryFactory = new GeometryFactory(); // // public static LineString parseLineString(String corridorLineString) { // String rawCoordinates = StringUtils.substringBetween(corridorLineString, "LINESTRING(", ")"); // if (rawCoordinates == null || rawCoordinates.trim().isEmpty()) { // LOGGER.warn("Linestring without coordinates found: '{}'", corridorLineString); // return geometryFactory.createLineString((Coordinate[]) null); // } // String[] coordinates = rawCoordinates.trim().split(","); // // Coordinate[] wktCoordinates = Arrays.stream(coordinates).map(WktUtils::createCoordinate).toArray(Coordinate[]::new); // return geometryFactory.createLineString(wktCoordinates); // } // // public static Point parsePoint(String pointString) { // String rawPoints = StringUtils.substringBetween(pointString, "POINT(", ")"); // if (rawPoints == null) { // throw new IllegalArgumentException("Parameter must be a valid WKT Point!"); // } // // Coordinate coordinate = createCoordinate(rawPoints); // return geometryFactory.createPoint(coordinate); // } // // private static Coordinate createCoordinate(String rawCoordinates) { // String[] points = rawCoordinates.trim().split(" "); // // Coordinate coordinate = new Coordinate(); // coordinate.x = Double.parseDouble(points[0]); // coordinate.y = Double.parseDouble(points[1]); // geometryFactory.getPrecisionModel().makePrecise(coordinate); // return coordinate; // } // }
import java.util.ArrayList; import java.util.List; import com.indoqa.solr.spatial.corridor.LineStringValueSource; import com.indoqa.solr.spatial.corridor.wkt.WktUtils; import org.apache.lucene.queries.function.ValueSource; import org.apache.solr.search.FunctionQParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.ValueSourceParser; import org.locationtech.jts.geom.Point;
/* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.query.circle; public class CircleDistanceValueSourceParser extends ValueSourceParser { @Override public ValueSource parse(FunctionQParser fp) throws SyntaxError { List<Point> queryPoints = new ArrayList<>(); String queryRadiusParameter = fp.getParam("corridor.circle.radius"); Double radius = null; try { radius = Double.parseDouble(queryRadiusParameter); } catch (NullPointerException | NumberFormatException e) { throw new IllegalArgumentException("Parameter must be a double!", e); } String[] queryPointParameters = fp.getParams().getParams("corridor.circle.point"); for (String queryPointParameter : queryPointParameters) {
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringValueSource.java // public class LineStringValueSource extends ValueSource { // // private String linestringFieldName; // // public LineStringValueSource(String linestringFieldName) { // this.linestringFieldName = linestringFieldName; // } // // @Override // public String description() { // return "retrieve raw linestring even for tokenized fields"; // } // // @Override // public boolean equals(Object o) { // return false; // } // // @SuppressWarnings("rawtypes") // @Override // public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { // return new LineStringFunctionValues(this.linestringFieldName, readerContext); // } // // @Override // public int hashCode() { // return ("linestring" + this.linestringFieldName).hashCode(); // } // // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/wkt/WktUtils.java // public class WktUtils { // // private static final Logger LOGGER = LoggerFactory.getLogger(WktUtils.class); // // private static final GeometryFactory geometryFactory = new GeometryFactory(); // // public static LineString parseLineString(String corridorLineString) { // String rawCoordinates = StringUtils.substringBetween(corridorLineString, "LINESTRING(", ")"); // if (rawCoordinates == null || rawCoordinates.trim().isEmpty()) { // LOGGER.warn("Linestring without coordinates found: '{}'", corridorLineString); // return geometryFactory.createLineString((Coordinate[]) null); // } // String[] coordinates = rawCoordinates.trim().split(","); // // Coordinate[] wktCoordinates = Arrays.stream(coordinates).map(WktUtils::createCoordinate).toArray(Coordinate[]::new); // return geometryFactory.createLineString(wktCoordinates); // } // // public static Point parsePoint(String pointString) { // String rawPoints = StringUtils.substringBetween(pointString, "POINT(", ")"); // if (rawPoints == null) { // throw new IllegalArgumentException("Parameter must be a valid WKT Point!"); // } // // Coordinate coordinate = createCoordinate(rawPoints); // return geometryFactory.createPoint(coordinate); // } // // private static Coordinate createCoordinate(String rawCoordinates) { // String[] points = rawCoordinates.trim().split(" "); // // Coordinate coordinate = new Coordinate(); // coordinate.x = Double.parseDouble(points[0]); // coordinate.y = Double.parseDouble(points[1]); // geometryFactory.getPrecisionModel().makePrecise(coordinate); // return coordinate; // } // } // Path: src/main/java/com/indoqa/solr/spatial/corridor/query/circle/CircleDistanceValueSourceParser.java import java.util.ArrayList; import java.util.List; import com.indoqa.solr.spatial.corridor.LineStringValueSource; import com.indoqa.solr.spatial.corridor.wkt.WktUtils; import org.apache.lucene.queries.function.ValueSource; import org.apache.solr.search.FunctionQParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.ValueSourceParser; import org.locationtech.jts.geom.Point; /* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.query.circle; public class CircleDistanceValueSourceParser extends ValueSourceParser { @Override public ValueSource parse(FunctionQParser fp) throws SyntaxError { List<Point> queryPoints = new ArrayList<>(); String queryRadiusParameter = fp.getParam("corridor.circle.radius"); Double radius = null; try { radius = Double.parseDouble(queryRadiusParameter); } catch (NullPointerException | NumberFormatException e) { throw new IllegalArgumentException("Parameter must be a double!", e); } String[] queryPointParameters = fp.getParams().getParams("corridor.circle.point"); for (String queryPointParameter : queryPointParameters) {
queryPoints.add(WktUtils.parsePoint(queryPointParameter));
Indoqa/solr-spatial-corridor
src/main/java/com/indoqa/solr/spatial/corridor/query/circle/CircleDistanceValueSourceParser.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringValueSource.java // public class LineStringValueSource extends ValueSource { // // private String linestringFieldName; // // public LineStringValueSource(String linestringFieldName) { // this.linestringFieldName = linestringFieldName; // } // // @Override // public String description() { // return "retrieve raw linestring even for tokenized fields"; // } // // @Override // public boolean equals(Object o) { // return false; // } // // @SuppressWarnings("rawtypes") // @Override // public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { // return new LineStringFunctionValues(this.linestringFieldName, readerContext); // } // // @Override // public int hashCode() { // return ("linestring" + this.linestringFieldName).hashCode(); // } // // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/wkt/WktUtils.java // public class WktUtils { // // private static final Logger LOGGER = LoggerFactory.getLogger(WktUtils.class); // // private static final GeometryFactory geometryFactory = new GeometryFactory(); // // public static LineString parseLineString(String corridorLineString) { // String rawCoordinates = StringUtils.substringBetween(corridorLineString, "LINESTRING(", ")"); // if (rawCoordinates == null || rawCoordinates.trim().isEmpty()) { // LOGGER.warn("Linestring without coordinates found: '{}'", corridorLineString); // return geometryFactory.createLineString((Coordinate[]) null); // } // String[] coordinates = rawCoordinates.trim().split(","); // // Coordinate[] wktCoordinates = Arrays.stream(coordinates).map(WktUtils::createCoordinate).toArray(Coordinate[]::new); // return geometryFactory.createLineString(wktCoordinates); // } // // public static Point parsePoint(String pointString) { // String rawPoints = StringUtils.substringBetween(pointString, "POINT(", ")"); // if (rawPoints == null) { // throw new IllegalArgumentException("Parameter must be a valid WKT Point!"); // } // // Coordinate coordinate = createCoordinate(rawPoints); // return geometryFactory.createPoint(coordinate); // } // // private static Coordinate createCoordinate(String rawCoordinates) { // String[] points = rawCoordinates.trim().split(" "); // // Coordinate coordinate = new Coordinate(); // coordinate.x = Double.parseDouble(points[0]); // coordinate.y = Double.parseDouble(points[1]); // geometryFactory.getPrecisionModel().makePrecise(coordinate); // return coordinate; // } // }
import java.util.ArrayList; import java.util.List; import com.indoqa.solr.spatial.corridor.LineStringValueSource; import com.indoqa.solr.spatial.corridor.wkt.WktUtils; import org.apache.lucene.queries.function.ValueSource; import org.apache.solr.search.FunctionQParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.ValueSourceParser; import org.locationtech.jts.geom.Point;
/* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.query.circle; public class CircleDistanceValueSourceParser extends ValueSourceParser { @Override public ValueSource parse(FunctionQParser fp) throws SyntaxError { List<Point> queryPoints = new ArrayList<>(); String queryRadiusParameter = fp.getParam("corridor.circle.radius"); Double radius = null; try { radius = Double.parseDouble(queryRadiusParameter); } catch (NullPointerException | NumberFormatException e) { throw new IllegalArgumentException("Parameter must be a double!", e); } String[] queryPointParameters = fp.getParams().getParams("corridor.circle.point"); for (String queryPointParameter : queryPointParameters) { queryPoints.add(WktUtils.parsePoint(queryPointParameter)); }
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringValueSource.java // public class LineStringValueSource extends ValueSource { // // private String linestringFieldName; // // public LineStringValueSource(String linestringFieldName) { // this.linestringFieldName = linestringFieldName; // } // // @Override // public String description() { // return "retrieve raw linestring even for tokenized fields"; // } // // @Override // public boolean equals(Object o) { // return false; // } // // @SuppressWarnings("rawtypes") // @Override // public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { // return new LineStringFunctionValues(this.linestringFieldName, readerContext); // } // // @Override // public int hashCode() { // return ("linestring" + this.linestringFieldName).hashCode(); // } // // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/wkt/WktUtils.java // public class WktUtils { // // private static final Logger LOGGER = LoggerFactory.getLogger(WktUtils.class); // // private static final GeometryFactory geometryFactory = new GeometryFactory(); // // public static LineString parseLineString(String corridorLineString) { // String rawCoordinates = StringUtils.substringBetween(corridorLineString, "LINESTRING(", ")"); // if (rawCoordinates == null || rawCoordinates.trim().isEmpty()) { // LOGGER.warn("Linestring without coordinates found: '{}'", corridorLineString); // return geometryFactory.createLineString((Coordinate[]) null); // } // String[] coordinates = rawCoordinates.trim().split(","); // // Coordinate[] wktCoordinates = Arrays.stream(coordinates).map(WktUtils::createCoordinate).toArray(Coordinate[]::new); // return geometryFactory.createLineString(wktCoordinates); // } // // public static Point parsePoint(String pointString) { // String rawPoints = StringUtils.substringBetween(pointString, "POINT(", ")"); // if (rawPoints == null) { // throw new IllegalArgumentException("Parameter must be a valid WKT Point!"); // } // // Coordinate coordinate = createCoordinate(rawPoints); // return geometryFactory.createPoint(coordinate); // } // // private static Coordinate createCoordinate(String rawCoordinates) { // String[] points = rawCoordinates.trim().split(" "); // // Coordinate coordinate = new Coordinate(); // coordinate.x = Double.parseDouble(points[0]); // coordinate.y = Double.parseDouble(points[1]); // geometryFactory.getPrecisionModel().makePrecise(coordinate); // return coordinate; // } // } // Path: src/main/java/com/indoqa/solr/spatial/corridor/query/circle/CircleDistanceValueSourceParser.java import java.util.ArrayList; import java.util.List; import com.indoqa.solr.spatial.corridor.LineStringValueSource; import com.indoqa.solr.spatial.corridor.wkt.WktUtils; import org.apache.lucene.queries.function.ValueSource; import org.apache.solr.search.FunctionQParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.ValueSourceParser; import org.locationtech.jts.geom.Point; /* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.query.circle; public class CircleDistanceValueSourceParser extends ValueSourceParser { @Override public ValueSource parse(FunctionQParser fp) throws SyntaxError { List<Point> queryPoints = new ArrayList<>(); String queryRadiusParameter = fp.getParam("corridor.circle.radius"); Double radius = null; try { radius = Double.parseDouble(queryRadiusParameter); } catch (NullPointerException | NumberFormatException e) { throw new IllegalArgumentException("Parameter must be a double!", e); } String[] queryPointParameters = fp.getParams().getParams("corridor.circle.point"); for (String queryPointParameter : queryPointParameters) { queryPoints.add(WktUtils.parsePoint(queryPointParameter)); }
return new CircleDistanceValueSource(radius, queryPoints, new LineStringValueSource(fp.parseArg()), fp.parseValueSource());
Indoqa/solr-spatial-corridor
src/main/java/com/indoqa/solr/spatial/corridor/query/points/AbstractPointsQueryCorridorValueSourceParser.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringValueSource.java // public class LineStringValueSource extends ValueSource { // // private String linestringFieldName; // // public LineStringValueSource(String linestringFieldName) { // this.linestringFieldName = linestringFieldName; // } // // @Override // public String description() { // return "retrieve raw linestring even for tokenized fields"; // } // // @Override // public boolean equals(Object o) { // return false; // } // // @SuppressWarnings("rawtypes") // @Override // public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { // return new LineStringFunctionValues(this.linestringFieldName, readerContext); // } // // @Override // public int hashCode() { // return ("linestring" + this.linestringFieldName).hashCode(); // } // // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/wkt/WktUtils.java // public class WktUtils { // // private static final Logger LOGGER = LoggerFactory.getLogger(WktUtils.class); // // private static final GeometryFactory geometryFactory = new GeometryFactory(); // // public static LineString parseLineString(String corridorLineString) { // String rawCoordinates = StringUtils.substringBetween(corridorLineString, "LINESTRING(", ")"); // if (rawCoordinates == null || rawCoordinates.trim().isEmpty()) { // LOGGER.warn("Linestring without coordinates found: '{}'", corridorLineString); // return geometryFactory.createLineString((Coordinate[]) null); // } // String[] coordinates = rawCoordinates.trim().split(","); // // Coordinate[] wktCoordinates = Arrays.stream(coordinates).map(WktUtils::createCoordinate).toArray(Coordinate[]::new); // return geometryFactory.createLineString(wktCoordinates); // } // // public static Point parsePoint(String pointString) { // String rawPoints = StringUtils.substringBetween(pointString, "POINT(", ")"); // if (rawPoints == null) { // throw new IllegalArgumentException("Parameter must be a valid WKT Point!"); // } // // Coordinate coordinate = createCoordinate(rawPoints); // return geometryFactory.createPoint(coordinate); // } // // private static Coordinate createCoordinate(String rawCoordinates) { // String[] points = rawCoordinates.trim().split(" "); // // Coordinate coordinate = new Coordinate(); // coordinate.x = Double.parseDouble(points[0]); // coordinate.y = Double.parseDouble(points[1]); // geometryFactory.getPrecisionModel().makePrecise(coordinate); // return coordinate; // } // }
import java.util.ArrayList; import java.util.List; import com.indoqa.solr.spatial.corridor.LineStringValueSource; import com.indoqa.solr.spatial.corridor.wkt.WktUtils; import org.apache.lucene.queries.function.ValueSource; import org.apache.solr.schema.StrFieldSource; import org.apache.solr.search.FunctionQParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.ValueSourceParser; import org.locationtech.jts.geom.Point;
/* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.query.points; public abstract class AbstractPointsQueryCorridorValueSourceParser extends ValueSourceParser { @Override public ValueSource parse(FunctionQParser fp) throws SyntaxError { List<Point> queryPoints = new ArrayList<>(); String[] queryPointParameters = fp.getParams().getParams("corridor.point"); for (String queryPointParameter : queryPointParameters) {
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringValueSource.java // public class LineStringValueSource extends ValueSource { // // private String linestringFieldName; // // public LineStringValueSource(String linestringFieldName) { // this.linestringFieldName = linestringFieldName; // } // // @Override // public String description() { // return "retrieve raw linestring even for tokenized fields"; // } // // @Override // public boolean equals(Object o) { // return false; // } // // @SuppressWarnings("rawtypes") // @Override // public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { // return new LineStringFunctionValues(this.linestringFieldName, readerContext); // } // // @Override // public int hashCode() { // return ("linestring" + this.linestringFieldName).hashCode(); // } // // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/wkt/WktUtils.java // public class WktUtils { // // private static final Logger LOGGER = LoggerFactory.getLogger(WktUtils.class); // // private static final GeometryFactory geometryFactory = new GeometryFactory(); // // public static LineString parseLineString(String corridorLineString) { // String rawCoordinates = StringUtils.substringBetween(corridorLineString, "LINESTRING(", ")"); // if (rawCoordinates == null || rawCoordinates.trim().isEmpty()) { // LOGGER.warn("Linestring without coordinates found: '{}'", corridorLineString); // return geometryFactory.createLineString((Coordinate[]) null); // } // String[] coordinates = rawCoordinates.trim().split(","); // // Coordinate[] wktCoordinates = Arrays.stream(coordinates).map(WktUtils::createCoordinate).toArray(Coordinate[]::new); // return geometryFactory.createLineString(wktCoordinates); // } // // public static Point parsePoint(String pointString) { // String rawPoints = StringUtils.substringBetween(pointString, "POINT(", ")"); // if (rawPoints == null) { // throw new IllegalArgumentException("Parameter must be a valid WKT Point!"); // } // // Coordinate coordinate = createCoordinate(rawPoints); // return geometryFactory.createPoint(coordinate); // } // // private static Coordinate createCoordinate(String rawCoordinates) { // String[] points = rawCoordinates.trim().split(" "); // // Coordinate coordinate = new Coordinate(); // coordinate.x = Double.parseDouble(points[0]); // coordinate.y = Double.parseDouble(points[1]); // geometryFactory.getPrecisionModel().makePrecise(coordinate); // return coordinate; // } // } // Path: src/main/java/com/indoqa/solr/spatial/corridor/query/points/AbstractPointsQueryCorridorValueSourceParser.java import java.util.ArrayList; import java.util.List; import com.indoqa.solr.spatial.corridor.LineStringValueSource; import com.indoqa.solr.spatial.corridor.wkt.WktUtils; import org.apache.lucene.queries.function.ValueSource; import org.apache.solr.schema.StrFieldSource; import org.apache.solr.search.FunctionQParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.ValueSourceParser; import org.locationtech.jts.geom.Point; /* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.query.points; public abstract class AbstractPointsQueryCorridorValueSourceParser extends ValueSourceParser { @Override public ValueSource parse(FunctionQParser fp) throws SyntaxError { List<Point> queryPoints = new ArrayList<>(); String[] queryPointParameters = fp.getParams().getParams("corridor.point"); for (String queryPointParameter : queryPointParameters) {
queryPoints.add(WktUtils.parsePoint(queryPointParameter));
Indoqa/solr-spatial-corridor
src/main/java/com/indoqa/solr/spatial/corridor/query/points/AbstractPointsQueryCorridorValueSourceParser.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringValueSource.java // public class LineStringValueSource extends ValueSource { // // private String linestringFieldName; // // public LineStringValueSource(String linestringFieldName) { // this.linestringFieldName = linestringFieldName; // } // // @Override // public String description() { // return "retrieve raw linestring even for tokenized fields"; // } // // @Override // public boolean equals(Object o) { // return false; // } // // @SuppressWarnings("rawtypes") // @Override // public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { // return new LineStringFunctionValues(this.linestringFieldName, readerContext); // } // // @Override // public int hashCode() { // return ("linestring" + this.linestringFieldName).hashCode(); // } // // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/wkt/WktUtils.java // public class WktUtils { // // private static final Logger LOGGER = LoggerFactory.getLogger(WktUtils.class); // // private static final GeometryFactory geometryFactory = new GeometryFactory(); // // public static LineString parseLineString(String corridorLineString) { // String rawCoordinates = StringUtils.substringBetween(corridorLineString, "LINESTRING(", ")"); // if (rawCoordinates == null || rawCoordinates.trim().isEmpty()) { // LOGGER.warn("Linestring without coordinates found: '{}'", corridorLineString); // return geometryFactory.createLineString((Coordinate[]) null); // } // String[] coordinates = rawCoordinates.trim().split(","); // // Coordinate[] wktCoordinates = Arrays.stream(coordinates).map(WktUtils::createCoordinate).toArray(Coordinate[]::new); // return geometryFactory.createLineString(wktCoordinates); // } // // public static Point parsePoint(String pointString) { // String rawPoints = StringUtils.substringBetween(pointString, "POINT(", ")"); // if (rawPoints == null) { // throw new IllegalArgumentException("Parameter must be a valid WKT Point!"); // } // // Coordinate coordinate = createCoordinate(rawPoints); // return geometryFactory.createPoint(coordinate); // } // // private static Coordinate createCoordinate(String rawCoordinates) { // String[] points = rawCoordinates.trim().split(" "); // // Coordinate coordinate = new Coordinate(); // coordinate.x = Double.parseDouble(points[0]); // coordinate.y = Double.parseDouble(points[1]); // geometryFactory.getPrecisionModel().makePrecise(coordinate); // return coordinate; // } // }
import java.util.ArrayList; import java.util.List; import com.indoqa.solr.spatial.corridor.LineStringValueSource; import com.indoqa.solr.spatial.corridor.wkt.WktUtils; import org.apache.lucene.queries.function.ValueSource; import org.apache.solr.schema.StrFieldSource; import org.apache.solr.search.FunctionQParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.ValueSourceParser; import org.locationtech.jts.geom.Point;
/* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.query.points; public abstract class AbstractPointsQueryCorridorValueSourceParser extends ValueSourceParser { @Override public ValueSource parse(FunctionQParser fp) throws SyntaxError { List<Point> queryPoints = new ArrayList<>(); String[] queryPointParameters = fp.getParams().getParams("corridor.point"); for (String queryPointParameter : queryPointParameters) { queryPoints.add(WktUtils.parsePoint(queryPointParameter)); }
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringValueSource.java // public class LineStringValueSource extends ValueSource { // // private String linestringFieldName; // // public LineStringValueSource(String linestringFieldName) { // this.linestringFieldName = linestringFieldName; // } // // @Override // public String description() { // return "retrieve raw linestring even for tokenized fields"; // } // // @Override // public boolean equals(Object o) { // return false; // } // // @SuppressWarnings("rawtypes") // @Override // public FunctionValues getValues(Map context, LeafReaderContext readerContext) throws IOException { // return new LineStringFunctionValues(this.linestringFieldName, readerContext); // } // // @Override // public int hashCode() { // return ("linestring" + this.linestringFieldName).hashCode(); // } // // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/wkt/WktUtils.java // public class WktUtils { // // private static final Logger LOGGER = LoggerFactory.getLogger(WktUtils.class); // // private static final GeometryFactory geometryFactory = new GeometryFactory(); // // public static LineString parseLineString(String corridorLineString) { // String rawCoordinates = StringUtils.substringBetween(corridorLineString, "LINESTRING(", ")"); // if (rawCoordinates == null || rawCoordinates.trim().isEmpty()) { // LOGGER.warn("Linestring without coordinates found: '{}'", corridorLineString); // return geometryFactory.createLineString((Coordinate[]) null); // } // String[] coordinates = rawCoordinates.trim().split(","); // // Coordinate[] wktCoordinates = Arrays.stream(coordinates).map(WktUtils::createCoordinate).toArray(Coordinate[]::new); // return geometryFactory.createLineString(wktCoordinates); // } // // public static Point parsePoint(String pointString) { // String rawPoints = StringUtils.substringBetween(pointString, "POINT(", ")"); // if (rawPoints == null) { // throw new IllegalArgumentException("Parameter must be a valid WKT Point!"); // } // // Coordinate coordinate = createCoordinate(rawPoints); // return geometryFactory.createPoint(coordinate); // } // // private static Coordinate createCoordinate(String rawCoordinates) { // String[] points = rawCoordinates.trim().split(" "); // // Coordinate coordinate = new Coordinate(); // coordinate.x = Double.parseDouble(points[0]); // coordinate.y = Double.parseDouble(points[1]); // geometryFactory.getPrecisionModel().makePrecise(coordinate); // return coordinate; // } // } // Path: src/main/java/com/indoqa/solr/spatial/corridor/query/points/AbstractPointsQueryCorridorValueSourceParser.java import java.util.ArrayList; import java.util.List; import com.indoqa.solr.spatial.corridor.LineStringValueSource; import com.indoqa.solr.spatial.corridor.wkt.WktUtils; import org.apache.lucene.queries.function.ValueSource; import org.apache.solr.schema.StrFieldSource; import org.apache.solr.search.FunctionQParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.ValueSourceParser; import org.locationtech.jts.geom.Point; /* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.query.points; public abstract class AbstractPointsQueryCorridorValueSourceParser extends ValueSourceParser { @Override public ValueSource parse(FunctionQParser fp) throws SyntaxError { List<Point> queryPoints = new ArrayList<>(); String[] queryPointParameters = fp.getParams().getParams("corridor.point"); for (String queryPointParameter : queryPointParameters) { queryPoints.add(WktUtils.parsePoint(queryPointParameter)); }
return this.createValueSource(queryPoints, new LineStringValueSource(fp.parseArg()), fp.parseValueSource());
Indoqa/solr-spatial-corridor
src/main/java/com/indoqa/solr/spatial/corridor/direction/InDirectionPointsValueSource.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/direction/InDirectionUtils.java // public class InDirectionUtils { // // private InDirectionUtils() { // //hide utility class // } // // public static int percentageOfPointsWithinDistanceTo(LineString route, List<Point> points, double pointsMaxDistanceToRoute) { // LocationIndexedLine lineRef = new LocationIndexedLine(route); // // int result = 0; // // for (Point point : points) { // LinearLocation loc = lineRef.project(point.getCoordinate()); // Coordinate nearestPoint = lineRef.extractPoint(loc); // // double distance = nearestPoint.distance(point.getCoordinate()) * WGS84_TO_KILOMETERS_FACTOR; // // if (distance <= pointsMaxDistanceToRoute) { // result++; // } // } // // return Double.valueOf((double) result / points.size() * 100).intValue(); // } // // public static boolean checkAngleDifferenceInThirdOrFourthQuadrant(double actualDifference, double maxDifference) { // return actualDifference >= 180 - maxDifference && actualDifference <= 180 + maxDifference; // } // // public static boolean checkAngleDifferenceInFirstOrSecondQuadrant(double actualDifference, double maxDifference) { // if (actualDifference >= 360 - maxDifference && actualDifference <= 360) { // return true; // } // // if (actualDifference >= 0 && actualDifference <= maxDifference) { // return true; // } // // return false; // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/debug/DebugValues.java // public interface DebugValues { // // void add(String key, String value); // void add(String key, boolean value); // void add(String key, Number value); // // void addAngleDifference(String key, String value); // void addAngleDifference(String key, Number value); // void addAngleDifference(String key, Coordinate coordinate); // // void addSingleAngleDifference(String key, Number value); // // String toJson(); // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/debug/NoOpDebugValues.java // public class NoOpDebugValues implements DebugValues { // // public static NoOpDebugValues NOOP_DEBUG_VALUES = new NoOpDebugValues(); // // private NoOpDebugValues() { // super(); // } // // @Override // public void add(String key, String value) { // // } // // @Override // public void add(String key, boolean value) { // // } // // @Override // public void add(String key, Number value) { // // } // // @Override // public void addAngleDifference(String key, String value) { // // } // // @Override // public void addAngleDifference(String key, Number value) { // // } // // @Override // public void addAngleDifference(String key, Coordinate coordinate) { // // } // // @Override // public void addSingleAngleDifference(String distance, Number distance1) { // // } // // @Override // public String toJson() { // return null; // } // }
import org.apache.lucene.queries.function.docvalues.DoubleDocValues; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.indoqa.solr.spatial.corridor.direction.InDirectionUtils.*; import java.io.IOException; import java.util.*; import com.indoqa.solr.spatial.corridor.debug.DebugValues; import com.indoqa.solr.spatial.corridor.debug.NoOpDebugValues; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.LineString; import org.locationtech.jts.geom.Point; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.queries.function.FunctionValues; import org.apache.lucene.queries.function.ValueSource;
/* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.direction; public class InDirectionPointsValueSource extends ValueSource { private static final Logger LOGGER = LoggerFactory.getLogger(InDirectionPointsValueSource.class); private static final GeometryFactory geometryFactory = new GeometryFactory(); private LineString lineString; private ValueSource locationValueSource; private double maxDifference; private double maxDifferenceAdditionalPointsCheck; private double pointsMaxDistanceToRoute; private int percentageOfPointsWithinDistance; private boolean alwaysCheckPointDistancePercent;
// Path: src/main/java/com/indoqa/solr/spatial/corridor/direction/InDirectionUtils.java // public class InDirectionUtils { // // private InDirectionUtils() { // //hide utility class // } // // public static int percentageOfPointsWithinDistanceTo(LineString route, List<Point> points, double pointsMaxDistanceToRoute) { // LocationIndexedLine lineRef = new LocationIndexedLine(route); // // int result = 0; // // for (Point point : points) { // LinearLocation loc = lineRef.project(point.getCoordinate()); // Coordinate nearestPoint = lineRef.extractPoint(loc); // // double distance = nearestPoint.distance(point.getCoordinate()) * WGS84_TO_KILOMETERS_FACTOR; // // if (distance <= pointsMaxDistanceToRoute) { // result++; // } // } // // return Double.valueOf((double) result / points.size() * 100).intValue(); // } // // public static boolean checkAngleDifferenceInThirdOrFourthQuadrant(double actualDifference, double maxDifference) { // return actualDifference >= 180 - maxDifference && actualDifference <= 180 + maxDifference; // } // // public static boolean checkAngleDifferenceInFirstOrSecondQuadrant(double actualDifference, double maxDifference) { // if (actualDifference >= 360 - maxDifference && actualDifference <= 360) { // return true; // } // // if (actualDifference >= 0 && actualDifference <= maxDifference) { // return true; // } // // return false; // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/debug/DebugValues.java // public interface DebugValues { // // void add(String key, String value); // void add(String key, boolean value); // void add(String key, Number value); // // void addAngleDifference(String key, String value); // void addAngleDifference(String key, Number value); // void addAngleDifference(String key, Coordinate coordinate); // // void addSingleAngleDifference(String key, Number value); // // String toJson(); // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/debug/NoOpDebugValues.java // public class NoOpDebugValues implements DebugValues { // // public static NoOpDebugValues NOOP_DEBUG_VALUES = new NoOpDebugValues(); // // private NoOpDebugValues() { // super(); // } // // @Override // public void add(String key, String value) { // // } // // @Override // public void add(String key, boolean value) { // // } // // @Override // public void add(String key, Number value) { // // } // // @Override // public void addAngleDifference(String key, String value) { // // } // // @Override // public void addAngleDifference(String key, Number value) { // // } // // @Override // public void addAngleDifference(String key, Coordinate coordinate) { // // } // // @Override // public void addSingleAngleDifference(String distance, Number distance1) { // // } // // @Override // public String toJson() { // return null; // } // } // Path: src/main/java/com/indoqa/solr/spatial/corridor/direction/InDirectionPointsValueSource.java import org.apache.lucene.queries.function.docvalues.DoubleDocValues; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.indoqa.solr.spatial.corridor.direction.InDirectionUtils.*; import java.io.IOException; import java.util.*; import com.indoqa.solr.spatial.corridor.debug.DebugValues; import com.indoqa.solr.spatial.corridor.debug.NoOpDebugValues; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.LineString; import org.locationtech.jts.geom.Point; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.queries.function.FunctionValues; import org.apache.lucene.queries.function.ValueSource; /* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.direction; public class InDirectionPointsValueSource extends ValueSource { private static final Logger LOGGER = LoggerFactory.getLogger(InDirectionPointsValueSource.class); private static final GeometryFactory geometryFactory = new GeometryFactory(); private LineString lineString; private ValueSource locationValueSource; private double maxDifference; private double maxDifferenceAdditionalPointsCheck; private double pointsMaxDistanceToRoute; private int percentageOfPointsWithinDistance; private boolean alwaysCheckPointDistancePercent;
private DebugValues debugValues;
Indoqa/solr-spatial-corridor
src/main/java/com/indoqa/solr/spatial/corridor/direction/InDirectionPointsValueSource.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/direction/InDirectionUtils.java // public class InDirectionUtils { // // private InDirectionUtils() { // //hide utility class // } // // public static int percentageOfPointsWithinDistanceTo(LineString route, List<Point> points, double pointsMaxDistanceToRoute) { // LocationIndexedLine lineRef = new LocationIndexedLine(route); // // int result = 0; // // for (Point point : points) { // LinearLocation loc = lineRef.project(point.getCoordinate()); // Coordinate nearestPoint = lineRef.extractPoint(loc); // // double distance = nearestPoint.distance(point.getCoordinate()) * WGS84_TO_KILOMETERS_FACTOR; // // if (distance <= pointsMaxDistanceToRoute) { // result++; // } // } // // return Double.valueOf((double) result / points.size() * 100).intValue(); // } // // public static boolean checkAngleDifferenceInThirdOrFourthQuadrant(double actualDifference, double maxDifference) { // return actualDifference >= 180 - maxDifference && actualDifference <= 180 + maxDifference; // } // // public static boolean checkAngleDifferenceInFirstOrSecondQuadrant(double actualDifference, double maxDifference) { // if (actualDifference >= 360 - maxDifference && actualDifference <= 360) { // return true; // } // // if (actualDifference >= 0 && actualDifference <= maxDifference) { // return true; // } // // return false; // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/debug/DebugValues.java // public interface DebugValues { // // void add(String key, String value); // void add(String key, boolean value); // void add(String key, Number value); // // void addAngleDifference(String key, String value); // void addAngleDifference(String key, Number value); // void addAngleDifference(String key, Coordinate coordinate); // // void addSingleAngleDifference(String key, Number value); // // String toJson(); // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/debug/NoOpDebugValues.java // public class NoOpDebugValues implements DebugValues { // // public static NoOpDebugValues NOOP_DEBUG_VALUES = new NoOpDebugValues(); // // private NoOpDebugValues() { // super(); // } // // @Override // public void add(String key, String value) { // // } // // @Override // public void add(String key, boolean value) { // // } // // @Override // public void add(String key, Number value) { // // } // // @Override // public void addAngleDifference(String key, String value) { // // } // // @Override // public void addAngleDifference(String key, Number value) { // // } // // @Override // public void addAngleDifference(String key, Coordinate coordinate) { // // } // // @Override // public void addSingleAngleDifference(String distance, Number distance1) { // // } // // @Override // public String toJson() { // return null; // } // }
import org.apache.lucene.queries.function.docvalues.DoubleDocValues; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.indoqa.solr.spatial.corridor.direction.InDirectionUtils.*; import java.io.IOException; import java.util.*; import com.indoqa.solr.spatial.corridor.debug.DebugValues; import com.indoqa.solr.spatial.corridor.debug.NoOpDebugValues; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.LineString; import org.locationtech.jts.geom.Point; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.queries.function.FunctionValues; import org.apache.lucene.queries.function.ValueSource;
/* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.direction; public class InDirectionPointsValueSource extends ValueSource { private static final Logger LOGGER = LoggerFactory.getLogger(InDirectionPointsValueSource.class); private static final GeometryFactory geometryFactory = new GeometryFactory(); private LineString lineString; private ValueSource locationValueSource; private double maxDifference; private double maxDifferenceAdditionalPointsCheck; private double pointsMaxDistanceToRoute; private int percentageOfPointsWithinDistance; private boolean alwaysCheckPointDistancePercent; private DebugValues debugValues; public InDirectionPointsValueSource(LineString lineString, ValueSource locationValueSource, double maxDifference, double maxDifferenceAdditionalPointsCheck, double pointsMaxDistanceToRoute, int percentageOfPointsWithinDistance, boolean alwaysCheckPointDistancePercent) { this.lineString = lineString; this.locationValueSource = locationValueSource; this.maxDifference = maxDifference; this.maxDifferenceAdditionalPointsCheck = maxDifferenceAdditionalPointsCheck; this.pointsMaxDistanceToRoute = pointsMaxDistanceToRoute; this.percentageOfPointsWithinDistance = percentageOfPointsWithinDistance; this.alwaysCheckPointDistancePercent = alwaysCheckPointDistancePercent;
// Path: src/main/java/com/indoqa/solr/spatial/corridor/direction/InDirectionUtils.java // public class InDirectionUtils { // // private InDirectionUtils() { // //hide utility class // } // // public static int percentageOfPointsWithinDistanceTo(LineString route, List<Point> points, double pointsMaxDistanceToRoute) { // LocationIndexedLine lineRef = new LocationIndexedLine(route); // // int result = 0; // // for (Point point : points) { // LinearLocation loc = lineRef.project(point.getCoordinate()); // Coordinate nearestPoint = lineRef.extractPoint(loc); // // double distance = nearestPoint.distance(point.getCoordinate()) * WGS84_TO_KILOMETERS_FACTOR; // // if (distance <= pointsMaxDistanceToRoute) { // result++; // } // } // // return Double.valueOf((double) result / points.size() * 100).intValue(); // } // // public static boolean checkAngleDifferenceInThirdOrFourthQuadrant(double actualDifference, double maxDifference) { // return actualDifference >= 180 - maxDifference && actualDifference <= 180 + maxDifference; // } // // public static boolean checkAngleDifferenceInFirstOrSecondQuadrant(double actualDifference, double maxDifference) { // if (actualDifference >= 360 - maxDifference && actualDifference <= 360) { // return true; // } // // if (actualDifference >= 0 && actualDifference <= maxDifference) { // return true; // } // // return false; // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/debug/DebugValues.java // public interface DebugValues { // // void add(String key, String value); // void add(String key, boolean value); // void add(String key, Number value); // // void addAngleDifference(String key, String value); // void addAngleDifference(String key, Number value); // void addAngleDifference(String key, Coordinate coordinate); // // void addSingleAngleDifference(String key, Number value); // // String toJson(); // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/debug/NoOpDebugValues.java // public class NoOpDebugValues implements DebugValues { // // public static NoOpDebugValues NOOP_DEBUG_VALUES = new NoOpDebugValues(); // // private NoOpDebugValues() { // super(); // } // // @Override // public void add(String key, String value) { // // } // // @Override // public void add(String key, boolean value) { // // } // // @Override // public void add(String key, Number value) { // // } // // @Override // public void addAngleDifference(String key, String value) { // // } // // @Override // public void addAngleDifference(String key, Number value) { // // } // // @Override // public void addAngleDifference(String key, Coordinate coordinate) { // // } // // @Override // public void addSingleAngleDifference(String distance, Number distance1) { // // } // // @Override // public String toJson() { // return null; // } // } // Path: src/main/java/com/indoqa/solr/spatial/corridor/direction/InDirectionPointsValueSource.java import org.apache.lucene.queries.function.docvalues.DoubleDocValues; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.indoqa.solr.spatial.corridor.direction.InDirectionUtils.*; import java.io.IOException; import java.util.*; import com.indoqa.solr.spatial.corridor.debug.DebugValues; import com.indoqa.solr.spatial.corridor.debug.NoOpDebugValues; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.LineString; import org.locationtech.jts.geom.Point; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.queries.function.FunctionValues; import org.apache.lucene.queries.function.ValueSource; /* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.direction; public class InDirectionPointsValueSource extends ValueSource { private static final Logger LOGGER = LoggerFactory.getLogger(InDirectionPointsValueSource.class); private static final GeometryFactory geometryFactory = new GeometryFactory(); private LineString lineString; private ValueSource locationValueSource; private double maxDifference; private double maxDifferenceAdditionalPointsCheck; private double pointsMaxDistanceToRoute; private int percentageOfPointsWithinDistance; private boolean alwaysCheckPointDistancePercent; private DebugValues debugValues; public InDirectionPointsValueSource(LineString lineString, ValueSource locationValueSource, double maxDifference, double maxDifferenceAdditionalPointsCheck, double pointsMaxDistanceToRoute, int percentageOfPointsWithinDistance, boolean alwaysCheckPointDistancePercent) { this.lineString = lineString; this.locationValueSource = locationValueSource; this.maxDifference = maxDifference; this.maxDifferenceAdditionalPointsCheck = maxDifferenceAdditionalPointsCheck; this.pointsMaxDistanceToRoute = pointsMaxDistanceToRoute; this.percentageOfPointsWithinDistance = percentageOfPointsWithinDistance; this.alwaysCheckPointDistancePercent = alwaysCheckPointDistancePercent;
this.debugValues = NoOpDebugValues.NOOP_DEBUG_VALUES;
Indoqa/solr-spatial-corridor
src/test/java/com/indoqa/solr/spatial/corridor/query/circle/TestCircleDistance.java
// Path: src/test/java/com/indoqa/solr/spatial/corridor/EmbeddedSolrInfrastructureRule.java // public class EmbeddedSolrInfrastructureRule extends ExternalResource { // // private SolrClient solrClient; // private boolean initialized; // // public SolrClient getSolrClient() { // return this.solrClient; // } // // @Override // protected void after() { // try { // this.solrClient.close(); // } catch (Exception e) { // // ignore // } // // if (this.solrClient instanceof EmbeddedSolrServer) { // EmbeddedSolrServer embeddedSolrServer = (EmbeddedSolrServer) this.solrClient; // embeddedSolrServer.getCoreContainer().shutdown(); // } // } // // @Override // protected void before() throws Throwable { // if (this.initialized) { // return; // } // // this.solrClient = EmbeddedSolrServerBuilder.build("file://./target/test-core", "solr/test"); // // this.initialized = true; // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // }
import static org.junit.Assert.assertEquals; import java.io.IOException; import com.indoqa.solr.spatial.corridor.EmbeddedSolrInfrastructureRule; import com.indoqa.solr.spatial.corridor.LineStringUtils; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrInputDocument; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test;
/* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.query.circle; public class TestCircleDistance { private static final String SOLR_FIELD_ID = "id"; private static final String SOLR_FIELD_CIRCLE_DISTANCE = "circleDistance"; private static final String DOCUMENT_ID_1 = "id-1"; private static final String DOCUMENT_ID_2 = "id-2"; @ClassRule
// Path: src/test/java/com/indoqa/solr/spatial/corridor/EmbeddedSolrInfrastructureRule.java // public class EmbeddedSolrInfrastructureRule extends ExternalResource { // // private SolrClient solrClient; // private boolean initialized; // // public SolrClient getSolrClient() { // return this.solrClient; // } // // @Override // protected void after() { // try { // this.solrClient.close(); // } catch (Exception e) { // // ignore // } // // if (this.solrClient instanceof EmbeddedSolrServer) { // EmbeddedSolrServer embeddedSolrServer = (EmbeddedSolrServer) this.solrClient; // embeddedSolrServer.getCoreContainer().shutdown(); // } // } // // @Override // protected void before() throws Throwable { // if (this.initialized) { // return; // } // // this.solrClient = EmbeddedSolrServerBuilder.build("file://./target/test-core", "solr/test"); // // this.initialized = true; // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // } // Path: src/test/java/com/indoqa/solr/spatial/corridor/query/circle/TestCircleDistance.java import static org.junit.Assert.assertEquals; import java.io.IOException; import com.indoqa.solr.spatial.corridor.EmbeddedSolrInfrastructureRule; import com.indoqa.solr.spatial.corridor.LineStringUtils; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrInputDocument; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; /* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.query.circle; public class TestCircleDistance { private static final String SOLR_FIELD_ID = "id"; private static final String SOLR_FIELD_CIRCLE_DISTANCE = "circleDistance"; private static final String DOCUMENT_ID_1 = "id-1"; private static final String DOCUMENT_ID_2 = "id-2"; @ClassRule
public static EmbeddedSolrInfrastructureRule infrastructureRule = new EmbeddedSolrInfrastructureRule();
Indoqa/solr-spatial-corridor
src/test/java/com/indoqa/solr/spatial/corridor/query/circle/TestCircleDistance.java
// Path: src/test/java/com/indoqa/solr/spatial/corridor/EmbeddedSolrInfrastructureRule.java // public class EmbeddedSolrInfrastructureRule extends ExternalResource { // // private SolrClient solrClient; // private boolean initialized; // // public SolrClient getSolrClient() { // return this.solrClient; // } // // @Override // protected void after() { // try { // this.solrClient.close(); // } catch (Exception e) { // // ignore // } // // if (this.solrClient instanceof EmbeddedSolrServer) { // EmbeddedSolrServer embeddedSolrServer = (EmbeddedSolrServer) this.solrClient; // embeddedSolrServer.getCoreContainer().shutdown(); // } // } // // @Override // protected void before() throws Throwable { // if (this.initialized) { // return; // } // // this.solrClient = EmbeddedSolrServerBuilder.build("file://./target/test-core", "solr/test"); // // this.initialized = true; // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // }
import static org.junit.Assert.assertEquals; import java.io.IOException; import com.indoqa.solr.spatial.corridor.EmbeddedSolrInfrastructureRule; import com.indoqa.solr.spatial.corridor.LineStringUtils; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrInputDocument; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test;
query.setRows(Integer.MAX_VALUE); query.add("corridor.circle.point", "POINT(16.41618 48.19288)"); query.add("corridor.circle.radius", "0.000005"); query.addField(SOLR_FIELD_ID); query.addField(SOLR_FIELD_CIRCLE_DISTANCE + ":circleDistance(geo, geoHash)"); response = infrastructureRule.getSolrClient().query(query); assertEquals(1, response.getResults().getNumFound()); assertEquals(DOCUMENT_ID_1, response.getResults().get(0).getFieldValue(SOLR_FIELD_ID)); assertEquals(0.0006, (double) response.getResults().get(0).getFieldValue(SOLR_FIELD_CIRCLE_DISTANCE), 0.00009); query = new SolrQuery("{!frange l=0 u=0.01}circleDistance(geo, geoHash)"); query.setRows(Integer.MAX_VALUE); query.add("corridor.circle.point", "POINT(16.41618 48.19288)"); query.add("corridor.circle.radius", "0.00005"); query.addField(SOLR_FIELD_ID); query.addField(SOLR_FIELD_CIRCLE_DISTANCE + ":circleDistance(geo, geoHash)"); response = infrastructureRule.getSolrClient().query(query); assertEquals(1, response.getResults().getNumFound()); assertEquals(DOCUMENT_ID_1, response.getResults().get(0).getFieldValue(SOLR_FIELD_ID)); assertEquals(0.0, (double) response.getResults().get(0).getFieldValue(SOLR_FIELD_CIRCLE_DISTANCE), 0.00009); } @Test public void circleCacheCleanup() throws SolrServerException, IOException { circleExactMatch();
// Path: src/test/java/com/indoqa/solr/spatial/corridor/EmbeddedSolrInfrastructureRule.java // public class EmbeddedSolrInfrastructureRule extends ExternalResource { // // private SolrClient solrClient; // private boolean initialized; // // public SolrClient getSolrClient() { // return this.solrClient; // } // // @Override // protected void after() { // try { // this.solrClient.close(); // } catch (Exception e) { // // ignore // } // // if (this.solrClient instanceof EmbeddedSolrServer) { // EmbeddedSolrServer embeddedSolrServer = (EmbeddedSolrServer) this.solrClient; // embeddedSolrServer.getCoreContainer().shutdown(); // } // } // // @Override // protected void before() throws Throwable { // if (this.initialized) { // return; // } // // this.solrClient = EmbeddedSolrServerBuilder.build("file://./target/test-core", "solr/test"); // // this.initialized = true; // } // } // // Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // } // Path: src/test/java/com/indoqa/solr/spatial/corridor/query/circle/TestCircleDistance.java import static org.junit.Assert.assertEquals; import java.io.IOException; import com.indoqa.solr.spatial.corridor.EmbeddedSolrInfrastructureRule; import com.indoqa.solr.spatial.corridor.LineStringUtils; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrInputDocument; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; query.setRows(Integer.MAX_VALUE); query.add("corridor.circle.point", "POINT(16.41618 48.19288)"); query.add("corridor.circle.radius", "0.000005"); query.addField(SOLR_FIELD_ID); query.addField(SOLR_FIELD_CIRCLE_DISTANCE + ":circleDistance(geo, geoHash)"); response = infrastructureRule.getSolrClient().query(query); assertEquals(1, response.getResults().getNumFound()); assertEquals(DOCUMENT_ID_1, response.getResults().get(0).getFieldValue(SOLR_FIELD_ID)); assertEquals(0.0006, (double) response.getResults().get(0).getFieldValue(SOLR_FIELD_CIRCLE_DISTANCE), 0.00009); query = new SolrQuery("{!frange l=0 u=0.01}circleDistance(geo, geoHash)"); query.setRows(Integer.MAX_VALUE); query.add("corridor.circle.point", "POINT(16.41618 48.19288)"); query.add("corridor.circle.radius", "0.00005"); query.addField(SOLR_FIELD_ID); query.addField(SOLR_FIELD_CIRCLE_DISTANCE + ":circleDistance(geo, geoHash)"); response = infrastructureRule.getSolrClient().query(query); assertEquals(1, response.getResults().getNumFound()); assertEquals(DOCUMENT_ID_1, response.getResults().get(0).getFieldValue(SOLR_FIELD_ID)); assertEquals(0.0, (double) response.getResults().get(0).getFieldValue(SOLR_FIELD_CIRCLE_DISTANCE), 0.00009); } @Test public void circleCacheCleanup() throws SolrServerException, IOException { circleExactMatch();
LineStringUtils.purgeCache();
Indoqa/solr-spatial-corridor
src/main/java/com/indoqa/solr/spatial/corridor/query/route/AbstractRouteQueryValueSourceParser.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // }
import com.indoqa.solr.spatial.corridor.LineStringUtils; import org.apache.lucene.queries.function.ValueSource; import org.apache.solr.search.FunctionQParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.ValueSourceParser; import org.locationtech.jts.geom.LineString;
/* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.query.route; public abstract class AbstractRouteQueryValueSourceParser extends ValueSourceParser { @Override public ValueSource parse(FunctionQParser fp) throws SyntaxError {
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // } // Path: src/main/java/com/indoqa/solr/spatial/corridor/query/route/AbstractRouteQueryValueSourceParser.java import com.indoqa.solr.spatial.corridor.LineStringUtils; import org.apache.lucene.queries.function.ValueSource; import org.apache.solr.search.FunctionQParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.ValueSourceParser; import org.locationtech.jts.geom.LineString; /* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.query.route; public abstract class AbstractRouteQueryValueSourceParser extends ValueSourceParser { @Override public ValueSource parse(FunctionQParser fp) throws SyntaxError {
LineString lineString = LineStringUtils.parseOrGet(fp.getParam("corridor.route"), null);
Indoqa/solr-spatial-corridor
src/test/java/com/indoqa/solr/spatial/corridor/TestWktUtils.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/wkt/WktUtils.java // public class WktUtils { // // private static final Logger LOGGER = LoggerFactory.getLogger(WktUtils.class); // // private static final GeometryFactory geometryFactory = new GeometryFactory(); // // public static LineString parseLineString(String corridorLineString) { // String rawCoordinates = StringUtils.substringBetween(corridorLineString, "LINESTRING(", ")"); // if (rawCoordinates == null || rawCoordinates.trim().isEmpty()) { // LOGGER.warn("Linestring without coordinates found: '{}'", corridorLineString); // return geometryFactory.createLineString((Coordinate[]) null); // } // String[] coordinates = rawCoordinates.trim().split(","); // // Coordinate[] wktCoordinates = Arrays.stream(coordinates).map(WktUtils::createCoordinate).toArray(Coordinate[]::new); // return geometryFactory.createLineString(wktCoordinates); // } // // public static Point parsePoint(String pointString) { // String rawPoints = StringUtils.substringBetween(pointString, "POINT(", ")"); // if (rawPoints == null) { // throw new IllegalArgumentException("Parameter must be a valid WKT Point!"); // } // // Coordinate coordinate = createCoordinate(rawPoints); // return geometryFactory.createPoint(coordinate); // } // // private static Coordinate createCoordinate(String rawCoordinates) { // String[] points = rawCoordinates.trim().split(" "); // // Coordinate coordinate = new Coordinate(); // coordinate.x = Double.parseDouble(points[0]); // coordinate.y = Double.parseDouble(points[1]); // geometryFactory.getPrecisionModel().makePrecise(coordinate); // return coordinate; // } // }
import com.indoqa.solr.spatial.corridor.wkt.WktUtils; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrInputDocument; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertEquals;
/* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor; public class TestWktUtils { @Test public void testEmptyLinestring() throws SolrServerException, IOException {
// Path: src/main/java/com/indoqa/solr/spatial/corridor/wkt/WktUtils.java // public class WktUtils { // // private static final Logger LOGGER = LoggerFactory.getLogger(WktUtils.class); // // private static final GeometryFactory geometryFactory = new GeometryFactory(); // // public static LineString parseLineString(String corridorLineString) { // String rawCoordinates = StringUtils.substringBetween(corridorLineString, "LINESTRING(", ")"); // if (rawCoordinates == null || rawCoordinates.trim().isEmpty()) { // LOGGER.warn("Linestring without coordinates found: '{}'", corridorLineString); // return geometryFactory.createLineString((Coordinate[]) null); // } // String[] coordinates = rawCoordinates.trim().split(","); // // Coordinate[] wktCoordinates = Arrays.stream(coordinates).map(WktUtils::createCoordinate).toArray(Coordinate[]::new); // return geometryFactory.createLineString(wktCoordinates); // } // // public static Point parsePoint(String pointString) { // String rawPoints = StringUtils.substringBetween(pointString, "POINT(", ")"); // if (rawPoints == null) { // throw new IllegalArgumentException("Parameter must be a valid WKT Point!"); // } // // Coordinate coordinate = createCoordinate(rawPoints); // return geometryFactory.createPoint(coordinate); // } // // private static Coordinate createCoordinate(String rawCoordinates) { // String[] points = rawCoordinates.trim().split(" "); // // Coordinate coordinate = new Coordinate(); // coordinate.x = Double.parseDouble(points[0]); // coordinate.y = Double.parseDouble(points[1]); // geometryFactory.getPrecisionModel().makePrecise(coordinate); // return coordinate; // } // } // Path: src/test/java/com/indoqa/solr/spatial/corridor/TestWktUtils.java import com.indoqa.solr.spatial.corridor.wkt.WktUtils; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrInputDocument; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertEquals; /* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor; public class TestWktUtils { @Test public void testEmptyLinestring() throws SolrServerException, IOException {
WktUtils.parseLineString("LINESTRING()");
Indoqa/solr-spatial-corridor
src/main/java/com/indoqa/solr/spatial/corridor/query/route/RouteQueryParser.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // }
import com.indoqa.solr.spatial.corridor.LineStringUtils; import org.apache.lucene.queries.function.ValueSource; import org.apache.lucene.search.Query; import org.apache.solr.common.params.SolrParams; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.schema.SchemaField; import org.apache.solr.search.FunctionRangeQuery; import org.apache.solr.search.QParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.function.ValueSourceRangeFilter; import org.locationtech.jts.geom.LineString;
/* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.query.route; public class RouteQueryParser extends QParser { public RouteQueryParser(String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req) { super(qstr, localParams, params, req); } @Override public Query parse() throws SyntaxError { ValueSource locationValueSource = this.parseLocationValueSource(); LineString lineString = this.parseLineString(); String buffer = this.parseBuffer(); RouteDistanceValueSource corridorDistanceValueSource = new RouteDistanceValueSource(lineString, locationValueSource); ValueSourceRangeFilter filter = new ValueSourceRangeFilter(corridorDistanceValueSource, "0", buffer, true, true); return new FunctionRangeQuery(filter); } private String parseBuffer() { String buffer = this.getParam("buffer"); if (buffer == null) { return "5"; } return buffer; } private LineString parseLineString() throws SyntaxError {
// Path: src/main/java/com/indoqa/solr/spatial/corridor/LineStringUtils.java // public final class LineStringUtils { // // static { // cache = Caffeine.newBuilder() // .maximumSize(100000) // .expireAfterAccess(24, TimeUnit.HOURS) // .build(); // } // // private static Cache<String, LineString> cache; // // public static LineString parseOrGet(String value, String hash) { // if (value == null) { // return null; // } // // if (hash != null) { // LineString cached = cache.getIfPresent(hash); // // if (cached != null) { // return cached; // } // } // // String key = calculateHash(value); // return cache.get(key, s -> parseWktLinestring(value)); // } // // public static HashGeometry cacheLineStringGetHashGeometry(String linestring, int radiusInMeters){ // if(linestring == null){ // return null; // } // String key = calculateHash(linestring); // LineString parsedLineString = parseWktLinestring(linestring); // // cache.put(key, parsedLineString); // HashGeometry result = new HashGeometry(); // // meters /((PI/180)x6378137) // result.setGeometry(parsedLineString.buffer(radiusInMeters / (Math.PI / 180 * 6378137)).toText()); // result.setHash(key); // return result; // } // // public static void purgeCache() { // cache.invalidateAll(); // cache.cleanUp(); // } // // private static LineString parseWktLinestring(String corridorLineString) { // return WktUtils.parseLineString(corridorLineString); // } // // private static String calculateHash(String linestring) { // if (linestring == null) { // return null; // } // // StringBuilder result = new StringBuilder("hash-"); // result.append(Hex.encodeHex(DigestUtils.md5(linestring))); // return result.toString(); // } // } // Path: src/main/java/com/indoqa/solr/spatial/corridor/query/route/RouteQueryParser.java import com.indoqa.solr.spatial.corridor.LineStringUtils; import org.apache.lucene.queries.function.ValueSource; import org.apache.lucene.search.Query; import org.apache.solr.common.params.SolrParams; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.schema.SchemaField; import org.apache.solr.search.FunctionRangeQuery; import org.apache.solr.search.QParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.function.ValueSourceRangeFilter; import org.locationtech.jts.geom.LineString; /* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.query.route; public class RouteQueryParser extends QParser { public RouteQueryParser(String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req) { super(qstr, localParams, params, req); } @Override public Query parse() throws SyntaxError { ValueSource locationValueSource = this.parseLocationValueSource(); LineString lineString = this.parseLineString(); String buffer = this.parseBuffer(); RouteDistanceValueSource corridorDistanceValueSource = new RouteDistanceValueSource(lineString, locationValueSource); ValueSourceRangeFilter filter = new ValueSourceRangeFilter(corridorDistanceValueSource, "0", buffer, true, true); return new FunctionRangeQuery(filter); } private String parseBuffer() { String buffer = this.getParam("buffer"); if (buffer == null) { return "5"; } return buffer; } private LineString parseLineString() throws SyntaxError {
return LineStringUtils.parseOrGet(this.getParam("corridor.route"), null);
Indoqa/solr-spatial-corridor
src/main/java/com/indoqa/solr/spatial/corridor/direction/AngleUtils.java
// Path: src/main/java/com/indoqa/solr/spatial/corridor/debug/DebugValues.java // public interface DebugValues { // // void add(String key, String value); // void add(String key, boolean value); // void add(String key, Number value); // // void addAngleDifference(String key, String value); // void addAngleDifference(String key, Number value); // void addAngleDifference(String key, Coordinate coordinate); // // void addSingleAngleDifference(String key, Number value); // // String toJson(); // }
import static com.indoqa.solr.spatial.corridor.CorridorConstants.WGS84_TO_KILOMETERS_FACTOR; import static java.lang.Math.PI; import com.indoqa.solr.spatial.corridor.debug.DebugValues; import org.locationtech.jts.algorithm.Angle; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.LineString; import org.locationtech.jts.geom.Point; import org.locationtech.jts.linearref.LinearLocation; import org.locationtech.jts.linearref.LocationIndexedLine; import java.util.Arrays; import java.util.List; import java.util.stream.Stream;
/* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.direction; public class AngleUtils { public static double angle(Coordinate c1, Coordinate c2) { double angleInRadians = Angle.angle(c1, c2); return angleInRadians * (180 / PI); }
// Path: src/main/java/com/indoqa/solr/spatial/corridor/debug/DebugValues.java // public interface DebugValues { // // void add(String key, String value); // void add(String key, boolean value); // void add(String key, Number value); // // void addAngleDifference(String key, String value); // void addAngleDifference(String key, Number value); // void addAngleDifference(String key, Coordinate coordinate); // // void addSingleAngleDifference(String key, Number value); // // String toJson(); // } // Path: src/main/java/com/indoqa/solr/spatial/corridor/direction/AngleUtils.java import static com.indoqa.solr.spatial.corridor.CorridorConstants.WGS84_TO_KILOMETERS_FACTOR; import static java.lang.Math.PI; import com.indoqa.solr.spatial.corridor.debug.DebugValues; import org.locationtech.jts.algorithm.Angle; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.LineString; import org.locationtech.jts.geom.Point; import org.locationtech.jts.linearref.LinearLocation; import org.locationtech.jts.linearref.LocationIndexedLine; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; /* * Licensed to the Indoqa Software Design und Beratung GmbH (Indoqa) under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Indoqa licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.indoqa.solr.spatial.corridor.direction; public class AngleUtils { public static double angle(Coordinate c1, Coordinate c2) { double angleInRadians = Angle.angle(c1, c2); return angleInRadians * (180 / PI); }
protected static double getAngleDifference(DebugValues debugValues, LineString lineString, List<Point> queryPoints, double maxDistance) {
dubboclub/reloud
reloud-admin/src/main/java/net/dubboclub/reloud/manager/ClusterManager.java
// Path: reloud-admin/src/main/java/net/dubboclub/reloud/manager/entity/RedisNodeCluster.java // public class RedisNodeCluster { // // // //集群节点名称 // private String clusterName; // // //集群包含的分片 // private List<RedisNodeShared> sharedList; // // //集群的状态 // private ClusterStatus clusterStatus; // // public ClusterStatus getClusterStatus() { // return clusterStatus; // } // // public void setClusterStatus(ClusterStatus clusterStatus) { // this.clusterStatus = clusterStatus; // } // // public String getClusterName() { // return clusterName; // } // // public void setClusterName(String clusterName) { // this.clusterName = clusterName; // } // // public List<RedisNodeShared> getSharedList() { // return sharedList; // } // // public void setSharedList(List<RedisNodeShared> sharedList) { // this.sharedList = sharedList; // } // // static enum ClusterStatus{ // ENABLE,DISABLE; // } // }
import net.dubboclub.reloud.manager.entity.RedisNodeCluster; import java.util.List;
package net.dubboclub.reloud.manager; /** * Created by bieber on 16/3/31. * 整个集群管理 */ public interface ClusterManager { /** * 创建一个集群节点信息 * @param clusterName * @return */ public boolean createCluster(String clusterName); /** * 激活这个集群 * @param clusterId * @return */ public boolean enableCluster(Long clusterId); /** * 下线这个集群 * @param clusterId * @return */ public boolean disableCluster(Long clusterId); /** * 删除这个集群 * @param clusterId * @return */ public boolean removeCluster(Long clusterId); /** * 查询集群列表 * @param offset * @return */
// Path: reloud-admin/src/main/java/net/dubboclub/reloud/manager/entity/RedisNodeCluster.java // public class RedisNodeCluster { // // // //集群节点名称 // private String clusterName; // // //集群包含的分片 // private List<RedisNodeShared> sharedList; // // //集群的状态 // private ClusterStatus clusterStatus; // // public ClusterStatus getClusterStatus() { // return clusterStatus; // } // // public void setClusterStatus(ClusterStatus clusterStatus) { // this.clusterStatus = clusterStatus; // } // // public String getClusterName() { // return clusterName; // } // // public void setClusterName(String clusterName) { // this.clusterName = clusterName; // } // // public List<RedisNodeShared> getSharedList() { // return sharedList; // } // // public void setSharedList(List<RedisNodeShared> sharedList) { // this.sharedList = sharedList; // } // // static enum ClusterStatus{ // ENABLE,DISABLE; // } // } // Path: reloud-admin/src/main/java/net/dubboclub/reloud/manager/ClusterManager.java import net.dubboclub.reloud.manager.entity.RedisNodeCluster; import java.util.List; package net.dubboclub.reloud.manager; /** * Created by bieber on 16/3/31. * 整个集群管理 */ public interface ClusterManager { /** * 创建一个集群节点信息 * @param clusterName * @return */ public boolean createCluster(String clusterName); /** * 激活这个集群 * @param clusterId * @return */ public boolean enableCluster(Long clusterId); /** * 下线这个集群 * @param clusterId * @return */ public boolean disableCluster(Long clusterId); /** * 删除这个集群 * @param clusterId * @return */ public boolean removeCluster(Long clusterId); /** * 查询集群列表 * @param offset * @return */
public List<RedisNodeCluster> clusterList(int offset);
Zerokyuuni/Ex-Aliquo
exaliquo/bridges/Mariculture/CrucibleSmelt.java
// Path: exaliquo/data/OreDict.java // public class OreDict // { // public static boolean isOreDict(ItemStack itemstack, String name) // { // if (OreDictionary.getOreName(OreDictionary.getOreID(itemstack)).equals(name)) // { // return true; // } // else // { // return ((OreDictionary.getOres(name).isEmpty()) && (itemstack.itemID == Item.ingotIron.itemID)) ? true : false; // } // } // // public static EnumToolMaterial getMaterial(String string) // { // try // { // return EnumToolMaterial.valueOf(string); // } // catch (IllegalArgumentException e) // { // return EnumToolMaterial.IRON; // } // } // // public static ItemStack getFirstOre(String string) // { // return getFirstOre(string, true); // } // // public static ItemStack getFirstOre(String string, boolean warning) // { // ArrayList<ItemStack> ores = OreDictionary.getOres(string); // if (!ores.isEmpty()) // { // return ores.get(0); // } // if (warning) exaliquo.logger.warning("ExAliquo could not find the oreDict item called by " + string); // return new ItemStack(Block.redstoneWire, 1, 0); // } // // public static Block getBlock(ItemStack itemStack) // { // return Block.blocksList[itemStack.itemID]; // } // }
import static net.minecraftforge.fluids.FluidRegistry.getFluid; import net.minecraft.item.ItemStack; import exaliquo.data.OreDict; import exnihilo.registries.CrucibleRegistry;
package exaliquo.bridges.Mariculture; public class CrucibleSmelt { protected static void SmeltMariculture() {
// Path: exaliquo/data/OreDict.java // public class OreDict // { // public static boolean isOreDict(ItemStack itemstack, String name) // { // if (OreDictionary.getOreName(OreDictionary.getOreID(itemstack)).equals(name)) // { // return true; // } // else // { // return ((OreDictionary.getOres(name).isEmpty()) && (itemstack.itemID == Item.ingotIron.itemID)) ? true : false; // } // } // // public static EnumToolMaterial getMaterial(String string) // { // try // { // return EnumToolMaterial.valueOf(string); // } // catch (IllegalArgumentException e) // { // return EnumToolMaterial.IRON; // } // } // // public static ItemStack getFirstOre(String string) // { // return getFirstOre(string, true); // } // // public static ItemStack getFirstOre(String string, boolean warning) // { // ArrayList<ItemStack> ores = OreDictionary.getOres(string); // if (!ores.isEmpty()) // { // return ores.get(0); // } // if (warning) exaliquo.logger.warning("ExAliquo could not find the oreDict item called by " + string); // return new ItemStack(Block.redstoneWire, 1, 0); // } // // public static Block getBlock(ItemStack itemStack) // { // return Block.blocksList[itemStack.itemID]; // } // } // Path: exaliquo/bridges/Mariculture/CrucibleSmelt.java import static net.minecraftforge.fluids.FluidRegistry.getFluid; import net.minecraft.item.ItemStack; import exaliquo.data.OreDict; import exnihilo.registries.CrucibleRegistry; package exaliquo.bridges.Mariculture; public class CrucibleSmelt { protected static void SmeltMariculture() {
ItemStack limestone = OreDict.getFirstOre("blockLimestone");
shoutrain/gMaxLinked
clients/java/src/com/example/network/Connection.java
// Path: clients/java/src/com/example/tool/Log.java // public class Log { // // public static void d(String tag, String info) { // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // System.out.println("[" + df.format(new Date()) + "]" + tag + " : " + info); // } // // public static void e(String tag, String info) { // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // System.out.println("[" + df.format(new Date()) + "]" + "* ERROR * : " + info); // } // }
import java.io.InterruptedIOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.nio.ByteBuffer; import com.avcon.conf.Config; import com.avcon.msg.MsgDefine; import com.avcon.tool.Log; import com.avcon.tool.NetworkDataHelper;
} public void run() { isRunning = true; while (isRun) { if (false == running()) { int i = WAIT_TIMES; while (0 < i-- && isRun) { try { Thread.sleep(CONNECTION_TIME_OUT); } catch (InterruptedException e) { e.printStackTrace(); } } } } isRunning = false; } private final int sizeSize = 2; // the size of size field in header private ByteBuffer bufferSize = ByteBuffer.allocate(sizeSize); private ByteBuffer bufferMsg = null; private int offset = 0; private int pendingSize = 0; private void close() {
// Path: clients/java/src/com/example/tool/Log.java // public class Log { // // public static void d(String tag, String info) { // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // System.out.println("[" + df.format(new Date()) + "]" + tag + " : " + info); // } // // public static void e(String tag, String info) { // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // System.out.println("[" + df.format(new Date()) + "]" + "* ERROR * : " + info); // } // } // Path: clients/java/src/com/example/network/Connection.java import java.io.InterruptedIOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.nio.ByteBuffer; import com.avcon.conf.Config; import com.avcon.msg.MsgDefine; import com.avcon.tool.Log; import com.avcon.tool.NetworkDataHelper; } public void run() { isRunning = true; while (isRun) { if (false == running()) { int i = WAIT_TIMES; while (0 < i-- && isRun) { try { Thread.sleep(CONNECTION_TIME_OUT); } catch (InterruptedException e) { e.printStackTrace(); } } } } isRunning = false; } private final int sizeSize = 2; // the size of size field in header private ByteBuffer bufferSize = ByteBuffer.allocate(sizeSize); private ByteBuffer bufferMsg = null; private int offset = 0; private int pendingSize = 0; private void close() {
Log.d(Config.LOG_TAG, "Close socket");
shoutrain/gMaxLinked
clients/java/src/com/example/network/Tester.java
// Path: clients/java/src/com/example/tool/Log.java // public class Log { // // public static void d(String tag, String info) { // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // System.out.println("[" + df.format(new Date()) + "]" + tag + " : " + info); // } // // public static void e(String tag, String info) { // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // System.out.println("[" + df.format(new Date()) + "]" + "* ERROR * : " + info); // } // }
import java.nio.ByteBuffer; import com.avcon.msg.Ack; import com.avcon.msg.Header; import com.avcon.msg.MsgDefine; import com.avcon.msg.MsgHandshake; import com.avcon.msg.MsgHelper; import com.avcon.tool.Log;
package com.exmaple.network; public class Tester implements ConnectionDelegate { private Connection cnn = null; @Override public void onConnected(Connection cnn) {
// Path: clients/java/src/com/example/tool/Log.java // public class Log { // // public static void d(String tag, String info) { // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // System.out.println("[" + df.format(new Date()) + "]" + tag + " : " + info); // } // // public static void e(String tag, String info) { // SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // System.out.println("[" + df.format(new Date()) + "]" + "* ERROR * : " + info); // } // } // Path: clients/java/src/com/example/network/Tester.java import java.nio.ByteBuffer; import com.avcon.msg.Ack; import com.avcon.msg.Header; import com.avcon.msg.MsgDefine; import com.avcon.msg.MsgHandshake; import com.avcon.msg.MsgHelper; import com.avcon.tool.Log; package com.exmaple.network; public class Tester implements ConnectionDelegate { private Connection cnn = null; @Override public void onConnected(Connection cnn) {
Log.d("Tester", "onConnected");
nyholku/purejavacomm
src/purejavacomm/testsuite/Test1.java
// Path: src/purejavacomm/SerialPortEvent.java // public class SerialPortEvent extends EventObject { // /** // * Data available at the serial port. // */ // public static final int DATA_AVAILABLE = 1; // /** // * Output buffer is empty. // */ // public static final int OUTPUT_BUFFER_EMPTY = 2; // /** // * Clear to send. // */ // public static final int CTS = 3; // /** // * Data set ready. // */ // public static final int DSR = 4; // /** // * Ring indicator. // */ // public static final int RI = 5; // /** // * Carrier detect. // */ // public static final int CD = 6; // /** // * Overrun error. // */ // public static final int OE = 7; // /** // * Parity error. // */ // public static final int PE = 8; // /** // * Framing error. // */ // public static final int FE = 9; // /** // * Break interrupt. // */ // public static final int BI = 10; // // private final int eventType; // private final boolean newValue; // private final boolean oldValue; // // /** // * Constructs a <CODE>SerialPortEvent</CODE> with the specified serial port, // * event type, old and new values. Application programs should not directly // * create <CODE>SerialPortEvent</CODE> objects. // * // * @param source // * @param eventType // * @param oldValue // * @param newValue // */ // public SerialPortEvent(SerialPort source, int eventType, boolean oldValue, boolean newValue) { // super(source); // this.eventType = eventType; // this.newValue = newValue; // this.oldValue = oldValue; // } // // /** // * Returns the type of this event. // * // * @return The type of this event. // */ // public int getEventType() { // return this.eventType; // } // // /** // * Returns the new value of the state change that caused the // * <CODE>SerialPortEvent</CODE> to be propagated. // * // * @return The new value of the state change. // */ // public boolean getNewValue() { // return this.newValue; // } // // /** // * Returns the old value of the state change that caused the // * <CODE>SerialPortEvent</CODE> to be propagated. // * // * @return The old value of the state change. // */ // public boolean getOldValue() { // return this.oldValue; // } // } // // Path: src/purejavacomm/SerialPortEventListener.java // public interface SerialPortEventListener extends EventListener { // public void serialEvent(SerialPortEvent event); // }
import purejavacomm.SerialPortEventListener; import purejavacomm.SerialPortEvent;
/* * Copyright (c) 2011, Kustaa Nyholm / SpareTimeLabs * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * Neither the name of the Kustaa Nyholm or SpareTimeLabs nor the names of its * contributors may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ package purejavacomm.testsuite; public class Test1 extends TestBase { static void run() throws Exception { try { begin("Test1 - control lines "); openPort(); m_Port.setRTS(false); m_Port.setDTR(false); sleep(); m_Port.notifyOnCTS(true); m_Port.notifyOnRingIndicator(true); m_Port.notifyOnCarrierDetect(true); m_Port.notifyOnDSR(true); final int[] counts = new int[11];
// Path: src/purejavacomm/SerialPortEvent.java // public class SerialPortEvent extends EventObject { // /** // * Data available at the serial port. // */ // public static final int DATA_AVAILABLE = 1; // /** // * Output buffer is empty. // */ // public static final int OUTPUT_BUFFER_EMPTY = 2; // /** // * Clear to send. // */ // public static final int CTS = 3; // /** // * Data set ready. // */ // public static final int DSR = 4; // /** // * Ring indicator. // */ // public static final int RI = 5; // /** // * Carrier detect. // */ // public static final int CD = 6; // /** // * Overrun error. // */ // public static final int OE = 7; // /** // * Parity error. // */ // public static final int PE = 8; // /** // * Framing error. // */ // public static final int FE = 9; // /** // * Break interrupt. // */ // public static final int BI = 10; // // private final int eventType; // private final boolean newValue; // private final boolean oldValue; // // /** // * Constructs a <CODE>SerialPortEvent</CODE> with the specified serial port, // * event type, old and new values. Application programs should not directly // * create <CODE>SerialPortEvent</CODE> objects. // * // * @param source // * @param eventType // * @param oldValue // * @param newValue // */ // public SerialPortEvent(SerialPort source, int eventType, boolean oldValue, boolean newValue) { // super(source); // this.eventType = eventType; // this.newValue = newValue; // this.oldValue = oldValue; // } // // /** // * Returns the type of this event. // * // * @return The type of this event. // */ // public int getEventType() { // return this.eventType; // } // // /** // * Returns the new value of the state change that caused the // * <CODE>SerialPortEvent</CODE> to be propagated. // * // * @return The new value of the state change. // */ // public boolean getNewValue() { // return this.newValue; // } // // /** // * Returns the old value of the state change that caused the // * <CODE>SerialPortEvent</CODE> to be propagated. // * // * @return The old value of the state change. // */ // public boolean getOldValue() { // return this.oldValue; // } // } // // Path: src/purejavacomm/SerialPortEventListener.java // public interface SerialPortEventListener extends EventListener { // public void serialEvent(SerialPortEvent event); // } // Path: src/purejavacomm/testsuite/Test1.java import purejavacomm.SerialPortEventListener; import purejavacomm.SerialPortEvent; /* * Copyright (c) 2011, Kustaa Nyholm / SpareTimeLabs * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * Neither the name of the Kustaa Nyholm or SpareTimeLabs nor the names of its * contributors may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ package purejavacomm.testsuite; public class Test1 extends TestBase { static void run() throws Exception { try { begin("Test1 - control lines "); openPort(); m_Port.setRTS(false); m_Port.setDTR(false); sleep(); m_Port.notifyOnCTS(true); m_Port.notifyOnRingIndicator(true); m_Port.notifyOnCarrierDetect(true); m_Port.notifyOnDSR(true); final int[] counts = new int[11];
m_Port.addEventListener(new SerialPortEventListener() {
nyholku/purejavacomm
src/purejavacomm/testsuite/Test1.java
// Path: src/purejavacomm/SerialPortEvent.java // public class SerialPortEvent extends EventObject { // /** // * Data available at the serial port. // */ // public static final int DATA_AVAILABLE = 1; // /** // * Output buffer is empty. // */ // public static final int OUTPUT_BUFFER_EMPTY = 2; // /** // * Clear to send. // */ // public static final int CTS = 3; // /** // * Data set ready. // */ // public static final int DSR = 4; // /** // * Ring indicator. // */ // public static final int RI = 5; // /** // * Carrier detect. // */ // public static final int CD = 6; // /** // * Overrun error. // */ // public static final int OE = 7; // /** // * Parity error. // */ // public static final int PE = 8; // /** // * Framing error. // */ // public static final int FE = 9; // /** // * Break interrupt. // */ // public static final int BI = 10; // // private final int eventType; // private final boolean newValue; // private final boolean oldValue; // // /** // * Constructs a <CODE>SerialPortEvent</CODE> with the specified serial port, // * event type, old and new values. Application programs should not directly // * create <CODE>SerialPortEvent</CODE> objects. // * // * @param source // * @param eventType // * @param oldValue // * @param newValue // */ // public SerialPortEvent(SerialPort source, int eventType, boolean oldValue, boolean newValue) { // super(source); // this.eventType = eventType; // this.newValue = newValue; // this.oldValue = oldValue; // } // // /** // * Returns the type of this event. // * // * @return The type of this event. // */ // public int getEventType() { // return this.eventType; // } // // /** // * Returns the new value of the state change that caused the // * <CODE>SerialPortEvent</CODE> to be propagated. // * // * @return The new value of the state change. // */ // public boolean getNewValue() { // return this.newValue; // } // // /** // * Returns the old value of the state change that caused the // * <CODE>SerialPortEvent</CODE> to be propagated. // * // * @return The old value of the state change. // */ // public boolean getOldValue() { // return this.oldValue; // } // } // // Path: src/purejavacomm/SerialPortEventListener.java // public interface SerialPortEventListener extends EventListener { // public void serialEvent(SerialPortEvent event); // }
import purejavacomm.SerialPortEventListener; import purejavacomm.SerialPortEvent;
/* * Copyright (c) 2011, Kustaa Nyholm / SpareTimeLabs * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * Neither the name of the Kustaa Nyholm or SpareTimeLabs nor the names of its * contributors may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ package purejavacomm.testsuite; public class Test1 extends TestBase { static void run() throws Exception { try { begin("Test1 - control lines "); openPort(); m_Port.setRTS(false); m_Port.setDTR(false); sleep(); m_Port.notifyOnCTS(true); m_Port.notifyOnRingIndicator(true); m_Port.notifyOnCarrierDetect(true); m_Port.notifyOnDSR(true); final int[] counts = new int[11]; m_Port.addEventListener(new SerialPortEventListener() {
// Path: src/purejavacomm/SerialPortEvent.java // public class SerialPortEvent extends EventObject { // /** // * Data available at the serial port. // */ // public static final int DATA_AVAILABLE = 1; // /** // * Output buffer is empty. // */ // public static final int OUTPUT_BUFFER_EMPTY = 2; // /** // * Clear to send. // */ // public static final int CTS = 3; // /** // * Data set ready. // */ // public static final int DSR = 4; // /** // * Ring indicator. // */ // public static final int RI = 5; // /** // * Carrier detect. // */ // public static final int CD = 6; // /** // * Overrun error. // */ // public static final int OE = 7; // /** // * Parity error. // */ // public static final int PE = 8; // /** // * Framing error. // */ // public static final int FE = 9; // /** // * Break interrupt. // */ // public static final int BI = 10; // // private final int eventType; // private final boolean newValue; // private final boolean oldValue; // // /** // * Constructs a <CODE>SerialPortEvent</CODE> with the specified serial port, // * event type, old and new values. Application programs should not directly // * create <CODE>SerialPortEvent</CODE> objects. // * // * @param source // * @param eventType // * @param oldValue // * @param newValue // */ // public SerialPortEvent(SerialPort source, int eventType, boolean oldValue, boolean newValue) { // super(source); // this.eventType = eventType; // this.newValue = newValue; // this.oldValue = oldValue; // } // // /** // * Returns the type of this event. // * // * @return The type of this event. // */ // public int getEventType() { // return this.eventType; // } // // /** // * Returns the new value of the state change that caused the // * <CODE>SerialPortEvent</CODE> to be propagated. // * // * @return The new value of the state change. // */ // public boolean getNewValue() { // return this.newValue; // } // // /** // * Returns the old value of the state change that caused the // * <CODE>SerialPortEvent</CODE> to be propagated. // * // * @return The old value of the state change. // */ // public boolean getOldValue() { // return this.oldValue; // } // } // // Path: src/purejavacomm/SerialPortEventListener.java // public interface SerialPortEventListener extends EventListener { // public void serialEvent(SerialPortEvent event); // } // Path: src/purejavacomm/testsuite/Test1.java import purejavacomm.SerialPortEventListener; import purejavacomm.SerialPortEvent; /* * Copyright (c) 2011, Kustaa Nyholm / SpareTimeLabs * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * Neither the name of the Kustaa Nyholm or SpareTimeLabs nor the names of its * contributors may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ package purejavacomm.testsuite; public class Test1 extends TestBase { static void run() throws Exception { try { begin("Test1 - control lines "); openPort(); m_Port.setRTS(false); m_Port.setDTR(false); sleep(); m_Port.notifyOnCTS(true); m_Port.notifyOnRingIndicator(true); m_Port.notifyOnCarrierDetect(true); m_Port.notifyOnDSR(true); final int[] counts = new int[11]; m_Port.addEventListener(new SerialPortEventListener() {
public void serialEvent(SerialPortEvent event) {
PhantomThief/simple-failover-java
src/test/java/com/github/phantomthief/failover/impl/checker/SimplePortCheckerTest.java
// Path: src/main/java/com/github/phantomthief/failover/impl/checker/SimplePortChecker.java // @Nonnull // public static ListenableFuture<Void> asyncCheck(@Nonnull HostAndPort hostAndPort) { // return asyncCheck(hostAndPort.getHost(), hostAndPort.getPort()); // } // // Path: src/main/java/com/github/phantomthief/failover/impl/checker/SimplePortChecker.java // public static boolean check(String host, int port) { // return check(host, port, DEFAULT_CONNECTION_TIMEOUT); // }
import static com.github.phantomthief.failover.impl.checker.SimplePortChecker.asyncCheck; import static com.github.phantomthief.failover.impl.checker.SimplePortChecker.check; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.net.ServerSocket; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeoutException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.google.common.util.concurrent.ListenableFuture;
package com.github.phantomthief.failover.impl.checker; /** * @author w.vela * Created on 2018-06-25. */ class SimplePortCheckerTest { private ServerSocket serverSocket; private int port; @BeforeEach void setUp() throws IOException { port = ThreadLocalRandom.current().nextInt(1025, 10240); serverSocket = new ServerSocket(port); } @Test void testSync() {
// Path: src/main/java/com/github/phantomthief/failover/impl/checker/SimplePortChecker.java // @Nonnull // public static ListenableFuture<Void> asyncCheck(@Nonnull HostAndPort hostAndPort) { // return asyncCheck(hostAndPort.getHost(), hostAndPort.getPort()); // } // // Path: src/main/java/com/github/phantomthief/failover/impl/checker/SimplePortChecker.java // public static boolean check(String host, int port) { // return check(host, port, DEFAULT_CONNECTION_TIMEOUT); // } // Path: src/test/java/com/github/phantomthief/failover/impl/checker/SimplePortCheckerTest.java import static com.github.phantomthief.failover.impl.checker.SimplePortChecker.asyncCheck; import static com.github.phantomthief.failover.impl.checker.SimplePortChecker.check; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.net.ServerSocket; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeoutException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.google.common.util.concurrent.ListenableFuture; package com.github.phantomthief.failover.impl.checker; /** * @author w.vela * Created on 2018-06-25. */ class SimplePortCheckerTest { private ServerSocket serverSocket; private int port; @BeforeEach void setUp() throws IOException { port = ThreadLocalRandom.current().nextInt(1025, 10240); serverSocket = new ServerSocket(port); } @Test void testSync() {
assertTrue(check("localhost", port, 100));
PhantomThief/simple-failover-java
src/test/java/com/github/phantomthief/failover/impl/checker/SimplePortCheckerTest.java
// Path: src/main/java/com/github/phantomthief/failover/impl/checker/SimplePortChecker.java // @Nonnull // public static ListenableFuture<Void> asyncCheck(@Nonnull HostAndPort hostAndPort) { // return asyncCheck(hostAndPort.getHost(), hostAndPort.getPort()); // } // // Path: src/main/java/com/github/phantomthief/failover/impl/checker/SimplePortChecker.java // public static boolean check(String host, int port) { // return check(host, port, DEFAULT_CONNECTION_TIMEOUT); // }
import static com.github.phantomthief.failover.impl.checker.SimplePortChecker.asyncCheck; import static com.github.phantomthief.failover.impl.checker.SimplePortChecker.check; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.net.ServerSocket; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeoutException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.google.common.util.concurrent.ListenableFuture;
package com.github.phantomthief.failover.impl.checker; /** * @author w.vela * Created on 2018-06-25. */ class SimplePortCheckerTest { private ServerSocket serverSocket; private int port; @BeforeEach void setUp() throws IOException { port = ThreadLocalRandom.current().nextInt(1025, 10240); serverSocket = new ServerSocket(port); } @Test void testSync() { assertTrue(check("localhost", port, 100)); } @Test void testAsync() throws InterruptedException, ExecutionException, TimeoutException {
// Path: src/main/java/com/github/phantomthief/failover/impl/checker/SimplePortChecker.java // @Nonnull // public static ListenableFuture<Void> asyncCheck(@Nonnull HostAndPort hostAndPort) { // return asyncCheck(hostAndPort.getHost(), hostAndPort.getPort()); // } // // Path: src/main/java/com/github/phantomthief/failover/impl/checker/SimplePortChecker.java // public static boolean check(String host, int port) { // return check(host, port, DEFAULT_CONNECTION_TIMEOUT); // } // Path: src/test/java/com/github/phantomthief/failover/impl/checker/SimplePortCheckerTest.java import static com.github.phantomthief.failover.impl.checker.SimplePortChecker.asyncCheck; import static com.github.phantomthief.failover.impl.checker.SimplePortChecker.check; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.net.ServerSocket; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeoutException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import com.google.common.util.concurrent.ListenableFuture; package com.github.phantomthief.failover.impl.checker; /** * @author w.vela * Created on 2018-06-25. */ class SimplePortCheckerTest { private ServerSocket serverSocket; private int port; @BeforeEach void setUp() throws IOException { port = ThreadLocalRandom.current().nextInt(1025, 10240); serverSocket = new ServerSocket(port); } @Test void testSync() { assertTrue(check("localhost", port, 100)); } @Test void testAsync() throws InterruptedException, ExecutionException, TimeoutException {
ListenableFuture<Void> future = asyncCheck("localhost", port);
PhantomThief/simple-failover-java
src/main/java/com/github/phantomthief/failover/impl/WeightFailoverCheckTask.java
// Path: src/main/java/com/github/phantomthief/failover/util/SharedCheckExecutorHolder.java // public class SharedCheckExecutorHolder { // // private static final int THREAD_COUNT = 10; // // public static ScheduledExecutorService getInstance() { // return LazyHolder.INSTANCE; // } // // private static class LazyHolder { // // private static final ScheduledExecutorService INSTANCE = new ScheduledThreadPoolExecutor( // THREAD_COUNT, // new ThreadFactory() { // private AtomicLong count = new AtomicLong(); // private static final String NAME_PATTERN = "scheduled-failover-recovery-check-%d"; // @Override // public Thread newThread(Runnable r) { // String name = format(NAME_PATTERN, count.getAndIncrement()); // Thread thread = new Thread(r, name); // thread.setDaemon(true); // thread.setPriority(MIN_PRIORITY); // if (Thread.getDefaultUncaughtExceptionHandler() == null) { // thread.setUncaughtExceptionHandler((t, e) -> { // e.printStackTrace(); // }); // } // return thread; // } // }) { // // public void shutdown() { // throw new UnsupportedOperationException(); // } // // public List<Runnable> shutdownNow() { // throw new UnsupportedOperationException(); // } // }; // } // }
import static com.github.phantomthief.util.MoreSuppliers.lazy; import static com.google.common.primitives.Ints.constrainToRange; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import java.lang.ref.PhantomReference; import java.lang.ref.ReferenceQueue; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.phantomthief.failover.util.SharedCheckExecutorHolder; import com.github.phantomthief.util.MoreSuppliers.CloseableSupplier;
package com.github.phantomthief.failover.impl; /** * * @author w.vela * @author huangli */ class WeightFailoverCheckTask<T> { private static final Logger logger = LoggerFactory.getLogger(WeightFailoverCheckTask.class); static final int CLEAN_INIT_DELAY_SECONDS = 5; static final int CLEAN_DELAY_SECONDS = 10; static {
// Path: src/main/java/com/github/phantomthief/failover/util/SharedCheckExecutorHolder.java // public class SharedCheckExecutorHolder { // // private static final int THREAD_COUNT = 10; // // public static ScheduledExecutorService getInstance() { // return LazyHolder.INSTANCE; // } // // private static class LazyHolder { // // private static final ScheduledExecutorService INSTANCE = new ScheduledThreadPoolExecutor( // THREAD_COUNT, // new ThreadFactory() { // private AtomicLong count = new AtomicLong(); // private static final String NAME_PATTERN = "scheduled-failover-recovery-check-%d"; // @Override // public Thread newThread(Runnable r) { // String name = format(NAME_PATTERN, count.getAndIncrement()); // Thread thread = new Thread(r, name); // thread.setDaemon(true); // thread.setPriority(MIN_PRIORITY); // if (Thread.getDefaultUncaughtExceptionHandler() == null) { // thread.setUncaughtExceptionHandler((t, e) -> { // e.printStackTrace(); // }); // } // return thread; // } // }) { // // public void shutdown() { // throw new UnsupportedOperationException(); // } // // public List<Runnable> shutdownNow() { // throw new UnsupportedOperationException(); // } // }; // } // } // Path: src/main/java/com/github/phantomthief/failover/impl/WeightFailoverCheckTask.java import static com.github.phantomthief.util.MoreSuppliers.lazy; import static com.google.common.primitives.Ints.constrainToRange; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import java.lang.ref.PhantomReference; import java.lang.ref.ReferenceQueue; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.phantomthief.failover.util.SharedCheckExecutorHolder; import com.github.phantomthief.util.MoreSuppliers.CloseableSupplier; package com.github.phantomthief.failover.impl; /** * * @author w.vela * @author huangli */ class WeightFailoverCheckTask<T> { private static final Logger logger = LoggerFactory.getLogger(WeightFailoverCheckTask.class); static final int CLEAN_INIT_DELAY_SECONDS = 5; static final int CLEAN_DELAY_SECONDS = 10; static {
SharedCheckExecutorHolder.getInstance().scheduleWithFixedDelay(WeightFailoverCheckTask::doClean,
PhantomThief/simple-failover-java
src/test/java/com/github/phantomthief/failover/util/SharedResourceV2Test.java
// Path: src/main/java/com/github/phantomthief/failover/util/SharedResourceV2.java // public static class UnregisterFailedException extends RuntimeException { // // private final Object removed; // // private UnregisterFailedException(Throwable cause, Object removed) { // super(cause); // this.removed = removed; // } // // @SuppressWarnings("unchecked") // public <T> T getRemoved() { // return (T) removed; // } // }
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.github.phantomthief.failover.util.SharedResourceV2.UnregisterFailedException; import com.google.common.util.concurrent.Uninterruptibles;
assertFalse(mockResource1.isShutdown()); resources.unregister("1"); mockResource1 = resources.get("1"); assertNotNull(mockResource1); assertFalse(mockResource1.isShutdown()); resources.unregister("1"); assertTrue(mockResource1.isShutdown()); mockResource1 = resources.get("1"); assertNull(mockResource1); } @Test void testUnpairUnregister() { resources.register("3"); MockResource mock = resources.get("3"); assertSame(mock, resources.unregister("3")); assertThrows(IllegalStateException.class, () -> resources.unregister("3")); } @Test void testCleanupFailed() { SharedResourceV2<String, MockResource> resources = new SharedResourceV2<>(MockResource::new, it -> { throw new IllegalArgumentException(); }); resources.register("4"); MockResource mock = resources.get("4");
// Path: src/main/java/com/github/phantomthief/failover/util/SharedResourceV2.java // public static class UnregisterFailedException extends RuntimeException { // // private final Object removed; // // private UnregisterFailedException(Throwable cause, Object removed) { // super(cause); // this.removed = removed; // } // // @SuppressWarnings("unchecked") // public <T> T getRemoved() { // return (T) removed; // } // } // Path: src/test/java/com/github/phantomthief/failover/util/SharedResourceV2Test.java import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.github.phantomthief.failover.util.SharedResourceV2.UnregisterFailedException; import com.google.common.util.concurrent.Uninterruptibles; assertFalse(mockResource1.isShutdown()); resources.unregister("1"); mockResource1 = resources.get("1"); assertNotNull(mockResource1); assertFalse(mockResource1.isShutdown()); resources.unregister("1"); assertTrue(mockResource1.isShutdown()); mockResource1 = resources.get("1"); assertNull(mockResource1); } @Test void testUnpairUnregister() { resources.register("3"); MockResource mock = resources.get("3"); assertSame(mock, resources.unregister("3")); assertThrows(IllegalStateException.class, () -> resources.unregister("3")); } @Test void testCleanupFailed() { SharedResourceV2<String, MockResource> resources = new SharedResourceV2<>(MockResource::new, it -> { throw new IllegalArgumentException(); }); resources.register("4"); MockResource mock = resources.get("4");
UnregisterFailedException e = assertThrows(UnregisterFailedException.class,
PhantomThief/simple-failover-java
src/main/java/com/github/phantomthief/failover/util/ConcurrencyAware.java
// Path: src/main/java/com/github/phantomthief/failover/util/RandomListUtils.java // @Nullable // public static <T> T getRandom(List<T> source) { // if (source == null || source.isEmpty()) { // return null; // } // return source.get(ThreadLocalRandom.current().nextInt(source.size())); // }
import static com.github.phantomthief.failover.util.RandomListUtils.getRandom; import static com.google.common.base.Preconditions.checkNotNull; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.RandomAccess; import java.util.concurrent.ConcurrentHashMap; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.phantomthief.util.ThrowableConsumer; import com.github.phantomthief.util.ThrowableFunction;
} public static <T> ConcurrencyAware<T> create() { return new ConcurrencyAware<>(); } @Nullable private T selectIdlest(@Nonnull Iterable<T> candidates) { checkNotNull(candidates); if (candidates instanceof List && candidates instanceof RandomAccess) { List<T> candidatesCol = (List<T>) candidates; T t = selectIdlestFast(candidatesCol); if (t != null) { return t; } } // find objects with minimum concurrency List<T> idlest = new ArrayList<>(); int minValue = Integer.MAX_VALUE; for (T obj : candidates) { int c = concurrency.getOrDefault(obj, 0); if (c < minValue) { minValue = c; idlest.clear(); idlest.add(obj); } else if (c == minValue) { idlest.add(obj); } }
// Path: src/main/java/com/github/phantomthief/failover/util/RandomListUtils.java // @Nullable // public static <T> T getRandom(List<T> source) { // if (source == null || source.isEmpty()) { // return null; // } // return source.get(ThreadLocalRandom.current().nextInt(source.size())); // } // Path: src/main/java/com/github/phantomthief/failover/util/ConcurrencyAware.java import static com.github.phantomthief.failover.util.RandomListUtils.getRandom; import static com.google.common.base.Preconditions.checkNotNull; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.RandomAccess; import java.util.concurrent.ConcurrentHashMap; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.phantomthief.util.ThrowableConsumer; import com.github.phantomthief.util.ThrowableFunction; } public static <T> ConcurrencyAware<T> create() { return new ConcurrencyAware<>(); } @Nullable private T selectIdlest(@Nonnull Iterable<T> candidates) { checkNotNull(candidates); if (candidates instanceof List && candidates instanceof RandomAccess) { List<T> candidatesCol = (List<T>) candidates; T t = selectIdlestFast(candidatesCol); if (t != null) { return t; } } // find objects with minimum concurrency List<T> idlest = new ArrayList<>(); int minValue = Integer.MAX_VALUE; for (T obj : candidates) { int c = concurrency.getOrDefault(obj, 0); if (c < minValue) { minValue = c; idlest.clear(); idlest.add(obj); } else if (c == minValue) { idlest.add(obj); } }
T result = getRandom(idlest);
PhantomThief/simple-failover-java
src/test/java/com/github/phantomthief/failover/util/RandomListUtilsTest.java
// Path: src/main/java/com/github/phantomthief/failover/util/RandomListUtils.java // static <T> List<T> getRandomUsingLcg(List<T> source, int size) { // int targetSize = min(source.size(), size); // List<T> newList = new ArrayList<>(targetSize); // LcgRandomIterator<T> iterator = new LcgRandomIterator<>(source); // for (int i = 0; i < targetSize; i++) { // newList.add(iterator.next()); // } // return newList; // } // // Path: src/main/java/com/github/phantomthief/failover/util/RandomListUtils.java // static <T> List<T> getRandomUsingShuffle(Collection<T> source, int size) { // List<T> newList = new ArrayList<>(source); // shuffle(newList, ThreadLocalRandom.current()); // return newList.subList(0, min(newList.size(), size)); // }
import static com.github.phantomthief.failover.util.RandomListUtils.getRandomUsingLcg; import static com.github.phantomthief.failover.util.RandomListUtils.getRandomUsingShuffle; import static java.lang.System.nanoTime; import static java.util.stream.Collectors.toList; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.IntStream; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.github.phantomthief.failover.util; /** * @author w.vela * Created on 2018-02-26. */ class RandomListUtilsTest { private static final Logger logger = LoggerFactory.getLogger(RandomListUtilsTest.class); @Test void getRandom() { long lcgBetter = 0, shuffleBetter = 0; for (int i = 0; i < 1000; i++) { int size = ThreadLocalRandom.current().nextInt(1, 10000); int retrieved = ThreadLocalRandom.current().nextInt(1, Math.max(2, size / 3)); List<Integer> list = IntStream.range(0, size).boxed().collect(toList()); long s = nanoTime();
// Path: src/main/java/com/github/phantomthief/failover/util/RandomListUtils.java // static <T> List<T> getRandomUsingLcg(List<T> source, int size) { // int targetSize = min(source.size(), size); // List<T> newList = new ArrayList<>(targetSize); // LcgRandomIterator<T> iterator = new LcgRandomIterator<>(source); // for (int i = 0; i < targetSize; i++) { // newList.add(iterator.next()); // } // return newList; // } // // Path: src/main/java/com/github/phantomthief/failover/util/RandomListUtils.java // static <T> List<T> getRandomUsingShuffle(Collection<T> source, int size) { // List<T> newList = new ArrayList<>(source); // shuffle(newList, ThreadLocalRandom.current()); // return newList.subList(0, min(newList.size(), size)); // } // Path: src/test/java/com/github/phantomthief/failover/util/RandomListUtilsTest.java import static com.github.phantomthief.failover.util.RandomListUtils.getRandomUsingLcg; import static com.github.phantomthief.failover.util.RandomListUtils.getRandomUsingShuffle; import static java.lang.System.nanoTime; import static java.util.stream.Collectors.toList; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.IntStream; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.github.phantomthief.failover.util; /** * @author w.vela * Created on 2018-02-26. */ class RandomListUtilsTest { private static final Logger logger = LoggerFactory.getLogger(RandomListUtilsTest.class); @Test void getRandom() { long lcgBetter = 0, shuffleBetter = 0; for (int i = 0; i < 1000; i++) { int size = ThreadLocalRandom.current().nextInt(1, 10000); int retrieved = ThreadLocalRandom.current().nextInt(1, Math.max(2, size / 3)); List<Integer> list = IntStream.range(0, size).boxed().collect(toList()); long s = nanoTime();
List<Integer> result = getRandomUsingLcg(list, retrieved);
PhantomThief/simple-failover-java
src/test/java/com/github/phantomthief/failover/util/RandomListUtilsTest.java
// Path: src/main/java/com/github/phantomthief/failover/util/RandomListUtils.java // static <T> List<T> getRandomUsingLcg(List<T> source, int size) { // int targetSize = min(source.size(), size); // List<T> newList = new ArrayList<>(targetSize); // LcgRandomIterator<T> iterator = new LcgRandomIterator<>(source); // for (int i = 0; i < targetSize; i++) { // newList.add(iterator.next()); // } // return newList; // } // // Path: src/main/java/com/github/phantomthief/failover/util/RandomListUtils.java // static <T> List<T> getRandomUsingShuffle(Collection<T> source, int size) { // List<T> newList = new ArrayList<>(source); // shuffle(newList, ThreadLocalRandom.current()); // return newList.subList(0, min(newList.size(), size)); // }
import static com.github.phantomthief.failover.util.RandomListUtils.getRandomUsingLcg; import static com.github.phantomthief.failover.util.RandomListUtils.getRandomUsingShuffle; import static java.lang.System.nanoTime; import static java.util.stream.Collectors.toList; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.IntStream; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.github.phantomthief.failover.util; /** * @author w.vela * Created on 2018-02-26. */ class RandomListUtilsTest { private static final Logger logger = LoggerFactory.getLogger(RandomListUtilsTest.class); @Test void getRandom() { long lcgBetter = 0, shuffleBetter = 0; for (int i = 0; i < 1000; i++) { int size = ThreadLocalRandom.current().nextInt(1, 10000); int retrieved = ThreadLocalRandom.current().nextInt(1, Math.max(2, size / 3)); List<Integer> list = IntStream.range(0, size).boxed().collect(toList()); long s = nanoTime(); List<Integer> result = getRandomUsingLcg(list, retrieved); long costLcg = nanoTime() - s; long s2 = nanoTime();
// Path: src/main/java/com/github/phantomthief/failover/util/RandomListUtils.java // static <T> List<T> getRandomUsingLcg(List<T> source, int size) { // int targetSize = min(source.size(), size); // List<T> newList = new ArrayList<>(targetSize); // LcgRandomIterator<T> iterator = new LcgRandomIterator<>(source); // for (int i = 0; i < targetSize; i++) { // newList.add(iterator.next()); // } // return newList; // } // // Path: src/main/java/com/github/phantomthief/failover/util/RandomListUtils.java // static <T> List<T> getRandomUsingShuffle(Collection<T> source, int size) { // List<T> newList = new ArrayList<>(source); // shuffle(newList, ThreadLocalRandom.current()); // return newList.subList(0, min(newList.size(), size)); // } // Path: src/test/java/com/github/phantomthief/failover/util/RandomListUtilsTest.java import static com.github.phantomthief.failover.util.RandomListUtils.getRandomUsingLcg; import static com.github.phantomthief.failover.util.RandomListUtils.getRandomUsingShuffle; import static java.lang.System.nanoTime; import static java.util.stream.Collectors.toList; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.IntStream; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.github.phantomthief.failover.util; /** * @author w.vela * Created on 2018-02-26. */ class RandomListUtilsTest { private static final Logger logger = LoggerFactory.getLogger(RandomListUtilsTest.class); @Test void getRandom() { long lcgBetter = 0, shuffleBetter = 0; for (int i = 0; i < 1000; i++) { int size = ThreadLocalRandom.current().nextInt(1, 10000); int retrieved = ThreadLocalRandom.current().nextInt(1, Math.max(2, size / 3)); List<Integer> list = IntStream.range(0, size).boxed().collect(toList()); long s = nanoTime(); List<Integer> result = getRandomUsingLcg(list, retrieved); long costLcg = nanoTime() - s; long s2 = nanoTime();
getRandomUsingShuffle(list, retrieved);
PhantomThief/simple-failover-java
src/main/java/com/github/phantomthief/failover/impl/PriorityFailoverBuilder.java
// Path: src/main/java/com/github/phantomthief/failover/util/SharedCheckExecutorHolder.java // public class SharedCheckExecutorHolder { // // private static final int THREAD_COUNT = 10; // // public static ScheduledExecutorService getInstance() { // return LazyHolder.INSTANCE; // } // // private static class LazyHolder { // // private static final ScheduledExecutorService INSTANCE = new ScheduledThreadPoolExecutor( // THREAD_COUNT, // new ThreadFactory() { // private AtomicLong count = new AtomicLong(); // private static final String NAME_PATTERN = "scheduled-failover-recovery-check-%d"; // @Override // public Thread newThread(Runnable r) { // String name = format(NAME_PATTERN, count.getAndIncrement()); // Thread thread = new Thread(r, name); // thread.setDaemon(true); // thread.setPriority(MIN_PRIORITY); // if (Thread.getDefaultUncaughtExceptionHandler() == null) { // thread.setUncaughtExceptionHandler((t, e) -> { // e.printStackTrace(); // }); // } // return thread; // } // }) { // // public void shutdown() { // throw new UnsupportedOperationException(); // } // // public List<Runnable> shutdownNow() { // throw new UnsupportedOperationException(); // } // }; // } // }
import static java.util.Objects.requireNonNull; import java.time.Duration; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.ScheduledExecutorService; import java.util.function.Predicate; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.github.phantomthief.failover.util.SharedCheckExecutorHolder;
public int getPriority() { return priority; } public double getMaxWeight() { return maxWeight; } public double getMinWeight() { return minWeight; } public double getInitWeight() { return initWeight; } } static class PriorityFailoverConfig<T> implements Cloneable { private Map<T, ResConfig> resources = new HashMap<>(); private String name; private double priorityFactor = 1.4; private WeightFunction<T> weightFunction = new RatioWeightFunction<>(); @Nullable private WeightListener<T> weightListener; private boolean concurrencyControl = false; private boolean manualConcurrencyControl = false; private Duration checkDuration = Duration.ofSeconds(1);
// Path: src/main/java/com/github/phantomthief/failover/util/SharedCheckExecutorHolder.java // public class SharedCheckExecutorHolder { // // private static final int THREAD_COUNT = 10; // // public static ScheduledExecutorService getInstance() { // return LazyHolder.INSTANCE; // } // // private static class LazyHolder { // // private static final ScheduledExecutorService INSTANCE = new ScheduledThreadPoolExecutor( // THREAD_COUNT, // new ThreadFactory() { // private AtomicLong count = new AtomicLong(); // private static final String NAME_PATTERN = "scheduled-failover-recovery-check-%d"; // @Override // public Thread newThread(Runnable r) { // String name = format(NAME_PATTERN, count.getAndIncrement()); // Thread thread = new Thread(r, name); // thread.setDaemon(true); // thread.setPriority(MIN_PRIORITY); // if (Thread.getDefaultUncaughtExceptionHandler() == null) { // thread.setUncaughtExceptionHandler((t, e) -> { // e.printStackTrace(); // }); // } // return thread; // } // }) { // // public void shutdown() { // throw new UnsupportedOperationException(); // } // // public List<Runnable> shutdownNow() { // throw new UnsupportedOperationException(); // } // }; // } // } // Path: src/main/java/com/github/phantomthief/failover/impl/PriorityFailoverBuilder.java import static java.util.Objects.requireNonNull; import java.time.Duration; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.ScheduledExecutorService; import java.util.function.Predicate; import javax.annotation.Nonnull; import javax.annotation.Nullable; import com.github.phantomthief.failover.util.SharedCheckExecutorHolder; public int getPriority() { return priority; } public double getMaxWeight() { return maxWeight; } public double getMinWeight() { return minWeight; } public double getInitWeight() { return initWeight; } } static class PriorityFailoverConfig<T> implements Cloneable { private Map<T, ResConfig> resources = new HashMap<>(); private String name; private double priorityFactor = 1.4; private WeightFunction<T> weightFunction = new RatioWeightFunction<>(); @Nullable private WeightListener<T> weightListener; private boolean concurrencyControl = false; private boolean manualConcurrencyControl = false; private Duration checkDuration = Duration.ofSeconds(1);
private ScheduledExecutorService checkExecutor = SharedCheckExecutorHolder.getInstance();
PhantomThief/simple-failover-java
src/test/java/com/github/phantomthief/failover/impl/PriorityGroupManagerTest.java
// Path: src/main/java/com/github/phantomthief/failover/impl/PriorityGroupManager.java // static <T> HashMap<T, int[]> buildResMap(List<T> coreResources, List<T> restResources, // int[] coreGroupSizes) { // final int totalGroupCount = coreGroupSizes.length + 1; // HashMap<T, int[]> map = new HashMap<>(); // int logicIndex = 0; // int priority = 0; // int groupIndex = 0; // for (T res : coreResources) { // while (groupIndex >= coreGroupSizes[priority]) { // priority++; // groupIndex = 0; // } // map.put(res, new int[] {priority, logicIndex}); // groupIndex++; // logicIndex++; // } // for (T res : restResources) { // map.put(res, new int[] {totalGroupCount - 1, logicIndex}); // logicIndex++; // } // return map; // }
import static com.github.phantomthief.failover.impl.PriorityGroupManager.buildResMap; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.emptySet; import static java.util.Collections.singleton; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test;
package com.github.phantomthief.failover.impl; /** * @author huangli * Created on 2020-02-06 */ class PriorityGroupManagerTest { @Test public void testBuildResMap() { List<String> cores = asList("0", "1", "2"); List<String> rests = asList("3", "4", "5");
// Path: src/main/java/com/github/phantomthief/failover/impl/PriorityGroupManager.java // static <T> HashMap<T, int[]> buildResMap(List<T> coreResources, List<T> restResources, // int[] coreGroupSizes) { // final int totalGroupCount = coreGroupSizes.length + 1; // HashMap<T, int[]> map = new HashMap<>(); // int logicIndex = 0; // int priority = 0; // int groupIndex = 0; // for (T res : coreResources) { // while (groupIndex >= coreGroupSizes[priority]) { // priority++; // groupIndex = 0; // } // map.put(res, new int[] {priority, logicIndex}); // groupIndex++; // logicIndex++; // } // for (T res : restResources) { // map.put(res, new int[] {totalGroupCount - 1, logicIndex}); // logicIndex++; // } // return map; // } // Path: src/test/java/com/github/phantomthief/failover/impl/PriorityGroupManagerTest.java import static com.github.phantomthief.failover.impl.PriorityGroupManager.buildResMap; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.emptySet; import static java.util.Collections.singleton; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; package com.github.phantomthief.failover.impl; /** * @author huangli * Created on 2020-02-06 */ class PriorityGroupManagerTest { @Test public void testBuildResMap() { List<String> cores = asList("0", "1", "2"); List<String> rests = asList("3", "4", "5");
HashMap<String, int[]> map = buildResMap(cores, rests, new int[] {1, 2});
PhantomThief/simple-failover-java
src/test/java/com/github/phantomthief/failover/util/WeightTest.java
// Path: src/test/java/com/github/phantomthief/failover/WeighTestUtils.java // public static boolean checkRatio(int a, int b, int ratio) { // return between((double) a / b, (double) ratio - OFFSET, (double) ratio + OFFSET); // }
import static com.github.phantomthief.failover.WeighTestUtils.checkRatio; import static java.util.Collections.singleton; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import com.google.common.collect.HashMultiset; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Multiset;
package com.github.phantomthief.failover.util; /** * @author w.vela * Created on 2019-01-04. */ class WeightTest { @Test void test() { Weight<String> weight = new Weight<String>() .add("s1", 1) .add("s2", 2) .add("s3", 3); Multiset<String> result = HashMultiset.create(); for (int i = 0; i < 10000; i++) { result.add(weight.get()); }
// Path: src/test/java/com/github/phantomthief/failover/WeighTestUtils.java // public static boolean checkRatio(int a, int b, int ratio) { // return between((double) a / b, (double) ratio - OFFSET, (double) ratio + OFFSET); // } // Path: src/test/java/com/github/phantomthief/failover/util/WeightTest.java import static com.github.phantomthief.failover.WeighTestUtils.checkRatio; import static java.util.Collections.singleton; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import com.google.common.collect.HashMultiset; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Multiset; package com.github.phantomthief.failover.util; /** * @author w.vela * Created on 2019-01-04. */ class WeightTest { @Test void test() { Weight<String> weight = new Weight<String>() .add("s1", 1) .add("s2", 2) .add("s3", 3); Multiset<String> result = HashMultiset.create(); for (int i = 0; i < 10000; i++) { result.add(weight.get()); }
assertTrue(checkRatio(result.count("s2"), result.count("s1"), 2));
PhantomThief/simple-failover-java
src/test/java/com/github/phantomthief/failover/util/SharedResourceTest.java
// Path: src/main/java/com/github/phantomthief/failover/util/SharedResource.java // public static class UnregisterFailedException extends RuntimeException { // // private final Object removed; // // private UnregisterFailedException(Throwable cause, Object removed) { // super(cause); // this.removed = removed; // } // // @SuppressWarnings("unchecked") // public <T> T getRemoved() { // return (T) removed; // } // }
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import org.junit.jupiter.api.Test; import com.github.phantomthief.failover.util.SharedResource.UnregisterFailedException;
MockResource mockResource1 = resources.get("1"); MockResource mockResource2 = resources.get("1"); assertNotNull(mockResource1); assertSame(mockResource1, mockResource2); assertFalse(mockResource1.isShutdown()); resources.unregister("1", MockResource::close); mockResource1 = resources.get("1"); assertNotNull(mockResource1); assertFalse(mockResource1.isShutdown()); resources.unregister("1", MockResource::close); assertTrue(mockResource1.isShutdown()); mockResource1 = resources.get("1"); assertNull(mockResource1); } @Test void testUnpairUnregister() { resources.register("3", MockResource::new); MockResource mock = resources.get("3"); assertSame(mock, resources.unregister("3", MockResource::close)); assertThrows(IllegalStateException.class, () -> resources.unregister("3", MockResource::close)); } @Test void testCleanupFailed() { resources.register("4", MockResource::new); MockResource mock = resources.get("4");
// Path: src/main/java/com/github/phantomthief/failover/util/SharedResource.java // public static class UnregisterFailedException extends RuntimeException { // // private final Object removed; // // private UnregisterFailedException(Throwable cause, Object removed) { // super(cause); // this.removed = removed; // } // // @SuppressWarnings("unchecked") // public <T> T getRemoved() { // return (T) removed; // } // } // Path: src/test/java/com/github/phantomthief/failover/util/SharedResourceTest.java import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import org.junit.jupiter.api.Test; import com.github.phantomthief.failover.util.SharedResource.UnregisterFailedException; MockResource mockResource1 = resources.get("1"); MockResource mockResource2 = resources.get("1"); assertNotNull(mockResource1); assertSame(mockResource1, mockResource2); assertFalse(mockResource1.isShutdown()); resources.unregister("1", MockResource::close); mockResource1 = resources.get("1"); assertNotNull(mockResource1); assertFalse(mockResource1.isShutdown()); resources.unregister("1", MockResource::close); assertTrue(mockResource1.isShutdown()); mockResource1 = resources.get("1"); assertNull(mockResource1); } @Test void testUnpairUnregister() { resources.register("3", MockResource::new); MockResource mock = resources.get("3"); assertSame(mock, resources.unregister("3", MockResource::close)); assertThrows(IllegalStateException.class, () -> resources.unregister("3", MockResource::close)); } @Test void testCleanupFailed() { resources.register("4", MockResource::new); MockResource mock = resources.get("4");
UnregisterFailedException e = assertThrows(UnregisterFailedException.class,
PhantomThief/simple-failover-java
src/test/java/com/github/phantomthief/failover/impl/PriorityFailoverManagerTest.java
// Path: src/test/java/com/github/phantomthief/failover/impl/PriorityGroupManagerTest.java // static int[] countOfEachGroup(int groupCount, PriorityGroupManager<?> manager) { // Map<?, Integer> map = manager.getPriorityMap(); // int[] result = new int[groupCount]; // for (Map.Entry<?, Integer> en : map.entrySet()) { // result[en.getValue()]++; // } // return result; // } // // Path: src/main/java/com/github/phantomthief/failover/impl/PriorityFailoverBuilder.java // public static final class ResConfig implements Cloneable { // private final int priority; // private final double maxWeight; // private final double minWeight; // private final double initWeight; // // public ResConfig() { // this(DEFAULT_MAX_WEIGHT); // } // // public ResConfig(double maxWeight) { // this(maxWeight, DEFAULT_MIN_WEIGHT); // } // // public ResConfig(double maxWeight, double minWeight) { // this(maxWeight, minWeight, DEFAULT_PRIORITY); // } // // public ResConfig(double maxWeight, double minWeight, int priority) { // this(maxWeight, minWeight, priority, maxWeight); // } // // public ResConfig(double maxWeight, double minWeight, int priority, double initWeight) { // this.maxWeight = maxWeight; // this.minWeight = minWeight; // this.priority = priority; // this.initWeight = initWeight; // } // // @Override // public ResConfig clone() { // try { // return (ResConfig) super.clone(); // } catch (CloneNotSupportedException e) { // throw new RuntimeException(e); // } // } // // public int getPriority() { // return priority; // } // // public double getMaxWeight() { // return maxWeight; // } // // public double getMinWeight() { // return minWeight; // } // // public double getInitWeight() { // return initWeight; // } // } // // Path: src/main/java/com/github/phantomthief/failover/impl/PriorityFailoverManager.java // public static class UpdateResult<T> { // private Map<T, ResConfig> addedResources = new HashMap<>(); // private Map<T, ResConfig> removedResources = new HashMap<>(); // private Map<T, ResConfig> updatedResources = new HashMap<>(); // // /** // * 本次添加的资源,Map的value是新的配置。 // * @return 更新的资源 // */ // public Map<T, ResConfig> getAddedResources() { // return addedResources; // } // // /** // * 删除的资源,Map的value是旧的配置。 // * @return 更新的资源 // */ // public Map<T, ResConfig> getRemovedResources() { // return removedResources; // } // // /** // * 本次更新的资源,Map的value是新的配置。 // * @return 更新的资源 // */ // public Map<T, ResConfig> getUpdatedResources() { // return updatedResources; // } // // }
import static com.github.phantomthief.failover.impl.PriorityGroupManagerTest.countOfEachGroup; import static java.util.Collections.singleton; import static java.util.Collections.singletonMap; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.github.phantomthief.failover.impl.PriorityFailoverBuilder.ResConfig; import com.github.phantomthief.failover.impl.PriorityFailoverManager.UpdateResult;
package com.github.phantomthief.failover.impl; /** * @author huangli * Created on 2020-02-02 */ class PriorityFailoverManagerTest { private Object o0 = "o0"; private Object o1 = "o1"; private Object o2 = "o2"; @Test public void testUpdate() { PriorityFailover<Object> failover = PriorityFailover.newBuilder() .addResource(o0, 100, 0, 0, 100) .addResource(o1, 100, 0, 0, 100) .build(); PriorityFailoverManager<Object> manager = new PriorityFailoverManager<>(failover, null);
// Path: src/test/java/com/github/phantomthief/failover/impl/PriorityGroupManagerTest.java // static int[] countOfEachGroup(int groupCount, PriorityGroupManager<?> manager) { // Map<?, Integer> map = manager.getPriorityMap(); // int[] result = new int[groupCount]; // for (Map.Entry<?, Integer> en : map.entrySet()) { // result[en.getValue()]++; // } // return result; // } // // Path: src/main/java/com/github/phantomthief/failover/impl/PriorityFailoverBuilder.java // public static final class ResConfig implements Cloneable { // private final int priority; // private final double maxWeight; // private final double minWeight; // private final double initWeight; // // public ResConfig() { // this(DEFAULT_MAX_WEIGHT); // } // // public ResConfig(double maxWeight) { // this(maxWeight, DEFAULT_MIN_WEIGHT); // } // // public ResConfig(double maxWeight, double minWeight) { // this(maxWeight, minWeight, DEFAULT_PRIORITY); // } // // public ResConfig(double maxWeight, double minWeight, int priority) { // this(maxWeight, minWeight, priority, maxWeight); // } // // public ResConfig(double maxWeight, double minWeight, int priority, double initWeight) { // this.maxWeight = maxWeight; // this.minWeight = minWeight; // this.priority = priority; // this.initWeight = initWeight; // } // // @Override // public ResConfig clone() { // try { // return (ResConfig) super.clone(); // } catch (CloneNotSupportedException e) { // throw new RuntimeException(e); // } // } // // public int getPriority() { // return priority; // } // // public double getMaxWeight() { // return maxWeight; // } // // public double getMinWeight() { // return minWeight; // } // // public double getInitWeight() { // return initWeight; // } // } // // Path: src/main/java/com/github/phantomthief/failover/impl/PriorityFailoverManager.java // public static class UpdateResult<T> { // private Map<T, ResConfig> addedResources = new HashMap<>(); // private Map<T, ResConfig> removedResources = new HashMap<>(); // private Map<T, ResConfig> updatedResources = new HashMap<>(); // // /** // * 本次添加的资源,Map的value是新的配置。 // * @return 更新的资源 // */ // public Map<T, ResConfig> getAddedResources() { // return addedResources; // } // // /** // * 删除的资源,Map的value是旧的配置。 // * @return 更新的资源 // */ // public Map<T, ResConfig> getRemovedResources() { // return removedResources; // } // // /** // * 本次更新的资源,Map的value是新的配置。 // * @return 更新的资源 // */ // public Map<T, ResConfig> getUpdatedResources() { // return updatedResources; // } // // } // Path: src/test/java/com/github/phantomthief/failover/impl/PriorityFailoverManagerTest.java import static com.github.phantomthief.failover.impl.PriorityGroupManagerTest.countOfEachGroup; import static java.util.Collections.singleton; import static java.util.Collections.singletonMap; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.github.phantomthief.failover.impl.PriorityFailoverBuilder.ResConfig; import com.github.phantomthief.failover.impl.PriorityFailoverManager.UpdateResult; package com.github.phantomthief.failover.impl; /** * @author huangli * Created on 2020-02-02 */ class PriorityFailoverManagerTest { private Object o0 = "o0"; private Object o1 = "o1"; private Object o2 = "o2"; @Test public void testUpdate() { PriorityFailover<Object> failover = PriorityFailover.newBuilder() .addResource(o0, 100, 0, 0, 100) .addResource(o1, 100, 0, 0, 100) .build(); PriorityFailoverManager<Object> manager = new PriorityFailoverManager<>(failover, null);
Map<Object, ResConfig> addOrUpdate = new HashMap<>();
PhantomThief/simple-failover-java
src/test/java/com/github/phantomthief/failover/impl/PriorityFailoverManagerTest.java
// Path: src/test/java/com/github/phantomthief/failover/impl/PriorityGroupManagerTest.java // static int[] countOfEachGroup(int groupCount, PriorityGroupManager<?> manager) { // Map<?, Integer> map = manager.getPriorityMap(); // int[] result = new int[groupCount]; // for (Map.Entry<?, Integer> en : map.entrySet()) { // result[en.getValue()]++; // } // return result; // } // // Path: src/main/java/com/github/phantomthief/failover/impl/PriorityFailoverBuilder.java // public static final class ResConfig implements Cloneable { // private final int priority; // private final double maxWeight; // private final double minWeight; // private final double initWeight; // // public ResConfig() { // this(DEFAULT_MAX_WEIGHT); // } // // public ResConfig(double maxWeight) { // this(maxWeight, DEFAULT_MIN_WEIGHT); // } // // public ResConfig(double maxWeight, double minWeight) { // this(maxWeight, minWeight, DEFAULT_PRIORITY); // } // // public ResConfig(double maxWeight, double minWeight, int priority) { // this(maxWeight, minWeight, priority, maxWeight); // } // // public ResConfig(double maxWeight, double minWeight, int priority, double initWeight) { // this.maxWeight = maxWeight; // this.minWeight = minWeight; // this.priority = priority; // this.initWeight = initWeight; // } // // @Override // public ResConfig clone() { // try { // return (ResConfig) super.clone(); // } catch (CloneNotSupportedException e) { // throw new RuntimeException(e); // } // } // // public int getPriority() { // return priority; // } // // public double getMaxWeight() { // return maxWeight; // } // // public double getMinWeight() { // return minWeight; // } // // public double getInitWeight() { // return initWeight; // } // } // // Path: src/main/java/com/github/phantomthief/failover/impl/PriorityFailoverManager.java // public static class UpdateResult<T> { // private Map<T, ResConfig> addedResources = new HashMap<>(); // private Map<T, ResConfig> removedResources = new HashMap<>(); // private Map<T, ResConfig> updatedResources = new HashMap<>(); // // /** // * 本次添加的资源,Map的value是新的配置。 // * @return 更新的资源 // */ // public Map<T, ResConfig> getAddedResources() { // return addedResources; // } // // /** // * 删除的资源,Map的value是旧的配置。 // * @return 更新的资源 // */ // public Map<T, ResConfig> getRemovedResources() { // return removedResources; // } // // /** // * 本次更新的资源,Map的value是新的配置。 // * @return 更新的资源 // */ // public Map<T, ResConfig> getUpdatedResources() { // return updatedResources; // } // // }
import static com.github.phantomthief.failover.impl.PriorityGroupManagerTest.countOfEachGroup; import static java.util.Collections.singleton; import static java.util.Collections.singletonMap; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.github.phantomthief.failover.impl.PriorityFailoverBuilder.ResConfig; import com.github.phantomthief.failover.impl.PriorityFailoverManager.UpdateResult;
package com.github.phantomthief.failover.impl; /** * @author huangli * Created on 2020-02-02 */ class PriorityFailoverManagerTest { private Object o0 = "o0"; private Object o1 = "o1"; private Object o2 = "o2"; @Test public void testUpdate() { PriorityFailover<Object> failover = PriorityFailover.newBuilder() .addResource(o0, 100, 0, 0, 100) .addResource(o1, 100, 0, 0, 100) .build(); PriorityFailoverManager<Object> manager = new PriorityFailoverManager<>(failover, null); Map<Object, ResConfig> addOrUpdate = new HashMap<>(); addOrUpdate.put(o1, new ResConfig( 10, 5, 1, -1/*illegal but will be ignore*/)); addOrUpdate.put(o2, new ResConfig(10, 5, 1, 7));
// Path: src/test/java/com/github/phantomthief/failover/impl/PriorityGroupManagerTest.java // static int[] countOfEachGroup(int groupCount, PriorityGroupManager<?> manager) { // Map<?, Integer> map = manager.getPriorityMap(); // int[] result = new int[groupCount]; // for (Map.Entry<?, Integer> en : map.entrySet()) { // result[en.getValue()]++; // } // return result; // } // // Path: src/main/java/com/github/phantomthief/failover/impl/PriorityFailoverBuilder.java // public static final class ResConfig implements Cloneable { // private final int priority; // private final double maxWeight; // private final double minWeight; // private final double initWeight; // // public ResConfig() { // this(DEFAULT_MAX_WEIGHT); // } // // public ResConfig(double maxWeight) { // this(maxWeight, DEFAULT_MIN_WEIGHT); // } // // public ResConfig(double maxWeight, double minWeight) { // this(maxWeight, minWeight, DEFAULT_PRIORITY); // } // // public ResConfig(double maxWeight, double minWeight, int priority) { // this(maxWeight, minWeight, priority, maxWeight); // } // // public ResConfig(double maxWeight, double minWeight, int priority, double initWeight) { // this.maxWeight = maxWeight; // this.minWeight = minWeight; // this.priority = priority; // this.initWeight = initWeight; // } // // @Override // public ResConfig clone() { // try { // return (ResConfig) super.clone(); // } catch (CloneNotSupportedException e) { // throw new RuntimeException(e); // } // } // // public int getPriority() { // return priority; // } // // public double getMaxWeight() { // return maxWeight; // } // // public double getMinWeight() { // return minWeight; // } // // public double getInitWeight() { // return initWeight; // } // } // // Path: src/main/java/com/github/phantomthief/failover/impl/PriorityFailoverManager.java // public static class UpdateResult<T> { // private Map<T, ResConfig> addedResources = new HashMap<>(); // private Map<T, ResConfig> removedResources = new HashMap<>(); // private Map<T, ResConfig> updatedResources = new HashMap<>(); // // /** // * 本次添加的资源,Map的value是新的配置。 // * @return 更新的资源 // */ // public Map<T, ResConfig> getAddedResources() { // return addedResources; // } // // /** // * 删除的资源,Map的value是旧的配置。 // * @return 更新的资源 // */ // public Map<T, ResConfig> getRemovedResources() { // return removedResources; // } // // /** // * 本次更新的资源,Map的value是新的配置。 // * @return 更新的资源 // */ // public Map<T, ResConfig> getUpdatedResources() { // return updatedResources; // } // // } // Path: src/test/java/com/github/phantomthief/failover/impl/PriorityFailoverManagerTest.java import static com.github.phantomthief.failover.impl.PriorityGroupManagerTest.countOfEachGroup; import static java.util.Collections.singleton; import static java.util.Collections.singletonMap; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.github.phantomthief.failover.impl.PriorityFailoverBuilder.ResConfig; import com.github.phantomthief.failover.impl.PriorityFailoverManager.UpdateResult; package com.github.phantomthief.failover.impl; /** * @author huangli * Created on 2020-02-02 */ class PriorityFailoverManagerTest { private Object o0 = "o0"; private Object o1 = "o1"; private Object o2 = "o2"; @Test public void testUpdate() { PriorityFailover<Object> failover = PriorityFailover.newBuilder() .addResource(o0, 100, 0, 0, 100) .addResource(o1, 100, 0, 0, 100) .build(); PriorityFailoverManager<Object> manager = new PriorityFailoverManager<>(failover, null); Map<Object, ResConfig> addOrUpdate = new HashMap<>(); addOrUpdate.put(o1, new ResConfig( 10, 5, 1, -1/*illegal but will be ignore*/)); addOrUpdate.put(o2, new ResConfig(10, 5, 1, 7));
UpdateResult<Object> result = manager.update(addOrUpdate, singleton(o0));
PhantomThief/simple-failover-java
src/test/java/com/github/phantomthief/failover/impl/PriorityFailoverManagerTest.java
// Path: src/test/java/com/github/phantomthief/failover/impl/PriorityGroupManagerTest.java // static int[] countOfEachGroup(int groupCount, PriorityGroupManager<?> manager) { // Map<?, Integer> map = manager.getPriorityMap(); // int[] result = new int[groupCount]; // for (Map.Entry<?, Integer> en : map.entrySet()) { // result[en.getValue()]++; // } // return result; // } // // Path: src/main/java/com/github/phantomthief/failover/impl/PriorityFailoverBuilder.java // public static final class ResConfig implements Cloneable { // private final int priority; // private final double maxWeight; // private final double minWeight; // private final double initWeight; // // public ResConfig() { // this(DEFAULT_MAX_WEIGHT); // } // // public ResConfig(double maxWeight) { // this(maxWeight, DEFAULT_MIN_WEIGHT); // } // // public ResConfig(double maxWeight, double minWeight) { // this(maxWeight, minWeight, DEFAULT_PRIORITY); // } // // public ResConfig(double maxWeight, double minWeight, int priority) { // this(maxWeight, minWeight, priority, maxWeight); // } // // public ResConfig(double maxWeight, double minWeight, int priority, double initWeight) { // this.maxWeight = maxWeight; // this.minWeight = minWeight; // this.priority = priority; // this.initWeight = initWeight; // } // // @Override // public ResConfig clone() { // try { // return (ResConfig) super.clone(); // } catch (CloneNotSupportedException e) { // throw new RuntimeException(e); // } // } // // public int getPriority() { // return priority; // } // // public double getMaxWeight() { // return maxWeight; // } // // public double getMinWeight() { // return minWeight; // } // // public double getInitWeight() { // return initWeight; // } // } // // Path: src/main/java/com/github/phantomthief/failover/impl/PriorityFailoverManager.java // public static class UpdateResult<T> { // private Map<T, ResConfig> addedResources = new HashMap<>(); // private Map<T, ResConfig> removedResources = new HashMap<>(); // private Map<T, ResConfig> updatedResources = new HashMap<>(); // // /** // * 本次添加的资源,Map的value是新的配置。 // * @return 更新的资源 // */ // public Map<T, ResConfig> getAddedResources() { // return addedResources; // } // // /** // * 删除的资源,Map的value是旧的配置。 // * @return 更新的资源 // */ // public Map<T, ResConfig> getRemovedResources() { // return removedResources; // } // // /** // * 本次更新的资源,Map的value是新的配置。 // * @return 更新的资源 // */ // public Map<T, ResConfig> getUpdatedResources() { // return updatedResources; // } // // }
import static com.github.phantomthief.failover.impl.PriorityGroupManagerTest.countOfEachGroup; import static java.util.Collections.singleton; import static java.util.Collections.singletonMap; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.github.phantomthief.failover.impl.PriorityFailoverBuilder.ResConfig; import com.github.phantomthief.failover.impl.PriorityFailoverManager.UpdateResult;
.build(); PriorityFailoverManager<Object> manager = new PriorityFailoverManager<>(failover, null); manager.getFailover().fail(manager.getFailover().getOneAvailable()); manager.updateAll(singletonMap(o0, new ResConfig(100, 0, 0, 100))); assertEquals(50, manager.getFailover().getResourcesMap().get(o0).currentWeight); manager.updateAll(singletonMap(o0, new ResConfig(100, 60, 0, 100))); assertEquals(60, manager.getFailover().getResourcesMap().get(o0).currentWeight); manager.updateAll(singletonMap(o0, new ResConfig(10, 0, 0, 100))); assertEquals(6, manager.getFailover().getResourcesMap().get(o0).currentWeight); manager.getFailover().success(manager.getFailover().getOneAvailable()); manager.updateAll(singletonMap(o0, new ResConfig(100, 0, 0, 100))); assertEquals(100, manager.getFailover().getResourcesMap().get(o0).currentWeight); manager.updateAll(singletonMap(o0, new ResConfig(10, 0, 0, 100))); assertEquals(10, manager.getFailover().getResourcesMap().get(o0).currentWeight); } @Test public void testAutoPriority() { PriorityFailoverManager<Object> manager = PriorityFailover.newBuilder() .enableAutoPriority(1) .addResource(o0) .addResource(o1) .buildManager();
// Path: src/test/java/com/github/phantomthief/failover/impl/PriorityGroupManagerTest.java // static int[] countOfEachGroup(int groupCount, PriorityGroupManager<?> manager) { // Map<?, Integer> map = manager.getPriorityMap(); // int[] result = new int[groupCount]; // for (Map.Entry<?, Integer> en : map.entrySet()) { // result[en.getValue()]++; // } // return result; // } // // Path: src/main/java/com/github/phantomthief/failover/impl/PriorityFailoverBuilder.java // public static final class ResConfig implements Cloneable { // private final int priority; // private final double maxWeight; // private final double minWeight; // private final double initWeight; // // public ResConfig() { // this(DEFAULT_MAX_WEIGHT); // } // // public ResConfig(double maxWeight) { // this(maxWeight, DEFAULT_MIN_WEIGHT); // } // // public ResConfig(double maxWeight, double minWeight) { // this(maxWeight, minWeight, DEFAULT_PRIORITY); // } // // public ResConfig(double maxWeight, double minWeight, int priority) { // this(maxWeight, minWeight, priority, maxWeight); // } // // public ResConfig(double maxWeight, double minWeight, int priority, double initWeight) { // this.maxWeight = maxWeight; // this.minWeight = minWeight; // this.priority = priority; // this.initWeight = initWeight; // } // // @Override // public ResConfig clone() { // try { // return (ResConfig) super.clone(); // } catch (CloneNotSupportedException e) { // throw new RuntimeException(e); // } // } // // public int getPriority() { // return priority; // } // // public double getMaxWeight() { // return maxWeight; // } // // public double getMinWeight() { // return minWeight; // } // // public double getInitWeight() { // return initWeight; // } // } // // Path: src/main/java/com/github/phantomthief/failover/impl/PriorityFailoverManager.java // public static class UpdateResult<T> { // private Map<T, ResConfig> addedResources = new HashMap<>(); // private Map<T, ResConfig> removedResources = new HashMap<>(); // private Map<T, ResConfig> updatedResources = new HashMap<>(); // // /** // * 本次添加的资源,Map的value是新的配置。 // * @return 更新的资源 // */ // public Map<T, ResConfig> getAddedResources() { // return addedResources; // } // // /** // * 删除的资源,Map的value是旧的配置。 // * @return 更新的资源 // */ // public Map<T, ResConfig> getRemovedResources() { // return removedResources; // } // // /** // * 本次更新的资源,Map的value是新的配置。 // * @return 更新的资源 // */ // public Map<T, ResConfig> getUpdatedResources() { // return updatedResources; // } // // } // Path: src/test/java/com/github/phantomthief/failover/impl/PriorityFailoverManagerTest.java import static com.github.phantomthief.failover.impl.PriorityGroupManagerTest.countOfEachGroup; import static java.util.Collections.singleton; import static java.util.Collections.singletonMap; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import com.github.phantomthief.failover.impl.PriorityFailoverBuilder.ResConfig; import com.github.phantomthief.failover.impl.PriorityFailoverManager.UpdateResult; .build(); PriorityFailoverManager<Object> manager = new PriorityFailoverManager<>(failover, null); manager.getFailover().fail(manager.getFailover().getOneAvailable()); manager.updateAll(singletonMap(o0, new ResConfig(100, 0, 0, 100))); assertEquals(50, manager.getFailover().getResourcesMap().get(o0).currentWeight); manager.updateAll(singletonMap(o0, new ResConfig(100, 60, 0, 100))); assertEquals(60, manager.getFailover().getResourcesMap().get(o0).currentWeight); manager.updateAll(singletonMap(o0, new ResConfig(10, 0, 0, 100))); assertEquals(6, manager.getFailover().getResourcesMap().get(o0).currentWeight); manager.getFailover().success(manager.getFailover().getOneAvailable()); manager.updateAll(singletonMap(o0, new ResConfig(100, 0, 0, 100))); assertEquals(100, manager.getFailover().getResourcesMap().get(o0).currentWeight); manager.updateAll(singletonMap(o0, new ResConfig(10, 0, 0, 100))); assertEquals(10, manager.getFailover().getResourcesMap().get(o0).currentWeight); } @Test public void testAutoPriority() { PriorityFailoverManager<Object> manager = PriorityFailover.newBuilder() .enableAutoPriority(1) .addResource(o0) .addResource(o1) .buildManager();
int[] resCountOfGroup = countOfEachGroup(2, manager.getGroupManager());
PhantomThief/simple-failover-java
src/test/java/com/github/phantomthief/failover/impl/RecoverableCheckFailoverTest.java
// Path: src/test/java/com/github/phantomthief/failover/WeighTestUtils.java // public static boolean checkRatio(int a, int b, int ratio) { // return between((double) a / b, (double) ratio - OFFSET, (double) ratio + OFFSET); // }
import static com.github.phantomthief.failover.WeighTestUtils.checkRatio; import static com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.function.Predicate; import org.junit.jupiter.api.Test; import com.google.common.collect.HashMultiset; import com.google.common.collect.ImmutableList; import com.google.common.collect.Multiset;
package com.github.phantomthief.failover.impl; /** * @author w.vela * Created on 2019-01-04. */ class RecoverableCheckFailoverTest { @Test void test() { boolean[] checkerSwitcher = { false }; Predicate<String> checker = it -> checkerSwitcher[0]; RecoverableCheckFailover<String> failover = RecoverableCheckFailover .<String> newGenericBuilder().setChecker(checker) // .setFailCount(10) .setFailDuration(100, MILLISECONDS) .setRecoveryCheckDuration(100, MILLISECONDS) .setReturnOriginalWhileAllFailed(false) .build(ImmutableList.of("s1", "s2")); for (int i = 0; i < 10; i++) { failover.fail("s2"); } for (int i = 0; i < 10; i++) { assertEquals("s1", failover.getOneAvailable()); } checkerSwitcher[0] = true; sleepUninterruptibly(100, MILLISECONDS); Multiset<String> result = HashMultiset.create(); for (int i = 0; i < 10000; i++) { result.add(failover.getOneAvailable()); }
// Path: src/test/java/com/github/phantomthief/failover/WeighTestUtils.java // public static boolean checkRatio(int a, int b, int ratio) { // return between((double) a / b, (double) ratio - OFFSET, (double) ratio + OFFSET); // } // Path: src/test/java/com/github/phantomthief/failover/impl/RecoverableCheckFailoverTest.java import static com.github.phantomthief.failover.WeighTestUtils.checkRatio; import static com.google.common.util.concurrent.Uninterruptibles.sleepUninterruptibly; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.function.Predicate; import org.junit.jupiter.api.Test; import com.google.common.collect.HashMultiset; import com.google.common.collect.ImmutableList; import com.google.common.collect.Multiset; package com.github.phantomthief.failover.impl; /** * @author w.vela * Created on 2019-01-04. */ class RecoverableCheckFailoverTest { @Test void test() { boolean[] checkerSwitcher = { false }; Predicate<String> checker = it -> checkerSwitcher[0]; RecoverableCheckFailover<String> failover = RecoverableCheckFailover .<String> newGenericBuilder().setChecker(checker) // .setFailCount(10) .setFailDuration(100, MILLISECONDS) .setRecoveryCheckDuration(100, MILLISECONDS) .setReturnOriginalWhileAllFailed(false) .build(ImmutableList.of("s1", "s2")); for (int i = 0; i < 10; i++) { failover.fail("s2"); } for (int i = 0; i < 10; i++) { assertEquals("s1", failover.getOneAvailable()); } checkerSwitcher[0] = true; sleepUninterruptibly(100, MILLISECONDS); Multiset<String> result = HashMultiset.create(); for (int i = 0; i < 10000; i++) { result.add(failover.getOneAvailable()); }
assertTrue(checkRatio(result.count("s2"), result.count("s1"), 1));
m-szalik/dbpatch
dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/extension/Extension.java
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractPatch.java // public abstract class AbstractPatch implements Serializable { // private static final long serialVersionUID = 4178101927323891639L; // private String name; // private int statementCount = -1; // private File file; // // public enum DbState { // COMMITTED, IN_PROGRESS, NOT_AVAILABLE // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getStatementCount() { // return statementCount; // } // // public void setStatementCount(int statementCount) { // this.statementCount = statementCount; // } // // public File getFile() { // return file; // } // // public void setFile(File file) { // this.file = file; // } // // public abstract void setDbDate(Date dbDate); // // public abstract void setDbState(DbState dbState); // // public abstract Date getDbDate(); // // public abstract DbState getDbState(); // // public abstract boolean canApply(); // // public String toString() { // return super.toString() + "-" + name; // } // // public static String normalizeName(String name) { // String nameLC = name.toLowerCase(); // while (nameLC.endsWith(".sql") || nameLC.endsWith(".undo") || nameLC.endsWith(".rollback")) { // int dot = nameLC.lastIndexOf('.'); // nameLC = nameLC.substring(0, dot); // } // return name.substring(0, nameLC.length()); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/RollbackPatch.java // public class RollbackPatch extends AbstractPatch { // private final Patch patch; // private final File originalPatchFile; // private boolean missing; // // public RollbackPatch(Patch patch) { // super.setName(patch.getName()); // this.originalPatchFile = patch.getFile(); // this.missing = true; // this.patch = patch; // } // // public RollbackPatch(Patch patch, File rollbackFile, int rollbackStatementsCount) { // this(patch); // super.setFile(rollbackFile); // super.setStatementCount(rollbackStatementsCount); // this.missing = false; // } // // // public void setFile(File file) { // throw new AssertionError("DO NOT USE IT! It shouldn't be invoked."); // } // // @Override // public void setDbDate(Date dbDate) { // patch.setDbDate(dbDate); // } // // @Override // public void setDbState(DbState dbState) { // patch.setDbState(dbState); // } // // @Override // public Date getDbDate() { // return patch.getDbDate(); // } // // @Override // public DbState getDbState() { // return patch.getDbState(); // } // // public File getOriginalPatchFile() { // return originalPatchFile; // } // // public boolean isMissing() { // return missing; // } // // // public boolean canApply() { // return !isMissing() && getStatementCount() > 0 && getDbState() == DbState.COMMITTED; // } // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/dialect/PatchExecutionResult.java // public interface PatchExecutionResult { // // /** // * @return false if Patch was executed with errors // */ // boolean isFailure(); // // /** // * @return SQLWarning if any during patch execution // */ // SQLWarning getSqlWarnings(); // // /** // * @return Fatal error during patch execution // */ // SQLException getCause(); // // PatchStatement getPatchStatement(); // // int getDmlCount(); // // DML_TYPE getDmlType(); // }
import org.jsoftware.dbpatch.config.AbstractPatch; import org.jsoftware.dbpatch.config.Patch; import org.jsoftware.dbpatch.config.RollbackPatch; import org.jsoftware.dbpatch.config.dialect.PatchExecutionResult; import org.jsoftware.dbpatch.impl.PatchStatement; import java.sql.Connection; import java.sql.SQLException;
package org.jsoftware.dbpatch.impl.extension; public interface Extension { /** * @param connection connection * Before patching procedure starts */ void beforePatching(Connection connection); /** * @param connection connection * After patching process ends */ void afterPatching(Connection connection); /** * @param connection connection * @param patch patch to apply * Before the patch is executed */ void beforePatch(Connection connection, Patch patch); /** * After the patch is executed * @param connection connection * @param patch patch to apply * @param ex execution exception - null if successful execution * @throws SQLException sql problem */ void afterPatch(Connection connection, Patch patch, Exception ex) throws SQLException; /** * Before patch's statement is executed * @param connection connection * @param patch patch * @param statement sql statement */
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractPatch.java // public abstract class AbstractPatch implements Serializable { // private static final long serialVersionUID = 4178101927323891639L; // private String name; // private int statementCount = -1; // private File file; // // public enum DbState { // COMMITTED, IN_PROGRESS, NOT_AVAILABLE // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getStatementCount() { // return statementCount; // } // // public void setStatementCount(int statementCount) { // this.statementCount = statementCount; // } // // public File getFile() { // return file; // } // // public void setFile(File file) { // this.file = file; // } // // public abstract void setDbDate(Date dbDate); // // public abstract void setDbState(DbState dbState); // // public abstract Date getDbDate(); // // public abstract DbState getDbState(); // // public abstract boolean canApply(); // // public String toString() { // return super.toString() + "-" + name; // } // // public static String normalizeName(String name) { // String nameLC = name.toLowerCase(); // while (nameLC.endsWith(".sql") || nameLC.endsWith(".undo") || nameLC.endsWith(".rollback")) { // int dot = nameLC.lastIndexOf('.'); // nameLC = nameLC.substring(0, dot); // } // return name.substring(0, nameLC.length()); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/RollbackPatch.java // public class RollbackPatch extends AbstractPatch { // private final Patch patch; // private final File originalPatchFile; // private boolean missing; // // public RollbackPatch(Patch patch) { // super.setName(patch.getName()); // this.originalPatchFile = patch.getFile(); // this.missing = true; // this.patch = patch; // } // // public RollbackPatch(Patch patch, File rollbackFile, int rollbackStatementsCount) { // this(patch); // super.setFile(rollbackFile); // super.setStatementCount(rollbackStatementsCount); // this.missing = false; // } // // // public void setFile(File file) { // throw new AssertionError("DO NOT USE IT! It shouldn't be invoked."); // } // // @Override // public void setDbDate(Date dbDate) { // patch.setDbDate(dbDate); // } // // @Override // public void setDbState(DbState dbState) { // patch.setDbState(dbState); // } // // @Override // public Date getDbDate() { // return patch.getDbDate(); // } // // @Override // public DbState getDbState() { // return patch.getDbState(); // } // // public File getOriginalPatchFile() { // return originalPatchFile; // } // // public boolean isMissing() { // return missing; // } // // // public boolean canApply() { // return !isMissing() && getStatementCount() > 0 && getDbState() == DbState.COMMITTED; // } // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/dialect/PatchExecutionResult.java // public interface PatchExecutionResult { // // /** // * @return false if Patch was executed with errors // */ // boolean isFailure(); // // /** // * @return SQLWarning if any during patch execution // */ // SQLWarning getSqlWarnings(); // // /** // * @return Fatal error during patch execution // */ // SQLException getCause(); // // PatchStatement getPatchStatement(); // // int getDmlCount(); // // DML_TYPE getDmlType(); // } // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/extension/Extension.java import org.jsoftware.dbpatch.config.AbstractPatch; import org.jsoftware.dbpatch.config.Patch; import org.jsoftware.dbpatch.config.RollbackPatch; import org.jsoftware.dbpatch.config.dialect.PatchExecutionResult; import org.jsoftware.dbpatch.impl.PatchStatement; import java.sql.Connection; import java.sql.SQLException; package org.jsoftware.dbpatch.impl.extension; public interface Extension { /** * @param connection connection * Before patching procedure starts */ void beforePatching(Connection connection); /** * @param connection connection * After patching process ends */ void afterPatching(Connection connection); /** * @param connection connection * @param patch patch to apply * Before the patch is executed */ void beforePatch(Connection connection, Patch patch); /** * After the patch is executed * @param connection connection * @param patch patch to apply * @param ex execution exception - null if successful execution * @throws SQLException sql problem */ void afterPatch(Connection connection, Patch patch, Exception ex) throws SQLException; /** * Before patch's statement is executed * @param connection connection * @param patch patch * @param statement sql statement */
void beforePatchStatement(Connection connection, AbstractPatch patch, PatchStatement statement);
m-szalik/dbpatch
dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/extension/Extension.java
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractPatch.java // public abstract class AbstractPatch implements Serializable { // private static final long serialVersionUID = 4178101927323891639L; // private String name; // private int statementCount = -1; // private File file; // // public enum DbState { // COMMITTED, IN_PROGRESS, NOT_AVAILABLE // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getStatementCount() { // return statementCount; // } // // public void setStatementCount(int statementCount) { // this.statementCount = statementCount; // } // // public File getFile() { // return file; // } // // public void setFile(File file) { // this.file = file; // } // // public abstract void setDbDate(Date dbDate); // // public abstract void setDbState(DbState dbState); // // public abstract Date getDbDate(); // // public abstract DbState getDbState(); // // public abstract boolean canApply(); // // public String toString() { // return super.toString() + "-" + name; // } // // public static String normalizeName(String name) { // String nameLC = name.toLowerCase(); // while (nameLC.endsWith(".sql") || nameLC.endsWith(".undo") || nameLC.endsWith(".rollback")) { // int dot = nameLC.lastIndexOf('.'); // nameLC = nameLC.substring(0, dot); // } // return name.substring(0, nameLC.length()); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/RollbackPatch.java // public class RollbackPatch extends AbstractPatch { // private final Patch patch; // private final File originalPatchFile; // private boolean missing; // // public RollbackPatch(Patch patch) { // super.setName(patch.getName()); // this.originalPatchFile = patch.getFile(); // this.missing = true; // this.patch = patch; // } // // public RollbackPatch(Patch patch, File rollbackFile, int rollbackStatementsCount) { // this(patch); // super.setFile(rollbackFile); // super.setStatementCount(rollbackStatementsCount); // this.missing = false; // } // // // public void setFile(File file) { // throw new AssertionError("DO NOT USE IT! It shouldn't be invoked."); // } // // @Override // public void setDbDate(Date dbDate) { // patch.setDbDate(dbDate); // } // // @Override // public void setDbState(DbState dbState) { // patch.setDbState(dbState); // } // // @Override // public Date getDbDate() { // return patch.getDbDate(); // } // // @Override // public DbState getDbState() { // return patch.getDbState(); // } // // public File getOriginalPatchFile() { // return originalPatchFile; // } // // public boolean isMissing() { // return missing; // } // // // public boolean canApply() { // return !isMissing() && getStatementCount() > 0 && getDbState() == DbState.COMMITTED; // } // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/dialect/PatchExecutionResult.java // public interface PatchExecutionResult { // // /** // * @return false if Patch was executed with errors // */ // boolean isFailure(); // // /** // * @return SQLWarning if any during patch execution // */ // SQLWarning getSqlWarnings(); // // /** // * @return Fatal error during patch execution // */ // SQLException getCause(); // // PatchStatement getPatchStatement(); // // int getDmlCount(); // // DML_TYPE getDmlType(); // }
import org.jsoftware.dbpatch.config.AbstractPatch; import org.jsoftware.dbpatch.config.Patch; import org.jsoftware.dbpatch.config.RollbackPatch; import org.jsoftware.dbpatch.config.dialect.PatchExecutionResult; import org.jsoftware.dbpatch.impl.PatchStatement; import java.sql.Connection; import java.sql.SQLException;
package org.jsoftware.dbpatch.impl.extension; public interface Extension { /** * @param connection connection * Before patching procedure starts */ void beforePatching(Connection connection); /** * @param connection connection * After patching process ends */ void afterPatching(Connection connection); /** * @param connection connection * @param patch patch to apply * Before the patch is executed */ void beforePatch(Connection connection, Patch patch); /** * After the patch is executed * @param connection connection * @param patch patch to apply * @param ex execution exception - null if successful execution * @throws SQLException sql problem */ void afterPatch(Connection connection, Patch patch, Exception ex) throws SQLException; /** * Before patch's statement is executed * @param connection connection * @param patch patch * @param statement sql statement */ void beforePatchStatement(Connection connection, AbstractPatch patch, PatchStatement statement); /** * After patch's statement is executed * @param connection connection * @param patch patch * @param result patching result */
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractPatch.java // public abstract class AbstractPatch implements Serializable { // private static final long serialVersionUID = 4178101927323891639L; // private String name; // private int statementCount = -1; // private File file; // // public enum DbState { // COMMITTED, IN_PROGRESS, NOT_AVAILABLE // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getStatementCount() { // return statementCount; // } // // public void setStatementCount(int statementCount) { // this.statementCount = statementCount; // } // // public File getFile() { // return file; // } // // public void setFile(File file) { // this.file = file; // } // // public abstract void setDbDate(Date dbDate); // // public abstract void setDbState(DbState dbState); // // public abstract Date getDbDate(); // // public abstract DbState getDbState(); // // public abstract boolean canApply(); // // public String toString() { // return super.toString() + "-" + name; // } // // public static String normalizeName(String name) { // String nameLC = name.toLowerCase(); // while (nameLC.endsWith(".sql") || nameLC.endsWith(".undo") || nameLC.endsWith(".rollback")) { // int dot = nameLC.lastIndexOf('.'); // nameLC = nameLC.substring(0, dot); // } // return name.substring(0, nameLC.length()); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/RollbackPatch.java // public class RollbackPatch extends AbstractPatch { // private final Patch patch; // private final File originalPatchFile; // private boolean missing; // // public RollbackPatch(Patch patch) { // super.setName(patch.getName()); // this.originalPatchFile = patch.getFile(); // this.missing = true; // this.patch = patch; // } // // public RollbackPatch(Patch patch, File rollbackFile, int rollbackStatementsCount) { // this(patch); // super.setFile(rollbackFile); // super.setStatementCount(rollbackStatementsCount); // this.missing = false; // } // // // public void setFile(File file) { // throw new AssertionError("DO NOT USE IT! It shouldn't be invoked."); // } // // @Override // public void setDbDate(Date dbDate) { // patch.setDbDate(dbDate); // } // // @Override // public void setDbState(DbState dbState) { // patch.setDbState(dbState); // } // // @Override // public Date getDbDate() { // return patch.getDbDate(); // } // // @Override // public DbState getDbState() { // return patch.getDbState(); // } // // public File getOriginalPatchFile() { // return originalPatchFile; // } // // public boolean isMissing() { // return missing; // } // // // public boolean canApply() { // return !isMissing() && getStatementCount() > 0 && getDbState() == DbState.COMMITTED; // } // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/dialect/PatchExecutionResult.java // public interface PatchExecutionResult { // // /** // * @return false if Patch was executed with errors // */ // boolean isFailure(); // // /** // * @return SQLWarning if any during patch execution // */ // SQLWarning getSqlWarnings(); // // /** // * @return Fatal error during patch execution // */ // SQLException getCause(); // // PatchStatement getPatchStatement(); // // int getDmlCount(); // // DML_TYPE getDmlType(); // } // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/extension/Extension.java import org.jsoftware.dbpatch.config.AbstractPatch; import org.jsoftware.dbpatch.config.Patch; import org.jsoftware.dbpatch.config.RollbackPatch; import org.jsoftware.dbpatch.config.dialect.PatchExecutionResult; import org.jsoftware.dbpatch.impl.PatchStatement; import java.sql.Connection; import java.sql.SQLException; package org.jsoftware.dbpatch.impl.extension; public interface Extension { /** * @param connection connection * Before patching procedure starts */ void beforePatching(Connection connection); /** * @param connection connection * After patching process ends */ void afterPatching(Connection connection); /** * @param connection connection * @param patch patch to apply * Before the patch is executed */ void beforePatch(Connection connection, Patch patch); /** * After the patch is executed * @param connection connection * @param patch patch to apply * @param ex execution exception - null if successful execution * @throws SQLException sql problem */ void afterPatch(Connection connection, Patch patch, Exception ex) throws SQLException; /** * Before patch's statement is executed * @param connection connection * @param patch patch * @param statement sql statement */ void beforePatchStatement(Connection connection, AbstractPatch patch, PatchStatement statement); /** * After patch's statement is executed * @param connection connection * @param patch patch * @param result patching result */
void afterPatchStatement(Connection connection, AbstractPatch patch, PatchExecutionResult result);
m-szalik/dbpatch
dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/extension/Extension.java
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractPatch.java // public abstract class AbstractPatch implements Serializable { // private static final long serialVersionUID = 4178101927323891639L; // private String name; // private int statementCount = -1; // private File file; // // public enum DbState { // COMMITTED, IN_PROGRESS, NOT_AVAILABLE // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getStatementCount() { // return statementCount; // } // // public void setStatementCount(int statementCount) { // this.statementCount = statementCount; // } // // public File getFile() { // return file; // } // // public void setFile(File file) { // this.file = file; // } // // public abstract void setDbDate(Date dbDate); // // public abstract void setDbState(DbState dbState); // // public abstract Date getDbDate(); // // public abstract DbState getDbState(); // // public abstract boolean canApply(); // // public String toString() { // return super.toString() + "-" + name; // } // // public static String normalizeName(String name) { // String nameLC = name.toLowerCase(); // while (nameLC.endsWith(".sql") || nameLC.endsWith(".undo") || nameLC.endsWith(".rollback")) { // int dot = nameLC.lastIndexOf('.'); // nameLC = nameLC.substring(0, dot); // } // return name.substring(0, nameLC.length()); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/RollbackPatch.java // public class RollbackPatch extends AbstractPatch { // private final Patch patch; // private final File originalPatchFile; // private boolean missing; // // public RollbackPatch(Patch patch) { // super.setName(patch.getName()); // this.originalPatchFile = patch.getFile(); // this.missing = true; // this.patch = patch; // } // // public RollbackPatch(Patch patch, File rollbackFile, int rollbackStatementsCount) { // this(patch); // super.setFile(rollbackFile); // super.setStatementCount(rollbackStatementsCount); // this.missing = false; // } // // // public void setFile(File file) { // throw new AssertionError("DO NOT USE IT! It shouldn't be invoked."); // } // // @Override // public void setDbDate(Date dbDate) { // patch.setDbDate(dbDate); // } // // @Override // public void setDbState(DbState dbState) { // patch.setDbState(dbState); // } // // @Override // public Date getDbDate() { // return patch.getDbDate(); // } // // @Override // public DbState getDbState() { // return patch.getDbState(); // } // // public File getOriginalPatchFile() { // return originalPatchFile; // } // // public boolean isMissing() { // return missing; // } // // // public boolean canApply() { // return !isMissing() && getStatementCount() > 0 && getDbState() == DbState.COMMITTED; // } // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/dialect/PatchExecutionResult.java // public interface PatchExecutionResult { // // /** // * @return false if Patch was executed with errors // */ // boolean isFailure(); // // /** // * @return SQLWarning if any during patch execution // */ // SQLWarning getSqlWarnings(); // // /** // * @return Fatal error during patch execution // */ // SQLException getCause(); // // PatchStatement getPatchStatement(); // // int getDmlCount(); // // DML_TYPE getDmlType(); // }
import org.jsoftware.dbpatch.config.AbstractPatch; import org.jsoftware.dbpatch.config.Patch; import org.jsoftware.dbpatch.config.RollbackPatch; import org.jsoftware.dbpatch.config.dialect.PatchExecutionResult; import org.jsoftware.dbpatch.impl.PatchStatement; import java.sql.Connection; import java.sql.SQLException;
package org.jsoftware.dbpatch.impl.extension; public interface Extension { /** * @param connection connection * Before patching procedure starts */ void beforePatching(Connection connection); /** * @param connection connection * After patching process ends */ void afterPatching(Connection connection); /** * @param connection connection * @param patch patch to apply * Before the patch is executed */ void beforePatch(Connection connection, Patch patch); /** * After the patch is executed * @param connection connection * @param patch patch to apply * @param ex execution exception - null if successful execution * @throws SQLException sql problem */ void afterPatch(Connection connection, Patch patch, Exception ex) throws SQLException; /** * Before patch's statement is executed * @param connection connection * @param patch patch * @param statement sql statement */ void beforePatchStatement(Connection connection, AbstractPatch patch, PatchStatement statement); /** * After patch's statement is executed * @param connection connection * @param patch patch * @param result patching result */ void afterPatchStatement(Connection connection, AbstractPatch patch, PatchExecutionResult result); /** * Before the patch rollback is executed * @param connection connection * @param patch patch to rollback */
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractPatch.java // public abstract class AbstractPatch implements Serializable { // private static final long serialVersionUID = 4178101927323891639L; // private String name; // private int statementCount = -1; // private File file; // // public enum DbState { // COMMITTED, IN_PROGRESS, NOT_AVAILABLE // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getStatementCount() { // return statementCount; // } // // public void setStatementCount(int statementCount) { // this.statementCount = statementCount; // } // // public File getFile() { // return file; // } // // public void setFile(File file) { // this.file = file; // } // // public abstract void setDbDate(Date dbDate); // // public abstract void setDbState(DbState dbState); // // public abstract Date getDbDate(); // // public abstract DbState getDbState(); // // public abstract boolean canApply(); // // public String toString() { // return super.toString() + "-" + name; // } // // public static String normalizeName(String name) { // String nameLC = name.toLowerCase(); // while (nameLC.endsWith(".sql") || nameLC.endsWith(".undo") || nameLC.endsWith(".rollback")) { // int dot = nameLC.lastIndexOf('.'); // nameLC = nameLC.substring(0, dot); // } // return name.substring(0, nameLC.length()); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/RollbackPatch.java // public class RollbackPatch extends AbstractPatch { // private final Patch patch; // private final File originalPatchFile; // private boolean missing; // // public RollbackPatch(Patch patch) { // super.setName(patch.getName()); // this.originalPatchFile = patch.getFile(); // this.missing = true; // this.patch = patch; // } // // public RollbackPatch(Patch patch, File rollbackFile, int rollbackStatementsCount) { // this(patch); // super.setFile(rollbackFile); // super.setStatementCount(rollbackStatementsCount); // this.missing = false; // } // // // public void setFile(File file) { // throw new AssertionError("DO NOT USE IT! It shouldn't be invoked."); // } // // @Override // public void setDbDate(Date dbDate) { // patch.setDbDate(dbDate); // } // // @Override // public void setDbState(DbState dbState) { // patch.setDbState(dbState); // } // // @Override // public Date getDbDate() { // return patch.getDbDate(); // } // // @Override // public DbState getDbState() { // return patch.getDbState(); // } // // public File getOriginalPatchFile() { // return originalPatchFile; // } // // public boolean isMissing() { // return missing; // } // // // public boolean canApply() { // return !isMissing() && getStatementCount() > 0 && getDbState() == DbState.COMMITTED; // } // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/dialect/PatchExecutionResult.java // public interface PatchExecutionResult { // // /** // * @return false if Patch was executed with errors // */ // boolean isFailure(); // // /** // * @return SQLWarning if any during patch execution // */ // SQLWarning getSqlWarnings(); // // /** // * @return Fatal error during patch execution // */ // SQLException getCause(); // // PatchStatement getPatchStatement(); // // int getDmlCount(); // // DML_TYPE getDmlType(); // } // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/extension/Extension.java import org.jsoftware.dbpatch.config.AbstractPatch; import org.jsoftware.dbpatch.config.Patch; import org.jsoftware.dbpatch.config.RollbackPatch; import org.jsoftware.dbpatch.config.dialect.PatchExecutionResult; import org.jsoftware.dbpatch.impl.PatchStatement; import java.sql.Connection; import java.sql.SQLException; package org.jsoftware.dbpatch.impl.extension; public interface Extension { /** * @param connection connection * Before patching procedure starts */ void beforePatching(Connection connection); /** * @param connection connection * After patching process ends */ void afterPatching(Connection connection); /** * @param connection connection * @param patch patch to apply * Before the patch is executed */ void beforePatch(Connection connection, Patch patch); /** * After the patch is executed * @param connection connection * @param patch patch to apply * @param ex execution exception - null if successful execution * @throws SQLException sql problem */ void afterPatch(Connection connection, Patch patch, Exception ex) throws SQLException; /** * Before patch's statement is executed * @param connection connection * @param patch patch * @param statement sql statement */ void beforePatchStatement(Connection connection, AbstractPatch patch, PatchStatement statement); /** * After patch's statement is executed * @param connection connection * @param patch patch * @param result patching result */ void afterPatchStatement(Connection connection, AbstractPatch patch, PatchExecutionResult result); /** * Before the patch rollback is executed * @param connection connection * @param patch patch to rollback */
void beforeRollbackPatch(Connection connection, RollbackPatch patch);
m-szalik/dbpatch
dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/SimplePatchScanner.java
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractPatch.java // public abstract class AbstractPatch implements Serializable { // private static final long serialVersionUID = 4178101927323891639L; // private String name; // private int statementCount = -1; // private File file; // // public enum DbState { // COMMITTED, IN_PROGRESS, NOT_AVAILABLE // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getStatementCount() { // return statementCount; // } // // public void setStatementCount(int statementCount) { // this.statementCount = statementCount; // } // // public File getFile() { // return file; // } // // public void setFile(File file) { // this.file = file; // } // // public abstract void setDbDate(Date dbDate); // // public abstract void setDbState(DbState dbState); // // public abstract Date getDbDate(); // // public abstract DbState getDbState(); // // public abstract boolean canApply(); // // public String toString() { // return super.toString() + "-" + name; // } // // public static String normalizeName(String name) { // String nameLC = name.toLowerCase(); // while (nameLC.endsWith(".sql") || nameLC.endsWith(".undo") || nameLC.endsWith(".rollback")) { // int dot = nameLC.lastIndexOf('.'); // nameLC = nameLC.substring(0, dot); // } // return name.substring(0, nameLC.length()); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/PatchScanner.java // public interface PatchScanner extends Serializable { // // /** // * @param directory base dir // * @param paths to scan (add directory if not absolute) // * @return list of found patches // * @throws DuplicatePatchNameException when duplicated patch names were found // * @throws IOException io problem // */ // List<Patch> scan(File directory, String[] paths) throws DuplicatePatchNameException, IOException; // // /** // * @param patch rollbacks for this patch // * @param directory base dir // * @param paths to scan (add directory if not absolute) // * @return null if no file was found // * @throws DuplicatePatchNameException when duplicated patch names were found // * @throws IOException io problem // */ // File findRollbackFile(File directory, String[] paths, Patch patch) throws DuplicatePatchNameException, IOException; // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/log/Log.java // public interface Log { // // void trace(String msg, Throwable e); // // void debug(String msg); // // void info(String msg); // // void warn(String msg); // // void fatal(String msg); // // void warn(String msg, Throwable e); // // void fatal(String msg, Throwable e); // }
import org.apache.commons.io.FilenameUtils; import org.jsoftware.dbpatch.config.AbstractPatch; import org.jsoftware.dbpatch.config.Patch; import org.jsoftware.dbpatch.config.PatchScanner; import org.jsoftware.dbpatch.log.Log; import org.jsoftware.dbpatch.log.LogFactory; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.LinkedList; import java.util.List;
package org.jsoftware.dbpatch.impl; /** * Abstract directory scanner that looks for patch files. */ public abstract class SimplePatchScanner implements PatchScanner { private final Log log = LogFactory.getInstance(); public List<Patch> scan(File baseDir, String[] paths) throws DuplicatePatchNameException, IOException { List<DirMask> dirMasks = parsePatchDirs(baseDir, paths); LinkedList<Patch> list = new LinkedList<Patch>(); for (DirMask dm : dirMasks) { log.debug("Scan for patches " + dm.getDir().getAbsolutePath() + " with " + dm.getMask()); LinkedList<Patch> dirList = new LinkedList<Patch>(); notADirectoryCheck(dm.getDir()); File[] fList = dm.getDir().listFiles(new WildcardMaskFileFilter(dm.getMask())); if (fList != null) { for (File f : fList) { Patch p = new Patch(); p.setFile(f);
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractPatch.java // public abstract class AbstractPatch implements Serializable { // private static final long serialVersionUID = 4178101927323891639L; // private String name; // private int statementCount = -1; // private File file; // // public enum DbState { // COMMITTED, IN_PROGRESS, NOT_AVAILABLE // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getStatementCount() { // return statementCount; // } // // public void setStatementCount(int statementCount) { // this.statementCount = statementCount; // } // // public File getFile() { // return file; // } // // public void setFile(File file) { // this.file = file; // } // // public abstract void setDbDate(Date dbDate); // // public abstract void setDbState(DbState dbState); // // public abstract Date getDbDate(); // // public abstract DbState getDbState(); // // public abstract boolean canApply(); // // public String toString() { // return super.toString() + "-" + name; // } // // public static String normalizeName(String name) { // String nameLC = name.toLowerCase(); // while (nameLC.endsWith(".sql") || nameLC.endsWith(".undo") || nameLC.endsWith(".rollback")) { // int dot = nameLC.lastIndexOf('.'); // nameLC = nameLC.substring(0, dot); // } // return name.substring(0, nameLC.length()); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/PatchScanner.java // public interface PatchScanner extends Serializable { // // /** // * @param directory base dir // * @param paths to scan (add directory if not absolute) // * @return list of found patches // * @throws DuplicatePatchNameException when duplicated patch names were found // * @throws IOException io problem // */ // List<Patch> scan(File directory, String[] paths) throws DuplicatePatchNameException, IOException; // // /** // * @param patch rollbacks for this patch // * @param directory base dir // * @param paths to scan (add directory if not absolute) // * @return null if no file was found // * @throws DuplicatePatchNameException when duplicated patch names were found // * @throws IOException io problem // */ // File findRollbackFile(File directory, String[] paths, Patch patch) throws DuplicatePatchNameException, IOException; // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/log/Log.java // public interface Log { // // void trace(String msg, Throwable e); // // void debug(String msg); // // void info(String msg); // // void warn(String msg); // // void fatal(String msg); // // void warn(String msg, Throwable e); // // void fatal(String msg, Throwable e); // } // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/SimplePatchScanner.java import org.apache.commons.io.FilenameUtils; import org.jsoftware.dbpatch.config.AbstractPatch; import org.jsoftware.dbpatch.config.Patch; import org.jsoftware.dbpatch.config.PatchScanner; import org.jsoftware.dbpatch.log.Log; import org.jsoftware.dbpatch.log.LogFactory; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.LinkedList; import java.util.List; package org.jsoftware.dbpatch.impl; /** * Abstract directory scanner that looks for patch files. */ public abstract class SimplePatchScanner implements PatchScanner { private final Log log = LogFactory.getInstance(); public List<Patch> scan(File baseDir, String[] paths) throws DuplicatePatchNameException, IOException { List<DirMask> dirMasks = parsePatchDirs(baseDir, paths); LinkedList<Patch> list = new LinkedList<Patch>(); for (DirMask dm : dirMasks) { log.debug("Scan for patches " + dm.getDir().getAbsolutePath() + " with " + dm.getMask()); LinkedList<Patch> dirList = new LinkedList<Patch>(); notADirectoryCheck(dm.getDir()); File[] fList = dm.getDir().listFiles(new WildcardMaskFileFilter(dm.getMask())); if (fList != null) { for (File f : fList) { Patch p = new Patch(); p.setFile(f);
p.setName(AbstractPatch.normalizeName(f.getName()));
m-szalik/dbpatch
dbpatch-core/src/test/java/org/jsoftware/dbpatch/command/RollbackListCommandTest.java
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/RollbackPatch.java // public class RollbackPatch extends AbstractPatch { // private final Patch patch; // private final File originalPatchFile; // private boolean missing; // // public RollbackPatch(Patch patch) { // super.setName(patch.getName()); // this.originalPatchFile = patch.getFile(); // this.missing = true; // this.patch = patch; // } // // public RollbackPatch(Patch patch, File rollbackFile, int rollbackStatementsCount) { // this(patch); // super.setFile(rollbackFile); // super.setStatementCount(rollbackStatementsCount); // this.missing = false; // } // // // public void setFile(File file) { // throw new AssertionError("DO NOT USE IT! It shouldn't be invoked."); // } // // @Override // public void setDbDate(Date dbDate) { // patch.setDbDate(dbDate); // } // // @Override // public void setDbState(DbState dbState) { // patch.setDbState(dbState); // } // // @Override // public Date getDbDate() { // return patch.getDbDate(); // } // // @Override // public DbState getDbState() { // return patch.getDbState(); // } // // public File getOriginalPatchFile() { // return originalPatchFile; // } // // public boolean isMissing() { // return missing; // } // // // public boolean canApply() { // return !isMissing() && getStatementCount() > 0 && getDbState() == DbState.COMMITTED; // } // }
import org.jsoftware.dbpatch.config.Patch; import org.jsoftware.dbpatch.config.RollbackPatch; import org.junit.Assert; import org.junit.Test; import java.util.LinkedList; import java.util.List;
package org.jsoftware.dbpatch.command; public class RollbackListCommandTest extends AbstractDbCommandTest { @Test public void testRollbackListCommand() throws Exception { RollbackListCommand command = prepareCommand(RollbackListCommand.class); List<Patch> patchList = new LinkedList<Patch>();
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/RollbackPatch.java // public class RollbackPatch extends AbstractPatch { // private final Patch patch; // private final File originalPatchFile; // private boolean missing; // // public RollbackPatch(Patch patch) { // super.setName(patch.getName()); // this.originalPatchFile = patch.getFile(); // this.missing = true; // this.patch = patch; // } // // public RollbackPatch(Patch patch, File rollbackFile, int rollbackStatementsCount) { // this(patch); // super.setFile(rollbackFile); // super.setStatementCount(rollbackStatementsCount); // this.missing = false; // } // // // public void setFile(File file) { // throw new AssertionError("DO NOT USE IT! It shouldn't be invoked."); // } // // @Override // public void setDbDate(Date dbDate) { // patch.setDbDate(dbDate); // } // // @Override // public void setDbState(DbState dbState) { // patch.setDbState(dbState); // } // // @Override // public Date getDbDate() { // return patch.getDbDate(); // } // // @Override // public DbState getDbState() { // return patch.getDbState(); // } // // public File getOriginalPatchFile() { // return originalPatchFile; // } // // public boolean isMissing() { // return missing; // } // // // public boolean canApply() { // return !isMissing() && getStatementCount() > 0 && getDbState() == DbState.COMMITTED; // } // } // Path: dbpatch-core/src/test/java/org/jsoftware/dbpatch/command/RollbackListCommandTest.java import org.jsoftware.dbpatch.config.Patch; import org.jsoftware.dbpatch.config.RollbackPatch; import org.junit.Assert; import org.junit.Test; import java.util.LinkedList; import java.util.List; package org.jsoftware.dbpatch.command; public class RollbackListCommandTest extends AbstractDbCommandTest { @Test public void testRollbackListCommand() throws Exception { RollbackListCommand command = prepareCommand(RollbackListCommand.class); List<Patch> patchList = new LinkedList<Patch>();
List<RollbackPatch> rollbackPatchList;
m-szalik/dbpatch
dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/SkipErrorsCommand.java
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/EnvSettings.java // public class EnvSettings { // private final String prefix; // // private EnvSettings(String prefix) { // this.prefix = prefix; // } // // public String getDbPatchFile() { // return prefix + "dbpatch.file"; // } // // public String getDbPatchConfiguration() { // return prefix + "dbpatch.configuration"; // } // // public String getDbPatchStop() { // return prefix + "dbpatch.stop"; // } // // public String getDbPatchSingle() { // return prefix + "dbpatch.single"; // } // // public String getLogLevel() { // return prefix + "dbpatch.logLevel"; // } // // public static EnvSettings standalone() { // return new EnvSettings(""); // } // // public static EnvSettings maven() { // return new EnvSettings("maven."); // } // // public static EnvSettings gradle() { // return new EnvSettings("gradle."); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/CloseUtil.java // public class CloseUtil { // // private CloseUtil() { // } // // public static void close(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Statement statement) { // try { // if (statement != null) { // statement.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Connection conn) { // try { // if (conn != null) { // conn.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(ResultSet rs) { // try { // if (rs != null) { // rs.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // }
import org.jsoftware.dbpatch.config.EnvSettings; import org.jsoftware.dbpatch.impl.CloseUtil; import java.sql.*;
package org.jsoftware.dbpatch.command; /** * Command: Mark patches &quot;in progress&quot; as committed. * * @author szalik */ public class SkipErrorsCommand extends AbstractSingleConfDbPatchCommand { public SkipErrorsCommand(EnvSettings envSettings) { super(envSettings); } protected void executeInternal() throws Exception { Connection connection = manager.getConnection(); Statement statement = null; ResultSet rs = null; PreparedStatement ps = null; try { statement = connection.createStatement(); rs = statement.executeQuery("SELECT patch_name FROM " + manager.getTableName() + " WHERE patch_db_date IS NULL"); ps = connection.prepareStatement("UPDATE " + manager.getTableName() + " SET patch_db_date=? WHERE patch_name=?"); ps.setDate(1, new Date(0)); while (rs.next()) { ps.setString(2, rs.getString(1)); ps.execute(); log.info("Mark to skip " + rs.getString(1)); } connection.commit(); } finally {
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/EnvSettings.java // public class EnvSettings { // private final String prefix; // // private EnvSettings(String prefix) { // this.prefix = prefix; // } // // public String getDbPatchFile() { // return prefix + "dbpatch.file"; // } // // public String getDbPatchConfiguration() { // return prefix + "dbpatch.configuration"; // } // // public String getDbPatchStop() { // return prefix + "dbpatch.stop"; // } // // public String getDbPatchSingle() { // return prefix + "dbpatch.single"; // } // // public String getLogLevel() { // return prefix + "dbpatch.logLevel"; // } // // public static EnvSettings standalone() { // return new EnvSettings(""); // } // // public static EnvSettings maven() { // return new EnvSettings("maven."); // } // // public static EnvSettings gradle() { // return new EnvSettings("gradle."); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/CloseUtil.java // public class CloseUtil { // // private CloseUtil() { // } // // public static void close(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Statement statement) { // try { // if (statement != null) { // statement.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Connection conn) { // try { // if (conn != null) { // conn.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(ResultSet rs) { // try { // if (rs != null) { // rs.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // } // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/SkipErrorsCommand.java import org.jsoftware.dbpatch.config.EnvSettings; import org.jsoftware.dbpatch.impl.CloseUtil; import java.sql.*; package org.jsoftware.dbpatch.command; /** * Command: Mark patches &quot;in progress&quot; as committed. * * @author szalik */ public class SkipErrorsCommand extends AbstractSingleConfDbPatchCommand { public SkipErrorsCommand(EnvSettings envSettings) { super(envSettings); } protected void executeInternal() throws Exception { Connection connection = manager.getConnection(); Statement statement = null; ResultSet rs = null; PreparedStatement ps = null; try { statement = connection.createStatement(); rs = statement.executeQuery("SELECT patch_name FROM " + manager.getTableName() + " WHERE patch_db_date IS NULL"); ps = connection.prepareStatement("UPDATE " + manager.getTableName() + " SET patch_db_date=? WHERE patch_name=?"); ps.setDate(1, new Date(0)); while (rs.next()) { ps.setString(2, rs.getString(1)); ps.execute(); log.info("Mark to skip " + rs.getString(1)); } connection.commit(); } finally {
CloseUtil.close(statement);
m-szalik/dbpatch
dbpatch-maven-plugin/src/main/java/org/jsoftware/dbpatch/maven/ListMojo.java
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/ListCommand.java // public class ListCommand extends AbstractListCommand<Patch> { // // public ListCommand(EnvSettings envSettings) { // super(envSettings); // } // // // protected List<Patch> generateList(List<Patch> inList) throws IOException { // ApplyStrategy strategy = configurationEntry.getApplyStarters(); // log.debug("Apply strategy is " + strategy.getClass().getSimpleName() + ", configurationId:" + configurationEntry.getId()); // List<Patch> patchesToApply = strategy.filter(manager.getConnection(), inList); // StringBuilder sb = new StringBuilder("Patch list:\n"); // for (Patch p : inList) { // getConfigurationEntry().getPatchParser().parse(p, getConfigurationEntry()); // sb.append('\t'); // if (p.getDbState() == AbstractPatch.DbState.COMMITTED) { // sb.append('*'); // } // if (p.getDbState() == AbstractPatch.DbState.IN_PROGRESS) { // sb.append('P'); // } // if (p.getDbState() == AbstractPatch.DbState.NOT_AVAILABLE) { // if (patchesToApply.contains(p)) { // sb.append('+'); // } else { // sb.append('-'); // } // } // sb.append(' ').append(p.getName()); // for (int a = p.getName().length(); a < SPACES; a++) { // sb.append(' '); // } // sb.append(" statements:").append(p.getStatementCount()); // sb.append('\n'); // } // log.info(sb.toString().trim()); // log.info("Patches to apply: " + patchesToApply.size() + " using configuration:" + configurationEntry.getId()); // return patchesToApply; // } // // // // protected void executeInternal() throws Exception { // getList(); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/EnvSettings.java // public class EnvSettings { // private final String prefix; // // private EnvSettings(String prefix) { // this.prefix = prefix; // } // // public String getDbPatchFile() { // return prefix + "dbpatch.file"; // } // // public String getDbPatchConfiguration() { // return prefix + "dbpatch.configuration"; // } // // public String getDbPatchStop() { // return prefix + "dbpatch.stop"; // } // // public String getDbPatchSingle() { // return prefix + "dbpatch.single"; // } // // public String getLogLevel() { // return prefix + "dbpatch.logLevel"; // } // // public static EnvSettings standalone() { // return new EnvSettings(""); // } // // public static EnvSettings maven() { // return new EnvSettings("maven."); // } // // public static EnvSettings gradle() { // return new EnvSettings("gradle."); // } // // }
import org.jsoftware.dbpatch.command.ListCommand; import org.jsoftware.dbpatch.config.EnvSettings;
package org.jsoftware.dbpatch.maven; /** * Show list of patches * * @author szalik * @goal list */ public class ListMojo extends CommandSingleConfMojoAdapter<ListCommand> { protected ListMojo() {
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/ListCommand.java // public class ListCommand extends AbstractListCommand<Patch> { // // public ListCommand(EnvSettings envSettings) { // super(envSettings); // } // // // protected List<Patch> generateList(List<Patch> inList) throws IOException { // ApplyStrategy strategy = configurationEntry.getApplyStarters(); // log.debug("Apply strategy is " + strategy.getClass().getSimpleName() + ", configurationId:" + configurationEntry.getId()); // List<Patch> patchesToApply = strategy.filter(manager.getConnection(), inList); // StringBuilder sb = new StringBuilder("Patch list:\n"); // for (Patch p : inList) { // getConfigurationEntry().getPatchParser().parse(p, getConfigurationEntry()); // sb.append('\t'); // if (p.getDbState() == AbstractPatch.DbState.COMMITTED) { // sb.append('*'); // } // if (p.getDbState() == AbstractPatch.DbState.IN_PROGRESS) { // sb.append('P'); // } // if (p.getDbState() == AbstractPatch.DbState.NOT_AVAILABLE) { // if (patchesToApply.contains(p)) { // sb.append('+'); // } else { // sb.append('-'); // } // } // sb.append(' ').append(p.getName()); // for (int a = p.getName().length(); a < SPACES; a++) { // sb.append(' '); // } // sb.append(" statements:").append(p.getStatementCount()); // sb.append('\n'); // } // log.info(sb.toString().trim()); // log.info("Patches to apply: " + patchesToApply.size() + " using configuration:" + configurationEntry.getId()); // return patchesToApply; // } // // // // protected void executeInternal() throws Exception { // getList(); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/EnvSettings.java // public class EnvSettings { // private final String prefix; // // private EnvSettings(String prefix) { // this.prefix = prefix; // } // // public String getDbPatchFile() { // return prefix + "dbpatch.file"; // } // // public String getDbPatchConfiguration() { // return prefix + "dbpatch.configuration"; // } // // public String getDbPatchStop() { // return prefix + "dbpatch.stop"; // } // // public String getDbPatchSingle() { // return prefix + "dbpatch.single"; // } // // public String getLogLevel() { // return prefix + "dbpatch.logLevel"; // } // // public static EnvSettings standalone() { // return new EnvSettings(""); // } // // public static EnvSettings maven() { // return new EnvSettings("maven."); // } // // public static EnvSettings gradle() { // return new EnvSettings("gradle."); // } // // } // Path: dbpatch-maven-plugin/src/main/java/org/jsoftware/dbpatch/maven/ListMojo.java import org.jsoftware.dbpatch.command.ListCommand; import org.jsoftware.dbpatch.config.EnvSettings; package org.jsoftware.dbpatch.maven; /** * Show list of patches * * @author szalik * @goal list */ public class ListMojo extends CommandSingleConfMojoAdapter<ListCommand> { protected ListMojo() {
super(new ListCommand(EnvSettings.maven()));
m-szalik/dbpatch
dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/PatchParser.java
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractPatch.java // public abstract class AbstractPatch implements Serializable { // private static final long serialVersionUID = 4178101927323891639L; // private String name; // private int statementCount = -1; // private File file; // // public enum DbState { // COMMITTED, IN_PROGRESS, NOT_AVAILABLE // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getStatementCount() { // return statementCount; // } // // public void setStatementCount(int statementCount) { // this.statementCount = statementCount; // } // // public File getFile() { // return file; // } // // public void setFile(File file) { // this.file = file; // } // // public abstract void setDbDate(Date dbDate); // // public abstract void setDbState(DbState dbState); // // public abstract Date getDbDate(); // // public abstract DbState getDbState(); // // public abstract boolean canApply(); // // public String toString() { // return super.toString() + "-" + name; // } // // public static String normalizeName(String name) { // String nameLC = name.toLowerCase(); // while (nameLC.endsWith(".sql") || nameLC.endsWith(".undo") || nameLC.endsWith(".rollback")) { // int dot = nameLC.lastIndexOf('.'); // nameLC = nameLC.substring(0, dot); // } // return name.substring(0, nameLC.length()); // } // // }
import org.jsoftware.dbpatch.config.AbstractPatch; import org.jsoftware.dbpatch.config.ConfigurationEntry; import java.io.IOException; import java.io.InputStream; import java.util.List;
package org.jsoftware.dbpatch.impl; /** * Patch parser. * <p>Splits Patches and RollbackPatches to PatchStatements</p> */ public interface PatchParser { interface ParseResult { List<PatchStatement> getStatements(); int executableCount(); int totalCount(); } ParseResult parse(InputStream inputStream, ConfigurationEntry ce) throws IOException;
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractPatch.java // public abstract class AbstractPatch implements Serializable { // private static final long serialVersionUID = 4178101927323891639L; // private String name; // private int statementCount = -1; // private File file; // // public enum DbState { // COMMITTED, IN_PROGRESS, NOT_AVAILABLE // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getStatementCount() { // return statementCount; // } // // public void setStatementCount(int statementCount) { // this.statementCount = statementCount; // } // // public File getFile() { // return file; // } // // public void setFile(File file) { // this.file = file; // } // // public abstract void setDbDate(Date dbDate); // // public abstract void setDbState(DbState dbState); // // public abstract Date getDbDate(); // // public abstract DbState getDbState(); // // public abstract boolean canApply(); // // public String toString() { // return super.toString() + "-" + name; // } // // public static String normalizeName(String name) { // String nameLC = name.toLowerCase(); // while (nameLC.endsWith(".sql") || nameLC.endsWith(".undo") || nameLC.endsWith(".rollback")) { // int dot = nameLC.lastIndexOf('.'); // nameLC = nameLC.substring(0, dot); // } // return name.substring(0, nameLC.length()); // } // // } // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/PatchParser.java import org.jsoftware.dbpatch.config.AbstractPatch; import org.jsoftware.dbpatch.config.ConfigurationEntry; import java.io.IOException; import java.io.InputStream; import java.util.List; package org.jsoftware.dbpatch.impl; /** * Patch parser. * <p>Splits Patches and RollbackPatches to PatchStatements</p> */ public interface PatchParser { interface ParseResult { List<PatchStatement> getStatements(); int executableCount(); int totalCount(); } ParseResult parse(InputStream inputStream, ConfigurationEntry ce) throws IOException;
ParseResult parse(AbstractPatch p, ConfigurationEntry ce) throws IOException;
m-szalik/dbpatch
dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/dialect/DefaultDialect.java
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractPatch.java // public abstract class AbstractPatch implements Serializable { // private static final long serialVersionUID = 4178101927323891639L; // private String name; // private int statementCount = -1; // private File file; // // public enum DbState { // COMMITTED, IN_PROGRESS, NOT_AVAILABLE // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getStatementCount() { // return statementCount; // } // // public void setStatementCount(int statementCount) { // this.statementCount = statementCount; // } // // public File getFile() { // return file; // } // // public void setFile(File file) { // this.file = file; // } // // public abstract void setDbDate(Date dbDate); // // public abstract void setDbState(DbState dbState); // // public abstract Date getDbDate(); // // public abstract DbState getDbState(); // // public abstract boolean canApply(); // // public String toString() { // return super.toString() + "-" + name; // } // // public static String normalizeName(String name) { // String nameLC = name.toLowerCase(); // while (nameLC.endsWith(".sql") || nameLC.endsWith(".undo") || nameLC.endsWith(".rollback")) { // int dot = nameLC.lastIndexOf('.'); // nameLC = nameLC.substring(0, dot); // } // return name.substring(0, nameLC.length()); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/RollbackPatch.java // public class RollbackPatch extends AbstractPatch { // private final Patch patch; // private final File originalPatchFile; // private boolean missing; // // public RollbackPatch(Patch patch) { // super.setName(patch.getName()); // this.originalPatchFile = patch.getFile(); // this.missing = true; // this.patch = patch; // } // // public RollbackPatch(Patch patch, File rollbackFile, int rollbackStatementsCount) { // this(patch); // super.setFile(rollbackFile); // super.setStatementCount(rollbackStatementsCount); // this.missing = false; // } // // // public void setFile(File file) { // throw new AssertionError("DO NOT USE IT! It shouldn't be invoked."); // } // // @Override // public void setDbDate(Date dbDate) { // patch.setDbDate(dbDate); // } // // @Override // public void setDbState(DbState dbState) { // patch.setDbState(dbState); // } // // @Override // public Date getDbDate() { // return patch.getDbDate(); // } // // @Override // public DbState getDbState() { // return patch.getDbState(); // } // // public File getOriginalPatchFile() { // return originalPatchFile; // } // // public boolean isMissing() { // return missing; // } // // // public boolean canApply() { // return !isMissing() && getStatementCount() > 0 && getDbState() == DbState.COMMITTED; // } // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/CloseUtil.java // public class CloseUtil { // // private CloseUtil() { // } // // public static void close(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Statement statement) { // try { // if (statement != null) { // statement.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Connection conn) { // try { // if (conn != null) { // conn.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(ResultSet rs) { // try { // if (rs != null) { // rs.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // }
import org.jsoftware.dbpatch.config.AbstractPatch; import org.jsoftware.dbpatch.config.Patch; import org.jsoftware.dbpatch.config.RollbackPatch; import org.jsoftware.dbpatch.impl.CloseUtil; import org.jsoftware.dbpatch.impl.PatchStatement; import org.jsoftware.dbpatch.log.LogFactory; import java.sql.*;
// } finally { // rs.close(); // } } public void releaseLock(Connection con) throws SQLException { // Statement stm = con.createStatement(); // stm.executeUpdate("UPDATE " + DBPATCH_TABLE_NAME + " SET patch_db_date = NULL WHERE patch_name IS NULL"); // stm.close(); // con.commit(); } public void savePatchInfoPrepare(Connection con, Patch patch) throws SQLException { PreparedStatement ps = null; ResultSet rs = null; try { ps = con.prepareStatement("SELECT * FROM " + DBPATCH_TABLE_NAME + " WHERE patch_name=? AND patch_db_date IS NULL"); ps.setString(1, patch.getName()); rs = ps.executeQuery(); boolean addRow = !rs.next(); rs.close(); ps.close(); if (addRow) { ps = con.prepareStatement("INSERT INTO " + DBPATCH_TABLE_NAME + " (patch_name,patch_date,patch_db_date) VALUES (?,?,NULL)"); ps.setString(1, patch.getName()); ps.setTimestamp(2, new Timestamp(patch.getFile().lastModified())); ps.execute(); } con.commit(); } finally {
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractPatch.java // public abstract class AbstractPatch implements Serializable { // private static final long serialVersionUID = 4178101927323891639L; // private String name; // private int statementCount = -1; // private File file; // // public enum DbState { // COMMITTED, IN_PROGRESS, NOT_AVAILABLE // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getStatementCount() { // return statementCount; // } // // public void setStatementCount(int statementCount) { // this.statementCount = statementCount; // } // // public File getFile() { // return file; // } // // public void setFile(File file) { // this.file = file; // } // // public abstract void setDbDate(Date dbDate); // // public abstract void setDbState(DbState dbState); // // public abstract Date getDbDate(); // // public abstract DbState getDbState(); // // public abstract boolean canApply(); // // public String toString() { // return super.toString() + "-" + name; // } // // public static String normalizeName(String name) { // String nameLC = name.toLowerCase(); // while (nameLC.endsWith(".sql") || nameLC.endsWith(".undo") || nameLC.endsWith(".rollback")) { // int dot = nameLC.lastIndexOf('.'); // nameLC = nameLC.substring(0, dot); // } // return name.substring(0, nameLC.length()); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/RollbackPatch.java // public class RollbackPatch extends AbstractPatch { // private final Patch patch; // private final File originalPatchFile; // private boolean missing; // // public RollbackPatch(Patch patch) { // super.setName(patch.getName()); // this.originalPatchFile = patch.getFile(); // this.missing = true; // this.patch = patch; // } // // public RollbackPatch(Patch patch, File rollbackFile, int rollbackStatementsCount) { // this(patch); // super.setFile(rollbackFile); // super.setStatementCount(rollbackStatementsCount); // this.missing = false; // } // // // public void setFile(File file) { // throw new AssertionError("DO NOT USE IT! It shouldn't be invoked."); // } // // @Override // public void setDbDate(Date dbDate) { // patch.setDbDate(dbDate); // } // // @Override // public void setDbState(DbState dbState) { // patch.setDbState(dbState); // } // // @Override // public Date getDbDate() { // return patch.getDbDate(); // } // // @Override // public DbState getDbState() { // return patch.getDbState(); // } // // public File getOriginalPatchFile() { // return originalPatchFile; // } // // public boolean isMissing() { // return missing; // } // // // public boolean canApply() { // return !isMissing() && getStatementCount() > 0 && getDbState() == DbState.COMMITTED; // } // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/CloseUtil.java // public class CloseUtil { // // private CloseUtil() { // } // // public static void close(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Statement statement) { // try { // if (statement != null) { // statement.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Connection conn) { // try { // if (conn != null) { // conn.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(ResultSet rs) { // try { // if (rs != null) { // rs.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // } // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/dialect/DefaultDialect.java import org.jsoftware.dbpatch.config.AbstractPatch; import org.jsoftware.dbpatch.config.Patch; import org.jsoftware.dbpatch.config.RollbackPatch; import org.jsoftware.dbpatch.impl.CloseUtil; import org.jsoftware.dbpatch.impl.PatchStatement; import org.jsoftware.dbpatch.log.LogFactory; import java.sql.*; // } finally { // rs.close(); // } } public void releaseLock(Connection con) throws SQLException { // Statement stm = con.createStatement(); // stm.executeUpdate("UPDATE " + DBPATCH_TABLE_NAME + " SET patch_db_date = NULL WHERE patch_name IS NULL"); // stm.close(); // con.commit(); } public void savePatchInfoPrepare(Connection con, Patch patch) throws SQLException { PreparedStatement ps = null; ResultSet rs = null; try { ps = con.prepareStatement("SELECT * FROM " + DBPATCH_TABLE_NAME + " WHERE patch_name=? AND patch_db_date IS NULL"); ps.setString(1, patch.getName()); rs = ps.executeQuery(); boolean addRow = !rs.next(); rs.close(); ps.close(); if (addRow) { ps = con.prepareStatement("INSERT INTO " + DBPATCH_TABLE_NAME + " (patch_name,patch_date,patch_db_date) VALUES (?,?,NULL)"); ps.setString(1, patch.getName()); ps.setTimestamp(2, new Timestamp(patch.getFile().lastModified())); ps.execute(); } con.commit(); } finally {
CloseUtil.close(rs);
m-szalik/dbpatch
dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/dialect/DefaultDialect.java
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractPatch.java // public abstract class AbstractPatch implements Serializable { // private static final long serialVersionUID = 4178101927323891639L; // private String name; // private int statementCount = -1; // private File file; // // public enum DbState { // COMMITTED, IN_PROGRESS, NOT_AVAILABLE // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getStatementCount() { // return statementCount; // } // // public void setStatementCount(int statementCount) { // this.statementCount = statementCount; // } // // public File getFile() { // return file; // } // // public void setFile(File file) { // this.file = file; // } // // public abstract void setDbDate(Date dbDate); // // public abstract void setDbState(DbState dbState); // // public abstract Date getDbDate(); // // public abstract DbState getDbState(); // // public abstract boolean canApply(); // // public String toString() { // return super.toString() + "-" + name; // } // // public static String normalizeName(String name) { // String nameLC = name.toLowerCase(); // while (nameLC.endsWith(".sql") || nameLC.endsWith(".undo") || nameLC.endsWith(".rollback")) { // int dot = nameLC.lastIndexOf('.'); // nameLC = nameLC.substring(0, dot); // } // return name.substring(0, nameLC.length()); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/RollbackPatch.java // public class RollbackPatch extends AbstractPatch { // private final Patch patch; // private final File originalPatchFile; // private boolean missing; // // public RollbackPatch(Patch patch) { // super.setName(patch.getName()); // this.originalPatchFile = patch.getFile(); // this.missing = true; // this.patch = patch; // } // // public RollbackPatch(Patch patch, File rollbackFile, int rollbackStatementsCount) { // this(patch); // super.setFile(rollbackFile); // super.setStatementCount(rollbackStatementsCount); // this.missing = false; // } // // // public void setFile(File file) { // throw new AssertionError("DO NOT USE IT! It shouldn't be invoked."); // } // // @Override // public void setDbDate(Date dbDate) { // patch.setDbDate(dbDate); // } // // @Override // public void setDbState(DbState dbState) { // patch.setDbState(dbState); // } // // @Override // public Date getDbDate() { // return patch.getDbDate(); // } // // @Override // public DbState getDbState() { // return patch.getDbState(); // } // // public File getOriginalPatchFile() { // return originalPatchFile; // } // // public boolean isMissing() { // return missing; // } // // // public boolean canApply() { // return !isMissing() && getStatementCount() > 0 && getDbState() == DbState.COMMITTED; // } // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/CloseUtil.java // public class CloseUtil { // // private CloseUtil() { // } // // public static void close(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Statement statement) { // try { // if (statement != null) { // statement.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Connection conn) { // try { // if (conn != null) { // conn.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(ResultSet rs) { // try { // if (rs != null) { // rs.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // }
import org.jsoftware.dbpatch.config.AbstractPatch; import org.jsoftware.dbpatch.config.Patch; import org.jsoftware.dbpatch.config.RollbackPatch; import org.jsoftware.dbpatch.impl.CloseUtil; import org.jsoftware.dbpatch.impl.PatchStatement; import org.jsoftware.dbpatch.log.LogFactory; import java.sql.*;
rs = ps.executeQuery(); boolean addRow = !rs.next(); rs.close(); ps.close(); if (addRow) { ps = con.prepareStatement("INSERT INTO " + DBPATCH_TABLE_NAME + " (patch_name,patch_date,patch_db_date) VALUES (?,?,NULL)"); ps.setString(1, patch.getName()); ps.setTimestamp(2, new Timestamp(patch.getFile().lastModified())); ps.execute(); } con.commit(); } finally { CloseUtil.close(rs); CloseUtil.close(ps); } } public void savePatchInfoFinal(Connection con, Patch patch) throws SQLException { PreparedStatement ps = null; try { ps = con.prepareStatement("UPDATE " + DBPATCH_TABLE_NAME + " SET patch_db_date=? WHERE patch_name=?"); ps.setTimestamp(1, getNow(con)); ps.setString(2, patch.getName()); ps.execute(); } finally { CloseUtil.close(ps); } }
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractPatch.java // public abstract class AbstractPatch implements Serializable { // private static final long serialVersionUID = 4178101927323891639L; // private String name; // private int statementCount = -1; // private File file; // // public enum DbState { // COMMITTED, IN_PROGRESS, NOT_AVAILABLE // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getStatementCount() { // return statementCount; // } // // public void setStatementCount(int statementCount) { // this.statementCount = statementCount; // } // // public File getFile() { // return file; // } // // public void setFile(File file) { // this.file = file; // } // // public abstract void setDbDate(Date dbDate); // // public abstract void setDbState(DbState dbState); // // public abstract Date getDbDate(); // // public abstract DbState getDbState(); // // public abstract boolean canApply(); // // public String toString() { // return super.toString() + "-" + name; // } // // public static String normalizeName(String name) { // String nameLC = name.toLowerCase(); // while (nameLC.endsWith(".sql") || nameLC.endsWith(".undo") || nameLC.endsWith(".rollback")) { // int dot = nameLC.lastIndexOf('.'); // nameLC = nameLC.substring(0, dot); // } // return name.substring(0, nameLC.length()); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/RollbackPatch.java // public class RollbackPatch extends AbstractPatch { // private final Patch patch; // private final File originalPatchFile; // private boolean missing; // // public RollbackPatch(Patch patch) { // super.setName(patch.getName()); // this.originalPatchFile = patch.getFile(); // this.missing = true; // this.patch = patch; // } // // public RollbackPatch(Patch patch, File rollbackFile, int rollbackStatementsCount) { // this(patch); // super.setFile(rollbackFile); // super.setStatementCount(rollbackStatementsCount); // this.missing = false; // } // // // public void setFile(File file) { // throw new AssertionError("DO NOT USE IT! It shouldn't be invoked."); // } // // @Override // public void setDbDate(Date dbDate) { // patch.setDbDate(dbDate); // } // // @Override // public void setDbState(DbState dbState) { // patch.setDbState(dbState); // } // // @Override // public Date getDbDate() { // return patch.getDbDate(); // } // // @Override // public DbState getDbState() { // return patch.getDbState(); // } // // public File getOriginalPatchFile() { // return originalPatchFile; // } // // public boolean isMissing() { // return missing; // } // // // public boolean canApply() { // return !isMissing() && getStatementCount() > 0 && getDbState() == DbState.COMMITTED; // } // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/CloseUtil.java // public class CloseUtil { // // private CloseUtil() { // } // // public static void close(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Statement statement) { // try { // if (statement != null) { // statement.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Connection conn) { // try { // if (conn != null) { // conn.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(ResultSet rs) { // try { // if (rs != null) { // rs.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // } // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/dialect/DefaultDialect.java import org.jsoftware.dbpatch.config.AbstractPatch; import org.jsoftware.dbpatch.config.Patch; import org.jsoftware.dbpatch.config.RollbackPatch; import org.jsoftware.dbpatch.impl.CloseUtil; import org.jsoftware.dbpatch.impl.PatchStatement; import org.jsoftware.dbpatch.log.LogFactory; import java.sql.*; rs = ps.executeQuery(); boolean addRow = !rs.next(); rs.close(); ps.close(); if (addRow) { ps = con.prepareStatement("INSERT INTO " + DBPATCH_TABLE_NAME + " (patch_name,patch_date,patch_db_date) VALUES (?,?,NULL)"); ps.setString(1, patch.getName()); ps.setTimestamp(2, new Timestamp(patch.getFile().lastModified())); ps.execute(); } con.commit(); } finally { CloseUtil.close(rs); CloseUtil.close(ps); } } public void savePatchInfoFinal(Connection con, Patch patch) throws SQLException { PreparedStatement ps = null; try { ps = con.prepareStatement("UPDATE " + DBPATCH_TABLE_NAME + " SET patch_db_date=? WHERE patch_name=?"); ps.setTimestamp(1, getNow(con)); ps.setString(2, patch.getName()); ps.execute(); } finally { CloseUtil.close(ps); } }
public void removePatchInfo(Connection con, RollbackPatch p) throws SQLException {
m-szalik/dbpatch
dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/dialect/DefaultDialect.java
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractPatch.java // public abstract class AbstractPatch implements Serializable { // private static final long serialVersionUID = 4178101927323891639L; // private String name; // private int statementCount = -1; // private File file; // // public enum DbState { // COMMITTED, IN_PROGRESS, NOT_AVAILABLE // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getStatementCount() { // return statementCount; // } // // public void setStatementCount(int statementCount) { // this.statementCount = statementCount; // } // // public File getFile() { // return file; // } // // public void setFile(File file) { // this.file = file; // } // // public abstract void setDbDate(Date dbDate); // // public abstract void setDbState(DbState dbState); // // public abstract Date getDbDate(); // // public abstract DbState getDbState(); // // public abstract boolean canApply(); // // public String toString() { // return super.toString() + "-" + name; // } // // public static String normalizeName(String name) { // String nameLC = name.toLowerCase(); // while (nameLC.endsWith(".sql") || nameLC.endsWith(".undo") || nameLC.endsWith(".rollback")) { // int dot = nameLC.lastIndexOf('.'); // nameLC = nameLC.substring(0, dot); // } // return name.substring(0, nameLC.length()); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/RollbackPatch.java // public class RollbackPatch extends AbstractPatch { // private final Patch patch; // private final File originalPatchFile; // private boolean missing; // // public RollbackPatch(Patch patch) { // super.setName(patch.getName()); // this.originalPatchFile = patch.getFile(); // this.missing = true; // this.patch = patch; // } // // public RollbackPatch(Patch patch, File rollbackFile, int rollbackStatementsCount) { // this(patch); // super.setFile(rollbackFile); // super.setStatementCount(rollbackStatementsCount); // this.missing = false; // } // // // public void setFile(File file) { // throw new AssertionError("DO NOT USE IT! It shouldn't be invoked."); // } // // @Override // public void setDbDate(Date dbDate) { // patch.setDbDate(dbDate); // } // // @Override // public void setDbState(DbState dbState) { // patch.setDbState(dbState); // } // // @Override // public Date getDbDate() { // return patch.getDbDate(); // } // // @Override // public DbState getDbState() { // return patch.getDbState(); // } // // public File getOriginalPatchFile() { // return originalPatchFile; // } // // public boolean isMissing() { // return missing; // } // // // public boolean canApply() { // return !isMissing() && getStatementCount() > 0 && getDbState() == DbState.COMMITTED; // } // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/CloseUtil.java // public class CloseUtil { // // private CloseUtil() { // } // // public static void close(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Statement statement) { // try { // if (statement != null) { // statement.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Connection conn) { // try { // if (conn != null) { // conn.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(ResultSet rs) { // try { // if (rs != null) { // rs.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // }
import org.jsoftware.dbpatch.config.AbstractPatch; import org.jsoftware.dbpatch.config.Patch; import org.jsoftware.dbpatch.config.RollbackPatch; import org.jsoftware.dbpatch.impl.CloseUtil; import org.jsoftware.dbpatch.impl.PatchStatement; import org.jsoftware.dbpatch.log.LogFactory; import java.sql.*;
CloseUtil.close(rs); CloseUtil.close(ps); } } public void savePatchInfoFinal(Connection con, Patch patch) throws SQLException { PreparedStatement ps = null; try { ps = con.prepareStatement("UPDATE " + DBPATCH_TABLE_NAME + " SET patch_db_date=? WHERE patch_name=?"); ps.setTimestamp(1, getNow(con)); ps.setString(2, patch.getName()); ps.execute(); } finally { CloseUtil.close(ps); } } public void removePatchInfo(Connection con, RollbackPatch p) throws SQLException { PreparedStatement ps = null; try { ps = con.prepareStatement("DELETE FROM " + DBPATCH_TABLE_NAME + " WHERE patch_name=?"); ps.setString(1, p.getName()); ps.execute(); } finally { CloseUtil.close(ps); } }
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractPatch.java // public abstract class AbstractPatch implements Serializable { // private static final long serialVersionUID = 4178101927323891639L; // private String name; // private int statementCount = -1; // private File file; // // public enum DbState { // COMMITTED, IN_PROGRESS, NOT_AVAILABLE // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getStatementCount() { // return statementCount; // } // // public void setStatementCount(int statementCount) { // this.statementCount = statementCount; // } // // public File getFile() { // return file; // } // // public void setFile(File file) { // this.file = file; // } // // public abstract void setDbDate(Date dbDate); // // public abstract void setDbState(DbState dbState); // // public abstract Date getDbDate(); // // public abstract DbState getDbState(); // // public abstract boolean canApply(); // // public String toString() { // return super.toString() + "-" + name; // } // // public static String normalizeName(String name) { // String nameLC = name.toLowerCase(); // while (nameLC.endsWith(".sql") || nameLC.endsWith(".undo") || nameLC.endsWith(".rollback")) { // int dot = nameLC.lastIndexOf('.'); // nameLC = nameLC.substring(0, dot); // } // return name.substring(0, nameLC.length()); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/RollbackPatch.java // public class RollbackPatch extends AbstractPatch { // private final Patch patch; // private final File originalPatchFile; // private boolean missing; // // public RollbackPatch(Patch patch) { // super.setName(patch.getName()); // this.originalPatchFile = patch.getFile(); // this.missing = true; // this.patch = patch; // } // // public RollbackPatch(Patch patch, File rollbackFile, int rollbackStatementsCount) { // this(patch); // super.setFile(rollbackFile); // super.setStatementCount(rollbackStatementsCount); // this.missing = false; // } // // // public void setFile(File file) { // throw new AssertionError("DO NOT USE IT! It shouldn't be invoked."); // } // // @Override // public void setDbDate(Date dbDate) { // patch.setDbDate(dbDate); // } // // @Override // public void setDbState(DbState dbState) { // patch.setDbState(dbState); // } // // @Override // public Date getDbDate() { // return patch.getDbDate(); // } // // @Override // public DbState getDbState() { // return patch.getDbState(); // } // // public File getOriginalPatchFile() { // return originalPatchFile; // } // // public boolean isMissing() { // return missing; // } // // // public boolean canApply() { // return !isMissing() && getStatementCount() > 0 && getDbState() == DbState.COMMITTED; // } // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/CloseUtil.java // public class CloseUtil { // // private CloseUtil() { // } // // public static void close(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Statement statement) { // try { // if (statement != null) { // statement.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Connection conn) { // try { // if (conn != null) { // conn.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(ResultSet rs) { // try { // if (rs != null) { // rs.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // } // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/dialect/DefaultDialect.java import org.jsoftware.dbpatch.config.AbstractPatch; import org.jsoftware.dbpatch.config.Patch; import org.jsoftware.dbpatch.config.RollbackPatch; import org.jsoftware.dbpatch.impl.CloseUtil; import org.jsoftware.dbpatch.impl.PatchStatement; import org.jsoftware.dbpatch.log.LogFactory; import java.sql.*; CloseUtil.close(rs); CloseUtil.close(ps); } } public void savePatchInfoFinal(Connection con, Patch patch) throws SQLException { PreparedStatement ps = null; try { ps = con.prepareStatement("UPDATE " + DBPATCH_TABLE_NAME + " SET patch_db_date=? WHERE patch_name=?"); ps.setTimestamp(1, getNow(con)); ps.setString(2, patch.getName()); ps.execute(); } finally { CloseUtil.close(ps); } } public void removePatchInfo(Connection con, RollbackPatch p) throws SQLException { PreparedStatement ps = null; try { ps = con.prepareStatement("DELETE FROM " + DBPATCH_TABLE_NAME + " WHERE patch_name=?"); ps.setString(1, p.getName()); ps.execute(); } finally { CloseUtil.close(ps); } }
public boolean checkIfPatchIsCommitted(Connection con, AbstractPatch patch) throws SQLException {
m-szalik/dbpatch
dbpatch-core/src/test/java/org/jsoftware/dbpatch/command/HelpParseCommandTest.java
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/EnvSettings.java // public class EnvSettings { // private final String prefix; // // private EnvSettings(String prefix) { // this.prefix = prefix; // } // // public String getDbPatchFile() { // return prefix + "dbpatch.file"; // } // // public String getDbPatchConfiguration() { // return prefix + "dbpatch.configuration"; // } // // public String getDbPatchStop() { // return prefix + "dbpatch.stop"; // } // // public String getDbPatchSingle() { // return prefix + "dbpatch.single"; // } // // public String getLogLevel() { // return prefix + "dbpatch.logLevel"; // } // // public static EnvSettings standalone() { // return new EnvSettings(""); // } // // public static EnvSettings maven() { // return new EnvSettings("maven."); // } // // public static EnvSettings gradle() { // return new EnvSettings("gradle."); // } // // }
import org.apache.commons.io.output.NullOutputStream; import org.jsoftware.dbpatch.config.EnvSettings; import org.jsoftware.dbpatch.config.Patch; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.PrintStream;
package org.jsoftware.dbpatch.command; public class HelpParseCommandTest extends AbstractDbCommandTest { private HelpParseCommand command; @Before public void setUp() throws Exception {
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/EnvSettings.java // public class EnvSettings { // private final String prefix; // // private EnvSettings(String prefix) { // this.prefix = prefix; // } // // public String getDbPatchFile() { // return prefix + "dbpatch.file"; // } // // public String getDbPatchConfiguration() { // return prefix + "dbpatch.configuration"; // } // // public String getDbPatchStop() { // return prefix + "dbpatch.stop"; // } // // public String getDbPatchSingle() { // return prefix + "dbpatch.single"; // } // // public String getLogLevel() { // return prefix + "dbpatch.logLevel"; // } // // public static EnvSettings standalone() { // return new EnvSettings(""); // } // // public static EnvSettings maven() { // return new EnvSettings("maven."); // } // // public static EnvSettings gradle() { // return new EnvSettings("gradle."); // } // // } // Path: dbpatch-core/src/test/java/org/jsoftware/dbpatch/command/HelpParseCommandTest.java import org.apache.commons.io.output.NullOutputStream; import org.jsoftware.dbpatch.config.EnvSettings; import org.jsoftware.dbpatch.config.Patch; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.PrintStream; package org.jsoftware.dbpatch.command; public class HelpParseCommandTest extends AbstractDbCommandTest { private HelpParseCommand command; @Before public void setUp() throws Exception {
command = new HelpParseCommand(EnvSettings.standalone());
m-szalik/dbpatch
dbpatch-maven-plugin/src/main/java/org/jsoftware/dbpatch/maven/RollbackMojo.java
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/RollbackCommand.java // public class RollbackCommand extends RollbackListCommand implements CommandSuccessIndicator { // private boolean success; // private RollbackCommandConf rollbackCommandConf; // // public RollbackCommand(EnvSettings envSettings) { // super(envSettings); // } // // void setRollbackCommandConf(RollbackCommandConf rollbackCommandConf) { // this.rollbackCommandConf = rollbackCommandConf; // } // // @SuppressWarnings("unchecked") // protected void executeInternal() throws Exception { // success = false; // List<RollbackPatch> patches = getList(); // List<RollbackPatch> patchesFiltered = new LinkedList<RollbackPatch>(); // if (rollbackCommandConf == null) { // rollbackCommandConf = createRollbackCommandConf(); // } // log.debug("Looking for patch '" + rollbackCommandConf.getPatchName() + "'."); // boolean found = false; // if (rollbackCommandConf.getAction() == RollbackCommandConf.Action.STOP_ON) { // for (RollbackPatch rp : patches) { // patchesFiltered.add(rp); // if (rp.getName().equals(rollbackCommandConf.getPatchName())) { // found = true; // break; // } // } // } else { // for (RollbackPatch rp : patches) { // if (rp.getName().equals(rollbackCommandConf.getPatchName())) { // found = true; // patchesFiltered.add(rp); // break; // } // } // } // if (!found) { // throw new CommandFailureException("Cannot find patch by name '" + rollbackCommandConf.getPatchName() + "'"); // } // // try { // manager.startExecution(); // for (RollbackPatch p : patchesFiltered) { // if (p.getDbState() == AbstractPatch.DbState.COMMITTED) { // if (p.isMissing()) { // String msg = "Missing or empty rollback file for patch " + p.getName(); // log.fatal(msg); // throw new CommandFailureException(msg); // } else { // log.info("Executing rollback for " + p.getName() + " - " + p.getFile().getName()); // manager.rollback(p); // } // } else { // log.info("Skipping rollback for " + p.getName() + " patch was not applied."); // } // } // success = true; // } finally { // manager.endExecution(); // } // } // // private RollbackCommandConf createRollbackCommandConf() throws CommandFailureException { // String dStop = System.getProperty(envSettings.getDbPatchStop()); // String dSingle = System.getProperty(envSettings.getDbPatchSingle()); // if (StringUtils.isBlank(dSingle) && StringUtils.isBlank(dStop)) { // throw new CommandFailureException("Missing property '" + envSettings.getDbPatchSingle() + "' or '" + envSettings.getDbPatchStop() + "'!"); // } // if (!StringUtils.isBlank(dSingle) && !StringUtils.isBlank(dStop)) { // throw new CommandFailureException("Both properties '" + envSettings.getDbPatchSingle() + "' and '" + envSettings.getDbPatchStop() + "' are set!"); // } // RollbackCommandConf.Action action = StringUtils.isBlank(dSingle) ? RollbackCommandConf.Action.STOP_ON : RollbackCommandConf.Action.SINGLE; // String pnOrg = action == RollbackCommandConf.Action.STOP_ON ? dStop : dSingle; // String patchName = AbstractPatch.normalizeName(pnOrg); // return new RollbackCommandConf(action, patchName); // } // // // public boolean isSuccess() { // return success; // } // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/EnvSettings.java // public class EnvSettings { // private final String prefix; // // private EnvSettings(String prefix) { // this.prefix = prefix; // } // // public String getDbPatchFile() { // return prefix + "dbpatch.file"; // } // // public String getDbPatchConfiguration() { // return prefix + "dbpatch.configuration"; // } // // public String getDbPatchStop() { // return prefix + "dbpatch.stop"; // } // // public String getDbPatchSingle() { // return prefix + "dbpatch.single"; // } // // public String getLogLevel() { // return prefix + "dbpatch.logLevel"; // } // // public static EnvSettings standalone() { // return new EnvSettings(""); // } // // public static EnvSettings maven() { // return new EnvSettings("maven."); // } // // public static EnvSettings gradle() { // return new EnvSettings("gradle."); // } // // }
import org.jsoftware.dbpatch.command.RollbackCommand; import org.jsoftware.dbpatch.config.EnvSettings;
package org.jsoftware.dbpatch.maven; /** * Roll-back patch or patches * * @author szalik * @goal rollback */ public class RollbackMojo extends CommandSingleConfMojoAdapter<RollbackCommand> { protected RollbackMojo() {
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/RollbackCommand.java // public class RollbackCommand extends RollbackListCommand implements CommandSuccessIndicator { // private boolean success; // private RollbackCommandConf rollbackCommandConf; // // public RollbackCommand(EnvSettings envSettings) { // super(envSettings); // } // // void setRollbackCommandConf(RollbackCommandConf rollbackCommandConf) { // this.rollbackCommandConf = rollbackCommandConf; // } // // @SuppressWarnings("unchecked") // protected void executeInternal() throws Exception { // success = false; // List<RollbackPatch> patches = getList(); // List<RollbackPatch> patchesFiltered = new LinkedList<RollbackPatch>(); // if (rollbackCommandConf == null) { // rollbackCommandConf = createRollbackCommandConf(); // } // log.debug("Looking for patch '" + rollbackCommandConf.getPatchName() + "'."); // boolean found = false; // if (rollbackCommandConf.getAction() == RollbackCommandConf.Action.STOP_ON) { // for (RollbackPatch rp : patches) { // patchesFiltered.add(rp); // if (rp.getName().equals(rollbackCommandConf.getPatchName())) { // found = true; // break; // } // } // } else { // for (RollbackPatch rp : patches) { // if (rp.getName().equals(rollbackCommandConf.getPatchName())) { // found = true; // patchesFiltered.add(rp); // break; // } // } // } // if (!found) { // throw new CommandFailureException("Cannot find patch by name '" + rollbackCommandConf.getPatchName() + "'"); // } // // try { // manager.startExecution(); // for (RollbackPatch p : patchesFiltered) { // if (p.getDbState() == AbstractPatch.DbState.COMMITTED) { // if (p.isMissing()) { // String msg = "Missing or empty rollback file for patch " + p.getName(); // log.fatal(msg); // throw new CommandFailureException(msg); // } else { // log.info("Executing rollback for " + p.getName() + " - " + p.getFile().getName()); // manager.rollback(p); // } // } else { // log.info("Skipping rollback for " + p.getName() + " patch was not applied."); // } // } // success = true; // } finally { // manager.endExecution(); // } // } // // private RollbackCommandConf createRollbackCommandConf() throws CommandFailureException { // String dStop = System.getProperty(envSettings.getDbPatchStop()); // String dSingle = System.getProperty(envSettings.getDbPatchSingle()); // if (StringUtils.isBlank(dSingle) && StringUtils.isBlank(dStop)) { // throw new CommandFailureException("Missing property '" + envSettings.getDbPatchSingle() + "' or '" + envSettings.getDbPatchStop() + "'!"); // } // if (!StringUtils.isBlank(dSingle) && !StringUtils.isBlank(dStop)) { // throw new CommandFailureException("Both properties '" + envSettings.getDbPatchSingle() + "' and '" + envSettings.getDbPatchStop() + "' are set!"); // } // RollbackCommandConf.Action action = StringUtils.isBlank(dSingle) ? RollbackCommandConf.Action.STOP_ON : RollbackCommandConf.Action.SINGLE; // String pnOrg = action == RollbackCommandConf.Action.STOP_ON ? dStop : dSingle; // String patchName = AbstractPatch.normalizeName(pnOrg); // return new RollbackCommandConf(action, patchName); // } // // // public boolean isSuccess() { // return success; // } // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/EnvSettings.java // public class EnvSettings { // private final String prefix; // // private EnvSettings(String prefix) { // this.prefix = prefix; // } // // public String getDbPatchFile() { // return prefix + "dbpatch.file"; // } // // public String getDbPatchConfiguration() { // return prefix + "dbpatch.configuration"; // } // // public String getDbPatchStop() { // return prefix + "dbpatch.stop"; // } // // public String getDbPatchSingle() { // return prefix + "dbpatch.single"; // } // // public String getLogLevel() { // return prefix + "dbpatch.logLevel"; // } // // public static EnvSettings standalone() { // return new EnvSettings(""); // } // // public static EnvSettings maven() { // return new EnvSettings("maven."); // } // // public static EnvSettings gradle() { // return new EnvSettings("gradle."); // } // // } // Path: dbpatch-maven-plugin/src/main/java/org/jsoftware/dbpatch/maven/RollbackMojo.java import org.jsoftware.dbpatch.command.RollbackCommand; import org.jsoftware.dbpatch.config.EnvSettings; package org.jsoftware.dbpatch.maven; /** * Roll-back patch or patches * * @author szalik * @goal rollback */ public class RollbackMojo extends CommandSingleConfMojoAdapter<RollbackCommand> { protected RollbackMojo() {
super(new RollbackCommand(EnvSettings.maven()));
m-szalik/dbpatch
dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractConfigurationParser.java
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/CloseUtil.java // public class CloseUtil { // // private CloseUtil() { // } // // public static void close(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Statement statement) { // try { // if (statement != null) { // statement.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Connection conn) { // try { // if (conn != null) { // conn.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(ResultSet rs) { // try { // if (rs != null) { // rs.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/log/Log.java // public interface Log { // // void trace(String msg, Throwable e); // // void debug(String msg); // // void info(String msg); // // void warn(String msg); // // void fatal(String msg); // // void warn(String msg, Throwable e); // // void fatal(String msg, Throwable e); // }
import org.jsoftware.dbpatch.impl.CloseUtil; import org.jsoftware.dbpatch.log.Log; import org.jsoftware.dbpatch.log.LogFactory; import java.io.*; import java.text.ParseException; import java.util.Collection;
package org.jsoftware.dbpatch.config; /** * Base class for parsing configuration */ public abstract class AbstractConfigurationParser { public static Collection<ConfigurationEntry> discoverConfiguration(File confFile) throws ParseException, IOException {
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/CloseUtil.java // public class CloseUtil { // // private CloseUtil() { // } // // public static void close(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Statement statement) { // try { // if (statement != null) { // statement.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Connection conn) { // try { // if (conn != null) { // conn.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(ResultSet rs) { // try { // if (rs != null) { // rs.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/log/Log.java // public interface Log { // // void trace(String msg, Throwable e); // // void debug(String msg); // // void info(String msg); // // void warn(String msg); // // void fatal(String msg); // // void warn(String msg, Throwable e); // // void fatal(String msg, Throwable e); // } // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractConfigurationParser.java import org.jsoftware.dbpatch.impl.CloseUtil; import org.jsoftware.dbpatch.log.Log; import org.jsoftware.dbpatch.log.LogFactory; import java.io.*; import java.text.ParseException; import java.util.Collection; package org.jsoftware.dbpatch.config; /** * Base class for parsing configuration */ public abstract class AbstractConfigurationParser { public static Collection<ConfigurationEntry> discoverConfiguration(File confFile) throws ParseException, IOException {
final Log log = LogFactory.getInstance();
m-szalik/dbpatch
dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractConfigurationParser.java
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/CloseUtil.java // public class CloseUtil { // // private CloseUtil() { // } // // public static void close(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Statement statement) { // try { // if (statement != null) { // statement.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Connection conn) { // try { // if (conn != null) { // conn.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(ResultSet rs) { // try { // if (rs != null) { // rs.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/log/Log.java // public interface Log { // // void trace(String msg, Throwable e); // // void debug(String msg); // // void info(String msg); // // void warn(String msg); // // void fatal(String msg); // // void warn(String msg, Throwable e); // // void fatal(String msg, Throwable e); // }
import org.jsoftware.dbpatch.impl.CloseUtil; import org.jsoftware.dbpatch.log.Log; import org.jsoftware.dbpatch.log.LogFactory; import java.io.*; import java.text.ParseException; import java.util.Collection;
final Log log = LogFactory.getInstance(); InputStream input = null; File baseDir = null; try { if (confFile == null) { log.debug("Looking for dbpach.properties in classpath."); input = Thread.currentThread().getContextClassLoader().getResourceAsStream("/dbpatch.properties"); log.debug("Resource dbpatch.properties " + (input == null ? "not" : "") + " found in classpath."); if (input == null) { log.debug("Looking for dbpach.properties in current directory."); File f = new File("dbpatch.properties"); log.debug("Resource dbpatch.properties " + (!f.exists() ? "not" : "") + " found in current directory."); input = new FileInputStream(f); baseDir = new File("."); } } else { if (!confFile.exists()) { throw new FileNotFoundException(confFile.getAbsolutePath()); } log.debug("Configuration found - " + confFile.getPath()); input = new FileInputStream(confFile); baseDir = confFile.getParentFile(); } AbstractConfigurationParser parser = new PropertiesConfigurationParser(); Collection<ConfigurationEntry> conf = parser.parse(baseDir, input); for (ConfigurationEntry ce : conf) { ce.validate(); } return conf; } finally {
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/CloseUtil.java // public class CloseUtil { // // private CloseUtil() { // } // // public static void close(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Statement statement) { // try { // if (statement != null) { // statement.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Connection conn) { // try { // if (conn != null) { // conn.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(ResultSet rs) { // try { // if (rs != null) { // rs.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/log/Log.java // public interface Log { // // void trace(String msg, Throwable e); // // void debug(String msg); // // void info(String msg); // // void warn(String msg); // // void fatal(String msg); // // void warn(String msg, Throwable e); // // void fatal(String msg, Throwable e); // } // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractConfigurationParser.java import org.jsoftware.dbpatch.impl.CloseUtil; import org.jsoftware.dbpatch.log.Log; import org.jsoftware.dbpatch.log.LogFactory; import java.io.*; import java.text.ParseException; import java.util.Collection; final Log log = LogFactory.getInstance(); InputStream input = null; File baseDir = null; try { if (confFile == null) { log.debug("Looking for dbpach.properties in classpath."); input = Thread.currentThread().getContextClassLoader().getResourceAsStream("/dbpatch.properties"); log.debug("Resource dbpatch.properties " + (input == null ? "not" : "") + " found in classpath."); if (input == null) { log.debug("Looking for dbpach.properties in current directory."); File f = new File("dbpatch.properties"); log.debug("Resource dbpatch.properties " + (!f.exists() ? "not" : "") + " found in current directory."); input = new FileInputStream(f); baseDir = new File("."); } } else { if (!confFile.exists()) { throw new FileNotFoundException(confFile.getAbsolutePath()); } log.debug("Configuration found - " + confFile.getPath()); input = new FileInputStream(confFile); baseDir = confFile.getParentFile(); } AbstractConfigurationParser parser = new PropertiesConfigurationParser(); Collection<ConfigurationEntry> conf = parser.parse(baseDir, input); for (ConfigurationEntry ce : conf) { ce.validate(); } return conf; } finally {
CloseUtil.close(input);
m-szalik/dbpatch
dbpatch-maven-plugin/src/main/java/org/jsoftware/dbpatch/maven/SkipErrorsMojo.java
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/SkipErrorsCommand.java // public class SkipErrorsCommand extends AbstractSingleConfDbPatchCommand { // // public SkipErrorsCommand(EnvSettings envSettings) { // super(envSettings); // } // // // protected void executeInternal() throws Exception { // Connection connection = manager.getConnection(); // Statement statement = null; // ResultSet rs = null; // PreparedStatement ps = null; // try { // statement = connection.createStatement(); // rs = statement.executeQuery("SELECT patch_name FROM " + manager.getTableName() + " WHERE patch_db_date IS NULL"); // ps = connection.prepareStatement("UPDATE " + manager.getTableName() + " SET patch_db_date=? WHERE patch_name=?"); // ps.setDate(1, new Date(0)); // while (rs.next()) { // ps.setString(2, rs.getString(1)); // ps.execute(); // log.info("Mark to skip " + rs.getString(1)); // } // connection.commit(); // } finally { // CloseUtil.close(statement); // CloseUtil.close(rs); // CloseUtil.close(ps); // } // } // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/EnvSettings.java // public class EnvSettings { // private final String prefix; // // private EnvSettings(String prefix) { // this.prefix = prefix; // } // // public String getDbPatchFile() { // return prefix + "dbpatch.file"; // } // // public String getDbPatchConfiguration() { // return prefix + "dbpatch.configuration"; // } // // public String getDbPatchStop() { // return prefix + "dbpatch.stop"; // } // // public String getDbPatchSingle() { // return prefix + "dbpatch.single"; // } // // public String getLogLevel() { // return prefix + "dbpatch.logLevel"; // } // // public static EnvSettings standalone() { // return new EnvSettings(""); // } // // public static EnvSettings maven() { // return new EnvSettings("maven."); // } // // public static EnvSettings gradle() { // return new EnvSettings("gradle."); // } // // }
import org.jsoftware.dbpatch.command.SkipErrorsCommand; import org.jsoftware.dbpatch.config.EnvSettings;
package org.jsoftware.dbpatch.maven; /** * Mark patches &quot;in progress&quot; as committed. * * @author szalik * @goal skip-errors */ public class SkipErrorsMojo extends CommandSingleConfMojoAdapter<SkipErrorsCommand> { protected SkipErrorsMojo() {
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/SkipErrorsCommand.java // public class SkipErrorsCommand extends AbstractSingleConfDbPatchCommand { // // public SkipErrorsCommand(EnvSettings envSettings) { // super(envSettings); // } // // // protected void executeInternal() throws Exception { // Connection connection = manager.getConnection(); // Statement statement = null; // ResultSet rs = null; // PreparedStatement ps = null; // try { // statement = connection.createStatement(); // rs = statement.executeQuery("SELECT patch_name FROM " + manager.getTableName() + " WHERE patch_db_date IS NULL"); // ps = connection.prepareStatement("UPDATE " + manager.getTableName() + " SET patch_db_date=? WHERE patch_name=?"); // ps.setDate(1, new Date(0)); // while (rs.next()) { // ps.setString(2, rs.getString(1)); // ps.execute(); // log.info("Mark to skip " + rs.getString(1)); // } // connection.commit(); // } finally { // CloseUtil.close(statement); // CloseUtil.close(rs); // CloseUtil.close(ps); // } // } // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/EnvSettings.java // public class EnvSettings { // private final String prefix; // // private EnvSettings(String prefix) { // this.prefix = prefix; // } // // public String getDbPatchFile() { // return prefix + "dbpatch.file"; // } // // public String getDbPatchConfiguration() { // return prefix + "dbpatch.configuration"; // } // // public String getDbPatchStop() { // return prefix + "dbpatch.stop"; // } // // public String getDbPatchSingle() { // return prefix + "dbpatch.single"; // } // // public String getLogLevel() { // return prefix + "dbpatch.logLevel"; // } // // public static EnvSettings standalone() { // return new EnvSettings(""); // } // // public static EnvSettings maven() { // return new EnvSettings("maven."); // } // // public static EnvSettings gradle() { // return new EnvSettings("gradle."); // } // // } // Path: dbpatch-maven-plugin/src/main/java/org/jsoftware/dbpatch/maven/SkipErrorsMojo.java import org.jsoftware.dbpatch.command.SkipErrorsCommand; import org.jsoftware.dbpatch.config.EnvSettings; package org.jsoftware.dbpatch.maven; /** * Mark patches &quot;in progress&quot; as committed. * * @author szalik * @goal skip-errors */ public class SkipErrorsMojo extends CommandSingleConfMojoAdapter<SkipErrorsCommand> { protected SkipErrorsMojo() {
super(new SkipErrorsCommand(EnvSettings.maven()));
m-szalik/dbpatch
dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/AbstractListCommand.java
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractPatch.java // public abstract class AbstractPatch implements Serializable { // private static final long serialVersionUID = 4178101927323891639L; // private String name; // private int statementCount = -1; // private File file; // // public enum DbState { // COMMITTED, IN_PROGRESS, NOT_AVAILABLE // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getStatementCount() { // return statementCount; // } // // public void setStatementCount(int statementCount) { // this.statementCount = statementCount; // } // // public File getFile() { // return file; // } // // public void setFile(File file) { // this.file = file; // } // // public abstract void setDbDate(Date dbDate); // // public abstract void setDbState(DbState dbState); // // public abstract Date getDbDate(); // // public abstract DbState getDbState(); // // public abstract boolean canApply(); // // public String toString() { // return super.toString() + "-" + name; // } // // public static String normalizeName(String name) { // String nameLC = name.toLowerCase(); // while (nameLC.endsWith(".sql") || nameLC.endsWith(".undo") || nameLC.endsWith(".rollback")) { // int dot = nameLC.lastIndexOf('.'); // nameLC = nameLC.substring(0, dot); // } // return name.substring(0, nameLC.length()); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/EnvSettings.java // public class EnvSettings { // private final String prefix; // // private EnvSettings(String prefix) { // this.prefix = prefix; // } // // public String getDbPatchFile() { // return prefix + "dbpatch.file"; // } // // public String getDbPatchConfiguration() { // return prefix + "dbpatch.configuration"; // } // // public String getDbPatchStop() { // return prefix + "dbpatch.stop"; // } // // public String getDbPatchSingle() { // return prefix + "dbpatch.single"; // } // // public String getLogLevel() { // return prefix + "dbpatch.logLevel"; // } // // public static EnvSettings standalone() { // return new EnvSettings(""); // } // // public static EnvSettings maven() { // return new EnvSettings("maven."); // } // // public static EnvSettings gradle() { // return new EnvSettings("gradle."); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/PatchScanner.java // public interface PatchScanner extends Serializable { // // /** // * @param directory base dir // * @param paths to scan (add directory if not absolute) // * @return list of found patches // * @throws DuplicatePatchNameException when duplicated patch names were found // * @throws IOException io problem // */ // List<Patch> scan(File directory, String[] paths) throws DuplicatePatchNameException, IOException; // // /** // * @param patch rollbacks for this patch // * @param directory base dir // * @param paths to scan (add directory if not absolute) // * @return null if no file was found // * @throws DuplicatePatchNameException when duplicated patch names were found // * @throws IOException io problem // */ // File findRollbackFile(File directory, String[] paths, Patch patch) throws DuplicatePatchNameException, IOException; // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/DuplicatePatchNameException.java // public class DuplicatePatchNameException extends CommandFailureException { // private static final long serialVersionUID = 5221931112583803769L; // // public DuplicatePatchNameException(Object source, Patch patch1, Patch patch2) { // super(source, "Duplicate patch name", "Patches name \"" + patch1.getName() + "\" conflict between " + patch1.getFile().getAbsolutePath() + " and " + patch2.getFile().getAbsolutePath()); // } // // }
import org.jsoftware.dbpatch.config.AbstractPatch; import org.jsoftware.dbpatch.config.EnvSettings; import org.jsoftware.dbpatch.config.Patch; import org.jsoftware.dbpatch.config.PatchScanner; import org.jsoftware.dbpatch.impl.DuplicatePatchNameException; import java.io.IOException; import java.sql.SQLException; import java.util.List;
package org.jsoftware.dbpatch.command; /** * Show list of patches * * @author szalik */ abstract class AbstractListCommand<P extends AbstractPatch> extends AbstractSingleConfDbPatchCommand { static final int SPACES = 46;
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractPatch.java // public abstract class AbstractPatch implements Serializable { // private static final long serialVersionUID = 4178101927323891639L; // private String name; // private int statementCount = -1; // private File file; // // public enum DbState { // COMMITTED, IN_PROGRESS, NOT_AVAILABLE // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getStatementCount() { // return statementCount; // } // // public void setStatementCount(int statementCount) { // this.statementCount = statementCount; // } // // public File getFile() { // return file; // } // // public void setFile(File file) { // this.file = file; // } // // public abstract void setDbDate(Date dbDate); // // public abstract void setDbState(DbState dbState); // // public abstract Date getDbDate(); // // public abstract DbState getDbState(); // // public abstract boolean canApply(); // // public String toString() { // return super.toString() + "-" + name; // } // // public static String normalizeName(String name) { // String nameLC = name.toLowerCase(); // while (nameLC.endsWith(".sql") || nameLC.endsWith(".undo") || nameLC.endsWith(".rollback")) { // int dot = nameLC.lastIndexOf('.'); // nameLC = nameLC.substring(0, dot); // } // return name.substring(0, nameLC.length()); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/EnvSettings.java // public class EnvSettings { // private final String prefix; // // private EnvSettings(String prefix) { // this.prefix = prefix; // } // // public String getDbPatchFile() { // return prefix + "dbpatch.file"; // } // // public String getDbPatchConfiguration() { // return prefix + "dbpatch.configuration"; // } // // public String getDbPatchStop() { // return prefix + "dbpatch.stop"; // } // // public String getDbPatchSingle() { // return prefix + "dbpatch.single"; // } // // public String getLogLevel() { // return prefix + "dbpatch.logLevel"; // } // // public static EnvSettings standalone() { // return new EnvSettings(""); // } // // public static EnvSettings maven() { // return new EnvSettings("maven."); // } // // public static EnvSettings gradle() { // return new EnvSettings("gradle."); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/PatchScanner.java // public interface PatchScanner extends Serializable { // // /** // * @param directory base dir // * @param paths to scan (add directory if not absolute) // * @return list of found patches // * @throws DuplicatePatchNameException when duplicated patch names were found // * @throws IOException io problem // */ // List<Patch> scan(File directory, String[] paths) throws DuplicatePatchNameException, IOException; // // /** // * @param patch rollbacks for this patch // * @param directory base dir // * @param paths to scan (add directory if not absolute) // * @return null if no file was found // * @throws DuplicatePatchNameException when duplicated patch names were found // * @throws IOException io problem // */ // File findRollbackFile(File directory, String[] paths, Patch patch) throws DuplicatePatchNameException, IOException; // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/DuplicatePatchNameException.java // public class DuplicatePatchNameException extends CommandFailureException { // private static final long serialVersionUID = 5221931112583803769L; // // public DuplicatePatchNameException(Object source, Patch patch1, Patch patch2) { // super(source, "Duplicate patch name", "Patches name \"" + patch1.getName() + "\" conflict between " + patch1.getFile().getAbsolutePath() + " and " + patch2.getFile().getAbsolutePath()); // } // // } // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/AbstractListCommand.java import org.jsoftware.dbpatch.config.AbstractPatch; import org.jsoftware.dbpatch.config.EnvSettings; import org.jsoftware.dbpatch.config.Patch; import org.jsoftware.dbpatch.config.PatchScanner; import org.jsoftware.dbpatch.impl.DuplicatePatchNameException; import java.io.IOException; import java.sql.SQLException; import java.util.List; package org.jsoftware.dbpatch.command; /** * Show list of patches * * @author szalik */ abstract class AbstractListCommand<P extends AbstractPatch> extends AbstractSingleConfDbPatchCommand { static final int SPACES = 46;
public AbstractListCommand(EnvSettings envSettings) {
m-szalik/dbpatch
dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/AbstractListCommand.java
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractPatch.java // public abstract class AbstractPatch implements Serializable { // private static final long serialVersionUID = 4178101927323891639L; // private String name; // private int statementCount = -1; // private File file; // // public enum DbState { // COMMITTED, IN_PROGRESS, NOT_AVAILABLE // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getStatementCount() { // return statementCount; // } // // public void setStatementCount(int statementCount) { // this.statementCount = statementCount; // } // // public File getFile() { // return file; // } // // public void setFile(File file) { // this.file = file; // } // // public abstract void setDbDate(Date dbDate); // // public abstract void setDbState(DbState dbState); // // public abstract Date getDbDate(); // // public abstract DbState getDbState(); // // public abstract boolean canApply(); // // public String toString() { // return super.toString() + "-" + name; // } // // public static String normalizeName(String name) { // String nameLC = name.toLowerCase(); // while (nameLC.endsWith(".sql") || nameLC.endsWith(".undo") || nameLC.endsWith(".rollback")) { // int dot = nameLC.lastIndexOf('.'); // nameLC = nameLC.substring(0, dot); // } // return name.substring(0, nameLC.length()); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/EnvSettings.java // public class EnvSettings { // private final String prefix; // // private EnvSettings(String prefix) { // this.prefix = prefix; // } // // public String getDbPatchFile() { // return prefix + "dbpatch.file"; // } // // public String getDbPatchConfiguration() { // return prefix + "dbpatch.configuration"; // } // // public String getDbPatchStop() { // return prefix + "dbpatch.stop"; // } // // public String getDbPatchSingle() { // return prefix + "dbpatch.single"; // } // // public String getLogLevel() { // return prefix + "dbpatch.logLevel"; // } // // public static EnvSettings standalone() { // return new EnvSettings(""); // } // // public static EnvSettings maven() { // return new EnvSettings("maven."); // } // // public static EnvSettings gradle() { // return new EnvSettings("gradle."); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/PatchScanner.java // public interface PatchScanner extends Serializable { // // /** // * @param directory base dir // * @param paths to scan (add directory if not absolute) // * @return list of found patches // * @throws DuplicatePatchNameException when duplicated patch names were found // * @throws IOException io problem // */ // List<Patch> scan(File directory, String[] paths) throws DuplicatePatchNameException, IOException; // // /** // * @param patch rollbacks for this patch // * @param directory base dir // * @param paths to scan (add directory if not absolute) // * @return null if no file was found // * @throws DuplicatePatchNameException when duplicated patch names were found // * @throws IOException io problem // */ // File findRollbackFile(File directory, String[] paths, Patch patch) throws DuplicatePatchNameException, IOException; // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/DuplicatePatchNameException.java // public class DuplicatePatchNameException extends CommandFailureException { // private static final long serialVersionUID = 5221931112583803769L; // // public DuplicatePatchNameException(Object source, Patch patch1, Patch patch2) { // super(source, "Duplicate patch name", "Patches name \"" + patch1.getName() + "\" conflict between " + patch1.getFile().getAbsolutePath() + " and " + patch2.getFile().getAbsolutePath()); // } // // }
import org.jsoftware.dbpatch.config.AbstractPatch; import org.jsoftware.dbpatch.config.EnvSettings; import org.jsoftware.dbpatch.config.Patch; import org.jsoftware.dbpatch.config.PatchScanner; import org.jsoftware.dbpatch.impl.DuplicatePatchNameException; import java.io.IOException; import java.sql.SQLException; import java.util.List;
package org.jsoftware.dbpatch.command; /** * Show list of patches * * @author szalik */ abstract class AbstractListCommand<P extends AbstractPatch> extends AbstractSingleConfDbPatchCommand { static final int SPACES = 46; public AbstractListCommand(EnvSettings envSettings) { super(envSettings); } /** * @return patches to apply * @throws java.io.IOException * @throws java.sql.SQLException * @throws DuplicatePatchNameException */
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractPatch.java // public abstract class AbstractPatch implements Serializable { // private static final long serialVersionUID = 4178101927323891639L; // private String name; // private int statementCount = -1; // private File file; // // public enum DbState { // COMMITTED, IN_PROGRESS, NOT_AVAILABLE // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getStatementCount() { // return statementCount; // } // // public void setStatementCount(int statementCount) { // this.statementCount = statementCount; // } // // public File getFile() { // return file; // } // // public void setFile(File file) { // this.file = file; // } // // public abstract void setDbDate(Date dbDate); // // public abstract void setDbState(DbState dbState); // // public abstract Date getDbDate(); // // public abstract DbState getDbState(); // // public abstract boolean canApply(); // // public String toString() { // return super.toString() + "-" + name; // } // // public static String normalizeName(String name) { // String nameLC = name.toLowerCase(); // while (nameLC.endsWith(".sql") || nameLC.endsWith(".undo") || nameLC.endsWith(".rollback")) { // int dot = nameLC.lastIndexOf('.'); // nameLC = nameLC.substring(0, dot); // } // return name.substring(0, nameLC.length()); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/EnvSettings.java // public class EnvSettings { // private final String prefix; // // private EnvSettings(String prefix) { // this.prefix = prefix; // } // // public String getDbPatchFile() { // return prefix + "dbpatch.file"; // } // // public String getDbPatchConfiguration() { // return prefix + "dbpatch.configuration"; // } // // public String getDbPatchStop() { // return prefix + "dbpatch.stop"; // } // // public String getDbPatchSingle() { // return prefix + "dbpatch.single"; // } // // public String getLogLevel() { // return prefix + "dbpatch.logLevel"; // } // // public static EnvSettings standalone() { // return new EnvSettings(""); // } // // public static EnvSettings maven() { // return new EnvSettings("maven."); // } // // public static EnvSettings gradle() { // return new EnvSettings("gradle."); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/PatchScanner.java // public interface PatchScanner extends Serializable { // // /** // * @param directory base dir // * @param paths to scan (add directory if not absolute) // * @return list of found patches // * @throws DuplicatePatchNameException when duplicated patch names were found // * @throws IOException io problem // */ // List<Patch> scan(File directory, String[] paths) throws DuplicatePatchNameException, IOException; // // /** // * @param patch rollbacks for this patch // * @param directory base dir // * @param paths to scan (add directory if not absolute) // * @return null if no file was found // * @throws DuplicatePatchNameException when duplicated patch names were found // * @throws IOException io problem // */ // File findRollbackFile(File directory, String[] paths, Patch patch) throws DuplicatePatchNameException, IOException; // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/DuplicatePatchNameException.java // public class DuplicatePatchNameException extends CommandFailureException { // private static final long serialVersionUID = 5221931112583803769L; // // public DuplicatePatchNameException(Object source, Patch patch1, Patch patch2) { // super(source, "Duplicate patch name", "Patches name \"" + patch1.getName() + "\" conflict between " + patch1.getFile().getAbsolutePath() + " and " + patch2.getFile().getAbsolutePath()); // } // // } // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/AbstractListCommand.java import org.jsoftware.dbpatch.config.AbstractPatch; import org.jsoftware.dbpatch.config.EnvSettings; import org.jsoftware.dbpatch.config.Patch; import org.jsoftware.dbpatch.config.PatchScanner; import org.jsoftware.dbpatch.impl.DuplicatePatchNameException; import java.io.IOException; import java.sql.SQLException; import java.util.List; package org.jsoftware.dbpatch.command; /** * Show list of patches * * @author szalik */ abstract class AbstractListCommand<P extends AbstractPatch> extends AbstractSingleConfDbPatchCommand { static final int SPACES = 46; public AbstractListCommand(EnvSettings envSettings) { super(envSettings); } /** * @return patches to apply * @throws java.io.IOException * @throws java.sql.SQLException * @throws DuplicatePatchNameException */
private List<Patch> generatePatchListAll() throws IOException, SQLException, DuplicatePatchNameException {
m-szalik/dbpatch
dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/AbstractListCommand.java
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractPatch.java // public abstract class AbstractPatch implements Serializable { // private static final long serialVersionUID = 4178101927323891639L; // private String name; // private int statementCount = -1; // private File file; // // public enum DbState { // COMMITTED, IN_PROGRESS, NOT_AVAILABLE // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getStatementCount() { // return statementCount; // } // // public void setStatementCount(int statementCount) { // this.statementCount = statementCount; // } // // public File getFile() { // return file; // } // // public void setFile(File file) { // this.file = file; // } // // public abstract void setDbDate(Date dbDate); // // public abstract void setDbState(DbState dbState); // // public abstract Date getDbDate(); // // public abstract DbState getDbState(); // // public abstract boolean canApply(); // // public String toString() { // return super.toString() + "-" + name; // } // // public static String normalizeName(String name) { // String nameLC = name.toLowerCase(); // while (nameLC.endsWith(".sql") || nameLC.endsWith(".undo") || nameLC.endsWith(".rollback")) { // int dot = nameLC.lastIndexOf('.'); // nameLC = nameLC.substring(0, dot); // } // return name.substring(0, nameLC.length()); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/EnvSettings.java // public class EnvSettings { // private final String prefix; // // private EnvSettings(String prefix) { // this.prefix = prefix; // } // // public String getDbPatchFile() { // return prefix + "dbpatch.file"; // } // // public String getDbPatchConfiguration() { // return prefix + "dbpatch.configuration"; // } // // public String getDbPatchStop() { // return prefix + "dbpatch.stop"; // } // // public String getDbPatchSingle() { // return prefix + "dbpatch.single"; // } // // public String getLogLevel() { // return prefix + "dbpatch.logLevel"; // } // // public static EnvSettings standalone() { // return new EnvSettings(""); // } // // public static EnvSettings maven() { // return new EnvSettings("maven."); // } // // public static EnvSettings gradle() { // return new EnvSettings("gradle."); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/PatchScanner.java // public interface PatchScanner extends Serializable { // // /** // * @param directory base dir // * @param paths to scan (add directory if not absolute) // * @return list of found patches // * @throws DuplicatePatchNameException when duplicated patch names were found // * @throws IOException io problem // */ // List<Patch> scan(File directory, String[] paths) throws DuplicatePatchNameException, IOException; // // /** // * @param patch rollbacks for this patch // * @param directory base dir // * @param paths to scan (add directory if not absolute) // * @return null if no file was found // * @throws DuplicatePatchNameException when duplicated patch names were found // * @throws IOException io problem // */ // File findRollbackFile(File directory, String[] paths, Patch patch) throws DuplicatePatchNameException, IOException; // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/DuplicatePatchNameException.java // public class DuplicatePatchNameException extends CommandFailureException { // private static final long serialVersionUID = 5221931112583803769L; // // public DuplicatePatchNameException(Object source, Patch patch1, Patch patch2) { // super(source, "Duplicate patch name", "Patches name \"" + patch1.getName() + "\" conflict between " + patch1.getFile().getAbsolutePath() + " and " + patch2.getFile().getAbsolutePath()); // } // // }
import org.jsoftware.dbpatch.config.AbstractPatch; import org.jsoftware.dbpatch.config.EnvSettings; import org.jsoftware.dbpatch.config.Patch; import org.jsoftware.dbpatch.config.PatchScanner; import org.jsoftware.dbpatch.impl.DuplicatePatchNameException; import java.io.IOException; import java.sql.SQLException; import java.util.List;
package org.jsoftware.dbpatch.command; /** * Show list of patches * * @author szalik */ abstract class AbstractListCommand<P extends AbstractPatch> extends AbstractSingleConfDbPatchCommand { static final int SPACES = 46; public AbstractListCommand(EnvSettings envSettings) { super(envSettings); } /** * @return patches to apply * @throws java.io.IOException * @throws java.sql.SQLException * @throws DuplicatePatchNameException */ private List<Patch> generatePatchListAll() throws IOException, SQLException, DuplicatePatchNameException {
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/AbstractPatch.java // public abstract class AbstractPatch implements Serializable { // private static final long serialVersionUID = 4178101927323891639L; // private String name; // private int statementCount = -1; // private File file; // // public enum DbState { // COMMITTED, IN_PROGRESS, NOT_AVAILABLE // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public int getStatementCount() { // return statementCount; // } // // public void setStatementCount(int statementCount) { // this.statementCount = statementCount; // } // // public File getFile() { // return file; // } // // public void setFile(File file) { // this.file = file; // } // // public abstract void setDbDate(Date dbDate); // // public abstract void setDbState(DbState dbState); // // public abstract Date getDbDate(); // // public abstract DbState getDbState(); // // public abstract boolean canApply(); // // public String toString() { // return super.toString() + "-" + name; // } // // public static String normalizeName(String name) { // String nameLC = name.toLowerCase(); // while (nameLC.endsWith(".sql") || nameLC.endsWith(".undo") || nameLC.endsWith(".rollback")) { // int dot = nameLC.lastIndexOf('.'); // nameLC = nameLC.substring(0, dot); // } // return name.substring(0, nameLC.length()); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/EnvSettings.java // public class EnvSettings { // private final String prefix; // // private EnvSettings(String prefix) { // this.prefix = prefix; // } // // public String getDbPatchFile() { // return prefix + "dbpatch.file"; // } // // public String getDbPatchConfiguration() { // return prefix + "dbpatch.configuration"; // } // // public String getDbPatchStop() { // return prefix + "dbpatch.stop"; // } // // public String getDbPatchSingle() { // return prefix + "dbpatch.single"; // } // // public String getLogLevel() { // return prefix + "dbpatch.logLevel"; // } // // public static EnvSettings standalone() { // return new EnvSettings(""); // } // // public static EnvSettings maven() { // return new EnvSettings("maven."); // } // // public static EnvSettings gradle() { // return new EnvSettings("gradle."); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/PatchScanner.java // public interface PatchScanner extends Serializable { // // /** // * @param directory base dir // * @param paths to scan (add directory if not absolute) // * @return list of found patches // * @throws DuplicatePatchNameException when duplicated patch names were found // * @throws IOException io problem // */ // List<Patch> scan(File directory, String[] paths) throws DuplicatePatchNameException, IOException; // // /** // * @param patch rollbacks for this patch // * @param directory base dir // * @param paths to scan (add directory if not absolute) // * @return null if no file was found // * @throws DuplicatePatchNameException when duplicated patch names were found // * @throws IOException io problem // */ // File findRollbackFile(File directory, String[] paths, Patch patch) throws DuplicatePatchNameException, IOException; // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/DuplicatePatchNameException.java // public class DuplicatePatchNameException extends CommandFailureException { // private static final long serialVersionUID = 5221931112583803769L; // // public DuplicatePatchNameException(Object source, Patch patch1, Patch patch2) { // super(source, "Duplicate patch name", "Patches name \"" + patch1.getName() + "\" conflict between " + patch1.getFile().getAbsolutePath() + " and " + patch2.getFile().getAbsolutePath()); // } // // } // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/AbstractListCommand.java import org.jsoftware.dbpatch.config.AbstractPatch; import org.jsoftware.dbpatch.config.EnvSettings; import org.jsoftware.dbpatch.config.Patch; import org.jsoftware.dbpatch.config.PatchScanner; import org.jsoftware.dbpatch.impl.DuplicatePatchNameException; import java.io.IOException; import java.sql.SQLException; import java.util.List; package org.jsoftware.dbpatch.command; /** * Show list of patches * * @author szalik */ abstract class AbstractListCommand<P extends AbstractPatch> extends AbstractSingleConfDbPatchCommand { static final int SPACES = 46; public AbstractListCommand(EnvSettings envSettings) { super(envSettings); } /** * @return patches to apply * @throws java.io.IOException * @throws java.sql.SQLException * @throws DuplicatePatchNameException */ private List<Patch> generatePatchListAll() throws IOException, SQLException, DuplicatePatchNameException {
PatchScanner scanner = configurationEntry.getPatchScanner();
m-szalik/dbpatch
dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/dialect/OracleDialect.java
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/CloseUtil.java // public class CloseUtil { // // private CloseUtil() { // } // // public static void close(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Statement statement) { // try { // if (statement != null) { // statement.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Connection conn) { // try { // if (conn != null) { // conn.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(ResultSet rs) { // try { // if (rs != null) { // rs.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // }
import org.jsoftware.dbpatch.impl.CloseUtil; import org.jsoftware.dbpatch.impl.PatchStatement; import java.sql.*;
if (sql.toLowerCase().startsWith("execute ")) { sql = sql.substring(8); sql = "{ call " + sql + " }"; PatchExecutionResultImpl result = new PatchExecutionResultImpl(ps); try { c.clearWarnings(); CallableStatement p = c.prepareCall(sql); p.execute(); p.close(); result.setSqlWarning(c.getWarnings()); } catch (SQLException e) { result.setCause(e); } return result; } return super.executeStatement(c, ps); } public Timestamp getNow(Connection con) throws SQLException { Statement stm = null; ResultSet rs = null; try { stm = con.createStatement(); rs = stm.executeQuery("SELECT sysdate FROM dual"); if (! rs.next()) { throw new SQLException("No rows returned."); } return rs.getTimestamp(1); } finally {
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/CloseUtil.java // public class CloseUtil { // // private CloseUtil() { // } // // public static void close(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Statement statement) { // try { // if (statement != null) { // statement.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Connection conn) { // try { // if (conn != null) { // conn.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(ResultSet rs) { // try { // if (rs != null) { // rs.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // } // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/dialect/OracleDialect.java import org.jsoftware.dbpatch.impl.CloseUtil; import org.jsoftware.dbpatch.impl.PatchStatement; import java.sql.*; if (sql.toLowerCase().startsWith("execute ")) { sql = sql.substring(8); sql = "{ call " + sql + " }"; PatchExecutionResultImpl result = new PatchExecutionResultImpl(ps); try { c.clearWarnings(); CallableStatement p = c.prepareCall(sql); p.execute(); p.close(); result.setSqlWarning(c.getWarnings()); } catch (SQLException e) { result.setCause(e); } return result; } return super.executeStatement(c, ps); } public Timestamp getNow(Connection con) throws SQLException { Statement stm = null; ResultSet rs = null; try { stm = con.createStatement(); rs = stm.executeQuery("SELECT sysdate FROM dual"); if (! rs.next()) { throw new SQLException("No rows returned."); } return rs.getTimestamp(1); } finally {
CloseUtil.close(rs);
m-szalik/dbpatch
dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/dialect/HsqlDialect.java
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/CloseUtil.java // public class CloseUtil { // // private CloseUtil() { // } // // public static void close(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Statement statement) { // try { // if (statement != null) { // statement.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Connection conn) { // try { // if (conn != null) { // conn.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(ResultSet rs) { // try { // if (rs != null) { // rs.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // }
import org.jsoftware.dbpatch.impl.CloseUtil; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp;
package org.jsoftware.dbpatch.config.dialect; /** * HsqlDb dialect * * @author szalik */ public class HsqlDialect extends DefaultDialect { private static final long serialVersionUID = -1090776645312248L; public Timestamp getNow(Connection con) throws SQLException { Statement stm = null; ResultSet rs = null; try { stm = con.createStatement(); rs = stm.executeQuery("VALUES (CURRENT_TIMESTAMP)"); if (rs.next()) { return rs.getTimestamp(1); } else { throw new SQLException("No rows returned."); } } finally {
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/CloseUtil.java // public class CloseUtil { // // private CloseUtil() { // } // // public static void close(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Statement statement) { // try { // if (statement != null) { // statement.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Connection conn) { // try { // if (conn != null) { // conn.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(ResultSet rs) { // try { // if (rs != null) { // rs.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // } // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/dialect/HsqlDialect.java import org.jsoftware.dbpatch.impl.CloseUtil; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; package org.jsoftware.dbpatch.config.dialect; /** * HsqlDb dialect * * @author szalik */ public class HsqlDialect extends DefaultDialect { private static final long serialVersionUID = -1090776645312248L; public Timestamp getNow(Connection con) throws SQLException { Statement stm = null; ResultSet rs = null; try { stm = con.createStatement(); rs = stm.executeQuery("VALUES (CURRENT_TIMESTAMP)"); if (rs.next()) { return rs.getTimestamp(1); } else { throw new SQLException("No rows returned."); } } finally {
CloseUtil.close(rs);
m-szalik/dbpatch
dbpatch-maven-plugin/src/main/java/org/jsoftware/dbpatch/maven/CommandMojoAdapter.java
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/AbstractCommand.java // public abstract class AbstractCommand { // protected final org.jsoftware.dbpatch.log.Log log = LogFactory.getInstance(); // protected final EnvSettings envSettings; // private File configFile; // protected ConfigurationEntry configurationEntry; // protected File directory; // // protected AbstractCommand(EnvSettings envSettings) { // this.envSettings = envSettings; // } // // public void setConfigFile(File configFile) { // this.configFile = configFile; // } // // public void setConf(ConfigurationEntry conf) { // this.configurationEntry = conf; // } // // public void setDirectory(File directory) { // this.directory = directory; // } // // public File getConfigFile() { // if (configFile != null) { // return configFile; // } // String cFile = System.getProperty(envSettings.getDbPatchFile()); // if (cFile != null) { // return new File(cFile); // } else { // return null; // } // } // // public ConfigurationEntry getConf() { // return configurationEntry; /* findBugs ok - unwritten field (maven writes it) */ // } // // // public abstract void execute() throws CommandExecutionException, CommandFailureException; // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/CommandExecutionException.java // public class CommandExecutionException extends Exception { // public CommandExecutionException(String message) { // super(message); // } // // public CommandExecutionException(String message, Throwable init) { // super(message); // initCause(init); // } // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/CommandFailureException.java // public class CommandFailureException extends Exception { // private final Object source; // private final String messageString, descriptionString; // // public CommandFailureException(Object source, String message, String description) { // super(message + " - " + description); // this.source = source; // this.messageString = message; // this.descriptionString = description; // } // // public CommandFailureException(String message) { // super(message); // this.messageString = message; // this.source = null; // this.descriptionString = null; // } // // public Object getSource() { // return source; // } // // public String getMessageString() { // return messageString; // } // // public String getDescriptionString() { // return descriptionString; // } // }
import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.logging.Log; import org.jsoftware.dbpatch.command.AbstractCommand; import org.jsoftware.dbpatch.command.CommandExecutionException; import org.jsoftware.dbpatch.command.CommandFailureException; import org.jsoftware.dbpatch.log.LogFactory; import java.io.File;
package org.jsoftware.dbpatch.maven; /** * Abstract mojo for dbPatch plugin goals * * @author szalik */ public class CommandMojoAdapter<C extends AbstractCommand> extends AbstractMojo { protected final C command; /** * Configuration file * * @parameter */ protected File configFile; /** * Daatabase and patch configuration * * @parameter * @see ConfigurationEntry fields */ protected ConfigurationEntry conf; /** * Project directory * * @parameter default-value="${basedir}" * @required * @readonly */ protected File directory; protected CommandMojoAdapter(C command) { this.command = command; } public void setLog(Log log) { super.setLog(log); if (log != null) { LogFactory.init(new MavenLog(log)); } } public void execute() throws MojoExecutionException, MojoFailureException { Log log = getLog(); if (System.getProperty("maven.dbpatch.skip") != null) { log.debug("dbpatch skipped"); return; } command.setConf(conf); command.setDirectory(directory); command.setConfigFile(configFile); setup(command); try { command.execute();
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/AbstractCommand.java // public abstract class AbstractCommand { // protected final org.jsoftware.dbpatch.log.Log log = LogFactory.getInstance(); // protected final EnvSettings envSettings; // private File configFile; // protected ConfigurationEntry configurationEntry; // protected File directory; // // protected AbstractCommand(EnvSettings envSettings) { // this.envSettings = envSettings; // } // // public void setConfigFile(File configFile) { // this.configFile = configFile; // } // // public void setConf(ConfigurationEntry conf) { // this.configurationEntry = conf; // } // // public void setDirectory(File directory) { // this.directory = directory; // } // // public File getConfigFile() { // if (configFile != null) { // return configFile; // } // String cFile = System.getProperty(envSettings.getDbPatchFile()); // if (cFile != null) { // return new File(cFile); // } else { // return null; // } // } // // public ConfigurationEntry getConf() { // return configurationEntry; /* findBugs ok - unwritten field (maven writes it) */ // } // // // public abstract void execute() throws CommandExecutionException, CommandFailureException; // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/CommandExecutionException.java // public class CommandExecutionException extends Exception { // public CommandExecutionException(String message) { // super(message); // } // // public CommandExecutionException(String message, Throwable init) { // super(message); // initCause(init); // } // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/CommandFailureException.java // public class CommandFailureException extends Exception { // private final Object source; // private final String messageString, descriptionString; // // public CommandFailureException(Object source, String message, String description) { // super(message + " - " + description); // this.source = source; // this.messageString = message; // this.descriptionString = description; // } // // public CommandFailureException(String message) { // super(message); // this.messageString = message; // this.source = null; // this.descriptionString = null; // } // // public Object getSource() { // return source; // } // // public String getMessageString() { // return messageString; // } // // public String getDescriptionString() { // return descriptionString; // } // } // Path: dbpatch-maven-plugin/src/main/java/org/jsoftware/dbpatch/maven/CommandMojoAdapter.java import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.logging.Log; import org.jsoftware.dbpatch.command.AbstractCommand; import org.jsoftware.dbpatch.command.CommandExecutionException; import org.jsoftware.dbpatch.command.CommandFailureException; import org.jsoftware.dbpatch.log.LogFactory; import java.io.File; package org.jsoftware.dbpatch.maven; /** * Abstract mojo for dbPatch plugin goals * * @author szalik */ public class CommandMojoAdapter<C extends AbstractCommand> extends AbstractMojo { protected final C command; /** * Configuration file * * @parameter */ protected File configFile; /** * Daatabase and patch configuration * * @parameter * @see ConfigurationEntry fields */ protected ConfigurationEntry conf; /** * Project directory * * @parameter default-value="${basedir}" * @required * @readonly */ protected File directory; protected CommandMojoAdapter(C command) { this.command = command; } public void setLog(Log log) { super.setLog(log); if (log != null) { LogFactory.init(new MavenLog(log)); } } public void execute() throws MojoExecutionException, MojoFailureException { Log log = getLog(); if (System.getProperty("maven.dbpatch.skip") != null) { log.debug("dbpatch skipped"); return; } command.setConf(conf); command.setDirectory(directory); command.setConfigFile(configFile); setup(command); try { command.execute();
} catch (CommandExecutionException e) {
m-szalik/dbpatch
dbpatch-maven-plugin/src/main/java/org/jsoftware/dbpatch/maven/CommandMojoAdapter.java
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/AbstractCommand.java // public abstract class AbstractCommand { // protected final org.jsoftware.dbpatch.log.Log log = LogFactory.getInstance(); // protected final EnvSettings envSettings; // private File configFile; // protected ConfigurationEntry configurationEntry; // protected File directory; // // protected AbstractCommand(EnvSettings envSettings) { // this.envSettings = envSettings; // } // // public void setConfigFile(File configFile) { // this.configFile = configFile; // } // // public void setConf(ConfigurationEntry conf) { // this.configurationEntry = conf; // } // // public void setDirectory(File directory) { // this.directory = directory; // } // // public File getConfigFile() { // if (configFile != null) { // return configFile; // } // String cFile = System.getProperty(envSettings.getDbPatchFile()); // if (cFile != null) { // return new File(cFile); // } else { // return null; // } // } // // public ConfigurationEntry getConf() { // return configurationEntry; /* findBugs ok - unwritten field (maven writes it) */ // } // // // public abstract void execute() throws CommandExecutionException, CommandFailureException; // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/CommandExecutionException.java // public class CommandExecutionException extends Exception { // public CommandExecutionException(String message) { // super(message); // } // // public CommandExecutionException(String message, Throwable init) { // super(message); // initCause(init); // } // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/CommandFailureException.java // public class CommandFailureException extends Exception { // private final Object source; // private final String messageString, descriptionString; // // public CommandFailureException(Object source, String message, String description) { // super(message + " - " + description); // this.source = source; // this.messageString = message; // this.descriptionString = description; // } // // public CommandFailureException(String message) { // super(message); // this.messageString = message; // this.source = null; // this.descriptionString = null; // } // // public Object getSource() { // return source; // } // // public String getMessageString() { // return messageString; // } // // public String getDescriptionString() { // return descriptionString; // } // }
import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.logging.Log; import org.jsoftware.dbpatch.command.AbstractCommand; import org.jsoftware.dbpatch.command.CommandExecutionException; import org.jsoftware.dbpatch.command.CommandFailureException; import org.jsoftware.dbpatch.log.LogFactory; import java.io.File;
protected CommandMojoAdapter(C command) { this.command = command; } public void setLog(Log log) { super.setLog(log); if (log != null) { LogFactory.init(new MavenLog(log)); } } public void execute() throws MojoExecutionException, MojoFailureException { Log log = getLog(); if (System.getProperty("maven.dbpatch.skip") != null) { log.debug("dbpatch skipped"); return; } command.setConf(conf); command.setDirectory(directory); command.setConfigFile(configFile); setup(command); try { command.execute(); } catch (CommandExecutionException e) { MojoExecutionException mojoExecutionException = new MojoExecutionException(command, e.getMessage(), ""); mojoExecutionException.initCause(e); throw mojoExecutionException;
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/AbstractCommand.java // public abstract class AbstractCommand { // protected final org.jsoftware.dbpatch.log.Log log = LogFactory.getInstance(); // protected final EnvSettings envSettings; // private File configFile; // protected ConfigurationEntry configurationEntry; // protected File directory; // // protected AbstractCommand(EnvSettings envSettings) { // this.envSettings = envSettings; // } // // public void setConfigFile(File configFile) { // this.configFile = configFile; // } // // public void setConf(ConfigurationEntry conf) { // this.configurationEntry = conf; // } // // public void setDirectory(File directory) { // this.directory = directory; // } // // public File getConfigFile() { // if (configFile != null) { // return configFile; // } // String cFile = System.getProperty(envSettings.getDbPatchFile()); // if (cFile != null) { // return new File(cFile); // } else { // return null; // } // } // // public ConfigurationEntry getConf() { // return configurationEntry; /* findBugs ok - unwritten field (maven writes it) */ // } // // // public abstract void execute() throws CommandExecutionException, CommandFailureException; // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/CommandExecutionException.java // public class CommandExecutionException extends Exception { // public CommandExecutionException(String message) { // super(message); // } // // public CommandExecutionException(String message, Throwable init) { // super(message); // initCause(init); // } // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/CommandFailureException.java // public class CommandFailureException extends Exception { // private final Object source; // private final String messageString, descriptionString; // // public CommandFailureException(Object source, String message, String description) { // super(message + " - " + description); // this.source = source; // this.messageString = message; // this.descriptionString = description; // } // // public CommandFailureException(String message) { // super(message); // this.messageString = message; // this.source = null; // this.descriptionString = null; // } // // public Object getSource() { // return source; // } // // public String getMessageString() { // return messageString; // } // // public String getDescriptionString() { // return descriptionString; // } // } // Path: dbpatch-maven-plugin/src/main/java/org/jsoftware/dbpatch/maven/CommandMojoAdapter.java import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.logging.Log; import org.jsoftware.dbpatch.command.AbstractCommand; import org.jsoftware.dbpatch.command.CommandExecutionException; import org.jsoftware.dbpatch.command.CommandFailureException; import org.jsoftware.dbpatch.log.LogFactory; import java.io.File; protected CommandMojoAdapter(C command) { this.command = command; } public void setLog(Log log) { super.setLog(log); if (log != null) { LogFactory.init(new MavenLog(log)); } } public void execute() throws MojoExecutionException, MojoFailureException { Log log = getLog(); if (System.getProperty("maven.dbpatch.skip") != null) { log.debug("dbpatch skipped"); return; } command.setConf(conf); command.setDirectory(directory); command.setConfigFile(configFile); setup(command); try { command.execute(); } catch (CommandExecutionException e) { MojoExecutionException mojoExecutionException = new MojoExecutionException(command, e.getMessage(), ""); mojoExecutionException.initCause(e); throw mojoExecutionException;
} catch (CommandFailureException e) {
m-szalik/dbpatch
dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/HelpCommand.java
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/EnvSettings.java // public class EnvSettings { // private final String prefix; // // private EnvSettings(String prefix) { // this.prefix = prefix; // } // // public String getDbPatchFile() { // return prefix + "dbpatch.file"; // } // // public String getDbPatchConfiguration() { // return prefix + "dbpatch.configuration"; // } // // public String getDbPatchStop() { // return prefix + "dbpatch.stop"; // } // // public String getDbPatchSingle() { // return prefix + "dbpatch.single"; // } // // public String getLogLevel() { // return prefix + "dbpatch.logLevel"; // } // // public static EnvSettings standalone() { // return new EnvSettings(""); // } // // public static EnvSettings maven() { // return new EnvSettings("maven."); // } // // public static EnvSettings gradle() { // return new EnvSettings("gradle."); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/CloseUtil.java // public class CloseUtil { // // private CloseUtil() { // } // // public static void close(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Statement statement) { // try { // if (statement != null) { // statement.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Connection conn) { // try { // if (conn != null) { // conn.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(ResultSet rs) { // try { // if (rs != null) { // rs.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // }
import org.jsoftware.dbpatch.config.EnvSettings; import org.jsoftware.dbpatch.impl.CloseUtil; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.regex.Pattern;
package org.jsoftware.dbpatch.command; /** * Command: Display help * * @author szalik */ public class HelpCommand extends AbstractCommand { private static final Pattern TASK_PREFIX_PATTERN = Pattern.compile("\\[prefix:task\\]"); private static final Pattern PROPERTY_PREFIX_PATTERN = Pattern.compile("\\[prefix:property\\]"); private final String taskPrefix, propertyPrefix; private final String commandTitle;
// Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/config/EnvSettings.java // public class EnvSettings { // private final String prefix; // // private EnvSettings(String prefix) { // this.prefix = prefix; // } // // public String getDbPatchFile() { // return prefix + "dbpatch.file"; // } // // public String getDbPatchConfiguration() { // return prefix + "dbpatch.configuration"; // } // // public String getDbPatchStop() { // return prefix + "dbpatch.stop"; // } // // public String getDbPatchSingle() { // return prefix + "dbpatch.single"; // } // // public String getLogLevel() { // return prefix + "dbpatch.logLevel"; // } // // public static EnvSettings standalone() { // return new EnvSettings(""); // } // // public static EnvSettings maven() { // return new EnvSettings("maven."); // } // // public static EnvSettings gradle() { // return new EnvSettings("gradle."); // } // // } // // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/impl/CloseUtil.java // public class CloseUtil { // // private CloseUtil() { // } // // public static void close(Closeable closeable) { // try { // if (closeable != null) { // closeable.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Statement statement) { // try { // if (statement != null) { // statement.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(Connection conn) { // try { // if (conn != null) { // conn.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // public static void close(ResultSet rs) { // try { // if (rs != null) { // rs.close(); // } // } catch (Exception e) { /* findBugs ok */ } // } // // } // Path: dbpatch-core/src/main/java/org/jsoftware/dbpatch/command/HelpCommand.java import org.jsoftware.dbpatch.config.EnvSettings; import org.jsoftware.dbpatch.impl.CloseUtil; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.regex.Pattern; package org.jsoftware.dbpatch.command; /** * Command: Display help * * @author szalik */ public class HelpCommand extends AbstractCommand { private static final Pattern TASK_PREFIX_PATTERN = Pattern.compile("\\[prefix:task\\]"); private static final Pattern PROPERTY_PREFIX_PATTERN = Pattern.compile("\\[prefix:property\\]"); private final String taskPrefix, propertyPrefix; private final String commandTitle;
private HelpCommand(EnvSettings envSettings, String taskPrefix, String propertyPrefix, String commandTitle) {