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 |
|---|---|---|---|---|---|---|
jcommon/process | src/main/java/jcommon/process/platform/win32/IOCPBUFFER.java | // Path: src/main/java/jcommon/process/api/JNAUtils.java
// public static <T> List<T> fromSeq(T...iterable) {
// return Arrays.asList(iterable);
// }
| import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import java.util.List;
import static jcommon.process.api.JNAUtils.fromSeq; | package jcommon.process.platform.win32;
public class IOCPBUFFER extends Structure {
public Pointer buffer;
public int bufferSize;
public int sequenceNumber;
public int bytesTransferred;
| // Path: src/main/java/jcommon/process/api/JNAUtils.java
// public static <T> List<T> fromSeq(T...iterable) {
// return Arrays.asList(iterable);
// }
// Path: src/main/java/jcommon/process/platform/win32/IOCPBUFFER.java
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import java.util.List;
import static jcommon.process.api.JNAUtils.fromSeq;
package jcommon.process.platform.win32;
public class IOCPBUFFER extends Structure {
public Pointer buffer;
public int bufferSize;
public int sequenceNumber;
public int bytesTransferred;
| private static final List FIELD_ORDER = fromSeq( |
jcommon/process | src/main/java/jcommon/process/ProcessBuilder.java | // Path: src/main/java/jcommon/process/platform/IProcessLauncher.java
// public interface IProcessLauncher extends IPlatformImplementation {
// public static class Default implements IProcessLauncher, Serializable {
// public static final IProcessLauncher INSTANCE = new Default();
//
// private Default() {
// //Prevent outside instantiation
// }
//
// private Object readResolve() {
// return INSTANCE;
// }
//
// @Override
// public final IEnvironmentVariableBlock requestParentEnvironmentVariableBlock() {
// return null;
// }
//
// @Override
// public final IProcess launch(final boolean inherit_parent_environment, final IEnvironmentVariableBlock environment_variables, final String[] command_line, final IProcessListener[] listeners) {
// throw new UnsupportedOperationException("launch");
// }
// }
//
// public static final IProcessLauncher DEFAULT = Default.INSTANCE;
//
// IEnvironmentVariableBlock requestParentEnvironmentVariableBlock();
// IProcess launch(final boolean inherit_parent_environment, final IEnvironmentVariableBlock environment_variables, final String[] command_line, final IProcessListener[] listeners);
// }
| import java.util.*;
import jcommon.core.StringUtil;
import jcommon.core.platform.PlatformProviders;
import jcommon.process.platform.IProcessLauncher; | /*
Copyright (C) 2013 the original author or authors.
See the LICENSE.txt file distributed with this work for additional
information regarding copyright ownership.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package jcommon.process;
/**
* Configures a child process for execution using the builder pattern.
*
* This class is <b>not</b> thread safe.
*/
@SuppressWarnings("unused")
public class ProcessBuilder implements Cloneable { | // Path: src/main/java/jcommon/process/platform/IProcessLauncher.java
// public interface IProcessLauncher extends IPlatformImplementation {
// public static class Default implements IProcessLauncher, Serializable {
// public static final IProcessLauncher INSTANCE = new Default();
//
// private Default() {
// //Prevent outside instantiation
// }
//
// private Object readResolve() {
// return INSTANCE;
// }
//
// @Override
// public final IEnvironmentVariableBlock requestParentEnvironmentVariableBlock() {
// return null;
// }
//
// @Override
// public final IProcess launch(final boolean inherit_parent_environment, final IEnvironmentVariableBlock environment_variables, final String[] command_line, final IProcessListener[] listeners) {
// throw new UnsupportedOperationException("launch");
// }
// }
//
// public static final IProcessLauncher DEFAULT = Default.INSTANCE;
//
// IEnvironmentVariableBlock requestParentEnvironmentVariableBlock();
// IProcess launch(final boolean inherit_parent_environment, final IEnvironmentVariableBlock environment_variables, final String[] command_line, final IProcessListener[] listeners);
// }
// Path: src/main/java/jcommon/process/ProcessBuilder.java
import java.util.*;
import jcommon.core.StringUtil;
import jcommon.core.platform.PlatformProviders;
import jcommon.process.platform.IProcessLauncher;
/*
Copyright (C) 2013 the original author or authors.
See the LICENSE.txt file distributed with this work for additional
information regarding copyright ownership.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package jcommon.process;
/**
* Configures a child process for execution using the builder pattern.
*
* This class is <b>not</b> thread safe.
*/
@SuppressWarnings("unused")
public class ProcessBuilder implements Cloneable { | private static final IProcessLauncher impl = PlatformProviders.find(IProcessLauncher.class, IProcessLauncher.DEFAULT); |
jcommon/process | src/main/java/jcommon/process/api/win32/Win32Utils.java | // Path: src/main/java/jcommon/process/api/PinnableMemory.java
// public final class PinnableMemory extends Memory {
// private static final Map<Pointer, PinnableMemory> pinned = new HashMap<Pointer, PinnableMemory>(2, 1.0f);
// private static final Map<Pointer, IPinListener> listeners = new HashMap<Pointer, IPinListener>(2, 1.0f);
// private static final Object pin_lock = new Object();
// private static final Object listeners_lock = new Object();
// private boolean disposed = false;
//
// public static interface IPinListener {
// boolean unpinned(Pointer memory);
// }
//
// public PinnableMemory(long size) {
// super(size);
// }
//
// /**
// * Publicly-accessible form of {@link com.sun.jna.Memory#dispose()}.
// */
// public void dispose() {
// synchronized (this) {
// if (disposed)
// return;
// disposed = true;
//
// super.dispose();
// }
// }
//
// @Override
// protected void finalize() {
// //Do NOT call super.dispose();
// //We want to ensure that the semantics of our version is
// //used and to insulate against any future changes.
// dispose();
// }
//
// public PinnableMemory pin() {
// return this.pin(null);
// }
//
// public PinnableMemory pin(final IPinListener listener) {
// synchronized (pin_lock) {
// pinned.put(this, this);
// }
//
// synchronized (listeners_lock) {
// if (listener != null) {
// listeners.put(this, listener);
// }
// }
//
// return this;
// }
//
// public PinnableMemory unpin() {
// synchronized (pin_lock) {
// pinned.remove(this);
// }
//
// final IPinListener listener;
// synchronized (listeners_lock) {
// listener = listeners.remove(this);
// }
//
// if (listener != null) {
// if (listener.unpinned(this)) {
// dispose();
// }
// //If the listener returns false, then we do not
// //explicitly dispose of the memory -- the user will
// //need to take care of that himself.
// } else {
// dispose();
// }
// return this;
// }
//
// public static PinnableMemory pin(final long size) {
// return new PinnableMemory(size).pin();
// }
//
// public static PinnableMemory pin(final long size, final IPinListener listener) {
// return new PinnableMemory(size).pin(listener);
// }
//
// public static PinnableMemory unpin(Pointer ptr) {
// final PinnableMemory mem;
//
// synchronized (pin_lock) {
// mem = pinned.remove(ptr);
// }
//
// final IPinListener listener;
// synchronized (listeners_lock) {
// listener = listeners.remove(ptr);
// }
//
// if (listener != null) {
// if (listener.unpinned(ptr)) {
// if (ptr instanceof PinnableMemory)
// ((PinnableMemory)ptr).dispose();
// }
// //If the listener returns false, then we do not
// //explicitly dispose of the memory -- the user will
// //need to take care of that himself.
// }
//
// return mem;
// }
//
// public static void dispose(Pointer ptr) {
// final PinnableMemory mem;
// synchronized (pin_lock) {
// mem = pinned.remove(ptr);
// }
//
// if (mem != null) {
// mem.dispose();
// }
// }
// }
| import java.io.UnsupportedEncodingException;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import jcommon.process.api.PinnableMemory; | /*
Copyright (C) 2013 the original author or authors.
See the LICENSE.txt file distributed with this work for additional
information regarding copyright ownership.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package jcommon.process.api.win32;
/**
*
*/
public class Win32Utils {
/**
* LPTSTRs are not constant and can be modified in-memory. So it's
* important that we create a representation of the String that can
* be modified.
*
* @param value The {@link String} to represent.
* @return A pointer to the modifiable {@link String}.
*/
public static Pointer toLPTSTR(String value) {
return toLPTSTR(value, Win32Library.USE_UNICODE);
}
/**
* LPTSTRs are not constant and can be modified in-memory. So it's
* important that we create a representation of the String that can
* be modified.
*
* @param value The {@link String} to represent.
* @param wide <code>true</code> if the value {@link String} is wide, <code>false</code> otherwise.
* @return A pointer to the modifiable {@link String}.
*/
@SuppressWarnings("deprecation")
public static Pointer toLPTSTR(String value, boolean wide) { | // Path: src/main/java/jcommon/process/api/PinnableMemory.java
// public final class PinnableMemory extends Memory {
// private static final Map<Pointer, PinnableMemory> pinned = new HashMap<Pointer, PinnableMemory>(2, 1.0f);
// private static final Map<Pointer, IPinListener> listeners = new HashMap<Pointer, IPinListener>(2, 1.0f);
// private static final Object pin_lock = new Object();
// private static final Object listeners_lock = new Object();
// private boolean disposed = false;
//
// public static interface IPinListener {
// boolean unpinned(Pointer memory);
// }
//
// public PinnableMemory(long size) {
// super(size);
// }
//
// /**
// * Publicly-accessible form of {@link com.sun.jna.Memory#dispose()}.
// */
// public void dispose() {
// synchronized (this) {
// if (disposed)
// return;
// disposed = true;
//
// super.dispose();
// }
// }
//
// @Override
// protected void finalize() {
// //Do NOT call super.dispose();
// //We want to ensure that the semantics of our version is
// //used and to insulate against any future changes.
// dispose();
// }
//
// public PinnableMemory pin() {
// return this.pin(null);
// }
//
// public PinnableMemory pin(final IPinListener listener) {
// synchronized (pin_lock) {
// pinned.put(this, this);
// }
//
// synchronized (listeners_lock) {
// if (listener != null) {
// listeners.put(this, listener);
// }
// }
//
// return this;
// }
//
// public PinnableMemory unpin() {
// synchronized (pin_lock) {
// pinned.remove(this);
// }
//
// final IPinListener listener;
// synchronized (listeners_lock) {
// listener = listeners.remove(this);
// }
//
// if (listener != null) {
// if (listener.unpinned(this)) {
// dispose();
// }
// //If the listener returns false, then we do not
// //explicitly dispose of the memory -- the user will
// //need to take care of that himself.
// } else {
// dispose();
// }
// return this;
// }
//
// public static PinnableMemory pin(final long size) {
// return new PinnableMemory(size).pin();
// }
//
// public static PinnableMemory pin(final long size, final IPinListener listener) {
// return new PinnableMemory(size).pin(listener);
// }
//
// public static PinnableMemory unpin(Pointer ptr) {
// final PinnableMemory mem;
//
// synchronized (pin_lock) {
// mem = pinned.remove(ptr);
// }
//
// final IPinListener listener;
// synchronized (listeners_lock) {
// listener = listeners.remove(ptr);
// }
//
// if (listener != null) {
// if (listener.unpinned(ptr)) {
// if (ptr instanceof PinnableMemory)
// ((PinnableMemory)ptr).dispose();
// }
// //If the listener returns false, then we do not
// //explicitly dispose of the memory -- the user will
// //need to take care of that himself.
// }
//
// return mem;
// }
//
// public static void dispose(Pointer ptr) {
// final PinnableMemory mem;
// synchronized (pin_lock) {
// mem = pinned.remove(ptr);
// }
//
// if (mem != null) {
// mem.dispose();
// }
// }
// }
// Path: src/main/java/jcommon/process/api/win32/Win32Utils.java
import java.io.UnsupportedEncodingException;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import jcommon.process.api.PinnableMemory;
/*
Copyright (C) 2013 the original author or authors.
See the LICENSE.txt file distributed with this work for additional
information regarding copyright ownership.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package jcommon.process.api.win32;
/**
*
*/
public class Win32Utils {
/**
* LPTSTRs are not constant and can be modified in-memory. So it's
* important that we create a representation of the String that can
* be modified.
*
* @param value The {@link String} to represent.
* @return A pointer to the modifiable {@link String}.
*/
public static Pointer toLPTSTR(String value) {
return toLPTSTR(value, Win32Library.USE_UNICODE);
}
/**
* LPTSTRs are not constant and can be modified in-memory. So it's
* important that we create a representation of the String that can
* be modified.
*
* @param value The {@link String} to represent.
* @param wide <code>true</code> if the value {@link String} is wide, <code>false</code> otherwise.
* @return A pointer to the modifiable {@link String}.
*/
@SuppressWarnings("deprecation")
public static Pointer toLPTSTR(String value, boolean wide) { | PinnableMemory ptr = null; |
jcommon/process | src/main/java/jcommon/process/platform/win32/CONTEXT.java | // Path: src/main/java/jcommon/process/api/JNAUtils.java
// public static <T> List<T> fromSeq(T...iterable) {
// return Arrays.asList(iterable);
// }
| import com.sun.jna.Structure;
import java.util.List;
import static jcommon.process.api.JNAUtils.fromSeq; | package jcommon.process.platform.win32;
public class CONTEXT extends Structure {
public int sentinel;
| // Path: src/main/java/jcommon/process/api/JNAUtils.java
// public static <T> List<T> fromSeq(T...iterable) {
// return Arrays.asList(iterable);
// }
// Path: src/main/java/jcommon/process/platform/win32/CONTEXT.java
import com.sun.jna.Structure;
import java.util.List;
import static jcommon.process.api.JNAUtils.fromSeq;
package jcommon.process.platform.win32;
public class CONTEXT extends Structure {
public int sentinel;
| private static final List FIELD_ORDER = fromSeq( |
ivoa/lyonetia | src/adql-validator/test/cds/adql/validation/report/MarkdownReportTest.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import adql.parser.ADQLParser;
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertNull; | return "# ADQL Validation report" + LINE_SEP +
LINE_SEP +
LINE_SEP +
"## About the validation set" + LINE_SEP +
LINE_SEP +
"| _Key_ | _Value_ |" + LINE_SEP +
"| ------------------- | ------------------------------------------------------------ |" + LINE_SEP +
"| **Origin** | " + setName + " |" + LINE_SEP +
"| **Publisher** | - |" + LINE_SEP +
"| **Contact** | - |" + LINE_SEP +
"| **Description** | - |" + LINE_SEP +
"| **Available tests** | " + nbAvailableTests + " |" + LINE_SEP;
}
@Test
void startWithNoSet() {
// No validation set:
report.start(null, null);
// Check collected counts:
assertEquals(0, report.nbAvailableTests);
// Check the output:
assertEquals(0, out.toByteArray().length);
assertEquals(0, err.toByteArray().length);
}
@Test
void startWithNoInformation() {
// Create a really empty validation set: | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/test/cds/adql/validation/report/MarkdownReportTest.java
import adql.parser.ADQLParser;
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertNull;
return "# ADQL Validation report" + LINE_SEP +
LINE_SEP +
LINE_SEP +
"## About the validation set" + LINE_SEP +
LINE_SEP +
"| _Key_ | _Value_ |" + LINE_SEP +
"| ------------------- | ------------------------------------------------------------ |" + LINE_SEP +
"| **Origin** | " + setName + " |" + LINE_SEP +
"| **Publisher** | - |" + LINE_SEP +
"| **Contact** | - |" + LINE_SEP +
"| **Description** | - |" + LINE_SEP +
"| **Available tests** | " + nbAvailableTests + " |" + LINE_SEP;
}
@Test
void startWithNoSet() {
// No validation set:
report.start(null, null);
// Check collected counts:
assertEquals(0, report.nbAvailableTests);
// Check the output:
assertEquals(0, out.toByteArray().length);
assertEquals(0, err.toByteArray().length);
}
@Test
void startWithNoInformation() {
// Create a really empty validation set: | final ValidationSet validationSet = new ValidationSet(); |
ivoa/lyonetia | src/adql-validator/test/cds/adql/validation/report/MarkdownReportTest.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import adql.parser.ADQLParser;
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertNull; | // Check collected counts:
assertEquals(0, report.nbAvailableTests);
// Check the output:
assertEquals(0, out.toByteArray().length);
assertEquals(0, err.toByteArray().length);
}
@Test
void startWithNoInformation() {
// Create a really empty validation set:
final ValidationSet validationSet = new ValidationSet();
assertEquals(0, validationSet.queries.size());
// Trigger the 'start' event:
report.start(validationSet, null);
// Check collected counts:
assertEquals(validationSet.queries.size(), report.nbAvailableTests);
// Check the output:
assertEquals(generateReportHeader("-", 0), out.toString());
assertEquals(0, err.toByteArray().length);
}
@Test
void startWithAllInformation() throws MalformedURLException {
// Create a validation set:
final ValidationSet validationSet = new ValidationSet();
// Set all info about a publisher: | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/test/cds/adql/validation/report/MarkdownReportTest.java
import adql.parser.ADQLParser;
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertNull;
// Check collected counts:
assertEquals(0, report.nbAvailableTests);
// Check the output:
assertEquals(0, out.toByteArray().length);
assertEquals(0, err.toByteArray().length);
}
@Test
void startWithNoInformation() {
// Create a really empty validation set:
final ValidationSet validationSet = new ValidationSet();
assertEquals(0, validationSet.queries.size());
// Trigger the 'start' event:
report.start(validationSet, null);
// Check collected counts:
assertEquals(validationSet.queries.size(), report.nbAvailableTests);
// Check the output:
assertEquals(generateReportHeader("-", 0), out.toString());
assertEquals(0, err.toByteArray().length);
}
@Test
void startWithAllInformation() throws MalformedURLException {
// Create a validation set:
final ValidationSet validationSet = new ValidationSet();
// Set all info about a publisher: | validationSet.publisher = new Publisher(); |
ivoa/lyonetia | src/adql-validator/test/cds/adql/validation/report/MarkdownReportTest.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import adql.parser.ADQLParser;
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertNull; | assertEquals(0, err.toByteArray().length);
}
@Test
void startWithNoInformation() {
// Create a really empty validation set:
final ValidationSet validationSet = new ValidationSet();
assertEquals(0, validationSet.queries.size());
// Trigger the 'start' event:
report.start(validationSet, null);
// Check collected counts:
assertEquals(validationSet.queries.size(), report.nbAvailableTests);
// Check the output:
assertEquals(generateReportHeader("-", 0), out.toString());
assertEquals(0, err.toByteArray().length);
}
@Test
void startWithAllInformation() throws MalformedURLException {
// Create a validation set:
final ValidationSet validationSet = new ValidationSet();
// Set all info about a publisher:
validationSet.publisher = new Publisher();
validationSet.publisher.name = "John Doe";
final String PUBLISHER_EMAIL = "mailto:johndoe.org";
validationSet.publisher.url = new URL(PUBLISHER_EMAIL);
// Set all info about a contact person: | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/test/cds/adql/validation/report/MarkdownReportTest.java
import adql.parser.ADQLParser;
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertNull;
assertEquals(0, err.toByteArray().length);
}
@Test
void startWithNoInformation() {
// Create a really empty validation set:
final ValidationSet validationSet = new ValidationSet();
assertEquals(0, validationSet.queries.size());
// Trigger the 'start' event:
report.start(validationSet, null);
// Check collected counts:
assertEquals(validationSet.queries.size(), report.nbAvailableTests);
// Check the output:
assertEquals(generateReportHeader("-", 0), out.toString());
assertEquals(0, err.toByteArray().length);
}
@Test
void startWithAllInformation() throws MalformedURLException {
// Create a validation set:
final ValidationSet validationSet = new ValidationSet();
// Set all info about a publisher:
validationSet.publisher = new Publisher();
validationSet.publisher.name = "John Doe";
final String PUBLISHER_EMAIL = "mailto:johndoe.org";
validationSet.publisher.url = new URL(PUBLISHER_EMAIL);
// Set all info about a contact person: | validationSet.contact = new Contact(); |
ivoa/lyonetia | src/adql-validator/test/cds/adql/validation/report/MarkdownReportTest.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import adql.parser.ADQLParser;
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertNull; | assertEquals(0, validationSet.queries.size());
// Trigger the 'start' event:
report.start(validationSet, null);
// Check collected counts:
assertEquals(validationSet.queries.size(), report.nbAvailableTests);
// Check the output:
assertEquals(generateReportHeader("-", 0), out.toString());
assertEquals(0, err.toByteArray().length);
}
@Test
void startWithAllInformation() throws MalformedURLException {
// Create a validation set:
final ValidationSet validationSet = new ValidationSet();
// Set all info about a publisher:
validationSet.publisher = new Publisher();
validationSet.publisher.name = "John Doe";
final String PUBLISHER_EMAIL = "mailto:johndoe.org";
validationSet.publisher.url = new URL(PUBLISHER_EMAIL);
// Set all info about a contact person:
validationSet.contact = new Contact();
validationSet.contact.name = "Nobody";
final String CONTACT_EMAIL = "mailto:nobody.org";
validationSet.contact.url = new URL(CONTACT_EMAIL);
// Set a (very smart) description:
validationSet.description = "Here is a dummy description.";
// Set at least one query: | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/test/cds/adql/validation/report/MarkdownReportTest.java
import adql.parser.ADQLParser;
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertNull;
assertEquals(0, validationSet.queries.size());
// Trigger the 'start' event:
report.start(validationSet, null);
// Check collected counts:
assertEquals(validationSet.queries.size(), report.nbAvailableTests);
// Check the output:
assertEquals(generateReportHeader("-", 0), out.toString());
assertEquals(0, err.toByteArray().length);
}
@Test
void startWithAllInformation() throws MalformedURLException {
// Create a validation set:
final ValidationSet validationSet = new ValidationSet();
// Set all info about a publisher:
validationSet.publisher = new Publisher();
validationSet.publisher.name = "John Doe";
final String PUBLISHER_EMAIL = "mailto:johndoe.org";
validationSet.publisher.url = new URL(PUBLISHER_EMAIL);
// Set all info about a contact person:
validationSet.contact = new Contact();
validationSet.contact.name = "Nobody";
final String CONTACT_EMAIL = "mailto:nobody.org";
validationSet.contact.url = new URL(CONTACT_EMAIL);
// Set a (very smart) description:
validationSet.description = "Here is a dummy description.";
// Set at least one query: | assertTrue(validationSet.queries.add(new ValidationQuery())); |
ivoa/lyonetia | src/adql-validator/test/cds/adql/validation/report/MarkdownReportTest.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import adql.parser.ADQLParser;
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertNull; | buf.append(" * **Duration:** ").append(report.testedQueries.get(i-1).duration < 0 ? "-" : report.testedQueries.get(i-1).duration + ".0ms").append(LINE_SEP).append(LINE_SEP);
buf.append(" * **Status:** ").append(report.testedQueries.get(i-1).passed ? "OK" : "FAILED").append(LINE_SEP);
if (report.testedQueries.get(i-1).error != null) {
buf.append(LINE_SEP).append(" * **Error:**").append(LINE_SEP).append(LINE_SEP);
buf.append(" > ").append(report.testedQueries.get(i-1).error.replaceAll("" + LINE_SEP, "\n > ")).append(LINE_SEP);
}
}
assertEquals(buf.toString(), out.toString());
assertEquals(0, err.toByteArray().length);
}
@Test
void errorNoException() {
// Trigger the 'error' event without an Exception:
report.error(null);
// => no error output!
assertEquals(0, out.toByteArray().length);
assertEquals(0, err.toByteArray().length);
}
@Test
void errorWithException() {
// Trigger the 'error' event with an Exception:
final String ERROR_MSG = "Oops!";
// Trigger the 'end' event with a ValidationSet:
final ValidationSet vSet = new ValidationSet();
final String SET_NAME = "TEST";
report.start(vSet, SET_NAME); | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/test/cds/adql/validation/report/MarkdownReportTest.java
import adql.parser.ADQLParser;
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertNull;
buf.append(" * **Duration:** ").append(report.testedQueries.get(i-1).duration < 0 ? "-" : report.testedQueries.get(i-1).duration + ".0ms").append(LINE_SEP).append(LINE_SEP);
buf.append(" * **Status:** ").append(report.testedQueries.get(i-1).passed ? "OK" : "FAILED").append(LINE_SEP);
if (report.testedQueries.get(i-1).error != null) {
buf.append(LINE_SEP).append(" * **Error:**").append(LINE_SEP).append(LINE_SEP);
buf.append(" > ").append(report.testedQueries.get(i-1).error.replaceAll("" + LINE_SEP, "\n > ")).append(LINE_SEP);
}
}
assertEquals(buf.toString(), out.toString());
assertEquals(0, err.toByteArray().length);
}
@Test
void errorNoException() {
// Trigger the 'error' event without an Exception:
report.error(null);
// => no error output!
assertEquals(0, out.toByteArray().length);
assertEquals(0, err.toByteArray().length);
}
@Test
void errorWithException() {
// Trigger the 'error' event with an Exception:
final String ERROR_MSG = "Oops!";
// Trigger the 'end' event with a ValidationSet:
final ValidationSet vSet = new ValidationSet();
final String SET_NAME = "TEST";
report.start(vSet, SET_NAME); | report.error(new ValidationException(ERROR_MSG)); |
ivoa/lyonetia | src/adql-validator/src/cds/adql/validation/report/MarkdownReport.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import java.io.PrintStream;
import java.net.URL;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.ChronoField;
import java.util.*; | package cds.adql.validation.report;
/**
* Print the output of an {@link cds.adql.validation.ADQLValidator} into a
* Markdown format.
*
* <p>
* This {@link ValidatorListener} accepts a {@link StatCollector} in
* argument of its constructor. This is useful to collect statistics in the
* same time and then to print them.
* </p>
*
* @author Grégory Mantelet (CDS)
* @version 1.0 (12/2021)
*/
public class MarkdownReport implements ValidatorListener {
/** Date format for the test's execution date. */
protected final static DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM )
.withResolverFields(ChronoField.SECOND_OF_MINUTE)
.withLocale( Locale.US )
.withZone( ZoneId.of("UTC") );
/** Standard output stream. */
protected final PrintStream out;
/** Error output stream. */
protected final PrintStream err;
/** Indicate whether all tests or only failed ones should be reported.
* By default, <code>false</code>. */
protected boolean showOnlyFailures = false;
/** List of all tested queries. */
protected List<TestedValidationQuery> testedQueries = new ArrayList<>();
/** List of all validation exception/errors that may have unexpectedly
* happened. */ | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/src/cds/adql/validation/report/MarkdownReport.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import java.io.PrintStream;
import java.net.URL;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.ChronoField;
import java.util.*;
package cds.adql.validation.report;
/**
* Print the output of an {@link cds.adql.validation.ADQLValidator} into a
* Markdown format.
*
* <p>
* This {@link ValidatorListener} accepts a {@link StatCollector} in
* argument of its constructor. This is useful to collect statistics in the
* same time and then to print them.
* </p>
*
* @author Grégory Mantelet (CDS)
* @version 1.0 (12/2021)
*/
public class MarkdownReport implements ValidatorListener {
/** Date format for the test's execution date. */
protected final static DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM )
.withResolverFields(ChronoField.SECOND_OF_MINUTE)
.withLocale( Locale.US )
.withZone( ZoneId.of("UTC") );
/** Standard output stream. */
protected final PrintStream out;
/** Error output stream. */
protected final PrintStream err;
/** Indicate whether all tests or only failed ones should be reported.
* By default, <code>false</code>. */
protected boolean showOnlyFailures = false;
/** List of all tested queries. */
protected List<TestedValidationQuery> testedQueries = new ArrayList<>();
/** List of all validation exception/errors that may have unexpectedly
* happened. */ | protected List<ValidationException> errors = new ArrayList<>(); |
ivoa/lyonetia | src/adql-validator/src/cds/adql/validation/report/MarkdownReport.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import java.io.PrintStream;
import java.net.URL;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.ChronoField;
import java.util.*; |
if (error == null)
err = System.err;
else
err = error;
}
public final boolean isShowOnlyFailures() {
return showOnlyFailures;
}
public final void setShowOnlyFailures(final boolean showOnlyFailures) {
this.showOnlyFailures = showOnlyFailures;
}
public final void setValidationStats(final ValidationStatistics validationStats){
this.validationStats = validationStats;
}
@Override
public void clear() {
indexTest = 0;
nbAvailableTests = 0;
nbPassed = 0;
startDate = null;
testedQueries.clear();
errors.clear();
}
@Override | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/src/cds/adql/validation/report/MarkdownReport.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import java.io.PrintStream;
import java.net.URL;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.ChronoField;
import java.util.*;
if (error == null)
err = System.err;
else
err = error;
}
public final boolean isShowOnlyFailures() {
return showOnlyFailures;
}
public final void setShowOnlyFailures(final boolean showOnlyFailures) {
this.showOnlyFailures = showOnlyFailures;
}
public final void setValidationStats(final ValidationStatistics validationStats){
this.validationStats = validationStats;
}
@Override
public void clear() {
indexTest = 0;
nbAvailableTests = 0;
nbPassed = 0;
startDate = null;
testedQueries.clear();
errors.clear();
}
@Override | public void start(final ValidationSet set, final String source) { |
ivoa/lyonetia | src/adql-validator/src/cds/adql/validation/report/MarkdownReport.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import java.io.PrintStream;
import java.net.URL;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.ChronoField;
import java.util.*; | }
@Override
public void start(final ValidationSet set, final String source) {
// Nothing to do if no validation set:
if (set == null)
return;
// Display a description of the validation tests set:
out.println("# ADQL Validation report");
out.println();
out.println();
out.println("## About the validation set");
out.println();
out.println("| _Key_ | _Value_ |");
out.println("| ------------------- | ------------------------------------------------------------ |");
out.println("| **Origin** | " + ((source != null && source.trim().length() > 0) ? source : "-") + " |");
out.println("| **Publisher** | " + formatPublisher(set.publisher) + " |");
out.println("| **Contact** | " + formatContact(set.contact) + " |");
out.println("| **Description** | " + (set.description != null ? set.description : "-") + " |");
out.println("| **Available tests** | " + set.queries.size() + " |");
// Remember the max. number of tests to run:
nbAvailableTests = set.queries.size();
// Set the start date:
startDate = getCurrentUTCTime();
}
@Override | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/src/cds/adql/validation/report/MarkdownReport.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import java.io.PrintStream;
import java.net.URL;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.ChronoField;
import java.util.*;
}
@Override
public void start(final ValidationSet set, final String source) {
// Nothing to do if no validation set:
if (set == null)
return;
// Display a description of the validation tests set:
out.println("# ADQL Validation report");
out.println();
out.println();
out.println("## About the validation set");
out.println();
out.println("| _Key_ | _Value_ |");
out.println("| ------------------- | ------------------------------------------------------------ |");
out.println("| **Origin** | " + ((source != null && source.trim().length() > 0) ? source : "-") + " |");
out.println("| **Publisher** | " + formatPublisher(set.publisher) + " |");
out.println("| **Contact** | " + formatContact(set.contact) + " |");
out.println("| **Description** | " + (set.description != null ? set.description : "-") + " |");
out.println("| **Available tests** | " + set.queries.size() + " |");
// Remember the max. number of tests to run:
nbAvailableTests = set.queries.size();
// Set the start date:
startDate = getCurrentUTCTime();
}
@Override | public void validating(final ValidationQuery query) { |
ivoa/lyonetia | src/adql-validator/src/cds/adql/validation/report/MarkdownReport.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import java.io.PrintStream;
import java.net.URL;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.ChronoField;
import java.util.*; | }
}
}
@Override
public void error(final ValidationException error) {
if (error != null)
errors.add(error);
}
/**
* Give the serialized form of the current UTC time.
*
* @return The serialized UTC time.
*/
protected static String getCurrentUTCTime() {
return formatter.format( Instant.now() );
}
/**
* Format a publisher into a Markdown format.
*
* @param publisher The publisher to format.
*
* @return The formatted publisher,
* <code>-</code> if NULL.
*
* @see #formatContact(String, URL)
*/ | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/src/cds/adql/validation/report/MarkdownReport.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import java.io.PrintStream;
import java.net.URL;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.ChronoField;
import java.util.*;
}
}
}
@Override
public void error(final ValidationException error) {
if (error != null)
errors.add(error);
}
/**
* Give the serialized form of the current UTC time.
*
* @return The serialized UTC time.
*/
protected static String getCurrentUTCTime() {
return formatter.format( Instant.now() );
}
/**
* Format a publisher into a Markdown format.
*
* @param publisher The publisher to format.
*
* @return The formatted publisher,
* <code>-</code> if NULL.
*
* @see #formatContact(String, URL)
*/ | protected final String formatPublisher(final Publisher publisher){ |
ivoa/lyonetia | src/adql-validator/src/cds/adql/validation/report/MarkdownReport.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import java.io.PrintStream;
import java.net.URL;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.ChronoField;
import java.util.*; | * @return The serialized UTC time.
*/
protected static String getCurrentUTCTime() {
return formatter.format( Instant.now() );
}
/**
* Format a publisher into a Markdown format.
*
* @param publisher The publisher to format.
*
* @return The formatted publisher,
* <code>-</code> if NULL.
*
* @see #formatContact(String, URL)
*/
protected final String formatPublisher(final Publisher publisher){
return (publisher == null) ? formatContact(null, null) : formatContact(publisher.name, publisher.url);
}
/**
* Format a contact into a Markdown format.
*
* @param contact The contact to format.
*
* @return The formatted contact,
* <code>-</code> if NULL.
*
* @see #formatContact(String, URL)
*/ | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/src/cds/adql/validation/report/MarkdownReport.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import java.io.PrintStream;
import java.net.URL;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.ChronoField;
import java.util.*;
* @return The serialized UTC time.
*/
protected static String getCurrentUTCTime() {
return formatter.format( Instant.now() );
}
/**
* Format a publisher into a Markdown format.
*
* @param publisher The publisher to format.
*
* @return The formatted publisher,
* <code>-</code> if NULL.
*
* @see #formatContact(String, URL)
*/
protected final String formatPublisher(final Publisher publisher){
return (publisher == null) ? formatContact(null, null) : formatContact(publisher.name, publisher.url);
}
/**
* Format a contact into a Markdown format.
*
* @param contact The contact to format.
*
* @return The formatted contact,
* <code>-</code> if NULL.
*
* @see #formatContact(String, URL)
*/ | protected final String formatContact(final Contact contact) { |
ivoa/lyonetia | src/adql-validator/test/cds/adql/validation/report/TextReportTest.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import static org.junit.jupiter.api.Assertions.*; | assertNull(report.validationStats);
}
@Test
void clear() {
report.indexTest = 12;
report.nbAvailableTests = 42;
// Clear() should erase this information:
report.clear();
assertEquals(0, report.indexTest);
assertEquals(0, report.nbAvailableTests);
}
@Test
void startWithNoSet() {
// No validation set:
report.start(null, null);
// Check collected counts:
assertEquals(0, report.nbAvailableTests);
// Check the output:
assertEquals(0, out.toByteArray().length);
assertEquals(0, err.toByteArray().length);
}
@Test
void startWithNoInformation() {
// Create a really empty validation set: | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/test/cds/adql/validation/report/TextReportTest.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import static org.junit.jupiter.api.Assertions.*;
assertNull(report.validationStats);
}
@Test
void clear() {
report.indexTest = 12;
report.nbAvailableTests = 42;
// Clear() should erase this information:
report.clear();
assertEquals(0, report.indexTest);
assertEquals(0, report.nbAvailableTests);
}
@Test
void startWithNoSet() {
// No validation set:
report.start(null, null);
// Check collected counts:
assertEquals(0, report.nbAvailableTests);
// Check the output:
assertEquals(0, out.toByteArray().length);
assertEquals(0, err.toByteArray().length);
}
@Test
void startWithNoInformation() {
// Create a really empty validation set: | final ValidationSet validationSet = new ValidationSet(); |
ivoa/lyonetia | src/adql-validator/test/cds/adql/validation/report/TextReportTest.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import static org.junit.jupiter.api.Assertions.*; | // Check collected counts:
assertEquals(0, report.nbAvailableTests);
// Check the output:
assertEquals(0, out.toByteArray().length);
assertEquals(0, err.toByteArray().length);
}
@Test
void startWithNoInformation() {
// Create a really empty validation set:
final ValidationSet validationSet = new ValidationSet();
assertEquals(0, validationSet.queries.size());
// Trigger the 'start' event:
report.start(validationSet, null);
// Check collected counts:
assertEquals(validationSet.queries.size(), report.nbAvailableTests);
// Check the output:
assertEquals(generateReportHeader("-", 0), out.toString());
assertEquals(0, err.toByteArray().length);
}
@Test
void startWithAllInformation() throws MalformedURLException {
// Create a validation set:
final ValidationSet validationSet = new ValidationSet();
// Set all info about a publisher: | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/test/cds/adql/validation/report/TextReportTest.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import static org.junit.jupiter.api.Assertions.*;
// Check collected counts:
assertEquals(0, report.nbAvailableTests);
// Check the output:
assertEquals(0, out.toByteArray().length);
assertEquals(0, err.toByteArray().length);
}
@Test
void startWithNoInformation() {
// Create a really empty validation set:
final ValidationSet validationSet = new ValidationSet();
assertEquals(0, validationSet.queries.size());
// Trigger the 'start' event:
report.start(validationSet, null);
// Check collected counts:
assertEquals(validationSet.queries.size(), report.nbAvailableTests);
// Check the output:
assertEquals(generateReportHeader("-", 0), out.toString());
assertEquals(0, err.toByteArray().length);
}
@Test
void startWithAllInformation() throws MalformedURLException {
// Create a validation set:
final ValidationSet validationSet = new ValidationSet();
// Set all info about a publisher: | validationSet.publisher = new Publisher(); |
ivoa/lyonetia | src/adql-validator/test/cds/adql/validation/report/TextReportTest.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import static org.junit.jupiter.api.Assertions.*; | assertEquals(0, err.toByteArray().length);
}
@Test
void startWithNoInformation() {
// Create a really empty validation set:
final ValidationSet validationSet = new ValidationSet();
assertEquals(0, validationSet.queries.size());
// Trigger the 'start' event:
report.start(validationSet, null);
// Check collected counts:
assertEquals(validationSet.queries.size(), report.nbAvailableTests);
// Check the output:
assertEquals(generateReportHeader("-", 0), out.toString());
assertEquals(0, err.toByteArray().length);
}
@Test
void startWithAllInformation() throws MalformedURLException {
// Create a validation set:
final ValidationSet validationSet = new ValidationSet();
// Set all info about a publisher:
validationSet.publisher = new Publisher();
validationSet.publisher.name = "John Doe";
final String PUBLISHER_EMAIL = "johndoe.org";
validationSet.publisher.url = new URL("mailto:"+PUBLISHER_EMAIL);
// Set all info about a contact person: | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/test/cds/adql/validation/report/TextReportTest.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import static org.junit.jupiter.api.Assertions.*;
assertEquals(0, err.toByteArray().length);
}
@Test
void startWithNoInformation() {
// Create a really empty validation set:
final ValidationSet validationSet = new ValidationSet();
assertEquals(0, validationSet.queries.size());
// Trigger the 'start' event:
report.start(validationSet, null);
// Check collected counts:
assertEquals(validationSet.queries.size(), report.nbAvailableTests);
// Check the output:
assertEquals(generateReportHeader("-", 0), out.toString());
assertEquals(0, err.toByteArray().length);
}
@Test
void startWithAllInformation() throws MalformedURLException {
// Create a validation set:
final ValidationSet validationSet = new ValidationSet();
// Set all info about a publisher:
validationSet.publisher = new Publisher();
validationSet.publisher.name = "John Doe";
final String PUBLISHER_EMAIL = "johndoe.org";
validationSet.publisher.url = new URL("mailto:"+PUBLISHER_EMAIL);
// Set all info about a contact person: | validationSet.contact = new Contact(); |
ivoa/lyonetia | src/adql-validator/test/cds/adql/validation/report/TextReportTest.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import static org.junit.jupiter.api.Assertions.*; | assertEquals(0, validationSet.queries.size());
// Trigger the 'start' event:
report.start(validationSet, null);
// Check collected counts:
assertEquals(validationSet.queries.size(), report.nbAvailableTests);
// Check the output:
assertEquals(generateReportHeader("-", 0), out.toString());
assertEquals(0, err.toByteArray().length);
}
@Test
void startWithAllInformation() throws MalformedURLException {
// Create a validation set:
final ValidationSet validationSet = new ValidationSet();
// Set all info about a publisher:
validationSet.publisher = new Publisher();
validationSet.publisher.name = "John Doe";
final String PUBLISHER_EMAIL = "johndoe.org";
validationSet.publisher.url = new URL("mailto:"+PUBLISHER_EMAIL);
// Set all info about a contact person:
validationSet.contact = new Contact();
validationSet.contact.name = "Nobody";
final String CONTACT_EMAIL = "nobody.org";
validationSet.contact.url = new URL("mailto:"+CONTACT_EMAIL);
// Set a (very smart) description:
validationSet.description = "Here is a dummy description.";
// Set at least one query: | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/test/cds/adql/validation/report/TextReportTest.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import static org.junit.jupiter.api.Assertions.*;
assertEquals(0, validationSet.queries.size());
// Trigger the 'start' event:
report.start(validationSet, null);
// Check collected counts:
assertEquals(validationSet.queries.size(), report.nbAvailableTests);
// Check the output:
assertEquals(generateReportHeader("-", 0), out.toString());
assertEquals(0, err.toByteArray().length);
}
@Test
void startWithAllInformation() throws MalformedURLException {
// Create a validation set:
final ValidationSet validationSet = new ValidationSet();
// Set all info about a publisher:
validationSet.publisher = new Publisher();
validationSet.publisher.name = "John Doe";
final String PUBLISHER_EMAIL = "johndoe.org";
validationSet.publisher.url = new URL("mailto:"+PUBLISHER_EMAIL);
// Set all info about a contact person:
validationSet.contact = new Contact();
validationSet.contact.name = "Nobody";
final String CONTACT_EMAIL = "nobody.org";
validationSet.contact.url = new URL("mailto:"+CONTACT_EMAIL);
// Set a (very smart) description:
validationSet.description = "Here is a dummy description.";
// Set at least one query: | assertTrue(validationSet.queries.add(new ValidationQuery())); |
ivoa/lyonetia | src/adql-validator/test/cds/adql/validation/report/TextReportTest.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import static org.junit.jupiter.api.Assertions.*; | stats.totalDuration = (long)1e10;
// Associate them with the TextReport:
report.setValidationStats(stats);
// Trigger the 'end' event with a ValidationSet:
report.end(new ValidationSet());
// Check the output:
assertEquals("Validation completed!" + LINE_SEP +
TextReport.LIGHT_SEP + LINE_SEP +
"Summary : " + report.nbPassed + "/" + report.nbAvailableTests + " successful tests (50%)" + LINE_SEP +
"Duration: total=10.0s, average=238.09523ms" + LINE_SEP +
TextReport.SEPARATOR + LINE_SEP, out.toString());
assertEquals(0, err.toByteArray().length);
}
@Test
void errorNoException() {
// Trigger the 'error' event without an Exception:
report.error(null);
// => no error output!
assertEquals(0, out.toByteArray().length);
assertEquals(0, err.toByteArray().length);
}
@Test
void errorWithException() {
// Trigger the 'error' event with an Exception:
final String ERROR_MSG = "Oops!"; | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/test/cds/adql/validation/report/TextReportTest.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import static org.junit.jupiter.api.Assertions.*;
stats.totalDuration = (long)1e10;
// Associate them with the TextReport:
report.setValidationStats(stats);
// Trigger the 'end' event with a ValidationSet:
report.end(new ValidationSet());
// Check the output:
assertEquals("Validation completed!" + LINE_SEP +
TextReport.LIGHT_SEP + LINE_SEP +
"Summary : " + report.nbPassed + "/" + report.nbAvailableTests + " successful tests (50%)" + LINE_SEP +
"Duration: total=10.0s, average=238.09523ms" + LINE_SEP +
TextReport.SEPARATOR + LINE_SEP, out.toString());
assertEquals(0, err.toByteArray().length);
}
@Test
void errorNoException() {
// Trigger the 'error' event without an Exception:
report.error(null);
// => no error output!
assertEquals(0, out.toByteArray().length);
assertEquals(0, err.toByteArray().length);
}
@Test
void errorWithException() {
// Trigger the 'error' event with an Exception:
final String ERROR_MSG = "Oops!"; | report.error(new ValidationException(ERROR_MSG)); |
ivoa/lyonetia | src/adql-validator/src/cds/adql/validation/report/TestedValidationQuery.java | // Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
| import cds.adql.validation.query.ValidationQuery; | package cds.adql.validation.report;
public class TestedValidationQuery {
public final long index;
/** The tested query. */ | // Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
// Path: src/adql-validator/src/cds/adql/validation/report/TestedValidationQuery.java
import cds.adql.validation.query.ValidationQuery;
package cds.adql.validation.report;
public class TestedValidationQuery {
public final long index;
/** The tested query. */ | public final ValidationQuery query; |
ivoa/lyonetia | src/adql-validator/src/cds/adql/validation/report/StatCollector.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet; | */
public final long getLastTestDuration(){
return lastTestDuration;
}
/**
* Compute the duration of the last validation test and append it to
* {@link #getTotalDuration()}.
*
* <p>
* This function resets {@link #startTest} to 0.
* </p>
*/
protected void appendTestDuration(){
if (startTest > 0) {
lastTestDuration = System.nanoTime() - startTest;
totalDuration += lastTestDuration;
startTest = 0;
}
}
@Override
public void clear() {
cntTests = 0;
cntPass = 0;
totalDuration = 0;
lastTestDuration = 0;
}
@Override | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/src/cds/adql/validation/report/StatCollector.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
*/
public final long getLastTestDuration(){
return lastTestDuration;
}
/**
* Compute the duration of the last validation test and append it to
* {@link #getTotalDuration()}.
*
* <p>
* This function resets {@link #startTest} to 0.
* </p>
*/
protected void appendTestDuration(){
if (startTest > 0) {
lastTestDuration = System.nanoTime() - startTest;
totalDuration += lastTestDuration;
startTest = 0;
}
}
@Override
public void clear() {
cntTests = 0;
cntPass = 0;
totalDuration = 0;
lastTestDuration = 0;
}
@Override | public void start(ValidationSet set, String source) {} |
ivoa/lyonetia | src/adql-validator/src/cds/adql/validation/report/StatCollector.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet; | }
/**
* Compute the duration of the last validation test and append it to
* {@link #getTotalDuration()}.
*
* <p>
* This function resets {@link #startTest} to 0.
* </p>
*/
protected void appendTestDuration(){
if (startTest > 0) {
lastTestDuration = System.nanoTime() - startTest;
totalDuration += lastTestDuration;
startTest = 0;
}
}
@Override
public void clear() {
cntTests = 0;
cntPass = 0;
totalDuration = 0;
lastTestDuration = 0;
}
@Override
public void start(ValidationSet set, String source) {}
@Override | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/src/cds/adql/validation/report/StatCollector.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
}
/**
* Compute the duration of the last validation test and append it to
* {@link #getTotalDuration()}.
*
* <p>
* This function resets {@link #startTest} to 0.
* </p>
*/
protected void appendTestDuration(){
if (startTest > 0) {
lastTestDuration = System.nanoTime() - startTest;
totalDuration += lastTestDuration;
startTest = 0;
}
}
@Override
public void clear() {
cntTests = 0;
cntPass = 0;
totalDuration = 0;
lastTestDuration = 0;
}
@Override
public void start(ValidationSet set, String source) {}
@Override | public void validating(ValidationQuery query) { |
ivoa/lyonetia | src/adql-validator/src/cds/adql/validation/report/StatCollector.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet; | }
@Override
public void start(ValidationSet set, String source) {}
@Override
public void validating(ValidationQuery query) {
cntTests++;
startTest = System.nanoTime();
}
@Override
public void pass(ValidationQuery query) {
if (startTest > 0) {
cntPass++;
appendTestDuration();
}
}
@Override
public void fail(ValidationQuery query, String errorMessage) {
if (startTest > 0) {
appendTestDuration();
}
}
@Override
public void end(ValidationSet set) {}
@Override | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/src/cds/adql/validation/report/StatCollector.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
}
@Override
public void start(ValidationSet set, String source) {}
@Override
public void validating(ValidationQuery query) {
cntTests++;
startTest = System.nanoTime();
}
@Override
public void pass(ValidationQuery query) {
if (startTest > 0) {
cntPass++;
appendTestDuration();
}
}
@Override
public void fail(ValidationQuery query, String errorMessage) {
if (startTest > 0) {
appendTestDuration();
}
}
@Override
public void end(ValidationSet set) {}
@Override | public void error(ValidationException error) {} |
ivoa/lyonetia | src/adql-validator/test/cds/adql/validation/query/ADQLVersionParsingTest.java | // Path: src/adql-validator/src/cds/adql/validation/parser/ValidationSetParser.java
// public interface ValidationSetParser {
//
// /**
// * Parses a set of ADQL validation queries.
// *
// * @param stream The serialized queries set to parse.
// *
// * @return The object representation of this queries set.
// *
// * @throws ParseException In case of parsing error.
// */
// ValidationSet parse(final InputStream stream) throws ParseException;
//
// /** ADQL version set by default when none is specified.
// * Generally it corresponds to the most recent ADQL version. */
// ADQLVersion DEFAULT_ADQL_VERSION = ADQLVersion.V2_1;
//
// /** Regular expression for the version 2.1 of ADQL. */
// Pattern PATTERN_ADQL_2_1 = Pattern.compile("^(adql-?)?v?2(.1)?$");
//
// /** Regular expression for the version 2.0 of ADQL. */
// Pattern PATTERN_ADQL_2_0 = Pattern.compile("^(adql-?)?v?2.0$");
//
// /**
// * Tell whether the given string represents an ADQL version.
// *
// * <p><i><b>Notes:</b>
// * This function is case IN-sensitive. Many variants are tested: with
// * or without <code>adql</code> prefix, <code>v</code> prefix, minor
// * release number suffix, ...
// * </i></p>
// *
// * @param str The string which may represent an ADQL version.
// *
// * @return <code>true</code> if an ADQL version,
// * <code>false</code> otherwise.
// *
// * @see #PATTERN_ADQL_2_0
// * @see #PATTERN_ADQL_2_1
// */
// static boolean matchesVersion(String str){
// if (str == null || str.trim().length() == 0)
// return false;
//
// // Normalize the input string:
// str = str.trim().toLowerCase();
//
// // Try to resolve a version:
// return PATTERN_ADQL_2_1.matcher(str).find()
// || PATTERN_ADQL_2_0.matcher(str).find();
// }
//
// /**
// * Parse the given ADQL version string serialization.
// *
// * <p><i><b>Notes:</b>
// * This function is case IN-sensitive. Many variants are tested: with
// * or without <code>adql</code> prefix, <code>v</code> prefix, minor
// * release number suffix, ...
// * </i></p>
// *
// * @param str The string serialization of an ADQL version.
// *
// * @return The interpreted ADQL version,
// * or {@link #DEFAULT_ADQL_VERSION} if none is provided or if the
// * given string can not be resolved as an {@link ADQLVersion}.
// */
// static ADQLVersion parseVersion(String str){
// if (str == null || str.trim().length() == 0)
// return DEFAULT_ADQL_VERSION;
//
// // Normalize the input string:
// str = str.trim().toLowerCase();
//
// // Parse and resolve the version as much as possible:
// if (PATTERN_ADQL_2_1.matcher(str).find())
// return ADQLVersion.V2_1;
// else if (PATTERN_ADQL_2_0.matcher(str).find())
// return ADQLVersion.V2_0;
// else
// return DEFAULT_ADQL_VERSION;
// }
//
// }
| import static adql.parser.ADQLParser.ADQLVersion;
import static org.junit.jupiter.api.Assertions.*;
import cds.adql.validation.parser.ValidationSetParser;
import org.junit.jupiter.api.Test; | package cds.adql.validation.query;
public class ADQLVersionParsingTest {
final String[] CORRECT_2_0 = new String[]{"2.0", "v2.0", "V2.0", "adql-2.0", "adql-v2.0", "Adql-V2.0", "ADQL-2.0"};
final String[] CORRECT_2_1 = new String[]{"2.1", "2", "v2", "v2.1", "V2", "V2.1", "adql-2.1", "adql-v2.1", "adql-v2", "Adql-V2", "ADQL-2.1", "ADQL-v2.1"};
@Test
public void parseEmpty() {
for(String s : new String[]{null, "", " ", " \t\n "}) | // Path: src/adql-validator/src/cds/adql/validation/parser/ValidationSetParser.java
// public interface ValidationSetParser {
//
// /**
// * Parses a set of ADQL validation queries.
// *
// * @param stream The serialized queries set to parse.
// *
// * @return The object representation of this queries set.
// *
// * @throws ParseException In case of parsing error.
// */
// ValidationSet parse(final InputStream stream) throws ParseException;
//
// /** ADQL version set by default when none is specified.
// * Generally it corresponds to the most recent ADQL version. */
// ADQLVersion DEFAULT_ADQL_VERSION = ADQLVersion.V2_1;
//
// /** Regular expression for the version 2.1 of ADQL. */
// Pattern PATTERN_ADQL_2_1 = Pattern.compile("^(adql-?)?v?2(.1)?$");
//
// /** Regular expression for the version 2.0 of ADQL. */
// Pattern PATTERN_ADQL_2_0 = Pattern.compile("^(adql-?)?v?2.0$");
//
// /**
// * Tell whether the given string represents an ADQL version.
// *
// * <p><i><b>Notes:</b>
// * This function is case IN-sensitive. Many variants are tested: with
// * or without <code>adql</code> prefix, <code>v</code> prefix, minor
// * release number suffix, ...
// * </i></p>
// *
// * @param str The string which may represent an ADQL version.
// *
// * @return <code>true</code> if an ADQL version,
// * <code>false</code> otherwise.
// *
// * @see #PATTERN_ADQL_2_0
// * @see #PATTERN_ADQL_2_1
// */
// static boolean matchesVersion(String str){
// if (str == null || str.trim().length() == 0)
// return false;
//
// // Normalize the input string:
// str = str.trim().toLowerCase();
//
// // Try to resolve a version:
// return PATTERN_ADQL_2_1.matcher(str).find()
// || PATTERN_ADQL_2_0.matcher(str).find();
// }
//
// /**
// * Parse the given ADQL version string serialization.
// *
// * <p><i><b>Notes:</b>
// * This function is case IN-sensitive. Many variants are tested: with
// * or without <code>adql</code> prefix, <code>v</code> prefix, minor
// * release number suffix, ...
// * </i></p>
// *
// * @param str The string serialization of an ADQL version.
// *
// * @return The interpreted ADQL version,
// * or {@link #DEFAULT_ADQL_VERSION} if none is provided or if the
// * given string can not be resolved as an {@link ADQLVersion}.
// */
// static ADQLVersion parseVersion(String str){
// if (str == null || str.trim().length() == 0)
// return DEFAULT_ADQL_VERSION;
//
// // Normalize the input string:
// str = str.trim().toLowerCase();
//
// // Parse and resolve the version as much as possible:
// if (PATTERN_ADQL_2_1.matcher(str).find())
// return ADQLVersion.V2_1;
// else if (PATTERN_ADQL_2_0.matcher(str).find())
// return ADQLVersion.V2_0;
// else
// return DEFAULT_ADQL_VERSION;
// }
//
// }
// Path: src/adql-validator/test/cds/adql/validation/query/ADQLVersionParsingTest.java
import static adql.parser.ADQLParser.ADQLVersion;
import static org.junit.jupiter.api.Assertions.*;
import cds.adql.validation.parser.ValidationSetParser;
import org.junit.jupiter.api.Test;
package cds.adql.validation.query;
public class ADQLVersionParsingTest {
final String[] CORRECT_2_0 = new String[]{"2.0", "v2.0", "V2.0", "adql-2.0", "adql-v2.0", "Adql-V2.0", "ADQL-2.0"};
final String[] CORRECT_2_1 = new String[]{"2.1", "2", "v2", "v2.1", "V2", "V2.1", "adql-2.1", "adql-v2.1", "adql-v2", "Adql-V2", "ADQL-2.1", "ADQL-v2.1"};
@Test
public void parseEmpty() {
for(String s : new String[]{null, "", " ", " \t\n "}) | assertEquals(ValidationSetParser.DEFAULT_ADQL_VERSION, ValidationSetParser.parseVersion(s)); |
ivoa/lyonetia | src/adql-validator/src/cds/adql/validation/report/TextReport.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import java.io.PrintStream; | out = System.out;
else
out = output;
if (error == null)
err = System.err;
else
err = error;
}
public final boolean isShowOnlyFailures() {
return showOnlyFailures;
}
public final void setShowOnlyFailures(final boolean showOnlyFailures) {
this.showOnlyFailures = showOnlyFailures;
}
public final void setValidationStats(final ValidationStatistics validationStats){
this.validationStats = validationStats;
}
@Override
public void clear() {
indexTest = 0;
nbAvailableTests = 0;
nbPassed = 0;
}
@Override | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/src/cds/adql/validation/report/TextReport.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import java.io.PrintStream;
out = System.out;
else
out = output;
if (error == null)
err = System.err;
else
err = error;
}
public final boolean isShowOnlyFailures() {
return showOnlyFailures;
}
public final void setShowOnlyFailures(final boolean showOnlyFailures) {
this.showOnlyFailures = showOnlyFailures;
}
public final void setValidationStats(final ValidationStatistics validationStats){
this.validationStats = validationStats;
}
@Override
public void clear() {
indexTest = 0;
nbAvailableTests = 0;
nbPassed = 0;
}
@Override | public void start(final ValidationSet set, final String source) { |
ivoa/lyonetia | src/adql-validator/src/cds/adql/validation/report/TextReport.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import java.io.PrintStream; | }
@Override
public void clear() {
indexTest = 0;
nbAvailableTests = 0;
nbPassed = 0;
}
@Override
public void start(final ValidationSet set, final String source) {
// Nothing to do if no validation set:
if (set == null)
return;
// Display a description of the validation tests set:
out.println("Starting validation...");
out.println(SEPARATOR);
out.println("Origin : "+((source != null && source.trim().length() > 0) ? source : "-"));
out.println("Publisher : "+formatPublisher(set.publisher));
out.println("Contact : "+formatContact(set.contact));
out.println("Description : "+(set.description != null ? set.description : "-"));
out.println("Available tests: "+set.queries.size());
out.println(SEPARATOR);
// Remember the max. number of tests to run:
nbAvailableTests = set.queries.size();
}
@Override | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/src/cds/adql/validation/report/TextReport.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import java.io.PrintStream;
}
@Override
public void clear() {
indexTest = 0;
nbAvailableTests = 0;
nbPassed = 0;
}
@Override
public void start(final ValidationSet set, final String source) {
// Nothing to do if no validation set:
if (set == null)
return;
// Display a description of the validation tests set:
out.println("Starting validation...");
out.println(SEPARATOR);
out.println("Origin : "+((source != null && source.trim().length() > 0) ? source : "-"));
out.println("Publisher : "+formatPublisher(set.publisher));
out.println("Contact : "+formatContact(set.contact));
out.println("Description : "+(set.description != null ? set.description : "-"));
out.println("Available tests: "+set.queries.size());
out.println(SEPARATOR);
// Remember the max. number of tests to run:
nbAvailableTests = set.queries.size();
}
@Override | public void validating(final ValidationQuery query) { |
ivoa/lyonetia | src/adql-validator/src/cds/adql/validation/report/TextReport.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import java.io.PrintStream; | out.println("Executed in "+ validationStats.getLastTestDuration()/((float)1e6) + "ms");
// Print the test's description:
out.println(LIGHT_SEP);
out.println("Description: "+(query.description == null || query.description.trim().length() == 0 ? "-" : query.description));
out.println("Query : "+(query.query == null || query.query.trim().length() == 0 ? "" : query.query));
out.println("Expected : "+(query.isValid ? "success" : "failure"));
out.println(SEPARATOR);
}
@Override
public void end(final ValidationSet set) {
// Nothing to do, if no validation set:
if (set == null)
return;
// Validation status:
out.println("Validation completed!");
// Display general stats, if any:
out.println(LIGHT_SEP);
out.println("Summary : "+nbPassed+"/"+nbAvailableTests+ " successful tests ("+(nbAvailableTests <= 0 ? 100 : (int)(100.0*nbPassed/nbAvailableTests))+"%)");
if (validationStats != null)
out.println("Duration: total=" + validationStats.getTotalDuration() / ((float) 1e9) + "s, average=" + validationStats.getAvgDuration() / ((float) 1e6)+"ms");
out.println(SEPARATOR);
}
@Override | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/src/cds/adql/validation/report/TextReport.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import java.io.PrintStream;
out.println("Executed in "+ validationStats.getLastTestDuration()/((float)1e6) + "ms");
// Print the test's description:
out.println(LIGHT_SEP);
out.println("Description: "+(query.description == null || query.description.trim().length() == 0 ? "-" : query.description));
out.println("Query : "+(query.query == null || query.query.trim().length() == 0 ? "" : query.query));
out.println("Expected : "+(query.isValid ? "success" : "failure"));
out.println(SEPARATOR);
}
@Override
public void end(final ValidationSet set) {
// Nothing to do, if no validation set:
if (set == null)
return;
// Validation status:
out.println("Validation completed!");
// Display general stats, if any:
out.println(LIGHT_SEP);
out.println("Summary : "+nbPassed+"/"+nbAvailableTests+ " successful tests ("+(nbAvailableTests <= 0 ? 100 : (int)(100.0*nbPassed/nbAvailableTests))+"%)");
if (validationStats != null)
out.println("Duration: total=" + validationStats.getTotalDuration() / ((float) 1e9) + "s, average=" + validationStats.getAvgDuration() / ((float) 1e6)+"ms");
out.println(SEPARATOR);
}
@Override | public void error(final ValidationException error) { |
ivoa/lyonetia | src/adql-validator/src/cds/adql/validation/report/TextReport.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import java.io.PrintStream; | return;
// Validation status:
out.println("Validation completed!");
// Display general stats, if any:
out.println(LIGHT_SEP);
out.println("Summary : "+nbPassed+"/"+nbAvailableTests+ " successful tests ("+(nbAvailableTests <= 0 ? 100 : (int)(100.0*nbPassed/nbAvailableTests))+"%)");
if (validationStats != null)
out.println("Duration: total=" + validationStats.getTotalDuration() / ((float) 1e9) + "s, average=" + validationStats.getAvgDuration() / ((float) 1e6)+"ms");
out.println(SEPARATOR);
}
@Override
public void error(final ValidationException error) {
if (error != null){
final String errMsg = error.getMessage();
err.println("ERROR: "+(errMsg == null || errMsg.trim().length() == 0 ? "<" + error.getClass().getName() + ">" : error.getMessage()));
}
}
/**
* Format a publisher into a text format.
*
* @param publisher The publisher to format.
*
* @return The formatted publisher,
* <code>-</code> if NULL.
*/ | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/src/cds/adql/validation/report/TextReport.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import java.io.PrintStream;
return;
// Validation status:
out.println("Validation completed!");
// Display general stats, if any:
out.println(LIGHT_SEP);
out.println("Summary : "+nbPassed+"/"+nbAvailableTests+ " successful tests ("+(nbAvailableTests <= 0 ? 100 : (int)(100.0*nbPassed/nbAvailableTests))+"%)");
if (validationStats != null)
out.println("Duration: total=" + validationStats.getTotalDuration() / ((float) 1e9) + "s, average=" + validationStats.getAvgDuration() / ((float) 1e6)+"ms");
out.println(SEPARATOR);
}
@Override
public void error(final ValidationException error) {
if (error != null){
final String errMsg = error.getMessage();
err.println("ERROR: "+(errMsg == null || errMsg.trim().length() == 0 ? "<" + error.getClass().getName() + ">" : error.getMessage()));
}
}
/**
* Format a publisher into a text format.
*
* @param publisher The publisher to format.
*
* @return The formatted publisher,
* <code>-</code> if NULL.
*/ | protected String formatPublisher(final Publisher publisher){ |
ivoa/lyonetia | src/adql-validator/src/cds/adql/validation/report/TextReport.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import java.io.PrintStream; | err.println("ERROR: "+(errMsg == null || errMsg.trim().length() == 0 ? "<" + error.getClass().getName() + ">" : error.getMessage()));
}
}
/**
* Format a publisher into a text format.
*
* @param publisher The publisher to format.
*
* @return The formatted publisher,
* <code>-</code> if NULL.
*/
protected String formatPublisher(final Publisher publisher){
// No publisher or no name + no URL => nothing to show ("-"):
if (publisher == null || ((publisher.name == null || publisher.name.trim().length() == 0) && publisher.url == null))
return "-";
// Otherwise, show the name and/or the URL:
else
return (publisher.name == null || publisher.name.trim().length() == 0 ? "" : publisher.name)
+ (publisher.url == null ? "" : " (" + ("mailto".equalsIgnoreCase(publisher.url.getProtocol()) ? publisher.url.getPath() : publisher.url) + ")");
}
/**
* Format a contact into a text format.
*
* @param contact The contact to format.
*
* @return The formatted contact,
* <code>-</code> if NULL.
*/ | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Contact.java
// public class Contact {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Contact{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/Publisher.java
// public class Publisher {
//
// public String name = null;
//
// public URL url = null;
//
// @Override
// public String toString() {
// return "Publisher{name='" + name + '\'' + ", url=" + url + '}';
// }
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/src/cds/adql/validation/report/TextReport.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.Contact;
import cds.adql.validation.query.Publisher;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
import java.io.PrintStream;
err.println("ERROR: "+(errMsg == null || errMsg.trim().length() == 0 ? "<" + error.getClass().getName() + ">" : error.getMessage()));
}
}
/**
* Format a publisher into a text format.
*
* @param publisher The publisher to format.
*
* @return The formatted publisher,
* <code>-</code> if NULL.
*/
protected String formatPublisher(final Publisher publisher){
// No publisher or no name + no URL => nothing to show ("-"):
if (publisher == null || ((publisher.name == null || publisher.name.trim().length() == 0) && publisher.url == null))
return "-";
// Otherwise, show the name and/or the URL:
else
return (publisher.name == null || publisher.name.trim().length() == 0 ? "" : publisher.name)
+ (publisher.url == null ? "" : " (" + ("mailto".equalsIgnoreCase(publisher.url.getProtocol()) ? publisher.url.getPath() : publisher.url) + ")");
}
/**
* Format a contact into a text format.
*
* @param contact The contact to format.
*
* @return The formatted contact,
* <code>-</code> if NULL.
*/ | protected String formatContact(final Contact contact){ |
ivoa/lyonetia | src/adql-validator/src/cds/adql/validation/report/ValidatorListener.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet; | package cds.adql.validation.report;
/**
* Interface of an object listening for the progress of ADQL validation tests.
*
* @author Grégory Mantelet (CDS)
* @version 1.0 (09/2021)
*/
public interface ValidatorListener {
/** Clear any data/resources associated with the last validation session. */
void clear();
/**
* Event triggered when starting a new validation session.
*
* @param set Set of validation queries.
* @param source Origin of the validation set.
*/
void start(final ValidationSet set, final String source);
/**
* Event triggered just before starting the validation of a test query.
*
* @param query The validation test to be started.
*/ | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/src/cds/adql/validation/report/ValidatorListener.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
package cds.adql.validation.report;
/**
* Interface of an object listening for the progress of ADQL validation tests.
*
* @author Grégory Mantelet (CDS)
* @version 1.0 (09/2021)
*/
public interface ValidatorListener {
/** Clear any data/resources associated with the last validation session. */
void clear();
/**
* Event triggered when starting a new validation session.
*
* @param set Set of validation queries.
* @param source Origin of the validation set.
*/
void start(final ValidationSet set, final String source);
/**
* Event triggered just before starting the validation of a test query.
*
* @param query The validation test to be started.
*/ | void validating(final ValidationQuery query); |
ivoa/lyonetia | src/adql-validator/src/cds/adql/validation/report/ValidatorListener.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet; | package cds.adql.validation.report;
/**
* Interface of an object listening for the progress of ADQL validation tests.
*
* @author Grégory Mantelet (CDS)
* @version 1.0 (09/2021)
*/
public interface ValidatorListener {
/** Clear any data/resources associated with the last validation session. */
void clear();
/**
* Event triggered when starting a new validation session.
*
* @param set Set of validation queries.
* @param source Origin of the validation set.
*/
void start(final ValidationSet set, final String source);
/**
* Event triggered just before starting the validation of a test query.
*
* @param query The validation test to be started.
*/
void validating(final ValidationQuery query);
/**
* Event triggered when the last validation test previously reported by
* {@link #validating(ValidationQuery)} successfully completed.
*
* @param query The successful validation test.
*/
void pass(final ValidationQuery query);
/**
* Event triggered when the last validation test previously reported by
* {@link #validating(ValidationQuery)} failed.
*
* @param query The failed validation test.
* @param errorMessage Error reported by the parser.
*/
void fail(final ValidationQuery query, final String errorMessage);
/**
* Event triggered at the end of a validation session.
*
* @param set Set of validation queries.
*/
void end(final ValidationSet set);
/**
* Event triggered when an error occurred.
*
* @param error The error to report.
*/ | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/src/cds/adql/validation/report/ValidatorListener.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
package cds.adql.validation.report;
/**
* Interface of an object listening for the progress of ADQL validation tests.
*
* @author Grégory Mantelet (CDS)
* @version 1.0 (09/2021)
*/
public interface ValidatorListener {
/** Clear any data/resources associated with the last validation session. */
void clear();
/**
* Event triggered when starting a new validation session.
*
* @param set Set of validation queries.
* @param source Origin of the validation set.
*/
void start(final ValidationSet set, final String source);
/**
* Event triggered just before starting the validation of a test query.
*
* @param query The validation test to be started.
*/
void validating(final ValidationQuery query);
/**
* Event triggered when the last validation test previously reported by
* {@link #validating(ValidationQuery)} successfully completed.
*
* @param query The successful validation test.
*/
void pass(final ValidationQuery query);
/**
* Event triggered when the last validation test previously reported by
* {@link #validating(ValidationQuery)} failed.
*
* @param query The failed validation test.
* @param errorMessage Error reported by the parser.
*/
void fail(final ValidationQuery query, final String errorMessage);
/**
* Event triggered at the end of a validation session.
*
* @param set Set of validation queries.
*/
void end(final ValidationSet set);
/**
* Event triggered when an error occurred.
*
* @param error The error to report.
*/ | void error(final ValidationException error); |
ivoa/lyonetia | src/adql-validator/test/cds/adql/validation/report/VoidListener.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet; | package cds.adql.validation.report;
public class VoidListener implements ValidatorListener {
@Override
public void clear() {
}
@Override | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/test/cds/adql/validation/report/VoidListener.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
package cds.adql.validation.report;
public class VoidListener implements ValidatorListener {
@Override
public void clear() {
}
@Override | public void start(ValidationSet set, String source) { |
ivoa/lyonetia | src/adql-validator/test/cds/adql/validation/report/VoidListener.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet; | package cds.adql.validation.report;
public class VoidListener implements ValidatorListener {
@Override
public void clear() {
}
@Override
public void start(ValidationSet set, String source) {
}
@Override | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/test/cds/adql/validation/report/VoidListener.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
package cds.adql.validation.report;
public class VoidListener implements ValidatorListener {
@Override
public void clear() {
}
@Override
public void start(ValidationSet set, String source) {
}
@Override | public void validating(ValidationQuery query) { |
ivoa/lyonetia | src/adql-validator/test/cds/adql/validation/report/VoidListener.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet; | package cds.adql.validation.report;
public class VoidListener implements ValidatorListener {
@Override
public void clear() {
}
@Override
public void start(ValidationSet set, String source) {
}
@Override
public void validating(ValidationQuery query) {
}
@Override
public void pass(ValidationQuery query) {
}
@Override
public void fail(ValidationQuery query, String errorMessage) {
}
@Override
public void end(ValidationSet set) {
}
@Override | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/test/cds/adql/validation/report/VoidListener.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
package cds.adql.validation.report;
public class VoidListener implements ValidatorListener {
@Override
public void clear() {
}
@Override
public void start(ValidationSet set, String source) {
}
@Override
public void validating(ValidationQuery query) {
}
@Override
public void pass(ValidationQuery query) {
}
@Override
public void fail(ValidationQuery query, String errorMessage) {
}
@Override
public void end(ValidationSet set) {
}
@Override | public void error(ValidationException error) { |
ivoa/lyonetia | src/adql-validator/test/cds/adql/validation/report/RecorderListener.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet; | package cds.adql.validation.report;
public class RecorderListener extends VoidListener {
int cntPass = 0;
int cntFail = 0;
boolean setStarted = false;
boolean setEnded = false;
boolean queryStarted = false;
boolean queryEnded = false;
final StringBuffer errors = new StringBuffer();
final StringBuffer failures = new StringBuffer();
@Override
public void clear() {
cntPass = 0;
cntFail = 0;
setStarted = false;
setEnded = false;
queryStarted = false;
queryEnded = false;
errors.delete(0, errors.length());
failures.delete(0, failures.length());
}
@Override | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/test/cds/adql/validation/report/RecorderListener.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
package cds.adql.validation.report;
public class RecorderListener extends VoidListener {
int cntPass = 0;
int cntFail = 0;
boolean setStarted = false;
boolean setEnded = false;
boolean queryStarted = false;
boolean queryEnded = false;
final StringBuffer errors = new StringBuffer();
final StringBuffer failures = new StringBuffer();
@Override
public void clear() {
cntPass = 0;
cntFail = 0;
setStarted = false;
setEnded = false;
queryStarted = false;
queryEnded = false;
errors.delete(0, errors.length());
failures.delete(0, failures.length());
}
@Override | public void error(ValidationException error) { |
ivoa/lyonetia | src/adql-validator/test/cds/adql/validation/report/RecorderListener.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet; |
public String getFailures(){
return failures.toString();
}
public int getCntPass() {
return cntPass;
}
public int getCntFail() {
return cntFail;
}
public boolean isSetStarted() {
return setStarted;
}
public boolean isSetEnded() {
return setEnded;
}
public boolean isQueryStarted() {
return queryStarted;
}
public boolean isQueryEnded() {
return queryEnded;
}
@Override | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/test/cds/adql/validation/report/RecorderListener.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
public String getFailures(){
return failures.toString();
}
public int getCntPass() {
return cntPass;
}
public int getCntFail() {
return cntFail;
}
public boolean isSetStarted() {
return setStarted;
}
public boolean isSetEnded() {
return setEnded;
}
public boolean isQueryStarted() {
return queryStarted;
}
public boolean isQueryEnded() {
return queryEnded;
}
@Override | public void start(ValidationSet set, String source) { |
ivoa/lyonetia | src/adql-validator/test/cds/adql/validation/report/RecorderListener.java | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
| import cds.adql.validation.ValidationException;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet; |
public int getCntFail() {
return cntFail;
}
public boolean isSetStarted() {
return setStarted;
}
public boolean isSetEnded() {
return setEnded;
}
public boolean isQueryStarted() {
return queryStarted;
}
public boolean isQueryEnded() {
return queryEnded;
}
@Override
public void start(ValidationSet set, String source) {
setStarted = true;
setEnded = false;
queryStarted = false;
queryEnded = false;
}
@Override | // Path: src/adql-validator/src/cds/adql/validation/ValidationException.java
// public class ValidationException extends Exception {
//
// public ValidationException() {
// super();
// }
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public ValidationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationQuery.java
// public class ValidationQuery {
//
// /** Unique ID of this test in an entire validation tests set. */
// public final UUID id;
//
// /** Human description of this test. */
// public String description = null;
//
// /** The ADQL query to test. */
// public String query = null;
//
// /** Indicate whether the query is expected to be valid or not. */
// public boolean isValid = false;
//
// /** Query's ADQL version target. */
// public ADQLVersion adqlVersion = ValidationSetParser.DEFAULT_ADQL_VERSION;
//
// /**
// * Create a {@link ValidationQuery} with a generated UUID.
// */
// public ValidationQuery(){
// this((UUID)null);
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final UUID id){
// this.id = (id == null) ? UUID.randomUUID() : id;
// }
//
// /**
// * Create a {@link ValidationQuery} with the given UUID.
// *
// * @param id UUID of this validation test.
// * <i>If NULL, one will be automatically generated.</i>
// */
// public ValidationQuery(final String id){
// this.id = (id == null || id.trim().length() == 0) ? UUID.randomUUID() : UUID.fromString(id);
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// final ValidationQuery testQuery = (ValidationQuery) o;
// return id.equals(testQuery.id);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(id);
// }
//
// }
//
// Path: src/adql-validator/src/cds/adql/validation/query/ValidationSet.java
// public class ValidationSet {
//
// /** Person/Entity to contact in case of question/comment about this set. */
// public Contact contact = null;
//
// /** Person/Entity who published this set. */
// public Publisher publisher = null;
//
// /** Human description of this entire set.*/
// public String description = null;
//
// /** Set of all Validation Tests included inside this set.
// * <p>
// * It contains only unique items: no two {@link ValidationQuery}
// * instances have the same UUID.
// * </p> */
// public final Set<ValidationQuery> queries = new LinkedHashSet<>(30);
//
// }
// Path: src/adql-validator/test/cds/adql/validation/report/RecorderListener.java
import cds.adql.validation.ValidationException;
import cds.adql.validation.query.ValidationQuery;
import cds.adql.validation.query.ValidationSet;
public int getCntFail() {
return cntFail;
}
public boolean isSetStarted() {
return setStarted;
}
public boolean isSetEnded() {
return setEnded;
}
public boolean isQueryStarted() {
return queryStarted;
}
public boolean isQueryEnded() {
return queryEnded;
}
@Override
public void start(ValidationSet set, String source) {
setStarted = true;
setEnded = false;
queryStarted = false;
queryEnded = false;
}
@Override | public void validating(ValidationQuery query) { |
all4you/redant | redant-core/src/main/java/com/redant/core/controller/ControllerProxy.java | // Path: redant-core/src/main/java/com/redant/core/common/enums/RequestMethod.java
// public enum RequestMethod {
// /**
// * GET
// */
// GET(HttpMethod.GET),
// /**
// * HEAD
// */
// HEAD(HttpMethod.HEAD),
// /**
// * POST
// */
// POST(HttpMethod.POST),
// /**
// * PUT
// */
// PUT(HttpMethod.PUT),
// /**
// * PATCH
// */
// PATCH(HttpMethod.PATCH),
// /**
// * DELETE
// */
// DELETE(HttpMethod.DELETE),
// /**
// * OPTIONS
// */
// OPTIONS(HttpMethod.OPTIONS),
// /**
// * TRACE
// */
// TRACE(HttpMethod.TRACE);
//
// HttpMethod httpMethod;
//
// RequestMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public static HttpMethod getHttpMethod(RequestMethod requestMethod){
// for(RequestMethod method : values()){
// if(requestMethod==method){
// return method.httpMethod;
// }
// }
// return null;
// }
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/render/RenderType.java
// public enum RenderType {
//
// /**
// * JSON
// */
// JSON("application/json;charset=UTF-8"),
// /**
// * XML
// */
// XML("text/xml;charset=UTF-8"),
// /**
// * TEXT
// */
// TEXT("text/plain;charset=UTF-8"),
// /**
// * HTML
// */
// HTML("text/html;charset=UTF-8");
//
// private String contentType;
//
// RenderType(String contentType){
// this.contentType = contentType;
// }
//
// public String getContentType() {
// return contentType;
// }
// }
| import com.redant.core.common.enums.RequestMethod;
import com.redant.core.render.RenderType;
import java.lang.reflect.Method; | package com.redant.core.controller;
/**
* 路由请求代理,用以根据路由调用具体的controller类
* @author houyi.wh
* @date 2017-10-20
*/
public class ControllerProxy {
private RenderType renderType;
| // Path: redant-core/src/main/java/com/redant/core/common/enums/RequestMethod.java
// public enum RequestMethod {
// /**
// * GET
// */
// GET(HttpMethod.GET),
// /**
// * HEAD
// */
// HEAD(HttpMethod.HEAD),
// /**
// * POST
// */
// POST(HttpMethod.POST),
// /**
// * PUT
// */
// PUT(HttpMethod.PUT),
// /**
// * PATCH
// */
// PATCH(HttpMethod.PATCH),
// /**
// * DELETE
// */
// DELETE(HttpMethod.DELETE),
// /**
// * OPTIONS
// */
// OPTIONS(HttpMethod.OPTIONS),
// /**
// * TRACE
// */
// TRACE(HttpMethod.TRACE);
//
// HttpMethod httpMethod;
//
// RequestMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public static HttpMethod getHttpMethod(RequestMethod requestMethod){
// for(RequestMethod method : values()){
// if(requestMethod==method){
// return method.httpMethod;
// }
// }
// return null;
// }
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/render/RenderType.java
// public enum RenderType {
//
// /**
// * JSON
// */
// JSON("application/json;charset=UTF-8"),
// /**
// * XML
// */
// XML("text/xml;charset=UTF-8"),
// /**
// * TEXT
// */
// TEXT("text/plain;charset=UTF-8"),
// /**
// * HTML
// */
// HTML("text/html;charset=UTF-8");
//
// private String contentType;
//
// RenderType(String contentType){
// this.contentType = contentType;
// }
//
// public String getContentType() {
// return contentType;
// }
// }
// Path: redant-core/src/main/java/com/redant/core/controller/ControllerProxy.java
import com.redant.core.common.enums.RequestMethod;
import com.redant.core.render.RenderType;
import java.lang.reflect.Method;
package com.redant.core.controller;
/**
* 路由请求代理,用以根据路由调用具体的controller类
* @author houyi.wh
* @date 2017-10-20
*/
public class ControllerProxy {
private RenderType renderType;
| private RequestMethod requestMethod; |
all4you/redant | redant-example/src/main/java/com/redant/example/controller/UserController.java | // Path: redant-core/src/main/java/com/redant/core/common/enums/RequestMethod.java
// public enum RequestMethod {
// /**
// * GET
// */
// GET(HttpMethod.GET),
// /**
// * HEAD
// */
// HEAD(HttpMethod.HEAD),
// /**
// * POST
// */
// POST(HttpMethod.POST),
// /**
// * PUT
// */
// PUT(HttpMethod.PUT),
// /**
// * PATCH
// */
// PATCH(HttpMethod.PATCH),
// /**
// * DELETE
// */
// DELETE(HttpMethod.DELETE),
// /**
// * OPTIONS
// */
// OPTIONS(HttpMethod.OPTIONS),
// /**
// * TRACE
// */
// TRACE(HttpMethod.TRACE);
//
// HttpMethod httpMethod;
//
// RequestMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public static HttpMethod getHttpMethod(RequestMethod requestMethod){
// for(RequestMethod method : values()){
// if(requestMethod==method){
// return method.httpMethod;
// }
// }
// return null;
// }
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/render/RenderType.java
// public enum RenderType {
//
// /**
// * JSON
// */
// JSON("application/json;charset=UTF-8"),
// /**
// * XML
// */
// XML("text/xml;charset=UTF-8"),
// /**
// * TEXT
// */
// TEXT("text/plain;charset=UTF-8"),
// /**
// * HTML
// */
// HTML("text/html;charset=UTF-8");
//
// private String contentType;
//
// RenderType(String contentType){
// this.contentType = contentType;
// }
//
// public String getContentType() {
// return contentType;
// }
// }
//
// Path: redant-example/src/main/java/com/redant/example/service/UserBean.java
// public class UserBean implements Serializable {
//
// private Integer id;
//
// private String userName;
//
// private String password;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// @Override
// public String toString() {
// return JSON.toJSONString(this);
// }
// }
//
// Path: redant-example/src/main/java/com/redant/example/service/UserService.java
// public interface UserService {
//
// /**
// * 获取用户信息
// * @param id 用户id
// * @return 用户信息
// */
// UserBean selectUserInfo(Integer id);
//
// /**
// * 获取用户个数
// * @return 用户个数
// */
// int selectCount();
// }
| import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.redant.core.bean.annotation.Autowired;
import com.redant.core.bean.annotation.Bean;
import com.redant.core.common.enums.RequestMethod;
import com.redant.core.controller.annotation.Controller;
import com.redant.core.controller.annotation.Mapping;
import com.redant.core.controller.annotation.Param;
import com.redant.core.render.RenderType;
import com.redant.example.service.UserBean;
import com.redant.example.service.UserService;
import java.util.concurrent.TimeUnit; | package com.redant.example.controller;
/**
* @author houyi.wh
* @date 2017/12/1
**/
@Bean
@Controller(path = "/user")
public class UserController {
/**
* 如果需要使用Autowired,则该类自身需要使用Bean注解标注
*/
@Autowired(name = "userService") | // Path: redant-core/src/main/java/com/redant/core/common/enums/RequestMethod.java
// public enum RequestMethod {
// /**
// * GET
// */
// GET(HttpMethod.GET),
// /**
// * HEAD
// */
// HEAD(HttpMethod.HEAD),
// /**
// * POST
// */
// POST(HttpMethod.POST),
// /**
// * PUT
// */
// PUT(HttpMethod.PUT),
// /**
// * PATCH
// */
// PATCH(HttpMethod.PATCH),
// /**
// * DELETE
// */
// DELETE(HttpMethod.DELETE),
// /**
// * OPTIONS
// */
// OPTIONS(HttpMethod.OPTIONS),
// /**
// * TRACE
// */
// TRACE(HttpMethod.TRACE);
//
// HttpMethod httpMethod;
//
// RequestMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public static HttpMethod getHttpMethod(RequestMethod requestMethod){
// for(RequestMethod method : values()){
// if(requestMethod==method){
// return method.httpMethod;
// }
// }
// return null;
// }
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/render/RenderType.java
// public enum RenderType {
//
// /**
// * JSON
// */
// JSON("application/json;charset=UTF-8"),
// /**
// * XML
// */
// XML("text/xml;charset=UTF-8"),
// /**
// * TEXT
// */
// TEXT("text/plain;charset=UTF-8"),
// /**
// * HTML
// */
// HTML("text/html;charset=UTF-8");
//
// private String contentType;
//
// RenderType(String contentType){
// this.contentType = contentType;
// }
//
// public String getContentType() {
// return contentType;
// }
// }
//
// Path: redant-example/src/main/java/com/redant/example/service/UserBean.java
// public class UserBean implements Serializable {
//
// private Integer id;
//
// private String userName;
//
// private String password;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// @Override
// public String toString() {
// return JSON.toJSONString(this);
// }
// }
//
// Path: redant-example/src/main/java/com/redant/example/service/UserService.java
// public interface UserService {
//
// /**
// * 获取用户信息
// * @param id 用户id
// * @return 用户信息
// */
// UserBean selectUserInfo(Integer id);
//
// /**
// * 获取用户个数
// * @return 用户个数
// */
// int selectCount();
// }
// Path: redant-example/src/main/java/com/redant/example/controller/UserController.java
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.redant.core.bean.annotation.Autowired;
import com.redant.core.bean.annotation.Bean;
import com.redant.core.common.enums.RequestMethod;
import com.redant.core.controller.annotation.Controller;
import com.redant.core.controller.annotation.Mapping;
import com.redant.core.controller.annotation.Param;
import com.redant.core.render.RenderType;
import com.redant.example.service.UserBean;
import com.redant.example.service.UserService;
import java.util.concurrent.TimeUnit;
package com.redant.example.controller;
/**
* @author houyi.wh
* @date 2017/12/1
**/
@Bean
@Controller(path = "/user")
public class UserController {
/**
* 如果需要使用Autowired,则该类自身需要使用Bean注解标注
*/
@Autowired(name = "userService") | private UserService userService; |
all4you/redant | redant-example/src/main/java/com/redant/example/controller/UserController.java | // Path: redant-core/src/main/java/com/redant/core/common/enums/RequestMethod.java
// public enum RequestMethod {
// /**
// * GET
// */
// GET(HttpMethod.GET),
// /**
// * HEAD
// */
// HEAD(HttpMethod.HEAD),
// /**
// * POST
// */
// POST(HttpMethod.POST),
// /**
// * PUT
// */
// PUT(HttpMethod.PUT),
// /**
// * PATCH
// */
// PATCH(HttpMethod.PATCH),
// /**
// * DELETE
// */
// DELETE(HttpMethod.DELETE),
// /**
// * OPTIONS
// */
// OPTIONS(HttpMethod.OPTIONS),
// /**
// * TRACE
// */
// TRACE(HttpMethod.TRACE);
//
// HttpMethod httpMethod;
//
// RequestMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public static HttpMethod getHttpMethod(RequestMethod requestMethod){
// for(RequestMethod method : values()){
// if(requestMethod==method){
// return method.httpMethod;
// }
// }
// return null;
// }
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/render/RenderType.java
// public enum RenderType {
//
// /**
// * JSON
// */
// JSON("application/json;charset=UTF-8"),
// /**
// * XML
// */
// XML("text/xml;charset=UTF-8"),
// /**
// * TEXT
// */
// TEXT("text/plain;charset=UTF-8"),
// /**
// * HTML
// */
// HTML("text/html;charset=UTF-8");
//
// private String contentType;
//
// RenderType(String contentType){
// this.contentType = contentType;
// }
//
// public String getContentType() {
// return contentType;
// }
// }
//
// Path: redant-example/src/main/java/com/redant/example/service/UserBean.java
// public class UserBean implements Serializable {
//
// private Integer id;
//
// private String userName;
//
// private String password;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// @Override
// public String toString() {
// return JSON.toJSONString(this);
// }
// }
//
// Path: redant-example/src/main/java/com/redant/example/service/UserService.java
// public interface UserService {
//
// /**
// * 获取用户信息
// * @param id 用户id
// * @return 用户信息
// */
// UserBean selectUserInfo(Integer id);
//
// /**
// * 获取用户个数
// * @return 用户个数
// */
// int selectCount();
// }
| import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.redant.core.bean.annotation.Autowired;
import com.redant.core.bean.annotation.Bean;
import com.redant.core.common.enums.RequestMethod;
import com.redant.core.controller.annotation.Controller;
import com.redant.core.controller.annotation.Mapping;
import com.redant.core.controller.annotation.Param;
import com.redant.core.render.RenderType;
import com.redant.example.service.UserBean;
import com.redant.example.service.UserService;
import java.util.concurrent.TimeUnit; | package com.redant.example.controller;
/**
* @author houyi.wh
* @date 2017/12/1
**/
@Bean
@Controller(path = "/user")
public class UserController {
/**
* 如果需要使用Autowired,则该类自身需要使用Bean注解标注
*/
@Autowired(name = "userService")
private UserService userService;
| // Path: redant-core/src/main/java/com/redant/core/common/enums/RequestMethod.java
// public enum RequestMethod {
// /**
// * GET
// */
// GET(HttpMethod.GET),
// /**
// * HEAD
// */
// HEAD(HttpMethod.HEAD),
// /**
// * POST
// */
// POST(HttpMethod.POST),
// /**
// * PUT
// */
// PUT(HttpMethod.PUT),
// /**
// * PATCH
// */
// PATCH(HttpMethod.PATCH),
// /**
// * DELETE
// */
// DELETE(HttpMethod.DELETE),
// /**
// * OPTIONS
// */
// OPTIONS(HttpMethod.OPTIONS),
// /**
// * TRACE
// */
// TRACE(HttpMethod.TRACE);
//
// HttpMethod httpMethod;
//
// RequestMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public static HttpMethod getHttpMethod(RequestMethod requestMethod){
// for(RequestMethod method : values()){
// if(requestMethod==method){
// return method.httpMethod;
// }
// }
// return null;
// }
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/render/RenderType.java
// public enum RenderType {
//
// /**
// * JSON
// */
// JSON("application/json;charset=UTF-8"),
// /**
// * XML
// */
// XML("text/xml;charset=UTF-8"),
// /**
// * TEXT
// */
// TEXT("text/plain;charset=UTF-8"),
// /**
// * HTML
// */
// HTML("text/html;charset=UTF-8");
//
// private String contentType;
//
// RenderType(String contentType){
// this.contentType = contentType;
// }
//
// public String getContentType() {
// return contentType;
// }
// }
//
// Path: redant-example/src/main/java/com/redant/example/service/UserBean.java
// public class UserBean implements Serializable {
//
// private Integer id;
//
// private String userName;
//
// private String password;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// @Override
// public String toString() {
// return JSON.toJSONString(this);
// }
// }
//
// Path: redant-example/src/main/java/com/redant/example/service/UserService.java
// public interface UserService {
//
// /**
// * 获取用户信息
// * @param id 用户id
// * @return 用户信息
// */
// UserBean selectUserInfo(Integer id);
//
// /**
// * 获取用户个数
// * @return 用户个数
// */
// int selectCount();
// }
// Path: redant-example/src/main/java/com/redant/example/controller/UserController.java
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.redant.core.bean.annotation.Autowired;
import com.redant.core.bean.annotation.Bean;
import com.redant.core.common.enums.RequestMethod;
import com.redant.core.controller.annotation.Controller;
import com.redant.core.controller.annotation.Mapping;
import com.redant.core.controller.annotation.Param;
import com.redant.core.render.RenderType;
import com.redant.example.service.UserBean;
import com.redant.example.service.UserService;
import java.util.concurrent.TimeUnit;
package com.redant.example.controller;
/**
* @author houyi.wh
* @date 2017/12/1
**/
@Bean
@Controller(path = "/user")
public class UserController {
/**
* 如果需要使用Autowired,则该类自身需要使用Bean注解标注
*/
@Autowired(name = "userService")
private UserService userService;
| @Mapping(path = "/info", requestMethod = RequestMethod.GET, renderType = RenderType.JSON) |
all4you/redant | redant-example/src/main/java/com/redant/example/controller/UserController.java | // Path: redant-core/src/main/java/com/redant/core/common/enums/RequestMethod.java
// public enum RequestMethod {
// /**
// * GET
// */
// GET(HttpMethod.GET),
// /**
// * HEAD
// */
// HEAD(HttpMethod.HEAD),
// /**
// * POST
// */
// POST(HttpMethod.POST),
// /**
// * PUT
// */
// PUT(HttpMethod.PUT),
// /**
// * PATCH
// */
// PATCH(HttpMethod.PATCH),
// /**
// * DELETE
// */
// DELETE(HttpMethod.DELETE),
// /**
// * OPTIONS
// */
// OPTIONS(HttpMethod.OPTIONS),
// /**
// * TRACE
// */
// TRACE(HttpMethod.TRACE);
//
// HttpMethod httpMethod;
//
// RequestMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public static HttpMethod getHttpMethod(RequestMethod requestMethod){
// for(RequestMethod method : values()){
// if(requestMethod==method){
// return method.httpMethod;
// }
// }
// return null;
// }
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/render/RenderType.java
// public enum RenderType {
//
// /**
// * JSON
// */
// JSON("application/json;charset=UTF-8"),
// /**
// * XML
// */
// XML("text/xml;charset=UTF-8"),
// /**
// * TEXT
// */
// TEXT("text/plain;charset=UTF-8"),
// /**
// * HTML
// */
// HTML("text/html;charset=UTF-8");
//
// private String contentType;
//
// RenderType(String contentType){
// this.contentType = contentType;
// }
//
// public String getContentType() {
// return contentType;
// }
// }
//
// Path: redant-example/src/main/java/com/redant/example/service/UserBean.java
// public class UserBean implements Serializable {
//
// private Integer id;
//
// private String userName;
//
// private String password;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// @Override
// public String toString() {
// return JSON.toJSONString(this);
// }
// }
//
// Path: redant-example/src/main/java/com/redant/example/service/UserService.java
// public interface UserService {
//
// /**
// * 获取用户信息
// * @param id 用户id
// * @return 用户信息
// */
// UserBean selectUserInfo(Integer id);
//
// /**
// * 获取用户个数
// * @return 用户个数
// */
// int selectCount();
// }
| import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.redant.core.bean.annotation.Autowired;
import com.redant.core.bean.annotation.Bean;
import com.redant.core.common.enums.RequestMethod;
import com.redant.core.controller.annotation.Controller;
import com.redant.core.controller.annotation.Mapping;
import com.redant.core.controller.annotation.Param;
import com.redant.core.render.RenderType;
import com.redant.example.service.UserBean;
import com.redant.example.service.UserService;
import java.util.concurrent.TimeUnit; | package com.redant.example.controller;
/**
* @author houyi.wh
* @date 2017/12/1
**/
@Bean
@Controller(path = "/user")
public class UserController {
/**
* 如果需要使用Autowired,则该类自身需要使用Bean注解标注
*/
@Autowired(name = "userService")
private UserService userService;
| // Path: redant-core/src/main/java/com/redant/core/common/enums/RequestMethod.java
// public enum RequestMethod {
// /**
// * GET
// */
// GET(HttpMethod.GET),
// /**
// * HEAD
// */
// HEAD(HttpMethod.HEAD),
// /**
// * POST
// */
// POST(HttpMethod.POST),
// /**
// * PUT
// */
// PUT(HttpMethod.PUT),
// /**
// * PATCH
// */
// PATCH(HttpMethod.PATCH),
// /**
// * DELETE
// */
// DELETE(HttpMethod.DELETE),
// /**
// * OPTIONS
// */
// OPTIONS(HttpMethod.OPTIONS),
// /**
// * TRACE
// */
// TRACE(HttpMethod.TRACE);
//
// HttpMethod httpMethod;
//
// RequestMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public static HttpMethod getHttpMethod(RequestMethod requestMethod){
// for(RequestMethod method : values()){
// if(requestMethod==method){
// return method.httpMethod;
// }
// }
// return null;
// }
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/render/RenderType.java
// public enum RenderType {
//
// /**
// * JSON
// */
// JSON("application/json;charset=UTF-8"),
// /**
// * XML
// */
// XML("text/xml;charset=UTF-8"),
// /**
// * TEXT
// */
// TEXT("text/plain;charset=UTF-8"),
// /**
// * HTML
// */
// HTML("text/html;charset=UTF-8");
//
// private String contentType;
//
// RenderType(String contentType){
// this.contentType = contentType;
// }
//
// public String getContentType() {
// return contentType;
// }
// }
//
// Path: redant-example/src/main/java/com/redant/example/service/UserBean.java
// public class UserBean implements Serializable {
//
// private Integer id;
//
// private String userName;
//
// private String password;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// @Override
// public String toString() {
// return JSON.toJSONString(this);
// }
// }
//
// Path: redant-example/src/main/java/com/redant/example/service/UserService.java
// public interface UserService {
//
// /**
// * 获取用户信息
// * @param id 用户id
// * @return 用户信息
// */
// UserBean selectUserInfo(Integer id);
//
// /**
// * 获取用户个数
// * @return 用户个数
// */
// int selectCount();
// }
// Path: redant-example/src/main/java/com/redant/example/controller/UserController.java
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.redant.core.bean.annotation.Autowired;
import com.redant.core.bean.annotation.Bean;
import com.redant.core.common.enums.RequestMethod;
import com.redant.core.controller.annotation.Controller;
import com.redant.core.controller.annotation.Mapping;
import com.redant.core.controller.annotation.Param;
import com.redant.core.render.RenderType;
import com.redant.example.service.UserBean;
import com.redant.example.service.UserService;
import java.util.concurrent.TimeUnit;
package com.redant.example.controller;
/**
* @author houyi.wh
* @date 2017/12/1
**/
@Bean
@Controller(path = "/user")
public class UserController {
/**
* 如果需要使用Autowired,则该类自身需要使用Bean注解标注
*/
@Autowired(name = "userService")
private UserService userService;
| @Mapping(path = "/info", requestMethod = RequestMethod.GET, renderType = RenderType.JSON) |
all4you/redant | redant-example/src/main/java/com/redant/example/controller/UserController.java | // Path: redant-core/src/main/java/com/redant/core/common/enums/RequestMethod.java
// public enum RequestMethod {
// /**
// * GET
// */
// GET(HttpMethod.GET),
// /**
// * HEAD
// */
// HEAD(HttpMethod.HEAD),
// /**
// * POST
// */
// POST(HttpMethod.POST),
// /**
// * PUT
// */
// PUT(HttpMethod.PUT),
// /**
// * PATCH
// */
// PATCH(HttpMethod.PATCH),
// /**
// * DELETE
// */
// DELETE(HttpMethod.DELETE),
// /**
// * OPTIONS
// */
// OPTIONS(HttpMethod.OPTIONS),
// /**
// * TRACE
// */
// TRACE(HttpMethod.TRACE);
//
// HttpMethod httpMethod;
//
// RequestMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public static HttpMethod getHttpMethod(RequestMethod requestMethod){
// for(RequestMethod method : values()){
// if(requestMethod==method){
// return method.httpMethod;
// }
// }
// return null;
// }
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/render/RenderType.java
// public enum RenderType {
//
// /**
// * JSON
// */
// JSON("application/json;charset=UTF-8"),
// /**
// * XML
// */
// XML("text/xml;charset=UTF-8"),
// /**
// * TEXT
// */
// TEXT("text/plain;charset=UTF-8"),
// /**
// * HTML
// */
// HTML("text/html;charset=UTF-8");
//
// private String contentType;
//
// RenderType(String contentType){
// this.contentType = contentType;
// }
//
// public String getContentType() {
// return contentType;
// }
// }
//
// Path: redant-example/src/main/java/com/redant/example/service/UserBean.java
// public class UserBean implements Serializable {
//
// private Integer id;
//
// private String userName;
//
// private String password;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// @Override
// public String toString() {
// return JSON.toJSONString(this);
// }
// }
//
// Path: redant-example/src/main/java/com/redant/example/service/UserService.java
// public interface UserService {
//
// /**
// * 获取用户信息
// * @param id 用户id
// * @return 用户信息
// */
// UserBean selectUserInfo(Integer id);
//
// /**
// * 获取用户个数
// * @return 用户个数
// */
// int selectCount();
// }
| import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.redant.core.bean.annotation.Autowired;
import com.redant.core.bean.annotation.Bean;
import com.redant.core.common.enums.RequestMethod;
import com.redant.core.controller.annotation.Controller;
import com.redant.core.controller.annotation.Mapping;
import com.redant.core.controller.annotation.Param;
import com.redant.core.render.RenderType;
import com.redant.example.service.UserBean;
import com.redant.example.service.UserService;
import java.util.concurrent.TimeUnit; | package com.redant.example.controller;
/**
* @author houyi.wh
* @date 2017/12/1
**/
@Bean
@Controller(path = "/user")
public class UserController {
/**
* 如果需要使用Autowired,则该类自身需要使用Bean注解标注
*/
@Autowired(name = "userService")
private UserService userService;
@Mapping(path = "/info", requestMethod = RequestMethod.GET, renderType = RenderType.JSON) | // Path: redant-core/src/main/java/com/redant/core/common/enums/RequestMethod.java
// public enum RequestMethod {
// /**
// * GET
// */
// GET(HttpMethod.GET),
// /**
// * HEAD
// */
// HEAD(HttpMethod.HEAD),
// /**
// * POST
// */
// POST(HttpMethod.POST),
// /**
// * PUT
// */
// PUT(HttpMethod.PUT),
// /**
// * PATCH
// */
// PATCH(HttpMethod.PATCH),
// /**
// * DELETE
// */
// DELETE(HttpMethod.DELETE),
// /**
// * OPTIONS
// */
// OPTIONS(HttpMethod.OPTIONS),
// /**
// * TRACE
// */
// TRACE(HttpMethod.TRACE);
//
// HttpMethod httpMethod;
//
// RequestMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public static HttpMethod getHttpMethod(RequestMethod requestMethod){
// for(RequestMethod method : values()){
// if(requestMethod==method){
// return method.httpMethod;
// }
// }
// return null;
// }
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/render/RenderType.java
// public enum RenderType {
//
// /**
// * JSON
// */
// JSON("application/json;charset=UTF-8"),
// /**
// * XML
// */
// XML("text/xml;charset=UTF-8"),
// /**
// * TEXT
// */
// TEXT("text/plain;charset=UTF-8"),
// /**
// * HTML
// */
// HTML("text/html;charset=UTF-8");
//
// private String contentType;
//
// RenderType(String contentType){
// this.contentType = contentType;
// }
//
// public String getContentType() {
// return contentType;
// }
// }
//
// Path: redant-example/src/main/java/com/redant/example/service/UserBean.java
// public class UserBean implements Serializable {
//
// private Integer id;
//
// private String userName;
//
// private String password;
//
// public Integer getId() {
// return id;
// }
//
// public void setId(Integer id) {
// this.id = id;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// @Override
// public String toString() {
// return JSON.toJSONString(this);
// }
// }
//
// Path: redant-example/src/main/java/com/redant/example/service/UserService.java
// public interface UserService {
//
// /**
// * 获取用户信息
// * @param id 用户id
// * @return 用户信息
// */
// UserBean selectUserInfo(Integer id);
//
// /**
// * 获取用户个数
// * @return 用户个数
// */
// int selectCount();
// }
// Path: redant-example/src/main/java/com/redant/example/controller/UserController.java
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.redant.core.bean.annotation.Autowired;
import com.redant.core.bean.annotation.Bean;
import com.redant.core.common.enums.RequestMethod;
import com.redant.core.controller.annotation.Controller;
import com.redant.core.controller.annotation.Mapping;
import com.redant.core.controller.annotation.Param;
import com.redant.core.render.RenderType;
import com.redant.example.service.UserBean;
import com.redant.example.service.UserService;
import java.util.concurrent.TimeUnit;
package com.redant.example.controller;
/**
* @author houyi.wh
* @date 2017/12/1
**/
@Bean
@Controller(path = "/user")
public class UserController {
/**
* 如果需要使用Autowired,则该类自身需要使用Bean注解标注
*/
@Autowired(name = "userService")
private UserService userService;
@Mapping(path = "/info", requestMethod = RequestMethod.GET, renderType = RenderType.JSON) | public UserBean info(@Param(key = "id", notNull = true) Integer id) { |
all4you/redant | redant-core/src/main/java/com/redant/core/session/SessionHelper.java | // Path: redant-core/src/main/java/com/redant/core/common/exception/InvalidSessionException.java
// public class InvalidSessionException extends RuntimeException{
// private static final long serialVersionUID = 1L;
//
// public InvalidSessionException(String s) {
// super(s);
// }
//
// }
| import com.redant.core.common.exception.InvalidSessionException;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; | package com.redant.core.session;
/**
* Session辅助器
* @author houyi.wh
* @date 2017/11/6
*/
public class SessionHelper {
/**
* 保存session对象的map
*/
private Map<ChannelId,HttpSession> sessionMap;
private static SessionHelper manager;
private SessionHelper(){
}
//======================================
/**
* 获取单例
* @return
*/
public static SessionHelper instange(){
synchronized (SessionHelper.class) {
if (manager == null) {
manager = new SessionHelper();
if (manager.sessionMap == null) {
// 需要线程安全的Map
manager.sessionMap = new ConcurrentHashMap<ChannelId,HttpSession>();
}
}
}
return manager;
}
/**
* 判断session是否存在
* @param context
* @return
*/
public boolean containsSession(ChannelHandlerContext context){
return context!=null && context.channel()!=null && context.channel().id()!=null && manager.sessionMap.get(context.channel().id())!=null;
}
/**
* 添加一个session
* @param context
* @param session
*/
public void addSession(ChannelHandlerContext context,HttpSession session){
if(context==null || context.channel()==null || context.channel().id()==null || session==null){ | // Path: redant-core/src/main/java/com/redant/core/common/exception/InvalidSessionException.java
// public class InvalidSessionException extends RuntimeException{
// private static final long serialVersionUID = 1L;
//
// public InvalidSessionException(String s) {
// super(s);
// }
//
// }
// Path: redant-core/src/main/java/com/redant/core/session/SessionHelper.java
import com.redant.core.common.exception.InvalidSessionException;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
package com.redant.core.session;
/**
* Session辅助器
* @author houyi.wh
* @date 2017/11/6
*/
public class SessionHelper {
/**
* 保存session对象的map
*/
private Map<ChannelId,HttpSession> sessionMap;
private static SessionHelper manager;
private SessionHelper(){
}
//======================================
/**
* 获取单例
* @return
*/
public static SessionHelper instange(){
synchronized (SessionHelper.class) {
if (manager == null) {
manager = new SessionHelper();
if (manager.sessionMap == null) {
// 需要线程安全的Map
manager.sessionMap = new ConcurrentHashMap<ChannelId,HttpSession>();
}
}
}
return manager;
}
/**
* 判断session是否存在
* @param context
* @return
*/
public boolean containsSession(ChannelHandlerContext context){
return context!=null && context.channel()!=null && context.channel().id()!=null && manager.sessionMap.get(context.channel().id())!=null;
}
/**
* 添加一个session
* @param context
* @param session
*/
public void addSession(ChannelHandlerContext context,HttpSession session){
if(context==null || context.channel()==null || context.channel().id()==null || session==null){ | throw new InvalidSessionException("context or session is null"); |
all4you/redant | redant-core/src/main/java/com/redant/core/interceptor/InterceptorProvider.java | // Path: redant-core/src/main/java/com/redant/core/common/constants/CommonConstants.java
// public class CommonConstants {
//
//
// private static final String REDANT_PROPERTIES_PATH = "/redant.properties";
//
// private static PropertiesUtil propertiesUtil = PropertiesUtil.getInstance(REDANT_PROPERTIES_PATH);
//
// /**
// * 服务端口号
// */
// public static final int SERVER_PORT = propertiesUtil.getInt("netty.server.port",8888);
//
// /**
// * BossGroup Size
// * 先从启动参数中获取:-Dnetty.server.bossGroup.size=2
// * 如果获取不到从配置文件中获取
// * 如果再获取不到则取默认值
// */
// public static final int BOSS_GROUP_SIZE = null!=Integer.getInteger("netty.server.bossGroup.size")?Integer.getInteger("netty.server.bossGroup.size"):propertiesUtil.getInt("netty.server.bossGroup.size",2);
//
// /**
// * WorkerGroup Size
// * 先从启动参数中获取:-Dnetty.server.workerGroup.size=4
// * 如果获取不到从配置文件中获取
// * 如果再获取不到则取默认值
// */
// public static final int WORKER_GROUP_SIZE = null!=Integer.getInteger("netty.server.workerGroup.size")?Integer.getInteger("netty.server.workerGroup.size"):propertiesUtil.getInt("netty.server.workerGroup.size",4);
//
// /**
// * 能处理的最大数据的字节数
// */
// public static final int MAX_CONTENT_LENGTH = propertiesUtil.getInt("netty.maxContentLength",10485760);
//
// /**
// * 是否开启ssl
// */
// public static final boolean USE_SSL = propertiesUtil.getBoolean("netty.server.use.ssl");
//
// /**
// * 是否开启压缩
// */
// public static final boolean USE_COMPRESS = propertiesUtil.getBoolean("netty.server.use.compress");
//
// /**
// * 是否开启http对象聚合
// */
// public static final boolean USE_AGGREGATOR = propertiesUtil.getBoolean("netty.server.use.aggregator");
//
// /**
// * KeyStore path
// */
// public static final String KEY_STORE_PATH = propertiesUtil.getString("ssl.keyStore.path");
//
// /**
// * KeyStore password
// */
// public static final String KEY_STORE_PASSWORD = propertiesUtil.getString("ssl.keyStore.password");
//
// /**
// * 扫描bean的包路径
// */
// public static final String BEAN_SCAN_PACKAGE = propertiesUtil.getString("bean.scan.package");
//
// /**
// * 扫描interceptor的包路径
// */
// public static final String INTERCEPTOR_SCAN_PACKAGE = propertiesUtil.getString("interceptor.scan.package");
//
// /**
// * 服务端出错时的错误描述
// */
// public static final String SERVER_INTERNAL_ERROR_DESC = propertiesUtil.getString("server.internal.error.desc");
//
// public static final String FAVICON_ICO = "/favicon.ico";
//
// public static final String CONNECTION_KEEP_ALIVE = "keep-alive";
//
// public static final String CONNECTION_CLOSE = "close";
//
// /**
// * 是否异步处理业务逻辑
// */
// public static final boolean ASYNC_EXECUTE_EVENT = propertiesUtil.getBoolean("async.execute.event");
//
// /**
// * 业务线程池核心线程数
// */
// public static final int EVENT_EXECUTOR_POOL_CORE_SIZE = propertiesUtil.getInt("async.executor.pool.core.size",10);
//
// /**
// * 业务线程池最大线程数
// */
// public static final int EVENT_EXECUTOR_POOL_MAX_SIZE = propertiesUtil.getInt("async.executor.pool.max.size",20);
//
// /**
// * 业务线程池临时线程存活时间,单位:s
// */
// public static final int EVENT_EXECUTOR_POOL_KEEP_ALIVE_SECONDS = propertiesUtil.getInt("async.executor.pool.keep.alive.seconds",10);
//
// /**
// * 业务线程池阻塞队列大学
// */
// public static final int EVENT_EXECUTOR_POOL_BLOCKING_QUEUE_SIZE = propertiesUtil.getInt("async.executor.pool.blocking.queue.size",10);
//
// }
| import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.ClassScaner;
import com.redant.core.anno.Order;
import com.redant.core.common.constants.CommonConstants;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors; | package com.redant.core.interceptor;
/**
* @author houyi
**/
public class InterceptorProvider {
private static volatile boolean loaded = false;
private static volatile InterceptorBuilder builder = null;
public static List<Interceptor> getInterceptors(){
// 优先获取用户自定义的 InterceptorBuilder 构造的 Interceptor
if(!loaded){
synchronized (InterceptorProvider.class) {
if(!loaded) { | // Path: redant-core/src/main/java/com/redant/core/common/constants/CommonConstants.java
// public class CommonConstants {
//
//
// private static final String REDANT_PROPERTIES_PATH = "/redant.properties";
//
// private static PropertiesUtil propertiesUtil = PropertiesUtil.getInstance(REDANT_PROPERTIES_PATH);
//
// /**
// * 服务端口号
// */
// public static final int SERVER_PORT = propertiesUtil.getInt("netty.server.port",8888);
//
// /**
// * BossGroup Size
// * 先从启动参数中获取:-Dnetty.server.bossGroup.size=2
// * 如果获取不到从配置文件中获取
// * 如果再获取不到则取默认值
// */
// public static final int BOSS_GROUP_SIZE = null!=Integer.getInteger("netty.server.bossGroup.size")?Integer.getInteger("netty.server.bossGroup.size"):propertiesUtil.getInt("netty.server.bossGroup.size",2);
//
// /**
// * WorkerGroup Size
// * 先从启动参数中获取:-Dnetty.server.workerGroup.size=4
// * 如果获取不到从配置文件中获取
// * 如果再获取不到则取默认值
// */
// public static final int WORKER_GROUP_SIZE = null!=Integer.getInteger("netty.server.workerGroup.size")?Integer.getInteger("netty.server.workerGroup.size"):propertiesUtil.getInt("netty.server.workerGroup.size",4);
//
// /**
// * 能处理的最大数据的字节数
// */
// public static final int MAX_CONTENT_LENGTH = propertiesUtil.getInt("netty.maxContentLength",10485760);
//
// /**
// * 是否开启ssl
// */
// public static final boolean USE_SSL = propertiesUtil.getBoolean("netty.server.use.ssl");
//
// /**
// * 是否开启压缩
// */
// public static final boolean USE_COMPRESS = propertiesUtil.getBoolean("netty.server.use.compress");
//
// /**
// * 是否开启http对象聚合
// */
// public static final boolean USE_AGGREGATOR = propertiesUtil.getBoolean("netty.server.use.aggregator");
//
// /**
// * KeyStore path
// */
// public static final String KEY_STORE_PATH = propertiesUtil.getString("ssl.keyStore.path");
//
// /**
// * KeyStore password
// */
// public static final String KEY_STORE_PASSWORD = propertiesUtil.getString("ssl.keyStore.password");
//
// /**
// * 扫描bean的包路径
// */
// public static final String BEAN_SCAN_PACKAGE = propertiesUtil.getString("bean.scan.package");
//
// /**
// * 扫描interceptor的包路径
// */
// public static final String INTERCEPTOR_SCAN_PACKAGE = propertiesUtil.getString("interceptor.scan.package");
//
// /**
// * 服务端出错时的错误描述
// */
// public static final String SERVER_INTERNAL_ERROR_DESC = propertiesUtil.getString("server.internal.error.desc");
//
// public static final String FAVICON_ICO = "/favicon.ico";
//
// public static final String CONNECTION_KEEP_ALIVE = "keep-alive";
//
// public static final String CONNECTION_CLOSE = "close";
//
// /**
// * 是否异步处理业务逻辑
// */
// public static final boolean ASYNC_EXECUTE_EVENT = propertiesUtil.getBoolean("async.execute.event");
//
// /**
// * 业务线程池核心线程数
// */
// public static final int EVENT_EXECUTOR_POOL_CORE_SIZE = propertiesUtil.getInt("async.executor.pool.core.size",10);
//
// /**
// * 业务线程池最大线程数
// */
// public static final int EVENT_EXECUTOR_POOL_MAX_SIZE = propertiesUtil.getInt("async.executor.pool.max.size",20);
//
// /**
// * 业务线程池临时线程存活时间,单位:s
// */
// public static final int EVENT_EXECUTOR_POOL_KEEP_ALIVE_SECONDS = propertiesUtil.getInt("async.executor.pool.keep.alive.seconds",10);
//
// /**
// * 业务线程池阻塞队列大学
// */
// public static final int EVENT_EXECUTOR_POOL_BLOCKING_QUEUE_SIZE = propertiesUtil.getInt("async.executor.pool.blocking.queue.size",10);
//
// }
// Path: redant-core/src/main/java/com/redant/core/interceptor/InterceptorProvider.java
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.ClassScaner;
import com.redant.core.anno.Order;
import com.redant.core.common.constants.CommonConstants;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
package com.redant.core.interceptor;
/**
* @author houyi
**/
public class InterceptorProvider {
private static volatile boolean loaded = false;
private static volatile InterceptorBuilder builder = null;
public static List<Interceptor> getInterceptors(){
// 优先获取用户自定义的 InterceptorBuilder 构造的 Interceptor
if(!loaded){
synchronized (InterceptorProvider.class) {
if(!loaded) { | Set<Class<?>> builders = ClassScaner.scanPackageBySuper(CommonConstants.INTERCEPTOR_SCAN_PACKAGE, InterceptorBuilder.class); |
all4you/redant | redant-core/src/main/java/com/redant/core/common/util/GenericsUtil.java | // Path: redant-core/src/main/java/com/redant/core/common/exception/ValidationException.java
// public class ValidationException extends RuntimeException{
// private static final long serialVersionUID = 1L;
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String message, Throwable cause) {
// super(message, cause);
// }
//
//
// }
| import cn.hutool.core.util.NetUtil;
import cn.hutool.core.util.StrUtil;
import com.redant.core.common.exception.ValidationException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List; | package com.redant.core.common.util;
/**
* GenericsUtil
* @author houyi.wh
* @date 2017-10-20
*/
public class GenericsUtil {
/**
* 通过反射获得Class声明的范型Class.
* 通过反射,获得方法输入参数第index个输入参数的所有泛型参数的实际类型. 如: public void add(Map<String, Buyer> maps, List<String> names){}
* @param method 方法
* @param index 第几个输入参数
* @return 输入参数的泛型参数的实际类型集合, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回空集合
*/
@SuppressWarnings("rawtypes")
public static List<Class> getMethodGenericParameterTypes(Method method, int index) {
List<Class> results = new ArrayList<Class>();
Type[] genericParameterTypes = method.getGenericParameterTypes();
if (index >= genericParameterTypes.length || index < 0) {
throw new RuntimeException("你输入的索引" + (index < 0 ? "不能小于0" : "超出了参数的总数"));
}
Type genericParameterType = genericParameterTypes[index];
if (genericParameterType instanceof ParameterizedType) {
ParameterizedType aType = (ParameterizedType) genericParameterType;
Type[] parameterArgTypes = aType.getActualTypeArguments();
for (Type parameterArgType : parameterArgTypes) {
Class parameterArgClass = (Class) parameterArgType;
results.add(parameterArgClass);
}
return results;
}
return results;
}
/**
* 断言非空
* @param dataName 参数
* @param values 值
*/
public static void checkNull(String dataName, Object... values){
if(values == null){ | // Path: redant-core/src/main/java/com/redant/core/common/exception/ValidationException.java
// public class ValidationException extends RuntimeException{
// private static final long serialVersionUID = 1L;
//
// public ValidationException(String s) {
// super(s);
// }
//
// public ValidationException(String message, Throwable cause) {
// super(message, cause);
// }
//
//
// }
// Path: redant-core/src/main/java/com/redant/core/common/util/GenericsUtil.java
import cn.hutool.core.util.NetUtil;
import cn.hutool.core.util.StrUtil;
import com.redant.core.common.exception.ValidationException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
package com.redant.core.common.util;
/**
* GenericsUtil
* @author houyi.wh
* @date 2017-10-20
*/
public class GenericsUtil {
/**
* 通过反射获得Class声明的范型Class.
* 通过反射,获得方法输入参数第index个输入参数的所有泛型参数的实际类型. 如: public void add(Map<String, Buyer> maps, List<String> names){}
* @param method 方法
* @param index 第几个输入参数
* @return 输入参数的泛型参数的实际类型集合, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回空集合
*/
@SuppressWarnings("rawtypes")
public static List<Class> getMethodGenericParameterTypes(Method method, int index) {
List<Class> results = new ArrayList<Class>();
Type[] genericParameterTypes = method.getGenericParameterTypes();
if (index >= genericParameterTypes.length || index < 0) {
throw new RuntimeException("你输入的索引" + (index < 0 ? "不能小于0" : "超出了参数的总数"));
}
Type genericParameterType = genericParameterTypes[index];
if (genericParameterType instanceof ParameterizedType) {
ParameterizedType aType = (ParameterizedType) genericParameterType;
Type[] parameterArgTypes = aType.getActualTypeArguments();
for (Type parameterArgType : parameterArgTypes) {
Class parameterArgClass = (Class) parameterArgType;
results.add(parameterArgClass);
}
return results;
}
return results;
}
/**
* 断言非空
* @param dataName 参数
* @param values 值
*/
public static void checkNull(String dataName, Object... values){
if(values == null){ | throw new ValidationException("["+ dataName + "] cannot be null"); |
all4you/redant | redant-cluster/src/main/java/com/redant/cluster/service/discover/ServiceDiscover.java | // Path: redant-cluster/src/main/java/com/redant/cluster/node/Node.java
// public class Node {
//
// private static final String DEFAULT_HOST = GenericsUtil.getLocalIpV4();
//
// private static final int DEFAULT_PORT = 8088;
//
// public static final Node DEFAULT_PORT_NODE = new Node(DEFAULT_HOST,DEFAULT_PORT);
//
// private String id;
//
// private String host;
//
// private int port;
//
// public Node(int port){
// this(DEFAULT_HOST,port);
// }
//
// public Node(String host, int port){
// this(SecureUtil.md5(host+"&"+port),host,port);
// }
//
// public Node(String id, String host, int port){
// this.id = id;
// this.host = host;
// this.port = port;
// }
//
// public static Node getNodeWithArgs(String[] args){
// Node node = Node.DEFAULT_PORT_NODE;
// if(args.length>1 && NumberUtil.isInteger(args[1])){
// node = new Node(Integer.parseInt(args[1]));
// }
// return node;
// }
//
// /**
// * 从JsonObject中解析出SlaveNode
// * @param object 对象
// * @return 节点
// */
// public static Node parse(JSONObject object){
// if(object==null){
// return null;
// }
// String host = object.getString("host");
// int port = object.getIntValue("port");
// String id = object.getString("id");
// return new Node(id,host,port);
// }
//
// public String getHost() {
// return host;
// }
//
// public void setHost(String host) {
// this.host = host;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// public String getId(){
// return id;
// }
//
// @Override
// public String toString() {
// return JSON.toJSONString(this);
// }
//
// }
| import com.redant.cluster.node.Node; | package com.redant.cluster.service.discover;
/**
* 服务发现-应用级别
* @author houyi.wh
* @date 2017/11/20
**/
public interface ServiceDiscover {
/**
* 监听Slave节点
*/
void watch();
/**
* 发现可用的Slave节点
* @return 可用节点
*/ | // Path: redant-cluster/src/main/java/com/redant/cluster/node/Node.java
// public class Node {
//
// private static final String DEFAULT_HOST = GenericsUtil.getLocalIpV4();
//
// private static final int DEFAULT_PORT = 8088;
//
// public static final Node DEFAULT_PORT_NODE = new Node(DEFAULT_HOST,DEFAULT_PORT);
//
// private String id;
//
// private String host;
//
// private int port;
//
// public Node(int port){
// this(DEFAULT_HOST,port);
// }
//
// public Node(String host, int port){
// this(SecureUtil.md5(host+"&"+port),host,port);
// }
//
// public Node(String id, String host, int port){
// this.id = id;
// this.host = host;
// this.port = port;
// }
//
// public static Node getNodeWithArgs(String[] args){
// Node node = Node.DEFAULT_PORT_NODE;
// if(args.length>1 && NumberUtil.isInteger(args[1])){
// node = new Node(Integer.parseInt(args[1]));
// }
// return node;
// }
//
// /**
// * 从JsonObject中解析出SlaveNode
// * @param object 对象
// * @return 节点
// */
// public static Node parse(JSONObject object){
// if(object==null){
// return null;
// }
// String host = object.getString("host");
// int port = object.getIntValue("port");
// String id = object.getString("id");
// return new Node(id,host,port);
// }
//
// public String getHost() {
// return host;
// }
//
// public void setHost(String host) {
// this.host = host;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// public String getId(){
// return id;
// }
//
// @Override
// public String toString() {
// return JSON.toJSONString(this);
// }
//
// }
// Path: redant-cluster/src/main/java/com/redant/cluster/service/discover/ServiceDiscover.java
import com.redant.cluster.node.Node;
package com.redant.cluster.service.discover;
/**
* 服务发现-应用级别
* @author houyi.wh
* @date 2017/11/20
**/
public interface ServiceDiscover {
/**
* 监听Slave节点
*/
void watch();
/**
* 发现可用的Slave节点
* @return 可用节点
*/ | Node discover(); |
all4you/redant | redant-core/src/main/java/com/redant/core/common/constants/CommonConstants.java | // Path: redant-core/src/main/java/com/redant/core/common/util/PropertiesUtil.java
// public class PropertiesUtil {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(PropertiesUtil.class);
//
// private static Map<String,PropertiesUtil> propertiesUtilsHolder = null;
//
// private static Map<PropertiesUtil,Properties> propertiesMap = null;
//
// private volatile boolean propertiesLoaded;
//
// private PropertiesUtil(){
//
// }
//
// static{
// propertiesUtilsHolder = new HashMap<>();
// propertiesMap = new HashMap<>();
// }
//
// /**
// * 是否加载完毕
// */
// private boolean propertiesLoaded(){
// int retryTime = 0;
// int retryTimeout = 1000;
// int sleep = 500;
// while(!propertiesLoaded && retryTime<retryTimeout){
// try {
// Thread.sleep(sleep);
// retryTime+=sleep;
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// return propertiesLoaded;
// }
//
//
// /**
// * 根据Resource获取properties
// */
// public static Properties getPropertiesByResource(String propertiesPath){
// InputStream inputStream = null;
// Properties properties = null;
// try{
// inputStream = PropertiesUtil.class.getResourceAsStream(propertiesPath);
// if(inputStream!=null){
// properties = new Properties();
// properties.load(inputStream);
// }
// } catch (Exception e) {
// LOGGER.error("getInstance occur error,cause:",e);
// } finally{
// try {
// if(inputStream!=null){
// inputStream.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// return properties;
// }
//
// /**
// * 获取实例
// */
// public static synchronized PropertiesUtil getInstance(String propertiesPath){
// PropertiesUtil propertiesUtil = propertiesUtilsHolder.get(propertiesPath);
// if(null==propertiesUtil){
// LOGGER.info("[PropertiesUtil] instance is null with propertiesPath={},will create a new instance directly.",propertiesPath);
// InputStream inputStream = null;
// try{
// propertiesUtil = new PropertiesUtil();
// Properties properties = new Properties();
// inputStream = PropertiesUtil.class.getResourceAsStream(propertiesPath);
// if(inputStream!=null){
// properties.load(inputStream);
// propertiesUtilsHolder.put(propertiesPath, propertiesUtil);
// propertiesMap.put(propertiesUtil, properties);
//
// LOGGER.info("[PropertiesUtil] instance init success.");
// propertiesUtil.propertiesLoaded = true;
// }
// } catch (Exception e) {
// LOGGER.error("[PropertiesUtil] getInstance error,cause:{}",e.getMessage(),e);
// } finally{
// try {
// if(inputStream!=null){
// inputStream.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// return propertiesUtil;
// }
//
// /**
// * 获得配置信息的String值
// */
// public String getString(String key){
// if(propertiesLoaded()){
// Properties properties = propertiesMap.get(this);
// return null != properties ? properties.getProperty(key) : null;
// }
// return null;
// }
//
// /**
// * 获得配置信息的boolean值
// */
// public boolean getBoolean(String key){
// String value = getString(key);
// return "true".equalsIgnoreCase(value);
// }
//
// /**
// * 获得配置信息的int值
// */
// public int getInt(String key,int defaultValue){
// String value = getString(key);
// int intValue;
// try{
// intValue = Integer.parseInt(value);
// }catch(Exception e){
// intValue = defaultValue;
// }
// return intValue;
// }
//
// /**
// * 获得配置信息的long值
// */
// public long getLong(String key,long defaultValue){
// String value = getString(key);
// long longValue;
// try{
// longValue = Long.parseLong(value);
// }catch(Exception e){
// longValue = defaultValue;
// }
// return longValue;
// }
//
//
// public static void main(String[] args) {
// int loopTimes = 200;
//
// final CountDownLatch latch = new CountDownLatch(loopTimes);
//
// class Runner implements Runnable{
//
// private Logger logger = LoggerFactory.getLogger(Runner.class);
//
// @Override
// public void run() {
// String property = PropertiesUtil.getInstance("/redant.properties").getString("bean.scan.package");
// logger.info("property={},currentThread={}",property,Thread.currentThread().getName());
// latch.countDown();
// }
// }
//
// TagUtil.addTag("start");
// for(int i=0;i<loopTimes;i++){
// new Thread(new Runner()).start();
// }
// try {
// latch.await();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// TagUtil.addTag("end");
// TagUtil.showCost("start","end");
// }
//
// }
| import com.redant.core.common.util.PropertiesUtil; | package com.redant.core.common.constants;
/**
* 公共常量
* @author houyi.wh
* @date 2017-10-20
*/
public class CommonConstants {
private static final String REDANT_PROPERTIES_PATH = "/redant.properties";
| // Path: redant-core/src/main/java/com/redant/core/common/util/PropertiesUtil.java
// public class PropertiesUtil {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(PropertiesUtil.class);
//
// private static Map<String,PropertiesUtil> propertiesUtilsHolder = null;
//
// private static Map<PropertiesUtil,Properties> propertiesMap = null;
//
// private volatile boolean propertiesLoaded;
//
// private PropertiesUtil(){
//
// }
//
// static{
// propertiesUtilsHolder = new HashMap<>();
// propertiesMap = new HashMap<>();
// }
//
// /**
// * 是否加载完毕
// */
// private boolean propertiesLoaded(){
// int retryTime = 0;
// int retryTimeout = 1000;
// int sleep = 500;
// while(!propertiesLoaded && retryTime<retryTimeout){
// try {
// Thread.sleep(sleep);
// retryTime+=sleep;
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// return propertiesLoaded;
// }
//
//
// /**
// * 根据Resource获取properties
// */
// public static Properties getPropertiesByResource(String propertiesPath){
// InputStream inputStream = null;
// Properties properties = null;
// try{
// inputStream = PropertiesUtil.class.getResourceAsStream(propertiesPath);
// if(inputStream!=null){
// properties = new Properties();
// properties.load(inputStream);
// }
// } catch (Exception e) {
// LOGGER.error("getInstance occur error,cause:",e);
// } finally{
// try {
// if(inputStream!=null){
// inputStream.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// return properties;
// }
//
// /**
// * 获取实例
// */
// public static synchronized PropertiesUtil getInstance(String propertiesPath){
// PropertiesUtil propertiesUtil = propertiesUtilsHolder.get(propertiesPath);
// if(null==propertiesUtil){
// LOGGER.info("[PropertiesUtil] instance is null with propertiesPath={},will create a new instance directly.",propertiesPath);
// InputStream inputStream = null;
// try{
// propertiesUtil = new PropertiesUtil();
// Properties properties = new Properties();
// inputStream = PropertiesUtil.class.getResourceAsStream(propertiesPath);
// if(inputStream!=null){
// properties.load(inputStream);
// propertiesUtilsHolder.put(propertiesPath, propertiesUtil);
// propertiesMap.put(propertiesUtil, properties);
//
// LOGGER.info("[PropertiesUtil] instance init success.");
// propertiesUtil.propertiesLoaded = true;
// }
// } catch (Exception e) {
// LOGGER.error("[PropertiesUtil] getInstance error,cause:{}",e.getMessage(),e);
// } finally{
// try {
// if(inputStream!=null){
// inputStream.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
// return propertiesUtil;
// }
//
// /**
// * 获得配置信息的String值
// */
// public String getString(String key){
// if(propertiesLoaded()){
// Properties properties = propertiesMap.get(this);
// return null != properties ? properties.getProperty(key) : null;
// }
// return null;
// }
//
// /**
// * 获得配置信息的boolean值
// */
// public boolean getBoolean(String key){
// String value = getString(key);
// return "true".equalsIgnoreCase(value);
// }
//
// /**
// * 获得配置信息的int值
// */
// public int getInt(String key,int defaultValue){
// String value = getString(key);
// int intValue;
// try{
// intValue = Integer.parseInt(value);
// }catch(Exception e){
// intValue = defaultValue;
// }
// return intValue;
// }
//
// /**
// * 获得配置信息的long值
// */
// public long getLong(String key,long defaultValue){
// String value = getString(key);
// long longValue;
// try{
// longValue = Long.parseLong(value);
// }catch(Exception e){
// longValue = defaultValue;
// }
// return longValue;
// }
//
//
// public static void main(String[] args) {
// int loopTimes = 200;
//
// final CountDownLatch latch = new CountDownLatch(loopTimes);
//
// class Runner implements Runnable{
//
// private Logger logger = LoggerFactory.getLogger(Runner.class);
//
// @Override
// public void run() {
// String property = PropertiesUtil.getInstance("/redant.properties").getString("bean.scan.package");
// logger.info("property={},currentThread={}",property,Thread.currentThread().getName());
// latch.countDown();
// }
// }
//
// TagUtil.addTag("start");
// for(int i=0;i<loopTimes;i++){
// new Thread(new Runner()).start();
// }
// try {
// latch.await();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// TagUtil.addTag("end");
// TagUtil.showCost("start","end");
// }
//
// }
// Path: redant-core/src/main/java/com/redant/core/common/constants/CommonConstants.java
import com.redant.core.common.util.PropertiesUtil;
package com.redant.core.common.constants;
/**
* 公共常量
* @author houyi.wh
* @date 2017-10-20
*/
public class CommonConstants {
private static final String REDANT_PROPERTIES_PATH = "/redant.properties";
| private static PropertiesUtil propertiesUtil = PropertiesUtil.getInstance(REDANT_PROPERTIES_PATH); |
all4you/redant | redant-example/src/test/java/com/lememo/core/interceptor/InterceptorProviderTest.java | // Path: redant-core/src/main/java/com/redant/core/interceptor/Interceptor.java
// public abstract class Interceptor {
//
// /**
// * 拦截器的前置处理方法
// */
// public boolean preHandle(Map<String, List<String>> paramMap){
// return true;
// }
//
// /**
// * 拦截器的后置处理方法
// */
// public abstract void postHandle(Map<String, List<String>> paramMap);
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/interceptor/InterceptorProvider.java
// public class InterceptorProvider {
//
// private static volatile boolean loaded = false;
//
// private static volatile InterceptorBuilder builder = null;
//
// public static List<Interceptor> getInterceptors(){
// // 优先获取用户自定义的 InterceptorBuilder 构造的 Interceptor
// if(!loaded){
// synchronized (InterceptorProvider.class) {
// if(!loaded) {
// Set<Class<?>> builders = ClassScaner.scanPackageBySuper(CommonConstants.INTERCEPTOR_SCAN_PACKAGE, InterceptorBuilder.class);
// if (CollectionUtil.isNotEmpty(builders)) {
// try {
// for (Class<?> cls : builders) {
// builder = (InterceptorBuilder) cls.newInstance();
// break;
// }
// } catch (IllegalAccessException | InstantiationException e) {
// e.printStackTrace();
// }
// }
// loaded = true;
// }
// }
// }
// if(builder!=null){
// return builder.build();
// }
// // 获取不到时,再扫描所有指定目录下的 Interceptor
// return InterceptorsHolder.interceptors;
// }
//
// static class InterceptorsHolder {
//
// static List<Interceptor> interceptors;
//
// static {
// interceptors = scanInterceptors();
// }
//
// private static List<Interceptor> scanInterceptors() {
// Set<Class<?>> classSet = ClassScaner.scanPackageBySuper(CommonConstants.INTERCEPTOR_SCAN_PACKAGE,Interceptor.class);
// if(CollectionUtil.isEmpty(classSet)){
// return Collections.emptyList();
// }
// List<InterceptorWrapper> wrappers = new ArrayList<>(classSet.size());
// try {
// for (Class<?> cls : classSet) {
// Interceptor interceptor =(Interceptor)cls.newInstance();
// insertSorted(wrappers,interceptor);
// }
// }catch (IllegalAccessException | InstantiationException e) {
// e.printStackTrace();
// }
// return wrappers.stream()
// .map(InterceptorWrapper::getInterceptor)
// .collect(Collectors.toList());
// }
//
// private static void insertSorted(List<InterceptorWrapper> list, Interceptor interceptor) {
// int order = resolveOrder(interceptor);
// int idx = 0;
// for (; idx < list.size(); idx++) {
// // 将当前interceptor插入到order值比他大的第一个interceptor前面
// if (list.get(idx).getOrder() > order) {
// break;
// }
// }
// list.add(idx, new InterceptorWrapper(order, interceptor));
// }
//
// private static int resolveOrder(Interceptor interceptor) {
// if (!interceptor.getClass().isAnnotationPresent(Order.class)) {
// return Order.LOWEST_PRECEDENCE;
// } else {
// return interceptor.getClass().getAnnotation(Order.class).value();
// }
// }
//
// private static class InterceptorWrapper {
// private final int order;
// private final Interceptor interceptor;
//
// InterceptorWrapper(int order, Interceptor interceptor) {
// this.order = order;
// this.interceptor = interceptor;
// }
//
// int getOrder() {
// return order;
// }
//
// Interceptor getInterceptor() {
// return interceptor;
// }
// }
// }
// }
| import com.redant.core.interceptor.Interceptor;
import com.redant.core.interceptor.InterceptorProvider;
import java.util.List; | package com.lememo.core.interceptor;
/**
* @author houyi
**/
public class InterceptorProviderTest {
public static void main(String[] args) {
for(int i=0;i<10;i++){
new Thread(new Run()).start();
}
}
static class Run implements Runnable {
@Override
public void run() { | // Path: redant-core/src/main/java/com/redant/core/interceptor/Interceptor.java
// public abstract class Interceptor {
//
// /**
// * 拦截器的前置处理方法
// */
// public boolean preHandle(Map<String, List<String>> paramMap){
// return true;
// }
//
// /**
// * 拦截器的后置处理方法
// */
// public abstract void postHandle(Map<String, List<String>> paramMap);
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/interceptor/InterceptorProvider.java
// public class InterceptorProvider {
//
// private static volatile boolean loaded = false;
//
// private static volatile InterceptorBuilder builder = null;
//
// public static List<Interceptor> getInterceptors(){
// // 优先获取用户自定义的 InterceptorBuilder 构造的 Interceptor
// if(!loaded){
// synchronized (InterceptorProvider.class) {
// if(!loaded) {
// Set<Class<?>> builders = ClassScaner.scanPackageBySuper(CommonConstants.INTERCEPTOR_SCAN_PACKAGE, InterceptorBuilder.class);
// if (CollectionUtil.isNotEmpty(builders)) {
// try {
// for (Class<?> cls : builders) {
// builder = (InterceptorBuilder) cls.newInstance();
// break;
// }
// } catch (IllegalAccessException | InstantiationException e) {
// e.printStackTrace();
// }
// }
// loaded = true;
// }
// }
// }
// if(builder!=null){
// return builder.build();
// }
// // 获取不到时,再扫描所有指定目录下的 Interceptor
// return InterceptorsHolder.interceptors;
// }
//
// static class InterceptorsHolder {
//
// static List<Interceptor> interceptors;
//
// static {
// interceptors = scanInterceptors();
// }
//
// private static List<Interceptor> scanInterceptors() {
// Set<Class<?>> classSet = ClassScaner.scanPackageBySuper(CommonConstants.INTERCEPTOR_SCAN_PACKAGE,Interceptor.class);
// if(CollectionUtil.isEmpty(classSet)){
// return Collections.emptyList();
// }
// List<InterceptorWrapper> wrappers = new ArrayList<>(classSet.size());
// try {
// for (Class<?> cls : classSet) {
// Interceptor interceptor =(Interceptor)cls.newInstance();
// insertSorted(wrappers,interceptor);
// }
// }catch (IllegalAccessException | InstantiationException e) {
// e.printStackTrace();
// }
// return wrappers.stream()
// .map(InterceptorWrapper::getInterceptor)
// .collect(Collectors.toList());
// }
//
// private static void insertSorted(List<InterceptorWrapper> list, Interceptor interceptor) {
// int order = resolveOrder(interceptor);
// int idx = 0;
// for (; idx < list.size(); idx++) {
// // 将当前interceptor插入到order值比他大的第一个interceptor前面
// if (list.get(idx).getOrder() > order) {
// break;
// }
// }
// list.add(idx, new InterceptorWrapper(order, interceptor));
// }
//
// private static int resolveOrder(Interceptor interceptor) {
// if (!interceptor.getClass().isAnnotationPresent(Order.class)) {
// return Order.LOWEST_PRECEDENCE;
// } else {
// return interceptor.getClass().getAnnotation(Order.class).value();
// }
// }
//
// private static class InterceptorWrapper {
// private final int order;
// private final Interceptor interceptor;
//
// InterceptorWrapper(int order, Interceptor interceptor) {
// this.order = order;
// this.interceptor = interceptor;
// }
//
// int getOrder() {
// return order;
// }
//
// Interceptor getInterceptor() {
// return interceptor;
// }
// }
// }
// }
// Path: redant-example/src/test/java/com/lememo/core/interceptor/InterceptorProviderTest.java
import com.redant.core.interceptor.Interceptor;
import com.redant.core.interceptor.InterceptorProvider;
import java.util.List;
package com.lememo.core.interceptor;
/**
* @author houyi
**/
public class InterceptorProviderTest {
public static void main(String[] args) {
for(int i=0;i<10;i++){
new Thread(new Run()).start();
}
}
static class Run implements Runnable {
@Override
public void run() { | List<Interceptor> interceptors = InterceptorProvider.getInterceptors(); |
all4you/redant | redant-example/src/test/java/com/lememo/core/interceptor/InterceptorProviderTest.java | // Path: redant-core/src/main/java/com/redant/core/interceptor/Interceptor.java
// public abstract class Interceptor {
//
// /**
// * 拦截器的前置处理方法
// */
// public boolean preHandle(Map<String, List<String>> paramMap){
// return true;
// }
//
// /**
// * 拦截器的后置处理方法
// */
// public abstract void postHandle(Map<String, List<String>> paramMap);
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/interceptor/InterceptorProvider.java
// public class InterceptorProvider {
//
// private static volatile boolean loaded = false;
//
// private static volatile InterceptorBuilder builder = null;
//
// public static List<Interceptor> getInterceptors(){
// // 优先获取用户自定义的 InterceptorBuilder 构造的 Interceptor
// if(!loaded){
// synchronized (InterceptorProvider.class) {
// if(!loaded) {
// Set<Class<?>> builders = ClassScaner.scanPackageBySuper(CommonConstants.INTERCEPTOR_SCAN_PACKAGE, InterceptorBuilder.class);
// if (CollectionUtil.isNotEmpty(builders)) {
// try {
// for (Class<?> cls : builders) {
// builder = (InterceptorBuilder) cls.newInstance();
// break;
// }
// } catch (IllegalAccessException | InstantiationException e) {
// e.printStackTrace();
// }
// }
// loaded = true;
// }
// }
// }
// if(builder!=null){
// return builder.build();
// }
// // 获取不到时,再扫描所有指定目录下的 Interceptor
// return InterceptorsHolder.interceptors;
// }
//
// static class InterceptorsHolder {
//
// static List<Interceptor> interceptors;
//
// static {
// interceptors = scanInterceptors();
// }
//
// private static List<Interceptor> scanInterceptors() {
// Set<Class<?>> classSet = ClassScaner.scanPackageBySuper(CommonConstants.INTERCEPTOR_SCAN_PACKAGE,Interceptor.class);
// if(CollectionUtil.isEmpty(classSet)){
// return Collections.emptyList();
// }
// List<InterceptorWrapper> wrappers = new ArrayList<>(classSet.size());
// try {
// for (Class<?> cls : classSet) {
// Interceptor interceptor =(Interceptor)cls.newInstance();
// insertSorted(wrappers,interceptor);
// }
// }catch (IllegalAccessException | InstantiationException e) {
// e.printStackTrace();
// }
// return wrappers.stream()
// .map(InterceptorWrapper::getInterceptor)
// .collect(Collectors.toList());
// }
//
// private static void insertSorted(List<InterceptorWrapper> list, Interceptor interceptor) {
// int order = resolveOrder(interceptor);
// int idx = 0;
// for (; idx < list.size(); idx++) {
// // 将当前interceptor插入到order值比他大的第一个interceptor前面
// if (list.get(idx).getOrder() > order) {
// break;
// }
// }
// list.add(idx, new InterceptorWrapper(order, interceptor));
// }
//
// private static int resolveOrder(Interceptor interceptor) {
// if (!interceptor.getClass().isAnnotationPresent(Order.class)) {
// return Order.LOWEST_PRECEDENCE;
// } else {
// return interceptor.getClass().getAnnotation(Order.class).value();
// }
// }
//
// private static class InterceptorWrapper {
// private final int order;
// private final Interceptor interceptor;
//
// InterceptorWrapper(int order, Interceptor interceptor) {
// this.order = order;
// this.interceptor = interceptor;
// }
//
// int getOrder() {
// return order;
// }
//
// Interceptor getInterceptor() {
// return interceptor;
// }
// }
// }
// }
| import com.redant.core.interceptor.Interceptor;
import com.redant.core.interceptor.InterceptorProvider;
import java.util.List; | package com.lememo.core.interceptor;
/**
* @author houyi
**/
public class InterceptorProviderTest {
public static void main(String[] args) {
for(int i=0;i<10;i++){
new Thread(new Run()).start();
}
}
static class Run implements Runnable {
@Override
public void run() { | // Path: redant-core/src/main/java/com/redant/core/interceptor/Interceptor.java
// public abstract class Interceptor {
//
// /**
// * 拦截器的前置处理方法
// */
// public boolean preHandle(Map<String, List<String>> paramMap){
// return true;
// }
//
// /**
// * 拦截器的后置处理方法
// */
// public abstract void postHandle(Map<String, List<String>> paramMap);
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/interceptor/InterceptorProvider.java
// public class InterceptorProvider {
//
// private static volatile boolean loaded = false;
//
// private static volatile InterceptorBuilder builder = null;
//
// public static List<Interceptor> getInterceptors(){
// // 优先获取用户自定义的 InterceptorBuilder 构造的 Interceptor
// if(!loaded){
// synchronized (InterceptorProvider.class) {
// if(!loaded) {
// Set<Class<?>> builders = ClassScaner.scanPackageBySuper(CommonConstants.INTERCEPTOR_SCAN_PACKAGE, InterceptorBuilder.class);
// if (CollectionUtil.isNotEmpty(builders)) {
// try {
// for (Class<?> cls : builders) {
// builder = (InterceptorBuilder) cls.newInstance();
// break;
// }
// } catch (IllegalAccessException | InstantiationException e) {
// e.printStackTrace();
// }
// }
// loaded = true;
// }
// }
// }
// if(builder!=null){
// return builder.build();
// }
// // 获取不到时,再扫描所有指定目录下的 Interceptor
// return InterceptorsHolder.interceptors;
// }
//
// static class InterceptorsHolder {
//
// static List<Interceptor> interceptors;
//
// static {
// interceptors = scanInterceptors();
// }
//
// private static List<Interceptor> scanInterceptors() {
// Set<Class<?>> classSet = ClassScaner.scanPackageBySuper(CommonConstants.INTERCEPTOR_SCAN_PACKAGE,Interceptor.class);
// if(CollectionUtil.isEmpty(classSet)){
// return Collections.emptyList();
// }
// List<InterceptorWrapper> wrappers = new ArrayList<>(classSet.size());
// try {
// for (Class<?> cls : classSet) {
// Interceptor interceptor =(Interceptor)cls.newInstance();
// insertSorted(wrappers,interceptor);
// }
// }catch (IllegalAccessException | InstantiationException e) {
// e.printStackTrace();
// }
// return wrappers.stream()
// .map(InterceptorWrapper::getInterceptor)
// .collect(Collectors.toList());
// }
//
// private static void insertSorted(List<InterceptorWrapper> list, Interceptor interceptor) {
// int order = resolveOrder(interceptor);
// int idx = 0;
// for (; idx < list.size(); idx++) {
// // 将当前interceptor插入到order值比他大的第一个interceptor前面
// if (list.get(idx).getOrder() > order) {
// break;
// }
// }
// list.add(idx, new InterceptorWrapper(order, interceptor));
// }
//
// private static int resolveOrder(Interceptor interceptor) {
// if (!interceptor.getClass().isAnnotationPresent(Order.class)) {
// return Order.LOWEST_PRECEDENCE;
// } else {
// return interceptor.getClass().getAnnotation(Order.class).value();
// }
// }
//
// private static class InterceptorWrapper {
// private final int order;
// private final Interceptor interceptor;
//
// InterceptorWrapper(int order, Interceptor interceptor) {
// this.order = order;
// this.interceptor = interceptor;
// }
//
// int getOrder() {
// return order;
// }
//
// Interceptor getInterceptor() {
// return interceptor;
// }
// }
// }
// }
// Path: redant-example/src/test/java/com/lememo/core/interceptor/InterceptorProviderTest.java
import com.redant.core.interceptor.Interceptor;
import com.redant.core.interceptor.InterceptorProvider;
import java.util.List;
package com.lememo.core.interceptor;
/**
* @author houyi
**/
public class InterceptorProviderTest {
public static void main(String[] args) {
for(int i=0;i<10;i++){
new Thread(new Run()).start();
}
}
static class Run implements Runnable {
@Override
public void run() { | List<Interceptor> interceptors = InterceptorProvider.getInterceptors(); |
all4you/redant | redant-cluster/src/main/java/com/redant/cluster/zk/ZkConfig.java | // Path: redant-core/src/main/java/com/redant/core/common/util/GenericsUtil.java
// public class GenericsUtil {
//
// /**
// * 通过反射获得Class声明的范型Class.
// * 通过反射,获得方法输入参数第index个输入参数的所有泛型参数的实际类型. 如: public void add(Map<String, Buyer> maps, List<String> names){}
// * @param method 方法
// * @param index 第几个输入参数
// * @return 输入参数的泛型参数的实际类型集合, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回空集合
// */
// @SuppressWarnings("rawtypes")
// public static List<Class> getMethodGenericParameterTypes(Method method, int index) {
// List<Class> results = new ArrayList<Class>();
// Type[] genericParameterTypes = method.getGenericParameterTypes();
// if (index >= genericParameterTypes.length || index < 0) {
// throw new RuntimeException("你输入的索引" + (index < 0 ? "不能小于0" : "超出了参数的总数"));
// }
// Type genericParameterType = genericParameterTypes[index];
// if (genericParameterType instanceof ParameterizedType) {
// ParameterizedType aType = (ParameterizedType) genericParameterType;
// Type[] parameterArgTypes = aType.getActualTypeArguments();
// for (Type parameterArgType : parameterArgTypes) {
// Class parameterArgClass = (Class) parameterArgType;
// results.add(parameterArgClass);
// }
// return results;
// }
// return results;
// }
//
//
// /**
// * 断言非空
// * @param dataName 参数
// * @param values 值
// */
// public static void checkNull(String dataName, Object... values){
// if(values == null){
// throw new ValidationException("["+ dataName + "] cannot be null");
// }
// for (Object value : values) {
// if (value == null) {
// throw new ValidationException("[" + dataName + "] cannot be null");
// }
// }
// }
//
// /**
// * 断言非空
// * @param dataName 参数
// * @param values 值
// */
// public static void checkBlank(String dataName, Object... values){
// if(values == null){
// throw new ValidationException("["+ dataName + "] cannot be null");
// }
// for (Object value : values) {
// if (value == null || StrUtil.isBlank(value.toString())) {
// throw new ValidationException("[" + dataName + "] cannot be blank");
// }
// }
// }
//
// /**
// * 获取ipV4
// * @return ipV4
// */
// public static String getLocalIpV4(){
// LinkedHashSet<String> ipV4Set = NetUtil.localIpv4s();
// return ipV4Set.isEmpty()?"":ipV4Set.toArray()[0].toString();
// }
//
// }
| import com.redant.core.common.util.GenericsUtil;
import java.util.Properties; | package com.redant.cluster.zk;
/**
* 启动zk所需要的配置信息
* @author houyi.wh
* @date 2017/11/21
*/
public class ZkConfig {
private interface ZkConstant {
int CLIENT_PORT = 2181;
String DATA_DIR = "/Users/houyi/zookeeper/data";
String DATA_LOG_DIR = "/Users/houyi/zookeeper/log";
}
/**
* 客户端连接的端口
*/
private int clientPort;
private int tickTime = 2000;
private int initLimit = 10;
private int syncLimit = 5;
/**
* 数据存储目录,格式为:
* /home/zookeeper/1/data
*/
private String dataDir;
/**
* 日志存储目录,格式为:
* /home/zookeeper/1/log
*/
private String dataLogDir;
/**
* 客户端连接数上限
*/
private int maxClientCnxns = 60;
public ZkConfig(int clientPort,String dataDir,String dataLogDir){
this.clientPort = clientPort;
this.dataDir = dataDir;
this.dataLogDir = dataLogDir;
}
public static ZkConfig DEFAULT = new ZkConfig(ZkConstant.CLIENT_PORT,ZkConstant.DATA_DIR,ZkConstant.DATA_LOG_DIR);
public String generateZkAddress(){ | // Path: redant-core/src/main/java/com/redant/core/common/util/GenericsUtil.java
// public class GenericsUtil {
//
// /**
// * 通过反射获得Class声明的范型Class.
// * 通过反射,获得方法输入参数第index个输入参数的所有泛型参数的实际类型. 如: public void add(Map<String, Buyer> maps, List<String> names){}
// * @param method 方法
// * @param index 第几个输入参数
// * @return 输入参数的泛型参数的实际类型集合, 如果没有实现ParameterizedType接口,即不支持泛型,所以直接返回空集合
// */
// @SuppressWarnings("rawtypes")
// public static List<Class> getMethodGenericParameterTypes(Method method, int index) {
// List<Class> results = new ArrayList<Class>();
// Type[] genericParameterTypes = method.getGenericParameterTypes();
// if (index >= genericParameterTypes.length || index < 0) {
// throw new RuntimeException("你输入的索引" + (index < 0 ? "不能小于0" : "超出了参数的总数"));
// }
// Type genericParameterType = genericParameterTypes[index];
// if (genericParameterType instanceof ParameterizedType) {
// ParameterizedType aType = (ParameterizedType) genericParameterType;
// Type[] parameterArgTypes = aType.getActualTypeArguments();
// for (Type parameterArgType : parameterArgTypes) {
// Class parameterArgClass = (Class) parameterArgType;
// results.add(parameterArgClass);
// }
// return results;
// }
// return results;
// }
//
//
// /**
// * 断言非空
// * @param dataName 参数
// * @param values 值
// */
// public static void checkNull(String dataName, Object... values){
// if(values == null){
// throw new ValidationException("["+ dataName + "] cannot be null");
// }
// for (Object value : values) {
// if (value == null) {
// throw new ValidationException("[" + dataName + "] cannot be null");
// }
// }
// }
//
// /**
// * 断言非空
// * @param dataName 参数
// * @param values 值
// */
// public static void checkBlank(String dataName, Object... values){
// if(values == null){
// throw new ValidationException("["+ dataName + "] cannot be null");
// }
// for (Object value : values) {
// if (value == null || StrUtil.isBlank(value.toString())) {
// throw new ValidationException("[" + dataName + "] cannot be blank");
// }
// }
// }
//
// /**
// * 获取ipV4
// * @return ipV4
// */
// public static String getLocalIpV4(){
// LinkedHashSet<String> ipV4Set = NetUtil.localIpv4s();
// return ipV4Set.isEmpty()?"":ipV4Set.toArray()[0].toString();
// }
//
// }
// Path: redant-cluster/src/main/java/com/redant/cluster/zk/ZkConfig.java
import com.redant.core.common.util.GenericsUtil;
import java.util.Properties;
package com.redant.cluster.zk;
/**
* 启动zk所需要的配置信息
* @author houyi.wh
* @date 2017/11/21
*/
public class ZkConfig {
private interface ZkConstant {
int CLIENT_PORT = 2181;
String DATA_DIR = "/Users/houyi/zookeeper/data";
String DATA_LOG_DIR = "/Users/houyi/zookeeper/log";
}
/**
* 客户端连接的端口
*/
private int clientPort;
private int tickTime = 2000;
private int initLimit = 10;
private int syncLimit = 5;
/**
* 数据存储目录,格式为:
* /home/zookeeper/1/data
*/
private String dataDir;
/**
* 日志存储目录,格式为:
* /home/zookeeper/1/log
*/
private String dataLogDir;
/**
* 客户端连接数上限
*/
private int maxClientCnxns = 60;
public ZkConfig(int clientPort,String dataDir,String dataLogDir){
this.clientPort = clientPort;
this.dataDir = dataDir;
this.dataLogDir = dataLogDir;
}
public static ZkConfig DEFAULT = new ZkConfig(ZkConstant.CLIENT_PORT,ZkConstant.DATA_DIR,ZkConstant.DATA_LOG_DIR);
public String generateZkAddress(){ | return GenericsUtil.getLocalIpV4()+":"+this.clientPort; |
all4you/redant | redant-core/src/main/java/com/redant/core/init/InitExecutor.java | // Path: redant-core/src/main/java/com/redant/core/common/constants/CommonConstants.java
// public class CommonConstants {
//
//
// private static final String REDANT_PROPERTIES_PATH = "/redant.properties";
//
// private static PropertiesUtil propertiesUtil = PropertiesUtil.getInstance(REDANT_PROPERTIES_PATH);
//
// /**
// * 服务端口号
// */
// public static final int SERVER_PORT = propertiesUtil.getInt("netty.server.port",8888);
//
// /**
// * BossGroup Size
// * 先从启动参数中获取:-Dnetty.server.bossGroup.size=2
// * 如果获取不到从配置文件中获取
// * 如果再获取不到则取默认值
// */
// public static final int BOSS_GROUP_SIZE = null!=Integer.getInteger("netty.server.bossGroup.size")?Integer.getInteger("netty.server.bossGroup.size"):propertiesUtil.getInt("netty.server.bossGroup.size",2);
//
// /**
// * WorkerGroup Size
// * 先从启动参数中获取:-Dnetty.server.workerGroup.size=4
// * 如果获取不到从配置文件中获取
// * 如果再获取不到则取默认值
// */
// public static final int WORKER_GROUP_SIZE = null!=Integer.getInteger("netty.server.workerGroup.size")?Integer.getInteger("netty.server.workerGroup.size"):propertiesUtil.getInt("netty.server.workerGroup.size",4);
//
// /**
// * 能处理的最大数据的字节数
// */
// public static final int MAX_CONTENT_LENGTH = propertiesUtil.getInt("netty.maxContentLength",10485760);
//
// /**
// * 是否开启ssl
// */
// public static final boolean USE_SSL = propertiesUtil.getBoolean("netty.server.use.ssl");
//
// /**
// * 是否开启压缩
// */
// public static final boolean USE_COMPRESS = propertiesUtil.getBoolean("netty.server.use.compress");
//
// /**
// * 是否开启http对象聚合
// */
// public static final boolean USE_AGGREGATOR = propertiesUtil.getBoolean("netty.server.use.aggregator");
//
// /**
// * KeyStore path
// */
// public static final String KEY_STORE_PATH = propertiesUtil.getString("ssl.keyStore.path");
//
// /**
// * KeyStore password
// */
// public static final String KEY_STORE_PASSWORD = propertiesUtil.getString("ssl.keyStore.password");
//
// /**
// * 扫描bean的包路径
// */
// public static final String BEAN_SCAN_PACKAGE = propertiesUtil.getString("bean.scan.package");
//
// /**
// * 扫描interceptor的包路径
// */
// public static final String INTERCEPTOR_SCAN_PACKAGE = propertiesUtil.getString("interceptor.scan.package");
//
// /**
// * 服务端出错时的错误描述
// */
// public static final String SERVER_INTERNAL_ERROR_DESC = propertiesUtil.getString("server.internal.error.desc");
//
// public static final String FAVICON_ICO = "/favicon.ico";
//
// public static final String CONNECTION_KEEP_ALIVE = "keep-alive";
//
// public static final String CONNECTION_CLOSE = "close";
//
// /**
// * 是否异步处理业务逻辑
// */
// public static final boolean ASYNC_EXECUTE_EVENT = propertiesUtil.getBoolean("async.execute.event");
//
// /**
// * 业务线程池核心线程数
// */
// public static final int EVENT_EXECUTOR_POOL_CORE_SIZE = propertiesUtil.getInt("async.executor.pool.core.size",10);
//
// /**
// * 业务线程池最大线程数
// */
// public static final int EVENT_EXECUTOR_POOL_MAX_SIZE = propertiesUtil.getInt("async.executor.pool.max.size",20);
//
// /**
// * 业务线程池临时线程存活时间,单位:s
// */
// public static final int EVENT_EXECUTOR_POOL_KEEP_ALIVE_SECONDS = propertiesUtil.getInt("async.executor.pool.keep.alive.seconds",10);
//
// /**
// * 业务线程池阻塞队列大学
// */
// public static final int EVENT_EXECUTOR_POOL_BLOCKING_QUEUE_SIZE = propertiesUtil.getInt("async.executor.pool.blocking.queue.size",10);
//
// }
| import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.ClassScaner;
import com.redant.core.common.constants.CommonConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean; | package com.redant.core.init;
/**
* @author houyi.wh
* @date 2019-01-14
*/
public final class InitExecutor {
private static final Logger LOGGER = LoggerFactory.getLogger(InitExecutor.class);
private static AtomicBoolean initialized = new AtomicBoolean(false);
public static void init() {
if (!initialized.compareAndSet(false, true)) {
return;
}
try { | // Path: redant-core/src/main/java/com/redant/core/common/constants/CommonConstants.java
// public class CommonConstants {
//
//
// private static final String REDANT_PROPERTIES_PATH = "/redant.properties";
//
// private static PropertiesUtil propertiesUtil = PropertiesUtil.getInstance(REDANT_PROPERTIES_PATH);
//
// /**
// * 服务端口号
// */
// public static final int SERVER_PORT = propertiesUtil.getInt("netty.server.port",8888);
//
// /**
// * BossGroup Size
// * 先从启动参数中获取:-Dnetty.server.bossGroup.size=2
// * 如果获取不到从配置文件中获取
// * 如果再获取不到则取默认值
// */
// public static final int BOSS_GROUP_SIZE = null!=Integer.getInteger("netty.server.bossGroup.size")?Integer.getInteger("netty.server.bossGroup.size"):propertiesUtil.getInt("netty.server.bossGroup.size",2);
//
// /**
// * WorkerGroup Size
// * 先从启动参数中获取:-Dnetty.server.workerGroup.size=4
// * 如果获取不到从配置文件中获取
// * 如果再获取不到则取默认值
// */
// public static final int WORKER_GROUP_SIZE = null!=Integer.getInteger("netty.server.workerGroup.size")?Integer.getInteger("netty.server.workerGroup.size"):propertiesUtil.getInt("netty.server.workerGroup.size",4);
//
// /**
// * 能处理的最大数据的字节数
// */
// public static final int MAX_CONTENT_LENGTH = propertiesUtil.getInt("netty.maxContentLength",10485760);
//
// /**
// * 是否开启ssl
// */
// public static final boolean USE_SSL = propertiesUtil.getBoolean("netty.server.use.ssl");
//
// /**
// * 是否开启压缩
// */
// public static final boolean USE_COMPRESS = propertiesUtil.getBoolean("netty.server.use.compress");
//
// /**
// * 是否开启http对象聚合
// */
// public static final boolean USE_AGGREGATOR = propertiesUtil.getBoolean("netty.server.use.aggregator");
//
// /**
// * KeyStore path
// */
// public static final String KEY_STORE_PATH = propertiesUtil.getString("ssl.keyStore.path");
//
// /**
// * KeyStore password
// */
// public static final String KEY_STORE_PASSWORD = propertiesUtil.getString("ssl.keyStore.password");
//
// /**
// * 扫描bean的包路径
// */
// public static final String BEAN_SCAN_PACKAGE = propertiesUtil.getString("bean.scan.package");
//
// /**
// * 扫描interceptor的包路径
// */
// public static final String INTERCEPTOR_SCAN_PACKAGE = propertiesUtil.getString("interceptor.scan.package");
//
// /**
// * 服务端出错时的错误描述
// */
// public static final String SERVER_INTERNAL_ERROR_DESC = propertiesUtil.getString("server.internal.error.desc");
//
// public static final String FAVICON_ICO = "/favicon.ico";
//
// public static final String CONNECTION_KEEP_ALIVE = "keep-alive";
//
// public static final String CONNECTION_CLOSE = "close";
//
// /**
// * 是否异步处理业务逻辑
// */
// public static final boolean ASYNC_EXECUTE_EVENT = propertiesUtil.getBoolean("async.execute.event");
//
// /**
// * 业务线程池核心线程数
// */
// public static final int EVENT_EXECUTOR_POOL_CORE_SIZE = propertiesUtil.getInt("async.executor.pool.core.size",10);
//
// /**
// * 业务线程池最大线程数
// */
// public static final int EVENT_EXECUTOR_POOL_MAX_SIZE = propertiesUtil.getInt("async.executor.pool.max.size",20);
//
// /**
// * 业务线程池临时线程存活时间,单位:s
// */
// public static final int EVENT_EXECUTOR_POOL_KEEP_ALIVE_SECONDS = propertiesUtil.getInt("async.executor.pool.keep.alive.seconds",10);
//
// /**
// * 业务线程池阻塞队列大学
// */
// public static final int EVENT_EXECUTOR_POOL_BLOCKING_QUEUE_SIZE = propertiesUtil.getInt("async.executor.pool.blocking.queue.size",10);
//
// }
// Path: redant-core/src/main/java/com/redant/core/init/InitExecutor.java
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.ClassScaner;
import com.redant.core.common.constants.CommonConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
package com.redant.core.init;
/**
* @author houyi.wh
* @date 2019-01-14
*/
public final class InitExecutor {
private static final Logger LOGGER = LoggerFactory.getLogger(InitExecutor.class);
private static AtomicBoolean initialized = new AtomicBoolean(false);
public static void init() {
if (!initialized.compareAndSet(false, true)) {
return;
}
try { | Set<Class<?>> classSet = ClassScaner.scanPackageBySuper(CommonConstants.BEAN_SCAN_PACKAGE,InitFunc.class); |
all4you/redant | redant-example/src/main/java/com/redant/example/interceptor/PerformanceInterceptor.java | // Path: redant-core/src/main/java/com/redant/core/context/RedantContext.java
// public class RedantContext {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(RedantContext.class);
//
// /**
// * 使用FastThreadLocal替代JDK自带的ThreadLocal以提升并发性能
// */
// private static final FastThreadLocal<RedantContext> CONTEXT_HOLDER = new FastThreadLocal<>();
//
// private HttpRequest request;
//
// private ChannelHandlerContext context;
//
// private HttpResponse response;
//
// private Set<Cookie> cookies;
//
// private RedantContext(){
//
// }
//
// public RedantContext setRequest(HttpRequest request){
// this.request = request;
// return this;
// }
//
// public RedantContext setContext(ChannelHandlerContext context){
// this.context = context;
// return this;
// }
//
// public RedantContext setResponse(HttpResponse response){
// this.response = response;
// return this;
// }
//
// public RedantContext addCookie(Cookie cookie){
// if(cookie!=null){
// if(CollectionUtil.isEmpty(cookies)){
// cookies = new HashSet<>();
// }
// cookies.add(cookie);
// }
// return this;
// }
//
// public RedantContext addCookies(Set<Cookie> cookieSet){
// if(CollectionUtil.isNotEmpty(cookieSet)){
// if(CollectionUtil.isEmpty(cookies)){
// cookies = new HashSet<>();
// }
// cookies.addAll(cookieSet);
// }
// return this;
// }
//
// public HttpRequest getRequest() {
// return request;
// }
//
// public ChannelHandlerContext getContext() {
// return context;
// }
//
// public HttpResponse getResponse() {
// return response;
// }
//
// public Set<Cookie> getCookies() {
// return cookies;
// }
//
// public static RedantContext currentContext(){
// RedantContext context = CONTEXT_HOLDER.get();
// if(context==null){
// context = new RedantContext();
// CONTEXT_HOLDER.set(context);
// }
// return context;
// }
//
// public static void clear(){
// CONTEXT_HOLDER.remove();
// }
//
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/interceptor/Interceptor.java
// public abstract class Interceptor {
//
// /**
// * 拦截器的前置处理方法
// */
// public boolean preHandle(Map<String, List<String>> paramMap){
// return true;
// }
//
// /**
// * 拦截器的后置处理方法
// */
// public abstract void postHandle(Map<String, List<String>> paramMap);
//
// }
| import com.redant.core.anno.Order;
import com.redant.core.context.RedantContext;
import com.redant.core.interceptor.Interceptor;
import io.netty.handler.codec.http.HttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map; | package com.redant.example.interceptor;
/**
* 该拦截器可以计算出用户自定义 Controller 方法的执行时间
* @author houyi
**/
@Order(value = 2)
public class PerformanceInterceptor extends Interceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(PerformanceInterceptor.class);
private ThreadLocal<Long> start = new ThreadLocal<>();
@Override
public boolean preHandle(Map<String, List<String>> paramMap) {
start.set(System.currentTimeMillis());
return true;
}
@Override
public void postHandle(Map<String, List<String>> paramMap) {
try {
long end = System.currentTimeMillis();
long cost = end - start.get(); | // Path: redant-core/src/main/java/com/redant/core/context/RedantContext.java
// public class RedantContext {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(RedantContext.class);
//
// /**
// * 使用FastThreadLocal替代JDK自带的ThreadLocal以提升并发性能
// */
// private static final FastThreadLocal<RedantContext> CONTEXT_HOLDER = new FastThreadLocal<>();
//
// private HttpRequest request;
//
// private ChannelHandlerContext context;
//
// private HttpResponse response;
//
// private Set<Cookie> cookies;
//
// private RedantContext(){
//
// }
//
// public RedantContext setRequest(HttpRequest request){
// this.request = request;
// return this;
// }
//
// public RedantContext setContext(ChannelHandlerContext context){
// this.context = context;
// return this;
// }
//
// public RedantContext setResponse(HttpResponse response){
// this.response = response;
// return this;
// }
//
// public RedantContext addCookie(Cookie cookie){
// if(cookie!=null){
// if(CollectionUtil.isEmpty(cookies)){
// cookies = new HashSet<>();
// }
// cookies.add(cookie);
// }
// return this;
// }
//
// public RedantContext addCookies(Set<Cookie> cookieSet){
// if(CollectionUtil.isNotEmpty(cookieSet)){
// if(CollectionUtil.isEmpty(cookies)){
// cookies = new HashSet<>();
// }
// cookies.addAll(cookieSet);
// }
// return this;
// }
//
// public HttpRequest getRequest() {
// return request;
// }
//
// public ChannelHandlerContext getContext() {
// return context;
// }
//
// public HttpResponse getResponse() {
// return response;
// }
//
// public Set<Cookie> getCookies() {
// return cookies;
// }
//
// public static RedantContext currentContext(){
// RedantContext context = CONTEXT_HOLDER.get();
// if(context==null){
// context = new RedantContext();
// CONTEXT_HOLDER.set(context);
// }
// return context;
// }
//
// public static void clear(){
// CONTEXT_HOLDER.remove();
// }
//
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/interceptor/Interceptor.java
// public abstract class Interceptor {
//
// /**
// * 拦截器的前置处理方法
// */
// public boolean preHandle(Map<String, List<String>> paramMap){
// return true;
// }
//
// /**
// * 拦截器的后置处理方法
// */
// public abstract void postHandle(Map<String, List<String>> paramMap);
//
// }
// Path: redant-example/src/main/java/com/redant/example/interceptor/PerformanceInterceptor.java
import com.redant.core.anno.Order;
import com.redant.core.context.RedantContext;
import com.redant.core.interceptor.Interceptor;
import io.netty.handler.codec.http.HttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
package com.redant.example.interceptor;
/**
* 该拦截器可以计算出用户自定义 Controller 方法的执行时间
* @author houyi
**/
@Order(value = 2)
public class PerformanceInterceptor extends Interceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(PerformanceInterceptor.class);
private ThreadLocal<Long> start = new ThreadLocal<>();
@Override
public boolean preHandle(Map<String, List<String>> paramMap) {
start.set(System.currentTimeMillis());
return true;
}
@Override
public void postHandle(Map<String, List<String>> paramMap) {
try {
long end = System.currentTimeMillis();
long cost = end - start.get(); | HttpRequest request = RedantContext.currentContext().getRequest(); |
all4you/redant | redant-cluster/src/main/java/com/redant/cluster/service/discover/ZkServiceDiscover.java | // Path: redant-cluster/src/main/java/com/redant/cluster/node/Node.java
// public class Node {
//
// private static final String DEFAULT_HOST = GenericsUtil.getLocalIpV4();
//
// private static final int DEFAULT_PORT = 8088;
//
// public static final Node DEFAULT_PORT_NODE = new Node(DEFAULT_HOST,DEFAULT_PORT);
//
// private String id;
//
// private String host;
//
// private int port;
//
// public Node(int port){
// this(DEFAULT_HOST,port);
// }
//
// public Node(String host, int port){
// this(SecureUtil.md5(host+"&"+port),host,port);
// }
//
// public Node(String id, String host, int port){
// this.id = id;
// this.host = host;
// this.port = port;
// }
//
// public static Node getNodeWithArgs(String[] args){
// Node node = Node.DEFAULT_PORT_NODE;
// if(args.length>1 && NumberUtil.isInteger(args[1])){
// node = new Node(Integer.parseInt(args[1]));
// }
// return node;
// }
//
// /**
// * 从JsonObject中解析出SlaveNode
// * @param object 对象
// * @return 节点
// */
// public static Node parse(JSONObject object){
// if(object==null){
// return null;
// }
// String host = object.getString("host");
// int port = object.getIntValue("port");
// String id = object.getString("id");
// return new Node(id,host,port);
// }
//
// public String getHost() {
// return host;
// }
//
// public void setHost(String host) {
// this.host = host;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// public String getId(){
// return id;
// }
//
// @Override
// public String toString() {
// return JSON.toJSONString(this);
// }
//
// }
//
// Path: redant-cluster/src/main/java/com/redant/cluster/zk/ZkClient.java
// public class ZkClient {
//
// /**
// * 节点的session超时时间,当Slave服务停掉后,
// * curator客户端需要等待该节点超时后才会触发CHILD_REMOVED事件
// */
// private static final int DEFAULT_SESSION_TIMEOUT_MS = 5000;
//
// private static final int DEFAULT_CONNECTION_TIMEOUT_MS = 15000;
//
// /**
// * 操作ZK的客户端
// */
// private static Map<String,CuratorFramework> clients;
//
// private static Lock lock;
//
// static{
// clients = new ConcurrentHashMap<>();
// lock = new ReentrantLock();
// }
//
// /**
// * 获取ZK客户端
// * @param zkAddress zk服务端地址
// * @return zk客户端
// */
// public static CuratorFramework getClient(String zkAddress){
// if(zkAddress == null || zkAddress.trim().length() == 0){
// return null;
// }
// CuratorFramework client = clients.get(zkAddress);
// if(client==null){
// lock.lock();
// try {
// if(!clients.containsKey(zkAddress)) {
// client = CuratorFrameworkFactory.newClient(
// zkAddress,
// DEFAULT_SESSION_TIMEOUT_MS,
// DEFAULT_CONNECTION_TIMEOUT_MS,
// new RetryNTimes(10, 5000)
// );
// client.start();
// clients.putIfAbsent(zkAddress,client);
// }else{
// client = clients.get(zkAddress);
// }
// }finally {
// lock.unlock();
// }
// }
// return client;
// }
//
// }
//
// Path: redant-cluster/src/main/java/com/redant/cluster/zk/ZkNode.java
// public class ZkNode {
//
// /**
// * 根节点
// */
// public static final String ROOT_NODE_PATH = "/redant";
//
// /**
// * SlaveNode注册的节点
// */
// public static final String SLAVE_NODE_PATH = ROOT_NODE_PATH+"/slave";
//
//
//
// }
| import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.redant.cluster.node.Node;
import com.redant.cluster.zk.ZkClient;
import com.redant.cluster.zk.ZkNode;
import io.netty.util.CharsetUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; | package com.redant.cluster.service.discover;
/**
* 服务发现
* @author houyi.wh
* @date 2017/11/20
**/
public class ZkServiceDiscover implements ServiceDiscover {
private static final Logger LOGGER = LoggerFactory.getLogger(ZkServiceDiscover.class);
private CuratorFramework client;
| // Path: redant-cluster/src/main/java/com/redant/cluster/node/Node.java
// public class Node {
//
// private static final String DEFAULT_HOST = GenericsUtil.getLocalIpV4();
//
// private static final int DEFAULT_PORT = 8088;
//
// public static final Node DEFAULT_PORT_NODE = new Node(DEFAULT_HOST,DEFAULT_PORT);
//
// private String id;
//
// private String host;
//
// private int port;
//
// public Node(int port){
// this(DEFAULT_HOST,port);
// }
//
// public Node(String host, int port){
// this(SecureUtil.md5(host+"&"+port),host,port);
// }
//
// public Node(String id, String host, int port){
// this.id = id;
// this.host = host;
// this.port = port;
// }
//
// public static Node getNodeWithArgs(String[] args){
// Node node = Node.DEFAULT_PORT_NODE;
// if(args.length>1 && NumberUtil.isInteger(args[1])){
// node = new Node(Integer.parseInt(args[1]));
// }
// return node;
// }
//
// /**
// * 从JsonObject中解析出SlaveNode
// * @param object 对象
// * @return 节点
// */
// public static Node parse(JSONObject object){
// if(object==null){
// return null;
// }
// String host = object.getString("host");
// int port = object.getIntValue("port");
// String id = object.getString("id");
// return new Node(id,host,port);
// }
//
// public String getHost() {
// return host;
// }
//
// public void setHost(String host) {
// this.host = host;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// public String getId(){
// return id;
// }
//
// @Override
// public String toString() {
// return JSON.toJSONString(this);
// }
//
// }
//
// Path: redant-cluster/src/main/java/com/redant/cluster/zk/ZkClient.java
// public class ZkClient {
//
// /**
// * 节点的session超时时间,当Slave服务停掉后,
// * curator客户端需要等待该节点超时后才会触发CHILD_REMOVED事件
// */
// private static final int DEFAULT_SESSION_TIMEOUT_MS = 5000;
//
// private static final int DEFAULT_CONNECTION_TIMEOUT_MS = 15000;
//
// /**
// * 操作ZK的客户端
// */
// private static Map<String,CuratorFramework> clients;
//
// private static Lock lock;
//
// static{
// clients = new ConcurrentHashMap<>();
// lock = new ReentrantLock();
// }
//
// /**
// * 获取ZK客户端
// * @param zkAddress zk服务端地址
// * @return zk客户端
// */
// public static CuratorFramework getClient(String zkAddress){
// if(zkAddress == null || zkAddress.trim().length() == 0){
// return null;
// }
// CuratorFramework client = clients.get(zkAddress);
// if(client==null){
// lock.lock();
// try {
// if(!clients.containsKey(zkAddress)) {
// client = CuratorFrameworkFactory.newClient(
// zkAddress,
// DEFAULT_SESSION_TIMEOUT_MS,
// DEFAULT_CONNECTION_TIMEOUT_MS,
// new RetryNTimes(10, 5000)
// );
// client.start();
// clients.putIfAbsent(zkAddress,client);
// }else{
// client = clients.get(zkAddress);
// }
// }finally {
// lock.unlock();
// }
// }
// return client;
// }
//
// }
//
// Path: redant-cluster/src/main/java/com/redant/cluster/zk/ZkNode.java
// public class ZkNode {
//
// /**
// * 根节点
// */
// public static final String ROOT_NODE_PATH = "/redant";
//
// /**
// * SlaveNode注册的节点
// */
// public static final String SLAVE_NODE_PATH = ROOT_NODE_PATH+"/slave";
//
//
//
// }
// Path: redant-cluster/src/main/java/com/redant/cluster/service/discover/ZkServiceDiscover.java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.redant.cluster.node.Node;
import com.redant.cluster.zk.ZkClient;
import com.redant.cluster.zk.ZkNode;
import io.netty.util.CharsetUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
package com.redant.cluster.service.discover;
/**
* 服务发现
* @author houyi.wh
* @date 2017/11/20
**/
public class ZkServiceDiscover implements ServiceDiscover {
private static final Logger LOGGER = LoggerFactory.getLogger(ZkServiceDiscover.class);
private CuratorFramework client;
| private Map<String,Node> nodeMap; |
all4you/redant | redant-cluster/src/main/java/com/redant/cluster/service/discover/ZkServiceDiscover.java | // Path: redant-cluster/src/main/java/com/redant/cluster/node/Node.java
// public class Node {
//
// private static final String DEFAULT_HOST = GenericsUtil.getLocalIpV4();
//
// private static final int DEFAULT_PORT = 8088;
//
// public static final Node DEFAULT_PORT_NODE = new Node(DEFAULT_HOST,DEFAULT_PORT);
//
// private String id;
//
// private String host;
//
// private int port;
//
// public Node(int port){
// this(DEFAULT_HOST,port);
// }
//
// public Node(String host, int port){
// this(SecureUtil.md5(host+"&"+port),host,port);
// }
//
// public Node(String id, String host, int port){
// this.id = id;
// this.host = host;
// this.port = port;
// }
//
// public static Node getNodeWithArgs(String[] args){
// Node node = Node.DEFAULT_PORT_NODE;
// if(args.length>1 && NumberUtil.isInteger(args[1])){
// node = new Node(Integer.parseInt(args[1]));
// }
// return node;
// }
//
// /**
// * 从JsonObject中解析出SlaveNode
// * @param object 对象
// * @return 节点
// */
// public static Node parse(JSONObject object){
// if(object==null){
// return null;
// }
// String host = object.getString("host");
// int port = object.getIntValue("port");
// String id = object.getString("id");
// return new Node(id,host,port);
// }
//
// public String getHost() {
// return host;
// }
//
// public void setHost(String host) {
// this.host = host;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// public String getId(){
// return id;
// }
//
// @Override
// public String toString() {
// return JSON.toJSONString(this);
// }
//
// }
//
// Path: redant-cluster/src/main/java/com/redant/cluster/zk/ZkClient.java
// public class ZkClient {
//
// /**
// * 节点的session超时时间,当Slave服务停掉后,
// * curator客户端需要等待该节点超时后才会触发CHILD_REMOVED事件
// */
// private static final int DEFAULT_SESSION_TIMEOUT_MS = 5000;
//
// private static final int DEFAULT_CONNECTION_TIMEOUT_MS = 15000;
//
// /**
// * 操作ZK的客户端
// */
// private static Map<String,CuratorFramework> clients;
//
// private static Lock lock;
//
// static{
// clients = new ConcurrentHashMap<>();
// lock = new ReentrantLock();
// }
//
// /**
// * 获取ZK客户端
// * @param zkAddress zk服务端地址
// * @return zk客户端
// */
// public static CuratorFramework getClient(String zkAddress){
// if(zkAddress == null || zkAddress.trim().length() == 0){
// return null;
// }
// CuratorFramework client = clients.get(zkAddress);
// if(client==null){
// lock.lock();
// try {
// if(!clients.containsKey(zkAddress)) {
// client = CuratorFrameworkFactory.newClient(
// zkAddress,
// DEFAULT_SESSION_TIMEOUT_MS,
// DEFAULT_CONNECTION_TIMEOUT_MS,
// new RetryNTimes(10, 5000)
// );
// client.start();
// clients.putIfAbsent(zkAddress,client);
// }else{
// client = clients.get(zkAddress);
// }
// }finally {
// lock.unlock();
// }
// }
// return client;
// }
//
// }
//
// Path: redant-cluster/src/main/java/com/redant/cluster/zk/ZkNode.java
// public class ZkNode {
//
// /**
// * 根节点
// */
// public static final String ROOT_NODE_PATH = "/redant";
//
// /**
// * SlaveNode注册的节点
// */
// public static final String SLAVE_NODE_PATH = ROOT_NODE_PATH+"/slave";
//
//
//
// }
| import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.redant.cluster.node.Node;
import com.redant.cluster.zk.ZkClient;
import com.redant.cluster.zk.ZkNode;
import io.netty.util.CharsetUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; | package com.redant.cluster.service.discover;
/**
* 服务发现
* @author houyi.wh
* @date 2017/11/20
**/
public class ZkServiceDiscover implements ServiceDiscover {
private static final Logger LOGGER = LoggerFactory.getLogger(ZkServiceDiscover.class);
private CuratorFramework client;
private Map<String,Node> nodeMap;
private Lock lock;
private int slaveIndex = 0;
private static ServiceDiscover discover;
private ZkServiceDiscover(){
}
private ZkServiceDiscover(String zkAddress){ | // Path: redant-cluster/src/main/java/com/redant/cluster/node/Node.java
// public class Node {
//
// private static final String DEFAULT_HOST = GenericsUtil.getLocalIpV4();
//
// private static final int DEFAULT_PORT = 8088;
//
// public static final Node DEFAULT_PORT_NODE = new Node(DEFAULT_HOST,DEFAULT_PORT);
//
// private String id;
//
// private String host;
//
// private int port;
//
// public Node(int port){
// this(DEFAULT_HOST,port);
// }
//
// public Node(String host, int port){
// this(SecureUtil.md5(host+"&"+port),host,port);
// }
//
// public Node(String id, String host, int port){
// this.id = id;
// this.host = host;
// this.port = port;
// }
//
// public static Node getNodeWithArgs(String[] args){
// Node node = Node.DEFAULT_PORT_NODE;
// if(args.length>1 && NumberUtil.isInteger(args[1])){
// node = new Node(Integer.parseInt(args[1]));
// }
// return node;
// }
//
// /**
// * 从JsonObject中解析出SlaveNode
// * @param object 对象
// * @return 节点
// */
// public static Node parse(JSONObject object){
// if(object==null){
// return null;
// }
// String host = object.getString("host");
// int port = object.getIntValue("port");
// String id = object.getString("id");
// return new Node(id,host,port);
// }
//
// public String getHost() {
// return host;
// }
//
// public void setHost(String host) {
// this.host = host;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// public String getId(){
// return id;
// }
//
// @Override
// public String toString() {
// return JSON.toJSONString(this);
// }
//
// }
//
// Path: redant-cluster/src/main/java/com/redant/cluster/zk/ZkClient.java
// public class ZkClient {
//
// /**
// * 节点的session超时时间,当Slave服务停掉后,
// * curator客户端需要等待该节点超时后才会触发CHILD_REMOVED事件
// */
// private static final int DEFAULT_SESSION_TIMEOUT_MS = 5000;
//
// private static final int DEFAULT_CONNECTION_TIMEOUT_MS = 15000;
//
// /**
// * 操作ZK的客户端
// */
// private static Map<String,CuratorFramework> clients;
//
// private static Lock lock;
//
// static{
// clients = new ConcurrentHashMap<>();
// lock = new ReentrantLock();
// }
//
// /**
// * 获取ZK客户端
// * @param zkAddress zk服务端地址
// * @return zk客户端
// */
// public static CuratorFramework getClient(String zkAddress){
// if(zkAddress == null || zkAddress.trim().length() == 0){
// return null;
// }
// CuratorFramework client = clients.get(zkAddress);
// if(client==null){
// lock.lock();
// try {
// if(!clients.containsKey(zkAddress)) {
// client = CuratorFrameworkFactory.newClient(
// zkAddress,
// DEFAULT_SESSION_TIMEOUT_MS,
// DEFAULT_CONNECTION_TIMEOUT_MS,
// new RetryNTimes(10, 5000)
// );
// client.start();
// clients.putIfAbsent(zkAddress,client);
// }else{
// client = clients.get(zkAddress);
// }
// }finally {
// lock.unlock();
// }
// }
// return client;
// }
//
// }
//
// Path: redant-cluster/src/main/java/com/redant/cluster/zk/ZkNode.java
// public class ZkNode {
//
// /**
// * 根节点
// */
// public static final String ROOT_NODE_PATH = "/redant";
//
// /**
// * SlaveNode注册的节点
// */
// public static final String SLAVE_NODE_PATH = ROOT_NODE_PATH+"/slave";
//
//
//
// }
// Path: redant-cluster/src/main/java/com/redant/cluster/service/discover/ZkServiceDiscover.java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.redant.cluster.node.Node;
import com.redant.cluster.zk.ZkClient;
import com.redant.cluster.zk.ZkNode;
import io.netty.util.CharsetUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
package com.redant.cluster.service.discover;
/**
* 服务发现
* @author houyi.wh
* @date 2017/11/20
**/
public class ZkServiceDiscover implements ServiceDiscover {
private static final Logger LOGGER = LoggerFactory.getLogger(ZkServiceDiscover.class);
private CuratorFramework client;
private Map<String,Node> nodeMap;
private Lock lock;
private int slaveIndex = 0;
private static ServiceDiscover discover;
private ZkServiceDiscover(){
}
private ZkServiceDiscover(String zkAddress){ | client = ZkClient.getClient(zkAddress); |
all4you/redant | redant-core/src/main/java/com/redant/core/ServerBootstrap.java | // Path: redant-core/src/main/java/com/redant/core/server/NettyHttpServer.java
// public final class NettyHttpServer implements Server {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(NettyHttpServer.class);
//
// @Override
// public void preStart() {
// InitExecutor.init();
// }
//
// @Override
// public void start() {
// EventLoopGroup bossGroup = new NioEventLoopGroup(CommonConstants.BOSS_GROUP_SIZE, new DefaultThreadFactory("boss", true));
// EventLoopGroup workerGroup = new NioEventLoopGroup(CommonConstants.WORKER_GROUP_SIZE, new DefaultThreadFactory("worker", true));
// try {
// long start = System.currentTimeMillis();
// ServerBootstrap b = new ServerBootstrap();
// b.option(ChannelOption.SO_BACKLOG, 1024);
// b.group(bossGroup, workerGroup)
// .channel(NioServerSocketChannel.class)
// // .handler(new LoggingHandler(LogLevel.INFO))
// .childHandler(new NettyHttpServerInitializer());
//
// ChannelFuture future = b.bind(CommonConstants.SERVER_PORT).sync();
// long cost = System.currentTimeMillis()-start;
// LOGGER.info("[NettyHttpServer] Startup at port:{} cost:{}[ms]",CommonConstants.SERVER_PORT,cost);
//
// // 等待服务端Socket关闭
// future.channel().closeFuture().sync();
// } catch (InterruptedException e) {
// LOGGER.error("[NettyHttpServer] InterruptedException:",e);
// } finally {
// bossGroup.shutdownGracefully();
// workerGroup.shutdownGracefully();
// }
// }
//
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/server/Server.java
// public interface Server {
//
// /**
// * 启动服务器之前的事件处理
// */
// void preStart();
//
// /**
// * 启动服务器
// */
// void start();
//
// }
| import com.redant.core.server.NettyHttpServer;
import com.redant.core.server.Server; | package com.redant.core;
/**
* 服务端启动入口
* @author houyi.wh
* @date 2017-10-20
*/
public final class ServerBootstrap {
public static void main(String[] args) { | // Path: redant-core/src/main/java/com/redant/core/server/NettyHttpServer.java
// public final class NettyHttpServer implements Server {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(NettyHttpServer.class);
//
// @Override
// public void preStart() {
// InitExecutor.init();
// }
//
// @Override
// public void start() {
// EventLoopGroup bossGroup = new NioEventLoopGroup(CommonConstants.BOSS_GROUP_SIZE, new DefaultThreadFactory("boss", true));
// EventLoopGroup workerGroup = new NioEventLoopGroup(CommonConstants.WORKER_GROUP_SIZE, new DefaultThreadFactory("worker", true));
// try {
// long start = System.currentTimeMillis();
// ServerBootstrap b = new ServerBootstrap();
// b.option(ChannelOption.SO_BACKLOG, 1024);
// b.group(bossGroup, workerGroup)
// .channel(NioServerSocketChannel.class)
// // .handler(new LoggingHandler(LogLevel.INFO))
// .childHandler(new NettyHttpServerInitializer());
//
// ChannelFuture future = b.bind(CommonConstants.SERVER_PORT).sync();
// long cost = System.currentTimeMillis()-start;
// LOGGER.info("[NettyHttpServer] Startup at port:{} cost:{}[ms]",CommonConstants.SERVER_PORT,cost);
//
// // 等待服务端Socket关闭
// future.channel().closeFuture().sync();
// } catch (InterruptedException e) {
// LOGGER.error("[NettyHttpServer] InterruptedException:",e);
// } finally {
// bossGroup.shutdownGracefully();
// workerGroup.shutdownGracefully();
// }
// }
//
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/server/Server.java
// public interface Server {
//
// /**
// * 启动服务器之前的事件处理
// */
// void preStart();
//
// /**
// * 启动服务器
// */
// void start();
//
// }
// Path: redant-core/src/main/java/com/redant/core/ServerBootstrap.java
import com.redant.core.server.NettyHttpServer;
import com.redant.core.server.Server;
package com.redant.core;
/**
* 服务端启动入口
* @author houyi.wh
* @date 2017-10-20
*/
public final class ServerBootstrap {
public static void main(String[] args) { | Server nettyServer = new NettyHttpServer(); |
all4you/redant | redant-core/src/main/java/com/redant/core/ServerBootstrap.java | // Path: redant-core/src/main/java/com/redant/core/server/NettyHttpServer.java
// public final class NettyHttpServer implements Server {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(NettyHttpServer.class);
//
// @Override
// public void preStart() {
// InitExecutor.init();
// }
//
// @Override
// public void start() {
// EventLoopGroup bossGroup = new NioEventLoopGroup(CommonConstants.BOSS_GROUP_SIZE, new DefaultThreadFactory("boss", true));
// EventLoopGroup workerGroup = new NioEventLoopGroup(CommonConstants.WORKER_GROUP_SIZE, new DefaultThreadFactory("worker", true));
// try {
// long start = System.currentTimeMillis();
// ServerBootstrap b = new ServerBootstrap();
// b.option(ChannelOption.SO_BACKLOG, 1024);
// b.group(bossGroup, workerGroup)
// .channel(NioServerSocketChannel.class)
// // .handler(new LoggingHandler(LogLevel.INFO))
// .childHandler(new NettyHttpServerInitializer());
//
// ChannelFuture future = b.bind(CommonConstants.SERVER_PORT).sync();
// long cost = System.currentTimeMillis()-start;
// LOGGER.info("[NettyHttpServer] Startup at port:{} cost:{}[ms]",CommonConstants.SERVER_PORT,cost);
//
// // 等待服务端Socket关闭
// future.channel().closeFuture().sync();
// } catch (InterruptedException e) {
// LOGGER.error("[NettyHttpServer] InterruptedException:",e);
// } finally {
// bossGroup.shutdownGracefully();
// workerGroup.shutdownGracefully();
// }
// }
//
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/server/Server.java
// public interface Server {
//
// /**
// * 启动服务器之前的事件处理
// */
// void preStart();
//
// /**
// * 启动服务器
// */
// void start();
//
// }
| import com.redant.core.server.NettyHttpServer;
import com.redant.core.server.Server; | package com.redant.core;
/**
* 服务端启动入口
* @author houyi.wh
* @date 2017-10-20
*/
public final class ServerBootstrap {
public static void main(String[] args) { | // Path: redant-core/src/main/java/com/redant/core/server/NettyHttpServer.java
// public final class NettyHttpServer implements Server {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(NettyHttpServer.class);
//
// @Override
// public void preStart() {
// InitExecutor.init();
// }
//
// @Override
// public void start() {
// EventLoopGroup bossGroup = new NioEventLoopGroup(CommonConstants.BOSS_GROUP_SIZE, new DefaultThreadFactory("boss", true));
// EventLoopGroup workerGroup = new NioEventLoopGroup(CommonConstants.WORKER_GROUP_SIZE, new DefaultThreadFactory("worker", true));
// try {
// long start = System.currentTimeMillis();
// ServerBootstrap b = new ServerBootstrap();
// b.option(ChannelOption.SO_BACKLOG, 1024);
// b.group(bossGroup, workerGroup)
// .channel(NioServerSocketChannel.class)
// // .handler(new LoggingHandler(LogLevel.INFO))
// .childHandler(new NettyHttpServerInitializer());
//
// ChannelFuture future = b.bind(CommonConstants.SERVER_PORT).sync();
// long cost = System.currentTimeMillis()-start;
// LOGGER.info("[NettyHttpServer] Startup at port:{} cost:{}[ms]",CommonConstants.SERVER_PORT,cost);
//
// // 等待服务端Socket关闭
// future.channel().closeFuture().sync();
// } catch (InterruptedException e) {
// LOGGER.error("[NettyHttpServer] InterruptedException:",e);
// } finally {
// bossGroup.shutdownGracefully();
// workerGroup.shutdownGracefully();
// }
// }
//
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/server/Server.java
// public interface Server {
//
// /**
// * 启动服务器之前的事件处理
// */
// void preStart();
//
// /**
// * 启动服务器
// */
// void start();
//
// }
// Path: redant-core/src/main/java/com/redant/core/ServerBootstrap.java
import com.redant.core.server.NettyHttpServer;
import com.redant.core.server.Server;
package com.redant.core;
/**
* 服务端启动入口
* @author houyi.wh
* @date 2017-10-20
*/
public final class ServerBootstrap {
public static void main(String[] args) { | Server nettyServer = new NettyHttpServer(); |
all4you/redant | redant-cluster/src/main/java/com/redant/cluster/service/register/ZkServiceRegister.java | // Path: redant-cluster/src/main/java/com/redant/cluster/node/Node.java
// public class Node {
//
// private static final String DEFAULT_HOST = GenericsUtil.getLocalIpV4();
//
// private static final int DEFAULT_PORT = 8088;
//
// public static final Node DEFAULT_PORT_NODE = new Node(DEFAULT_HOST,DEFAULT_PORT);
//
// private String id;
//
// private String host;
//
// private int port;
//
// public Node(int port){
// this(DEFAULT_HOST,port);
// }
//
// public Node(String host, int port){
// this(SecureUtil.md5(host+"&"+port),host,port);
// }
//
// public Node(String id, String host, int port){
// this.id = id;
// this.host = host;
// this.port = port;
// }
//
// public static Node getNodeWithArgs(String[] args){
// Node node = Node.DEFAULT_PORT_NODE;
// if(args.length>1 && NumberUtil.isInteger(args[1])){
// node = new Node(Integer.parseInt(args[1]));
// }
// return node;
// }
//
// /**
// * 从JsonObject中解析出SlaveNode
// * @param object 对象
// * @return 节点
// */
// public static Node parse(JSONObject object){
// if(object==null){
// return null;
// }
// String host = object.getString("host");
// int port = object.getIntValue("port");
// String id = object.getString("id");
// return new Node(id,host,port);
// }
//
// public String getHost() {
// return host;
// }
//
// public void setHost(String host) {
// this.host = host;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// public String getId(){
// return id;
// }
//
// @Override
// public String toString() {
// return JSON.toJSONString(this);
// }
//
// }
//
// Path: redant-cluster/src/main/java/com/redant/cluster/zk/ZkClient.java
// public class ZkClient {
//
// /**
// * 节点的session超时时间,当Slave服务停掉后,
// * curator客户端需要等待该节点超时后才会触发CHILD_REMOVED事件
// */
// private static final int DEFAULT_SESSION_TIMEOUT_MS = 5000;
//
// private static final int DEFAULT_CONNECTION_TIMEOUT_MS = 15000;
//
// /**
// * 操作ZK的客户端
// */
// private static Map<String,CuratorFramework> clients;
//
// private static Lock lock;
//
// static{
// clients = new ConcurrentHashMap<>();
// lock = new ReentrantLock();
// }
//
// /**
// * 获取ZK客户端
// * @param zkAddress zk服务端地址
// * @return zk客户端
// */
// public static CuratorFramework getClient(String zkAddress){
// if(zkAddress == null || zkAddress.trim().length() == 0){
// return null;
// }
// CuratorFramework client = clients.get(zkAddress);
// if(client==null){
// lock.lock();
// try {
// if(!clients.containsKey(zkAddress)) {
// client = CuratorFrameworkFactory.newClient(
// zkAddress,
// DEFAULT_SESSION_TIMEOUT_MS,
// DEFAULT_CONNECTION_TIMEOUT_MS,
// new RetryNTimes(10, 5000)
// );
// client.start();
// clients.putIfAbsent(zkAddress,client);
// }else{
// client = clients.get(zkAddress);
// }
// }finally {
// lock.unlock();
// }
// }
// return client;
// }
//
// }
//
// Path: redant-cluster/src/main/java/com/redant/cluster/zk/ZkNode.java
// public class ZkNode {
//
// /**
// * 根节点
// */
// public static final String ROOT_NODE_PATH = "/redant";
//
// /**
// * SlaveNode注册的节点
// */
// public static final String SLAVE_NODE_PATH = ROOT_NODE_PATH+"/slave";
//
//
//
// }
| import cn.hutool.core.util.StrUtil;
import com.redant.cluster.node.Node;
import com.redant.cluster.zk.ZkClient;
import com.redant.cluster.zk.ZkNode;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package com.redant.cluster.service.register;
/**
* @author houyi.wh
* @date 2017/11/21
**/
public class ZkServiceRegister implements ServiceRegister {
private static final Logger LOGGER = LoggerFactory.getLogger(ZkServiceRegister.class);
private CuratorFramework client;
private static ZkServiceRegister register;
private ZkServiceRegister(){
}
private ZkServiceRegister(String zkAddress){ | // Path: redant-cluster/src/main/java/com/redant/cluster/node/Node.java
// public class Node {
//
// private static final String DEFAULT_HOST = GenericsUtil.getLocalIpV4();
//
// private static final int DEFAULT_PORT = 8088;
//
// public static final Node DEFAULT_PORT_NODE = new Node(DEFAULT_HOST,DEFAULT_PORT);
//
// private String id;
//
// private String host;
//
// private int port;
//
// public Node(int port){
// this(DEFAULT_HOST,port);
// }
//
// public Node(String host, int port){
// this(SecureUtil.md5(host+"&"+port),host,port);
// }
//
// public Node(String id, String host, int port){
// this.id = id;
// this.host = host;
// this.port = port;
// }
//
// public static Node getNodeWithArgs(String[] args){
// Node node = Node.DEFAULT_PORT_NODE;
// if(args.length>1 && NumberUtil.isInteger(args[1])){
// node = new Node(Integer.parseInt(args[1]));
// }
// return node;
// }
//
// /**
// * 从JsonObject中解析出SlaveNode
// * @param object 对象
// * @return 节点
// */
// public static Node parse(JSONObject object){
// if(object==null){
// return null;
// }
// String host = object.getString("host");
// int port = object.getIntValue("port");
// String id = object.getString("id");
// return new Node(id,host,port);
// }
//
// public String getHost() {
// return host;
// }
//
// public void setHost(String host) {
// this.host = host;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// public String getId(){
// return id;
// }
//
// @Override
// public String toString() {
// return JSON.toJSONString(this);
// }
//
// }
//
// Path: redant-cluster/src/main/java/com/redant/cluster/zk/ZkClient.java
// public class ZkClient {
//
// /**
// * 节点的session超时时间,当Slave服务停掉后,
// * curator客户端需要等待该节点超时后才会触发CHILD_REMOVED事件
// */
// private static final int DEFAULT_SESSION_TIMEOUT_MS = 5000;
//
// private static final int DEFAULT_CONNECTION_TIMEOUT_MS = 15000;
//
// /**
// * 操作ZK的客户端
// */
// private static Map<String,CuratorFramework> clients;
//
// private static Lock lock;
//
// static{
// clients = new ConcurrentHashMap<>();
// lock = new ReentrantLock();
// }
//
// /**
// * 获取ZK客户端
// * @param zkAddress zk服务端地址
// * @return zk客户端
// */
// public static CuratorFramework getClient(String zkAddress){
// if(zkAddress == null || zkAddress.trim().length() == 0){
// return null;
// }
// CuratorFramework client = clients.get(zkAddress);
// if(client==null){
// lock.lock();
// try {
// if(!clients.containsKey(zkAddress)) {
// client = CuratorFrameworkFactory.newClient(
// zkAddress,
// DEFAULT_SESSION_TIMEOUT_MS,
// DEFAULT_CONNECTION_TIMEOUT_MS,
// new RetryNTimes(10, 5000)
// );
// client.start();
// clients.putIfAbsent(zkAddress,client);
// }else{
// client = clients.get(zkAddress);
// }
// }finally {
// lock.unlock();
// }
// }
// return client;
// }
//
// }
//
// Path: redant-cluster/src/main/java/com/redant/cluster/zk/ZkNode.java
// public class ZkNode {
//
// /**
// * 根节点
// */
// public static final String ROOT_NODE_PATH = "/redant";
//
// /**
// * SlaveNode注册的节点
// */
// public static final String SLAVE_NODE_PATH = ROOT_NODE_PATH+"/slave";
//
//
//
// }
// Path: redant-cluster/src/main/java/com/redant/cluster/service/register/ZkServiceRegister.java
import cn.hutool.core.util.StrUtil;
import com.redant.cluster.node.Node;
import com.redant.cluster.zk.ZkClient;
import com.redant.cluster.zk.ZkNode;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package com.redant.cluster.service.register;
/**
* @author houyi.wh
* @date 2017/11/21
**/
public class ZkServiceRegister implements ServiceRegister {
private static final Logger LOGGER = LoggerFactory.getLogger(ZkServiceRegister.class);
private CuratorFramework client;
private static ZkServiceRegister register;
private ZkServiceRegister(){
}
private ZkServiceRegister(String zkAddress){ | client = ZkClient.getClient(zkAddress); |
all4you/redant | redant-cluster/src/main/java/com/redant/cluster/service/register/ZkServiceRegister.java | // Path: redant-cluster/src/main/java/com/redant/cluster/node/Node.java
// public class Node {
//
// private static final String DEFAULT_HOST = GenericsUtil.getLocalIpV4();
//
// private static final int DEFAULT_PORT = 8088;
//
// public static final Node DEFAULT_PORT_NODE = new Node(DEFAULT_HOST,DEFAULT_PORT);
//
// private String id;
//
// private String host;
//
// private int port;
//
// public Node(int port){
// this(DEFAULT_HOST,port);
// }
//
// public Node(String host, int port){
// this(SecureUtil.md5(host+"&"+port),host,port);
// }
//
// public Node(String id, String host, int port){
// this.id = id;
// this.host = host;
// this.port = port;
// }
//
// public static Node getNodeWithArgs(String[] args){
// Node node = Node.DEFAULT_PORT_NODE;
// if(args.length>1 && NumberUtil.isInteger(args[1])){
// node = new Node(Integer.parseInt(args[1]));
// }
// return node;
// }
//
// /**
// * 从JsonObject中解析出SlaveNode
// * @param object 对象
// * @return 节点
// */
// public static Node parse(JSONObject object){
// if(object==null){
// return null;
// }
// String host = object.getString("host");
// int port = object.getIntValue("port");
// String id = object.getString("id");
// return new Node(id,host,port);
// }
//
// public String getHost() {
// return host;
// }
//
// public void setHost(String host) {
// this.host = host;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// public String getId(){
// return id;
// }
//
// @Override
// public String toString() {
// return JSON.toJSONString(this);
// }
//
// }
//
// Path: redant-cluster/src/main/java/com/redant/cluster/zk/ZkClient.java
// public class ZkClient {
//
// /**
// * 节点的session超时时间,当Slave服务停掉后,
// * curator客户端需要等待该节点超时后才会触发CHILD_REMOVED事件
// */
// private static final int DEFAULT_SESSION_TIMEOUT_MS = 5000;
//
// private static final int DEFAULT_CONNECTION_TIMEOUT_MS = 15000;
//
// /**
// * 操作ZK的客户端
// */
// private static Map<String,CuratorFramework> clients;
//
// private static Lock lock;
//
// static{
// clients = new ConcurrentHashMap<>();
// lock = new ReentrantLock();
// }
//
// /**
// * 获取ZK客户端
// * @param zkAddress zk服务端地址
// * @return zk客户端
// */
// public static CuratorFramework getClient(String zkAddress){
// if(zkAddress == null || zkAddress.trim().length() == 0){
// return null;
// }
// CuratorFramework client = clients.get(zkAddress);
// if(client==null){
// lock.lock();
// try {
// if(!clients.containsKey(zkAddress)) {
// client = CuratorFrameworkFactory.newClient(
// zkAddress,
// DEFAULT_SESSION_TIMEOUT_MS,
// DEFAULT_CONNECTION_TIMEOUT_MS,
// new RetryNTimes(10, 5000)
// );
// client.start();
// clients.putIfAbsent(zkAddress,client);
// }else{
// client = clients.get(zkAddress);
// }
// }finally {
// lock.unlock();
// }
// }
// return client;
// }
//
// }
//
// Path: redant-cluster/src/main/java/com/redant/cluster/zk/ZkNode.java
// public class ZkNode {
//
// /**
// * 根节点
// */
// public static final String ROOT_NODE_PATH = "/redant";
//
// /**
// * SlaveNode注册的节点
// */
// public static final String SLAVE_NODE_PATH = ROOT_NODE_PATH+"/slave";
//
//
//
// }
| import cn.hutool.core.util.StrUtil;
import com.redant.cluster.node.Node;
import com.redant.cluster.zk.ZkClient;
import com.redant.cluster.zk.ZkNode;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package com.redant.cluster.service.register;
/**
* @author houyi.wh
* @date 2017/11/21
**/
public class ZkServiceRegister implements ServiceRegister {
private static final Logger LOGGER = LoggerFactory.getLogger(ZkServiceRegister.class);
private CuratorFramework client;
private static ZkServiceRegister register;
private ZkServiceRegister(){
}
private ZkServiceRegister(String zkAddress){
client = ZkClient.getClient(zkAddress);
}
public static ServiceRegister getInstance(String zkAddress){
if(register==null) {
synchronized (ZkServiceRegister.class) {
if(register==null) {
register = new ZkServiceRegister(zkAddress);
}
}
}
return register;
}
@Override | // Path: redant-cluster/src/main/java/com/redant/cluster/node/Node.java
// public class Node {
//
// private static final String DEFAULT_HOST = GenericsUtil.getLocalIpV4();
//
// private static final int DEFAULT_PORT = 8088;
//
// public static final Node DEFAULT_PORT_NODE = new Node(DEFAULT_HOST,DEFAULT_PORT);
//
// private String id;
//
// private String host;
//
// private int port;
//
// public Node(int port){
// this(DEFAULT_HOST,port);
// }
//
// public Node(String host, int port){
// this(SecureUtil.md5(host+"&"+port),host,port);
// }
//
// public Node(String id, String host, int port){
// this.id = id;
// this.host = host;
// this.port = port;
// }
//
// public static Node getNodeWithArgs(String[] args){
// Node node = Node.DEFAULT_PORT_NODE;
// if(args.length>1 && NumberUtil.isInteger(args[1])){
// node = new Node(Integer.parseInt(args[1]));
// }
// return node;
// }
//
// /**
// * 从JsonObject中解析出SlaveNode
// * @param object 对象
// * @return 节点
// */
// public static Node parse(JSONObject object){
// if(object==null){
// return null;
// }
// String host = object.getString("host");
// int port = object.getIntValue("port");
// String id = object.getString("id");
// return new Node(id,host,port);
// }
//
// public String getHost() {
// return host;
// }
//
// public void setHost(String host) {
// this.host = host;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// public String getId(){
// return id;
// }
//
// @Override
// public String toString() {
// return JSON.toJSONString(this);
// }
//
// }
//
// Path: redant-cluster/src/main/java/com/redant/cluster/zk/ZkClient.java
// public class ZkClient {
//
// /**
// * 节点的session超时时间,当Slave服务停掉后,
// * curator客户端需要等待该节点超时后才会触发CHILD_REMOVED事件
// */
// private static final int DEFAULT_SESSION_TIMEOUT_MS = 5000;
//
// private static final int DEFAULT_CONNECTION_TIMEOUT_MS = 15000;
//
// /**
// * 操作ZK的客户端
// */
// private static Map<String,CuratorFramework> clients;
//
// private static Lock lock;
//
// static{
// clients = new ConcurrentHashMap<>();
// lock = new ReentrantLock();
// }
//
// /**
// * 获取ZK客户端
// * @param zkAddress zk服务端地址
// * @return zk客户端
// */
// public static CuratorFramework getClient(String zkAddress){
// if(zkAddress == null || zkAddress.trim().length() == 0){
// return null;
// }
// CuratorFramework client = clients.get(zkAddress);
// if(client==null){
// lock.lock();
// try {
// if(!clients.containsKey(zkAddress)) {
// client = CuratorFrameworkFactory.newClient(
// zkAddress,
// DEFAULT_SESSION_TIMEOUT_MS,
// DEFAULT_CONNECTION_TIMEOUT_MS,
// new RetryNTimes(10, 5000)
// );
// client.start();
// clients.putIfAbsent(zkAddress,client);
// }else{
// client = clients.get(zkAddress);
// }
// }finally {
// lock.unlock();
// }
// }
// return client;
// }
//
// }
//
// Path: redant-cluster/src/main/java/com/redant/cluster/zk/ZkNode.java
// public class ZkNode {
//
// /**
// * 根节点
// */
// public static final String ROOT_NODE_PATH = "/redant";
//
// /**
// * SlaveNode注册的节点
// */
// public static final String SLAVE_NODE_PATH = ROOT_NODE_PATH+"/slave";
//
//
//
// }
// Path: redant-cluster/src/main/java/com/redant/cluster/service/register/ZkServiceRegister.java
import cn.hutool.core.util.StrUtil;
import com.redant.cluster.node.Node;
import com.redant.cluster.zk.ZkClient;
import com.redant.cluster.zk.ZkNode;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package com.redant.cluster.service.register;
/**
* @author houyi.wh
* @date 2017/11/21
**/
public class ZkServiceRegister implements ServiceRegister {
private static final Logger LOGGER = LoggerFactory.getLogger(ZkServiceRegister.class);
private CuratorFramework client;
private static ZkServiceRegister register;
private ZkServiceRegister(){
}
private ZkServiceRegister(String zkAddress){
client = ZkClient.getClient(zkAddress);
}
public static ServiceRegister getInstance(String zkAddress){
if(register==null) {
synchronized (ZkServiceRegister.class) {
if(register==null) {
register = new ZkServiceRegister(zkAddress);
}
}
}
return register;
}
@Override | public void register(Node node) { |
all4you/redant | redant-cluster/src/main/java/com/redant/cluster/service/register/ZkServiceRegister.java | // Path: redant-cluster/src/main/java/com/redant/cluster/node/Node.java
// public class Node {
//
// private static final String DEFAULT_HOST = GenericsUtil.getLocalIpV4();
//
// private static final int DEFAULT_PORT = 8088;
//
// public static final Node DEFAULT_PORT_NODE = new Node(DEFAULT_HOST,DEFAULT_PORT);
//
// private String id;
//
// private String host;
//
// private int port;
//
// public Node(int port){
// this(DEFAULT_HOST,port);
// }
//
// public Node(String host, int port){
// this(SecureUtil.md5(host+"&"+port),host,port);
// }
//
// public Node(String id, String host, int port){
// this.id = id;
// this.host = host;
// this.port = port;
// }
//
// public static Node getNodeWithArgs(String[] args){
// Node node = Node.DEFAULT_PORT_NODE;
// if(args.length>1 && NumberUtil.isInteger(args[1])){
// node = new Node(Integer.parseInt(args[1]));
// }
// return node;
// }
//
// /**
// * 从JsonObject中解析出SlaveNode
// * @param object 对象
// * @return 节点
// */
// public static Node parse(JSONObject object){
// if(object==null){
// return null;
// }
// String host = object.getString("host");
// int port = object.getIntValue("port");
// String id = object.getString("id");
// return new Node(id,host,port);
// }
//
// public String getHost() {
// return host;
// }
//
// public void setHost(String host) {
// this.host = host;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// public String getId(){
// return id;
// }
//
// @Override
// public String toString() {
// return JSON.toJSONString(this);
// }
//
// }
//
// Path: redant-cluster/src/main/java/com/redant/cluster/zk/ZkClient.java
// public class ZkClient {
//
// /**
// * 节点的session超时时间,当Slave服务停掉后,
// * curator客户端需要等待该节点超时后才会触发CHILD_REMOVED事件
// */
// private static final int DEFAULT_SESSION_TIMEOUT_MS = 5000;
//
// private static final int DEFAULT_CONNECTION_TIMEOUT_MS = 15000;
//
// /**
// * 操作ZK的客户端
// */
// private static Map<String,CuratorFramework> clients;
//
// private static Lock lock;
//
// static{
// clients = new ConcurrentHashMap<>();
// lock = new ReentrantLock();
// }
//
// /**
// * 获取ZK客户端
// * @param zkAddress zk服务端地址
// * @return zk客户端
// */
// public static CuratorFramework getClient(String zkAddress){
// if(zkAddress == null || zkAddress.trim().length() == 0){
// return null;
// }
// CuratorFramework client = clients.get(zkAddress);
// if(client==null){
// lock.lock();
// try {
// if(!clients.containsKey(zkAddress)) {
// client = CuratorFrameworkFactory.newClient(
// zkAddress,
// DEFAULT_SESSION_TIMEOUT_MS,
// DEFAULT_CONNECTION_TIMEOUT_MS,
// new RetryNTimes(10, 5000)
// );
// client.start();
// clients.putIfAbsent(zkAddress,client);
// }else{
// client = clients.get(zkAddress);
// }
// }finally {
// lock.unlock();
// }
// }
// return client;
// }
//
// }
//
// Path: redant-cluster/src/main/java/com/redant/cluster/zk/ZkNode.java
// public class ZkNode {
//
// /**
// * 根节点
// */
// public static final String ROOT_NODE_PATH = "/redant";
//
// /**
// * SlaveNode注册的节点
// */
// public static final String SLAVE_NODE_PATH = ROOT_NODE_PATH+"/slave";
//
//
//
// }
| import cn.hutool.core.util.StrUtil;
import com.redant.cluster.node.Node;
import com.redant.cluster.zk.ZkClient;
import com.redant.cluster.zk.ZkNode;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package com.redant.cluster.service.register;
/**
* @author houyi.wh
* @date 2017/11/21
**/
public class ZkServiceRegister implements ServiceRegister {
private static final Logger LOGGER = LoggerFactory.getLogger(ZkServiceRegister.class);
private CuratorFramework client;
private static ZkServiceRegister register;
private ZkServiceRegister(){
}
private ZkServiceRegister(String zkAddress){
client = ZkClient.getClient(zkAddress);
}
public static ServiceRegister getInstance(String zkAddress){
if(register==null) {
synchronized (ZkServiceRegister.class) {
if(register==null) {
register = new ZkServiceRegister(zkAddress);
}
}
}
return register;
}
@Override
public void register(Node node) {
if(client==null || node ==null){
throw new IllegalArgumentException(String.format("param illegal with client={%s},slave={%s}",client==null?null:client.toString(), node ==null?null: node.toString()));
}
try { | // Path: redant-cluster/src/main/java/com/redant/cluster/node/Node.java
// public class Node {
//
// private static final String DEFAULT_HOST = GenericsUtil.getLocalIpV4();
//
// private static final int DEFAULT_PORT = 8088;
//
// public static final Node DEFAULT_PORT_NODE = new Node(DEFAULT_HOST,DEFAULT_PORT);
//
// private String id;
//
// private String host;
//
// private int port;
//
// public Node(int port){
// this(DEFAULT_HOST,port);
// }
//
// public Node(String host, int port){
// this(SecureUtil.md5(host+"&"+port),host,port);
// }
//
// public Node(String id, String host, int port){
// this.id = id;
// this.host = host;
// this.port = port;
// }
//
// public static Node getNodeWithArgs(String[] args){
// Node node = Node.DEFAULT_PORT_NODE;
// if(args.length>1 && NumberUtil.isInteger(args[1])){
// node = new Node(Integer.parseInt(args[1]));
// }
// return node;
// }
//
// /**
// * 从JsonObject中解析出SlaveNode
// * @param object 对象
// * @return 节点
// */
// public static Node parse(JSONObject object){
// if(object==null){
// return null;
// }
// String host = object.getString("host");
// int port = object.getIntValue("port");
// String id = object.getString("id");
// return new Node(id,host,port);
// }
//
// public String getHost() {
// return host;
// }
//
// public void setHost(String host) {
// this.host = host;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
// public String getId(){
// return id;
// }
//
// @Override
// public String toString() {
// return JSON.toJSONString(this);
// }
//
// }
//
// Path: redant-cluster/src/main/java/com/redant/cluster/zk/ZkClient.java
// public class ZkClient {
//
// /**
// * 节点的session超时时间,当Slave服务停掉后,
// * curator客户端需要等待该节点超时后才会触发CHILD_REMOVED事件
// */
// private static final int DEFAULT_SESSION_TIMEOUT_MS = 5000;
//
// private static final int DEFAULT_CONNECTION_TIMEOUT_MS = 15000;
//
// /**
// * 操作ZK的客户端
// */
// private static Map<String,CuratorFramework> clients;
//
// private static Lock lock;
//
// static{
// clients = new ConcurrentHashMap<>();
// lock = new ReentrantLock();
// }
//
// /**
// * 获取ZK客户端
// * @param zkAddress zk服务端地址
// * @return zk客户端
// */
// public static CuratorFramework getClient(String zkAddress){
// if(zkAddress == null || zkAddress.trim().length() == 0){
// return null;
// }
// CuratorFramework client = clients.get(zkAddress);
// if(client==null){
// lock.lock();
// try {
// if(!clients.containsKey(zkAddress)) {
// client = CuratorFrameworkFactory.newClient(
// zkAddress,
// DEFAULT_SESSION_TIMEOUT_MS,
// DEFAULT_CONNECTION_TIMEOUT_MS,
// new RetryNTimes(10, 5000)
// );
// client.start();
// clients.putIfAbsent(zkAddress,client);
// }else{
// client = clients.get(zkAddress);
// }
// }finally {
// lock.unlock();
// }
// }
// return client;
// }
//
// }
//
// Path: redant-cluster/src/main/java/com/redant/cluster/zk/ZkNode.java
// public class ZkNode {
//
// /**
// * 根节点
// */
// public static final String ROOT_NODE_PATH = "/redant";
//
// /**
// * SlaveNode注册的节点
// */
// public static final String SLAVE_NODE_PATH = ROOT_NODE_PATH+"/slave";
//
//
//
// }
// Path: redant-cluster/src/main/java/com/redant/cluster/service/register/ZkServiceRegister.java
import cn.hutool.core.util.StrUtil;
import com.redant.cluster.node.Node;
import com.redant.cluster.zk.ZkClient;
import com.redant.cluster.zk.ZkNode;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package com.redant.cluster.service.register;
/**
* @author houyi.wh
* @date 2017/11/21
**/
public class ZkServiceRegister implements ServiceRegister {
private static final Logger LOGGER = LoggerFactory.getLogger(ZkServiceRegister.class);
private CuratorFramework client;
private static ZkServiceRegister register;
private ZkServiceRegister(){
}
private ZkServiceRegister(String zkAddress){
client = ZkClient.getClient(zkAddress);
}
public static ServiceRegister getInstance(String zkAddress){
if(register==null) {
synchronized (ZkServiceRegister.class) {
if(register==null) {
register = new ZkServiceRegister(zkAddress);
}
}
}
return register;
}
@Override
public void register(Node node) {
if(client==null || node ==null){
throw new IllegalArgumentException(String.format("param illegal with client={%s},slave={%s}",client==null?null:client.toString(), node ==null?null: node.toString()));
}
try { | if(client.checkExists().forPath(ZkNode.SLAVE_NODE_PATH)==null) { |
all4you/redant | redant-core/src/main/java/com/redant/core/controller/annotation/Mapping.java | // Path: redant-core/src/main/java/com/redant/core/common/enums/RequestMethod.java
// public enum RequestMethod {
// /**
// * GET
// */
// GET(HttpMethod.GET),
// /**
// * HEAD
// */
// HEAD(HttpMethod.HEAD),
// /**
// * POST
// */
// POST(HttpMethod.POST),
// /**
// * PUT
// */
// PUT(HttpMethod.PUT),
// /**
// * PATCH
// */
// PATCH(HttpMethod.PATCH),
// /**
// * DELETE
// */
// DELETE(HttpMethod.DELETE),
// /**
// * OPTIONS
// */
// OPTIONS(HttpMethod.OPTIONS),
// /**
// * TRACE
// */
// TRACE(HttpMethod.TRACE);
//
// HttpMethod httpMethod;
//
// RequestMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public static HttpMethod getHttpMethod(RequestMethod requestMethod){
// for(RequestMethod method : values()){
// if(requestMethod==method){
// return method.httpMethod;
// }
// }
// return null;
// }
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/render/RenderType.java
// public enum RenderType {
//
// /**
// * JSON
// */
// JSON("application/json;charset=UTF-8"),
// /**
// * XML
// */
// XML("text/xml;charset=UTF-8"),
// /**
// * TEXT
// */
// TEXT("text/plain;charset=UTF-8"),
// /**
// * HTML
// */
// HTML("text/html;charset=UTF-8");
//
// private String contentType;
//
// RenderType(String contentType){
// this.contentType = contentType;
// }
//
// public String getContentType() {
// return contentType;
// }
// }
| import com.redant.core.common.enums.RequestMethod;
import com.redant.core.render.RenderType;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; | package com.redant.core.controller.annotation;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Mapping {
/**
* 请求方法类型
* @return 方法类型
*/ | // Path: redant-core/src/main/java/com/redant/core/common/enums/RequestMethod.java
// public enum RequestMethod {
// /**
// * GET
// */
// GET(HttpMethod.GET),
// /**
// * HEAD
// */
// HEAD(HttpMethod.HEAD),
// /**
// * POST
// */
// POST(HttpMethod.POST),
// /**
// * PUT
// */
// PUT(HttpMethod.PUT),
// /**
// * PATCH
// */
// PATCH(HttpMethod.PATCH),
// /**
// * DELETE
// */
// DELETE(HttpMethod.DELETE),
// /**
// * OPTIONS
// */
// OPTIONS(HttpMethod.OPTIONS),
// /**
// * TRACE
// */
// TRACE(HttpMethod.TRACE);
//
// HttpMethod httpMethod;
//
// RequestMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public static HttpMethod getHttpMethod(RequestMethod requestMethod){
// for(RequestMethod method : values()){
// if(requestMethod==method){
// return method.httpMethod;
// }
// }
// return null;
// }
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/render/RenderType.java
// public enum RenderType {
//
// /**
// * JSON
// */
// JSON("application/json;charset=UTF-8"),
// /**
// * XML
// */
// XML("text/xml;charset=UTF-8"),
// /**
// * TEXT
// */
// TEXT("text/plain;charset=UTF-8"),
// /**
// * HTML
// */
// HTML("text/html;charset=UTF-8");
//
// private String contentType;
//
// RenderType(String contentType){
// this.contentType = contentType;
// }
//
// public String getContentType() {
// return contentType;
// }
// }
// Path: redant-core/src/main/java/com/redant/core/controller/annotation/Mapping.java
import com.redant.core.common.enums.RequestMethod;
import com.redant.core.render.RenderType;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
package com.redant.core.controller.annotation;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Mapping {
/**
* 请求方法类型
* @return 方法类型
*/ | RequestMethod requestMethod() default RequestMethod.GET; |
all4you/redant | redant-core/src/main/java/com/redant/core/controller/annotation/Mapping.java | // Path: redant-core/src/main/java/com/redant/core/common/enums/RequestMethod.java
// public enum RequestMethod {
// /**
// * GET
// */
// GET(HttpMethod.GET),
// /**
// * HEAD
// */
// HEAD(HttpMethod.HEAD),
// /**
// * POST
// */
// POST(HttpMethod.POST),
// /**
// * PUT
// */
// PUT(HttpMethod.PUT),
// /**
// * PATCH
// */
// PATCH(HttpMethod.PATCH),
// /**
// * DELETE
// */
// DELETE(HttpMethod.DELETE),
// /**
// * OPTIONS
// */
// OPTIONS(HttpMethod.OPTIONS),
// /**
// * TRACE
// */
// TRACE(HttpMethod.TRACE);
//
// HttpMethod httpMethod;
//
// RequestMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public static HttpMethod getHttpMethod(RequestMethod requestMethod){
// for(RequestMethod method : values()){
// if(requestMethod==method){
// return method.httpMethod;
// }
// }
// return null;
// }
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/render/RenderType.java
// public enum RenderType {
//
// /**
// * JSON
// */
// JSON("application/json;charset=UTF-8"),
// /**
// * XML
// */
// XML("text/xml;charset=UTF-8"),
// /**
// * TEXT
// */
// TEXT("text/plain;charset=UTF-8"),
// /**
// * HTML
// */
// HTML("text/html;charset=UTF-8");
//
// private String contentType;
//
// RenderType(String contentType){
// this.contentType = contentType;
// }
//
// public String getContentType() {
// return contentType;
// }
// }
| import com.redant.core.common.enums.RequestMethod;
import com.redant.core.render.RenderType;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; | package com.redant.core.controller.annotation;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Mapping {
/**
* 请求方法类型
* @return 方法类型
*/
RequestMethod requestMethod() default RequestMethod.GET;
/**
* 请求的uri
* @return url
*/
String path() default "";
/**
* 返回类型
* @return 返回类型
*/ | // Path: redant-core/src/main/java/com/redant/core/common/enums/RequestMethod.java
// public enum RequestMethod {
// /**
// * GET
// */
// GET(HttpMethod.GET),
// /**
// * HEAD
// */
// HEAD(HttpMethod.HEAD),
// /**
// * POST
// */
// POST(HttpMethod.POST),
// /**
// * PUT
// */
// PUT(HttpMethod.PUT),
// /**
// * PATCH
// */
// PATCH(HttpMethod.PATCH),
// /**
// * DELETE
// */
// DELETE(HttpMethod.DELETE),
// /**
// * OPTIONS
// */
// OPTIONS(HttpMethod.OPTIONS),
// /**
// * TRACE
// */
// TRACE(HttpMethod.TRACE);
//
// HttpMethod httpMethod;
//
// RequestMethod(HttpMethod httpMethod) {
// this.httpMethod = httpMethod;
// }
//
// public static HttpMethod getHttpMethod(RequestMethod requestMethod){
// for(RequestMethod method : values()){
// if(requestMethod==method){
// return method.httpMethod;
// }
// }
// return null;
// }
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/render/RenderType.java
// public enum RenderType {
//
// /**
// * JSON
// */
// JSON("application/json;charset=UTF-8"),
// /**
// * XML
// */
// XML("text/xml;charset=UTF-8"),
// /**
// * TEXT
// */
// TEXT("text/plain;charset=UTF-8"),
// /**
// * HTML
// */
// HTML("text/html;charset=UTF-8");
//
// private String contentType;
//
// RenderType(String contentType){
// this.contentType = contentType;
// }
//
// public String getContentType() {
// return contentType;
// }
// }
// Path: redant-core/src/main/java/com/redant/core/controller/annotation/Mapping.java
import com.redant.core.common.enums.RequestMethod;
import com.redant.core.render.RenderType;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
package com.redant.core.controller.annotation;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Mapping {
/**
* 请求方法类型
* @return 方法类型
*/
RequestMethod requestMethod() default RequestMethod.GET;
/**
* 请求的uri
* @return url
*/
String path() default "";
/**
* 返回类型
* @return 返回类型
*/ | RenderType renderType() default RenderType.JSON; |
all4you/redant | redant-example/src/main/java/com/redant/example/interceptor/CustomInterceptorBuilder.java | // Path: redant-core/src/main/java/com/redant/core/interceptor/Interceptor.java
// public abstract class Interceptor {
//
// /**
// * 拦截器的前置处理方法
// */
// public boolean preHandle(Map<String, List<String>> paramMap){
// return true;
// }
//
// /**
// * 拦截器的后置处理方法
// */
// public abstract void postHandle(Map<String, List<String>> paramMap);
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/interceptor/InterceptorBuilder.java
// public interface InterceptorBuilder {
//
// /**
// * 构造拦截器列表
// * @return 列表
// */
// List<Interceptor> build();
//
// }
| import com.redant.core.interceptor.Interceptor;
import com.redant.core.interceptor.InterceptorBuilder;
import java.util.ArrayList;
import java.util.List; | package com.redant.example.interceptor;
/**
* @author houyi
**/
public class CustomInterceptorBuilder implements InterceptorBuilder {
private volatile boolean loaded = false;
| // Path: redant-core/src/main/java/com/redant/core/interceptor/Interceptor.java
// public abstract class Interceptor {
//
// /**
// * 拦截器的前置处理方法
// */
// public boolean preHandle(Map<String, List<String>> paramMap){
// return true;
// }
//
// /**
// * 拦截器的后置处理方法
// */
// public abstract void postHandle(Map<String, List<String>> paramMap);
//
// }
//
// Path: redant-core/src/main/java/com/redant/core/interceptor/InterceptorBuilder.java
// public interface InterceptorBuilder {
//
// /**
// * 构造拦截器列表
// * @return 列表
// */
// List<Interceptor> build();
//
// }
// Path: redant-example/src/main/java/com/redant/example/interceptor/CustomInterceptorBuilder.java
import com.redant.core.interceptor.Interceptor;
import com.redant.core.interceptor.InterceptorBuilder;
import java.util.ArrayList;
import java.util.List;
package com.redant.example.interceptor;
/**
* @author houyi
**/
public class CustomInterceptorBuilder implements InterceptorBuilder {
private volatile boolean loaded = false;
| private List<Interceptor> interceptors = null; |
all4you/redant | redant-core/src/main/java/com/redant/core/cookie/DefaultCookieManager.java | // Path: redant-core/src/main/java/com/redant/core/context/RedantContext.java
// public class RedantContext {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(RedantContext.class);
//
// /**
// * 使用FastThreadLocal替代JDK自带的ThreadLocal以提升并发性能
// */
// private static final FastThreadLocal<RedantContext> CONTEXT_HOLDER = new FastThreadLocal<>();
//
// private HttpRequest request;
//
// private ChannelHandlerContext context;
//
// private HttpResponse response;
//
// private Set<Cookie> cookies;
//
// private RedantContext(){
//
// }
//
// public RedantContext setRequest(HttpRequest request){
// this.request = request;
// return this;
// }
//
// public RedantContext setContext(ChannelHandlerContext context){
// this.context = context;
// return this;
// }
//
// public RedantContext setResponse(HttpResponse response){
// this.response = response;
// return this;
// }
//
// public RedantContext addCookie(Cookie cookie){
// if(cookie!=null){
// if(CollectionUtil.isEmpty(cookies)){
// cookies = new HashSet<>();
// }
// cookies.add(cookie);
// }
// return this;
// }
//
// public RedantContext addCookies(Set<Cookie> cookieSet){
// if(CollectionUtil.isNotEmpty(cookieSet)){
// if(CollectionUtil.isEmpty(cookies)){
// cookies = new HashSet<>();
// }
// cookies.addAll(cookieSet);
// }
// return this;
// }
//
// public HttpRequest getRequest() {
// return request;
// }
//
// public ChannelHandlerContext getContext() {
// return context;
// }
//
// public HttpResponse getResponse() {
// return response;
// }
//
// public Set<Cookie> getCookies() {
// return cookies;
// }
//
// public static RedantContext currentContext(){
// RedantContext context = CONTEXT_HOLDER.get();
// if(context==null){
// context = new RedantContext();
// CONTEXT_HOLDER.set(context);
// }
// return context;
// }
//
// public static void clear(){
// CONTEXT_HOLDER.remove();
// }
//
//
// }
| import cn.hutool.core.util.StrUtil;
import com.redant.core.context.RedantContext;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.cookie.Cookie;
import io.netty.handler.codec.http.cookie.DefaultCookie;
import io.netty.handler.codec.http.cookie.ServerCookieDecoder;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set; | package com.redant.core.cookie;
/**
* Cookie管理器
*
* @author houyi.wh
* @date 2019-01-16
*/
public class DefaultCookieManager implements CookieManager {
private static final class DefaultCookieManagerHolder {
private static DefaultCookieManager cookieManager = new DefaultCookieManager();
}
private DefaultCookieManager() {
}
public static CookieManager getInstance() {
return DefaultCookieManagerHolder.cookieManager;
}
@Override
public Set<Cookie> getCookies() { | // Path: redant-core/src/main/java/com/redant/core/context/RedantContext.java
// public class RedantContext {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(RedantContext.class);
//
// /**
// * 使用FastThreadLocal替代JDK自带的ThreadLocal以提升并发性能
// */
// private static final FastThreadLocal<RedantContext> CONTEXT_HOLDER = new FastThreadLocal<>();
//
// private HttpRequest request;
//
// private ChannelHandlerContext context;
//
// private HttpResponse response;
//
// private Set<Cookie> cookies;
//
// private RedantContext(){
//
// }
//
// public RedantContext setRequest(HttpRequest request){
// this.request = request;
// return this;
// }
//
// public RedantContext setContext(ChannelHandlerContext context){
// this.context = context;
// return this;
// }
//
// public RedantContext setResponse(HttpResponse response){
// this.response = response;
// return this;
// }
//
// public RedantContext addCookie(Cookie cookie){
// if(cookie!=null){
// if(CollectionUtil.isEmpty(cookies)){
// cookies = new HashSet<>();
// }
// cookies.add(cookie);
// }
// return this;
// }
//
// public RedantContext addCookies(Set<Cookie> cookieSet){
// if(CollectionUtil.isNotEmpty(cookieSet)){
// if(CollectionUtil.isEmpty(cookies)){
// cookies = new HashSet<>();
// }
// cookies.addAll(cookieSet);
// }
// return this;
// }
//
// public HttpRequest getRequest() {
// return request;
// }
//
// public ChannelHandlerContext getContext() {
// return context;
// }
//
// public HttpResponse getResponse() {
// return response;
// }
//
// public Set<Cookie> getCookies() {
// return cookies;
// }
//
// public static RedantContext currentContext(){
// RedantContext context = CONTEXT_HOLDER.get();
// if(context==null){
// context = new RedantContext();
// CONTEXT_HOLDER.set(context);
// }
// return context;
// }
//
// public static void clear(){
// CONTEXT_HOLDER.remove();
// }
//
//
// }
// Path: redant-core/src/main/java/com/redant/core/cookie/DefaultCookieManager.java
import cn.hutool.core.util.StrUtil;
import com.redant.core.context.RedantContext;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.cookie.Cookie;
import io.netty.handler.codec.http.cookie.DefaultCookie;
import io.netty.handler.codec.http.cookie.ServerCookieDecoder;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
package com.redant.core.cookie;
/**
* Cookie管理器
*
* @author houyi.wh
* @date 2019-01-16
*/
public class DefaultCookieManager implements CookieManager {
private static final class DefaultCookieManagerHolder {
private static DefaultCookieManager cookieManager = new DefaultCookieManager();
}
private DefaultCookieManager() {
}
public static CookieManager getInstance() {
return DefaultCookieManagerHolder.cookieManager;
}
@Override
public Set<Cookie> getCookies() { | HttpRequest request = RedantContext.currentContext().getRequest(); |
all4you/redant | redant-core/src/main/java/com/redant/core/common/html/DefaultHtmlMaker.java | // Path: redant-core/src/main/java/com/redant/core/common/view/HtmlKeyHolder.java
// public interface HtmlKeyHolder {
//
// /**
// * 未转义
// */
// String START_NO_ESCAPE = "#[";
//
// /**
// * 对[转义
// */
// String START_ESCAPE = "#\\[";
//
// String END = "]";
//
// }
| import cn.hutool.core.collection.CollectionUtil;
import com.redant.core.common.view.HtmlKeyHolder;
import java.util.Map; | package com.redant.core.common.html;
/**
* 默认的HtmlMaker,只处理字符串
* @author houyi.wh
* @date 2017/12/1
**/
public class DefaultHtmlMaker implements HtmlMaker {
@Override
public String make(String htmlTemplate, Map<String, Object> contentMap) {
String html = htmlTemplate;
if(CollectionUtil.isNotEmpty(contentMap)){
for(Map.Entry<String,Object> entry : contentMap.entrySet()){
String key = entry.getKey();
Object val = entry.getValue();
if(val instanceof String){ | // Path: redant-core/src/main/java/com/redant/core/common/view/HtmlKeyHolder.java
// public interface HtmlKeyHolder {
//
// /**
// * 未转义
// */
// String START_NO_ESCAPE = "#[";
//
// /**
// * 对[转义
// */
// String START_ESCAPE = "#\\[";
//
// String END = "]";
//
// }
// Path: redant-core/src/main/java/com/redant/core/common/html/DefaultHtmlMaker.java
import cn.hutool.core.collection.CollectionUtil;
import com.redant.core.common.view.HtmlKeyHolder;
import java.util.Map;
package com.redant.core.common.html;
/**
* 默认的HtmlMaker,只处理字符串
* @author houyi.wh
* @date 2017/12/1
**/
public class DefaultHtmlMaker implements HtmlMaker {
@Override
public String make(String htmlTemplate, Map<String, Object> contentMap) {
String html = htmlTemplate;
if(CollectionUtil.isNotEmpty(contentMap)){
for(Map.Entry<String,Object> entry : contentMap.entrySet()){
String key = entry.getKey();
Object val = entry.getValue();
if(val instanceof String){ | html = html.replaceAll(HtmlKeyHolder.START_ESCAPE+key+HtmlKeyHolder.END,val.toString()); |
steevp/UpdogFarmer | app/src/test/java/com/steevsapps/idledaddy/UtilsTest.java | // Path: app/src/main/java/com/steevsapps/idledaddy/utils/Utils.java
// public class Utils {
// private final static String SHA1_ALGORITHM = "SHA-1";
// private final static String HMAC_SHA1_ALGORITHM = "HmacSHA1";
//
// /**
// * Convert byte array to hex string
// * https://stackoverflow.com/a/9855338
// */
// public static String bytesToHex(byte[] bytes) {
// final char[] hexArray = "0123456789ABCDEF".toCharArray();
//
// char[] hexChars = new char[bytes.length * 2];
// for ( int j = 0; j < bytes.length; j++ ) {
// int v = bytes[j] & 0xFF;
// hexChars[j * 2] = hexArray[v >>> 4];
// hexChars[j * 2 + 1] = hexArray[v & 0x0F];
// }
// return new String(hexChars);
// }
//
// /**
// * Convert ArrayList to comma-separated String
// */
// public static String arrayToString(List<String> list) {
// final StringBuilder builder = new StringBuilder();
// for (int i=0,size=list.size();i<size;i++) {
// final String string = list.get(i);
// builder.append(string);
// if (i + 1 < size) {
// builder.append(",");
// }
// }
// return builder.toString();
// }
//
// /**
// * Convert array to comma-separated String
// */
// public static String arrayToString(String[] array) {
// return arrayToString(Arrays.asList(array));
// }
//
// /**
// * Save Logcat to file
// */
// public static void saveLogcat(File file) throws IOException {
// final Process p = Runtime.getRuntime().exec("logcat -d");
// try ( final BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
// final BufferedWriter bw = new BufferedWriter(new FileWriter(file)) ) {
// String line;
// while ((line = br.readLine()) != null) {
// bw.write(line);
// bw.write("\n");
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// /**
// * Strips non-ASCII characters from String
// */
// public static String removeSpecialChars(String s) {
// return s.replaceAll("[^\\u0000-\\u007F]", "");
// }
//
// /**
// * Check if API key is valid
// */
// public static boolean isValidKey(String key) {
// return key.matches("^[0-9A-Fa-f]+$");
// }
//
// /**
// * Calculate the SHA-1 hash of a file
// */
// public static byte[] calculateSHA1(File file) throws IOException, NoSuchAlgorithmException {
// try (final InputStream fis = new FileInputStream(file)) {
// final MessageDigest md = MessageDigest.getInstance(SHA1_ALGORITHM);
// final byte[] buffer = new byte[8192];
// int n;
// while ((n = fis.read(buffer)) != -1) {
// md.update(buffer, 0, n);
// }
// return md.digest();
// }
// }
//
// /**
// * Get the current unix time
// */
// public static long getCurrentUnixTime() {
// return System.currentTimeMillis() / 1000L;
// }
//
// /**
// * Calculate HMAC SHA1
// */
// public static byte[] calculateRFC2104HMAC(byte[] data, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException {
// final SecretKeySpec secretKey = new SecretKeySpec(key, HMAC_SHA1_ALGORITHM);
// final Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
// mac.init(secretKey);
// return mac.doFinal(data);
// }
//
// /**
// * Run a block of code a maximum of maxTries
// */
// public static void runWithRetries(int maxTries, ThrowingTask task) throws Exception {
// int count = 0;
// while (count < maxTries) {
// try {
// task.run();
// return;
// } catch (Exception e) {
// if (++count >= maxTries) {
// throw e;
// }
// Thread.sleep(1000);
// }
// }
// }
// }
| import com.steevsapps.idledaddy.utils.Utils;
import org.junit.Test;
import static org.junit.Assert.*; | package com.steevsapps.idledaddy;
public class UtilsTest {
/**
* Test the removeSpecialChars method
*/
@Test
public void removeSpecialChars_works() { | // Path: app/src/main/java/com/steevsapps/idledaddy/utils/Utils.java
// public class Utils {
// private final static String SHA1_ALGORITHM = "SHA-1";
// private final static String HMAC_SHA1_ALGORITHM = "HmacSHA1";
//
// /**
// * Convert byte array to hex string
// * https://stackoverflow.com/a/9855338
// */
// public static String bytesToHex(byte[] bytes) {
// final char[] hexArray = "0123456789ABCDEF".toCharArray();
//
// char[] hexChars = new char[bytes.length * 2];
// for ( int j = 0; j < bytes.length; j++ ) {
// int v = bytes[j] & 0xFF;
// hexChars[j * 2] = hexArray[v >>> 4];
// hexChars[j * 2 + 1] = hexArray[v & 0x0F];
// }
// return new String(hexChars);
// }
//
// /**
// * Convert ArrayList to comma-separated String
// */
// public static String arrayToString(List<String> list) {
// final StringBuilder builder = new StringBuilder();
// for (int i=0,size=list.size();i<size;i++) {
// final String string = list.get(i);
// builder.append(string);
// if (i + 1 < size) {
// builder.append(",");
// }
// }
// return builder.toString();
// }
//
// /**
// * Convert array to comma-separated String
// */
// public static String arrayToString(String[] array) {
// return arrayToString(Arrays.asList(array));
// }
//
// /**
// * Save Logcat to file
// */
// public static void saveLogcat(File file) throws IOException {
// final Process p = Runtime.getRuntime().exec("logcat -d");
// try ( final BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
// final BufferedWriter bw = new BufferedWriter(new FileWriter(file)) ) {
// String line;
// while ((line = br.readLine()) != null) {
// bw.write(line);
// bw.write("\n");
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// /**
// * Strips non-ASCII characters from String
// */
// public static String removeSpecialChars(String s) {
// return s.replaceAll("[^\\u0000-\\u007F]", "");
// }
//
// /**
// * Check if API key is valid
// */
// public static boolean isValidKey(String key) {
// return key.matches("^[0-9A-Fa-f]+$");
// }
//
// /**
// * Calculate the SHA-1 hash of a file
// */
// public static byte[] calculateSHA1(File file) throws IOException, NoSuchAlgorithmException {
// try (final InputStream fis = new FileInputStream(file)) {
// final MessageDigest md = MessageDigest.getInstance(SHA1_ALGORITHM);
// final byte[] buffer = new byte[8192];
// int n;
// while ((n = fis.read(buffer)) != -1) {
// md.update(buffer, 0, n);
// }
// return md.digest();
// }
// }
//
// /**
// * Get the current unix time
// */
// public static long getCurrentUnixTime() {
// return System.currentTimeMillis() / 1000L;
// }
//
// /**
// * Calculate HMAC SHA1
// */
// public static byte[] calculateRFC2104HMAC(byte[] data, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException {
// final SecretKeySpec secretKey = new SecretKeySpec(key, HMAC_SHA1_ALGORITHM);
// final Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
// mac.init(secretKey);
// return mac.doFinal(data);
// }
//
// /**
// * Run a block of code a maximum of maxTries
// */
// public static void runWithRetries(int maxTries, ThrowingTask task) throws Exception {
// int count = 0;
// while (count < maxTries) {
// try {
// task.run();
// return;
// } catch (Exception e) {
// if (++count >= maxTries) {
// throw e;
// }
// Thread.sleep(1000);
// }
// }
// }
// }
// Path: app/src/test/java/com/steevsapps/idledaddy/UtilsTest.java
import com.steevsapps.idledaddy.utils.Utils;
import org.junit.Test;
import static org.junit.Assert.*;
package com.steevsapps.idledaddy;
public class UtilsTest {
/**
* Test the removeSpecialChars method
*/
@Test
public void removeSpecialChars_works() { | assertEquals("daddy123", Utils.removeSpecialChars("daಥd益dಥy123")); |
steevp/UpdogFarmer | app/src/main/java/com/steevsapps/idledaddy/utils/Utils.java | // Path: app/src/main/java/com/steevsapps/idledaddy/ThrowingTask.java
// public interface ThrowingTask {
// void run() throws Exception;
// }
| import com.steevsapps.idledaddy.ThrowingTask;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec; | final MessageDigest md = MessageDigest.getInstance(SHA1_ALGORITHM);
final byte[] buffer = new byte[8192];
int n;
while ((n = fis.read(buffer)) != -1) {
md.update(buffer, 0, n);
}
return md.digest();
}
}
/**
* Get the current unix time
*/
public static long getCurrentUnixTime() {
return System.currentTimeMillis() / 1000L;
}
/**
* Calculate HMAC SHA1
*/
public static byte[] calculateRFC2104HMAC(byte[] data, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException {
final SecretKeySpec secretKey = new SecretKeySpec(key, HMAC_SHA1_ALGORITHM);
final Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(secretKey);
return mac.doFinal(data);
}
/**
* Run a block of code a maximum of maxTries
*/ | // Path: app/src/main/java/com/steevsapps/idledaddy/ThrowingTask.java
// public interface ThrowingTask {
// void run() throws Exception;
// }
// Path: app/src/main/java/com/steevsapps/idledaddy/utils/Utils.java
import com.steevsapps.idledaddy.ThrowingTask;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
final MessageDigest md = MessageDigest.getInstance(SHA1_ALGORITHM);
final byte[] buffer = new byte[8192];
int n;
while ((n = fis.read(buffer)) != -1) {
md.update(buffer, 0, n);
}
return md.digest();
}
}
/**
* Get the current unix time
*/
public static long getCurrentUnixTime() {
return System.currentTimeMillis() / 1000L;
}
/**
* Calculate HMAC SHA1
*/
public static byte[] calculateRFC2104HMAC(byte[] data, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException {
final SecretKeySpec secretKey = new SecretKeySpec(key, HMAC_SHA1_ALGORITHM);
final Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(secretKey);
return mac.doFinal(data);
}
/**
* Run a block of code a maximum of maxTries
*/ | public static void runWithRetries(int maxTries, ThrowingTask task) throws Exception { |
steevp/UpdogFarmer | app/src/main/java/com/steevsapps/idledaddy/dialogs/CustomAppDialog.java | // Path: app/src/main/java/com/steevsapps/idledaddy/listeners/GamePickedListener.java
// public interface GamePickedListener {
// void onGamePicked(Game game);
// void onGamesPicked(List<Game> games);
// void onGameRemoved(Game game);
// void onGameLongPressed(Game game);
// }
//
// Path: app/src/main/java/com/steevsapps/idledaddy/steam/model/Game.java
// public class Game implements Comparable<Game>, Parcelable {
// private final static String IMG_URL = "http://media.steampowered.com/steamcommunity/public/images/apps/%d/%s.jpg";
//
// @SerializedName("appid")
// public int appId;
// @SerializedName("name")
// public String name;
// @SerializedName("img_logo_url")
// public String iconUrl;
// @SerializedName("playtime_forever")
// public float hoursPlayed;
// @SerializedName("drops_remaining")
// public int dropsRemaining;
//
// public Game(int appId, String name, float hoursPlayed, int dropsRemaining) {
// this.appId = appId;
// this.name = name;
// this.iconUrl = "http://cdn.akamai.steamstatic.com/steam/apps/" + appId + "/header_292x136.jpg";
// this.hoursPlayed = hoursPlayed;
// this.dropsRemaining = dropsRemaining;
// }
//
// private Game(Parcel parcel) {
// appId = parcel.readInt();
// name = parcel.readString();
// iconUrl = parcel.readString();
// hoursPlayed = parcel.readFloat();
// dropsRemaining = parcel.readInt();
// }
//
// @Override
// public int compareTo(@NonNull Game game) {
// if (hoursPlayed == game.hoursPlayed) {
// return 0;
// }
// return hoursPlayed < game.hoursPlayed ? -1 : 1;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (obj.getClass() != getClass()) {
// return false;
// }
// final Game otherGame = (Game) obj;
// return otherGame.appId == appId;
// }
//
// @Override
// public int hashCode() {
// // Start with a non-zero constant. Prime is preferred
// int result = 17;
// // Include a hash for each field
// result = 31 * result + appId;
// return result;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel parcel, int i) {
// parcel.writeInt(appId);
// parcel.writeString(name);
// parcel.writeString(iconUrl);
// parcel.writeFloat(hoursPlayed);
// parcel.writeInt(dropsRemaining);
// }
//
// public final static Parcelable.Creator<Game> CREATOR = new Parcelable.Creator<Game>() {
// @Override
// public Game createFromParcel(Parcel parcel) {
// return new Game(parcel);
// }
//
// @Override
// public Game[] newArray(int i) {
// return new Game[i];
// }
// };
// }
| import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import com.steevsapps.idledaddy.R;
import com.steevsapps.idledaddy.listeners.GamePickedListener;
import com.steevsapps.idledaddy.steam.model.Game; | package com.steevsapps.idledaddy.dialogs;
public class CustomAppDialog extends DialogFragment {
public final static String TAG = CustomAppDialog.class.getSimpleName();
private final static int TYPE_APPID = 0;
private final static int TYPE_CUSTOM = 1;
private EditText customApp;
| // Path: app/src/main/java/com/steevsapps/idledaddy/listeners/GamePickedListener.java
// public interface GamePickedListener {
// void onGamePicked(Game game);
// void onGamesPicked(List<Game> games);
// void onGameRemoved(Game game);
// void onGameLongPressed(Game game);
// }
//
// Path: app/src/main/java/com/steevsapps/idledaddy/steam/model/Game.java
// public class Game implements Comparable<Game>, Parcelable {
// private final static String IMG_URL = "http://media.steampowered.com/steamcommunity/public/images/apps/%d/%s.jpg";
//
// @SerializedName("appid")
// public int appId;
// @SerializedName("name")
// public String name;
// @SerializedName("img_logo_url")
// public String iconUrl;
// @SerializedName("playtime_forever")
// public float hoursPlayed;
// @SerializedName("drops_remaining")
// public int dropsRemaining;
//
// public Game(int appId, String name, float hoursPlayed, int dropsRemaining) {
// this.appId = appId;
// this.name = name;
// this.iconUrl = "http://cdn.akamai.steamstatic.com/steam/apps/" + appId + "/header_292x136.jpg";
// this.hoursPlayed = hoursPlayed;
// this.dropsRemaining = dropsRemaining;
// }
//
// private Game(Parcel parcel) {
// appId = parcel.readInt();
// name = parcel.readString();
// iconUrl = parcel.readString();
// hoursPlayed = parcel.readFloat();
// dropsRemaining = parcel.readInt();
// }
//
// @Override
// public int compareTo(@NonNull Game game) {
// if (hoursPlayed == game.hoursPlayed) {
// return 0;
// }
// return hoursPlayed < game.hoursPlayed ? -1 : 1;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (obj.getClass() != getClass()) {
// return false;
// }
// final Game otherGame = (Game) obj;
// return otherGame.appId == appId;
// }
//
// @Override
// public int hashCode() {
// // Start with a non-zero constant. Prime is preferred
// int result = 17;
// // Include a hash for each field
// result = 31 * result + appId;
// return result;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel parcel, int i) {
// parcel.writeInt(appId);
// parcel.writeString(name);
// parcel.writeString(iconUrl);
// parcel.writeFloat(hoursPlayed);
// parcel.writeInt(dropsRemaining);
// }
//
// public final static Parcelable.Creator<Game> CREATOR = new Parcelable.Creator<Game>() {
// @Override
// public Game createFromParcel(Parcel parcel) {
// return new Game(parcel);
// }
//
// @Override
// public Game[] newArray(int i) {
// return new Game[i];
// }
// };
// }
// Path: app/src/main/java/com/steevsapps/idledaddy/dialogs/CustomAppDialog.java
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import com.steevsapps.idledaddy.R;
import com.steevsapps.idledaddy.listeners.GamePickedListener;
import com.steevsapps.idledaddy.steam.model.Game;
package com.steevsapps.idledaddy.dialogs;
public class CustomAppDialog extends DialogFragment {
public final static String TAG = CustomAppDialog.class.getSimpleName();
private final static int TYPE_APPID = 0;
private final static int TYPE_CUSTOM = 1;
private EditText customApp;
| private GamePickedListener callback; |
steevp/UpdogFarmer | app/src/main/java/com/steevsapps/idledaddy/dialogs/CustomAppDialog.java | // Path: app/src/main/java/com/steevsapps/idledaddy/listeners/GamePickedListener.java
// public interface GamePickedListener {
// void onGamePicked(Game game);
// void onGamesPicked(List<Game> games);
// void onGameRemoved(Game game);
// void onGameLongPressed(Game game);
// }
//
// Path: app/src/main/java/com/steevsapps/idledaddy/steam/model/Game.java
// public class Game implements Comparable<Game>, Parcelable {
// private final static String IMG_URL = "http://media.steampowered.com/steamcommunity/public/images/apps/%d/%s.jpg";
//
// @SerializedName("appid")
// public int appId;
// @SerializedName("name")
// public String name;
// @SerializedName("img_logo_url")
// public String iconUrl;
// @SerializedName("playtime_forever")
// public float hoursPlayed;
// @SerializedName("drops_remaining")
// public int dropsRemaining;
//
// public Game(int appId, String name, float hoursPlayed, int dropsRemaining) {
// this.appId = appId;
// this.name = name;
// this.iconUrl = "http://cdn.akamai.steamstatic.com/steam/apps/" + appId + "/header_292x136.jpg";
// this.hoursPlayed = hoursPlayed;
// this.dropsRemaining = dropsRemaining;
// }
//
// private Game(Parcel parcel) {
// appId = parcel.readInt();
// name = parcel.readString();
// iconUrl = parcel.readString();
// hoursPlayed = parcel.readFloat();
// dropsRemaining = parcel.readInt();
// }
//
// @Override
// public int compareTo(@NonNull Game game) {
// if (hoursPlayed == game.hoursPlayed) {
// return 0;
// }
// return hoursPlayed < game.hoursPlayed ? -1 : 1;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (obj.getClass() != getClass()) {
// return false;
// }
// final Game otherGame = (Game) obj;
// return otherGame.appId == appId;
// }
//
// @Override
// public int hashCode() {
// // Start with a non-zero constant. Prime is preferred
// int result = 17;
// // Include a hash for each field
// result = 31 * result + appId;
// return result;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel parcel, int i) {
// parcel.writeInt(appId);
// parcel.writeString(name);
// parcel.writeString(iconUrl);
// parcel.writeFloat(hoursPlayed);
// parcel.writeInt(dropsRemaining);
// }
//
// public final static Parcelable.Creator<Game> CREATOR = new Parcelable.Creator<Game>() {
// @Override
// public Game createFromParcel(Parcel parcel) {
// return new Game(parcel);
// }
//
// @Override
// public Game[] newArray(int i) {
// return new Game[i];
// }
// };
// }
| import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import com.steevsapps.idledaddy.R;
import com.steevsapps.idledaddy.listeners.GamePickedListener;
import com.steevsapps.idledaddy.steam.model.Game; | // Apply the adapter to the spinner
spinner.setAdapter(adapter);
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.idle_custom_app)
.setView(view)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (spinner.getSelectedItemPosition()) {
case TYPE_APPID:
idleHiddenApp();
break;
case TYPE_CUSTOM:
idleNonSteamApp();
break;
}
}
})
.setNegativeButton(android.R.string.cancel, null)
.create();
}
private void idleHiddenApp() {
final String text = customApp.getText().toString().trim();
if (text.isEmpty()) {
return;
}
try {
final int appId = Integer.parseInt(text); | // Path: app/src/main/java/com/steevsapps/idledaddy/listeners/GamePickedListener.java
// public interface GamePickedListener {
// void onGamePicked(Game game);
// void onGamesPicked(List<Game> games);
// void onGameRemoved(Game game);
// void onGameLongPressed(Game game);
// }
//
// Path: app/src/main/java/com/steevsapps/idledaddy/steam/model/Game.java
// public class Game implements Comparable<Game>, Parcelable {
// private final static String IMG_URL = "http://media.steampowered.com/steamcommunity/public/images/apps/%d/%s.jpg";
//
// @SerializedName("appid")
// public int appId;
// @SerializedName("name")
// public String name;
// @SerializedName("img_logo_url")
// public String iconUrl;
// @SerializedName("playtime_forever")
// public float hoursPlayed;
// @SerializedName("drops_remaining")
// public int dropsRemaining;
//
// public Game(int appId, String name, float hoursPlayed, int dropsRemaining) {
// this.appId = appId;
// this.name = name;
// this.iconUrl = "http://cdn.akamai.steamstatic.com/steam/apps/" + appId + "/header_292x136.jpg";
// this.hoursPlayed = hoursPlayed;
// this.dropsRemaining = dropsRemaining;
// }
//
// private Game(Parcel parcel) {
// appId = parcel.readInt();
// name = parcel.readString();
// iconUrl = parcel.readString();
// hoursPlayed = parcel.readFloat();
// dropsRemaining = parcel.readInt();
// }
//
// @Override
// public int compareTo(@NonNull Game game) {
// if (hoursPlayed == game.hoursPlayed) {
// return 0;
// }
// return hoursPlayed < game.hoursPlayed ? -1 : 1;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (obj.getClass() != getClass()) {
// return false;
// }
// final Game otherGame = (Game) obj;
// return otherGame.appId == appId;
// }
//
// @Override
// public int hashCode() {
// // Start with a non-zero constant. Prime is preferred
// int result = 17;
// // Include a hash for each field
// result = 31 * result + appId;
// return result;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel parcel, int i) {
// parcel.writeInt(appId);
// parcel.writeString(name);
// parcel.writeString(iconUrl);
// parcel.writeFloat(hoursPlayed);
// parcel.writeInt(dropsRemaining);
// }
//
// public final static Parcelable.Creator<Game> CREATOR = new Parcelable.Creator<Game>() {
// @Override
// public Game createFromParcel(Parcel parcel) {
// return new Game(parcel);
// }
//
// @Override
// public Game[] newArray(int i) {
// return new Game[i];
// }
// };
// }
// Path: app/src/main/java/com/steevsapps/idledaddy/dialogs/CustomAppDialog.java
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import com.steevsapps.idledaddy.R;
import com.steevsapps.idledaddy.listeners.GamePickedListener;
import com.steevsapps.idledaddy.steam.model.Game;
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.idle_custom_app)
.setView(view)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (spinner.getSelectedItemPosition()) {
case TYPE_APPID:
idleHiddenApp();
break;
case TYPE_CUSTOM:
idleNonSteamApp();
break;
}
}
})
.setNegativeButton(android.R.string.cancel, null)
.create();
}
private void idleHiddenApp() {
final String text = customApp.getText().toString().trim();
if (text.isEmpty()) {
return;
}
try {
final int appId = Integer.parseInt(text); | final Game game = new Game(appId, getString(R.string.playing_unknown_app, appId), 0, 0); |
steevp/UpdogFarmer | app/src/main/java/com/steevsapps/idledaddy/steam/converter/GamesOwnedResponseDeserializer.java | // Path: app/src/main/java/com/steevsapps/idledaddy/steam/model/Game.java
// public class Game implements Comparable<Game>, Parcelable {
// private final static String IMG_URL = "http://media.steampowered.com/steamcommunity/public/images/apps/%d/%s.jpg";
//
// @SerializedName("appid")
// public int appId;
// @SerializedName("name")
// public String name;
// @SerializedName("img_logo_url")
// public String iconUrl;
// @SerializedName("playtime_forever")
// public float hoursPlayed;
// @SerializedName("drops_remaining")
// public int dropsRemaining;
//
// public Game(int appId, String name, float hoursPlayed, int dropsRemaining) {
// this.appId = appId;
// this.name = name;
// this.iconUrl = "http://cdn.akamai.steamstatic.com/steam/apps/" + appId + "/header_292x136.jpg";
// this.hoursPlayed = hoursPlayed;
// this.dropsRemaining = dropsRemaining;
// }
//
// private Game(Parcel parcel) {
// appId = parcel.readInt();
// name = parcel.readString();
// iconUrl = parcel.readString();
// hoursPlayed = parcel.readFloat();
// dropsRemaining = parcel.readInt();
// }
//
// @Override
// public int compareTo(@NonNull Game game) {
// if (hoursPlayed == game.hoursPlayed) {
// return 0;
// }
// return hoursPlayed < game.hoursPlayed ? -1 : 1;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (obj.getClass() != getClass()) {
// return false;
// }
// final Game otherGame = (Game) obj;
// return otherGame.appId == appId;
// }
//
// @Override
// public int hashCode() {
// // Start with a non-zero constant. Prime is preferred
// int result = 17;
// // Include a hash for each field
// result = 31 * result + appId;
// return result;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel parcel, int i) {
// parcel.writeInt(appId);
// parcel.writeString(name);
// parcel.writeString(iconUrl);
// parcel.writeFloat(hoursPlayed);
// parcel.writeInt(dropsRemaining);
// }
//
// public final static Parcelable.Creator<Game> CREATOR = new Parcelable.Creator<Game>() {
// @Override
// public Game createFromParcel(Parcel parcel) {
// return new Game(parcel);
// }
//
// @Override
// public Game[] newArray(int i) {
// return new Game[i];
// }
// };
// }
//
// Path: app/src/main/java/com/steevsapps/idledaddy/steam/model/GamesOwnedResponse.java
// public class GamesOwnedResponse {
// @SerializedName("game_count")
// private int count;
//
// @SerializedName("games")
// private List<Game> games;
//
// public int getCount() {
// return count;
// }
//
// public List<Game> getGames() {
// return games;
// }
// }
| import com.google.gson.Gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.steevsapps.idledaddy.steam.model.Game;
import com.steevsapps.idledaddy.steam.model.GamesOwnedResponse;
import java.lang.reflect.Type;
import java.util.Locale; | package com.steevsapps.idledaddy.steam.converter;
public class GamesOwnedResponseDeserializer implements JsonDeserializer<GamesOwnedResponse> {
private final static String IMG_URL = "http://media.steampowered.com/steamcommunity/public/images/apps/%d/%s.jpg";
@Override
public GamesOwnedResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
final JsonElement element = json.getAsJsonObject().get("response");
final GamesOwnedResponse response = new Gson().fromJson(element, GamesOwnedResponse.class);
| // Path: app/src/main/java/com/steevsapps/idledaddy/steam/model/Game.java
// public class Game implements Comparable<Game>, Parcelable {
// private final static String IMG_URL = "http://media.steampowered.com/steamcommunity/public/images/apps/%d/%s.jpg";
//
// @SerializedName("appid")
// public int appId;
// @SerializedName("name")
// public String name;
// @SerializedName("img_logo_url")
// public String iconUrl;
// @SerializedName("playtime_forever")
// public float hoursPlayed;
// @SerializedName("drops_remaining")
// public int dropsRemaining;
//
// public Game(int appId, String name, float hoursPlayed, int dropsRemaining) {
// this.appId = appId;
// this.name = name;
// this.iconUrl = "http://cdn.akamai.steamstatic.com/steam/apps/" + appId + "/header_292x136.jpg";
// this.hoursPlayed = hoursPlayed;
// this.dropsRemaining = dropsRemaining;
// }
//
// private Game(Parcel parcel) {
// appId = parcel.readInt();
// name = parcel.readString();
// iconUrl = parcel.readString();
// hoursPlayed = parcel.readFloat();
// dropsRemaining = parcel.readInt();
// }
//
// @Override
// public int compareTo(@NonNull Game game) {
// if (hoursPlayed == game.hoursPlayed) {
// return 0;
// }
// return hoursPlayed < game.hoursPlayed ? -1 : 1;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (obj.getClass() != getClass()) {
// return false;
// }
// final Game otherGame = (Game) obj;
// return otherGame.appId == appId;
// }
//
// @Override
// public int hashCode() {
// // Start with a non-zero constant. Prime is preferred
// int result = 17;
// // Include a hash for each field
// result = 31 * result + appId;
// return result;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel parcel, int i) {
// parcel.writeInt(appId);
// parcel.writeString(name);
// parcel.writeString(iconUrl);
// parcel.writeFloat(hoursPlayed);
// parcel.writeInt(dropsRemaining);
// }
//
// public final static Parcelable.Creator<Game> CREATOR = new Parcelable.Creator<Game>() {
// @Override
// public Game createFromParcel(Parcel parcel) {
// return new Game(parcel);
// }
//
// @Override
// public Game[] newArray(int i) {
// return new Game[i];
// }
// };
// }
//
// Path: app/src/main/java/com/steevsapps/idledaddy/steam/model/GamesOwnedResponse.java
// public class GamesOwnedResponse {
// @SerializedName("game_count")
// private int count;
//
// @SerializedName("games")
// private List<Game> games;
//
// public int getCount() {
// return count;
// }
//
// public List<Game> getGames() {
// return games;
// }
// }
// Path: app/src/main/java/com/steevsapps/idledaddy/steam/converter/GamesOwnedResponseDeserializer.java
import com.google.gson.Gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.steevsapps.idledaddy.steam.model.Game;
import com.steevsapps.idledaddy.steam.model.GamesOwnedResponse;
import java.lang.reflect.Type;
import java.util.Locale;
package com.steevsapps.idledaddy.steam.converter;
public class GamesOwnedResponseDeserializer implements JsonDeserializer<GamesOwnedResponse> {
private final static String IMG_URL = "http://media.steampowered.com/steamcommunity/public/images/apps/%d/%s.jpg";
@Override
public GamesOwnedResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
final JsonElement element = json.getAsJsonObject().get("response");
final GamesOwnedResponse response = new Gson().fromJson(element, GamesOwnedResponse.class);
| for (Game game : response.getGames()) { |
steevp/UpdogFarmer | app/src/main/java/com/steevsapps/idledaddy/handlers/PurchaseResponse.java | // Path: app/src/main/java/com/steevsapps/idledaddy/handlers/callbacks/PurchaseResponseCallback.java
// public class PurchaseResponseCallback extends CallbackMsg {
// private final EResult result;
// private final EPurchaseResultDetail purchaseResultDetails;
// private final KeyValue purchaseReceiptInfo;
//
// public PurchaseResponseCallback(JobID jobID, SteammessagesClientserver2.CMsgClientPurchaseResponse.Builder msg) {
// setJobID(jobID);
//
// result = EResult.from(msg.getEresult());
// purchaseResultDetails = EPurchaseResultDetail.from(msg.getPurchaseResultDetails());
// purchaseReceiptInfo = new KeyValue();
// try {
// purchaseReceiptInfo.tryReadAsBinary(new ByteArrayInputStream(msg.getPurchaseReceiptInfo().toByteArray()));
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// public EResult getResult() {
// return result;
// }
//
// public EPurchaseResultDetail getPurchaseResultDetails() {
// return purchaseResultDetails;
// }
//
// public KeyValue getPurchaseReceiptInfo() {
// return purchaseReceiptInfo;
// }
// }
| import com.steevsapps.idledaddy.handlers.callbacks.PurchaseResponseCallback;
import in.dragonbra.javasteam.base.ClientMsgProtobuf;
import in.dragonbra.javasteam.base.IPacketMsg;
import in.dragonbra.javasteam.handlers.ClientMsgHandler;
import in.dragonbra.javasteam.protobufs.steamclient.SteammessagesClientserver2; | package com.steevsapps.idledaddy.handlers;
public class PurchaseResponse extends ClientMsgHandler {
@Override
public void handleMsg(IPacketMsg packetMsg) {
if (packetMsg == null) {
throw new IllegalArgumentException("packetMsg is null");
}
switch (packetMsg.getMsgType()) {
case ClientPurchaseResponse:
handlePurchaseResponse(packetMsg);
break;
}
}
private void handlePurchaseResponse(IPacketMsg packetMsg) {
final ClientMsgProtobuf<SteammessagesClientserver2.CMsgClientPurchaseResponse.Builder> purchaseResponse;
purchaseResponse = new ClientMsgProtobuf<>(SteammessagesClientserver2.CMsgClientPurchaseResponse.class, packetMsg); | // Path: app/src/main/java/com/steevsapps/idledaddy/handlers/callbacks/PurchaseResponseCallback.java
// public class PurchaseResponseCallback extends CallbackMsg {
// private final EResult result;
// private final EPurchaseResultDetail purchaseResultDetails;
// private final KeyValue purchaseReceiptInfo;
//
// public PurchaseResponseCallback(JobID jobID, SteammessagesClientserver2.CMsgClientPurchaseResponse.Builder msg) {
// setJobID(jobID);
//
// result = EResult.from(msg.getEresult());
// purchaseResultDetails = EPurchaseResultDetail.from(msg.getPurchaseResultDetails());
// purchaseReceiptInfo = new KeyValue();
// try {
// purchaseReceiptInfo.tryReadAsBinary(new ByteArrayInputStream(msg.getPurchaseReceiptInfo().toByteArray()));
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// public EResult getResult() {
// return result;
// }
//
// public EPurchaseResultDetail getPurchaseResultDetails() {
// return purchaseResultDetails;
// }
//
// public KeyValue getPurchaseReceiptInfo() {
// return purchaseReceiptInfo;
// }
// }
// Path: app/src/main/java/com/steevsapps/idledaddy/handlers/PurchaseResponse.java
import com.steevsapps.idledaddy.handlers.callbacks.PurchaseResponseCallback;
import in.dragonbra.javasteam.base.ClientMsgProtobuf;
import in.dragonbra.javasteam.base.IPacketMsg;
import in.dragonbra.javasteam.handlers.ClientMsgHandler;
import in.dragonbra.javasteam.protobufs.steamclient.SteammessagesClientserver2;
package com.steevsapps.idledaddy.handlers;
public class PurchaseResponse extends ClientMsgHandler {
@Override
public void handleMsg(IPacketMsg packetMsg) {
if (packetMsg == null) {
throw new IllegalArgumentException("packetMsg is null");
}
switch (packetMsg.getMsgType()) {
case ClientPurchaseResponse:
handlePurchaseResponse(packetMsg);
break;
}
}
private void handlePurchaseResponse(IPacketMsg packetMsg) {
final ClientMsgProtobuf<SteammessagesClientserver2.CMsgClientPurchaseResponse.Builder> purchaseResponse;
purchaseResponse = new ClientMsgProtobuf<>(SteammessagesClientserver2.CMsgClientPurchaseResponse.class, packetMsg); | getClient().postCallback(new PurchaseResponseCallback(purchaseResponse.getTargetJobID(), purchaseResponse.getBody())); |
steevp/UpdogFarmer | app/src/main/java/com/steevsapps/idledaddy/steam/SteamAPI.java | // Path: app/src/main/java/com/steevsapps/idledaddy/steam/model/GamesOwnedResponse.java
// public class GamesOwnedResponse {
// @SerializedName("game_count")
// private int count;
//
// @SerializedName("games")
// private List<Game> games;
//
// public int getCount() {
// return count;
// }
//
// public List<Game> getGames() {
// return games;
// }
// }
//
// Path: app/src/main/java/com/steevsapps/idledaddy/steam/model/TimeQuery.java
// public class TimeQuery {
// @SerializedName("response")
// private TimeResponse response;
//
// public TimeResponse getResponse() {
// return response;
// }
// }
| import com.steevsapps.idledaddy.steam.model.GamesOwnedResponse;
import com.steevsapps.idledaddy.steam.model.TimeQuery;
import java.util.Map;
import in.dragonbra.javasteam.types.KeyValue;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.QueryMap; | package com.steevsapps.idledaddy.steam;
public interface SteamAPI {
@GET("IPlayerService/GetOwnedGames/v0001/?include_appinfo=1&format=json") | // Path: app/src/main/java/com/steevsapps/idledaddy/steam/model/GamesOwnedResponse.java
// public class GamesOwnedResponse {
// @SerializedName("game_count")
// private int count;
//
// @SerializedName("games")
// private List<Game> games;
//
// public int getCount() {
// return count;
// }
//
// public List<Game> getGames() {
// return games;
// }
// }
//
// Path: app/src/main/java/com/steevsapps/idledaddy/steam/model/TimeQuery.java
// public class TimeQuery {
// @SerializedName("response")
// private TimeResponse response;
//
// public TimeResponse getResponse() {
// return response;
// }
// }
// Path: app/src/main/java/com/steevsapps/idledaddy/steam/SteamAPI.java
import com.steevsapps.idledaddy.steam.model.GamesOwnedResponse;
import com.steevsapps.idledaddy.steam.model.TimeQuery;
import java.util.Map;
import in.dragonbra.javasteam.types.KeyValue;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.QueryMap;
package com.steevsapps.idledaddy.steam;
public interface SteamAPI {
@GET("IPlayerService/GetOwnedGames/v0001/?include_appinfo=1&format=json") | Call<GamesOwnedResponse> getGamesOwned(@QueryMap Map<String,String> args); |
steevp/UpdogFarmer | app/src/main/java/com/steevsapps/idledaddy/steam/SteamAPI.java | // Path: app/src/main/java/com/steevsapps/idledaddy/steam/model/GamesOwnedResponse.java
// public class GamesOwnedResponse {
// @SerializedName("game_count")
// private int count;
//
// @SerializedName("games")
// private List<Game> games;
//
// public int getCount() {
// return count;
// }
//
// public List<Game> getGames() {
// return games;
// }
// }
//
// Path: app/src/main/java/com/steevsapps/idledaddy/steam/model/TimeQuery.java
// public class TimeQuery {
// @SerializedName("response")
// private TimeResponse response;
//
// public TimeResponse getResponse() {
// return response;
// }
// }
| import com.steevsapps.idledaddy.steam.model.GamesOwnedResponse;
import com.steevsapps.idledaddy.steam.model.TimeQuery;
import java.util.Map;
import in.dragonbra.javasteam.types.KeyValue;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.QueryMap; | package com.steevsapps.idledaddy.steam;
public interface SteamAPI {
@GET("IPlayerService/GetOwnedGames/v0001/?include_appinfo=1&format=json")
Call<GamesOwnedResponse> getGamesOwned(@QueryMap Map<String,String> args);
@FormUrlEncoded
@POST("ISteamUserAuth/AuthenticateUser/v0001/")
Call<KeyValue> authenticateUser(@FieldMap(encoded = true) Map<String,String> args);
@FormUrlEncoded
@POST("ITwoFactorService/QueryTime/v0001") | // Path: app/src/main/java/com/steevsapps/idledaddy/steam/model/GamesOwnedResponse.java
// public class GamesOwnedResponse {
// @SerializedName("game_count")
// private int count;
//
// @SerializedName("games")
// private List<Game> games;
//
// public int getCount() {
// return count;
// }
//
// public List<Game> getGames() {
// return games;
// }
// }
//
// Path: app/src/main/java/com/steevsapps/idledaddy/steam/model/TimeQuery.java
// public class TimeQuery {
// @SerializedName("response")
// private TimeResponse response;
//
// public TimeResponse getResponse() {
// return response;
// }
// }
// Path: app/src/main/java/com/steevsapps/idledaddy/steam/SteamAPI.java
import com.steevsapps.idledaddy.steam.model.GamesOwnedResponse;
import com.steevsapps.idledaddy.steam.model.TimeQuery;
import java.util.Map;
import in.dragonbra.javasteam.types.KeyValue;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.QueryMap;
package com.steevsapps.idledaddy.steam;
public interface SteamAPI {
@GET("IPlayerService/GetOwnedGames/v0001/?include_appinfo=1&format=json")
Call<GamesOwnedResponse> getGamesOwned(@QueryMap Map<String,String> args);
@FormUrlEncoded
@POST("ISteamUserAuth/AuthenticateUser/v0001/")
Call<KeyValue> authenticateUser(@FieldMap(encoded = true) Map<String,String> args);
@FormUrlEncoded
@POST("ITwoFactorService/QueryTime/v0001") | Call<TimeQuery> queryServerTime(@Field("steamid") String steamId); |
steevp/UpdogFarmer | app/src/main/java/com/steevsapps/idledaddy/adapters/BlacklistAdapter.java | // Path: app/src/main/java/com/steevsapps/idledaddy/utils/Utils.java
// public class Utils {
// private final static String SHA1_ALGORITHM = "SHA-1";
// private final static String HMAC_SHA1_ALGORITHM = "HmacSHA1";
//
// /**
// * Convert byte array to hex string
// * https://stackoverflow.com/a/9855338
// */
// public static String bytesToHex(byte[] bytes) {
// final char[] hexArray = "0123456789ABCDEF".toCharArray();
//
// char[] hexChars = new char[bytes.length * 2];
// for ( int j = 0; j < bytes.length; j++ ) {
// int v = bytes[j] & 0xFF;
// hexChars[j * 2] = hexArray[v >>> 4];
// hexChars[j * 2 + 1] = hexArray[v & 0x0F];
// }
// return new String(hexChars);
// }
//
// /**
// * Convert ArrayList to comma-separated String
// */
// public static String arrayToString(List<String> list) {
// final StringBuilder builder = new StringBuilder();
// for (int i=0,size=list.size();i<size;i++) {
// final String string = list.get(i);
// builder.append(string);
// if (i + 1 < size) {
// builder.append(",");
// }
// }
// return builder.toString();
// }
//
// /**
// * Convert array to comma-separated String
// */
// public static String arrayToString(String[] array) {
// return arrayToString(Arrays.asList(array));
// }
//
// /**
// * Save Logcat to file
// */
// public static void saveLogcat(File file) throws IOException {
// final Process p = Runtime.getRuntime().exec("logcat -d");
// try ( final BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
// final BufferedWriter bw = new BufferedWriter(new FileWriter(file)) ) {
// String line;
// while ((line = br.readLine()) != null) {
// bw.write(line);
// bw.write("\n");
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// /**
// * Strips non-ASCII characters from String
// */
// public static String removeSpecialChars(String s) {
// return s.replaceAll("[^\\u0000-\\u007F]", "");
// }
//
// /**
// * Check if API key is valid
// */
// public static boolean isValidKey(String key) {
// return key.matches("^[0-9A-Fa-f]+$");
// }
//
// /**
// * Calculate the SHA-1 hash of a file
// */
// public static byte[] calculateSHA1(File file) throws IOException, NoSuchAlgorithmException {
// try (final InputStream fis = new FileInputStream(file)) {
// final MessageDigest md = MessageDigest.getInstance(SHA1_ALGORITHM);
// final byte[] buffer = new byte[8192];
// int n;
// while ((n = fis.read(buffer)) != -1) {
// md.update(buffer, 0, n);
// }
// return md.digest();
// }
// }
//
// /**
// * Get the current unix time
// */
// public static long getCurrentUnixTime() {
// return System.currentTimeMillis() / 1000L;
// }
//
// /**
// * Calculate HMAC SHA1
// */
// public static byte[] calculateRFC2104HMAC(byte[] data, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException {
// final SecretKeySpec secretKey = new SecretKeySpec(key, HMAC_SHA1_ALGORITHM);
// final Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
// mac.init(secretKey);
// return mac.doFinal(data);
// }
//
// /**
// * Run a block of code a maximum of maxTries
// */
// public static void runWithRetries(int maxTries, ThrowingTask task) throws Exception {
// int count = 0;
// while (count < maxTries) {
// try {
// task.run();
// return;
// } catch (Exception e) {
// if (++count >= maxTries) {
// throw e;
// }
// Thread.sleep(1000);
// }
// }
// }
// }
| import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.steevsapps.idledaddy.R;
import com.steevsapps.idledaddy.utils.Utils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; | package com.steevsapps.idledaddy.adapters;
public class BlacklistAdapter extends RecyclerView.Adapter<BlacklistAdapter.ViewHolder> {
private List<String> dataSet = new ArrayList<>();
public BlacklistAdapter(String data) {
data = data.trim();
if (!data.isEmpty()) {
dataSet.addAll(Arrays.asList(data.split(",")));
}
}
public String getValue() { | // Path: app/src/main/java/com/steevsapps/idledaddy/utils/Utils.java
// public class Utils {
// private final static String SHA1_ALGORITHM = "SHA-1";
// private final static String HMAC_SHA1_ALGORITHM = "HmacSHA1";
//
// /**
// * Convert byte array to hex string
// * https://stackoverflow.com/a/9855338
// */
// public static String bytesToHex(byte[] bytes) {
// final char[] hexArray = "0123456789ABCDEF".toCharArray();
//
// char[] hexChars = new char[bytes.length * 2];
// for ( int j = 0; j < bytes.length; j++ ) {
// int v = bytes[j] & 0xFF;
// hexChars[j * 2] = hexArray[v >>> 4];
// hexChars[j * 2 + 1] = hexArray[v & 0x0F];
// }
// return new String(hexChars);
// }
//
// /**
// * Convert ArrayList to comma-separated String
// */
// public static String arrayToString(List<String> list) {
// final StringBuilder builder = new StringBuilder();
// for (int i=0,size=list.size();i<size;i++) {
// final String string = list.get(i);
// builder.append(string);
// if (i + 1 < size) {
// builder.append(",");
// }
// }
// return builder.toString();
// }
//
// /**
// * Convert array to comma-separated String
// */
// public static String arrayToString(String[] array) {
// return arrayToString(Arrays.asList(array));
// }
//
// /**
// * Save Logcat to file
// */
// public static void saveLogcat(File file) throws IOException {
// final Process p = Runtime.getRuntime().exec("logcat -d");
// try ( final BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
// final BufferedWriter bw = new BufferedWriter(new FileWriter(file)) ) {
// String line;
// while ((line = br.readLine()) != null) {
// bw.write(line);
// bw.write("\n");
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// /**
// * Strips non-ASCII characters from String
// */
// public static String removeSpecialChars(String s) {
// return s.replaceAll("[^\\u0000-\\u007F]", "");
// }
//
// /**
// * Check if API key is valid
// */
// public static boolean isValidKey(String key) {
// return key.matches("^[0-9A-Fa-f]+$");
// }
//
// /**
// * Calculate the SHA-1 hash of a file
// */
// public static byte[] calculateSHA1(File file) throws IOException, NoSuchAlgorithmException {
// try (final InputStream fis = new FileInputStream(file)) {
// final MessageDigest md = MessageDigest.getInstance(SHA1_ALGORITHM);
// final byte[] buffer = new byte[8192];
// int n;
// while ((n = fis.read(buffer)) != -1) {
// md.update(buffer, 0, n);
// }
// return md.digest();
// }
// }
//
// /**
// * Get the current unix time
// */
// public static long getCurrentUnixTime() {
// return System.currentTimeMillis() / 1000L;
// }
//
// /**
// * Calculate HMAC SHA1
// */
// public static byte[] calculateRFC2104HMAC(byte[] data, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException {
// final SecretKeySpec secretKey = new SecretKeySpec(key, HMAC_SHA1_ALGORITHM);
// final Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
// mac.init(secretKey);
// return mac.doFinal(data);
// }
//
// /**
// * Run a block of code a maximum of maxTries
// */
// public static void runWithRetries(int maxTries, ThrowingTask task) throws Exception {
// int count = 0;
// while (count < maxTries) {
// try {
// task.run();
// return;
// } catch (Exception e) {
// if (++count >= maxTries) {
// throw e;
// }
// Thread.sleep(1000);
// }
// }
// }
// }
// Path: app/src/main/java/com/steevsapps/idledaddy/adapters/BlacklistAdapter.java
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.steevsapps.idledaddy.R;
import com.steevsapps.idledaddy.utils.Utils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
package com.steevsapps.idledaddy.adapters;
public class BlacklistAdapter extends RecyclerView.Adapter<BlacklistAdapter.ViewHolder> {
private List<String> dataSet = new ArrayList<>();
public BlacklistAdapter(String data) {
data = data.trim();
if (!data.isEmpty()) {
dataSet.addAll(Arrays.asList(data.split(",")));
}
}
public String getValue() { | return Utils.arrayToString(dataSet); |
steevp/UpdogFarmer | app/src/main/java/com/steevsapps/idledaddy/preferences/BlacklistDialog.java | // Path: app/src/main/java/com/steevsapps/idledaddy/adapters/BlacklistAdapter.java
// public class BlacklistAdapter extends RecyclerView.Adapter<BlacklistAdapter.ViewHolder> {
// private List<String> dataSet = new ArrayList<>();
//
// public BlacklistAdapter(String data) {
// data = data.trim();
// if (!data.isEmpty()) {
// dataSet.addAll(Arrays.asList(data.split(",")));
// }
// }
//
// public String getValue() {
// return Utils.arrayToString(dataSet);
// }
//
// public void addItem(String item) {
// if (!dataSet.contains(item)) {
// dataSet.add(0, item);
// notifyItemInserted(0);
// }
// }
//
// private void removeItem(int position) {
// dataSet.remove(position);
// notifyItemRemoved(position);
// }
//
// @Override
// public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.blacklist_dialog_item, parent, false);
// final ViewHolder vh = new ViewHolder(view);
// vh.removeButton.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// removeItem(vh.getAdapterPosition());
// }
// });
// return vh;
// }
//
// @Override
// public void onBindViewHolder(final ViewHolder holder, int position) {
// final String appId = dataSet.get(position);
// holder.appId.setText(appId);
// }
//
// @Override
// public int getItemCount() {
// return dataSet.size();
// }
//
// static class ViewHolder extends RecyclerView.ViewHolder {
// private TextView appId;
// private ImageView removeButton;
// private ViewHolder(View itemView) {
// super(itemView);
// appId = itemView.findViewById(R.id.appid);
// removeButton = itemView.findViewById(R.id.remove_button);
// }
// }
// }
| import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.preference.Preference;
import androidx.preference.PreferenceDialogFragmentCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.steevsapps.idledaddy.R;
import com.steevsapps.idledaddy.adapters.BlacklistAdapter; | package com.steevsapps.idledaddy.preferences;
public class BlacklistDialog extends PreferenceDialogFragmentCompat implements View.OnClickListener, EditText.OnEditorActionListener {
private final static String VALUE = "VALUE"; // Key to hold current value
private EditText input;
private ImageView addButton;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager; | // Path: app/src/main/java/com/steevsapps/idledaddy/adapters/BlacklistAdapter.java
// public class BlacklistAdapter extends RecyclerView.Adapter<BlacklistAdapter.ViewHolder> {
// private List<String> dataSet = new ArrayList<>();
//
// public BlacklistAdapter(String data) {
// data = data.trim();
// if (!data.isEmpty()) {
// dataSet.addAll(Arrays.asList(data.split(",")));
// }
// }
//
// public String getValue() {
// return Utils.arrayToString(dataSet);
// }
//
// public void addItem(String item) {
// if (!dataSet.contains(item)) {
// dataSet.add(0, item);
// notifyItemInserted(0);
// }
// }
//
// private void removeItem(int position) {
// dataSet.remove(position);
// notifyItemRemoved(position);
// }
//
// @Override
// public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.blacklist_dialog_item, parent, false);
// final ViewHolder vh = new ViewHolder(view);
// vh.removeButton.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// removeItem(vh.getAdapterPosition());
// }
// });
// return vh;
// }
//
// @Override
// public void onBindViewHolder(final ViewHolder holder, int position) {
// final String appId = dataSet.get(position);
// holder.appId.setText(appId);
// }
//
// @Override
// public int getItemCount() {
// return dataSet.size();
// }
//
// static class ViewHolder extends RecyclerView.ViewHolder {
// private TextView appId;
// private ImageView removeButton;
// private ViewHolder(View itemView) {
// super(itemView);
// appId = itemView.findViewById(R.id.appid);
// removeButton = itemView.findViewById(R.id.remove_button);
// }
// }
// }
// Path: app/src/main/java/com/steevsapps/idledaddy/preferences/BlacklistDialog.java
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.preference.Preference;
import androidx.preference.PreferenceDialogFragmentCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.steevsapps.idledaddy.R;
import com.steevsapps.idledaddy.adapters.BlacklistAdapter;
package com.steevsapps.idledaddy.preferences;
public class BlacklistDialog extends PreferenceDialogFragmentCompat implements View.OnClickListener, EditText.OnEditorActionListener {
private final static String VALUE = "VALUE"; // Key to hold current value
private EditText input;
private ImageView addButton;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager; | private BlacklistAdapter adapter; |
appfoundry/android-nfc-lib | nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/NfcMessageUtility.java | // Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/InsufficientCapacityException.java
// public class InsufficientCapacityException extends Exception {
//
// public InsufficientCapacityException() {
// }
//
// public InsufficientCapacityException(String message) {
// super(message);
// }
//
// public InsufficientCapacityException(StackTraceElement[] stackTraceElements) {
// setStackTrace(stackTraceElements);
// }
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/ReadOnlyTagException.java
// public class ReadOnlyTagException extends TagNotWritableException {
//
// public ReadOnlyTagException() {
// }
//
// public ReadOnlyTagException(String message) {
// super(message);
// }
//
//
// }
| import android.nfc.FormatException;
import android.nfc.NdefMessage;
import org.jetbrains.annotations.NotNull;
import be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException;
import be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException; | /*
* NfcMessageUtility.java
* NfcLibrary project.
*
* Created by : Daneo van Overloop - 17/6/2014.
*
* The MIT License (MIT)
*
* Copyright (c) 2014 AppFoundry. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*/
package be.appfoundry.nfclibrary.utilities.interfaces;
/**
* Interface containing the highest level methods, providing the user with a total abstraction of the way NFC works, layer 3 in abstraction.
*/
public interface NfcMessageUtility {
/**
* @param urlAddress
* The url, auto-prefixed with the http://www. header
* @return true if successful
*/
NdefMessage createUri(@NotNull String urlAddress) throws FormatException;
/**
* Creates a telephone number - NdefMessage
*
* @param telephone
* number to create
* @return true if success
*/
NdefMessage createTel(@NotNull String telephone) throws FormatException;
/**
* Create SMS - NdefMessage. Due to a bug in Android this is not correctly implemented by the OS.
*
* @param message
* to send to the person
* @param number
* of the recipient
* @return true if success
*/
NdefMessage createSms(@NotNull String number, String message) throws FormatException;
/**
* Creates a Geolocation - NdefMessage.
* @param latitude
* maximum 6 decimals
* @param longitude
* maximum 6 DECIMALS
* @return true if success
*/
NdefMessage createGeolocation(Double latitude, Double longitude) throws FormatException;
/**
* Create recipient, subject and message email - NdefMessage
*
* @param recipient
* to whom the mail should be sent
* @param subject
* of the email
* @param message
* body of the email
* @return true if success
*/
NdefMessage createEmail(@NotNull String recipient, String subject, String message) throws FormatException;
/**
* Create the bluetooth address - NdefMessage
*
* @param macAddress
* to create NdefMessage. Must be in format XX:XX:XX:XX:XX:XX, separator may differ
* @return true if success
*/ | // Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/InsufficientCapacityException.java
// public class InsufficientCapacityException extends Exception {
//
// public InsufficientCapacityException() {
// }
//
// public InsufficientCapacityException(String message) {
// super(message);
// }
//
// public InsufficientCapacityException(StackTraceElement[] stackTraceElements) {
// setStackTrace(stackTraceElements);
// }
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/ReadOnlyTagException.java
// public class ReadOnlyTagException extends TagNotWritableException {
//
// public ReadOnlyTagException() {
// }
//
// public ReadOnlyTagException(String message) {
// super(message);
// }
//
//
// }
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/NfcMessageUtility.java
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import org.jetbrains.annotations.NotNull;
import be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException;
import be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException;
/*
* NfcMessageUtility.java
* NfcLibrary project.
*
* Created by : Daneo van Overloop - 17/6/2014.
*
* The MIT License (MIT)
*
* Copyright (c) 2014 AppFoundry. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*/
package be.appfoundry.nfclibrary.utilities.interfaces;
/**
* Interface containing the highest level methods, providing the user with a total abstraction of the way NFC works, layer 3 in abstraction.
*/
public interface NfcMessageUtility {
/**
* @param urlAddress
* The url, auto-prefixed with the http://www. header
* @return true if successful
*/
NdefMessage createUri(@NotNull String urlAddress) throws FormatException;
/**
* Creates a telephone number - NdefMessage
*
* @param telephone
* number to create
* @return true if success
*/
NdefMessage createTel(@NotNull String telephone) throws FormatException;
/**
* Create SMS - NdefMessage. Due to a bug in Android this is not correctly implemented by the OS.
*
* @param message
* to send to the person
* @param number
* of the recipient
* @return true if success
*/
NdefMessage createSms(@NotNull String number, String message) throws FormatException;
/**
* Creates a Geolocation - NdefMessage.
* @param latitude
* maximum 6 decimals
* @param longitude
* maximum 6 DECIMALS
* @return true if success
*/
NdefMessage createGeolocation(Double latitude, Double longitude) throws FormatException;
/**
* Create recipient, subject and message email - NdefMessage
*
* @param recipient
* to whom the mail should be sent
* @param subject
* of the email
* @param message
* body of the email
* @return true if success
*/
NdefMessage createEmail(@NotNull String recipient, String subject, String message) throws FormatException;
/**
* Create the bluetooth address - NdefMessage
*
* @param macAddress
* to create NdefMessage. Must be in format XX:XX:XX:XX:XX:XX, separator may differ
* @return true if success
*/ | NdefMessage createBluetoothAddress(@NotNull String macAddress) throws InsufficientCapacityException, FormatException, ReadOnlyTagException; |
appfoundry/android-nfc-lib | nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/NfcMessageUtility.java | // Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/InsufficientCapacityException.java
// public class InsufficientCapacityException extends Exception {
//
// public InsufficientCapacityException() {
// }
//
// public InsufficientCapacityException(String message) {
// super(message);
// }
//
// public InsufficientCapacityException(StackTraceElement[] stackTraceElements) {
// setStackTrace(stackTraceElements);
// }
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/ReadOnlyTagException.java
// public class ReadOnlyTagException extends TagNotWritableException {
//
// public ReadOnlyTagException() {
// }
//
// public ReadOnlyTagException(String message) {
// super(message);
// }
//
//
// }
| import android.nfc.FormatException;
import android.nfc.NdefMessage;
import org.jetbrains.annotations.NotNull;
import be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException;
import be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException; | /*
* NfcMessageUtility.java
* NfcLibrary project.
*
* Created by : Daneo van Overloop - 17/6/2014.
*
* The MIT License (MIT)
*
* Copyright (c) 2014 AppFoundry. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*/
package be.appfoundry.nfclibrary.utilities.interfaces;
/**
* Interface containing the highest level methods, providing the user with a total abstraction of the way NFC works, layer 3 in abstraction.
*/
public interface NfcMessageUtility {
/**
* @param urlAddress
* The url, auto-prefixed with the http://www. header
* @return true if successful
*/
NdefMessage createUri(@NotNull String urlAddress) throws FormatException;
/**
* Creates a telephone number - NdefMessage
*
* @param telephone
* number to create
* @return true if success
*/
NdefMessage createTel(@NotNull String telephone) throws FormatException;
/**
* Create SMS - NdefMessage. Due to a bug in Android this is not correctly implemented by the OS.
*
* @param message
* to send to the person
* @param number
* of the recipient
* @return true if success
*/
NdefMessage createSms(@NotNull String number, String message) throws FormatException;
/**
* Creates a Geolocation - NdefMessage.
* @param latitude
* maximum 6 decimals
* @param longitude
* maximum 6 DECIMALS
* @return true if success
*/
NdefMessage createGeolocation(Double latitude, Double longitude) throws FormatException;
/**
* Create recipient, subject and message email - NdefMessage
*
* @param recipient
* to whom the mail should be sent
* @param subject
* of the email
* @param message
* body of the email
* @return true if success
*/
NdefMessage createEmail(@NotNull String recipient, String subject, String message) throws FormatException;
/**
* Create the bluetooth address - NdefMessage
*
* @param macAddress
* to create NdefMessage. Must be in format XX:XX:XX:XX:XX:XX, separator may differ
* @return true if success
*/ | // Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/InsufficientCapacityException.java
// public class InsufficientCapacityException extends Exception {
//
// public InsufficientCapacityException() {
// }
//
// public InsufficientCapacityException(String message) {
// super(message);
// }
//
// public InsufficientCapacityException(StackTraceElement[] stackTraceElements) {
// setStackTrace(stackTraceElements);
// }
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/ReadOnlyTagException.java
// public class ReadOnlyTagException extends TagNotWritableException {
//
// public ReadOnlyTagException() {
// }
//
// public ReadOnlyTagException(String message) {
// super(message);
// }
//
//
// }
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/NfcMessageUtility.java
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import org.jetbrains.annotations.NotNull;
import be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException;
import be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException;
/*
* NfcMessageUtility.java
* NfcLibrary project.
*
* Created by : Daneo van Overloop - 17/6/2014.
*
* The MIT License (MIT)
*
* Copyright (c) 2014 AppFoundry. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*/
package be.appfoundry.nfclibrary.utilities.interfaces;
/**
* Interface containing the highest level methods, providing the user with a total abstraction of the way NFC works, layer 3 in abstraction.
*/
public interface NfcMessageUtility {
/**
* @param urlAddress
* The url, auto-prefixed with the http://www. header
* @return true if successful
*/
NdefMessage createUri(@NotNull String urlAddress) throws FormatException;
/**
* Creates a telephone number - NdefMessage
*
* @param telephone
* number to create
* @return true if success
*/
NdefMessage createTel(@NotNull String telephone) throws FormatException;
/**
* Create SMS - NdefMessage. Due to a bug in Android this is not correctly implemented by the OS.
*
* @param message
* to send to the person
* @param number
* of the recipient
* @return true if success
*/
NdefMessage createSms(@NotNull String number, String message) throws FormatException;
/**
* Creates a Geolocation - NdefMessage.
* @param latitude
* maximum 6 decimals
* @param longitude
* maximum 6 DECIMALS
* @return true if success
*/
NdefMessage createGeolocation(Double latitude, Double longitude) throws FormatException;
/**
* Create recipient, subject and message email - NdefMessage
*
* @param recipient
* to whom the mail should be sent
* @param subject
* of the email
* @param message
* body of the email
* @return true if success
*/
NdefMessage createEmail(@NotNull String recipient, String subject, String message) throws FormatException;
/**
* Create the bluetooth address - NdefMessage
*
* @param macAddress
* to create NdefMessage. Must be in format XX:XX:XX:XX:XX:XX, separator may differ
* @return true if success
*/ | NdefMessage createBluetoothAddress(@NotNull String macAddress) throws InsufficientCapacityException, FormatException, ReadOnlyTagException; |
appfoundry/android-nfc-lib | nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/sync/NfcReadUtilityImpl.java | // Path: nfclib/src/main/java/be/appfoundry/nfclibrary/constants/NfcType.java
// public class NfcType {
//
// /**
// * Type for the Bluetooth Application Record
// */
// public static final byte[] BLUETOOTH_AAR = "application/vnd.bluetooth.ep.oob".getBytes();
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/NfcReadUtility.java
// public interface NfcReadUtility {
//
// /**
// * Read data from received {@link android.content.Intent}
// *
// * @param nfcDataIntent
// * the intent containing the data to read
// *
// * @return the data in an array of {@link android.content.Intent}'s or an empty {@link android.util.SparseArray} array
// */
// android.util.SparseArray<String> readFromTagWithSparseArray(Intent nfcDataIntent);
//
// /**
// * Read data from received {@link android.content.Intent}
// * @param nfcDataIntent the intent containing the data to read
// * @return the data is either a filled or empty {@link java.util.Map} depending on whether parsing was successful
// */
// Map<Byte,String> readFromTagWithMap(Intent nfcDataIntent);
//
//
// /**
// * Retrieve the content type from the message
// * @param message type {@link be.appfoundry.nfclibrary.constants.NfcPayloadHeader}
// * @return {@link be.appfoundry.nfclibrary.constants.NfcPayloadHeader}
// */
// java.util.Iterator<Byte> retrieveMessageTypes(NdefMessage message);
//
// /**
// * Retrieve the actual message content
// * @param message to parse
// * @return the formatted message
// */
// String retrieveMessage(NdefMessage message);
// }
| import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import be.appfoundry.nfclibrary.constants.NfcType;
import be.appfoundry.nfclibrary.utilities.interfaces.NfcReadUtility;
import android.content.Intent;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Parcelable;
import android.util.SparseArray;
import org.jetbrains.annotations.NotNull; | @Override
public Iterator<Byte> retrieveMessageTypes(NdefMessage record) {
Collection<Byte> list = new ArrayList<Byte>();
for (NdefRecord ndefRecord : record.getRecords()) {
list.add(retrieveTypeByte(ndefRecord.getPayload()));
}
return list.iterator();
}
/**
* {@inheritDoc}
*/
@Override
public String retrieveMessage(NdefMessage message) {
return message.getRecords()[0] != null ? parseAccordingToHeader(message.getRecords()[0].getPayload()) : null;
}
private byte retrieveTypeByte(byte[] payload) {
if (payload.length > 0) {
return payload[0];
}
return -1;
}
private String parseAccordingToHeader(@NotNull byte[] payload) {
return (payload.length > 0) ? new String(payload, 0, payload.length, Charset.forName("US-ASCII")).trim() : "";
}
private String parseAccordingToType(NdefRecord obj) { | // Path: nfclib/src/main/java/be/appfoundry/nfclibrary/constants/NfcType.java
// public class NfcType {
//
// /**
// * Type for the Bluetooth Application Record
// */
// public static final byte[] BLUETOOTH_AAR = "application/vnd.bluetooth.ep.oob".getBytes();
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/NfcReadUtility.java
// public interface NfcReadUtility {
//
// /**
// * Read data from received {@link android.content.Intent}
// *
// * @param nfcDataIntent
// * the intent containing the data to read
// *
// * @return the data in an array of {@link android.content.Intent}'s or an empty {@link android.util.SparseArray} array
// */
// android.util.SparseArray<String> readFromTagWithSparseArray(Intent nfcDataIntent);
//
// /**
// * Read data from received {@link android.content.Intent}
// * @param nfcDataIntent the intent containing the data to read
// * @return the data is either a filled or empty {@link java.util.Map} depending on whether parsing was successful
// */
// Map<Byte,String> readFromTagWithMap(Intent nfcDataIntent);
//
//
// /**
// * Retrieve the content type from the message
// * @param message type {@link be.appfoundry.nfclibrary.constants.NfcPayloadHeader}
// * @return {@link be.appfoundry.nfclibrary.constants.NfcPayloadHeader}
// */
// java.util.Iterator<Byte> retrieveMessageTypes(NdefMessage message);
//
// /**
// * Retrieve the actual message content
// * @param message to parse
// * @return the formatted message
// */
// String retrieveMessage(NdefMessage message);
// }
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/sync/NfcReadUtilityImpl.java
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import be.appfoundry.nfclibrary.constants.NfcType;
import be.appfoundry.nfclibrary.utilities.interfaces.NfcReadUtility;
import android.content.Intent;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Parcelable;
import android.util.SparseArray;
import org.jetbrains.annotations.NotNull;
@Override
public Iterator<Byte> retrieveMessageTypes(NdefMessage record) {
Collection<Byte> list = new ArrayList<Byte>();
for (NdefRecord ndefRecord : record.getRecords()) {
list.add(retrieveTypeByte(ndefRecord.getPayload()));
}
return list.iterator();
}
/**
* {@inheritDoc}
*/
@Override
public String retrieveMessage(NdefMessage message) {
return message.getRecords()[0] != null ? parseAccordingToHeader(message.getRecords()[0].getPayload()) : null;
}
private byte retrieveTypeByte(byte[] payload) {
if (payload.length > 0) {
return payload[0];
}
return -1;
}
private String parseAccordingToHeader(@NotNull byte[] payload) {
return (payload.length > 0) ? new String(payload, 0, payload.length, Charset.forName("US-ASCII")).trim() : "";
}
private String parseAccordingToType(NdefRecord obj) { | if (Arrays.equals(obj.getType(), NfcType.BLUETOOTH_AAR)) { |
appfoundry/android-nfc-lib | nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/sync/WriteUtilityImpl.java | // Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/InsufficientCapacityException.java
// public class InsufficientCapacityException extends Exception {
//
// public InsufficientCapacityException() {
// }
//
// public InsufficientCapacityException(String message) {
// super(message);
// }
//
// public InsufficientCapacityException(StackTraceElement[] stackTraceElements) {
// setStackTrace(stackTraceElements);
// }
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/ReadOnlyTagException.java
// public class ReadOnlyTagException extends TagNotWritableException {
//
// public ReadOnlyTagException() {
// }
//
// public ReadOnlyTagException(String message) {
// super(message);
// }
//
//
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/NdefWrite.java
// public interface NdefWrite {
// /**
// * Write message to ndef
// *
// * @param message
// * to write
// * @param ndef
// * from tag to write to
// *
// * @return true if success, false if ndef == null || message == null
// *
// * @throws ReadOnlyTagException
// * if tag is read-only
// * @throws InsufficientCapacityException
// * if the tag's capacity is not sufficient
// * @throws FormatException
// * if the message is malformed
// */
// boolean writeToNdef(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException;
//
// /**
// * Write message to ndef and make readonly
// *
// * @see NdefWrite#writeToNdef(android.nfc.NdefMessage, android.nfc.tech.Ndef)
// */
// boolean writeToNdefAndMakeReadonly(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException;
//
// /**
// * Write the message to an NdefFormatable
// * @param message to write
// * @param ndefFormatable to write to
// * @return true if success, false if ndefFormatable == null || message == null
// * @throws FormatException
// */
// boolean writeToNdefFormatable(NdefMessage message, NdefFormatable ndefFormatable) throws FormatException;
//
// /**
// * Write the message to an NdefFormatable and make readonly
// * @see NdefWrite#writeToNdefFormatable(android.nfc.NdefMessage, android.nfc.tech.NdefFormatable)
// */
// boolean writeToNdefFormatableAndMakeReadonly(NdefMessage message, NdefFormatable ndefFormat) throws FormatException;
//
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/WriteUtility.java
// public interface WriteUtility extends NdefWrite {
//
//
// /**
// * Writes towards a {@link android.nfc.Tag}
// *
// * @param message
// * to write
// * @param tag
// * to write to
// *
// * @return true if success
// *
// * @see #writeToNdef(android.nfc.NdefMessage, android.nfc.tech.Ndef)
// */
// boolean writeSafelyToTag(NdefMessage message, Tag tag);
//
// /**
// * Write the given message to the tag
// *
// * @param message
// * to write
// * @param tag
// * to write to
// *
// * @return true if success
// *
// * @throws android.nfc.FormatException if the message is in an incorrect format
// * @throws be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException if there is not enough space available on the tag
// * @throws be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException when attempting to write to a read-only tag
// */
// boolean writeToTag(NdefMessage message, Tag tag) throws FormatException, ReadOnlyTagException, InsufficientCapacityException;
//
// /**
// * Used to mark the following operation as readonly
// * @return an instance of WriteUtility in order to chain
// */
// WriteUtility makeOperationReadOnly();
// }
| import be.appfoundry.nfclibrary.utilities.interfaces.NdefWrite;
import be.appfoundry.nfclibrary.utilities.interfaces.WriteUtility;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.util.Log;
import be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException;
import be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException; | /*
* WriteUtilityImpl.java
* NfcLibrary project.
*
* Created by : Daneo van Overloop - 17/6/2014.
*
* The MIT License (MIT)
*
* Copyright (c) 2014 AppFoundry. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*/
package be.appfoundry.nfclibrary.utilities.sync;
/**
* @author Daneo Van Overloop
* NfcLibrary
* Created on 11/04/14.
*/
public class WriteUtilityImpl implements WriteUtility {
private static final String TAG = WriteUtilityImpl.class.getName();
private boolean readOnly = false;
| // Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/InsufficientCapacityException.java
// public class InsufficientCapacityException extends Exception {
//
// public InsufficientCapacityException() {
// }
//
// public InsufficientCapacityException(String message) {
// super(message);
// }
//
// public InsufficientCapacityException(StackTraceElement[] stackTraceElements) {
// setStackTrace(stackTraceElements);
// }
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/ReadOnlyTagException.java
// public class ReadOnlyTagException extends TagNotWritableException {
//
// public ReadOnlyTagException() {
// }
//
// public ReadOnlyTagException(String message) {
// super(message);
// }
//
//
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/NdefWrite.java
// public interface NdefWrite {
// /**
// * Write message to ndef
// *
// * @param message
// * to write
// * @param ndef
// * from tag to write to
// *
// * @return true if success, false if ndef == null || message == null
// *
// * @throws ReadOnlyTagException
// * if tag is read-only
// * @throws InsufficientCapacityException
// * if the tag's capacity is not sufficient
// * @throws FormatException
// * if the message is malformed
// */
// boolean writeToNdef(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException;
//
// /**
// * Write message to ndef and make readonly
// *
// * @see NdefWrite#writeToNdef(android.nfc.NdefMessage, android.nfc.tech.Ndef)
// */
// boolean writeToNdefAndMakeReadonly(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException;
//
// /**
// * Write the message to an NdefFormatable
// * @param message to write
// * @param ndefFormatable to write to
// * @return true if success, false if ndefFormatable == null || message == null
// * @throws FormatException
// */
// boolean writeToNdefFormatable(NdefMessage message, NdefFormatable ndefFormatable) throws FormatException;
//
// /**
// * Write the message to an NdefFormatable and make readonly
// * @see NdefWrite#writeToNdefFormatable(android.nfc.NdefMessage, android.nfc.tech.NdefFormatable)
// */
// boolean writeToNdefFormatableAndMakeReadonly(NdefMessage message, NdefFormatable ndefFormat) throws FormatException;
//
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/WriteUtility.java
// public interface WriteUtility extends NdefWrite {
//
//
// /**
// * Writes towards a {@link android.nfc.Tag}
// *
// * @param message
// * to write
// * @param tag
// * to write to
// *
// * @return true if success
// *
// * @see #writeToNdef(android.nfc.NdefMessage, android.nfc.tech.Ndef)
// */
// boolean writeSafelyToTag(NdefMessage message, Tag tag);
//
// /**
// * Write the given message to the tag
// *
// * @param message
// * to write
// * @param tag
// * to write to
// *
// * @return true if success
// *
// * @throws android.nfc.FormatException if the message is in an incorrect format
// * @throws be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException if there is not enough space available on the tag
// * @throws be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException when attempting to write to a read-only tag
// */
// boolean writeToTag(NdefMessage message, Tag tag) throws FormatException, ReadOnlyTagException, InsufficientCapacityException;
//
// /**
// * Used to mark the following operation as readonly
// * @return an instance of WriteUtility in order to chain
// */
// WriteUtility makeOperationReadOnly();
// }
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/sync/WriteUtilityImpl.java
import be.appfoundry.nfclibrary.utilities.interfaces.NdefWrite;
import be.appfoundry.nfclibrary.utilities.interfaces.WriteUtility;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.util.Log;
import be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException;
import be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException;
/*
* WriteUtilityImpl.java
* NfcLibrary project.
*
* Created by : Daneo van Overloop - 17/6/2014.
*
* The MIT License (MIT)
*
* Copyright (c) 2014 AppFoundry. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*/
package be.appfoundry.nfclibrary.utilities.sync;
/**
* @author Daneo Van Overloop
* NfcLibrary
* Created on 11/04/14.
*/
public class WriteUtilityImpl implements WriteUtility {
private static final String TAG = WriteUtilityImpl.class.getName();
private boolean readOnly = false;
| private NdefWrite mNdefWrite; |
appfoundry/android-nfc-lib | nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/sync/WriteUtilityImpl.java | // Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/InsufficientCapacityException.java
// public class InsufficientCapacityException extends Exception {
//
// public InsufficientCapacityException() {
// }
//
// public InsufficientCapacityException(String message) {
// super(message);
// }
//
// public InsufficientCapacityException(StackTraceElement[] stackTraceElements) {
// setStackTrace(stackTraceElements);
// }
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/ReadOnlyTagException.java
// public class ReadOnlyTagException extends TagNotWritableException {
//
// public ReadOnlyTagException() {
// }
//
// public ReadOnlyTagException(String message) {
// super(message);
// }
//
//
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/NdefWrite.java
// public interface NdefWrite {
// /**
// * Write message to ndef
// *
// * @param message
// * to write
// * @param ndef
// * from tag to write to
// *
// * @return true if success, false if ndef == null || message == null
// *
// * @throws ReadOnlyTagException
// * if tag is read-only
// * @throws InsufficientCapacityException
// * if the tag's capacity is not sufficient
// * @throws FormatException
// * if the message is malformed
// */
// boolean writeToNdef(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException;
//
// /**
// * Write message to ndef and make readonly
// *
// * @see NdefWrite#writeToNdef(android.nfc.NdefMessage, android.nfc.tech.Ndef)
// */
// boolean writeToNdefAndMakeReadonly(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException;
//
// /**
// * Write the message to an NdefFormatable
// * @param message to write
// * @param ndefFormatable to write to
// * @return true if success, false if ndefFormatable == null || message == null
// * @throws FormatException
// */
// boolean writeToNdefFormatable(NdefMessage message, NdefFormatable ndefFormatable) throws FormatException;
//
// /**
// * Write the message to an NdefFormatable and make readonly
// * @see NdefWrite#writeToNdefFormatable(android.nfc.NdefMessage, android.nfc.tech.NdefFormatable)
// */
// boolean writeToNdefFormatableAndMakeReadonly(NdefMessage message, NdefFormatable ndefFormat) throws FormatException;
//
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/WriteUtility.java
// public interface WriteUtility extends NdefWrite {
//
//
// /**
// * Writes towards a {@link android.nfc.Tag}
// *
// * @param message
// * to write
// * @param tag
// * to write to
// *
// * @return true if success
// *
// * @see #writeToNdef(android.nfc.NdefMessage, android.nfc.tech.Ndef)
// */
// boolean writeSafelyToTag(NdefMessage message, Tag tag);
//
// /**
// * Write the given message to the tag
// *
// * @param message
// * to write
// * @param tag
// * to write to
// *
// * @return true if success
// *
// * @throws android.nfc.FormatException if the message is in an incorrect format
// * @throws be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException if there is not enough space available on the tag
// * @throws be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException when attempting to write to a read-only tag
// */
// boolean writeToTag(NdefMessage message, Tag tag) throws FormatException, ReadOnlyTagException, InsufficientCapacityException;
//
// /**
// * Used to mark the following operation as readonly
// * @return an instance of WriteUtility in order to chain
// */
// WriteUtility makeOperationReadOnly();
// }
| import be.appfoundry.nfclibrary.utilities.interfaces.NdefWrite;
import be.appfoundry.nfclibrary.utilities.interfaces.WriteUtility;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.util.Log;
import be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException;
import be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException; | /*
* WriteUtilityImpl.java
* NfcLibrary project.
*
* Created by : Daneo van Overloop - 17/6/2014.
*
* The MIT License (MIT)
*
* Copyright (c) 2014 AppFoundry. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*/
package be.appfoundry.nfclibrary.utilities.sync;
/**
* @author Daneo Van Overloop
* NfcLibrary
* Created on 11/04/14.
*/
public class WriteUtilityImpl implements WriteUtility {
private static final String TAG = WriteUtilityImpl.class.getName();
private boolean readOnly = false;
private NdefWrite mNdefWrite;
public WriteUtilityImpl() {
setNdefWrite(new NdefWriteImpl());
}
/**
* @param ndefWrite
* used to delegate writing to Tag
*
* @throws java.lang.NullPointerException
* when null
*/
public WriteUtilityImpl(NdefWrite ndefWrite) {
if (ndefWrite == null) {
throw new NullPointerException("WriteUtility cannot be null");
}
setNdefWrite(ndefWrite);
}
private void setNdefWrite(NdefWrite ndefWrite) {
this.mNdefWrite = ndefWrite;
}
@Override | // Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/InsufficientCapacityException.java
// public class InsufficientCapacityException extends Exception {
//
// public InsufficientCapacityException() {
// }
//
// public InsufficientCapacityException(String message) {
// super(message);
// }
//
// public InsufficientCapacityException(StackTraceElement[] stackTraceElements) {
// setStackTrace(stackTraceElements);
// }
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/ReadOnlyTagException.java
// public class ReadOnlyTagException extends TagNotWritableException {
//
// public ReadOnlyTagException() {
// }
//
// public ReadOnlyTagException(String message) {
// super(message);
// }
//
//
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/NdefWrite.java
// public interface NdefWrite {
// /**
// * Write message to ndef
// *
// * @param message
// * to write
// * @param ndef
// * from tag to write to
// *
// * @return true if success, false if ndef == null || message == null
// *
// * @throws ReadOnlyTagException
// * if tag is read-only
// * @throws InsufficientCapacityException
// * if the tag's capacity is not sufficient
// * @throws FormatException
// * if the message is malformed
// */
// boolean writeToNdef(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException;
//
// /**
// * Write message to ndef and make readonly
// *
// * @see NdefWrite#writeToNdef(android.nfc.NdefMessage, android.nfc.tech.Ndef)
// */
// boolean writeToNdefAndMakeReadonly(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException;
//
// /**
// * Write the message to an NdefFormatable
// * @param message to write
// * @param ndefFormatable to write to
// * @return true if success, false if ndefFormatable == null || message == null
// * @throws FormatException
// */
// boolean writeToNdefFormatable(NdefMessage message, NdefFormatable ndefFormatable) throws FormatException;
//
// /**
// * Write the message to an NdefFormatable and make readonly
// * @see NdefWrite#writeToNdefFormatable(android.nfc.NdefMessage, android.nfc.tech.NdefFormatable)
// */
// boolean writeToNdefFormatableAndMakeReadonly(NdefMessage message, NdefFormatable ndefFormat) throws FormatException;
//
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/WriteUtility.java
// public interface WriteUtility extends NdefWrite {
//
//
// /**
// * Writes towards a {@link android.nfc.Tag}
// *
// * @param message
// * to write
// * @param tag
// * to write to
// *
// * @return true if success
// *
// * @see #writeToNdef(android.nfc.NdefMessage, android.nfc.tech.Ndef)
// */
// boolean writeSafelyToTag(NdefMessage message, Tag tag);
//
// /**
// * Write the given message to the tag
// *
// * @param message
// * to write
// * @param tag
// * to write to
// *
// * @return true if success
// *
// * @throws android.nfc.FormatException if the message is in an incorrect format
// * @throws be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException if there is not enough space available on the tag
// * @throws be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException when attempting to write to a read-only tag
// */
// boolean writeToTag(NdefMessage message, Tag tag) throws FormatException, ReadOnlyTagException, InsufficientCapacityException;
//
// /**
// * Used to mark the following operation as readonly
// * @return an instance of WriteUtility in order to chain
// */
// WriteUtility makeOperationReadOnly();
// }
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/sync/WriteUtilityImpl.java
import be.appfoundry.nfclibrary.utilities.interfaces.NdefWrite;
import be.appfoundry.nfclibrary.utilities.interfaces.WriteUtility;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.util.Log;
import be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException;
import be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException;
/*
* WriteUtilityImpl.java
* NfcLibrary project.
*
* Created by : Daneo van Overloop - 17/6/2014.
*
* The MIT License (MIT)
*
* Copyright (c) 2014 AppFoundry. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*/
package be.appfoundry.nfclibrary.utilities.sync;
/**
* @author Daneo Van Overloop
* NfcLibrary
* Created on 11/04/14.
*/
public class WriteUtilityImpl implements WriteUtility {
private static final String TAG = WriteUtilityImpl.class.getName();
private boolean readOnly = false;
private NdefWrite mNdefWrite;
public WriteUtilityImpl() {
setNdefWrite(new NdefWriteImpl());
}
/**
* @param ndefWrite
* used to delegate writing to Tag
*
* @throws java.lang.NullPointerException
* when null
*/
public WriteUtilityImpl(NdefWrite ndefWrite) {
if (ndefWrite == null) {
throw new NullPointerException("WriteUtility cannot be null");
}
setNdefWrite(ndefWrite);
}
private void setNdefWrite(NdefWrite ndefWrite) {
this.mNdefWrite = ndefWrite;
}
@Override | public boolean writeToNdef(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException { |
appfoundry/android-nfc-lib | nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/sync/WriteUtilityImpl.java | // Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/InsufficientCapacityException.java
// public class InsufficientCapacityException extends Exception {
//
// public InsufficientCapacityException() {
// }
//
// public InsufficientCapacityException(String message) {
// super(message);
// }
//
// public InsufficientCapacityException(StackTraceElement[] stackTraceElements) {
// setStackTrace(stackTraceElements);
// }
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/ReadOnlyTagException.java
// public class ReadOnlyTagException extends TagNotWritableException {
//
// public ReadOnlyTagException() {
// }
//
// public ReadOnlyTagException(String message) {
// super(message);
// }
//
//
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/NdefWrite.java
// public interface NdefWrite {
// /**
// * Write message to ndef
// *
// * @param message
// * to write
// * @param ndef
// * from tag to write to
// *
// * @return true if success, false if ndef == null || message == null
// *
// * @throws ReadOnlyTagException
// * if tag is read-only
// * @throws InsufficientCapacityException
// * if the tag's capacity is not sufficient
// * @throws FormatException
// * if the message is malformed
// */
// boolean writeToNdef(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException;
//
// /**
// * Write message to ndef and make readonly
// *
// * @see NdefWrite#writeToNdef(android.nfc.NdefMessage, android.nfc.tech.Ndef)
// */
// boolean writeToNdefAndMakeReadonly(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException;
//
// /**
// * Write the message to an NdefFormatable
// * @param message to write
// * @param ndefFormatable to write to
// * @return true if success, false if ndefFormatable == null || message == null
// * @throws FormatException
// */
// boolean writeToNdefFormatable(NdefMessage message, NdefFormatable ndefFormatable) throws FormatException;
//
// /**
// * Write the message to an NdefFormatable and make readonly
// * @see NdefWrite#writeToNdefFormatable(android.nfc.NdefMessage, android.nfc.tech.NdefFormatable)
// */
// boolean writeToNdefFormatableAndMakeReadonly(NdefMessage message, NdefFormatable ndefFormat) throws FormatException;
//
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/WriteUtility.java
// public interface WriteUtility extends NdefWrite {
//
//
// /**
// * Writes towards a {@link android.nfc.Tag}
// *
// * @param message
// * to write
// * @param tag
// * to write to
// *
// * @return true if success
// *
// * @see #writeToNdef(android.nfc.NdefMessage, android.nfc.tech.Ndef)
// */
// boolean writeSafelyToTag(NdefMessage message, Tag tag);
//
// /**
// * Write the given message to the tag
// *
// * @param message
// * to write
// * @param tag
// * to write to
// *
// * @return true if success
// *
// * @throws android.nfc.FormatException if the message is in an incorrect format
// * @throws be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException if there is not enough space available on the tag
// * @throws be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException when attempting to write to a read-only tag
// */
// boolean writeToTag(NdefMessage message, Tag tag) throws FormatException, ReadOnlyTagException, InsufficientCapacityException;
//
// /**
// * Used to mark the following operation as readonly
// * @return an instance of WriteUtility in order to chain
// */
// WriteUtility makeOperationReadOnly();
// }
| import be.appfoundry.nfclibrary.utilities.interfaces.NdefWrite;
import be.appfoundry.nfclibrary.utilities.interfaces.WriteUtility;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.util.Log;
import be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException;
import be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException; | /*
* WriteUtilityImpl.java
* NfcLibrary project.
*
* Created by : Daneo van Overloop - 17/6/2014.
*
* The MIT License (MIT)
*
* Copyright (c) 2014 AppFoundry. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*/
package be.appfoundry.nfclibrary.utilities.sync;
/**
* @author Daneo Van Overloop
* NfcLibrary
* Created on 11/04/14.
*/
public class WriteUtilityImpl implements WriteUtility {
private static final String TAG = WriteUtilityImpl.class.getName();
private boolean readOnly = false;
private NdefWrite mNdefWrite;
public WriteUtilityImpl() {
setNdefWrite(new NdefWriteImpl());
}
/**
* @param ndefWrite
* used to delegate writing to Tag
*
* @throws java.lang.NullPointerException
* when null
*/
public WriteUtilityImpl(NdefWrite ndefWrite) {
if (ndefWrite == null) {
throw new NullPointerException("WriteUtility cannot be null");
}
setNdefWrite(ndefWrite);
}
private void setNdefWrite(NdefWrite ndefWrite) {
this.mNdefWrite = ndefWrite;
}
@Override | // Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/InsufficientCapacityException.java
// public class InsufficientCapacityException extends Exception {
//
// public InsufficientCapacityException() {
// }
//
// public InsufficientCapacityException(String message) {
// super(message);
// }
//
// public InsufficientCapacityException(StackTraceElement[] stackTraceElements) {
// setStackTrace(stackTraceElements);
// }
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/ReadOnlyTagException.java
// public class ReadOnlyTagException extends TagNotWritableException {
//
// public ReadOnlyTagException() {
// }
//
// public ReadOnlyTagException(String message) {
// super(message);
// }
//
//
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/NdefWrite.java
// public interface NdefWrite {
// /**
// * Write message to ndef
// *
// * @param message
// * to write
// * @param ndef
// * from tag to write to
// *
// * @return true if success, false if ndef == null || message == null
// *
// * @throws ReadOnlyTagException
// * if tag is read-only
// * @throws InsufficientCapacityException
// * if the tag's capacity is not sufficient
// * @throws FormatException
// * if the message is malformed
// */
// boolean writeToNdef(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException;
//
// /**
// * Write message to ndef and make readonly
// *
// * @see NdefWrite#writeToNdef(android.nfc.NdefMessage, android.nfc.tech.Ndef)
// */
// boolean writeToNdefAndMakeReadonly(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException;
//
// /**
// * Write the message to an NdefFormatable
// * @param message to write
// * @param ndefFormatable to write to
// * @return true if success, false if ndefFormatable == null || message == null
// * @throws FormatException
// */
// boolean writeToNdefFormatable(NdefMessage message, NdefFormatable ndefFormatable) throws FormatException;
//
// /**
// * Write the message to an NdefFormatable and make readonly
// * @see NdefWrite#writeToNdefFormatable(android.nfc.NdefMessage, android.nfc.tech.NdefFormatable)
// */
// boolean writeToNdefFormatableAndMakeReadonly(NdefMessage message, NdefFormatable ndefFormat) throws FormatException;
//
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/WriteUtility.java
// public interface WriteUtility extends NdefWrite {
//
//
// /**
// * Writes towards a {@link android.nfc.Tag}
// *
// * @param message
// * to write
// * @param tag
// * to write to
// *
// * @return true if success
// *
// * @see #writeToNdef(android.nfc.NdefMessage, android.nfc.tech.Ndef)
// */
// boolean writeSafelyToTag(NdefMessage message, Tag tag);
//
// /**
// * Write the given message to the tag
// *
// * @param message
// * to write
// * @param tag
// * to write to
// *
// * @return true if success
// *
// * @throws android.nfc.FormatException if the message is in an incorrect format
// * @throws be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException if there is not enough space available on the tag
// * @throws be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException when attempting to write to a read-only tag
// */
// boolean writeToTag(NdefMessage message, Tag tag) throws FormatException, ReadOnlyTagException, InsufficientCapacityException;
//
// /**
// * Used to mark the following operation as readonly
// * @return an instance of WriteUtility in order to chain
// */
// WriteUtility makeOperationReadOnly();
// }
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/sync/WriteUtilityImpl.java
import be.appfoundry.nfclibrary.utilities.interfaces.NdefWrite;
import be.appfoundry.nfclibrary.utilities.interfaces.WriteUtility;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.util.Log;
import be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException;
import be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException;
/*
* WriteUtilityImpl.java
* NfcLibrary project.
*
* Created by : Daneo van Overloop - 17/6/2014.
*
* The MIT License (MIT)
*
* Copyright (c) 2014 AppFoundry. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*/
package be.appfoundry.nfclibrary.utilities.sync;
/**
* @author Daneo Van Overloop
* NfcLibrary
* Created on 11/04/14.
*/
public class WriteUtilityImpl implements WriteUtility {
private static final String TAG = WriteUtilityImpl.class.getName();
private boolean readOnly = false;
private NdefWrite mNdefWrite;
public WriteUtilityImpl() {
setNdefWrite(new NdefWriteImpl());
}
/**
* @param ndefWrite
* used to delegate writing to Tag
*
* @throws java.lang.NullPointerException
* when null
*/
public WriteUtilityImpl(NdefWrite ndefWrite) {
if (ndefWrite == null) {
throw new NullPointerException("WriteUtility cannot be null");
}
setNdefWrite(ndefWrite);
}
private void setNdefWrite(NdefWrite ndefWrite) {
this.mNdefWrite = ndefWrite;
}
@Override | public boolean writeToNdef(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException { |
appfoundry/android-nfc-lib | nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/WriteUtility.java | // Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/InsufficientCapacityException.java
// public class InsufficientCapacityException extends Exception {
//
// public InsufficientCapacityException() {
// }
//
// public InsufficientCapacityException(String message) {
// super(message);
// }
//
// public InsufficientCapacityException(StackTraceElement[] stackTraceElements) {
// setStackTrace(stackTraceElements);
// }
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/ReadOnlyTagException.java
// public class ReadOnlyTagException extends TagNotWritableException {
//
// public ReadOnlyTagException() {
// }
//
// public ReadOnlyTagException(String message) {
// super(message);
// }
//
//
// }
| import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.Tag;
import be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException;
import be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException; | /*
* WriteUtility.java
* NfcLibrary project.
*
* Created by : Daneo van Overloop - 17/6/2014.
*
* The MIT License (MIT)
*
* Copyright (c) 2014 AppFoundry. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*/
package be.appfoundry.nfclibrary.utilities.interfaces;
/**
* Interface containing a few convenience methods for the user. Layer 2 in abstraction.
*/
public interface WriteUtility extends NdefWrite {
/**
* Writes towards a {@link android.nfc.Tag}
*
* @param message
* to write
* @param tag
* to write to
*
* @return true if success
*
* @see #writeToNdef(android.nfc.NdefMessage, android.nfc.tech.Ndef)
*/
boolean writeSafelyToTag(NdefMessage message, Tag tag);
/**
* Write the given message to the tag
*
* @param message
* to write
* @param tag
* to write to
*
* @return true if success
*
* @throws android.nfc.FormatException if the message is in an incorrect format
* @throws be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException if there is not enough space available on the tag
* @throws be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException when attempting to write to a read-only tag
*/ | // Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/InsufficientCapacityException.java
// public class InsufficientCapacityException extends Exception {
//
// public InsufficientCapacityException() {
// }
//
// public InsufficientCapacityException(String message) {
// super(message);
// }
//
// public InsufficientCapacityException(StackTraceElement[] stackTraceElements) {
// setStackTrace(stackTraceElements);
// }
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/ReadOnlyTagException.java
// public class ReadOnlyTagException extends TagNotWritableException {
//
// public ReadOnlyTagException() {
// }
//
// public ReadOnlyTagException(String message) {
// super(message);
// }
//
//
// }
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/WriteUtility.java
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.Tag;
import be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException;
import be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException;
/*
* WriteUtility.java
* NfcLibrary project.
*
* Created by : Daneo van Overloop - 17/6/2014.
*
* The MIT License (MIT)
*
* Copyright (c) 2014 AppFoundry. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*/
package be.appfoundry.nfclibrary.utilities.interfaces;
/**
* Interface containing a few convenience methods for the user. Layer 2 in abstraction.
*/
public interface WriteUtility extends NdefWrite {
/**
* Writes towards a {@link android.nfc.Tag}
*
* @param message
* to write
* @param tag
* to write to
*
* @return true if success
*
* @see #writeToNdef(android.nfc.NdefMessage, android.nfc.tech.Ndef)
*/
boolean writeSafelyToTag(NdefMessage message, Tag tag);
/**
* Write the given message to the tag
*
* @param message
* to write
* @param tag
* to write to
*
* @return true if success
*
* @throws android.nfc.FormatException if the message is in an incorrect format
* @throws be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException if there is not enough space available on the tag
* @throws be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException when attempting to write to a read-only tag
*/ | boolean writeToTag(NdefMessage message, Tag tag) throws FormatException, ReadOnlyTagException, InsufficientCapacityException; |
appfoundry/android-nfc-lib | nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/WriteUtility.java | // Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/InsufficientCapacityException.java
// public class InsufficientCapacityException extends Exception {
//
// public InsufficientCapacityException() {
// }
//
// public InsufficientCapacityException(String message) {
// super(message);
// }
//
// public InsufficientCapacityException(StackTraceElement[] stackTraceElements) {
// setStackTrace(stackTraceElements);
// }
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/ReadOnlyTagException.java
// public class ReadOnlyTagException extends TagNotWritableException {
//
// public ReadOnlyTagException() {
// }
//
// public ReadOnlyTagException(String message) {
// super(message);
// }
//
//
// }
| import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.Tag;
import be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException;
import be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException; | /*
* WriteUtility.java
* NfcLibrary project.
*
* Created by : Daneo van Overloop - 17/6/2014.
*
* The MIT License (MIT)
*
* Copyright (c) 2014 AppFoundry. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*/
package be.appfoundry.nfclibrary.utilities.interfaces;
/**
* Interface containing a few convenience methods for the user. Layer 2 in abstraction.
*/
public interface WriteUtility extends NdefWrite {
/**
* Writes towards a {@link android.nfc.Tag}
*
* @param message
* to write
* @param tag
* to write to
*
* @return true if success
*
* @see #writeToNdef(android.nfc.NdefMessage, android.nfc.tech.Ndef)
*/
boolean writeSafelyToTag(NdefMessage message, Tag tag);
/**
* Write the given message to the tag
*
* @param message
* to write
* @param tag
* to write to
*
* @return true if success
*
* @throws android.nfc.FormatException if the message is in an incorrect format
* @throws be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException if there is not enough space available on the tag
* @throws be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException when attempting to write to a read-only tag
*/ | // Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/InsufficientCapacityException.java
// public class InsufficientCapacityException extends Exception {
//
// public InsufficientCapacityException() {
// }
//
// public InsufficientCapacityException(String message) {
// super(message);
// }
//
// public InsufficientCapacityException(StackTraceElement[] stackTraceElements) {
// setStackTrace(stackTraceElements);
// }
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/ReadOnlyTagException.java
// public class ReadOnlyTagException extends TagNotWritableException {
//
// public ReadOnlyTagException() {
// }
//
// public ReadOnlyTagException(String message) {
// super(message);
// }
//
//
// }
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/WriteUtility.java
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.Tag;
import be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException;
import be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException;
/*
* WriteUtility.java
* NfcLibrary project.
*
* Created by : Daneo van Overloop - 17/6/2014.
*
* The MIT License (MIT)
*
* Copyright (c) 2014 AppFoundry. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*/
package be.appfoundry.nfclibrary.utilities.interfaces;
/**
* Interface containing a few convenience methods for the user. Layer 2 in abstraction.
*/
public interface WriteUtility extends NdefWrite {
/**
* Writes towards a {@link android.nfc.Tag}
*
* @param message
* to write
* @param tag
* to write to
*
* @return true if success
*
* @see #writeToNdef(android.nfc.NdefMessage, android.nfc.tech.Ndef)
*/
boolean writeSafelyToTag(NdefMessage message, Tag tag);
/**
* Write the given message to the tag
*
* @param message
* to write
* @param tag
* to write to
*
* @return true if success
*
* @throws android.nfc.FormatException if the message is in an incorrect format
* @throws be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException if there is not enough space available on the tag
* @throws be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException when attempting to write to a read-only tag
*/ | boolean writeToTag(NdefMessage message, Tag tag) throws FormatException, ReadOnlyTagException, InsufficientCapacityException; |
appfoundry/android-nfc-lib | nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/sync/NdefWriteImpl.java | // Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/InsufficientCapacityException.java
// public class InsufficientCapacityException extends Exception {
//
// public InsufficientCapacityException() {
// }
//
// public InsufficientCapacityException(String message) {
// super(message);
// }
//
// public InsufficientCapacityException(StackTraceElement[] stackTraceElements) {
// setStackTrace(stackTraceElements);
// }
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/ReadOnlyTagException.java
// public class ReadOnlyTagException extends TagNotWritableException {
//
// public ReadOnlyTagException() {
// }
//
// public ReadOnlyTagException(String message) {
// super(message);
// }
//
//
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/NdefWrite.java
// public interface NdefWrite {
// /**
// * Write message to ndef
// *
// * @param message
// * to write
// * @param ndef
// * from tag to write to
// *
// * @return true if success, false if ndef == null || message == null
// *
// * @throws ReadOnlyTagException
// * if tag is read-only
// * @throws InsufficientCapacityException
// * if the tag's capacity is not sufficient
// * @throws FormatException
// * if the message is malformed
// */
// boolean writeToNdef(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException;
//
// /**
// * Write message to ndef and make readonly
// *
// * @see NdefWrite#writeToNdef(android.nfc.NdefMessage, android.nfc.tech.Ndef)
// */
// boolean writeToNdefAndMakeReadonly(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException;
//
// /**
// * Write the message to an NdefFormatable
// * @param message to write
// * @param ndefFormatable to write to
// * @return true if success, false if ndefFormatable == null || message == null
// * @throws FormatException
// */
// boolean writeToNdefFormatable(NdefMessage message, NdefFormatable ndefFormatable) throws FormatException;
//
// /**
// * Write the message to an NdefFormatable and make readonly
// * @see NdefWrite#writeToNdefFormatable(android.nfc.NdefMessage, android.nfc.tech.NdefFormatable)
// */
// boolean writeToNdefFormatableAndMakeReadonly(NdefMessage message, NdefFormatable ndefFormat) throws FormatException;
//
// }
| import be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException;
import be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException;
import be.appfoundry.nfclibrary.utilities.interfaces.NdefWrite;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.TagLostException;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.util.Log;
import java.io.IOException; | /*
* NdefWriteImpl.java
* NfcLibrary project.
*
* Created by : Daneo van Overloop - 17/6/2014.
*
* The MIT License (MIT)
*
* Copyright (c) 2014 AppFoundry. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*/
package be.appfoundry.nfclibrary.utilities.sync;
/**
* Class used for writing the message towards an NFC tag
* @author Daneo Van Overloop
* NfcLibrary
*/
public class NdefWriteImpl implements NdefWrite {
private static final String TAG = NdefWriteImpl.class.getName();
private boolean mReadOnly = false;
/**
* Instantiates a new NdefWriteImpl.
*/
public NdefWriteImpl() {
}
/**
* {@inheritDoc}
*/
@Override | // Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/InsufficientCapacityException.java
// public class InsufficientCapacityException extends Exception {
//
// public InsufficientCapacityException() {
// }
//
// public InsufficientCapacityException(String message) {
// super(message);
// }
//
// public InsufficientCapacityException(StackTraceElement[] stackTraceElements) {
// setStackTrace(stackTraceElements);
// }
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/ReadOnlyTagException.java
// public class ReadOnlyTagException extends TagNotWritableException {
//
// public ReadOnlyTagException() {
// }
//
// public ReadOnlyTagException(String message) {
// super(message);
// }
//
//
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/NdefWrite.java
// public interface NdefWrite {
// /**
// * Write message to ndef
// *
// * @param message
// * to write
// * @param ndef
// * from tag to write to
// *
// * @return true if success, false if ndef == null || message == null
// *
// * @throws ReadOnlyTagException
// * if tag is read-only
// * @throws InsufficientCapacityException
// * if the tag's capacity is not sufficient
// * @throws FormatException
// * if the message is malformed
// */
// boolean writeToNdef(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException;
//
// /**
// * Write message to ndef and make readonly
// *
// * @see NdefWrite#writeToNdef(android.nfc.NdefMessage, android.nfc.tech.Ndef)
// */
// boolean writeToNdefAndMakeReadonly(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException;
//
// /**
// * Write the message to an NdefFormatable
// * @param message to write
// * @param ndefFormatable to write to
// * @return true if success, false if ndefFormatable == null || message == null
// * @throws FormatException
// */
// boolean writeToNdefFormatable(NdefMessage message, NdefFormatable ndefFormatable) throws FormatException;
//
// /**
// * Write the message to an NdefFormatable and make readonly
// * @see NdefWrite#writeToNdefFormatable(android.nfc.NdefMessage, android.nfc.tech.NdefFormatable)
// */
// boolean writeToNdefFormatableAndMakeReadonly(NdefMessage message, NdefFormatable ndefFormat) throws FormatException;
//
// }
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/sync/NdefWriteImpl.java
import be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException;
import be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException;
import be.appfoundry.nfclibrary.utilities.interfaces.NdefWrite;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.TagLostException;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.util.Log;
import java.io.IOException;
/*
* NdefWriteImpl.java
* NfcLibrary project.
*
* Created by : Daneo van Overloop - 17/6/2014.
*
* The MIT License (MIT)
*
* Copyright (c) 2014 AppFoundry. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*/
package be.appfoundry.nfclibrary.utilities.sync;
/**
* Class used for writing the message towards an NFC tag
* @author Daneo Van Overloop
* NfcLibrary
*/
public class NdefWriteImpl implements NdefWrite {
private static final String TAG = NdefWriteImpl.class.getName();
private boolean mReadOnly = false;
/**
* Instantiates a new NdefWriteImpl.
*/
public NdefWriteImpl() {
}
/**
* {@inheritDoc}
*/
@Override | public boolean writeToNdef(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException { |
appfoundry/android-nfc-lib | nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/sync/NdefWriteImpl.java | // Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/InsufficientCapacityException.java
// public class InsufficientCapacityException extends Exception {
//
// public InsufficientCapacityException() {
// }
//
// public InsufficientCapacityException(String message) {
// super(message);
// }
//
// public InsufficientCapacityException(StackTraceElement[] stackTraceElements) {
// setStackTrace(stackTraceElements);
// }
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/ReadOnlyTagException.java
// public class ReadOnlyTagException extends TagNotWritableException {
//
// public ReadOnlyTagException() {
// }
//
// public ReadOnlyTagException(String message) {
// super(message);
// }
//
//
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/NdefWrite.java
// public interface NdefWrite {
// /**
// * Write message to ndef
// *
// * @param message
// * to write
// * @param ndef
// * from tag to write to
// *
// * @return true if success, false if ndef == null || message == null
// *
// * @throws ReadOnlyTagException
// * if tag is read-only
// * @throws InsufficientCapacityException
// * if the tag's capacity is not sufficient
// * @throws FormatException
// * if the message is malformed
// */
// boolean writeToNdef(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException;
//
// /**
// * Write message to ndef and make readonly
// *
// * @see NdefWrite#writeToNdef(android.nfc.NdefMessage, android.nfc.tech.Ndef)
// */
// boolean writeToNdefAndMakeReadonly(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException;
//
// /**
// * Write the message to an NdefFormatable
// * @param message to write
// * @param ndefFormatable to write to
// * @return true if success, false if ndefFormatable == null || message == null
// * @throws FormatException
// */
// boolean writeToNdefFormatable(NdefMessage message, NdefFormatable ndefFormatable) throws FormatException;
//
// /**
// * Write the message to an NdefFormatable and make readonly
// * @see NdefWrite#writeToNdefFormatable(android.nfc.NdefMessage, android.nfc.tech.NdefFormatable)
// */
// boolean writeToNdefFormatableAndMakeReadonly(NdefMessage message, NdefFormatable ndefFormat) throws FormatException;
//
// }
| import be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException;
import be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException;
import be.appfoundry.nfclibrary.utilities.interfaces.NdefWrite;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.TagLostException;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.util.Log;
import java.io.IOException; | /*
* NdefWriteImpl.java
* NfcLibrary project.
*
* Created by : Daneo van Overloop - 17/6/2014.
*
* The MIT License (MIT)
*
* Copyright (c) 2014 AppFoundry. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*/
package be.appfoundry.nfclibrary.utilities.sync;
/**
* Class used for writing the message towards an NFC tag
* @author Daneo Van Overloop
* NfcLibrary
*/
public class NdefWriteImpl implements NdefWrite {
private static final String TAG = NdefWriteImpl.class.getName();
private boolean mReadOnly = false;
/**
* Instantiates a new NdefWriteImpl.
*/
public NdefWriteImpl() {
}
/**
* {@inheritDoc}
*/
@Override | // Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/InsufficientCapacityException.java
// public class InsufficientCapacityException extends Exception {
//
// public InsufficientCapacityException() {
// }
//
// public InsufficientCapacityException(String message) {
// super(message);
// }
//
// public InsufficientCapacityException(StackTraceElement[] stackTraceElements) {
// setStackTrace(stackTraceElements);
// }
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/exceptions/ReadOnlyTagException.java
// public class ReadOnlyTagException extends TagNotWritableException {
//
// public ReadOnlyTagException() {
// }
//
// public ReadOnlyTagException(String message) {
// super(message);
// }
//
//
// }
//
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/interfaces/NdefWrite.java
// public interface NdefWrite {
// /**
// * Write message to ndef
// *
// * @param message
// * to write
// * @param ndef
// * from tag to write to
// *
// * @return true if success, false if ndef == null || message == null
// *
// * @throws ReadOnlyTagException
// * if tag is read-only
// * @throws InsufficientCapacityException
// * if the tag's capacity is not sufficient
// * @throws FormatException
// * if the message is malformed
// */
// boolean writeToNdef(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException;
//
// /**
// * Write message to ndef and make readonly
// *
// * @see NdefWrite#writeToNdef(android.nfc.NdefMessage, android.nfc.tech.Ndef)
// */
// boolean writeToNdefAndMakeReadonly(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException;
//
// /**
// * Write the message to an NdefFormatable
// * @param message to write
// * @param ndefFormatable to write to
// * @return true if success, false if ndefFormatable == null || message == null
// * @throws FormatException
// */
// boolean writeToNdefFormatable(NdefMessage message, NdefFormatable ndefFormatable) throws FormatException;
//
// /**
// * Write the message to an NdefFormatable and make readonly
// * @see NdefWrite#writeToNdefFormatable(android.nfc.NdefMessage, android.nfc.tech.NdefFormatable)
// */
// boolean writeToNdefFormatableAndMakeReadonly(NdefMessage message, NdefFormatable ndefFormat) throws FormatException;
//
// }
// Path: nfclib/src/main/java/be/appfoundry/nfclibrary/utilities/sync/NdefWriteImpl.java
import be.appfoundry.nfclibrary.exceptions.InsufficientCapacityException;
import be.appfoundry.nfclibrary.exceptions.ReadOnlyTagException;
import be.appfoundry.nfclibrary.utilities.interfaces.NdefWrite;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.TagLostException;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.util.Log;
import java.io.IOException;
/*
* NdefWriteImpl.java
* NfcLibrary project.
*
* Created by : Daneo van Overloop - 17/6/2014.
*
* The MIT License (MIT)
*
* Copyright (c) 2014 AppFoundry. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*/
package be.appfoundry.nfclibrary.utilities.sync;
/**
* Class used for writing the message towards an NFC tag
* @author Daneo Van Overloop
* NfcLibrary
*/
public class NdefWriteImpl implements NdefWrite {
private static final String TAG = NdefWriteImpl.class.getName();
private boolean mReadOnly = false;
/**
* Instantiates a new NdefWriteImpl.
*/
public NdefWriteImpl() {
}
/**
* {@inheritDoc}
*/
@Override | public boolean writeToNdef(NdefMessage message, Ndef ndef) throws ReadOnlyTagException, InsufficientCapacityException, FormatException { |
turesheim/eclipse-timekeeper | net.resheim.eclipse.timekeeper.db/src/main/java/net/resheim/eclipse/timekeeper/db/PreferenceInitializer.java | // Path: net.resheim.eclipse.timekeeper.db/src/main/java/net/resheim/eclipse/timekeeper/db/report/ReportTemplate.java
// public class ReportTemplate implements Serializable {
//
// private static final long serialVersionUID = 3796302809926743470L;
//
// String name;
// String code;
// Type type;
//
// public enum Type {
// /** Plain text */
// TEXT,
// /** Hyper Text Markup Language */
// HTML,
// /** Rich Text Format */
// RTF
// }
//
// public ReportTemplate(String name, Type type, String code) {
// super();
// this.name = name;
// this.setType(type);
// this.code = code;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getCode() {
// return code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public Type getType() {
// return type;
// }
//
// public void setType(Type type) {
// this.type = type;
// }
//
// }
| import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Enumeration;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.ui.preferences.ScopedPreferenceStore;
import org.osgi.framework.Bundle;
import net.resheim.eclipse.timekeeper.db.report.ReportTemplate; | /*******************************************************************************
* Copyright © 2018-2019 Torkild U. Resheim
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Torkild U. Resheim - initial API and implementation
*******************************************************************************/
package net.resheim.eclipse.timekeeper.db;
/**
* Specifies default values for the core Timekeeper preferences.
*/
public class PreferenceInitializer extends AbstractPreferenceInitializer {
@Override
public void initializeDefaultPreferences() {
IPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, TimekeeperPlugin.BUNDLE_ID);
try {
store.setDefault(TimekeeperPlugin.PREF_DATABASE_LOCATION, TimekeeperPlugin.PREF_DATABASE_LOCATION_SHARED);
store.setDefault(TimekeeperPlugin.PREF_DATABASE_LOCATION_URL,
TimekeeperPlugin.getDefault().getSharedLocation());
// read from the "templates" directory and create a list of templates – all files stored there
// will be registered.
Bundle bundle = TimekeeperPlugin.getDefault().getBundle();
Enumeration<URL> findEntries = bundle.findEntries("templates", "*", true); | // Path: net.resheim.eclipse.timekeeper.db/src/main/java/net/resheim/eclipse/timekeeper/db/report/ReportTemplate.java
// public class ReportTemplate implements Serializable {
//
// private static final long serialVersionUID = 3796302809926743470L;
//
// String name;
// String code;
// Type type;
//
// public enum Type {
// /** Plain text */
// TEXT,
// /** Hyper Text Markup Language */
// HTML,
// /** Rich Text Format */
// RTF
// }
//
// public ReportTemplate(String name, Type type, String code) {
// super();
// this.name = name;
// this.setType(type);
// this.code = code;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getCode() {
// return code;
// }
//
// public void setCode(String code) {
// this.code = code;
// }
//
// public Type getType() {
// return type;
// }
//
// public void setType(Type type) {
// this.type = type;
// }
//
// }
// Path: net.resheim.eclipse.timekeeper.db/src/main/java/net/resheim/eclipse/timekeeper/db/PreferenceInitializer.java
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Enumeration;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.ui.preferences.ScopedPreferenceStore;
import org.osgi.framework.Bundle;
import net.resheim.eclipse.timekeeper.db.report.ReportTemplate;
/*******************************************************************************
* Copyright © 2018-2019 Torkild U. Resheim
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Torkild U. Resheim - initial API and implementation
*******************************************************************************/
package net.resheim.eclipse.timekeeper.db;
/**
* Specifies default values for the core Timekeeper preferences.
*/
public class PreferenceInitializer extends AbstractPreferenceInitializer {
@Override
public void initializeDefaultPreferences() {
IPreferenceStore store = new ScopedPreferenceStore(InstanceScope.INSTANCE, TimekeeperPlugin.BUNDLE_ID);
try {
store.setDefault(TimekeeperPlugin.PREF_DATABASE_LOCATION, TimekeeperPlugin.PREF_DATABASE_LOCATION_SHARED);
store.setDefault(TimekeeperPlugin.PREF_DATABASE_LOCATION_URL,
TimekeeperPlugin.getDefault().getSharedLocation());
// read from the "templates" directory and create a list of templates – all files stored there
// will be registered.
Bundle bundle = TimekeeperPlugin.getDefault().getBundle();
Enumeration<URL> findEntries = bundle.findEntries("templates", "*", true); | ArrayList<ReportTemplate> templates = new ArrayList<>(); |
turesheim/eclipse-timekeeper | net.resheim.eclipse.timekeeper.db/src/main/java/net/resheim/eclipse/timekeeper/db/model/Activity.java | // Path: net.resheim.eclipse.timekeeper.db/src/main/java/net/resheim/eclipse/timekeeper/db/converters/LocalDateTimeAttributeConverter.java
// @Converter
// public class LocalDateTimeAttributeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
//
// @Override
// public Timestamp convertToDatabaseColumn(LocalDateTime locDateTime) {
// return (locDateTime == null ? null : Timestamp.valueOf(locDateTime));
// }
//
// @Override
// public LocalDateTime convertToEntityAttribute(Timestamp sqlTimestamp) {
// return (sqlTimestamp == null ? null : sqlTimestamp.toLocalDateTime());
// }
// }
| import java.io.Serializable;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.UuidGenerator;
import net.resheim.eclipse.timekeeper.db.converters.LocalDateTimeAttributeConverter; | /*******************************************************************************
* Copyright © 2016-2020 Torkild U. Resheim
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Torkild U. Resheim - initial API and implementation
*******************************************************************************/
package net.resheim.eclipse.timekeeper.db.model;
/**
* The {@link Activity} type represents a period of work on a task. It holds the
* start time, and the stop time. An activity can stretch over several days,
* however that should typically not be the case. Multiple activities can be
* assign to the same {@link Task}, on the same day.
*
* @author Torkild U. Resheim
*/
@Entity
@Table(name = "ACTIVITY")
@UuidGenerator(name = "uuid")
public class Activity implements Comparable<Activity>, Serializable {
private static final long serialVersionUID = 7770745026684660897L;
@Id
@GeneratedValue(generator = "uuid")
@Column(name = "ID")
private String id;
/** The time the activity was started */
@Column(name = "START_TIME") | // Path: net.resheim.eclipse.timekeeper.db/src/main/java/net/resheim/eclipse/timekeeper/db/converters/LocalDateTimeAttributeConverter.java
// @Converter
// public class LocalDateTimeAttributeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
//
// @Override
// public Timestamp convertToDatabaseColumn(LocalDateTime locDateTime) {
// return (locDateTime == null ? null : Timestamp.valueOf(locDateTime));
// }
//
// @Override
// public LocalDateTime convertToEntityAttribute(Timestamp sqlTimestamp) {
// return (sqlTimestamp == null ? null : sqlTimestamp.toLocalDateTime());
// }
// }
// Path: net.resheim.eclipse.timekeeper.db/src/main/java/net/resheim/eclipse/timekeeper/db/model/Activity.java
import java.io.Serializable;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.eclipse.persistence.annotations.UuidGenerator;
import net.resheim.eclipse.timekeeper.db.converters.LocalDateTimeAttributeConverter;
/*******************************************************************************
* Copyright © 2016-2020 Torkild U. Resheim
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Torkild U. Resheim - initial API and implementation
*******************************************************************************/
package net.resheim.eclipse.timekeeper.db.model;
/**
* The {@link Activity} type represents a period of work on a task. It holds the
* start time, and the stop time. An activity can stretch over several days,
* however that should typically not be the case. Multiple activities can be
* assign to the same {@link Task}, on the same day.
*
* @author Torkild U. Resheim
*/
@Entity
@Table(name = "ACTIVITY")
@UuidGenerator(name = "uuid")
public class Activity implements Comparable<Activity>, Serializable {
private static final long serialVersionUID = 7770745026684660897L;
@Id
@GeneratedValue(generator = "uuid")
@Column(name = "ID")
private String id;
/** The time the activity was started */
@Column(name = "START_TIME") | @Convert(converter = LocalDateTimeAttributeConverter.class) |
endgameinc/binarypig | binarypig/src/main/java/com/endgame/binarypig/loaders/AbstractExecutingLoader.java | // Path: binarypig/src/main/java/com/endgame/binarypig/util/ProgramExector.java
// public class ProgramExector extends Thread
// {
// int retVal = -1;
// long endtime;
// boolean timedOut = false;
//
// Process proc;
// OutputStream stdin;
// InputStream stdout;
// InputStream stderr;
//
// public ProgramExector(String[] cmd, long timeoutMS) throws IOException{
// if(timeoutMS <= 0 || (System.currentTimeMillis() + timeoutMS) <= 0){
// this.endtime = Long.MAX_VALUE;
// }
// else{
// this.endtime = (System.currentTimeMillis() + timeoutMS);
// }
//
// proc = Runtime.getRuntime().exec(cmd);
// stdin = new BufferedOutputStream(proc.getOutputStream());
// stdout = proc.getInputStream();
// stderr = proc.getErrorStream();
// }
//
// @Override
// public void run() {
// while(true)
// {
// try {
// retVal = proc.exitValue();
// // process finished!
// break;
// } catch (IllegalThreadStateException e)
// {
// // process is still running...
// if(System.currentTimeMillis() >= endtime){
// // Process timed out
// timedOut = true;
// proc.destroy();
// retVal = -1;
// break;
// }
// else
// {
// try {
// Thread.sleep(10);
// } catch (InterruptedException e1) {
// throw new RuntimeException(e1);
// }
// }
// }
// }
// }
//
// public boolean isTimedOut() {
// return timedOut;
// }
//
// public InputStream getStderr() {
// return stderr;
// }
//
// public OutputStream getStdin() {
// return stdin;
// }
//
// public InputStream getStdout() {
// return stdout;
// }
//
// public int getRetVal() {
// return retVal;
// }
//
// public void closeStreams()
// {
// IOUtils.closeStream(getStderr());
// IOUtils.closeStream(getStdin());
// IOUtils.closeStream(getStdout());
// }
// }
//
// Path: binarypig/src/main/java/com/endgame/binarypig/util/StreamUtils.java
// public class StreamUtils {
//
// public static String drainInputStream(InputStream stream)
// {
// StringBuilder buf = new StringBuilder();
// try {
// while(stream.available() > 0)
// {
// buf.append((char)stream.read());
// }
// } catch (IOException e) {}
// return buf.toString();
// }
//
// public static void writeToFile(BytesWritable value, File binaryFile) throws IOException
// {
// FileOutputStream fileOut = new FileOutputStream(binaryFile);
// fileOut.write(value.getBytes(), 0, value.getLength());
// fileOut.close();
// }
//
// }
| import com.endgame.binarypig.util.ProgramExector;
import com.endgame.binarypig.util.StreamUtils;
import com.google.common.base.Stopwatch;
import java.io.File;
import java.io.IOException;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit;
import org.apache.pig.data.Tuple; | ensureProgramFilePermissions();
}
public void ensureProgramFilePermissions()
{
programFile = new File(workingDir, this.script);
if(programFile.exists()) {
programFile.setExecutable(true);
programFile.setReadable(true);
}
else{
throw new RuntimeException("Program doesn't exist: "+programFile);
}
}
String[] getCommand(File inputFile)
{
return new String[]{programFile.getPath(), inputFile.getPath()};
}
public void dumpStats()
{
System.err.println("script = "+script);
System.err.println("programFile = "+programFile);
super.dumpStats();
}
@Override
public Tuple processFile(Text key, BytesWritable value, File binaryFile) throws IOException{
| // Path: binarypig/src/main/java/com/endgame/binarypig/util/ProgramExector.java
// public class ProgramExector extends Thread
// {
// int retVal = -1;
// long endtime;
// boolean timedOut = false;
//
// Process proc;
// OutputStream stdin;
// InputStream stdout;
// InputStream stderr;
//
// public ProgramExector(String[] cmd, long timeoutMS) throws IOException{
// if(timeoutMS <= 0 || (System.currentTimeMillis() + timeoutMS) <= 0){
// this.endtime = Long.MAX_VALUE;
// }
// else{
// this.endtime = (System.currentTimeMillis() + timeoutMS);
// }
//
// proc = Runtime.getRuntime().exec(cmd);
// stdin = new BufferedOutputStream(proc.getOutputStream());
// stdout = proc.getInputStream();
// stderr = proc.getErrorStream();
// }
//
// @Override
// public void run() {
// while(true)
// {
// try {
// retVal = proc.exitValue();
// // process finished!
// break;
// } catch (IllegalThreadStateException e)
// {
// // process is still running...
// if(System.currentTimeMillis() >= endtime){
// // Process timed out
// timedOut = true;
// proc.destroy();
// retVal = -1;
// break;
// }
// else
// {
// try {
// Thread.sleep(10);
// } catch (InterruptedException e1) {
// throw new RuntimeException(e1);
// }
// }
// }
// }
// }
//
// public boolean isTimedOut() {
// return timedOut;
// }
//
// public InputStream getStderr() {
// return stderr;
// }
//
// public OutputStream getStdin() {
// return stdin;
// }
//
// public InputStream getStdout() {
// return stdout;
// }
//
// public int getRetVal() {
// return retVal;
// }
//
// public void closeStreams()
// {
// IOUtils.closeStream(getStderr());
// IOUtils.closeStream(getStdin());
// IOUtils.closeStream(getStdout());
// }
// }
//
// Path: binarypig/src/main/java/com/endgame/binarypig/util/StreamUtils.java
// public class StreamUtils {
//
// public static String drainInputStream(InputStream stream)
// {
// StringBuilder buf = new StringBuilder();
// try {
// while(stream.available() > 0)
// {
// buf.append((char)stream.read());
// }
// } catch (IOException e) {}
// return buf.toString();
// }
//
// public static void writeToFile(BytesWritable value, File binaryFile) throws IOException
// {
// FileOutputStream fileOut = new FileOutputStream(binaryFile);
// fileOut.write(value.getBytes(), 0, value.getLength());
// fileOut.close();
// }
//
// }
// Path: binarypig/src/main/java/com/endgame/binarypig/loaders/AbstractExecutingLoader.java
import com.endgame.binarypig.util.ProgramExector;
import com.endgame.binarypig.util.StreamUtils;
import com.google.common.base.Stopwatch;
import java.io.File;
import java.io.IOException;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit;
import org.apache.pig.data.Tuple;
ensureProgramFilePermissions();
}
public void ensureProgramFilePermissions()
{
programFile = new File(workingDir, this.script);
if(programFile.exists()) {
programFile.setExecutable(true);
programFile.setReadable(true);
}
else{
throw new RuntimeException("Program doesn't exist: "+programFile);
}
}
String[] getCommand(File inputFile)
{
return new String[]{programFile.getPath(), inputFile.getPath()};
}
public void dumpStats()
{
System.err.println("script = "+script);
System.err.println("programFile = "+programFile);
super.dumpStats();
}
@Override
public Tuple processFile(Text key, BytesWritable value, File binaryFile) throws IOException{
| ProgramExector exec = new ProgramExector(getCommand(binaryFile), timeoutMS); |
endgameinc/binarypig | binarypig/src/main/java/com/endgame/binarypig/loaders/AbstractExecutingLoader.java | // Path: binarypig/src/main/java/com/endgame/binarypig/util/ProgramExector.java
// public class ProgramExector extends Thread
// {
// int retVal = -1;
// long endtime;
// boolean timedOut = false;
//
// Process proc;
// OutputStream stdin;
// InputStream stdout;
// InputStream stderr;
//
// public ProgramExector(String[] cmd, long timeoutMS) throws IOException{
// if(timeoutMS <= 0 || (System.currentTimeMillis() + timeoutMS) <= 0){
// this.endtime = Long.MAX_VALUE;
// }
// else{
// this.endtime = (System.currentTimeMillis() + timeoutMS);
// }
//
// proc = Runtime.getRuntime().exec(cmd);
// stdin = new BufferedOutputStream(proc.getOutputStream());
// stdout = proc.getInputStream();
// stderr = proc.getErrorStream();
// }
//
// @Override
// public void run() {
// while(true)
// {
// try {
// retVal = proc.exitValue();
// // process finished!
// break;
// } catch (IllegalThreadStateException e)
// {
// // process is still running...
// if(System.currentTimeMillis() >= endtime){
// // Process timed out
// timedOut = true;
// proc.destroy();
// retVal = -1;
// break;
// }
// else
// {
// try {
// Thread.sleep(10);
// } catch (InterruptedException e1) {
// throw new RuntimeException(e1);
// }
// }
// }
// }
// }
//
// public boolean isTimedOut() {
// return timedOut;
// }
//
// public InputStream getStderr() {
// return stderr;
// }
//
// public OutputStream getStdin() {
// return stdin;
// }
//
// public InputStream getStdout() {
// return stdout;
// }
//
// public int getRetVal() {
// return retVal;
// }
//
// public void closeStreams()
// {
// IOUtils.closeStream(getStderr());
// IOUtils.closeStream(getStdin());
// IOUtils.closeStream(getStdout());
// }
// }
//
// Path: binarypig/src/main/java/com/endgame/binarypig/util/StreamUtils.java
// public class StreamUtils {
//
// public static String drainInputStream(InputStream stream)
// {
// StringBuilder buf = new StringBuilder();
// try {
// while(stream.available() > 0)
// {
// buf.append((char)stream.read());
// }
// } catch (IOException e) {}
// return buf.toString();
// }
//
// public static void writeToFile(BytesWritable value, File binaryFile) throws IOException
// {
// FileOutputStream fileOut = new FileOutputStream(binaryFile);
// fileOut.write(value.getBytes(), 0, value.getLength());
// fileOut.close();
// }
//
// }
| import com.endgame.binarypig.util.ProgramExector;
import com.endgame.binarypig.util.StreamUtils;
import com.google.common.base.Stopwatch;
import java.io.File;
import java.io.IOException;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit;
import org.apache.pig.data.Tuple; | public void ensureProgramFilePermissions()
{
programFile = new File(workingDir, this.script);
if(programFile.exists()) {
programFile.setExecutable(true);
programFile.setReadable(true);
}
else{
throw new RuntimeException("Program doesn't exist: "+programFile);
}
}
String[] getCommand(File inputFile)
{
return new String[]{programFile.getPath(), inputFile.getPath()};
}
public void dumpStats()
{
System.err.println("script = "+script);
System.err.println("programFile = "+programFile);
super.dumpStats();
}
@Override
public Tuple processFile(Text key, BytesWritable value, File binaryFile) throws IOException{
ProgramExector exec = new ProgramExector(getCommand(binaryFile), timeoutMS);
exec.start();
waitOnProgramExecutor(exec); | // Path: binarypig/src/main/java/com/endgame/binarypig/util/ProgramExector.java
// public class ProgramExector extends Thread
// {
// int retVal = -1;
// long endtime;
// boolean timedOut = false;
//
// Process proc;
// OutputStream stdin;
// InputStream stdout;
// InputStream stderr;
//
// public ProgramExector(String[] cmd, long timeoutMS) throws IOException{
// if(timeoutMS <= 0 || (System.currentTimeMillis() + timeoutMS) <= 0){
// this.endtime = Long.MAX_VALUE;
// }
// else{
// this.endtime = (System.currentTimeMillis() + timeoutMS);
// }
//
// proc = Runtime.getRuntime().exec(cmd);
// stdin = new BufferedOutputStream(proc.getOutputStream());
// stdout = proc.getInputStream();
// stderr = proc.getErrorStream();
// }
//
// @Override
// public void run() {
// while(true)
// {
// try {
// retVal = proc.exitValue();
// // process finished!
// break;
// } catch (IllegalThreadStateException e)
// {
// // process is still running...
// if(System.currentTimeMillis() >= endtime){
// // Process timed out
// timedOut = true;
// proc.destroy();
// retVal = -1;
// break;
// }
// else
// {
// try {
// Thread.sleep(10);
// } catch (InterruptedException e1) {
// throw new RuntimeException(e1);
// }
// }
// }
// }
// }
//
// public boolean isTimedOut() {
// return timedOut;
// }
//
// public InputStream getStderr() {
// return stderr;
// }
//
// public OutputStream getStdin() {
// return stdin;
// }
//
// public InputStream getStdout() {
// return stdout;
// }
//
// public int getRetVal() {
// return retVal;
// }
//
// public void closeStreams()
// {
// IOUtils.closeStream(getStderr());
// IOUtils.closeStream(getStdin());
// IOUtils.closeStream(getStdout());
// }
// }
//
// Path: binarypig/src/main/java/com/endgame/binarypig/util/StreamUtils.java
// public class StreamUtils {
//
// public static String drainInputStream(InputStream stream)
// {
// StringBuilder buf = new StringBuilder();
// try {
// while(stream.available() > 0)
// {
// buf.append((char)stream.read());
// }
// } catch (IOException e) {}
// return buf.toString();
// }
//
// public static void writeToFile(BytesWritable value, File binaryFile) throws IOException
// {
// FileOutputStream fileOut = new FileOutputStream(binaryFile);
// fileOut.write(value.getBytes(), 0, value.getLength());
// fileOut.close();
// }
//
// }
// Path: binarypig/src/main/java/com/endgame/binarypig/loaders/AbstractExecutingLoader.java
import com.endgame.binarypig.util.ProgramExector;
import com.endgame.binarypig.util.StreamUtils;
import com.google.common.base.Stopwatch;
import java.io.File;
import java.io.IOException;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit;
import org.apache.pig.data.Tuple;
public void ensureProgramFilePermissions()
{
programFile = new File(workingDir, this.script);
if(programFile.exists()) {
programFile.setExecutable(true);
programFile.setReadable(true);
}
else{
throw new RuntimeException("Program doesn't exist: "+programFile);
}
}
String[] getCommand(File inputFile)
{
return new String[]{programFile.getPath(), inputFile.getPath()};
}
public void dumpStats()
{
System.err.println("script = "+script);
System.err.println("programFile = "+programFile);
super.dumpStats();
}
@Override
public Tuple processFile(Text key, BytesWritable value, File binaryFile) throws IOException{
ProgramExector exec = new ProgramExector(getCommand(binaryFile), timeoutMS);
exec.start();
waitOnProgramExecutor(exec); | String output = StreamUtils.drainInputStream(exec.getStdout()); |
endgameinc/binarypig | binarypig/src/main/java/com/endgame/binarypig/loaders/AbstractFileDroppingLoader.java | // Path: binarypig/src/main/java/com/endgame/binarypig/util/StreamUtils.java
// public class StreamUtils {
//
// public static String drainInputStream(InputStream stream)
// {
// StringBuilder buf = new StringBuilder();
// try {
// while(stream.available() > 0)
// {
// buf.append((char)stream.read());
// }
// } catch (IOException e) {}
// return buf.toString();
// }
//
// public static void writeToFile(BytesWritable value, File binaryFile) throws IOException
// {
// FileOutputStream fileOut = new FileOutputStream(binaryFile);
// fileOut.write(value.getBytes(), 0, value.getLength());
// fileOut.close();
// }
//
// }
| import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileRecordReader;
import org.apache.pig.FileInputLoadFunc;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import com.endgame.binarypig.util.StreamUtils;
import com.google.common.base.Stopwatch; | System.err.println("dataDir = "+dataDir);
System.err.println("useDevShm = "+useDevShm);
System.err.println("numRecords = "+numRecords);
long usec = totalOverhead.elapsedTime(TimeUnit.MICROSECONDS);
dumpStat("copyOverhead", copyOverhead, usec, numRecords);
dumpStat("deleteOverhead", deleteOverhead, usec, numRecords);
dumpStat("execOverhead", execOverhead, usec, numRecords);
dumpStat("tupleCreationOverhead", tupleCreationOverhead, usec, numRecords);
dumpStat("totalOverhead", totalOverhead, usec, numRecords);
}
@Override
public Tuple getNext() throws IOException {
if(!shouldContinue()){
dumpStats();
cleanUp();
return null;
}
totalOverhead.start();
key = reader.getCurrentKey();
value = reader.getCurrentValue();
++numRecords;
copyOverhead.start();
File binaryFile = new File(dataDir, key.toString());
binaryFile.deleteOnExit();
try { | // Path: binarypig/src/main/java/com/endgame/binarypig/util/StreamUtils.java
// public class StreamUtils {
//
// public static String drainInputStream(InputStream stream)
// {
// StringBuilder buf = new StringBuilder();
// try {
// while(stream.available() > 0)
// {
// buf.append((char)stream.read());
// }
// } catch (IOException e) {}
// return buf.toString();
// }
//
// public static void writeToFile(BytesWritable value, File binaryFile) throws IOException
// {
// FileOutputStream fileOut = new FileOutputStream(binaryFile);
// fileOut.write(value.getBytes(), 0, value.getLength());
// fileOut.close();
// }
//
// }
// Path: binarypig/src/main/java/com/endgame/binarypig/loaders/AbstractFileDroppingLoader.java
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileRecordReader;
import org.apache.pig.FileInputLoadFunc;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import com.endgame.binarypig.util.StreamUtils;
import com.google.common.base.Stopwatch;
System.err.println("dataDir = "+dataDir);
System.err.println("useDevShm = "+useDevShm);
System.err.println("numRecords = "+numRecords);
long usec = totalOverhead.elapsedTime(TimeUnit.MICROSECONDS);
dumpStat("copyOverhead", copyOverhead, usec, numRecords);
dumpStat("deleteOverhead", deleteOverhead, usec, numRecords);
dumpStat("execOverhead", execOverhead, usec, numRecords);
dumpStat("tupleCreationOverhead", tupleCreationOverhead, usec, numRecords);
dumpStat("totalOverhead", totalOverhead, usec, numRecords);
}
@Override
public Tuple getNext() throws IOException {
if(!shouldContinue()){
dumpStats();
cleanUp();
return null;
}
totalOverhead.start();
key = reader.getCurrentKey();
value = reader.getCurrentValue();
++numRecords;
copyOverhead.start();
File binaryFile = new File(dataDir, key.toString());
binaryFile.deleteOnExit();
try { | StreamUtils.writeToFile((BytesWritable) value, binaryFile); |
endgameinc/binarypig | binarypig/src/main/java/com/endgame/binarypig/loaders/ExecutingJsonLoader.java | // Path: binarypig/src/main/java/com/endgame/binarypig/util/JsonUtil.java
// public class JsonUtil {
//
// final protected TupleFactory tupleFactory = TupleFactory.getInstance();
//
// /**
// * Note: copied from elephantbird pig JsonLoader
// */
// boolean isNestedLoadEnabled = true;
// public Object wrap(Object value) {
//
// if (isNestedLoadEnabled && value instanceof JSONObject) {
// return walkJson((JSONObject) value);
// } else if (isNestedLoadEnabled && value instanceof JSONArray) {
//
// JSONArray a = (JSONArray) value;
// DataBag mapValue = new NonSpillableDataBag(a.size());
// for (int i = 0; i < a.size(); i++) {
// Tuple t = tupleFactory.newTuple(wrap(a.get(i)));
// mapValue.add(t);
// }
// return mapValue;
//
// } else {
// return value != null ? value.toString() : null;
// }
// }
//
// /**
// * Note: copied from elephantbird pig JsonLoader
// */
// public Map<String, Object> walkJson(JSONObject jsonObj) {
// Map<String, Object> v = Maps.newHashMap();
// for (Object key : jsonObj.keySet()) {
// v.put(key.toString(), wrap(jsonObj.get(key)));
// }
// return v;
// }
// }
| import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.pig.data.NonSpillableDataBag;
import org.apache.pig.data.Tuple;
import org.json.simple.parser.JSONParser;
import com.endgame.binarypig.util.JsonUtil; | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* 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.
*
* Copyright 2013 Endgame Inc.
*
*/
package com.endgame.binarypig.loaders;
public class ExecutingJsonLoader extends AbstractExecutingLoader
{
JSONParser jsonParser = new JSONParser(); | // Path: binarypig/src/main/java/com/endgame/binarypig/util/JsonUtil.java
// public class JsonUtil {
//
// final protected TupleFactory tupleFactory = TupleFactory.getInstance();
//
// /**
// * Note: copied from elephantbird pig JsonLoader
// */
// boolean isNestedLoadEnabled = true;
// public Object wrap(Object value) {
//
// if (isNestedLoadEnabled && value instanceof JSONObject) {
// return walkJson((JSONObject) value);
// } else if (isNestedLoadEnabled && value instanceof JSONArray) {
//
// JSONArray a = (JSONArray) value;
// DataBag mapValue = new NonSpillableDataBag(a.size());
// for (int i = 0; i < a.size(); i++) {
// Tuple t = tupleFactory.newTuple(wrap(a.get(i)));
// mapValue.add(t);
// }
// return mapValue;
//
// } else {
// return value != null ? value.toString() : null;
// }
// }
//
// /**
// * Note: copied from elephantbird pig JsonLoader
// */
// public Map<String, Object> walkJson(JSONObject jsonObj) {
// Map<String, Object> v = Maps.newHashMap();
// for (Object key : jsonObj.keySet()) {
// v.put(key.toString(), wrap(jsonObj.get(key)));
// }
// return v;
// }
// }
// Path: binarypig/src/main/java/com/endgame/binarypig/loaders/ExecutingJsonLoader.java
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.pig.data.NonSpillableDataBag;
import org.apache.pig.data.Tuple;
import org.json.simple.parser.JSONParser;
import com.endgame.binarypig.util.JsonUtil;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* 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.
*
* Copyright 2013 Endgame Inc.
*
*/
package com.endgame.binarypig.loaders;
public class ExecutingJsonLoader extends AbstractExecutingLoader
{
JSONParser jsonParser = new JSONParser(); | JsonUtil jsonUtil = new JsonUtil(); |
endgameinc/binarypig | binarypig/src/test/java/com/endgame/binarypig/loaders/TextDaemonLoaderTest.java | // Path: binarypig/src/main/java/com/endgame/binarypig/loaders/TextDaemonLoader.java
// public class TextDaemonLoader extends AbstractFileDroppingLoader
// {
// SocketAddress endpoint;
//
// Socket sock = null;
// BufferedReader in = null;
// OutputStream out = null;
//
// public TextDaemonLoader(String port){
// super();
// endpoint = new InetSocketAddress("127.0.0.1", Integer.parseInt(port));
// }
//
// public TextDaemonLoader(String port, String timeoutMS){
// super(timeoutMS);
// endpoint = new InetSocketAddress("127.0.0.1", Integer.parseInt(port));
// }
//
// public TextDaemonLoader(String port, String timeoutMS, String useDevShm){
// super(timeoutMS, useDevShm);
// endpoint = new InetSocketAddress("127.0.0.1", Integer.parseInt(port));
// }
//
// @Override
// public void init() throws IOException {
// super.init();
// sock = new Socket();
// if(getTimeoutMS() < (long)Integer.MAX_VALUE)
// {
// sock.setSoTimeout((int)getTimeoutMS());
// }
// System.err.println("Connecting to "+endpoint+" ...");
// sock.connect(endpoint);
// out = sock.getOutputStream();
// in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
// }
//
// @Override
// public Tuple processFile(Text key, BytesWritable value, File binaryFile) throws IOException {
// boolean timedOut = false;
// String result = "";
// try {
// out.write( (binaryFile.getAbsolutePath()+"\n" ).getBytes());
// String data = in.readLine();
// if(data != null){
// result = data;
// }
// } catch (SocketTimeoutException e) {
// result = "";
// timedOut = true;
// } catch (SocketException e) {
// System.err.println("WARN: Exception occurred, attempting to re-connect...");
// e.printStackTrace();
// close();
// init();
// out.write( (binaryFile.getAbsolutePath()+"\n" ).getBytes());
// String data = in.readLine();
// if(data != null){
// result = data;
// }
// }
//
// getProtoTuple().clear();
// getProtoTuple().add(key.toString());
// getProtoTuple().add(timedOut);
// getProtoTuple().add(result);
// return getTupleFactory().newTuple(getProtoTuple());
// }
//
// private void close() {
// IOUtils.closeSocket(sock);
// IOUtils.closeStream(in);
// IOUtils.closeStream(out);
// }
//
// @Override
// public void cleanUp() {
// super.cleanUp();
// close();
// }
// }
//
// Path: binarypig/src/test/java/com/endgame/binarypig/util/Server.java
// public class Server extends Thread
// {
// ServerSocket sock;
// int port;
// String sent;
// String reply;
// long sleepMS = -1;
//
// public Server() throws IOException{
// this.sock = new ServerSocket(0);
// this.port = sock.getLocalPort();
// }
//
// public void setSleepMS(long sleepMS) {
// this.sleepMS = sleepMS;
// }
//
// public void setReply(String reply) {
// this.reply = reply;
// }
//
// public int getPort() {
// return port;
// }
//
// public String getSent() {
// return sent;
// }
//
// public void run() {
// Socket client = null;
// BufferedReader in = null;
// PrintWriter out = null;
//
// try {
// client = sock.accept();
// if(sleepMS > 0)
// {
// try {
// Thread.sleep(sleepMS);
// } catch (InterruptedException e) {}
// }
//
// in = new BufferedReader(new InputStreamReader(client.getInputStream()));
// String line = in.readLine();
// sent = line;
//
// out = new PrintWriter(client.getOutputStream());
// out.println(reply);
// } catch (IOException e) {
//
// e.printStackTrace();
// }
// finally
// {
// IOUtils.closeStream(out);
// IOUtils.closeStream(in);
// IOUtils.closeStream(sock);
// IOUtils.closeStream(client);
// }
// }
// }
| import com.endgame.binarypig.loaders.TextDaemonLoader;
import com.endgame.binarypig.util.Server;
import java.io.File;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import junit.framework.TestCase;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.pig.data.Tuple; | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* 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.
*
* Copyright 2013 Endgame Inc.
*
*/
package com.endgame.binarypig.loaders;
public class TextDaemonLoaderTest extends TestCase {
TextDaemonLoader underTest; | // Path: binarypig/src/main/java/com/endgame/binarypig/loaders/TextDaemonLoader.java
// public class TextDaemonLoader extends AbstractFileDroppingLoader
// {
// SocketAddress endpoint;
//
// Socket sock = null;
// BufferedReader in = null;
// OutputStream out = null;
//
// public TextDaemonLoader(String port){
// super();
// endpoint = new InetSocketAddress("127.0.0.1", Integer.parseInt(port));
// }
//
// public TextDaemonLoader(String port, String timeoutMS){
// super(timeoutMS);
// endpoint = new InetSocketAddress("127.0.0.1", Integer.parseInt(port));
// }
//
// public TextDaemonLoader(String port, String timeoutMS, String useDevShm){
// super(timeoutMS, useDevShm);
// endpoint = new InetSocketAddress("127.0.0.1", Integer.parseInt(port));
// }
//
// @Override
// public void init() throws IOException {
// super.init();
// sock = new Socket();
// if(getTimeoutMS() < (long)Integer.MAX_VALUE)
// {
// sock.setSoTimeout((int)getTimeoutMS());
// }
// System.err.println("Connecting to "+endpoint+" ...");
// sock.connect(endpoint);
// out = sock.getOutputStream();
// in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
// }
//
// @Override
// public Tuple processFile(Text key, BytesWritable value, File binaryFile) throws IOException {
// boolean timedOut = false;
// String result = "";
// try {
// out.write( (binaryFile.getAbsolutePath()+"\n" ).getBytes());
// String data = in.readLine();
// if(data != null){
// result = data;
// }
// } catch (SocketTimeoutException e) {
// result = "";
// timedOut = true;
// } catch (SocketException e) {
// System.err.println("WARN: Exception occurred, attempting to re-connect...");
// e.printStackTrace();
// close();
// init();
// out.write( (binaryFile.getAbsolutePath()+"\n" ).getBytes());
// String data = in.readLine();
// if(data != null){
// result = data;
// }
// }
//
// getProtoTuple().clear();
// getProtoTuple().add(key.toString());
// getProtoTuple().add(timedOut);
// getProtoTuple().add(result);
// return getTupleFactory().newTuple(getProtoTuple());
// }
//
// private void close() {
// IOUtils.closeSocket(sock);
// IOUtils.closeStream(in);
// IOUtils.closeStream(out);
// }
//
// @Override
// public void cleanUp() {
// super.cleanUp();
// close();
// }
// }
//
// Path: binarypig/src/test/java/com/endgame/binarypig/util/Server.java
// public class Server extends Thread
// {
// ServerSocket sock;
// int port;
// String sent;
// String reply;
// long sleepMS = -1;
//
// public Server() throws IOException{
// this.sock = new ServerSocket(0);
// this.port = sock.getLocalPort();
// }
//
// public void setSleepMS(long sleepMS) {
// this.sleepMS = sleepMS;
// }
//
// public void setReply(String reply) {
// this.reply = reply;
// }
//
// public int getPort() {
// return port;
// }
//
// public String getSent() {
// return sent;
// }
//
// public void run() {
// Socket client = null;
// BufferedReader in = null;
// PrintWriter out = null;
//
// try {
// client = sock.accept();
// if(sleepMS > 0)
// {
// try {
// Thread.sleep(sleepMS);
// } catch (InterruptedException e) {}
// }
//
// in = new BufferedReader(new InputStreamReader(client.getInputStream()));
// String line = in.readLine();
// sent = line;
//
// out = new PrintWriter(client.getOutputStream());
// out.println(reply);
// } catch (IOException e) {
//
// e.printStackTrace();
// }
// finally
// {
// IOUtils.closeStream(out);
// IOUtils.closeStream(in);
// IOUtils.closeStream(sock);
// IOUtils.closeStream(client);
// }
// }
// }
// Path: binarypig/src/test/java/com/endgame/binarypig/loaders/TextDaemonLoaderTest.java
import com.endgame.binarypig.loaders.TextDaemonLoader;
import com.endgame.binarypig.util.Server;
import java.io.File;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import junit.framework.TestCase;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.pig.data.Tuple;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* 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.
*
* Copyright 2013 Endgame Inc.
*
*/
package com.endgame.binarypig.loaders;
public class TextDaemonLoaderTest extends TestCase {
TextDaemonLoader underTest; | Server server; |
endgameinc/binarypig | binarypig/src/test/java/com/endgame/binarypig/loaders/av/ClamScanDaemonLoaderTest.java | // Path: binarypig/src/test/java/com/endgame/binarypig/util/Server.java
// public class Server extends Thread
// {
// ServerSocket sock;
// int port;
// String sent;
// String reply;
// long sleepMS = -1;
//
// public Server() throws IOException{
// this.sock = new ServerSocket(0);
// this.port = sock.getLocalPort();
// }
//
// public void setSleepMS(long sleepMS) {
// this.sleepMS = sleepMS;
// }
//
// public void setReply(String reply) {
// this.reply = reply;
// }
//
// public int getPort() {
// return port;
// }
//
// public String getSent() {
// return sent;
// }
//
// public void run() {
// Socket client = null;
// BufferedReader in = null;
// PrintWriter out = null;
//
// try {
// client = sock.accept();
// if(sleepMS > 0)
// {
// try {
// Thread.sleep(sleepMS);
// } catch (InterruptedException e) {}
// }
//
// in = new BufferedReader(new InputStreamReader(client.getInputStream()));
// String line = in.readLine();
// sent = line;
//
// out = new PrintWriter(client.getOutputStream());
// out.println(reply);
// } catch (IOException e) {
//
// e.printStackTrace();
// }
// finally
// {
// IOUtils.closeStream(out);
// IOUtils.closeStream(in);
// IOUtils.closeStream(sock);
// IOUtils.closeStream(client);
// }
// }
// }
| import com.endgame.binarypig.util.Server;
import java.io.File;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import junit.framework.TestCase;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.pig.data.Tuple; | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* 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.
*
* Copyright 2013 Endgame Inc.
*
*/
package com.endgame.binarypig.loaders.av;
public class ClamScanDaemonLoaderTest extends TestCase {
ClamScanDaemonLoader underTest; | // Path: binarypig/src/test/java/com/endgame/binarypig/util/Server.java
// public class Server extends Thread
// {
// ServerSocket sock;
// int port;
// String sent;
// String reply;
// long sleepMS = -1;
//
// public Server() throws IOException{
// this.sock = new ServerSocket(0);
// this.port = sock.getLocalPort();
// }
//
// public void setSleepMS(long sleepMS) {
// this.sleepMS = sleepMS;
// }
//
// public void setReply(String reply) {
// this.reply = reply;
// }
//
// public int getPort() {
// return port;
// }
//
// public String getSent() {
// return sent;
// }
//
// public void run() {
// Socket client = null;
// BufferedReader in = null;
// PrintWriter out = null;
//
// try {
// client = sock.accept();
// if(sleepMS > 0)
// {
// try {
// Thread.sleep(sleepMS);
// } catch (InterruptedException e) {}
// }
//
// in = new BufferedReader(new InputStreamReader(client.getInputStream()));
// String line = in.readLine();
// sent = line;
//
// out = new PrintWriter(client.getOutputStream());
// out.println(reply);
// } catch (IOException e) {
//
// e.printStackTrace();
// }
// finally
// {
// IOUtils.closeStream(out);
// IOUtils.closeStream(in);
// IOUtils.closeStream(sock);
// IOUtils.closeStream(client);
// }
// }
// }
// Path: binarypig/src/test/java/com/endgame/binarypig/loaders/av/ClamScanDaemonLoaderTest.java
import com.endgame.binarypig.util.Server;
import java.io.File;
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import junit.framework.TestCase;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.pig.data.Tuple;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* 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.
*
* Copyright 2013 Endgame Inc.
*
*/
package com.endgame.binarypig.loaders.av;
public class ClamScanDaemonLoaderTest extends TestCase {
ClamScanDaemonLoader underTest; | Server server; |
multi-os-engine/moe-plugin-gradle | src/main/java/org/moe/gradle/tasks/NatJGen.java | // Path: src/main/java/org/moe/gradle/AbstractMoeExtension.java
// public abstract class AbstractMoeExtension {
//
// @NotNull
// public final AbstractMoePlugin plugin;
//
// @NotNull
// public final NatjgenOptions natjgen;
//
// @NotNull
// public final JavaProcessOptions javaProcess;
//
// public AbstractMoeExtension(@NotNull AbstractMoePlugin plugin, @NotNull Instantiator instantiator) {
// this.plugin = Require.nonNull(plugin);
// Require.nonNull(instantiator);
// this.javaProcess = instantiator.newInstance(JavaProcessOptions.class);
// this.natjgen = instantiator.newInstance(NatjgenOptions.class);
// }
//
// @NotNull
// @IgnoreUnused
// // Add this variant of the method so we can access it from Gradle as 'sdk'
// public MoeSDK getSdk() {
// return plugin.getSDK();
// }
//
// @NotNull
// @IgnoreUnused
// public MoeSDK getSDK() {
// return plugin.getSDK();
// }
//
// @IgnoreUnused
// public void javaProcess(Action<JavaProcessOptions> action) {
// Require.nonNull(action).execute(javaProcess);
// }
//
// @IgnoreUnused
// public void natjgen(Action<NatjgenOptions> action) {
// Require.nonNull(action).execute(natjgen);
// }
//
// @Nullable
// public abstract File getPlatformJar();
//
// @NotNull
// public static AbstractMoeExtension getInstance(@NotNull Project project) {
// return Require.nonNull((AbstractMoeExtension) project.getExtensions().findByName(AbstractMoePlugin.MOE));
// }
// }
//
// Path: src/main/java/org/moe/gradle/AbstractMoePlugin.java
// public static final String MOE = "moe";
| import java.util.List;
import static org.moe.gradle.AbstractMoePlugin.MOE;
import org.gradle.api.GradleException;
import org.gradle.api.Task;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputFile;
import org.gradle.api.tasks.Optional;
import org.moe.gradle.AbstractMoeExtension;
import org.moe.gradle.anns.IgnoreUnused;
import org.moe.gradle.anns.Nullable;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList; |
@Input
@Optional
@Nullable
public String getNatjgenOutput() {
return nullableGetOrConvention(config, CONVENTION_NATJGEN_LOG_OUTPUT);
}
@IgnoreUnused
public void setNatjgenOutput(@Nullable String output) {
this.natjgenOutput = output;
}
@Override
protected void run() {
String bindingConfiguration = getConfig();
String propertyConf = System.getProperty("moe.binding.conf");
final String configuration = propertyConf == null ? bindingConfiguration : propertyConf;
boolean isTest = Boolean.valueOf(System.getProperty("moe.natjgen.testrun"));
if (configuration == null || configuration.isEmpty()) {
throw new GradleException("Missing binding configuration settings");
}
String natjLogOutput = getNatjgenOutput();
| // Path: src/main/java/org/moe/gradle/AbstractMoeExtension.java
// public abstract class AbstractMoeExtension {
//
// @NotNull
// public final AbstractMoePlugin plugin;
//
// @NotNull
// public final NatjgenOptions natjgen;
//
// @NotNull
// public final JavaProcessOptions javaProcess;
//
// public AbstractMoeExtension(@NotNull AbstractMoePlugin plugin, @NotNull Instantiator instantiator) {
// this.plugin = Require.nonNull(plugin);
// Require.nonNull(instantiator);
// this.javaProcess = instantiator.newInstance(JavaProcessOptions.class);
// this.natjgen = instantiator.newInstance(NatjgenOptions.class);
// }
//
// @NotNull
// @IgnoreUnused
// // Add this variant of the method so we can access it from Gradle as 'sdk'
// public MoeSDK getSdk() {
// return plugin.getSDK();
// }
//
// @NotNull
// @IgnoreUnused
// public MoeSDK getSDK() {
// return plugin.getSDK();
// }
//
// @IgnoreUnused
// public void javaProcess(Action<JavaProcessOptions> action) {
// Require.nonNull(action).execute(javaProcess);
// }
//
// @IgnoreUnused
// public void natjgen(Action<NatjgenOptions> action) {
// Require.nonNull(action).execute(natjgen);
// }
//
// @Nullable
// public abstract File getPlatformJar();
//
// @NotNull
// public static AbstractMoeExtension getInstance(@NotNull Project project) {
// return Require.nonNull((AbstractMoeExtension) project.getExtensions().findByName(AbstractMoePlugin.MOE));
// }
// }
//
// Path: src/main/java/org/moe/gradle/AbstractMoePlugin.java
// public static final String MOE = "moe";
// Path: src/main/java/org/moe/gradle/tasks/NatJGen.java
import java.util.List;
import static org.moe.gradle.AbstractMoePlugin.MOE;
import org.gradle.api.GradleException;
import org.gradle.api.Task;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputFile;
import org.gradle.api.tasks.Optional;
import org.moe.gradle.AbstractMoeExtension;
import org.moe.gradle.anns.IgnoreUnused;
import org.moe.gradle.anns.Nullable;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
@Input
@Optional
@Nullable
public String getNatjgenOutput() {
return nullableGetOrConvention(config, CONVENTION_NATJGEN_LOG_OUTPUT);
}
@IgnoreUnused
public void setNatjgenOutput(@Nullable String output) {
this.natjgenOutput = output;
}
@Override
protected void run() {
String bindingConfiguration = getConfig();
String propertyConf = System.getProperty("moe.binding.conf");
final String configuration = propertyConf == null ? bindingConfiguration : propertyConf;
boolean isTest = Boolean.valueOf(System.getProperty("moe.natjgen.testrun"));
if (configuration == null || configuration.isEmpty()) {
throw new GradleException("Missing binding configuration settings");
}
String natjLogOutput = getNatjgenOutput();
| final AbstractMoeExtension ext = getExtension(); |
multi-os-engine/moe-plugin-gradle | src/main/java/org/moe/gradle/tasks/NatJGen.java | // Path: src/main/java/org/moe/gradle/AbstractMoeExtension.java
// public abstract class AbstractMoeExtension {
//
// @NotNull
// public final AbstractMoePlugin plugin;
//
// @NotNull
// public final NatjgenOptions natjgen;
//
// @NotNull
// public final JavaProcessOptions javaProcess;
//
// public AbstractMoeExtension(@NotNull AbstractMoePlugin plugin, @NotNull Instantiator instantiator) {
// this.plugin = Require.nonNull(plugin);
// Require.nonNull(instantiator);
// this.javaProcess = instantiator.newInstance(JavaProcessOptions.class);
// this.natjgen = instantiator.newInstance(NatjgenOptions.class);
// }
//
// @NotNull
// @IgnoreUnused
// // Add this variant of the method so we can access it from Gradle as 'sdk'
// public MoeSDK getSdk() {
// return plugin.getSDK();
// }
//
// @NotNull
// @IgnoreUnused
// public MoeSDK getSDK() {
// return plugin.getSDK();
// }
//
// @IgnoreUnused
// public void javaProcess(Action<JavaProcessOptions> action) {
// Require.nonNull(action).execute(javaProcess);
// }
//
// @IgnoreUnused
// public void natjgen(Action<NatjgenOptions> action) {
// Require.nonNull(action).execute(natjgen);
// }
//
// @Nullable
// public abstract File getPlatformJar();
//
// @NotNull
// public static AbstractMoeExtension getInstance(@NotNull Project project) {
// return Require.nonNull((AbstractMoeExtension) project.getExtensions().findByName(AbstractMoePlugin.MOE));
// }
// }
//
// Path: src/main/java/org/moe/gradle/AbstractMoePlugin.java
// public static final String MOE = "moe";
| import java.util.List;
import static org.moe.gradle.AbstractMoePlugin.MOE;
import org.gradle.api.GradleException;
import org.gradle.api.Task;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputFile;
import org.gradle.api.tasks.Optional;
import org.moe.gradle.AbstractMoeExtension;
import org.moe.gradle.anns.IgnoreUnused;
import org.moe.gradle.anns.Nullable;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList; |
javaexec(spec -> {
spec.setMain("-jar");
spec.setWorkingDir(ext.getSDK().getToolsDir().getAbsolutePath());
spec.args(getNatJGenJar().getAbsolutePath());
spec.args(getProject().getProjectDir().getParent());
spec.args(getProject().getName());
spec.args(configuration);
List<String> args = new ArrayList<String>();
if (isTest) {
args.add("-Dmoe.natjgen.testrun=true");
}
if (natjLogOutput != null && !natjLogOutput.isEmpty()) {
args.add("-Dmoe.natjgen.log.output=" + natjLogOutput);
}
//forward property
if (System.getProperty("moe.keep.natjgen") != null) {
args.add("-Dmoe.keep.natjgen=true");
}
spec.setJvmArgs(args);
});
}
protected final void setupMoeTask() {
setSupportsRemoteBuild(false);
final AbstractMoeExtension ext = getExtension();
// Construct default output path | // Path: src/main/java/org/moe/gradle/AbstractMoeExtension.java
// public abstract class AbstractMoeExtension {
//
// @NotNull
// public final AbstractMoePlugin plugin;
//
// @NotNull
// public final NatjgenOptions natjgen;
//
// @NotNull
// public final JavaProcessOptions javaProcess;
//
// public AbstractMoeExtension(@NotNull AbstractMoePlugin plugin, @NotNull Instantiator instantiator) {
// this.plugin = Require.nonNull(plugin);
// Require.nonNull(instantiator);
// this.javaProcess = instantiator.newInstance(JavaProcessOptions.class);
// this.natjgen = instantiator.newInstance(NatjgenOptions.class);
// }
//
// @NotNull
// @IgnoreUnused
// // Add this variant of the method so we can access it from Gradle as 'sdk'
// public MoeSDK getSdk() {
// return plugin.getSDK();
// }
//
// @NotNull
// @IgnoreUnused
// public MoeSDK getSDK() {
// return plugin.getSDK();
// }
//
// @IgnoreUnused
// public void javaProcess(Action<JavaProcessOptions> action) {
// Require.nonNull(action).execute(javaProcess);
// }
//
// @IgnoreUnused
// public void natjgen(Action<NatjgenOptions> action) {
// Require.nonNull(action).execute(natjgen);
// }
//
// @Nullable
// public abstract File getPlatformJar();
//
// @NotNull
// public static AbstractMoeExtension getInstance(@NotNull Project project) {
// return Require.nonNull((AbstractMoeExtension) project.getExtensions().findByName(AbstractMoePlugin.MOE));
// }
// }
//
// Path: src/main/java/org/moe/gradle/AbstractMoePlugin.java
// public static final String MOE = "moe";
// Path: src/main/java/org/moe/gradle/tasks/NatJGen.java
import java.util.List;
import static org.moe.gradle.AbstractMoePlugin.MOE;
import org.gradle.api.GradleException;
import org.gradle.api.Task;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputFile;
import org.gradle.api.tasks.Optional;
import org.moe.gradle.AbstractMoeExtension;
import org.moe.gradle.anns.IgnoreUnused;
import org.moe.gradle.anns.Nullable;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
javaexec(spec -> {
spec.setMain("-jar");
spec.setWorkingDir(ext.getSDK().getToolsDir().getAbsolutePath());
spec.args(getNatJGenJar().getAbsolutePath());
spec.args(getProject().getProjectDir().getParent());
spec.args(getProject().getName());
spec.args(configuration);
List<String> args = new ArrayList<String>();
if (isTest) {
args.add("-Dmoe.natjgen.testrun=true");
}
if (natjLogOutput != null && !natjLogOutput.isEmpty()) {
args.add("-Dmoe.natjgen.log.output=" + natjLogOutput);
}
//forward property
if (System.getProperty("moe.keep.natjgen") != null) {
args.add("-Dmoe.keep.natjgen=true");
}
spec.setJvmArgs(args);
});
}
protected final void setupMoeTask() {
setSupportsRemoteBuild(false);
final AbstractMoeExtension ext = getExtension();
// Construct default output path | final Path out = Paths.get(MOE); |
multi-os-engine/moe-plugin-gradle | src/test/java/org/moe/gradle/UIActionsAndOutletsTest.java | // Path: src/main/java/org/moe/gradle/utils/FileUtils.java
// public class FileUtils {
// public static void deleteFileOrFolder(final @NotNull Path path) throws IOException {
// Require.nonNull(path);
//
// if (!path.toFile().exists()) {
// return;
// }
// Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
// @Override
// public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
// throws IOException {
// Files.delete(file);
// return CONTINUE;
// }
//
// @Override
// public FileVisitResult postVisitDirectory(final Path dir, final IOException e)
// throws IOException {
// if (e != null) throw e;
// Files.delete(dir);
// return CONTINUE;
// }
// });
// }
//
// public static void deleteFileOrFolder(final @NotNull File file) throws IOException {
// Require.nonNull(file);
//
// deleteFileOrFolder(Paths.get(file.toURI()));
// }
//
// @NotNull
// public static String read(@NotNull File file) {
// Require.nonNull(file);
//
// String string;
// try {
// string = new String(Files.readAllBytes(Paths.get(file.toURI())));
// } catch (IOException e) {
// throw new GradleException("Failed to read " + file, e);
// }
// return string;
// }
//
// public static void write(@NotNull File file, @NotNull String string) {
// Require.nonNull(file);
// Require.nonNull(string);
//
// try {
// Files.write(Paths.get(file.toURI()), string.getBytes(),
// StandardOpenOption.CREATE,
// StandardOpenOption.WRITE,
// StandardOpenOption.TRUNCATE_EXISTING);
// } catch (IOException e) {
// throw new GradleException("Failed to write " + file, e);
// }
// }
//
// @NotNull
// public static File getRelativeTo(@NotNull File base, @NotNull File other) {
// Require.nonNull(base);
// Require.nonNull(other);
//
// return Paths.get(base.getAbsolutePath()).relativize(Paths.get(other.getAbsolutePath())).toFile();
// }
//
// @NotNull
// public static String getNameAsArtifact(@NotNull File file, @NotNull String version) {
// Require.nonNull(file);
// Require.nonNull(version);
//
// final String name = file.getName();
// final int idx = name.indexOf('.');
// if (idx == -1) {
// throw new GradleException("Unexpected state");
//
// } else {
// final String baseName = name.substring(0, idx);
// final String ext = name.substring(idx + 1);
// return "multi-os-engine:" + baseName + ":" + version + "@" + ext;
// }
// }
//
// public static void classAndJarInputIterator(
// @NotNull FileCollection fileCollection,
// @NotNull Consumer<InputStream> consumer
// ) {
// FileUtilsKt.classAndJarInputIterator(fileCollection, (path, inputStream) -> {
// consumer.accept(inputStream);
// return Unit.INSTANCE;
// });
// }
// }
| import org.gradle.testkit.runner.BuildResult;
import org.gradle.testkit.runner.GradleRunner;
import org.junit.Test;
import org.moe.generator.project.MOEProjectComposer;
import org.moe.generator.project.MOEProjectComposer.MOEProjectComposerException;
import org.moe.generator.project.MOEProjectComposer.Template;
import org.moe.gradle.utils.FileUtils;
import java.io.File;
import java.io.IOException;
import static org.gradle.testkit.runner.TaskOutcome.SUCCESS;
import static org.junit.Assert.*; | /*
Copyright (C) 2017 Migeran
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.moe.gradle;
public class UIActionsAndOutletsTest extends AbstractPluginTest {
protected String getTestResourcesFolder() {
return "ui-actions-and-outlets";
}
@Test
public void testGeneratedCode() throws MOEProjectComposerException, IOException {
new MOEProjectComposer()
.setMoeVersion("0.0.0")
.setOrganizationID("org.moe")
.setOrganizationName("Multi-OS Engine")
.setPackageName("org.moe")
.setProjectName("Test")
.setTargetDirectory(testProjectDir.getRoot())
.setTemplate(Template.IOS_JAVA_SINGLE_VIEW)
.setSubproject(true)
.compose();
copyJavaSourceFile("IgnoredController.java");
copyJavaSourceFile("InvalidController.java");
copyJavaSourceFile("UnmappedController.java");
copyJavaSourceFile("ValidController.java");
final File buildGradleFile = new File(testProjectDir.getRoot(), "build.gradle"); | // Path: src/main/java/org/moe/gradle/utils/FileUtils.java
// public class FileUtils {
// public static void deleteFileOrFolder(final @NotNull Path path) throws IOException {
// Require.nonNull(path);
//
// if (!path.toFile().exists()) {
// return;
// }
// Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
// @Override
// public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
// throws IOException {
// Files.delete(file);
// return CONTINUE;
// }
//
// @Override
// public FileVisitResult postVisitDirectory(final Path dir, final IOException e)
// throws IOException {
// if (e != null) throw e;
// Files.delete(dir);
// return CONTINUE;
// }
// });
// }
//
// public static void deleteFileOrFolder(final @NotNull File file) throws IOException {
// Require.nonNull(file);
//
// deleteFileOrFolder(Paths.get(file.toURI()));
// }
//
// @NotNull
// public static String read(@NotNull File file) {
// Require.nonNull(file);
//
// String string;
// try {
// string = new String(Files.readAllBytes(Paths.get(file.toURI())));
// } catch (IOException e) {
// throw new GradleException("Failed to read " + file, e);
// }
// return string;
// }
//
// public static void write(@NotNull File file, @NotNull String string) {
// Require.nonNull(file);
// Require.nonNull(string);
//
// try {
// Files.write(Paths.get(file.toURI()), string.getBytes(),
// StandardOpenOption.CREATE,
// StandardOpenOption.WRITE,
// StandardOpenOption.TRUNCATE_EXISTING);
// } catch (IOException e) {
// throw new GradleException("Failed to write " + file, e);
// }
// }
//
// @NotNull
// public static File getRelativeTo(@NotNull File base, @NotNull File other) {
// Require.nonNull(base);
// Require.nonNull(other);
//
// return Paths.get(base.getAbsolutePath()).relativize(Paths.get(other.getAbsolutePath())).toFile();
// }
//
// @NotNull
// public static String getNameAsArtifact(@NotNull File file, @NotNull String version) {
// Require.nonNull(file);
// Require.nonNull(version);
//
// final String name = file.getName();
// final int idx = name.indexOf('.');
// if (idx == -1) {
// throw new GradleException("Unexpected state");
//
// } else {
// final String baseName = name.substring(0, idx);
// final String ext = name.substring(idx + 1);
// return "multi-os-engine:" + baseName + ":" + version + "@" + ext;
// }
// }
//
// public static void classAndJarInputIterator(
// @NotNull FileCollection fileCollection,
// @NotNull Consumer<InputStream> consumer
// ) {
// FileUtilsKt.classAndJarInputIterator(fileCollection, (path, inputStream) -> {
// consumer.accept(inputStream);
// return Unit.INSTANCE;
// });
// }
// }
// Path: src/test/java/org/moe/gradle/UIActionsAndOutletsTest.java
import org.gradle.testkit.runner.BuildResult;
import org.gradle.testkit.runner.GradleRunner;
import org.junit.Test;
import org.moe.generator.project.MOEProjectComposer;
import org.moe.generator.project.MOEProjectComposer.MOEProjectComposerException;
import org.moe.generator.project.MOEProjectComposer.Template;
import org.moe.gradle.utils.FileUtils;
import java.io.File;
import java.io.IOException;
import static org.gradle.testkit.runner.TaskOutcome.SUCCESS;
import static org.junit.Assert.*;
/*
Copyright (C) 2017 Migeran
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.moe.gradle;
public class UIActionsAndOutletsTest extends AbstractPluginTest {
protected String getTestResourcesFolder() {
return "ui-actions-and-outlets";
}
@Test
public void testGeneratedCode() throws MOEProjectComposerException, IOException {
new MOEProjectComposer()
.setMoeVersion("0.0.0")
.setOrganizationID("org.moe")
.setOrganizationName("Multi-OS Engine")
.setPackageName("org.moe")
.setProjectName("Test")
.setTargetDirectory(testProjectDir.getRoot())
.setTemplate(Template.IOS_JAVA_SINGLE_VIEW)
.setSubproject(true)
.compose();
copyJavaSourceFile("IgnoredController.java");
copyJavaSourceFile("InvalidController.java");
copyJavaSourceFile("UnmappedController.java");
copyJavaSourceFile("ValidController.java");
final File buildGradleFile = new File(testProjectDir.getRoot(), "build.gradle"); | String gradle = FileUtils.read(buildGradleFile); |
theborakompanioni/thymeleaf-extras-shiro | src/test/java/at/pollux/thymeleaf/shiro/dialect/ShiroDialectTest.java | // Path: src/test/java/at/pollux/thymeleaf/shiro/test/ShiroTest.java
// public abstract class ShiroTest {
//
// private static ThreadState subjectThreadState;
//
// public ShiroTest() {
// }
//
// /**
// * Allows subclasses to set the currently executing {@link Subject} instance.
// *
// * @param subject the Subject instance
// */
// protected void setSubject(Subject subject) {
// clearSubject();
// subjectThreadState = createThreadState(subject);
// subjectThreadState.bind();
// }
//
// protected Subject getSubject() {
// return SecurityUtils.getSubject();
// }
//
// protected ThreadState createThreadState(Subject subject) {
// return new SubjectThreadState(subject);
// }
//
// /**
// * Clears Shiro's thread state, ensuring the thread remains clean for future test execution.
// */
// protected void clearSubject() {
// doClearSubject();
// }
//
// private static void doClearSubject() {
// if (subjectThreadState != null) {
// subjectThreadState.clear();
// subjectThreadState = null;
// }
// }
//
// protected static void setSecurityManager(SecurityManager securityManager) {
// SecurityUtils.setSecurityManager(securityManager);
// }
//
// protected static SecurityManager getSecurityManager() {
// return SecurityUtils.getSecurityManager();
// }
//
// @AfterClass
// public static void tearDownShiro() {
// doClearSubject();
// try {
// SecurityManager securityManager = getSecurityManager();
// LifecycleUtils.destroy(securityManager);
// } catch (UnavailableSecurityManagerException e) {
// //we don't care about this when cleaning up the test environment
// //(for example, maybe the subclass is a unit test and it didn't
// // need a SecurityManager instance because it was using only mock Subject instances)
// }
// setSecurityManager(null);
// }
// }
//
// Path: src/test/java/at/pollux/thymeleaf/shiro/test/TestIniSecurityManagerFactory.java
// public class TestIniSecurityManagerFactory extends IniSecurityManagerFactory {
//
// public TestIniSecurityManagerFactory(Ini config) {
// super(config);
// }
//
// @Override
// protected Realm createRealm(Ini ini) {
// //IniRealm realm = new IniRealm(ini); changed to support SHIRO-322
// IniRealm realm = new TestIniRealm();
// realm.setName(INI_REALM_NAME);
// realm.setIni(ini); //added for SHIRO-322
// return realm;
// }
// }
| import static org.junit.Assert.*;
import at.pollux.thymeleaf.shiro.test.ShiroTest;
import at.pollux.thymeleaf.shiro.test.TestIniSecurityManagerFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.Ini;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; | /*
* Copyright 2013 Art Gramlich.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package at.pollux.thymeleaf.shiro.dialect;
/**
* @author artgramlich
*/
public class ShiroDialectTest extends ShiroTest {
private static final String PACKAGE_PATH = "at/pollux/thymeleaf/shiro/dialect/test";
private static final String TEST_TEMPLATE_PATH = PACKAGE_PATH + "/test.html";
private static final String USER1 = "u1";
private static final String PASS1 = "p1";
private static final String USER2 = "u2";
private static final String PASS2 = "p2";
private static final String USER3 = "u3";
private static final String PASS3 = "p3";
private static TemplateEngine templateEngine;
private static void setupShiro() {
Ini ini = new Ini();
Ini.Section usersSection = ini.addSection("users");
usersSection.put(USER1, PASS1 + ",rolea,roled");
usersSection.put(USER2, PASS2 + ",roleb,rolec");
usersSection.put(USER3, PASS3 + ",rolec,rolee");
Ini.Section rolesSection = ini.addSection("roles");
rolesSection.put("rolea", "*");
rolesSection.put("roleb", "permtype1:permaction1:perminst1");
rolesSection.put("rolec", "permtype1:permaction2:*");
rolesSection.put("roled", "permtype3:*"); | // Path: src/test/java/at/pollux/thymeleaf/shiro/test/ShiroTest.java
// public abstract class ShiroTest {
//
// private static ThreadState subjectThreadState;
//
// public ShiroTest() {
// }
//
// /**
// * Allows subclasses to set the currently executing {@link Subject} instance.
// *
// * @param subject the Subject instance
// */
// protected void setSubject(Subject subject) {
// clearSubject();
// subjectThreadState = createThreadState(subject);
// subjectThreadState.bind();
// }
//
// protected Subject getSubject() {
// return SecurityUtils.getSubject();
// }
//
// protected ThreadState createThreadState(Subject subject) {
// return new SubjectThreadState(subject);
// }
//
// /**
// * Clears Shiro's thread state, ensuring the thread remains clean for future test execution.
// */
// protected void clearSubject() {
// doClearSubject();
// }
//
// private static void doClearSubject() {
// if (subjectThreadState != null) {
// subjectThreadState.clear();
// subjectThreadState = null;
// }
// }
//
// protected static void setSecurityManager(SecurityManager securityManager) {
// SecurityUtils.setSecurityManager(securityManager);
// }
//
// protected static SecurityManager getSecurityManager() {
// return SecurityUtils.getSecurityManager();
// }
//
// @AfterClass
// public static void tearDownShiro() {
// doClearSubject();
// try {
// SecurityManager securityManager = getSecurityManager();
// LifecycleUtils.destroy(securityManager);
// } catch (UnavailableSecurityManagerException e) {
// //we don't care about this when cleaning up the test environment
// //(for example, maybe the subclass is a unit test and it didn't
// // need a SecurityManager instance because it was using only mock Subject instances)
// }
// setSecurityManager(null);
// }
// }
//
// Path: src/test/java/at/pollux/thymeleaf/shiro/test/TestIniSecurityManagerFactory.java
// public class TestIniSecurityManagerFactory extends IniSecurityManagerFactory {
//
// public TestIniSecurityManagerFactory(Ini config) {
// super(config);
// }
//
// @Override
// protected Realm createRealm(Ini ini) {
// //IniRealm realm = new IniRealm(ini); changed to support SHIRO-322
// IniRealm realm = new TestIniRealm();
// realm.setName(INI_REALM_NAME);
// realm.setIni(ini); //added for SHIRO-322
// return realm;
// }
// }
// Path: src/test/java/at/pollux/thymeleaf/shiro/dialect/ShiroDialectTest.java
import static org.junit.Assert.*;
import at.pollux.thymeleaf.shiro.test.ShiroTest;
import at.pollux.thymeleaf.shiro.test.TestIniSecurityManagerFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.Ini;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.junit.After;
import org.junit.BeforeClass;
import org.junit.Test;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
/*
* Copyright 2013 Art Gramlich.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package at.pollux.thymeleaf.shiro.dialect;
/**
* @author artgramlich
*/
public class ShiroDialectTest extends ShiroTest {
private static final String PACKAGE_PATH = "at/pollux/thymeleaf/shiro/dialect/test";
private static final String TEST_TEMPLATE_PATH = PACKAGE_PATH + "/test.html";
private static final String USER1 = "u1";
private static final String PASS1 = "p1";
private static final String USER2 = "u2";
private static final String PASS2 = "p2";
private static final String USER3 = "u3";
private static final String PASS3 = "p3";
private static TemplateEngine templateEngine;
private static void setupShiro() {
Ini ini = new Ini();
Ini.Section usersSection = ini.addSection("users");
usersSection.put(USER1, PASS1 + ",rolea,roled");
usersSection.put(USER2, PASS2 + ",roleb,rolec");
usersSection.put(USER3, PASS3 + ",rolec,rolee");
Ini.Section rolesSection = ini.addSection("roles");
rolesSection.put("rolea", "*");
rolesSection.put("roleb", "permtype1:permaction1:perminst1");
rolesSection.put("rolec", "permtype1:permaction2:*");
rolesSection.put("roled", "permtype3:*"); | Factory<SecurityManager> factory = new TestIniSecurityManagerFactory(ini); |
theborakompanioni/thymeleaf-extras-shiro | src/test/java/at/pollux/thymeleaf/shiro/dialect/HasAllRolesTagTest.java | // Path: src/test/java/at/pollux/thymeleaf/shiro/test/AbstractThymeleafShiroDialectTest.java
// public class AbstractThymeleafShiroDialectTest extends ShiroTest {
//
// private static final String PACKAGE_PATH = "at/pollux/thymeleaf/shiro/dialect/test";
//
// private static TemplateEngine templateEngine;
//
// @BeforeClass
// public static void beforeClass() {
// setupShiro();
// setupThymeleaf();
// }
//
// @After
// public void tearDownSubject() {
// clearSubject();
// }
//
// protected String processThymeleafFile(String fileName, Context context) {
// return templateEngine.process(PACKAGE_PATH + "/" + fileName, context);
// }
//
// protected Subject createSubject() {
// final Subject subjectUnderTest = new Subject.Builder(getSecurityManager()).buildSubject();
//
// setSubject(subjectUnderTest);
//
// return subjectUnderTest;
// }
//
// protected Subject createAndLoginSubject(TestUsers userOrNull) {
// final Subject subjectUnderTest = createSubject();
//
// if (userOrNull != null) {
// subjectUnderTest.login(new UsernamePasswordToken(userOrNull.email(), userOrNull.password()));
// }
// return subjectUnderTest;
// }
//
// private static void setupShiro() {
// Ini ini = new Ini();
// Ini.Section usersSection = ini.addSection("users");
//
// usersSection.put(ALICE.email(), ALICE.roles());
// usersSection.put(BOB.email(), BOB.roles());
// usersSection.put(CAESAR.email(), CAESAR.roles());
//
// Ini.Section rolesSection = ini.addSection("roles");
// rolesSection.put(ROLE_A.label(), ROLE_A.permissions());
// rolesSection.put(ROLE_B.label(), ROLE_B.permissions());
// rolesSection.put(ROLE_C.label(), ROLE_C.permissions());
// rolesSection.put(ROLE_D.label(), ROLE_D.permissions());
//
// Factory<SecurityManager> factory = new TestIniSecurityManagerFactory(ini);
// SecurityManager secMgr = factory.getInstance();
// setSecurityManager(secMgr);
// }
//
// private static void setupThymeleaf() {
// ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
// templateResolver.setCacheable(false);
// templateResolver.setCharacterEncoding(Charsets.UTF_8.name());
// templateResolver.setTemplateMode(TemplateMode.HTML);
//
// templateEngine = new TemplateEngine();
// templateEngine.setTemplateResolver(templateResolver);
// final ShiroDialect dialect = new ShiroDialect();
// templateEngine.addDialect(dialect.getPrefix(), dialect);
//
// }
// }
//
// Path: src/test/java/at/pollux/thymeleaf/shiro/test/user/TestUsers.java
// public enum TestUsers {
// ALICE(new TestUser("u1", "p1", Sets.newHashSet(
// TestRoles.ROLE_A, TestRoles.ROLE_D
// ))),
// BOB(new TestUser("u2", "p2", Sets.newHashSet(
// TestRoles.ROLE_B, TestRoles.ROLE_C
// ))),
// CAESAR(new TestUser("u3", "p3", Sets.newHashSet(
// TestRoles.ROLE_C, TestRoles.ROLE_E
// )));
//
// private static Joiner comaJoiner = Joiner.on(",");
//
// private final TestUser delegate;
//
// TestUsers(TestUser user) {
// this.delegate = user;
// }
//
// public String email() {
// return delegate.getEmail();
// }
//
// public String password() {
// return delegate.getPassword();
// }
//
// public String roles() {
// return comaJoiner.join(
// delegate.getPassword(), comaJoiner.join(
// Collections2.transform(delegate.getRoles(), new Function<TestRoles, String>() {
// public String apply(TestRoles input) {
// return input.label();
// }
// }))
// );
// }
//
// public Collection<String> permissions() {
// return Collections2.transform(delegate.getRoles(), new Function<TestRoles, String>() {
// public String apply(TestRoles input) {
// return input.permissions();
// }
// });
// }
// }
| import at.pollux.thymeleaf.shiro.test.AbstractThymeleafShiroDialectTest;
import at.pollux.thymeleaf.shiro.test.user.TestUsers;
import com.google.common.collect.Lists;
import junitparams.JUnitParamsRunner;
import org.apache.shiro.subject.Subject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.thymeleaf.context.Context;
import static at.pollux.thymeleaf.shiro.test.user.TestRoles.ROLE_B;
import static at.pollux.thymeleaf.shiro.test.user.TestRoles.ROLE_C;
import static com.google.common.base.Preconditions.checkArgument;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not; | package at.pollux.thymeleaf.shiro.dialect;
/**
* @author tbk
*/
@RunWith(JUnitParamsRunner.class)
public class HasAllRolesTagTest extends AbstractThymeleafShiroDialectTest {
private static final String FILE_UNDER_TEST = "shiro_hasAllRoles.html";
private static Subject hasAllRolesSanityCheck(Subject subject) {
checkArgument(subject.hasAllRoles(Lists.newArrayList(ROLE_B.label(), ROLE_C.label())));
return subject;
}
@Test
public void itShouldNotRenderWithoutSubject() {
String result = processThymeleafFile(FILE_UNDER_TEST, new Context());
assertThat(result, not(containsString("shiro:")));
assertThat(result, not(containsString("HASALLROLES_ATTRIBUTE_STATIC")));
assertThat(result, not(containsString("HASALLROLES_ELEMENT_STATIC")));
}
@Test
public void itShouldRenderForUserAlice() { | // Path: src/test/java/at/pollux/thymeleaf/shiro/test/AbstractThymeleafShiroDialectTest.java
// public class AbstractThymeleafShiroDialectTest extends ShiroTest {
//
// private static final String PACKAGE_PATH = "at/pollux/thymeleaf/shiro/dialect/test";
//
// private static TemplateEngine templateEngine;
//
// @BeforeClass
// public static void beforeClass() {
// setupShiro();
// setupThymeleaf();
// }
//
// @After
// public void tearDownSubject() {
// clearSubject();
// }
//
// protected String processThymeleafFile(String fileName, Context context) {
// return templateEngine.process(PACKAGE_PATH + "/" + fileName, context);
// }
//
// protected Subject createSubject() {
// final Subject subjectUnderTest = new Subject.Builder(getSecurityManager()).buildSubject();
//
// setSubject(subjectUnderTest);
//
// return subjectUnderTest;
// }
//
// protected Subject createAndLoginSubject(TestUsers userOrNull) {
// final Subject subjectUnderTest = createSubject();
//
// if (userOrNull != null) {
// subjectUnderTest.login(new UsernamePasswordToken(userOrNull.email(), userOrNull.password()));
// }
// return subjectUnderTest;
// }
//
// private static void setupShiro() {
// Ini ini = new Ini();
// Ini.Section usersSection = ini.addSection("users");
//
// usersSection.put(ALICE.email(), ALICE.roles());
// usersSection.put(BOB.email(), BOB.roles());
// usersSection.put(CAESAR.email(), CAESAR.roles());
//
// Ini.Section rolesSection = ini.addSection("roles");
// rolesSection.put(ROLE_A.label(), ROLE_A.permissions());
// rolesSection.put(ROLE_B.label(), ROLE_B.permissions());
// rolesSection.put(ROLE_C.label(), ROLE_C.permissions());
// rolesSection.put(ROLE_D.label(), ROLE_D.permissions());
//
// Factory<SecurityManager> factory = new TestIniSecurityManagerFactory(ini);
// SecurityManager secMgr = factory.getInstance();
// setSecurityManager(secMgr);
// }
//
// private static void setupThymeleaf() {
// ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
// templateResolver.setCacheable(false);
// templateResolver.setCharacterEncoding(Charsets.UTF_8.name());
// templateResolver.setTemplateMode(TemplateMode.HTML);
//
// templateEngine = new TemplateEngine();
// templateEngine.setTemplateResolver(templateResolver);
// final ShiroDialect dialect = new ShiroDialect();
// templateEngine.addDialect(dialect.getPrefix(), dialect);
//
// }
// }
//
// Path: src/test/java/at/pollux/thymeleaf/shiro/test/user/TestUsers.java
// public enum TestUsers {
// ALICE(new TestUser("u1", "p1", Sets.newHashSet(
// TestRoles.ROLE_A, TestRoles.ROLE_D
// ))),
// BOB(new TestUser("u2", "p2", Sets.newHashSet(
// TestRoles.ROLE_B, TestRoles.ROLE_C
// ))),
// CAESAR(new TestUser("u3", "p3", Sets.newHashSet(
// TestRoles.ROLE_C, TestRoles.ROLE_E
// )));
//
// private static Joiner comaJoiner = Joiner.on(",");
//
// private final TestUser delegate;
//
// TestUsers(TestUser user) {
// this.delegate = user;
// }
//
// public String email() {
// return delegate.getEmail();
// }
//
// public String password() {
// return delegate.getPassword();
// }
//
// public String roles() {
// return comaJoiner.join(
// delegate.getPassword(), comaJoiner.join(
// Collections2.transform(delegate.getRoles(), new Function<TestRoles, String>() {
// public String apply(TestRoles input) {
// return input.label();
// }
// }))
// );
// }
//
// public Collection<String> permissions() {
// return Collections2.transform(delegate.getRoles(), new Function<TestRoles, String>() {
// public String apply(TestRoles input) {
// return input.permissions();
// }
// });
// }
// }
// Path: src/test/java/at/pollux/thymeleaf/shiro/dialect/HasAllRolesTagTest.java
import at.pollux.thymeleaf.shiro.test.AbstractThymeleafShiroDialectTest;
import at.pollux.thymeleaf.shiro.test.user.TestUsers;
import com.google.common.collect.Lists;
import junitparams.JUnitParamsRunner;
import org.apache.shiro.subject.Subject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.thymeleaf.context.Context;
import static at.pollux.thymeleaf.shiro.test.user.TestRoles.ROLE_B;
import static at.pollux.thymeleaf.shiro.test.user.TestRoles.ROLE_C;
import static com.google.common.base.Preconditions.checkArgument;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
package at.pollux.thymeleaf.shiro.dialect;
/**
* @author tbk
*/
@RunWith(JUnitParamsRunner.class)
public class HasAllRolesTagTest extends AbstractThymeleafShiroDialectTest {
private static final String FILE_UNDER_TEST = "shiro_hasAllRoles.html";
private static Subject hasAllRolesSanityCheck(Subject subject) {
checkArgument(subject.hasAllRoles(Lists.newArrayList(ROLE_B.label(), ROLE_C.label())));
return subject;
}
@Test
public void itShouldNotRenderWithoutSubject() {
String result = processThymeleafFile(FILE_UNDER_TEST, new Context());
assertThat(result, not(containsString("shiro:")));
assertThat(result, not(containsString("HASALLROLES_ATTRIBUTE_STATIC")));
assertThat(result, not(containsString("HASALLROLES_ELEMENT_STATIC")));
}
@Test
public void itShouldRenderForUserAlice() { | TestUsers user = TestUsers.ALICE; |
theborakompanioni/thymeleaf-extras-shiro | src/test/java/at/pollux/thymeleaf/shiro/test/mother/PermissionsMother.java | // Path: src/test/java/at/pollux/thymeleaf/shiro/test/user/TestUsers.java
// public enum TestUsers {
// ALICE(new TestUser("u1", "p1", Sets.newHashSet(
// TestRoles.ROLE_A, TestRoles.ROLE_D
// ))),
// BOB(new TestUser("u2", "p2", Sets.newHashSet(
// TestRoles.ROLE_B, TestRoles.ROLE_C
// ))),
// CAESAR(new TestUser("u3", "p3", Sets.newHashSet(
// TestRoles.ROLE_C, TestRoles.ROLE_E
// )));
//
// private static Joiner comaJoiner = Joiner.on(",");
//
// private final TestUser delegate;
//
// TestUsers(TestUser user) {
// this.delegate = user;
// }
//
// public String email() {
// return delegate.getEmail();
// }
//
// public String password() {
// return delegate.getPassword();
// }
//
// public String roles() {
// return comaJoiner.join(
// delegate.getPassword(), comaJoiner.join(
// Collections2.transform(delegate.getRoles(), new Function<TestRoles, String>() {
// public String apply(TestRoles input) {
// return input.label();
// }
// }))
// );
// }
//
// public Collection<String> permissions() {
// return Collections2.transform(delegate.getRoles(), new Function<TestRoles, String>() {
// public String apply(TestRoles input) {
// return input.permissions();
// }
// });
// }
// }
//
// Path: src/test/java/at/pollux/thymeleaf/shiro/test/user/TestUsers.java
// public enum TestUsers {
// ALICE(new TestUser("u1", "p1", Sets.newHashSet(
// TestRoles.ROLE_A, TestRoles.ROLE_D
// ))),
// BOB(new TestUser("u2", "p2", Sets.newHashSet(
// TestRoles.ROLE_B, TestRoles.ROLE_C
// ))),
// CAESAR(new TestUser("u3", "p3", Sets.newHashSet(
// TestRoles.ROLE_C, TestRoles.ROLE_E
// )));
//
// private static Joiner comaJoiner = Joiner.on(",");
//
// private final TestUser delegate;
//
// TestUsers(TestUser user) {
// this.delegate = user;
// }
//
// public String email() {
// return delegate.getEmail();
// }
//
// public String password() {
// return delegate.getPassword();
// }
//
// public String roles() {
// return comaJoiner.join(
// delegate.getPassword(), comaJoiner.join(
// Collections2.transform(delegate.getRoles(), new Function<TestRoles, String>() {
// public String apply(TestRoles input) {
// return input.label();
// }
// }))
// );
// }
//
// public Collection<String> permissions() {
// return Collections2.transform(delegate.getRoles(), new Function<TestRoles, String>() {
// public String apply(TestRoles input) {
// return input.permissions();
// }
// });
// }
// }
| import at.pollux.thymeleaf.shiro.test.user.TestUsers;
import com.google.common.collect.Sets;
import org.thymeleaf.context.Context;
import static at.pollux.thymeleaf.shiro.test.user.TestUsers.*;
import static junitparams.JUnitParamsRunner.$; | package at.pollux.thymeleaf.shiro.test.mother;
/**
* Created by tbk.
*/
public class PermissionsMother {
private static Context contextWithPermission(Object permissions) {
final Context context = new Context();
context.setVariable("permissions", permissions);
return context;
}
public static class HasAnyPermissions {
public static class ShouldRenderForUser {
public static Object[] provideAlice() {
return $(ALICE);
}
public static Object[] provideBob() {
return $(BOB);
}
}
public static class ShouldNotRenderForUser {
public static Object[] provideGuest() {
return new Object[]{null};
}
public static Object[] provideCaesar() {
return $(CAESAR);
}
}
public static class ShouldRenderExpression { | // Path: src/test/java/at/pollux/thymeleaf/shiro/test/user/TestUsers.java
// public enum TestUsers {
// ALICE(new TestUser("u1", "p1", Sets.newHashSet(
// TestRoles.ROLE_A, TestRoles.ROLE_D
// ))),
// BOB(new TestUser("u2", "p2", Sets.newHashSet(
// TestRoles.ROLE_B, TestRoles.ROLE_C
// ))),
// CAESAR(new TestUser("u3", "p3", Sets.newHashSet(
// TestRoles.ROLE_C, TestRoles.ROLE_E
// )));
//
// private static Joiner comaJoiner = Joiner.on(",");
//
// private final TestUser delegate;
//
// TestUsers(TestUser user) {
// this.delegate = user;
// }
//
// public String email() {
// return delegate.getEmail();
// }
//
// public String password() {
// return delegate.getPassword();
// }
//
// public String roles() {
// return comaJoiner.join(
// delegate.getPassword(), comaJoiner.join(
// Collections2.transform(delegate.getRoles(), new Function<TestRoles, String>() {
// public String apply(TestRoles input) {
// return input.label();
// }
// }))
// );
// }
//
// public Collection<String> permissions() {
// return Collections2.transform(delegate.getRoles(), new Function<TestRoles, String>() {
// public String apply(TestRoles input) {
// return input.permissions();
// }
// });
// }
// }
//
// Path: src/test/java/at/pollux/thymeleaf/shiro/test/user/TestUsers.java
// public enum TestUsers {
// ALICE(new TestUser("u1", "p1", Sets.newHashSet(
// TestRoles.ROLE_A, TestRoles.ROLE_D
// ))),
// BOB(new TestUser("u2", "p2", Sets.newHashSet(
// TestRoles.ROLE_B, TestRoles.ROLE_C
// ))),
// CAESAR(new TestUser("u3", "p3", Sets.newHashSet(
// TestRoles.ROLE_C, TestRoles.ROLE_E
// )));
//
// private static Joiner comaJoiner = Joiner.on(",");
//
// private final TestUser delegate;
//
// TestUsers(TestUser user) {
// this.delegate = user;
// }
//
// public String email() {
// return delegate.getEmail();
// }
//
// public String password() {
// return delegate.getPassword();
// }
//
// public String roles() {
// return comaJoiner.join(
// delegate.getPassword(), comaJoiner.join(
// Collections2.transform(delegate.getRoles(), new Function<TestRoles, String>() {
// public String apply(TestRoles input) {
// return input.label();
// }
// }))
// );
// }
//
// public Collection<String> permissions() {
// return Collections2.transform(delegate.getRoles(), new Function<TestRoles, String>() {
// public String apply(TestRoles input) {
// return input.permissions();
// }
// });
// }
// }
// Path: src/test/java/at/pollux/thymeleaf/shiro/test/mother/PermissionsMother.java
import at.pollux.thymeleaf.shiro.test.user.TestUsers;
import com.google.common.collect.Sets;
import org.thymeleaf.context.Context;
import static at.pollux.thymeleaf.shiro.test.user.TestUsers.*;
import static junitparams.JUnitParamsRunner.$;
package at.pollux.thymeleaf.shiro.test.mother;
/**
* Created by tbk.
*/
public class PermissionsMother {
private static Context contextWithPermission(Object permissions) {
final Context context = new Context();
context.setVariable("permissions", permissions);
return context;
}
public static class HasAnyPermissions {
public static class ShouldRenderForUser {
public static Object[] provideAlice() {
return $(ALICE);
}
public static Object[] provideBob() {
return $(BOB);
}
}
public static class ShouldNotRenderForUser {
public static Object[] provideGuest() {
return new Object[]{null};
}
public static Object[] provideCaesar() {
return $(CAESAR);
}
}
public static class ShouldRenderExpression { | private static Object[] paramsForUser(TestUsers user) { |
theborakompanioni/thymeleaf-extras-shiro | src/test/java/at/pollux/thymeleaf/shiro/dialect/HasPermissionTagTest.java | // Path: src/test/java/at/pollux/thymeleaf/shiro/test/AbstractThymeleafShiroDialectTest.java
// public class AbstractThymeleafShiroDialectTest extends ShiroTest {
//
// private static final String PACKAGE_PATH = "at/pollux/thymeleaf/shiro/dialect/test";
//
// private static TemplateEngine templateEngine;
//
// @BeforeClass
// public static void beforeClass() {
// setupShiro();
// setupThymeleaf();
// }
//
// @After
// public void tearDownSubject() {
// clearSubject();
// }
//
// protected String processThymeleafFile(String fileName, Context context) {
// return templateEngine.process(PACKAGE_PATH + "/" + fileName, context);
// }
//
// protected Subject createSubject() {
// final Subject subjectUnderTest = new Subject.Builder(getSecurityManager()).buildSubject();
//
// setSubject(subjectUnderTest);
//
// return subjectUnderTest;
// }
//
// protected Subject createAndLoginSubject(TestUsers userOrNull) {
// final Subject subjectUnderTest = createSubject();
//
// if (userOrNull != null) {
// subjectUnderTest.login(new UsernamePasswordToken(userOrNull.email(), userOrNull.password()));
// }
// return subjectUnderTest;
// }
//
// private static void setupShiro() {
// Ini ini = new Ini();
// Ini.Section usersSection = ini.addSection("users");
//
// usersSection.put(ALICE.email(), ALICE.roles());
// usersSection.put(BOB.email(), BOB.roles());
// usersSection.put(CAESAR.email(), CAESAR.roles());
//
// Ini.Section rolesSection = ini.addSection("roles");
// rolesSection.put(ROLE_A.label(), ROLE_A.permissions());
// rolesSection.put(ROLE_B.label(), ROLE_B.permissions());
// rolesSection.put(ROLE_C.label(), ROLE_C.permissions());
// rolesSection.put(ROLE_D.label(), ROLE_D.permissions());
//
// Factory<SecurityManager> factory = new TestIniSecurityManagerFactory(ini);
// SecurityManager secMgr = factory.getInstance();
// setSecurityManager(secMgr);
// }
//
// private static void setupThymeleaf() {
// ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
// templateResolver.setCacheable(false);
// templateResolver.setCharacterEncoding(Charsets.UTF_8.name());
// templateResolver.setTemplateMode(TemplateMode.HTML);
//
// templateEngine = new TemplateEngine();
// templateEngine.setTemplateResolver(templateResolver);
// final ShiroDialect dialect = new ShiroDialect();
// templateEngine.addDialect(dialect.getPrefix(), dialect);
//
// }
// }
//
// Path: src/test/java/at/pollux/thymeleaf/shiro/test/user/TestUsers.java
// public enum TestUsers {
// ALICE(new TestUser("u1", "p1", Sets.newHashSet(
// TestRoles.ROLE_A, TestRoles.ROLE_D
// ))),
// BOB(new TestUser("u2", "p2", Sets.newHashSet(
// TestRoles.ROLE_B, TestRoles.ROLE_C
// ))),
// CAESAR(new TestUser("u3", "p3", Sets.newHashSet(
// TestRoles.ROLE_C, TestRoles.ROLE_E
// )));
//
// private static Joiner comaJoiner = Joiner.on(",");
//
// private final TestUser delegate;
//
// TestUsers(TestUser user) {
// this.delegate = user;
// }
//
// public String email() {
// return delegate.getEmail();
// }
//
// public String password() {
// return delegate.getPassword();
// }
//
// public String roles() {
// return comaJoiner.join(
// delegate.getPassword(), comaJoiner.join(
// Collections2.transform(delegate.getRoles(), new Function<TestRoles, String>() {
// public String apply(TestRoles input) {
// return input.label();
// }
// }))
// );
// }
//
// public Collection<String> permissions() {
// return Collections2.transform(delegate.getRoles(), new Function<TestRoles, String>() {
// public String apply(TestRoles input) {
// return input.permissions();
// }
// });
// }
// }
| import at.pollux.thymeleaf.shiro.test.AbstractThymeleafShiroDialectTest;
import at.pollux.thymeleaf.shiro.test.user.TestUsers;
import org.apache.shiro.subject.Subject;
import org.junit.Test;
import org.thymeleaf.context.Context;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not; | /*
* Copyright 2013 Art Gramlich.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package at.pollux.thymeleaf.shiro.dialect;
/**
* @author tbk
*/
public class HasPermissionTagTest extends AbstractThymeleafShiroDialectTest {
private static final String FILE_UNDER_TEST = "shiro_hasPermission.html";
@Test
public void itShouldNotRenderWithoutSubject() {
String result = processThymeleafFile(FILE_UNDER_TEST, new Context());
assertThat(result, not(containsString("shiro:")));
assertThat(result, not(containsString("PERM_A")));
assertThat(result, not(containsString("PERM_B")));
assertThat(result, not(containsString("PERM_C")));
}
@Test
public void itShouldRenderForUserAlice() { | // Path: src/test/java/at/pollux/thymeleaf/shiro/test/AbstractThymeleafShiroDialectTest.java
// public class AbstractThymeleafShiroDialectTest extends ShiroTest {
//
// private static final String PACKAGE_PATH = "at/pollux/thymeleaf/shiro/dialect/test";
//
// private static TemplateEngine templateEngine;
//
// @BeforeClass
// public static void beforeClass() {
// setupShiro();
// setupThymeleaf();
// }
//
// @After
// public void tearDownSubject() {
// clearSubject();
// }
//
// protected String processThymeleafFile(String fileName, Context context) {
// return templateEngine.process(PACKAGE_PATH + "/" + fileName, context);
// }
//
// protected Subject createSubject() {
// final Subject subjectUnderTest = new Subject.Builder(getSecurityManager()).buildSubject();
//
// setSubject(subjectUnderTest);
//
// return subjectUnderTest;
// }
//
// protected Subject createAndLoginSubject(TestUsers userOrNull) {
// final Subject subjectUnderTest = createSubject();
//
// if (userOrNull != null) {
// subjectUnderTest.login(new UsernamePasswordToken(userOrNull.email(), userOrNull.password()));
// }
// return subjectUnderTest;
// }
//
// private static void setupShiro() {
// Ini ini = new Ini();
// Ini.Section usersSection = ini.addSection("users");
//
// usersSection.put(ALICE.email(), ALICE.roles());
// usersSection.put(BOB.email(), BOB.roles());
// usersSection.put(CAESAR.email(), CAESAR.roles());
//
// Ini.Section rolesSection = ini.addSection("roles");
// rolesSection.put(ROLE_A.label(), ROLE_A.permissions());
// rolesSection.put(ROLE_B.label(), ROLE_B.permissions());
// rolesSection.put(ROLE_C.label(), ROLE_C.permissions());
// rolesSection.put(ROLE_D.label(), ROLE_D.permissions());
//
// Factory<SecurityManager> factory = new TestIniSecurityManagerFactory(ini);
// SecurityManager secMgr = factory.getInstance();
// setSecurityManager(secMgr);
// }
//
// private static void setupThymeleaf() {
// ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
// templateResolver.setCacheable(false);
// templateResolver.setCharacterEncoding(Charsets.UTF_8.name());
// templateResolver.setTemplateMode(TemplateMode.HTML);
//
// templateEngine = new TemplateEngine();
// templateEngine.setTemplateResolver(templateResolver);
// final ShiroDialect dialect = new ShiroDialect();
// templateEngine.addDialect(dialect.getPrefix(), dialect);
//
// }
// }
//
// Path: src/test/java/at/pollux/thymeleaf/shiro/test/user/TestUsers.java
// public enum TestUsers {
// ALICE(new TestUser("u1", "p1", Sets.newHashSet(
// TestRoles.ROLE_A, TestRoles.ROLE_D
// ))),
// BOB(new TestUser("u2", "p2", Sets.newHashSet(
// TestRoles.ROLE_B, TestRoles.ROLE_C
// ))),
// CAESAR(new TestUser("u3", "p3", Sets.newHashSet(
// TestRoles.ROLE_C, TestRoles.ROLE_E
// )));
//
// private static Joiner comaJoiner = Joiner.on(",");
//
// private final TestUser delegate;
//
// TestUsers(TestUser user) {
// this.delegate = user;
// }
//
// public String email() {
// return delegate.getEmail();
// }
//
// public String password() {
// return delegate.getPassword();
// }
//
// public String roles() {
// return comaJoiner.join(
// delegate.getPassword(), comaJoiner.join(
// Collections2.transform(delegate.getRoles(), new Function<TestRoles, String>() {
// public String apply(TestRoles input) {
// return input.label();
// }
// }))
// );
// }
//
// public Collection<String> permissions() {
// return Collections2.transform(delegate.getRoles(), new Function<TestRoles, String>() {
// public String apply(TestRoles input) {
// return input.permissions();
// }
// });
// }
// }
// Path: src/test/java/at/pollux/thymeleaf/shiro/dialect/HasPermissionTagTest.java
import at.pollux.thymeleaf.shiro.test.AbstractThymeleafShiroDialectTest;
import at.pollux.thymeleaf.shiro.test.user.TestUsers;
import org.apache.shiro.subject.Subject;
import org.junit.Test;
import org.thymeleaf.context.Context;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
/*
* Copyright 2013 Art Gramlich.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package at.pollux.thymeleaf.shiro.dialect;
/**
* @author tbk
*/
public class HasPermissionTagTest extends AbstractThymeleafShiroDialectTest {
private static final String FILE_UNDER_TEST = "shiro_hasPermission.html";
@Test
public void itShouldNotRenderWithoutSubject() {
String result = processThymeleafFile(FILE_UNDER_TEST, new Context());
assertThat(result, not(containsString("shiro:")));
assertThat(result, not(containsString("PERM_A")));
assertThat(result, not(containsString("PERM_B")));
assertThat(result, not(containsString("PERM_C")));
}
@Test
public void itShouldRenderForUserAlice() { | TestUsers user = TestUsers.ALICE; |
lucas-dolsan/tcc-rpg | TCC/src/ClienteVoIP/MicThread.java | // Path: TCC/src/Dependencias/Message.java
// public class Message implements Serializable {
//
// private long chId; //-1 means from client to server, otherwise chId generated by the server
// private long timestamp, //-1 means from client to server, otherwise timeStamp of the moment when the server receives the message
// ttl = 2000; //2 seconds TTL
// private Object data; //can carry any type of object. in this program, i used a sound packet, but it could be a string, a chunk of video, ...
//
// public Message(long chId, long timestamp, Object data) {
// this.chId = chId;
// this.timestamp = timestamp;
// this.data = data;
// }
//
// public void setTimestamp(long timestamp) {
// this.timestamp = timestamp;
// }
//
// public long getChId() {
// return chId;
// }
//
// public Object getData() {
// return data;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public long getTtl() {
// return ttl;
// }
//
// public void setTtl(long ttl) {
// this.ttl = ttl;
// }
//
// public void setChId(long chId) {
// this.chId = chId;
// }
//
// }
//
// Path: TCC/src/Dependencias/SoundPacket.java
// public class SoundPacket implements Serializable {
//
// public static AudioFormat defaultFormat = new AudioFormat(11025f, 8, 1, true, true); //11.025khz, 8bit, mono, signed, big endian (changes nothing in 8 bit) ~8kb/s
// public static int defaultDataLenght = 1200; //send 1200 samples/packet by default
// private byte[] data; //actual data. if null, comfort noise will be played
//
// public SoundPacket(byte[] data) {
// this.data = data;
// }
//
// public byte[] getData() {
// return data;
// }
//
// }
//
// Path: TCC/src/Dependencias/Utils.java
// public class Utils {
//
// public static void sleep(int ms) {
// try {
// Thread.sleep(ms);
// } catch (InterruptedException ex) {
// }
// }
//
// public static String getExternalIP() {
// try {
// URL myIp = new URL("http://checkip.dyndns.org/");
// BufferedReader in = new BufferedReader(new InputStreamReader(myIp.openStream()));
// String s = in.readLine();
// return s.substring(s.lastIndexOf(":") + 2, s.lastIndexOf("</body>"));
// } catch (Exception ex) {
// return "error " + ex;
// }
// }
//
// public static String getInternalIP() {
// try {
// return InetAddress.getLocalHost().getHostAddress();
// } catch (UnknownHostException ex) {
// return "error";
// }
// }
// }
| import Dependencias.Message;
import Dependencias.SoundPacket;
import Dependencias.Utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.zip.GZIPOutputStream;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine; | package ClienteVoIP;
public class MicThread extends Thread {
public static double amplification = 1.0;
private ObjectOutputStream toServer;
private TargetDataLine mic;
public MicThread(ObjectOutputStream toServer) throws LineUnavailableException {
this.toServer = toServer;
//open microphone line, an exception is thrown in case of error | // Path: TCC/src/Dependencias/Message.java
// public class Message implements Serializable {
//
// private long chId; //-1 means from client to server, otherwise chId generated by the server
// private long timestamp, //-1 means from client to server, otherwise timeStamp of the moment when the server receives the message
// ttl = 2000; //2 seconds TTL
// private Object data; //can carry any type of object. in this program, i used a sound packet, but it could be a string, a chunk of video, ...
//
// public Message(long chId, long timestamp, Object data) {
// this.chId = chId;
// this.timestamp = timestamp;
// this.data = data;
// }
//
// public void setTimestamp(long timestamp) {
// this.timestamp = timestamp;
// }
//
// public long getChId() {
// return chId;
// }
//
// public Object getData() {
// return data;
// }
//
// public long getTimestamp() {
// return timestamp;
// }
//
// public long getTtl() {
// return ttl;
// }
//
// public void setTtl(long ttl) {
// this.ttl = ttl;
// }
//
// public void setChId(long chId) {
// this.chId = chId;
// }
//
// }
//
// Path: TCC/src/Dependencias/SoundPacket.java
// public class SoundPacket implements Serializable {
//
// public static AudioFormat defaultFormat = new AudioFormat(11025f, 8, 1, true, true); //11.025khz, 8bit, mono, signed, big endian (changes nothing in 8 bit) ~8kb/s
// public static int defaultDataLenght = 1200; //send 1200 samples/packet by default
// private byte[] data; //actual data. if null, comfort noise will be played
//
// public SoundPacket(byte[] data) {
// this.data = data;
// }
//
// public byte[] getData() {
// return data;
// }
//
// }
//
// Path: TCC/src/Dependencias/Utils.java
// public class Utils {
//
// public static void sleep(int ms) {
// try {
// Thread.sleep(ms);
// } catch (InterruptedException ex) {
// }
// }
//
// public static String getExternalIP() {
// try {
// URL myIp = new URL("http://checkip.dyndns.org/");
// BufferedReader in = new BufferedReader(new InputStreamReader(myIp.openStream()));
// String s = in.readLine();
// return s.substring(s.lastIndexOf(":") + 2, s.lastIndexOf("</body>"));
// } catch (Exception ex) {
// return "error " + ex;
// }
// }
//
// public static String getInternalIP() {
// try {
// return InetAddress.getLocalHost().getHostAddress();
// } catch (UnknownHostException ex) {
// return "error";
// }
// }
// }
// Path: TCC/src/ClienteVoIP/MicThread.java
import Dependencias.Message;
import Dependencias.SoundPacket;
import Dependencias.Utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.zip.GZIPOutputStream;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;
package ClienteVoIP;
public class MicThread extends Thread {
public static double amplification = 1.0;
private ObjectOutputStream toServer;
private TargetDataLine mic;
public MicThread(ObjectOutputStream toServer) throws LineUnavailableException {
this.toServer = toServer;
//open microphone line, an exception is thrown in case of error | AudioFormat af = SoundPacket.defaultFormat; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.