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
alexruiz/fest-util
src/main/java/org/fest/util/TypeFilter.java
// Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static org.fest.util.Preconditions.checkNotNull;
/* * Created on Nov 1, 2007 * * 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. * * Copyright @2007-2011 the original author or authors. */ package org.fest.util; /** * Filters elements of a collection by their data type. * * @param <T> the generic type of the objects returned by the filter. * @author Yvonne Wang */ public class TypeFilter<T> implements CollectionFilter<T> { private final Class<T> type; TypeFilter(Class<T> type) { this.type = type; } /** * Creates a new {@link TypeFilter}. * * @param <T> the generic type of the target type. * @param type the target type for this filter. * @return the created filter. */ public static @NotNull <T> TypeFilter<T> byType(@NotNull Class<T> type) { return new TypeFilter<T>(type); } /** * Filters the given collection by the type specified in this filter. * * @param target the collection to filter. * @return a list containing the filtered elements. * @throws NullPointerException if the given collection is {@code null}. */ @Override @SuppressWarnings("unchecked") public @NotNull List<T> filter(@NotNull Collection<?> target) {
// Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/org/fest/util/TypeFilter.java import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static org.fest.util.Preconditions.checkNotNull; /* * Created on Nov 1, 2007 * * 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. * * Copyright @2007-2011 the original author or authors. */ package org.fest.util; /** * Filters elements of a collection by their data type. * * @param <T> the generic type of the objects returned by the filter. * @author Yvonne Wang */ public class TypeFilter<T> implements CollectionFilter<T> { private final Class<T> type; TypeFilter(Class<T> type) { this.type = type; } /** * Creates a new {@link TypeFilter}. * * @param <T> the generic type of the target type. * @param type the target type for this filter. * @return the created filter. */ public static @NotNull <T> TypeFilter<T> byType(@NotNull Class<T> type) { return new TypeFilter<T>(type); } /** * Filters the given collection by the type specified in this filter. * * @param target the collection to filter. * @return a list containing the filtered elements. * @throws NullPointerException if the given collection is {@code null}. */ @Override @SuppressWarnings("unchecked") public @NotNull List<T> filter(@NotNull Collection<?> target) {
checkNotNull(target);
alexruiz/fest-util
src/test/java/org/fest/util/Iterables_isNullOrEmpty_Test.java
// Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) { // checkNotNull(elements); // ArrayList<T> list = newArrayList(); // for (T e : elements) { // list.add(e); // } // return list; // }
import org.junit.Test; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import static org.fest.util.Lists.newArrayList; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue;
/* * Created on Aug 23, 2012 * * 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. * * Copyright @2012-2013 Google, Inc. and others. */ package org.fest.util; /** * Tests for {@link Iterables#isNullOrEmpty(Iterable)}. * * @author Alex Ruiz */ public class Iterables_isNullOrEmpty_Test { @Test public void should_return_true_if_Collection_is_empty() { Iterable<String> c = new ArrayList<String>(); assertTrue(Iterables.isNullOrEmpty(c)); } @Test public void should_return_false_if_Collection_has_elements() {
// Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) { // checkNotNull(elements); // ArrayList<T> list = newArrayList(); // for (T e : elements) { // list.add(e); // } // return list; // } // Path: src/test/java/org/fest/util/Iterables_isNullOrEmpty_Test.java import org.junit.Test; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import static org.fest.util.Lists.newArrayList; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /* * Created on Aug 23, 2012 * * 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. * * Copyright @2012-2013 Google, Inc. and others. */ package org.fest.util; /** * Tests for {@link Iterables#isNullOrEmpty(Iterable)}. * * @author Alex Ruiz */ public class Iterables_isNullOrEmpty_Test { @Test public void should_return_true_if_Collection_is_empty() { Iterable<String> c = new ArrayList<String>(); assertTrue(Iterables.isNullOrEmpty(c)); } @Test public void should_return_false_if_Collection_has_elements() {
Iterable<String> c = newArrayList("Frodo");
alexruiz/fest-util
src/main/java/org/fest/util/Introspection.java
// Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull String checkNotNullOrEmpty(@Nullable String s) { // String checked = checkNotNull(s); // if (checked.isEmpty()) { // throw new IllegalArgumentException(); // } // return checked; // } // // Path: src/main/java/org/fest/util/Strings.java // public static @Nullable String quote(@Nullable String s) { // return s != null ? String.format("'%s'", s) : null; // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import static java.lang.reflect.Modifier.isPublic; import static java.util.Locale.ENGLISH; import static org.fest.util.Preconditions.checkNotNull; import static org.fest.util.Preconditions.checkNotNullOrEmpty; import static org.fest.util.Strings.quote;
/* * Created on Jun 28, 2010 * * 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. * * Copyright @2010-2013 the original author or authors. */ package org.fest.util; /** * Utility methods related to * <a href="http://java.sun.com/docs/books/tutorial/javabeans/introspection/index.html">JavaBeans Introspection</a>. * * @author Alex Ruiz */ public final class Introspection { private Introspection() { } /** * Returns a {@link PropertyDescriptor} for a property matching the given name in the given object. * * @param propertyName the given property name. * @param target the given object. * @return a {@code PropertyDescriptor} for a property matching the given name in the given object. * @throws NullPointerException if the given property name is {@code null}. * @throws IllegalArgumentException if the given property name is empty. * @throws NullPointerException if the given object is {@code null}. * @throws IntrospectionError if a matching property cannot be found or accessed. */ public static @NotNull PropertyDescriptor getProperty(@NotNull String propertyName, @NotNull Object target) {
// Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull String checkNotNullOrEmpty(@Nullable String s) { // String checked = checkNotNull(s); // if (checked.isEmpty()) { // throw new IllegalArgumentException(); // } // return checked; // } // // Path: src/main/java/org/fest/util/Strings.java // public static @Nullable String quote(@Nullable String s) { // return s != null ? String.format("'%s'", s) : null; // } // Path: src/main/java/org/fest/util/Introspection.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import static java.lang.reflect.Modifier.isPublic; import static java.util.Locale.ENGLISH; import static org.fest.util.Preconditions.checkNotNull; import static org.fest.util.Preconditions.checkNotNullOrEmpty; import static org.fest.util.Strings.quote; /* * Created on Jun 28, 2010 * * 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. * * Copyright @2010-2013 the original author or authors. */ package org.fest.util; /** * Utility methods related to * <a href="http://java.sun.com/docs/books/tutorial/javabeans/introspection/index.html">JavaBeans Introspection</a>. * * @author Alex Ruiz */ public final class Introspection { private Introspection() { } /** * Returns a {@link PropertyDescriptor} for a property matching the given name in the given object. * * @param propertyName the given property name. * @param target the given object. * @return a {@code PropertyDescriptor} for a property matching the given name in the given object. * @throws NullPointerException if the given property name is {@code null}. * @throws IllegalArgumentException if the given property name is empty. * @throws NullPointerException if the given object is {@code null}. * @throws IntrospectionError if a matching property cannot be found or accessed. */ public static @NotNull PropertyDescriptor getProperty(@NotNull String propertyName, @NotNull Object target) {
checkNotNullOrEmpty(propertyName);
alexruiz/fest-util
src/main/java/org/fest/util/Introspection.java
// Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull String checkNotNullOrEmpty(@Nullable String s) { // String checked = checkNotNull(s); // if (checked.isEmpty()) { // throw new IllegalArgumentException(); // } // return checked; // } // // Path: src/main/java/org/fest/util/Strings.java // public static @Nullable String quote(@Nullable String s) { // return s != null ? String.format("'%s'", s) : null; // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import static java.lang.reflect.Modifier.isPublic; import static java.util.Locale.ENGLISH; import static org.fest.util.Preconditions.checkNotNull; import static org.fest.util.Preconditions.checkNotNullOrEmpty; import static org.fest.util.Strings.quote;
/* * Created on Jun 28, 2010 * * 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. * * Copyright @2010-2013 the original author or authors. */ package org.fest.util; /** * Utility methods related to * <a href="http://java.sun.com/docs/books/tutorial/javabeans/introspection/index.html">JavaBeans Introspection</a>. * * @author Alex Ruiz */ public final class Introspection { private Introspection() { } /** * Returns a {@link PropertyDescriptor} for a property matching the given name in the given object. * * @param propertyName the given property name. * @param target the given object. * @return a {@code PropertyDescriptor} for a property matching the given name in the given object. * @throws NullPointerException if the given property name is {@code null}. * @throws IllegalArgumentException if the given property name is empty. * @throws NullPointerException if the given object is {@code null}. * @throws IntrospectionError if a matching property cannot be found or accessed. */ public static @NotNull PropertyDescriptor getProperty(@NotNull String propertyName, @NotNull Object target) { checkNotNullOrEmpty(propertyName);
// Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull String checkNotNullOrEmpty(@Nullable String s) { // String checked = checkNotNull(s); // if (checked.isEmpty()) { // throw new IllegalArgumentException(); // } // return checked; // } // // Path: src/main/java/org/fest/util/Strings.java // public static @Nullable String quote(@Nullable String s) { // return s != null ? String.format("'%s'", s) : null; // } // Path: src/main/java/org/fest/util/Introspection.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import static java.lang.reflect.Modifier.isPublic; import static java.util.Locale.ENGLISH; import static org.fest.util.Preconditions.checkNotNull; import static org.fest.util.Preconditions.checkNotNullOrEmpty; import static org.fest.util.Strings.quote; /* * Created on Jun 28, 2010 * * 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. * * Copyright @2010-2013 the original author or authors. */ package org.fest.util; /** * Utility methods related to * <a href="http://java.sun.com/docs/books/tutorial/javabeans/introspection/index.html">JavaBeans Introspection</a>. * * @author Alex Ruiz */ public final class Introspection { private Introspection() { } /** * Returns a {@link PropertyDescriptor} for a property matching the given name in the given object. * * @param propertyName the given property name. * @param target the given object. * @return a {@code PropertyDescriptor} for a property matching the given name in the given object. * @throws NullPointerException if the given property name is {@code null}. * @throws IllegalArgumentException if the given property name is empty. * @throws NullPointerException if the given object is {@code null}. * @throws IntrospectionError if a matching property cannot be found or accessed. */ public static @NotNull PropertyDescriptor getProperty(@NotNull String propertyName, @NotNull Object target) { checkNotNullOrEmpty(propertyName);
checkNotNull(target);
alexruiz/fest-util
src/main/java/org/fest/util/Introspection.java
// Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull String checkNotNullOrEmpty(@Nullable String s) { // String checked = checkNotNull(s); // if (checked.isEmpty()) { // throw new IllegalArgumentException(); // } // return checked; // } // // Path: src/main/java/org/fest/util/Strings.java // public static @Nullable String quote(@Nullable String s) { // return s != null ? String.format("'%s'", s) : null; // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import static java.lang.reflect.Modifier.isPublic; import static java.util.Locale.ENGLISH; import static org.fest.util.Preconditions.checkNotNull; import static org.fest.util.Preconditions.checkNotNullOrEmpty; import static org.fest.util.Strings.quote;
public static @NotNull PropertyDescriptor getProperty(@NotNull String propertyName, @NotNull Object target) { checkNotNullOrEmpty(propertyName); checkNotNull(target); BeanInfo beanInfo; Class<?> type = target.getClass(); try { beanInfo = Introspector.getBeanInfo(type); } catch (Throwable t) { String msg = String.format("Unable to get BeanInfo for type %s", type.getName()); throw new IntrospectionError(checkNotNull(msg), t); } for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) { if (propertyName.equals(descriptor.getName())) { return descriptor; } } throw propertyNotFoundError(propertyName, target); } private static @NotNull IntrospectionError propertyNotFoundError(@NotNull String propertyName, @NotNull Object target) { Method getter = findGetter(propertyName, target); String format; if (getter == null) { format = "No getter for property %s in %s"; } else if (!isPublic(getter.getModifiers())) { format = "No public getter for property %s in %s"; } else { format = "Unable to find property %s in %s"; }
// Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull String checkNotNullOrEmpty(@Nullable String s) { // String checked = checkNotNull(s); // if (checked.isEmpty()) { // throw new IllegalArgumentException(); // } // return checked; // } // // Path: src/main/java/org/fest/util/Strings.java // public static @Nullable String quote(@Nullable String s) { // return s != null ? String.format("'%s'", s) : null; // } // Path: src/main/java/org/fest/util/Introspection.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import static java.lang.reflect.Modifier.isPublic; import static java.util.Locale.ENGLISH; import static org.fest.util.Preconditions.checkNotNull; import static org.fest.util.Preconditions.checkNotNullOrEmpty; import static org.fest.util.Strings.quote; public static @NotNull PropertyDescriptor getProperty(@NotNull String propertyName, @NotNull Object target) { checkNotNullOrEmpty(propertyName); checkNotNull(target); BeanInfo beanInfo; Class<?> type = target.getClass(); try { beanInfo = Introspector.getBeanInfo(type); } catch (Throwable t) { String msg = String.format("Unable to get BeanInfo for type %s", type.getName()); throw new IntrospectionError(checkNotNull(msg), t); } for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) { if (propertyName.equals(descriptor.getName())) { return descriptor; } } throw propertyNotFoundError(propertyName, target); } private static @NotNull IntrospectionError propertyNotFoundError(@NotNull String propertyName, @NotNull Object target) { Method getter = findGetter(propertyName, target); String format; if (getter == null) { format = "No getter for property %s in %s"; } else if (!isPublic(getter.getModifiers())) { format = "No public getter for property %s in %s"; } else { format = "Unable to find property %s in %s"; }
String msg = String.format(format, quote(propertyName), target.getClass().getName());
alexruiz/fest-util
src/test/java/org/fest/util/Iterables_nonNullElementsIn_Test.java
// Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) { // checkNotNull(elements); // ArrayList<T> list = newArrayList(); // for (T e : elements) { // list.add(e); // } // return list; // }
import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static org.fest.util.Lists.newArrayList; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertTrue;
/* * Created on Apr 29, 2007 * * 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. * * Copyright @2007-2013 the original author or authors. */ package org.fest.util; /** * Tests for {@link Iterables#nonNullElementsIn(Iterable)}. * * @author Joel Costigliola * @author Alex Ruiz */ public class Iterables_nonNullElementsIn_Test { @Test public void should_return_empty_List_if_given_Iterable_is_null() { Collection<?> c = null; assertTrue(Iterables.nonNullElementsIn(c).isEmpty()); } @Test public void should_return_empty_List_if_given_Iterable_has_only_null_elements() { Collection<String> c = new ArrayList<String>(); c.add(null); assertTrue(Iterables.nonNullElementsIn(c).isEmpty()); } @Test public void should_return_empty_List_if_given_Iterable_is_empty() { Collection<String> c = new ArrayList<String>(); assertTrue(Iterables.nonNullElementsIn(c).isEmpty()); } @Test public void should_return_a_list_without_null_elements() {
// Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) { // checkNotNull(elements); // ArrayList<T> list = newArrayList(); // for (T e : elements) { // list.add(e); // } // return list; // } // Path: src/test/java/org/fest/util/Iterables_nonNullElementsIn_Test.java import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static org.fest.util.Lists.newArrayList; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertTrue; /* * Created on Apr 29, 2007 * * 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. * * Copyright @2007-2013 the original author or authors. */ package org.fest.util; /** * Tests for {@link Iterables#nonNullElementsIn(Iterable)}. * * @author Joel Costigliola * @author Alex Ruiz */ public class Iterables_nonNullElementsIn_Test { @Test public void should_return_empty_List_if_given_Iterable_is_null() { Collection<?> c = null; assertTrue(Iterables.nonNullElementsIn(c).isEmpty()); } @Test public void should_return_empty_List_if_given_Iterable_has_only_null_elements() { Collection<String> c = new ArrayList<String>(); c.add(null); assertTrue(Iterables.nonNullElementsIn(c).isEmpty()); } @Test public void should_return_empty_List_if_given_Iterable_is_empty() { Collection<String> c = new ArrayList<String>(); assertTrue(Iterables.nonNullElementsIn(c).isEmpty()); } @Test public void should_return_a_list_without_null_elements() {
List<String> c = newArrayList("Frodo", null, "Sam", null);
alexruiz/fest-util
src/test/java/org/fest/util/Collections_isNullOrEmpty_Test.java
// Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) { // checkNotNull(elements); // ArrayList<T> list = newArrayList(); // for (T e : elements) { // list.add(e); // } // return list; // }
import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import static org.fest.util.Lists.newArrayList; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue;
/* * Created on Apr 29, 2007 * * 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. * * Copyright @2007-2013 the original author or authors. */ package org.fest.util; /** * Tests for {@link Collections#isNullOrEmpty(Collection)}. * * @author Yvonne Wang * @author Alex Ruiz */ public class Collections_isNullOrEmpty_Test { @Test public void should_return_true_if_Collection_is_empty() { Collection<String> c = new ArrayList<String>(); assertTrue(Collections.isNullOrEmpty(c)); } @Test public void should_return_true_if_Collection_is_null() { assertTrue(Collections.isNullOrEmpty(null)); } @Test public void should_return_false_if_Collection_has_elements() {
// Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) { // checkNotNull(elements); // ArrayList<T> list = newArrayList(); // for (T e : elements) { // list.add(e); // } // return list; // } // Path: src/test/java/org/fest/util/Collections_isNullOrEmpty_Test.java import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import static org.fest.util.Lists.newArrayList; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /* * Created on Apr 29, 2007 * * 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. * * Copyright @2007-2013 the original author or authors. */ package org.fest.util; /** * Tests for {@link Collections#isNullOrEmpty(Collection)}. * * @author Yvonne Wang * @author Alex Ruiz */ public class Collections_isNullOrEmpty_Test { @Test public void should_return_true_if_Collection_is_empty() { Collection<String> c = new ArrayList<String>(); assertTrue(Collections.isNullOrEmpty(c)); } @Test public void should_return_true_if_Collection_is_null() { assertTrue(Collections.isNullOrEmpty(null)); } @Test public void should_return_false_if_Collection_has_elements() {
Collection<String> c = newArrayList("Frodo");
alexruiz/fest-util
src/main/java/org/fest/util/SystemProperties.java
// Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import org.jetbrains.annotations.NotNull; import static org.fest.util.Preconditions.checkNotNull;
/* * Created on Feb 10, 2008 * * 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. * * Copyright @2008-2013 the original author or authors. */ package org.fest.util; /** * System properties. * * @author Yvonne Wang */ public final class SystemProperties { private static final String LINE_SEPARATOR = getlineSeparator(); private SystemProperties() { } private static @NotNull String getlineSeparator() { try {
// Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/org/fest/util/SystemProperties.java import org.jetbrains.annotations.NotNull; import static org.fest.util.Preconditions.checkNotNull; /* * Created on Feb 10, 2008 * * 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. * * Copyright @2008-2013 the original author or authors. */ package org.fest.util; /** * System properties. * * @author Yvonne Wang */ public final class SystemProperties { private static final String LINE_SEPARATOR = getlineSeparator(); private SystemProperties() { } private static @NotNull String getlineSeparator() { try {
return checkNotNull(System.getProperty("line.separator"));
alexruiz/fest-util
src/test/java/org/fest/util/Files_temporaryFolder_Test.java
// Path: src/main/java/org/fest/util/Strings.java // public static @NotNull StringToAppend append(@NotNull String toAppend) { // return new StringToAppend(toAppend); // }
import org.junit.Test; import java.io.File; import static java.io.File.separator; import static org.fest.util.Strings.append; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
/* * Created on Sep 23, 2006 * * 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. * * Copyright @2006-2011 the original author or authors. */ package org.fest.util; /** * Tests for {@link Files#temporaryFolder()}. * * @author Alex Ruiz * @author Yvonne Wang */ public class Files_temporaryFolder_Test extends Files_TestCase { @Test public void should_find_temporary_folder() { File temporaryFolder = Files.temporaryFolder(); assertTrue(temporaryFolder.isDirectory());
// Path: src/main/java/org/fest/util/Strings.java // public static @NotNull StringToAppend append(@NotNull String toAppend) { // return new StringToAppend(toAppend); // } // Path: src/test/java/org/fest/util/Files_temporaryFolder_Test.java import org.junit.Test; import java.io.File; import static java.io.File.separator; import static org.fest.util.Strings.append; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /* * Created on Sep 23, 2006 * * 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. * * Copyright @2006-2011 the original author or authors. */ package org.fest.util; /** * Tests for {@link Files#temporaryFolder()}. * * @author Alex Ruiz * @author Yvonne Wang */ public class Files_temporaryFolder_Test extends Files_TestCase { @Test public void should_find_temporary_folder() { File temporaryFolder = Files.temporaryFolder(); assertTrue(temporaryFolder.isDirectory());
String a = append(separator).to(temporaryFolder.getAbsolutePath());
alexruiz/fest-util
src/test/java/org/fest/util/ToString_toStringOf_Test.java
// Path: src/main/java/org/fest/util/Arrays.java // public static @NotNull <T> T[] array(@NotNull T... values) { // return checkNotNull(values); // } // // Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) { // checkNotNull(elements); // ArrayList<T> list = newArrayList(); // for (T e : elements) { // list.add(e); // } // return list; // } // // Path: src/main/java/org/fest/util/ToString.java // public static @Nullable String toStringOf(@Nullable Object o) { // if (isArray(o)) { // return Arrays.format(o); // } // if (o instanceof Calendar) { // return toStringOf(o); // } // if (o instanceof Class<?>) { // return toStringOf((Class<?>) o); // } // if (o instanceof Collection<?>) { // return toStringOf((Collection<?>) o); // } // if (o instanceof Date) { // return toStringOf(o); // } // if (o instanceof Float) { // return toStringOf((Float) o); // } // if (o instanceof Long) { // return toStringOf((Long) o); // } // if (o instanceof File) { // return toStringOf((File) o); // } // if (o instanceof Map<?, ?>) { // return toStringOf((Map<?, ?>) o); // } // if (o instanceof String) { // return quote((String) o); // } // if (o instanceof Comparator) { // return toStringOf((Comparator<?>) o); // } // return o == null ? null : o.toString(); // }
import org.junit.Test; import java.io.File; import java.util.*; import static junit.framework.Assert.assertFalse; import static org.fest.util.Arrays.array; import static org.fest.util.Lists.newArrayList; import static org.fest.util.ToString.toStringOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull;
/* * Created on Sep 22, 2006 * * 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. * * Copyright @2006-2013 the original author or authors. */ package org.fest.util; /** * Tests for {@link ToString#toStringOf(Object)}. * * @author Joel Costigliola */ public class ToString_toStringOf_Test { @Test public void should_return_null_if_object_is_null() {
// Path: src/main/java/org/fest/util/Arrays.java // public static @NotNull <T> T[] array(@NotNull T... values) { // return checkNotNull(values); // } // // Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) { // checkNotNull(elements); // ArrayList<T> list = newArrayList(); // for (T e : elements) { // list.add(e); // } // return list; // } // // Path: src/main/java/org/fest/util/ToString.java // public static @Nullable String toStringOf(@Nullable Object o) { // if (isArray(o)) { // return Arrays.format(o); // } // if (o instanceof Calendar) { // return toStringOf(o); // } // if (o instanceof Class<?>) { // return toStringOf((Class<?>) o); // } // if (o instanceof Collection<?>) { // return toStringOf((Collection<?>) o); // } // if (o instanceof Date) { // return toStringOf(o); // } // if (o instanceof Float) { // return toStringOf((Float) o); // } // if (o instanceof Long) { // return toStringOf((Long) o); // } // if (o instanceof File) { // return toStringOf((File) o); // } // if (o instanceof Map<?, ?>) { // return toStringOf((Map<?, ?>) o); // } // if (o instanceof String) { // return quote((String) o); // } // if (o instanceof Comparator) { // return toStringOf((Comparator<?>) o); // } // return o == null ? null : o.toString(); // } // Path: src/test/java/org/fest/util/ToString_toStringOf_Test.java import org.junit.Test; import java.io.File; import java.util.*; import static junit.framework.Assert.assertFalse; import static org.fest.util.Arrays.array; import static org.fest.util.Lists.newArrayList; import static org.fest.util.ToString.toStringOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; /* * Created on Sep 22, 2006 * * 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. * * Copyright @2006-2013 the original author or authors. */ package org.fest.util; /** * Tests for {@link ToString#toStringOf(Object)}. * * @author Joel Costigliola */ public class ToString_toStringOf_Test { @Test public void should_return_null_if_object_is_null() {
assertNull(ToString.toStringOf(null));
alexruiz/fest-util
src/test/java/org/fest/util/ToString_toStringOf_Test.java
// Path: src/main/java/org/fest/util/Arrays.java // public static @NotNull <T> T[] array(@NotNull T... values) { // return checkNotNull(values); // } // // Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) { // checkNotNull(elements); // ArrayList<T> list = newArrayList(); // for (T e : elements) { // list.add(e); // } // return list; // } // // Path: src/main/java/org/fest/util/ToString.java // public static @Nullable String toStringOf(@Nullable Object o) { // if (isArray(o)) { // return Arrays.format(o); // } // if (o instanceof Calendar) { // return toStringOf(o); // } // if (o instanceof Class<?>) { // return toStringOf((Class<?>) o); // } // if (o instanceof Collection<?>) { // return toStringOf((Collection<?>) o); // } // if (o instanceof Date) { // return toStringOf(o); // } // if (o instanceof Float) { // return toStringOf((Float) o); // } // if (o instanceof Long) { // return toStringOf((Long) o); // } // if (o instanceof File) { // return toStringOf((File) o); // } // if (o instanceof Map<?, ?>) { // return toStringOf((Map<?, ?>) o); // } // if (o instanceof String) { // return quote((String) o); // } // if (o instanceof Comparator) { // return toStringOf((Comparator<?>) o); // } // return o == null ? null : o.toString(); // }
import org.junit.Test; import java.io.File; import java.util.*; import static junit.framework.Assert.assertFalse; import static org.fest.util.Arrays.array; import static org.fest.util.Lists.newArrayList; import static org.fest.util.ToString.toStringOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull;
@Test public void should_quote_String() { assertEquals("'Hello'", ToString.toStringOf("Hello")); } @Test public void should_quote_empty_String() { assertEquals("''", ToString.toStringOf("")); } @Test public void should_return_toString_of_File() { final String path = "/someFile.txt"; @SuppressWarnings("serial") File o = new File(path) { @Override public String getAbsolutePath() { return path; } }; assertEquals(path, ToString.toStringOf(o)); } @Test public void should_return_toString_of_Class_with_its_name() { assertEquals("java.lang.Object", ToString.toStringOf(Object.class)); } @Test public void should_return_toString_of_Collection_of_String() {
// Path: src/main/java/org/fest/util/Arrays.java // public static @NotNull <T> T[] array(@NotNull T... values) { // return checkNotNull(values); // } // // Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) { // checkNotNull(elements); // ArrayList<T> list = newArrayList(); // for (T e : elements) { // list.add(e); // } // return list; // } // // Path: src/main/java/org/fest/util/ToString.java // public static @Nullable String toStringOf(@Nullable Object o) { // if (isArray(o)) { // return Arrays.format(o); // } // if (o instanceof Calendar) { // return toStringOf(o); // } // if (o instanceof Class<?>) { // return toStringOf((Class<?>) o); // } // if (o instanceof Collection<?>) { // return toStringOf((Collection<?>) o); // } // if (o instanceof Date) { // return toStringOf(o); // } // if (o instanceof Float) { // return toStringOf((Float) o); // } // if (o instanceof Long) { // return toStringOf((Long) o); // } // if (o instanceof File) { // return toStringOf((File) o); // } // if (o instanceof Map<?, ?>) { // return toStringOf((Map<?, ?>) o); // } // if (o instanceof String) { // return quote((String) o); // } // if (o instanceof Comparator) { // return toStringOf((Comparator<?>) o); // } // return o == null ? null : o.toString(); // } // Path: src/test/java/org/fest/util/ToString_toStringOf_Test.java import org.junit.Test; import java.io.File; import java.util.*; import static junit.framework.Assert.assertFalse; import static org.fest.util.Arrays.array; import static org.fest.util.Lists.newArrayList; import static org.fest.util.ToString.toStringOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @Test public void should_quote_String() { assertEquals("'Hello'", ToString.toStringOf("Hello")); } @Test public void should_quote_empty_String() { assertEquals("''", ToString.toStringOf("")); } @Test public void should_return_toString_of_File() { final String path = "/someFile.txt"; @SuppressWarnings("serial") File o = new File(path) { @Override public String getAbsolutePath() { return path; } }; assertEquals(path, ToString.toStringOf(o)); } @Test public void should_return_toString_of_Class_with_its_name() { assertEquals("java.lang.Object", ToString.toStringOf(Object.class)); } @Test public void should_return_toString_of_Collection_of_String() {
Collection<String> collection = newArrayList("s1", "s2");
alexruiz/fest-util
src/test/java/org/fest/util/ToString_toStringOf_Test.java
// Path: src/main/java/org/fest/util/Arrays.java // public static @NotNull <T> T[] array(@NotNull T... values) { // return checkNotNull(values); // } // // Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) { // checkNotNull(elements); // ArrayList<T> list = newArrayList(); // for (T e : elements) { // list.add(e); // } // return list; // } // // Path: src/main/java/org/fest/util/ToString.java // public static @Nullable String toStringOf(@Nullable Object o) { // if (isArray(o)) { // return Arrays.format(o); // } // if (o instanceof Calendar) { // return toStringOf(o); // } // if (o instanceof Class<?>) { // return toStringOf((Class<?>) o); // } // if (o instanceof Collection<?>) { // return toStringOf((Collection<?>) o); // } // if (o instanceof Date) { // return toStringOf(o); // } // if (o instanceof Float) { // return toStringOf((Float) o); // } // if (o instanceof Long) { // return toStringOf((Long) o); // } // if (o instanceof File) { // return toStringOf((File) o); // } // if (o instanceof Map<?, ?>) { // return toStringOf((Map<?, ?>) o); // } // if (o instanceof String) { // return quote((String) o); // } // if (o instanceof Comparator) { // return toStringOf((Comparator<?>) o); // } // return o == null ? null : o.toString(); // }
import org.junit.Test; import java.io.File; import java.util.*; import static junit.framework.Assert.assertFalse; import static org.fest.util.Arrays.array; import static org.fest.util.Lists.newArrayList; import static org.fest.util.ToString.toStringOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull;
public void should_quote_empty_String() { assertEquals("''", ToString.toStringOf("")); } @Test public void should_return_toString_of_File() { final String path = "/someFile.txt"; @SuppressWarnings("serial") File o = new File(path) { @Override public String getAbsolutePath() { return path; } }; assertEquals(path, ToString.toStringOf(o)); } @Test public void should_return_toString_of_Class_with_its_name() { assertEquals("java.lang.Object", ToString.toStringOf(Object.class)); } @Test public void should_return_toString_of_Collection_of_String() { Collection<String> collection = newArrayList("s1", "s2"); assertEquals("['s1', 's2']", ToString.toStringOf(collection)); } @Test public void should_return_toString_of_Collection_of_arrays() {
// Path: src/main/java/org/fest/util/Arrays.java // public static @NotNull <T> T[] array(@NotNull T... values) { // return checkNotNull(values); // } // // Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) { // checkNotNull(elements); // ArrayList<T> list = newArrayList(); // for (T e : elements) { // list.add(e); // } // return list; // } // // Path: src/main/java/org/fest/util/ToString.java // public static @Nullable String toStringOf(@Nullable Object o) { // if (isArray(o)) { // return Arrays.format(o); // } // if (o instanceof Calendar) { // return toStringOf(o); // } // if (o instanceof Class<?>) { // return toStringOf((Class<?>) o); // } // if (o instanceof Collection<?>) { // return toStringOf((Collection<?>) o); // } // if (o instanceof Date) { // return toStringOf(o); // } // if (o instanceof Float) { // return toStringOf((Float) o); // } // if (o instanceof Long) { // return toStringOf((Long) o); // } // if (o instanceof File) { // return toStringOf((File) o); // } // if (o instanceof Map<?, ?>) { // return toStringOf((Map<?, ?>) o); // } // if (o instanceof String) { // return quote((String) o); // } // if (o instanceof Comparator) { // return toStringOf((Comparator<?>) o); // } // return o == null ? null : o.toString(); // } // Path: src/test/java/org/fest/util/ToString_toStringOf_Test.java import org.junit.Test; import java.io.File; import java.util.*; import static junit.framework.Assert.assertFalse; import static org.fest.util.Arrays.array; import static org.fest.util.Lists.newArrayList; import static org.fest.util.ToString.toStringOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; public void should_quote_empty_String() { assertEquals("''", ToString.toStringOf("")); } @Test public void should_return_toString_of_File() { final String path = "/someFile.txt"; @SuppressWarnings("serial") File o = new File(path) { @Override public String getAbsolutePath() { return path; } }; assertEquals(path, ToString.toStringOf(o)); } @Test public void should_return_toString_of_Class_with_its_name() { assertEquals("java.lang.Object", ToString.toStringOf(Object.class)); } @Test public void should_return_toString_of_Collection_of_String() { Collection<String> collection = newArrayList("s1", "s2"); assertEquals("['s1', 's2']", ToString.toStringOf(collection)); } @Test public void should_return_toString_of_Collection_of_arrays() {
List<Boolean[]> collection = newArrayList(array(true, false), array(true, false, true));
alexruiz/fest-util
src/main/java/org/fest/util/ArrayFormatter.java
// Path: src/main/java/org/fest/util/Arrays.java // public static boolean isArray(@Nullable Object o) { // return o != null && o.getClass().isArray(); // } // // Path: src/main/java/org/fest/util/Sets.java // public static @NotNull <T> HashSet<T> newHashSet() { // return new HashSet<T>(); // } // // Path: src/main/java/org/fest/util/ToString.java // public static @Nullable String toStringOf(@Nullable Object o) { // if (isArray(o)) { // return Arrays.format(o); // } // if (o instanceof Calendar) { // return toStringOf(o); // } // if (o instanceof Class<?>) { // return toStringOf((Class<?>) o); // } // if (o instanceof Collection<?>) { // return toStringOf((Collection<?>) o); // } // if (o instanceof Date) { // return toStringOf(o); // } // if (o instanceof Float) { // return toStringOf((Float) o); // } // if (o instanceof Long) { // return toStringOf((Long) o); // } // if (o instanceof File) { // return toStringOf((File) o); // } // if (o instanceof Map<?, ?>) { // return toStringOf((Map<?, ?>) o); // } // if (o instanceof String) { // return quote((String) o); // } // if (o instanceof Comparator) { // return toStringOf((Comparator<?>) o); // } // return o == null ? null : o.toString(); // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Array; import java.util.HashSet; import java.util.Set; import static java.lang.reflect.Array.getLength; import static org.fest.util.Arrays.isArray; import static org.fest.util.Sets.newHashSet; import static org.fest.util.ToString.toStringOf;
/* * Created on Mar 29, 2009 * * 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. * * Copyright @2009-2013 the original author or authors. */ package org.fest.util; /** * Creates a {@code String} representation of an array. * * @author Alex Ruiz * @author Joel Costigliola */ final class ArrayFormatter { private static final String NULL = "null"; @Nullable String format(@Nullable Object o) {
// Path: src/main/java/org/fest/util/Arrays.java // public static boolean isArray(@Nullable Object o) { // return o != null && o.getClass().isArray(); // } // // Path: src/main/java/org/fest/util/Sets.java // public static @NotNull <T> HashSet<T> newHashSet() { // return new HashSet<T>(); // } // // Path: src/main/java/org/fest/util/ToString.java // public static @Nullable String toStringOf(@Nullable Object o) { // if (isArray(o)) { // return Arrays.format(o); // } // if (o instanceof Calendar) { // return toStringOf(o); // } // if (o instanceof Class<?>) { // return toStringOf((Class<?>) o); // } // if (o instanceof Collection<?>) { // return toStringOf((Collection<?>) o); // } // if (o instanceof Date) { // return toStringOf(o); // } // if (o instanceof Float) { // return toStringOf((Float) o); // } // if (o instanceof Long) { // return toStringOf((Long) o); // } // if (o instanceof File) { // return toStringOf((File) o); // } // if (o instanceof Map<?, ?>) { // return toStringOf((Map<?, ?>) o); // } // if (o instanceof String) { // return quote((String) o); // } // if (o instanceof Comparator) { // return toStringOf((Comparator<?>) o); // } // return o == null ? null : o.toString(); // } // Path: src/main/java/org/fest/util/ArrayFormatter.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Array; import java.util.HashSet; import java.util.Set; import static java.lang.reflect.Array.getLength; import static org.fest.util.Arrays.isArray; import static org.fest.util.Sets.newHashSet; import static org.fest.util.ToString.toStringOf; /* * Created on Mar 29, 2009 * * 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. * * Copyright @2009-2013 the original author or authors. */ package org.fest.util; /** * Creates a {@code String} representation of an array. * * @author Alex Ruiz * @author Joel Costigliola */ final class ArrayFormatter { private static final String NULL = "null"; @Nullable String format(@Nullable Object o) {
if (o == null || !isArray(o)) {
alexruiz/fest-util
src/main/java/org/fest/util/ArrayFormatter.java
// Path: src/main/java/org/fest/util/Arrays.java // public static boolean isArray(@Nullable Object o) { // return o != null && o.getClass().isArray(); // } // // Path: src/main/java/org/fest/util/Sets.java // public static @NotNull <T> HashSet<T> newHashSet() { // return new HashSet<T>(); // } // // Path: src/main/java/org/fest/util/ToString.java // public static @Nullable String toStringOf(@Nullable Object o) { // if (isArray(o)) { // return Arrays.format(o); // } // if (o instanceof Calendar) { // return toStringOf(o); // } // if (o instanceof Class<?>) { // return toStringOf((Class<?>) o); // } // if (o instanceof Collection<?>) { // return toStringOf((Collection<?>) o); // } // if (o instanceof Date) { // return toStringOf(o); // } // if (o instanceof Float) { // return toStringOf((Float) o); // } // if (o instanceof Long) { // return toStringOf((Long) o); // } // if (o instanceof File) { // return toStringOf((File) o); // } // if (o instanceof Map<?, ?>) { // return toStringOf((Map<?, ?>) o); // } // if (o instanceof String) { // return quote((String) o); // } // if (o instanceof Comparator) { // return toStringOf((Comparator<?>) o); // } // return o == null ? null : o.toString(); // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Array; import java.util.HashSet; import java.util.Set; import static java.lang.reflect.Array.getLength; import static org.fest.util.Arrays.isArray; import static org.fest.util.Sets.newHashSet; import static org.fest.util.ToString.toStringOf;
/* * Created on Mar 29, 2009 * * 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. * * Copyright @2009-2013 the original author or authors. */ package org.fest.util; /** * Creates a {@code String} representation of an array. * * @author Alex Ruiz * @author Joel Costigliola */ final class ArrayFormatter { private static final String NULL = "null"; @Nullable String format(@Nullable Object o) { if (o == null || !isArray(o)) { return null; } return isObjectArray(o) ? formatObjectArray(o) : formatPrimitiveArray(o); } private @NotNull String formatObjectArray(@NotNull Object o) { Object[] array = (Object[]) o; int size = array.length; if (size == 0) { return "[]"; } StringBuilder buffer = new StringBuilder((20 * (size - 1)));
// Path: src/main/java/org/fest/util/Arrays.java // public static boolean isArray(@Nullable Object o) { // return o != null && o.getClass().isArray(); // } // // Path: src/main/java/org/fest/util/Sets.java // public static @NotNull <T> HashSet<T> newHashSet() { // return new HashSet<T>(); // } // // Path: src/main/java/org/fest/util/ToString.java // public static @Nullable String toStringOf(@Nullable Object o) { // if (isArray(o)) { // return Arrays.format(o); // } // if (o instanceof Calendar) { // return toStringOf(o); // } // if (o instanceof Class<?>) { // return toStringOf((Class<?>) o); // } // if (o instanceof Collection<?>) { // return toStringOf((Collection<?>) o); // } // if (o instanceof Date) { // return toStringOf(o); // } // if (o instanceof Float) { // return toStringOf((Float) o); // } // if (o instanceof Long) { // return toStringOf((Long) o); // } // if (o instanceof File) { // return toStringOf((File) o); // } // if (o instanceof Map<?, ?>) { // return toStringOf((Map<?, ?>) o); // } // if (o instanceof String) { // return quote((String) o); // } // if (o instanceof Comparator) { // return toStringOf((Comparator<?>) o); // } // return o == null ? null : o.toString(); // } // Path: src/main/java/org/fest/util/ArrayFormatter.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Array; import java.util.HashSet; import java.util.Set; import static java.lang.reflect.Array.getLength; import static org.fest.util.Arrays.isArray; import static org.fest.util.Sets.newHashSet; import static org.fest.util.ToString.toStringOf; /* * Created on Mar 29, 2009 * * 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. * * Copyright @2009-2013 the original author or authors. */ package org.fest.util; /** * Creates a {@code String} representation of an array. * * @author Alex Ruiz * @author Joel Costigliola */ final class ArrayFormatter { private static final String NULL = "null"; @Nullable String format(@Nullable Object o) { if (o == null || !isArray(o)) { return null; } return isObjectArray(o) ? formatObjectArray(o) : formatPrimitiveArray(o); } private @NotNull String formatObjectArray(@NotNull Object o) { Object[] array = (Object[]) o; int size = array.length; if (size == 0) { return "[]"; } StringBuilder buffer = new StringBuilder((20 * (size - 1)));
HashSet<Object[]> alreadyFormatted = newHashSet();
alexruiz/fest-util
src/main/java/org/fest/util/ArrayFormatter.java
// Path: src/main/java/org/fest/util/Arrays.java // public static boolean isArray(@Nullable Object o) { // return o != null && o.getClass().isArray(); // } // // Path: src/main/java/org/fest/util/Sets.java // public static @NotNull <T> HashSet<T> newHashSet() { // return new HashSet<T>(); // } // // Path: src/main/java/org/fest/util/ToString.java // public static @Nullable String toStringOf(@Nullable Object o) { // if (isArray(o)) { // return Arrays.format(o); // } // if (o instanceof Calendar) { // return toStringOf(o); // } // if (o instanceof Class<?>) { // return toStringOf((Class<?>) o); // } // if (o instanceof Collection<?>) { // return toStringOf((Collection<?>) o); // } // if (o instanceof Date) { // return toStringOf(o); // } // if (o instanceof Float) { // return toStringOf((Float) o); // } // if (o instanceof Long) { // return toStringOf((Long) o); // } // if (o instanceof File) { // return toStringOf((File) o); // } // if (o instanceof Map<?, ?>) { // return toStringOf((Map<?, ?>) o); // } // if (o instanceof String) { // return quote((String) o); // } // if (o instanceof Comparator) { // return toStringOf((Comparator<?>) o); // } // return o == null ? null : o.toString(); // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Array; import java.util.HashSet; import java.util.Set; import static java.lang.reflect.Array.getLength; import static org.fest.util.Arrays.isArray; import static org.fest.util.Sets.newHashSet; import static org.fest.util.ToString.toStringOf;
return isObjectArray(o) ? formatObjectArray(o) : formatPrimitiveArray(o); } private @NotNull String formatObjectArray(@NotNull Object o) { Object[] array = (Object[]) o; int size = array.length; if (size == 0) { return "[]"; } StringBuilder buffer = new StringBuilder((20 * (size - 1))); HashSet<Object[]> alreadyFormatted = newHashSet(); deepToString(array, buffer, alreadyFormatted); return buffer.toString(); } private void deepToString(@Nullable Object[] array, @NotNull StringBuilder buffer, @NotNull Set<Object[]> alreadyFormatted) { if (array == null) { buffer.append(NULL); return; } alreadyFormatted.add(array); buffer.append('['); int size = array.length; for (int i = 0; i < size; i++) { if (i != 0) { buffer.append(", "); } Object element = array[i]; if (!isArray(element)) {
// Path: src/main/java/org/fest/util/Arrays.java // public static boolean isArray(@Nullable Object o) { // return o != null && o.getClass().isArray(); // } // // Path: src/main/java/org/fest/util/Sets.java // public static @NotNull <T> HashSet<T> newHashSet() { // return new HashSet<T>(); // } // // Path: src/main/java/org/fest/util/ToString.java // public static @Nullable String toStringOf(@Nullable Object o) { // if (isArray(o)) { // return Arrays.format(o); // } // if (o instanceof Calendar) { // return toStringOf(o); // } // if (o instanceof Class<?>) { // return toStringOf((Class<?>) o); // } // if (o instanceof Collection<?>) { // return toStringOf((Collection<?>) o); // } // if (o instanceof Date) { // return toStringOf(o); // } // if (o instanceof Float) { // return toStringOf((Float) o); // } // if (o instanceof Long) { // return toStringOf((Long) o); // } // if (o instanceof File) { // return toStringOf((File) o); // } // if (o instanceof Map<?, ?>) { // return toStringOf((Map<?, ?>) o); // } // if (o instanceof String) { // return quote((String) o); // } // if (o instanceof Comparator) { // return toStringOf((Comparator<?>) o); // } // return o == null ? null : o.toString(); // } // Path: src/main/java/org/fest/util/ArrayFormatter.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Array; import java.util.HashSet; import java.util.Set; import static java.lang.reflect.Array.getLength; import static org.fest.util.Arrays.isArray; import static org.fest.util.Sets.newHashSet; import static org.fest.util.ToString.toStringOf; return isObjectArray(o) ? formatObjectArray(o) : formatPrimitiveArray(o); } private @NotNull String formatObjectArray(@NotNull Object o) { Object[] array = (Object[]) o; int size = array.length; if (size == 0) { return "[]"; } StringBuilder buffer = new StringBuilder((20 * (size - 1))); HashSet<Object[]> alreadyFormatted = newHashSet(); deepToString(array, buffer, alreadyFormatted); return buffer.toString(); } private void deepToString(@Nullable Object[] array, @NotNull StringBuilder buffer, @NotNull Set<Object[]> alreadyFormatted) { if (array == null) { buffer.append(NULL); return; } alreadyFormatted.add(array); buffer.append('['); int size = array.length; for (int i = 0; i < size; i++) { if (i != 0) { buffer.append(", "); } Object element = array[i]; if (!isArray(element)) {
buffer.append(element == null ? NULL : toStringOf(element));
alexruiz/fest-util
src/main/java/org/fest/util/Files.java
// Path: src/main/java/org/fest/util/Arrays.java // public static <T> boolean isNullOrEmpty(@Nullable T[] array) { // return array == null || !hasElements(array); // } // // Path: src/main/java/org/fest/util/Closeables.java // public static void closeQuietly(@NotNull Closeable... closeables) { // for (Closeable c : closeables) { // close(c); // } // } // // Path: src/main/java/org/fest/util/Flushables.java // public static void flushQuietly(@NotNull Flushable... flushables) { // for (Flushable f : flushables) { // flush(f); // } // } // // Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/org/fest/util/Strings.java // public static @NotNull StringToAppend append(@NotNull String toAppend) { // return new StringToAppend(toAppend); // } // // Path: src/main/java/org/fest/util/Strings.java // public static @Nullable String quote(@Nullable String s) { // return s != null ? String.format("'%s'", s) : null; // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import static java.io.File.separator; import static java.lang.String.format; import static org.fest.util.Arrays.isNullOrEmpty; import static org.fest.util.Closeables.closeQuietly; import static org.fest.util.Flushables.flushQuietly; import static org.fest.util.Preconditions.checkNotNull; import static org.fest.util.Strings.append; import static org.fest.util.Strings.quote;
/* * Created on Sep 23, 2006 * * 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. * * Copyright @2006-2013 the original author or authors. */ package org.fest.util; /** * Utility methods related to files. * * @author Yvonne Wang * @author Alex Ruiz */ public class Files { private Files() { } /** * Returns the names of the files inside the specified directory. * * @param dirName the name of the directory to start the search from. * @param recurse if {@code true}, we will look in subdirectories. * @return the names of the files inside the specified directory. * @throws IllegalArgumentException if the given directory name does not point to an existing directory. */ public static @NotNull List<String> fileNamesIn(@NotNull String dirName, boolean recurse) { File dir = new File(dirName); if (!dir.isDirectory()) {
// Path: src/main/java/org/fest/util/Arrays.java // public static <T> boolean isNullOrEmpty(@Nullable T[] array) { // return array == null || !hasElements(array); // } // // Path: src/main/java/org/fest/util/Closeables.java // public static void closeQuietly(@NotNull Closeable... closeables) { // for (Closeable c : closeables) { // close(c); // } // } // // Path: src/main/java/org/fest/util/Flushables.java // public static void flushQuietly(@NotNull Flushable... flushables) { // for (Flushable f : flushables) { // flush(f); // } // } // // Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/org/fest/util/Strings.java // public static @NotNull StringToAppend append(@NotNull String toAppend) { // return new StringToAppend(toAppend); // } // // Path: src/main/java/org/fest/util/Strings.java // public static @Nullable String quote(@Nullable String s) { // return s != null ? String.format("'%s'", s) : null; // } // Path: src/main/java/org/fest/util/Files.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import static java.io.File.separator; import static java.lang.String.format; import static org.fest.util.Arrays.isNullOrEmpty; import static org.fest.util.Closeables.closeQuietly; import static org.fest.util.Flushables.flushQuietly; import static org.fest.util.Preconditions.checkNotNull; import static org.fest.util.Strings.append; import static org.fest.util.Strings.quote; /* * Created on Sep 23, 2006 * * 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. * * Copyright @2006-2013 the original author or authors. */ package org.fest.util; /** * Utility methods related to files. * * @author Yvonne Wang * @author Alex Ruiz */ public class Files { private Files() { } /** * Returns the names of the files inside the specified directory. * * @param dirName the name of the directory to start the search from. * @param recurse if {@code true}, we will look in subdirectories. * @return the names of the files inside the specified directory. * @throws IllegalArgumentException if the given directory name does not point to an existing directory. */ public static @NotNull List<String> fileNamesIn(@NotNull String dirName, boolean recurse) { File dir = new File(dirName); if (!dir.isDirectory()) {
throw new IllegalArgumentException(format("%s is not a directory", quote(dirName)));
alexruiz/fest-util
src/main/java/org/fest/util/Files.java
// Path: src/main/java/org/fest/util/Arrays.java // public static <T> boolean isNullOrEmpty(@Nullable T[] array) { // return array == null || !hasElements(array); // } // // Path: src/main/java/org/fest/util/Closeables.java // public static void closeQuietly(@NotNull Closeable... closeables) { // for (Closeable c : closeables) { // close(c); // } // } // // Path: src/main/java/org/fest/util/Flushables.java // public static void flushQuietly(@NotNull Flushable... flushables) { // for (Flushable f : flushables) { // flush(f); // } // } // // Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/org/fest/util/Strings.java // public static @NotNull StringToAppend append(@NotNull String toAppend) { // return new StringToAppend(toAppend); // } // // Path: src/main/java/org/fest/util/Strings.java // public static @Nullable String quote(@Nullable String s) { // return s != null ? String.format("'%s'", s) : null; // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import static java.io.File.separator; import static java.lang.String.format; import static org.fest.util.Arrays.isNullOrEmpty; import static org.fest.util.Closeables.closeQuietly; import static org.fest.util.Flushables.flushQuietly; import static org.fest.util.Preconditions.checkNotNull; import static org.fest.util.Strings.append; import static org.fest.util.Strings.quote;
} continue; } String filename = existingFile.getAbsolutePath(); if (!fileNames.contains(filename)) { fileNames.add(filename); } } return fileNames; } /** * @return the system's temporary directory. * @throws IORuntimeException if this method cannot find or create the system's temporary directory. */ public static @NotNull File temporaryFolder() { File temp = new File(temporaryFolderPath()); if (!temp.isDirectory()) { throw new IORuntimeException("Unable to find temporary directory"); } return temp; } /** * Returns the path of the system's temporary directory. This method appends the system's file separator at the end of * the path. * * @return the path of the system's temporary directory. */ public static @NotNull String temporaryFolderPath() {
// Path: src/main/java/org/fest/util/Arrays.java // public static <T> boolean isNullOrEmpty(@Nullable T[] array) { // return array == null || !hasElements(array); // } // // Path: src/main/java/org/fest/util/Closeables.java // public static void closeQuietly(@NotNull Closeable... closeables) { // for (Closeable c : closeables) { // close(c); // } // } // // Path: src/main/java/org/fest/util/Flushables.java // public static void flushQuietly(@NotNull Flushable... flushables) { // for (Flushable f : flushables) { // flush(f); // } // } // // Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/org/fest/util/Strings.java // public static @NotNull StringToAppend append(@NotNull String toAppend) { // return new StringToAppend(toAppend); // } // // Path: src/main/java/org/fest/util/Strings.java // public static @Nullable String quote(@Nullable String s) { // return s != null ? String.format("'%s'", s) : null; // } // Path: src/main/java/org/fest/util/Files.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import static java.io.File.separator; import static java.lang.String.format; import static org.fest.util.Arrays.isNullOrEmpty; import static org.fest.util.Closeables.closeQuietly; import static org.fest.util.Flushables.flushQuietly; import static org.fest.util.Preconditions.checkNotNull; import static org.fest.util.Strings.append; import static org.fest.util.Strings.quote; } continue; } String filename = existingFile.getAbsolutePath(); if (!fileNames.contains(filename)) { fileNames.add(filename); } } return fileNames; } /** * @return the system's temporary directory. * @throws IORuntimeException if this method cannot find or create the system's temporary directory. */ public static @NotNull File temporaryFolder() { File temp = new File(temporaryFolderPath()); if (!temp.isDirectory()) { throw new IORuntimeException("Unable to find temporary directory"); } return temp; } /** * Returns the path of the system's temporary directory. This method appends the system's file separator at the end of * the path. * * @return the path of the system's temporary directory. */ public static @NotNull String temporaryFolderPath() {
String fileSeparator = checkNotNull(separator);
alexruiz/fest-util
src/main/java/org/fest/util/Files.java
// Path: src/main/java/org/fest/util/Arrays.java // public static <T> boolean isNullOrEmpty(@Nullable T[] array) { // return array == null || !hasElements(array); // } // // Path: src/main/java/org/fest/util/Closeables.java // public static void closeQuietly(@NotNull Closeable... closeables) { // for (Closeable c : closeables) { // close(c); // } // } // // Path: src/main/java/org/fest/util/Flushables.java // public static void flushQuietly(@NotNull Flushable... flushables) { // for (Flushable f : flushables) { // flush(f); // } // } // // Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/org/fest/util/Strings.java // public static @NotNull StringToAppend append(@NotNull String toAppend) { // return new StringToAppend(toAppend); // } // // Path: src/main/java/org/fest/util/Strings.java // public static @Nullable String quote(@Nullable String s) { // return s != null ? String.format("'%s'", s) : null; // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import static java.io.File.separator; import static java.lang.String.format; import static org.fest.util.Arrays.isNullOrEmpty; import static org.fest.util.Closeables.closeQuietly; import static org.fest.util.Flushables.flushQuietly; import static org.fest.util.Preconditions.checkNotNull; import static org.fest.util.Strings.append; import static org.fest.util.Strings.quote;
} String filename = existingFile.getAbsolutePath(); if (!fileNames.contains(filename)) { fileNames.add(filename); } } return fileNames; } /** * @return the system's temporary directory. * @throws IORuntimeException if this method cannot find or create the system's temporary directory. */ public static @NotNull File temporaryFolder() { File temp = new File(temporaryFolderPath()); if (!temp.isDirectory()) { throw new IORuntimeException("Unable to find temporary directory"); } return temp; } /** * Returns the path of the system's temporary directory. This method appends the system's file separator at the end of * the path. * * @return the path of the system's temporary directory. */ public static @NotNull String temporaryFolderPath() { String fileSeparator = checkNotNull(separator); String tmpDirPath = checkNotNull(System.getProperty("java.io.tmpdir"));
// Path: src/main/java/org/fest/util/Arrays.java // public static <T> boolean isNullOrEmpty(@Nullable T[] array) { // return array == null || !hasElements(array); // } // // Path: src/main/java/org/fest/util/Closeables.java // public static void closeQuietly(@NotNull Closeable... closeables) { // for (Closeable c : closeables) { // close(c); // } // } // // Path: src/main/java/org/fest/util/Flushables.java // public static void flushQuietly(@NotNull Flushable... flushables) { // for (Flushable f : flushables) { // flush(f); // } // } // // Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/org/fest/util/Strings.java // public static @NotNull StringToAppend append(@NotNull String toAppend) { // return new StringToAppend(toAppend); // } // // Path: src/main/java/org/fest/util/Strings.java // public static @Nullable String quote(@Nullable String s) { // return s != null ? String.format("'%s'", s) : null; // } // Path: src/main/java/org/fest/util/Files.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import static java.io.File.separator; import static java.lang.String.format; import static org.fest.util.Arrays.isNullOrEmpty; import static org.fest.util.Closeables.closeQuietly; import static org.fest.util.Flushables.flushQuietly; import static org.fest.util.Preconditions.checkNotNull; import static org.fest.util.Strings.append; import static org.fest.util.Strings.quote; } String filename = existingFile.getAbsolutePath(); if (!fileNames.contains(filename)) { fileNames.add(filename); } } return fileNames; } /** * @return the system's temporary directory. * @throws IORuntimeException if this method cannot find or create the system's temporary directory. */ public static @NotNull File temporaryFolder() { File temp = new File(temporaryFolderPath()); if (!temp.isDirectory()) { throw new IORuntimeException("Unable to find temporary directory"); } return temp; } /** * Returns the path of the system's temporary directory. This method appends the system's file separator at the end of * the path. * * @return the path of the system's temporary directory. */ public static @NotNull String temporaryFolderPath() { String fileSeparator = checkNotNull(separator); String tmpDirPath = checkNotNull(System.getProperty("java.io.tmpdir"));
return append(fileSeparator).to(tmpDirPath);
alexruiz/fest-util
src/main/java/org/fest/util/Files.java
// Path: src/main/java/org/fest/util/Arrays.java // public static <T> boolean isNullOrEmpty(@Nullable T[] array) { // return array == null || !hasElements(array); // } // // Path: src/main/java/org/fest/util/Closeables.java // public static void closeQuietly(@NotNull Closeable... closeables) { // for (Closeable c : closeables) { // close(c); // } // } // // Path: src/main/java/org/fest/util/Flushables.java // public static void flushQuietly(@NotNull Flushable... flushables) { // for (Flushable f : flushables) { // flush(f); // } // } // // Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/org/fest/util/Strings.java // public static @NotNull StringToAppend append(@NotNull String toAppend) { // return new StringToAppend(toAppend); // } // // Path: src/main/java/org/fest/util/Strings.java // public static @Nullable String quote(@Nullable String s) { // return s != null ? String.format("'%s'", s) : null; // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import static java.io.File.separator; import static java.lang.String.format; import static org.fest.util.Arrays.isNullOrEmpty; import static org.fest.util.Closeables.closeQuietly; import static org.fest.util.Flushables.flushQuietly; import static org.fest.util.Preconditions.checkNotNull; import static org.fest.util.Strings.append; import static org.fest.util.Strings.quote;
public static @NotNull File newTemporaryFile() { String tempFileName = String.format("%d.%s", System.currentTimeMillis(), ".txt"); return newFile(temporaryFolderPath() + tempFileName); } /** * Creates a new directory in the system's temporary directory. The name of the directory will be the result of: * <p/> * <pre> * System.currentTimeMillis(); * </pre> * * @return the created file. */ public static @NotNull File newTemporaryFolder() { String tempFileName = String.valueOf(System.currentTimeMillis()); return newFolder(temporaryFolderPath() + tempFileName); } /** * Creates a new file using the given path. * * @param path the path of the new file. * @return the new created file. * @throws IORuntimeException if the path belongs to an existing non-empty directory. * @throws IORuntimeException if the path belongs to an existing file. * @throws IORuntimeException if any I/O error is thrown when creating the new file. */ public static @NotNull File newFile(@NotNull String path) { File file = new File(path);
// Path: src/main/java/org/fest/util/Arrays.java // public static <T> boolean isNullOrEmpty(@Nullable T[] array) { // return array == null || !hasElements(array); // } // // Path: src/main/java/org/fest/util/Closeables.java // public static void closeQuietly(@NotNull Closeable... closeables) { // for (Closeable c : closeables) { // close(c); // } // } // // Path: src/main/java/org/fest/util/Flushables.java // public static void flushQuietly(@NotNull Flushable... flushables) { // for (Flushable f : flushables) { // flush(f); // } // } // // Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/org/fest/util/Strings.java // public static @NotNull StringToAppend append(@NotNull String toAppend) { // return new StringToAppend(toAppend); // } // // Path: src/main/java/org/fest/util/Strings.java // public static @Nullable String quote(@Nullable String s) { // return s != null ? String.format("'%s'", s) : null; // } // Path: src/main/java/org/fest/util/Files.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import static java.io.File.separator; import static java.lang.String.format; import static org.fest.util.Arrays.isNullOrEmpty; import static org.fest.util.Closeables.closeQuietly; import static org.fest.util.Flushables.flushQuietly; import static org.fest.util.Preconditions.checkNotNull; import static org.fest.util.Strings.append; import static org.fest.util.Strings.quote; public static @NotNull File newTemporaryFile() { String tempFileName = String.format("%d.%s", System.currentTimeMillis(), ".txt"); return newFile(temporaryFolderPath() + tempFileName); } /** * Creates a new directory in the system's temporary directory. The name of the directory will be the result of: * <p/> * <pre> * System.currentTimeMillis(); * </pre> * * @return the created file. */ public static @NotNull File newTemporaryFolder() { String tempFileName = String.valueOf(System.currentTimeMillis()); return newFolder(temporaryFolderPath() + tempFileName); } /** * Creates a new file using the given path. * * @param path the path of the new file. * @return the new created file. * @throws IORuntimeException if the path belongs to an existing non-empty directory. * @throws IORuntimeException if the path belongs to an existing file. * @throws IORuntimeException if any I/O error is thrown when creating the new file. */ public static @NotNull File newFile(@NotNull String path) { File file = new File(path);
if (file.isDirectory() && !isNullOrEmpty(file.list())) {
alexruiz/fest-util
src/main/java/org/fest/util/Files.java
// Path: src/main/java/org/fest/util/Arrays.java // public static <T> boolean isNullOrEmpty(@Nullable T[] array) { // return array == null || !hasElements(array); // } // // Path: src/main/java/org/fest/util/Closeables.java // public static void closeQuietly(@NotNull Closeable... closeables) { // for (Closeable c : closeables) { // close(c); // } // } // // Path: src/main/java/org/fest/util/Flushables.java // public static void flushQuietly(@NotNull Flushable... flushables) { // for (Flushable f : flushables) { // flush(f); // } // } // // Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/org/fest/util/Strings.java // public static @NotNull StringToAppend append(@NotNull String toAppend) { // return new StringToAppend(toAppend); // } // // Path: src/main/java/org/fest/util/Strings.java // public static @Nullable String quote(@Nullable String s) { // return s != null ? String.format("'%s'", s) : null; // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import static java.io.File.separator; import static java.lang.String.format; import static org.fest.util.Arrays.isNullOrEmpty; import static org.fest.util.Closeables.closeQuietly; import static org.fest.util.Flushables.flushQuietly; import static org.fest.util.Preconditions.checkNotNull; import static org.fest.util.Strings.append; import static org.fest.util.Strings.quote;
} return file; } private static @NotNull IORuntimeException cannotCreateNewFile(@NotNull String path, @NotNull String reason) { throw cannotCreateNewFile(path, reason, null); } private static @NotNull IORuntimeException cannotCreateNewFile(@NotNull String path, @NotNull IOException cause) { throw cannotCreateNewFile(path, null, cause); } private static @NotNull IORuntimeException cannotCreateNewFile( @NotNull String path, @Nullable String reason, @Nullable IOException cause) { String message = String.format("Unable to create the new file %s", quote(path)); if (!Strings.isNullOrEmpty(reason)) { message = String.format("%s: %s", message, reason); } return new IORuntimeException(checkNotNull(message), cause); } /** * Flushes and closes the given {@link Writer}. Any I/O errors caught by this method are ignored and not re-thrown. * * @param writer the writer to flush and close. */ public static void flushAndClose(@Nullable Writer writer) { if (writer == null) { return; }
// Path: src/main/java/org/fest/util/Arrays.java // public static <T> boolean isNullOrEmpty(@Nullable T[] array) { // return array == null || !hasElements(array); // } // // Path: src/main/java/org/fest/util/Closeables.java // public static void closeQuietly(@NotNull Closeable... closeables) { // for (Closeable c : closeables) { // close(c); // } // } // // Path: src/main/java/org/fest/util/Flushables.java // public static void flushQuietly(@NotNull Flushable... flushables) { // for (Flushable f : flushables) { // flush(f); // } // } // // Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/org/fest/util/Strings.java // public static @NotNull StringToAppend append(@NotNull String toAppend) { // return new StringToAppend(toAppend); // } // // Path: src/main/java/org/fest/util/Strings.java // public static @Nullable String quote(@Nullable String s) { // return s != null ? String.format("'%s'", s) : null; // } // Path: src/main/java/org/fest/util/Files.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import static java.io.File.separator; import static java.lang.String.format; import static org.fest.util.Arrays.isNullOrEmpty; import static org.fest.util.Closeables.closeQuietly; import static org.fest.util.Flushables.flushQuietly; import static org.fest.util.Preconditions.checkNotNull; import static org.fest.util.Strings.append; import static org.fest.util.Strings.quote; } return file; } private static @NotNull IORuntimeException cannotCreateNewFile(@NotNull String path, @NotNull String reason) { throw cannotCreateNewFile(path, reason, null); } private static @NotNull IORuntimeException cannotCreateNewFile(@NotNull String path, @NotNull IOException cause) { throw cannotCreateNewFile(path, null, cause); } private static @NotNull IORuntimeException cannotCreateNewFile( @NotNull String path, @Nullable String reason, @Nullable IOException cause) { String message = String.format("Unable to create the new file %s", quote(path)); if (!Strings.isNullOrEmpty(reason)) { message = String.format("%s: %s", message, reason); } return new IORuntimeException(checkNotNull(message), cause); } /** * Flushes and closes the given {@link Writer}. Any I/O errors caught by this method are ignored and not re-thrown. * * @param writer the writer to flush and close. */ public static void flushAndClose(@Nullable Writer writer) { if (writer == null) { return; }
flushQuietly(writer);
alexruiz/fest-util
src/main/java/org/fest/util/Files.java
// Path: src/main/java/org/fest/util/Arrays.java // public static <T> boolean isNullOrEmpty(@Nullable T[] array) { // return array == null || !hasElements(array); // } // // Path: src/main/java/org/fest/util/Closeables.java // public static void closeQuietly(@NotNull Closeable... closeables) { // for (Closeable c : closeables) { // close(c); // } // } // // Path: src/main/java/org/fest/util/Flushables.java // public static void flushQuietly(@NotNull Flushable... flushables) { // for (Flushable f : flushables) { // flush(f); // } // } // // Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/org/fest/util/Strings.java // public static @NotNull StringToAppend append(@NotNull String toAppend) { // return new StringToAppend(toAppend); // } // // Path: src/main/java/org/fest/util/Strings.java // public static @Nullable String quote(@Nullable String s) { // return s != null ? String.format("'%s'", s) : null; // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import static java.io.File.separator; import static java.lang.String.format; import static org.fest.util.Arrays.isNullOrEmpty; import static org.fest.util.Closeables.closeQuietly; import static org.fest.util.Flushables.flushQuietly; import static org.fest.util.Preconditions.checkNotNull; import static org.fest.util.Strings.append; import static org.fest.util.Strings.quote;
return file; } private static @NotNull IORuntimeException cannotCreateNewFile(@NotNull String path, @NotNull String reason) { throw cannotCreateNewFile(path, reason, null); } private static @NotNull IORuntimeException cannotCreateNewFile(@NotNull String path, @NotNull IOException cause) { throw cannotCreateNewFile(path, null, cause); } private static @NotNull IORuntimeException cannotCreateNewFile( @NotNull String path, @Nullable String reason, @Nullable IOException cause) { String message = String.format("Unable to create the new file %s", quote(path)); if (!Strings.isNullOrEmpty(reason)) { message = String.format("%s: %s", message, reason); } return new IORuntimeException(checkNotNull(message), cause); } /** * Flushes and closes the given {@link Writer}. Any I/O errors caught by this method are ignored and not re-thrown. * * @param writer the writer to flush and close. */ public static void flushAndClose(@Nullable Writer writer) { if (writer == null) { return; } flushQuietly(writer);
// Path: src/main/java/org/fest/util/Arrays.java // public static <T> boolean isNullOrEmpty(@Nullable T[] array) { // return array == null || !hasElements(array); // } // // Path: src/main/java/org/fest/util/Closeables.java // public static void closeQuietly(@NotNull Closeable... closeables) { // for (Closeable c : closeables) { // close(c); // } // } // // Path: src/main/java/org/fest/util/Flushables.java // public static void flushQuietly(@NotNull Flushable... flushables) { // for (Flushable f : flushables) { // flush(f); // } // } // // Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // // Path: src/main/java/org/fest/util/Strings.java // public static @NotNull StringToAppend append(@NotNull String toAppend) { // return new StringToAppend(toAppend); // } // // Path: src/main/java/org/fest/util/Strings.java // public static @Nullable String quote(@Nullable String s) { // return s != null ? String.format("'%s'", s) : null; // } // Path: src/main/java/org/fest/util/Files.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.*; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import static java.io.File.separator; import static java.lang.String.format; import static org.fest.util.Arrays.isNullOrEmpty; import static org.fest.util.Closeables.closeQuietly; import static org.fest.util.Flushables.flushQuietly; import static org.fest.util.Preconditions.checkNotNull; import static org.fest.util.Strings.append; import static org.fest.util.Strings.quote; return file; } private static @NotNull IORuntimeException cannotCreateNewFile(@NotNull String path, @NotNull String reason) { throw cannotCreateNewFile(path, reason, null); } private static @NotNull IORuntimeException cannotCreateNewFile(@NotNull String path, @NotNull IOException cause) { throw cannotCreateNewFile(path, null, cause); } private static @NotNull IORuntimeException cannotCreateNewFile( @NotNull String path, @Nullable String reason, @Nullable IOException cause) { String message = String.format("Unable to create the new file %s", quote(path)); if (!Strings.isNullOrEmpty(reason)) { message = String.format("%s: %s", message, reason); } return new IORuntimeException(checkNotNull(message), cause); } /** * Flushes and closes the given {@link Writer}. Any I/O errors caught by this method are ignored and not re-thrown. * * @param writer the writer to flush and close. */ public static void flushAndClose(@Nullable Writer writer) { if (writer == null) { return; } flushQuietly(writer);
closeQuietly(writer);
alexruiz/fest-util
src/main/java/org/fest/util/Arrays.java
// Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import static org.fest.util.Preconditions.checkNotNull;
/* * Created on May 13, 2007 * * 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. * * Copyright @2007-2013 the original author or authors. */ package org.fest.util; /** * Utility methods related to arrays. * * @author Alex Ruiz * @author Joel Costigliola */ public class Arrays { private static final ArrayFormatter FORMATTER = new ArrayFormatter(); private Arrays() { } /** * Indicates whether the given object is not {@code null} and is an array. * * @param o the given object. * @return {@code true} if the given object is not {@code null} and is an array, otherwise {@code false}. */ public static boolean isArray(@Nullable Object o) { return o != null && o.getClass().isArray(); } /** * Indicates whether the given array is {@code null} or empty. * * @param <T> the type of elements of the array. * @param array the array to check. * @return {@code true} if the given array is {@code null} or empty, otherwise {@code false}. */ public static <T> boolean isNullOrEmpty(@Nullable T[] array) { return array == null || !hasElements(array); } /** * Returns an array containing the given arguments. * * @param <T> the type of the array to return. * @param values the values to store in the array. * @return an array containing the given arguments. */ public static @NotNull <T> T[] array(@NotNull T... values) {
// Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/org/fest/util/Arrays.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import static org.fest.util.Preconditions.checkNotNull; /* * Created on May 13, 2007 * * 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. * * Copyright @2007-2013 the original author or authors. */ package org.fest.util; /** * Utility methods related to arrays. * * @author Alex Ruiz * @author Joel Costigliola */ public class Arrays { private static final ArrayFormatter FORMATTER = new ArrayFormatter(); private Arrays() { } /** * Indicates whether the given object is not {@code null} and is an array. * * @param o the given object. * @return {@code true} if the given object is not {@code null} and is an array, otherwise {@code false}. */ public static boolean isArray(@Nullable Object o) { return o != null && o.getClass().isArray(); } /** * Indicates whether the given array is {@code null} or empty. * * @param <T> the type of elements of the array. * @param array the array to check. * @return {@code true} if the given array is {@code null} or empty, otherwise {@code false}. */ public static <T> boolean isNullOrEmpty(@Nullable T[] array) { return array == null || !hasElements(array); } /** * Returns an array containing the given arguments. * * @param <T> the type of the array to return. * @param values the values to store in the array. * @return an array containing the given arguments. */ public static @NotNull <T> T[] array(@NotNull T... values) {
return checkNotNull(values);
alexruiz/fest-util
src/test/java/org/fest/util/Collections_nonNullElementsIn_Test.java
// Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) { // checkNotNull(elements); // ArrayList<T> list = newArrayList(); // for (T e : elements) { // list.add(e); // } // return list; // }
import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static org.fest.util.Lists.newArrayList; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertTrue;
/* * Created on Jun 17, 2010 * * 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. * * Copyright @2010-2013 the original author or authors. */ package org.fest.util; /** * Tests for {@link Collections#nonNullElementsIn(Collection)}. * * @author Joel Costigliola * @author Alex Ruiz */ public class Collections_nonNullElementsIn_Test { @Test public void should_return_empty_List_if_given_Collection_is_null() { Collection<?> c = null; assertTrue(Collections.nonNullElementsIn(c).isEmpty()); } @Test public void should_return_empty_List_if_given_Collection_has_only_null_elements() { Collection<String> c = new ArrayList<String>(); c.add(null); assertTrue(Collections.nonNullElementsIn(c).isEmpty()); } @Test public void should_return_empty_List_if_given_Collection_is_empty() { Collection<String> c = new ArrayList<String>(); assertTrue(Collections.nonNullElementsIn(c).isEmpty()); } @Test public void should_return_a_list_without_null_elements() {
// Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) { // checkNotNull(elements); // ArrayList<T> list = newArrayList(); // for (T e : elements) { // list.add(e); // } // return list; // } // Path: src/test/java/org/fest/util/Collections_nonNullElementsIn_Test.java import org.junit.Test; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static org.fest.util.Lists.newArrayList; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertTrue; /* * Created on Jun 17, 2010 * * 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. * * Copyright @2010-2013 the original author or authors. */ package org.fest.util; /** * Tests for {@link Collections#nonNullElementsIn(Collection)}. * * @author Joel Costigliola * @author Alex Ruiz */ public class Collections_nonNullElementsIn_Test { @Test public void should_return_empty_List_if_given_Collection_is_null() { Collection<?> c = null; assertTrue(Collections.nonNullElementsIn(c).isEmpty()); } @Test public void should_return_empty_List_if_given_Collection_has_only_null_elements() { Collection<String> c = new ArrayList<String>(); c.add(null); assertTrue(Collections.nonNullElementsIn(c).isEmpty()); } @Test public void should_return_empty_List_if_given_Collection_is_empty() { Collection<String> c = new ArrayList<String>(); assertTrue(Collections.nonNullElementsIn(c).isEmpty()); } @Test public void should_return_a_list_without_null_elements() {
List<String> c = newArrayList("Frodo", null, "Sam", null);
alexruiz/fest-util
src/main/java/org/fest/util/Lists.java
// Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import static org.fest.util.Preconditions.checkNotNull;
/* * Created on Aug 23, 2012 * * 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. * * Copyright @2012-2013 the original author or authors. */ package org.fest.util; /** * Utility methods related to {@code java.util.List}s. * * @author Yvonne Wang * @author Alex Ruiz * @author Joel Costigliola */ public final class Lists { private Lists() { } /** * Creates a <em>mutable</em> {@link ArrayList} containing the given elements. * * @param <T> the generic type of the {@code ArrayList} to create. * @param elements the elements to store in the {@code ArrayList}. * @return the created {@code ArrayList}. * @throws NullPointerException if the given array is {@code null}. */ public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) {
// Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/org/fest/util/Lists.java import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import static org.fest.util.Preconditions.checkNotNull; /* * Created on Aug 23, 2012 * * 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. * * Copyright @2012-2013 the original author or authors. */ package org.fest.util; /** * Utility methods related to {@code java.util.List}s. * * @author Yvonne Wang * @author Alex Ruiz * @author Joel Costigliola */ public final class Lists { private Lists() { } /** * Creates a <em>mutable</em> {@link ArrayList} containing the given elements. * * @param <T> the generic type of the {@code ArrayList} to create. * @param elements the elements to store in the {@code ArrayList}. * @return the created {@code ArrayList}. * @throws NullPointerException if the given array is {@code null}. */ public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) {
checkNotNull(elements);
alexruiz/fest-util
src/test/java/org/fest/util/Files_temporaryFolderPath_Test.java
// Path: src/main/java/org/fest/util/Strings.java // public static @NotNull StringToAppend append(@NotNull String toAppend) { // return new StringToAppend(toAppend); // }
import org.junit.Test; import static java.io.File.separator; import static org.fest.util.Strings.append; import static org.junit.Assert.assertEquals;
/* * Created on Sep 23, 2006 * * 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. * * Copyright @2006-2011 the original author or authors. */ package org.fest.util; /** * Tests for {@link Files#temporaryFolderPath()}. * * @author Alex Ruiz * @author Yvonne Wang */ public class Files_temporaryFolderPath_Test extends Files_TestCase { @Test public void should_find_path_of_temporary_folder() { String a = Files.temporaryFolderPath();
// Path: src/main/java/org/fest/util/Strings.java // public static @NotNull StringToAppend append(@NotNull String toAppend) { // return new StringToAppend(toAppend); // } // Path: src/test/java/org/fest/util/Files_temporaryFolderPath_Test.java import org.junit.Test; import static java.io.File.separator; import static org.fest.util.Strings.append; import static org.junit.Assert.assertEquals; /* * Created on Sep 23, 2006 * * 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. * * Copyright @2006-2011 the original author or authors. */ package org.fest.util; /** * Tests for {@link Files#temporaryFolderPath()}. * * @author Alex Ruiz * @author Yvonne Wang */ public class Files_temporaryFolderPath_Test extends Files_TestCase { @Test public void should_find_path_of_temporary_folder() { String a = Files.temporaryFolderPath();
String e = append(separator).to(systemTemporaryFolder());
alexruiz/fest-util
src/test/java/org/fest/util/Arrays_nonNullElementsIn_Test.java
// Path: src/main/java/org/fest/util/Arrays.java // public static <T> List<T> nonNullElementsIn(@NotNull T[] array) { // checkNotNull(array); // List<T> nonNullElements = new ArrayList<T>(); // for (T o : array) { // if (o != null) { // nonNullElements.add(o); // } // } // return nonNullElements; // }
import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.util.List; import static org.fest.util.Arrays.nonNullElementsIn; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertTrue; import static org.junit.rules.ExpectedException.none;
/* * Created on May 13, 2007 * * 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. * * Copyright @2007-2013 the original author or authors. */ package org.fest.util; /** * Tests for {@link Arrays#nonNullElementsIn(Object[])}. * * @author Joel Costigliola * @author Alex Ruiz */ public class Arrays_nonNullElementsIn_Test { @Rule public ExpectedException thrown = none(); @Test public void should_throw_error_if_given_array_is_null() { thrown.expect(NullPointerException.class);
// Path: src/main/java/org/fest/util/Arrays.java // public static <T> List<T> nonNullElementsIn(@NotNull T[] array) { // checkNotNull(array); // List<T> nonNullElements = new ArrayList<T>(); // for (T o : array) { // if (o != null) { // nonNullElements.add(o); // } // } // return nonNullElements; // } // Path: src/test/java/org/fest/util/Arrays_nonNullElementsIn_Test.java import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.util.List; import static org.fest.util.Arrays.nonNullElementsIn; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertTrue; import static org.junit.rules.ExpectedException.none; /* * Created on May 13, 2007 * * 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. * * Copyright @2007-2013 the original author or authors. */ package org.fest.util; /** * Tests for {@link Arrays#nonNullElementsIn(Object[])}. * * @author Joel Costigliola * @author Alex Ruiz */ public class Arrays_nonNullElementsIn_Test { @Rule public ExpectedException thrown = none(); @Test public void should_throw_error_if_given_array_is_null() { thrown.expect(NullPointerException.class);
Arrays.nonNullElementsIn(null);
alexruiz/fest-util
src/main/java/org/fest/util/Sets.java
// Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import org.jetbrains.annotations.NotNull; import java.util.HashSet; import java.util.LinkedHashSet; import static java.util.Collections.addAll; import static org.fest.util.Preconditions.checkNotNull;
/* * Created on Aug 23, 2012 * * 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. * * Copyright @2012-2013 the original author or authors. */ package org.fest.util; /** * Utility methods related to {@code java.util.Set}s. * * @author Alex Ruiz */ public final class Sets { private Sets() { } /** * Creates a <em>mutable</em> {@code HashSet}. * * @param <T> the generic type of the {@code HashSet} to create. * @return the created {@code HashSet}. * @since 1.2.3 */ public static @NotNull <T> HashSet<T> newHashSet() { return new HashSet<T>(); } /** * Creates a <em>mutable</em> {@code HashSet} containing the given elements. * * @param <T> the generic type of the {@code HashSet} to create. * @param elements the elements to store in the {@code HashSet}. * @return the created {@code HashSet}. * @throws NullPointerException if the given {@code Iterable} is {@code null}. * @since 1.2.3 */ public static @NotNull <T> HashSet<T> newHashSet(@NotNull Iterable<? extends T> elements) { HashSet<T> set = newHashSet(); for (T e : elements) { set.add(e); } return set; } /** * Creates a <em>mutable</em> {@code LinkedHashSet}. * * @param <T> the generic type of the {@code LinkedHashSet} to create. * @return the created {@code LinkedHashSet}. * @since 1.2.3 */ public static @NotNull <T> LinkedHashSet<T> newLinkedHashSet() { return new LinkedHashSet<T>(); } /** * Creates a <em>mutable</em> {@link LinkedHashSet} containing the given elements. * * @param <T> the generic type of the {@code LinkedHashSet} to create. * @param elements the elements to store in the {@code LinkedHashSet}. * @return the created {@code LinkedHashSet}. * @throws NullPointerException if the given array is {@code null}. * @since 1.2.3 */ public static @NotNull <T> LinkedHashSet<T> newLinkedHashSet(@NotNull T... elements) {
// Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/org/fest/util/Sets.java import org.jetbrains.annotations.NotNull; import java.util.HashSet; import java.util.LinkedHashSet; import static java.util.Collections.addAll; import static org.fest.util.Preconditions.checkNotNull; /* * Created on Aug 23, 2012 * * 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. * * Copyright @2012-2013 the original author or authors. */ package org.fest.util; /** * Utility methods related to {@code java.util.Set}s. * * @author Alex Ruiz */ public final class Sets { private Sets() { } /** * Creates a <em>mutable</em> {@code HashSet}. * * @param <T> the generic type of the {@code HashSet} to create. * @return the created {@code HashSet}. * @since 1.2.3 */ public static @NotNull <T> HashSet<T> newHashSet() { return new HashSet<T>(); } /** * Creates a <em>mutable</em> {@code HashSet} containing the given elements. * * @param <T> the generic type of the {@code HashSet} to create. * @param elements the elements to store in the {@code HashSet}. * @return the created {@code HashSet}. * @throws NullPointerException if the given {@code Iterable} is {@code null}. * @since 1.2.3 */ public static @NotNull <T> HashSet<T> newHashSet(@NotNull Iterable<? extends T> elements) { HashSet<T> set = newHashSet(); for (T e : elements) { set.add(e); } return set; } /** * Creates a <em>mutable</em> {@code LinkedHashSet}. * * @param <T> the generic type of the {@code LinkedHashSet} to create. * @return the created {@code LinkedHashSet}. * @since 1.2.3 */ public static @NotNull <T> LinkedHashSet<T> newLinkedHashSet() { return new LinkedHashSet<T>(); } /** * Creates a <em>mutable</em> {@link LinkedHashSet} containing the given elements. * * @param <T> the generic type of the {@code LinkedHashSet} to create. * @param elements the elements to store in the {@code LinkedHashSet}. * @return the created {@code LinkedHashSet}. * @throws NullPointerException if the given array is {@code null}. * @since 1.2.3 */ public static @NotNull <T> LinkedHashSet<T> newLinkedHashSet(@NotNull T... elements) {
checkNotNull(elements);
alexruiz/fest-util
src/test/java/org/fest/util/Throwables_appendCurrentThreadStackTraceToThrowable_Test.java
// Path: src/main/java/org/fest/util/Strings.java // public static @NotNull String concat(@NotNull Object... objects) { // checkNotNull(objects); // StringBuilder b = new StringBuilder(); // for (Object o : objects) { // b.append(o); // } // return b.toString(); // }
import org.junit.Before; import org.junit.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference; import static java.lang.Thread.currentThread; import static org.fest.util.Strings.concat; import static org.junit.Assert.assertEquals;
exceptionReference = new AtomicReference<RuntimeException>(); } @Test public void should_add_stack_trace_of_current_thread() { final CountDownLatch latch = new CountDownLatch(1); new Thread() { @Override public void run() { RuntimeException e = new RuntimeException("Thrown on purpose"); exceptionReference.set(e); latch.countDown(); } }.start(); try { latch.await(); } catch (InterruptedException e) { currentThread().interrupt(); } RuntimeException thrown = exceptionReference.get(); Throwables.appendStackTraceInCurentThreadToThrowable(thrown, "should_add_stack_trace_of_current_thread"); StackTraceElement[] stackTrace = thrown.getStackTrace(); assertEquals("org.fest.util.Throwables_appendCurrentThreadStackTraceToThrowable_Test$1.run", asString(stackTrace[0])); assertEquals( "org.fest.util.Throwables_appendCurrentThreadStackTraceToThrowable_Test.should_add_stack_trace_of_current_thread", asString(stackTrace[1])); } private String asString(StackTraceElement e) {
// Path: src/main/java/org/fest/util/Strings.java // public static @NotNull String concat(@NotNull Object... objects) { // checkNotNull(objects); // StringBuilder b = new StringBuilder(); // for (Object o : objects) { // b.append(o); // } // return b.toString(); // } // Path: src/test/java/org/fest/util/Throwables_appendCurrentThreadStackTraceToThrowable_Test.java import org.junit.Before; import org.junit.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference; import static java.lang.Thread.currentThread; import static org.fest.util.Strings.concat; import static org.junit.Assert.assertEquals; exceptionReference = new AtomicReference<RuntimeException>(); } @Test public void should_add_stack_trace_of_current_thread() { final CountDownLatch latch = new CountDownLatch(1); new Thread() { @Override public void run() { RuntimeException e = new RuntimeException("Thrown on purpose"); exceptionReference.set(e); latch.countDown(); } }.start(); try { latch.await(); } catch (InterruptedException e) { currentThread().interrupt(); } RuntimeException thrown = exceptionReference.get(); Throwables.appendStackTraceInCurentThreadToThrowable(thrown, "should_add_stack_trace_of_current_thread"); StackTraceElement[] stackTrace = thrown.getStackTrace(); assertEquals("org.fest.util.Throwables_appendCurrentThreadStackTraceToThrowable_Test$1.run", asString(stackTrace[0])); assertEquals( "org.fest.util.Throwables_appendCurrentThreadStackTraceToThrowable_Test.should_add_stack_trace_of_current_thread", asString(stackTrace[1])); } private String asString(StackTraceElement e) {
return concat(e.getClassName(), ".", e.getMethodName());
alexruiz/fest-util
src/test/java/org/fest/util/Files_newFile_Test.java
// Path: src/main/java/org/fest/util/Strings.java // public static @NotNull StringsToJoin join(@NotNull String... strings) { // return new StringsToJoin(strings); // }
import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.File; import static java.io.File.separator; import static org.fest.util.Strings.join; import static org.junit.Assert.assertTrue; import static org.junit.rules.ExpectedException.none;
/* * Created on Sep 23, 2006 * * 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. * * Copyright @2006-2011 the original author or authors. */ package org.fest.util; /** * Tests for {@link Files#newFile(String)}. * * @author Alex Ruiz * @author Yvonne Wang */ public class Files_newFile_Test extends Files_TestCase { @Rule public ExpectedException thrown = none(); @Test public void should_throw_error_if_file_path_belongs_to_directory_that_is_not_empty() { thrown.expect(IORuntimeException.class); Files.newFile("root"); } @Test public void should_throw_error_if_file_path_belongs_to_an_existing_file() {
// Path: src/main/java/org/fest/util/Strings.java // public static @NotNull StringsToJoin join(@NotNull String... strings) { // return new StringsToJoin(strings); // } // Path: src/test/java/org/fest/util/Files_newFile_Test.java import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.File; import static java.io.File.separator; import static org.fest.util.Strings.join; import static org.junit.Assert.assertTrue; import static org.junit.rules.ExpectedException.none; /* * Created on Sep 23, 2006 * * 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. * * Copyright @2006-2011 the original author or authors. */ package org.fest.util; /** * Tests for {@link Files#newFile(String)}. * * @author Alex Ruiz * @author Yvonne Wang */ public class Files_newFile_Test extends Files_TestCase { @Rule public ExpectedException thrown = none(); @Test public void should_throw_error_if_file_path_belongs_to_directory_that_is_not_empty() { thrown.expect(IORuntimeException.class); Files.newFile("root"); } @Test public void should_throw_error_if_file_path_belongs_to_an_existing_file() {
String path = join("root", "dir_1", "file_1_1").with(separator);
alexruiz/fest-util
src/main/java/org/fest/util/Maps.java
// Path: src/main/java/org/fest/util/ToString.java // public static @Nullable String toStringOf(@Nullable Object o) { // if (isArray(o)) { // return Arrays.format(o); // } // if (o instanceof Calendar) { // return toStringOf(o); // } // if (o instanceof Class<?>) { // return toStringOf((Class<?>) o); // } // if (o instanceof Collection<?>) { // return toStringOf((Collection<?>) o); // } // if (o instanceof Date) { // return toStringOf(o); // } // if (o instanceof Float) { // return toStringOf((Float) o); // } // if (o instanceof Long) { // return toStringOf((Long) o); // } // if (o instanceof File) { // return toStringOf((File) o); // } // if (o instanceof Map<?, ?>) { // return toStringOf((Map<?, ?>) o); // } // if (o instanceof String) { // return quote((String) o); // } // if (o instanceof Comparator) { // return toStringOf((Comparator<?>) o); // } // return o == null ? null : o.toString(); // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static org.fest.util.ToString.toStringOf;
/** * Returns the {@code String} representation of the given map, or {@code null} if the given map is {@code null}. * * @param map the map to format. * @return the {@code String} representation of the given map. */ public static @Nullable String format(@Nullable Map<?, ?> map) { if (map == null) { return null; } Iterator<?> i = map.entrySet().iterator(); if (!i.hasNext()) { return "{}"; } StringBuilder buffer = new StringBuilder(); buffer.append("{"); for (; ; ) { Entry<?, ?> e = (Entry<?, ?>) i.next(); buffer.append(format(map, e.getKey())); buffer.append('='); buffer.append(format(map, e.getValue())); if (!i.hasNext()) { return buffer.append("}").toString(); } buffer.append(", "); } } private static @Nullable Object format(@NotNull Map<?, ?> map, @Nullable Object o) {
// Path: src/main/java/org/fest/util/ToString.java // public static @Nullable String toStringOf(@Nullable Object o) { // if (isArray(o)) { // return Arrays.format(o); // } // if (o instanceof Calendar) { // return toStringOf(o); // } // if (o instanceof Class<?>) { // return toStringOf((Class<?>) o); // } // if (o instanceof Collection<?>) { // return toStringOf((Collection<?>) o); // } // if (o instanceof Date) { // return toStringOf(o); // } // if (o instanceof Float) { // return toStringOf((Float) o); // } // if (o instanceof Long) { // return toStringOf((Long) o); // } // if (o instanceof File) { // return toStringOf((File) o); // } // if (o instanceof Map<?, ?>) { // return toStringOf((Map<?, ?>) o); // } // if (o instanceof String) { // return quote((String) o); // } // if (o instanceof Comparator) { // return toStringOf((Comparator<?>) o); // } // return o == null ? null : o.toString(); // } // Path: src/main/java/org/fest/util/Maps.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import static org.fest.util.ToString.toStringOf; /** * Returns the {@code String} representation of the given map, or {@code null} if the given map is {@code null}. * * @param map the map to format. * @return the {@code String} representation of the given map. */ public static @Nullable String format(@Nullable Map<?, ?> map) { if (map == null) { return null; } Iterator<?> i = map.entrySet().iterator(); if (!i.hasNext()) { return "{}"; } StringBuilder buffer = new StringBuilder(); buffer.append("{"); for (; ; ) { Entry<?, ?> e = (Entry<?, ?>) i.next(); buffer.append(format(map, e.getKey())); buffer.append('='); buffer.append(format(map, e.getValue())); if (!i.hasNext()) { return buffer.append("}").toString(); } buffer.append(", "); } } private static @Nullable Object format(@NotNull Map<?, ?> map, @Nullable Object o) {
return o == map ? "(this Map)" : toStringOf(o);
alexruiz/fest-util
src/main/java/org/fest/util/Iterables.java
// Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import static java.util.Collections.emptyList; import static org.fest.util.Preconditions.checkNotNull;
/* * Created on Aug 23, 2012 * * 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. * * Copyright @2012-2013 the original author or authors. */ package org.fest.util; /** * Utility methods related to {@code Iterable}s. * * @author Yvonne Wang * @author Alex Ruiz * @author Joel Costigliola */ // TODO(alexRuiz): Get rid of this class. public final class Iterables { private Iterables() { } /** * Indicates whether the given {@link Iterable} is {@code null} or empty. * * @param iterable the given {@code Iterable} to check. * @return {@code true} if the given {@code Iterable} is {@code null} or empty, otherwise {@code false}. */ public static boolean isNullOrEmpty(@Nullable Iterable<?> iterable) { if (iterable == null) { return true; } if (iterable instanceof Collection && ((Collection<?>) iterable).isEmpty()) { return true; } return !iterable.iterator().hasNext(); } /** * Returns the size of the given {@link Iterable}. * * @param iterable the {@link Iterable} to get size. * @return the size of the given {@link Iterable}. * @throws NullPointerException if given {@link Iterable} is null. */ public static int sizeOf(@NotNull Iterable<?> iterable) {
// Path: src/main/java/org/fest/util/Preconditions.java // public static @NotNull <T> T checkNotNull(@Nullable T reference) { // if (reference == null) { // throw new NullPointerException(); // } // return reference; // } // Path: src/main/java/org/fest/util/Iterables.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import static java.util.Collections.emptyList; import static org.fest.util.Preconditions.checkNotNull; /* * Created on Aug 23, 2012 * * 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. * * Copyright @2012-2013 the original author or authors. */ package org.fest.util; /** * Utility methods related to {@code Iterable}s. * * @author Yvonne Wang * @author Alex Ruiz * @author Joel Costigliola */ // TODO(alexRuiz): Get rid of this class. public final class Iterables { private Iterables() { } /** * Indicates whether the given {@link Iterable} is {@code null} or empty. * * @param iterable the given {@code Iterable} to check. * @return {@code true} if the given {@code Iterable} is {@code null} or empty, otherwise {@code false}. */ public static boolean isNullOrEmpty(@Nullable Iterable<?> iterable) { if (iterable == null) { return true; } if (iterable instanceof Collection && ((Collection<?>) iterable).isEmpty()) { return true; } return !iterable.iterator().hasNext(); } /** * Returns the size of the given {@link Iterable}. * * @param iterable the {@link Iterable} to get size. * @return the size of the given {@link Iterable}. * @throws NullPointerException if given {@link Iterable} is null. */ public static int sizeOf(@NotNull Iterable<?> iterable) {
checkNotNull(iterable);
alexruiz/fest-util
src/main/java/org/fest/util/Collections.java
// Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> List<T> emptyList() { // return Collections.emptyList(); // } // // Path: src/main/java/org/fest/util/Sets.java // public static @NotNull <T> HashSet<T> newHashSet() { // return new HashSet<T>(); // } // // Path: src/main/java/org/fest/util/ToString.java // public static @Nullable String toStringOf(@Nullable Object o) { // if (isArray(o)) { // return Arrays.format(o); // } // if (o instanceof Calendar) { // return toStringOf(o); // } // if (o instanceof Class<?>) { // return toStringOf((Class<?>) o); // } // if (o instanceof Collection<?>) { // return toStringOf((Collection<?>) o); // } // if (o instanceof Date) { // return toStringOf(o); // } // if (o instanceof Float) { // return toStringOf((Float) o); // } // if (o instanceof Long) { // return toStringOf((Long) o); // } // if (o instanceof File) { // return toStringOf((File) o); // } // if (o instanceof Map<?, ?>) { // return toStringOf((Map<?, ?>) o); // } // if (o instanceof String) { // return quote((String) o); // } // if (o instanceof Comparator) { // return toStringOf((Comparator<?>) o); // } // return o == null ? null : o.toString(); // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import static org.fest.util.Lists.emptyList; import static org.fest.util.Sets.newHashSet; import static org.fest.util.ToString.toStringOf;
/* * Created on Apr 29, 2007 * * 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. * * Copyright @2007-2013 the original author or authors. */ package org.fest.util; /** * Utility methods related to {@code Collection}s. * * @author Yvonne Wang * @author Alex Ruiz * @author Joel Costigliola */ public final class Collections { private Collections() { } /** * Returns any duplicate elements from the given {@code Collection}. * * @param <T> the generic type of the given {@code Collection}. * @param c the given {@code Collection} that might have duplicate elements. * @return a {@code Collection} containing the duplicate elements of the given one. If the given {@code Collection} is * {@code null} or if no duplicates were found, an empty {@code Collection} is returned. */ public static @NotNull <T> Collection<T> duplicatesFrom(@Nullable Collection<T> c) { Set<T> duplicates = new LinkedHashSet<T>(); if (c == null) { return duplicates; }
// Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> List<T> emptyList() { // return Collections.emptyList(); // } // // Path: src/main/java/org/fest/util/Sets.java // public static @NotNull <T> HashSet<T> newHashSet() { // return new HashSet<T>(); // } // // Path: src/main/java/org/fest/util/ToString.java // public static @Nullable String toStringOf(@Nullable Object o) { // if (isArray(o)) { // return Arrays.format(o); // } // if (o instanceof Calendar) { // return toStringOf(o); // } // if (o instanceof Class<?>) { // return toStringOf((Class<?>) o); // } // if (o instanceof Collection<?>) { // return toStringOf((Collection<?>) o); // } // if (o instanceof Date) { // return toStringOf(o); // } // if (o instanceof Float) { // return toStringOf((Float) o); // } // if (o instanceof Long) { // return toStringOf((Long) o); // } // if (o instanceof File) { // return toStringOf((File) o); // } // if (o instanceof Map<?, ?>) { // return toStringOf((Map<?, ?>) o); // } // if (o instanceof String) { // return quote((String) o); // } // if (o instanceof Comparator) { // return toStringOf((Comparator<?>) o); // } // return o == null ? null : o.toString(); // } // Path: src/main/java/org/fest/util/Collections.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import static org.fest.util.Lists.emptyList; import static org.fest.util.Sets.newHashSet; import static org.fest.util.ToString.toStringOf; /* * Created on Apr 29, 2007 * * 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. * * Copyright @2007-2013 the original author or authors. */ package org.fest.util; /** * Utility methods related to {@code Collection}s. * * @author Yvonne Wang * @author Alex Ruiz * @author Joel Costigliola */ public final class Collections { private Collections() { } /** * Returns any duplicate elements from the given {@code Collection}. * * @param <T> the generic type of the given {@code Collection}. * @param c the given {@code Collection} that might have duplicate elements. * @return a {@code Collection} containing the duplicate elements of the given one. If the given {@code Collection} is * {@code null} or if no duplicates were found, an empty {@code Collection} is returned. */ public static @NotNull <T> Collection<T> duplicatesFrom(@Nullable Collection<T> c) { Set<T> duplicates = new LinkedHashSet<T>(); if (c == null) { return duplicates; }
Set<T> unique = newHashSet();
alexruiz/fest-util
src/main/java/org/fest/util/Collections.java
// Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> List<T> emptyList() { // return Collections.emptyList(); // } // // Path: src/main/java/org/fest/util/Sets.java // public static @NotNull <T> HashSet<T> newHashSet() { // return new HashSet<T>(); // } // // Path: src/main/java/org/fest/util/ToString.java // public static @Nullable String toStringOf(@Nullable Object o) { // if (isArray(o)) { // return Arrays.format(o); // } // if (o instanceof Calendar) { // return toStringOf(o); // } // if (o instanceof Class<?>) { // return toStringOf((Class<?>) o); // } // if (o instanceof Collection<?>) { // return toStringOf((Collection<?>) o); // } // if (o instanceof Date) { // return toStringOf(o); // } // if (o instanceof Float) { // return toStringOf((Float) o); // } // if (o instanceof Long) { // return toStringOf((Long) o); // } // if (o instanceof File) { // return toStringOf((File) o); // } // if (o instanceof Map<?, ?>) { // return toStringOf((Map<?, ?>) o); // } // if (o instanceof String) { // return quote((String) o); // } // if (o instanceof Comparator) { // return toStringOf((Comparator<?>) o); // } // return o == null ? null : o.toString(); // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import static org.fest.util.Lists.emptyList; import static org.fest.util.Sets.newHashSet; import static org.fest.util.ToString.toStringOf;
/** * Indicates whether the given {@code Collection} is {@code null} or empty. * * @param c the given {@code Collection}. * @return {@code true} if the given {@code Collection} is {@code null} or empty, otherwise {@code false}. */ public static boolean isNullOrEmpty(@Nullable Collection<?> c) { return c == null || c.isEmpty(); } /** * Returns the {@code String} representation of the given {@code Collection}, or {@code null} if the given {@code * Collection} is {@code null}. * * @param c the {@code Collection} to format. * @return the {@code String} representation of the given {@code Collection}. */ public static @Nullable String format(@Nullable Collection<?> c) { if (c == null) { return null; } Iterator<?> i = c.iterator(); if (!i.hasNext()) { return "[]"; } StringBuilder b = new StringBuilder(); b.append('['); for (; ; ) { Object e = i.next();
// Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> List<T> emptyList() { // return Collections.emptyList(); // } // // Path: src/main/java/org/fest/util/Sets.java // public static @NotNull <T> HashSet<T> newHashSet() { // return new HashSet<T>(); // } // // Path: src/main/java/org/fest/util/ToString.java // public static @Nullable String toStringOf(@Nullable Object o) { // if (isArray(o)) { // return Arrays.format(o); // } // if (o instanceof Calendar) { // return toStringOf(o); // } // if (o instanceof Class<?>) { // return toStringOf((Class<?>) o); // } // if (o instanceof Collection<?>) { // return toStringOf((Collection<?>) o); // } // if (o instanceof Date) { // return toStringOf(o); // } // if (o instanceof Float) { // return toStringOf((Float) o); // } // if (o instanceof Long) { // return toStringOf((Long) o); // } // if (o instanceof File) { // return toStringOf((File) o); // } // if (o instanceof Map<?, ?>) { // return toStringOf((Map<?, ?>) o); // } // if (o instanceof String) { // return quote((String) o); // } // if (o instanceof Comparator) { // return toStringOf((Comparator<?>) o); // } // return o == null ? null : o.toString(); // } // Path: src/main/java/org/fest/util/Collections.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import static org.fest.util.Lists.emptyList; import static org.fest.util.Sets.newHashSet; import static org.fest.util.ToString.toStringOf; /** * Indicates whether the given {@code Collection} is {@code null} or empty. * * @param c the given {@code Collection}. * @return {@code true} if the given {@code Collection} is {@code null} or empty, otherwise {@code false}. */ public static boolean isNullOrEmpty(@Nullable Collection<?> c) { return c == null || c.isEmpty(); } /** * Returns the {@code String} representation of the given {@code Collection}, or {@code null} if the given {@code * Collection} is {@code null}. * * @param c the {@code Collection} to format. * @return the {@code String} representation of the given {@code Collection}. */ public static @Nullable String format(@Nullable Collection<?> c) { if (c == null) { return null; } Iterator<?> i = c.iterator(); if (!i.hasNext()) { return "[]"; } StringBuilder b = new StringBuilder(); b.append('['); for (; ; ) { Object e = i.next();
b.append(e == c ? "(this Collection)" : toStringOf(e));
alexruiz/fest-util
src/main/java/org/fest/util/Collections.java
// Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> List<T> emptyList() { // return Collections.emptyList(); // } // // Path: src/main/java/org/fest/util/Sets.java // public static @NotNull <T> HashSet<T> newHashSet() { // return new HashSet<T>(); // } // // Path: src/main/java/org/fest/util/ToString.java // public static @Nullable String toStringOf(@Nullable Object o) { // if (isArray(o)) { // return Arrays.format(o); // } // if (o instanceof Calendar) { // return toStringOf(o); // } // if (o instanceof Class<?>) { // return toStringOf((Class<?>) o); // } // if (o instanceof Collection<?>) { // return toStringOf((Collection<?>) o); // } // if (o instanceof Date) { // return toStringOf(o); // } // if (o instanceof Float) { // return toStringOf((Float) o); // } // if (o instanceof Long) { // return toStringOf((Long) o); // } // if (o instanceof File) { // return toStringOf((File) o); // } // if (o instanceof Map<?, ?>) { // return toStringOf((Map<?, ?>) o); // } // if (o instanceof String) { // return quote((String) o); // } // if (o instanceof Comparator) { // return toStringOf((Comparator<?>) o); // } // return o == null ? null : o.toString(); // }
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import static org.fest.util.Lists.emptyList; import static org.fest.util.Sets.newHashSet; import static org.fest.util.ToString.toStringOf;
if (c == null) { return null; } Iterator<?> i = c.iterator(); if (!i.hasNext()) { return "[]"; } StringBuilder b = new StringBuilder(); b.append('['); for (; ; ) { Object e = i.next(); b.append(e == c ? "(this Collection)" : toStringOf(e)); if (!i.hasNext()) { return b.append(']').toString(); } b.append(", "); } } /** * Returns all the non-{@code null} elements in the given {@link Collection}. * * @param <T> the type of elements of the {@code Collection}. * @param c the given {@code Collection}. * @return all the non-{@code null} elements in the given {@code Collection}. An empty list is returned if the given * {@code Collection} is {@code null}. * @since 1.1.3 */ public static @NotNull <T> List<T> nonNullElementsIn(@Nullable Collection<T> c) { if (c == null) {
// Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> List<T> emptyList() { // return Collections.emptyList(); // } // // Path: src/main/java/org/fest/util/Sets.java // public static @NotNull <T> HashSet<T> newHashSet() { // return new HashSet<T>(); // } // // Path: src/main/java/org/fest/util/ToString.java // public static @Nullable String toStringOf(@Nullable Object o) { // if (isArray(o)) { // return Arrays.format(o); // } // if (o instanceof Calendar) { // return toStringOf(o); // } // if (o instanceof Class<?>) { // return toStringOf((Class<?>) o); // } // if (o instanceof Collection<?>) { // return toStringOf((Collection<?>) o); // } // if (o instanceof Date) { // return toStringOf(o); // } // if (o instanceof Float) { // return toStringOf((Float) o); // } // if (o instanceof Long) { // return toStringOf((Long) o); // } // if (o instanceof File) { // return toStringOf((File) o); // } // if (o instanceof Map<?, ?>) { // return toStringOf((Map<?, ?>) o); // } // if (o instanceof String) { // return quote((String) o); // } // if (o instanceof Comparator) { // return toStringOf((Comparator<?>) o); // } // return o == null ? null : o.toString(); // } // Path: src/main/java/org/fest/util/Collections.java import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import static org.fest.util.Lists.emptyList; import static org.fest.util.Sets.newHashSet; import static org.fest.util.ToString.toStringOf; if (c == null) { return null; } Iterator<?> i = c.iterator(); if (!i.hasNext()) { return "[]"; } StringBuilder b = new StringBuilder(); b.append('['); for (; ; ) { Object e = i.next(); b.append(e == c ? "(this Collection)" : toStringOf(e)); if (!i.hasNext()) { return b.append(']').toString(); } b.append(", "); } } /** * Returns all the non-{@code null} elements in the given {@link Collection}. * * @param <T> the type of elements of the {@code Collection}. * @param c the given {@code Collection}. * @return all the non-{@code null} elements in the given {@code Collection}. An empty list is returned if the given * {@code Collection} is {@code null}. * @since 1.1.3 */ public static @NotNull <T> List<T> nonNullElementsIn(@Nullable Collection<T> c) { if (c == null) {
return emptyList();
alexruiz/fest-util
src/test/java/org/fest/util/Files_fileNamesIn_Test.java
// Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) { // checkNotNull(elements); // ArrayList<T> list = newArrayList(); // for (T e : elements) { // list.add(e); // } // return list; // } // // Path: src/main/java/org/fest/util/Sets.java // public static @NotNull <T> HashSet<T> newHashSet() { // return new HashSet<T>(); // } // // Path: src/main/java/org/fest/util/Strings.java // public static @NotNull String concat(@NotNull Object... objects) { // checkNotNull(objects); // StringBuilder b = new StringBuilder(); // for (Object o : objects) { // b.append(o); // } // return b.toString(); // }
import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.File; import java.util.HashSet; import java.util.List; import static java.io.File.separator; import static org.fest.util.Lists.newArrayList; import static org.fest.util.Sets.newHashSet; import static org.fest.util.Strings.concat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.rules.ExpectedException.none;
/* * Created on Sep 23, 2006 * * 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. * * Copyright @2006-2013 the original author or authors. */ package org.fest.util; /** * Tests for {@link Files#fileNamesIn(String, boolean)}. * * @author Alex Ruiz * @author Yvonne Wang */ public class Files_fileNamesIn_Test extends Files_TestCase { @Rule public ExpectedException thrown = none(); @Test public void should_throw_error_if_directory_does_not_exist() {
// Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) { // checkNotNull(elements); // ArrayList<T> list = newArrayList(); // for (T e : elements) { // list.add(e); // } // return list; // } // // Path: src/main/java/org/fest/util/Sets.java // public static @NotNull <T> HashSet<T> newHashSet() { // return new HashSet<T>(); // } // // Path: src/main/java/org/fest/util/Strings.java // public static @NotNull String concat(@NotNull Object... objects) { // checkNotNull(objects); // StringBuilder b = new StringBuilder(); // for (Object o : objects) { // b.append(o); // } // return b.toString(); // } // Path: src/test/java/org/fest/util/Files_fileNamesIn_Test.java import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.File; import java.util.HashSet; import java.util.List; import static java.io.File.separator; import static org.fest.util.Lists.newArrayList; import static org.fest.util.Sets.newHashSet; import static org.fest.util.Strings.concat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.rules.ExpectedException.none; /* * Created on Sep 23, 2006 * * 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. * * Copyright @2006-2013 the original author or authors. */ package org.fest.util; /** * Tests for {@link Files#fileNamesIn(String, boolean)}. * * @author Alex Ruiz * @author Yvonne Wang */ public class Files_fileNamesIn_Test extends Files_TestCase { @Rule public ExpectedException thrown = none(); @Test public void should_throw_error_if_directory_does_not_exist() {
String path = concat("root", separator, "not_existing_dir");
alexruiz/fest-util
src/test/java/org/fest/util/Files_fileNamesIn_Test.java
// Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) { // checkNotNull(elements); // ArrayList<T> list = newArrayList(); // for (T e : elements) { // list.add(e); // } // return list; // } // // Path: src/main/java/org/fest/util/Sets.java // public static @NotNull <T> HashSet<T> newHashSet() { // return new HashSet<T>(); // } // // Path: src/main/java/org/fest/util/Strings.java // public static @NotNull String concat(@NotNull Object... objects) { // checkNotNull(objects); // StringBuilder b = new StringBuilder(); // for (Object o : objects) { // b.append(o); // } // return b.toString(); // }
import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.File; import java.util.HashSet; import java.util.List; import static java.io.File.separator; import static org.fest.util.Lists.newArrayList; import static org.fest.util.Sets.newHashSet; import static org.fest.util.Strings.concat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.rules.ExpectedException.none;
/* * Created on Sep 23, 2006 * * 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. * * Copyright @2006-2013 the original author or authors. */ package org.fest.util; /** * Tests for {@link Files#fileNamesIn(String, boolean)}. * * @author Alex Ruiz * @author Yvonne Wang */ public class Files_fileNamesIn_Test extends Files_TestCase { @Rule public ExpectedException thrown = none(); @Test public void should_throw_error_if_directory_does_not_exist() { String path = concat("root", separator, "not_existing_dir"); thrown.expect(IllegalArgumentException.class); Files.fileNamesIn(path, false); } @Test public void should_throw_error_if_path_does_not_belong_to_a_directory() throws Exception { String fileName = "file_1"; root.addFiles(fileName); String path = concat("root", separator, fileName); thrown.expect(IllegalArgumentException.class); Files.fileNamesIn(path, false); } @Test public void should_return_names_of_files_in_given_directory_but_not_subdirectories() { String path = concat("root", separator, "dir_1");
// Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) { // checkNotNull(elements); // ArrayList<T> list = newArrayList(); // for (T e : elements) { // list.add(e); // } // return list; // } // // Path: src/main/java/org/fest/util/Sets.java // public static @NotNull <T> HashSet<T> newHashSet() { // return new HashSet<T>(); // } // // Path: src/main/java/org/fest/util/Strings.java // public static @NotNull String concat(@NotNull Object... objects) { // checkNotNull(objects); // StringBuilder b = new StringBuilder(); // for (Object o : objects) { // b.append(o); // } // return b.toString(); // } // Path: src/test/java/org/fest/util/Files_fileNamesIn_Test.java import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.File; import java.util.HashSet; import java.util.List; import static java.io.File.separator; import static org.fest.util.Lists.newArrayList; import static org.fest.util.Sets.newHashSet; import static org.fest.util.Strings.concat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.rules.ExpectedException.none; /* * Created on Sep 23, 2006 * * 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. * * Copyright @2006-2013 the original author or authors. */ package org.fest.util; /** * Tests for {@link Files#fileNamesIn(String, boolean)}. * * @author Alex Ruiz * @author Yvonne Wang */ public class Files_fileNamesIn_Test extends Files_TestCase { @Rule public ExpectedException thrown = none(); @Test public void should_throw_error_if_directory_does_not_exist() { String path = concat("root", separator, "not_existing_dir"); thrown.expect(IllegalArgumentException.class); Files.fileNamesIn(path, false); } @Test public void should_throw_error_if_path_does_not_belong_to_a_directory() throws Exception { String fileName = "file_1"; root.addFiles(fileName); String path = concat("root", separator, fileName); thrown.expect(IllegalArgumentException.class); Files.fileNamesIn(path, false); } @Test public void should_return_names_of_files_in_given_directory_but_not_subdirectories() { String path = concat("root", separator, "dir_1");
assertThatContainsFiles(newArrayList("file_1_1", "file_1_2"), Files.fileNamesIn(path, false));
alexruiz/fest-util
src/test/java/org/fest/util/Files_fileNamesIn_Test.java
// Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) { // checkNotNull(elements); // ArrayList<T> list = newArrayList(); // for (T e : elements) { // list.add(e); // } // return list; // } // // Path: src/main/java/org/fest/util/Sets.java // public static @NotNull <T> HashSet<T> newHashSet() { // return new HashSet<T>(); // } // // Path: src/main/java/org/fest/util/Strings.java // public static @NotNull String concat(@NotNull Object... objects) { // checkNotNull(objects); // StringBuilder b = new StringBuilder(); // for (Object o : objects) { // b.append(o); // } // return b.toString(); // }
import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.File; import java.util.HashSet; import java.util.List; import static java.io.File.separator; import static org.fest.util.Lists.newArrayList; import static org.fest.util.Sets.newHashSet; import static org.fest.util.Strings.concat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.rules.ExpectedException.none;
} @Test public void should_return_names_of_files_in_given_directory_but_not_subdirectories() { String path = concat("root", separator, "dir_1"); assertThatContainsFiles(newArrayList("file_1_1", "file_1_2"), Files.fileNamesIn(path, false)); } @Test public void should_return_names_of_files_in_given_directory_and_its_subdirectories() { String path = concat("root", separator, "dir_1"); assertThatContainsFiles(newArrayList("file_1_1", "file_1_2", "file_1_1_1"), Files.fileNamesIn(path, true)); } private void assertThatContainsFiles(List<String> expectedFiles, List<String> actualFiles) { assertThereAreNoDuplicates(actualFiles); for (String fileName : actualFiles) { assertTrue(expectedFiles.remove(pathNameFor(fileName))); } assertTrue(expectedFiles.isEmpty()); } private String pathNameFor(String fileName) { return new File(fileName).getName(); } private void assertThereAreNoDuplicates(List<String> actualFiles) { if (actualFiles == null || actualFiles.isEmpty()) { return; }
// Path: src/main/java/org/fest/util/Lists.java // public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) { // checkNotNull(elements); // ArrayList<T> list = newArrayList(); // for (T e : elements) { // list.add(e); // } // return list; // } // // Path: src/main/java/org/fest/util/Sets.java // public static @NotNull <T> HashSet<T> newHashSet() { // return new HashSet<T>(); // } // // Path: src/main/java/org/fest/util/Strings.java // public static @NotNull String concat(@NotNull Object... objects) { // checkNotNull(objects); // StringBuilder b = new StringBuilder(); // for (Object o : objects) { // b.append(o); // } // return b.toString(); // } // Path: src/test/java/org/fest/util/Files_fileNamesIn_Test.java import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.File; import java.util.HashSet; import java.util.List; import static java.io.File.separator; import static org.fest.util.Lists.newArrayList; import static org.fest.util.Sets.newHashSet; import static org.fest.util.Strings.concat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.rules.ExpectedException.none; } @Test public void should_return_names_of_files_in_given_directory_but_not_subdirectories() { String path = concat("root", separator, "dir_1"); assertThatContainsFiles(newArrayList("file_1_1", "file_1_2"), Files.fileNamesIn(path, false)); } @Test public void should_return_names_of_files_in_given_directory_and_its_subdirectories() { String path = concat("root", separator, "dir_1"); assertThatContainsFiles(newArrayList("file_1_1", "file_1_2", "file_1_1_1"), Files.fileNamesIn(path, true)); } private void assertThatContainsFiles(List<String> expectedFiles, List<String> actualFiles) { assertThereAreNoDuplicates(actualFiles); for (String fileName : actualFiles) { assertTrue(expectedFiles.remove(pathNameFor(fileName))); } assertTrue(expectedFiles.isEmpty()); } private String pathNameFor(String fileName) { return new File(fileName).getName(); } private void assertThereAreNoDuplicates(List<String> actualFiles) { if (actualFiles == null || actualFiles.isEmpty()) { return; }
HashSet<String> withoutDuplicates = newHashSet(actualFiles);
indvd00m/java-ascii-render
ascii-render/src/main/java/com/indvd00m/ascii/render/Layer.java
// Path: ascii-render-api/src/main/java/com/indvd00m/ascii/render/api/IElement.java // public interface IElement { // // /** // * Draw element in canvas. // * // * @param canvas // * @param context // * @return Anchor point for this element in relative coordinates of his layer. If element was not be drawn, null // * must be returned. // */ // IPoint draw(ICanvas canvas, IContext context); // // } // // Path: ascii-render-api/src/main/java/com/indvd00m/ascii/render/api/ILayer.java // public interface ILayer { // // /** // * Region of this layer in Context coordinates. // * // * @return // */ // IRegion getRegion(); // // /** // * List of elements. Elements will be drawn by render in order of this list. // * // * @return // */ // List<IElement> getElements(); // // /** // * Opacity of this layer. {@code False} by default. // * // * @return // */ // boolean isOpacity(); // // } // // Path: ascii-render-api/src/main/java/com/indvd00m/ascii/render/api/IRegion.java // public interface IRegion { // // int getX(); // // int getY(); // // int getWidth(); // // int getHeight(); // // }
import com.indvd00m.ascii.render.api.IElement; import com.indvd00m.ascii.render.api.ILayer; import com.indvd00m.ascii.render.api.IRegion; import java.util.ArrayList; import java.util.Collections; import java.util.List;
package com.indvd00m.ascii.render; /** * @author indvd00m (gotoindvdum[at]gmail[dot]com) * @since 0.9.0 */ public class Layer implements ILayer { protected IRegion region;
// Path: ascii-render-api/src/main/java/com/indvd00m/ascii/render/api/IElement.java // public interface IElement { // // /** // * Draw element in canvas. // * // * @param canvas // * @param context // * @return Anchor point for this element in relative coordinates of his layer. If element was not be drawn, null // * must be returned. // */ // IPoint draw(ICanvas canvas, IContext context); // // } // // Path: ascii-render-api/src/main/java/com/indvd00m/ascii/render/api/ILayer.java // public interface ILayer { // // /** // * Region of this layer in Context coordinates. // * // * @return // */ // IRegion getRegion(); // // /** // * List of elements. Elements will be drawn by render in order of this list. // * // * @return // */ // List<IElement> getElements(); // // /** // * Opacity of this layer. {@code False} by default. // * // * @return // */ // boolean isOpacity(); // // } // // Path: ascii-render-api/src/main/java/com/indvd00m/ascii/render/api/IRegion.java // public interface IRegion { // // int getX(); // // int getY(); // // int getWidth(); // // int getHeight(); // // } // Path: ascii-render/src/main/java/com/indvd00m/ascii/render/Layer.java import com.indvd00m.ascii.render.api.IElement; import com.indvd00m.ascii.render.api.ILayer; import com.indvd00m.ascii.render.api.IRegion; import java.util.ArrayList; import java.util.Collections; import java.util.List; package com.indvd00m.ascii.render; /** * @author indvd00m (gotoindvdum[at]gmail[dot]com) * @since 0.9.0 */ public class Layer implements ILayer { protected IRegion region;
protected List<IElement> elements = new ArrayList<IElement>();
indvd00m/java-ascii-render
ascii-render/src/main/java/com/indvd00m/ascii/render/Canvas.java
// Path: ascii-render-api/src/main/java/com/indvd00m/ascii/render/api/ICanvas.java // public interface ICanvas { // // /** // * Final version of text with all drawed elements. Every {@code \0} will be replaced with {@code \s} symbol. // * // * @return // */ // String getText(); // // /** // * Height of canvas. // * // * @return // */ // int getHeight(); // // /** // * Width of canvas. // * // * @return // */ // int getWidth(); // // /** // * Draw char in a particular position. Coordinates {@code x} and {@code y} may be any, canvas will draw only text // * which gets in his region. {@code c} can contains line break. // * // * @param x // * @param y // * @param c // */ // void draw(int x, int y, char c); // // /** // * Draw char {@code count} times starting from {@code x} and {@code y}. Coordinates {@code x} and {@code y} may be // * any, canvas will draw only text which gets in his region. {@code c} can contains line break. // * // * @param x // * @param y // * @param c // * @param count // */ // void draw(int x, int y, char c, int count); // // /** // * Draw string in a particular position. Coordinates {@code x} and {@code y} may be any, canvas will draw only text // * which gets in his region. {@code s} can contains line breaks. // * // * @param x // * @param y // * @param s // */ // void draw(int x, int y, String s); // // /** // * Draw string {@code count} times starting from {@code x} and {@code y}. Coordinates {@code x} and {@code y} may be // * any, canvas will draw only text which gets in his region. {@code s} can contains line breaks. // * // * @param x // * @param y // * @param s // */ // void draw(int x, int y, String s, int count); // // /** // * Clear all region of canvas and fill it with {@code \0} symbols. // */ // void clear(); // // /** // * Gets char at a particular position. After creating canvas contains only {@code \0} symbols and line breaks // * {@code \n}. If coordinates do not gets in a canvas region {@code \0} will be returned. // * // * @param x // * @param y // * @return // */ // char getChar(int x, int y); // // /** // * Set char at a particular position. // * // * @param x // * @param y // * @return previous value // */ // char setChar(int x, int y, char c); // // /** // * Return {@code true} if any char except {@code \0} was drawed in this position. // * // * @param x // * @param y // * @return // */ // boolean isCharDrawed(int x, int y); // // /** // * Returns a canvas whose value is this canvas, with any leading and trailing {@code \s} and {@code \0} symbols // * removed. // * // * @return // */ // ICanvas trim(); // // /** // * Returns a canvas whose value is this canvas, with any leading and trailing whitespace {@code \s} removed. // * // * @return // */ // ICanvas trimSpaces(); // // /** // * Returns a canvas whose value is this canvas, with any leading and trailing {@code \0} symbol removed. // * // * @return // */ // ICanvas trimNulls(); // // /** // * Returns a canvas whose value is this canvas, with any leading and trailing {@code trimChar} symbol removed. // * // * @return // */ // ICanvas trim(char trimChar); // // /** // * Returns a {@code ICanvas} that is a subcanvas of this canvas. // * // * @param region // * @return // */ // ICanvas subCanvas(IRegion region); // // } // // Path: ascii-render-api/src/main/java/com/indvd00m/ascii/render/api/IRegion.java // public interface IRegion { // // int getX(); // // int getY(); // // int getWidth(); // // int getHeight(); // // }
import com.indvd00m.ascii.render.api.ICanvas; import com.indvd00m.ascii.render.api.IRegion; import java.util.ArrayList; import java.util.Iterator; import java.util.List;
} StringBuilder line = lines.get(y); char c = line.charAt(x); return c; } @Override public char setChar(int x, int y, char c) { if (x < 0 || x >= width) { return 0; } if (y < 0 || y >= height) { return 0; } StringBuilder line = lines.get(y); char prevC = line.charAt(x); line.setCharAt(x, c); needUpdateCache = true; return prevC; } @Override public boolean isCharDrawed(int x, int y) { return getChar(x, y) != NULL_CHAR; } @Override public ICanvas trim() {
// Path: ascii-render-api/src/main/java/com/indvd00m/ascii/render/api/ICanvas.java // public interface ICanvas { // // /** // * Final version of text with all drawed elements. Every {@code \0} will be replaced with {@code \s} symbol. // * // * @return // */ // String getText(); // // /** // * Height of canvas. // * // * @return // */ // int getHeight(); // // /** // * Width of canvas. // * // * @return // */ // int getWidth(); // // /** // * Draw char in a particular position. Coordinates {@code x} and {@code y} may be any, canvas will draw only text // * which gets in his region. {@code c} can contains line break. // * // * @param x // * @param y // * @param c // */ // void draw(int x, int y, char c); // // /** // * Draw char {@code count} times starting from {@code x} and {@code y}. Coordinates {@code x} and {@code y} may be // * any, canvas will draw only text which gets in his region. {@code c} can contains line break. // * // * @param x // * @param y // * @param c // * @param count // */ // void draw(int x, int y, char c, int count); // // /** // * Draw string in a particular position. Coordinates {@code x} and {@code y} may be any, canvas will draw only text // * which gets in his region. {@code s} can contains line breaks. // * // * @param x // * @param y // * @param s // */ // void draw(int x, int y, String s); // // /** // * Draw string {@code count} times starting from {@code x} and {@code y}. Coordinates {@code x} and {@code y} may be // * any, canvas will draw only text which gets in his region. {@code s} can contains line breaks. // * // * @param x // * @param y // * @param s // */ // void draw(int x, int y, String s, int count); // // /** // * Clear all region of canvas and fill it with {@code \0} symbols. // */ // void clear(); // // /** // * Gets char at a particular position. After creating canvas contains only {@code \0} symbols and line breaks // * {@code \n}. If coordinates do not gets in a canvas region {@code \0} will be returned. // * // * @param x // * @param y // * @return // */ // char getChar(int x, int y); // // /** // * Set char at a particular position. // * // * @param x // * @param y // * @return previous value // */ // char setChar(int x, int y, char c); // // /** // * Return {@code true} if any char except {@code \0} was drawed in this position. // * // * @param x // * @param y // * @return // */ // boolean isCharDrawed(int x, int y); // // /** // * Returns a canvas whose value is this canvas, with any leading and trailing {@code \s} and {@code \0} symbols // * removed. // * // * @return // */ // ICanvas trim(); // // /** // * Returns a canvas whose value is this canvas, with any leading and trailing whitespace {@code \s} removed. // * // * @return // */ // ICanvas trimSpaces(); // // /** // * Returns a canvas whose value is this canvas, with any leading and trailing {@code \0} symbol removed. // * // * @return // */ // ICanvas trimNulls(); // // /** // * Returns a canvas whose value is this canvas, with any leading and trailing {@code trimChar} symbol removed. // * // * @return // */ // ICanvas trim(char trimChar); // // /** // * Returns a {@code ICanvas} that is a subcanvas of this canvas. // * // * @param region // * @return // */ // ICanvas subCanvas(IRegion region); // // } // // Path: ascii-render-api/src/main/java/com/indvd00m/ascii/render/api/IRegion.java // public interface IRegion { // // int getX(); // // int getY(); // // int getWidth(); // // int getHeight(); // // } // Path: ascii-render/src/main/java/com/indvd00m/ascii/render/Canvas.java import com.indvd00m.ascii.render.api.ICanvas; import com.indvd00m.ascii.render.api.IRegion; import java.util.ArrayList; import java.util.Iterator; import java.util.List; } StringBuilder line = lines.get(y); char c = line.charAt(x); return c; } @Override public char setChar(int x, int y, char c) { if (x < 0 || x >= width) { return 0; } if (y < 0 || y >= height) { return 0; } StringBuilder line = lines.get(y); char prevC = line.charAt(x); line.setCharAt(x, c); needUpdateCache = true; return prevC; } @Override public boolean isCharDrawed(int x, int y) { return getChar(x, y) != NULL_CHAR; } @Override public ICanvas trim() {
IRegion region = getTrimmedRegion(this, ' ', NULL_CHAR);
nicoulaj/compile-command-annotations
src/test/java/net/nicoulaj/compilecommand/IncrementalCompileTest.java
// Path: src/main/java/net/nicoulaj/compilecommand/CompileCommandProcessor.java // public static final String COMPILE_COMMAND_FILE_PATH_DEFAULT = "META-INF/hotspot_compiler"; // // Path: src/main/java/net/nicoulaj/compilecommand/CompileCommandProcessor.java // public static final String COMPILE_COMMAND_INCREMENTAL_OUTPUT_OPTION = "compile.command.incremental.output"; // // Path: src/test/java/net/nicoulaj/compilecommand/JavaCompilationTester.java // public static final class Report { // // private final File classesDirectory; // // private final File sourcesDirectory; // // private final boolean successful; // // private final List<Diagnostic<? extends JavaFileObject>> diagnostics; // // private final String stdout; // // Report(final File classesDirectory, // final File sourcesDirectory, // final boolean successful, // final List<Diagnostic<? extends JavaFileObject>> diagnostics, // final String stdout) { // this.classesDirectory = classesDirectory; // this.sourcesDirectory = sourcesDirectory; // this.successful = successful; // this.diagnostics = diagnostics; // this.stdout = stdout; // } // // public File getClassesDirectory() { // return classesDirectory; // } // // public File getSourcesDirectory() { // return sourcesDirectory; // } // // public boolean isSuccessful() { // return successful; // } // // public boolean isFailed() { // return !successful; // } // // public boolean hasErrors() { // return !successful; // } // // public boolean hasWarnings() { // for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) // if (diagnostic.getKind() == WARNING || diagnostic.getKind() == MANDATORY_WARNING) // return true; // return false; // } // // public List<Diagnostic<? extends JavaFileObject>> getDiagnostics() { // return diagnostics; // } // // public String getStdout() { // return stdout; // } // }
import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static java.util.Arrays.sort; import static net.nicoulaj.compilecommand.CompileCommandProcessor.COMPILE_COMMAND_FILE_PATH_DEFAULT; import static net.nicoulaj.compilecommand.CompileCommandProcessor.COMPILE_COMMAND_INCREMENTAL_OUTPUT_OPTION; import static net.nicoulaj.compilecommand.JavaCompilationTester.Report; import static org.apache.commons.io.FilenameUtils.getBaseName; import static org.apache.commons.io.FilenameUtils.getExtension; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue;
/* * Hotspot compile command annotations - http://compile-command-annotations.nicoulaj.net * Copyright © 2014-2019 Hotspot compile command annotations contributors * * 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 net.nicoulaj.compilecommand; public class IncrementalCompileTest { private static final JavaCompilationTester JAVAC = new JavaCompilationTester(); private static final File TEST_CASES_SOURCES = new File("src/test/java/net/nicoulaj/compilecommand/incrementaltests"); private static final File TEST_CASES_RESOURCES = new File("src/test/resources/net/nicoulaj/compilecommand/incrementaltests"); private static final File TEST_CASES_MERGED = new File("src/test/resources/net/nicoulaj/compilecommand/incrementaltests-merged"); private static final String INCREMENTAL_FRAGMENTS = "INCREMENTAL_FRAGMENTS"; @DataProvider public Object[][] testcases() throws IOException { return getDataProvider(TEST_CASES_SOURCES, TEST_CASES_RESOURCES, TEST_CASES_MERGED); } private Object[][] getDataProvider(File sourceDir, File resourceDir, File mergedDir) { final List<Object[]> data = new ArrayList<Object[]>(); final File[] sources = sourceDir.listFiles(); if (sources == null) throw new IllegalArgumentException("No source in " + sourceDir); sort(sources); for (File source : sources) if ("java".equals(getExtension(source.toString()))) if (!"package-info".equals(getBaseName(source.toString()))) data.add(new Object[]{source, new File(resourceDir, getBaseName(source.toString())), new File(mergedDir, getBaseName(source.toString()))}); return data.toArray(new Object[data.size()][]); } @Test(dataProvider = "testcases") public void test(File source, File expected, File expectedMerged) throws IOException {
// Path: src/main/java/net/nicoulaj/compilecommand/CompileCommandProcessor.java // public static final String COMPILE_COMMAND_FILE_PATH_DEFAULT = "META-INF/hotspot_compiler"; // // Path: src/main/java/net/nicoulaj/compilecommand/CompileCommandProcessor.java // public static final String COMPILE_COMMAND_INCREMENTAL_OUTPUT_OPTION = "compile.command.incremental.output"; // // Path: src/test/java/net/nicoulaj/compilecommand/JavaCompilationTester.java // public static final class Report { // // private final File classesDirectory; // // private final File sourcesDirectory; // // private final boolean successful; // // private final List<Diagnostic<? extends JavaFileObject>> diagnostics; // // private final String stdout; // // Report(final File classesDirectory, // final File sourcesDirectory, // final boolean successful, // final List<Diagnostic<? extends JavaFileObject>> diagnostics, // final String stdout) { // this.classesDirectory = classesDirectory; // this.sourcesDirectory = sourcesDirectory; // this.successful = successful; // this.diagnostics = diagnostics; // this.stdout = stdout; // } // // public File getClassesDirectory() { // return classesDirectory; // } // // public File getSourcesDirectory() { // return sourcesDirectory; // } // // public boolean isSuccessful() { // return successful; // } // // public boolean isFailed() { // return !successful; // } // // public boolean hasErrors() { // return !successful; // } // // public boolean hasWarnings() { // for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) // if (diagnostic.getKind() == WARNING || diagnostic.getKind() == MANDATORY_WARNING) // return true; // return false; // } // // public List<Diagnostic<? extends JavaFileObject>> getDiagnostics() { // return diagnostics; // } // // public String getStdout() { // return stdout; // } // } // Path: src/test/java/net/nicoulaj/compilecommand/IncrementalCompileTest.java import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static java.util.Arrays.sort; import static net.nicoulaj.compilecommand.CompileCommandProcessor.COMPILE_COMMAND_FILE_PATH_DEFAULT; import static net.nicoulaj.compilecommand.CompileCommandProcessor.COMPILE_COMMAND_INCREMENTAL_OUTPUT_OPTION; import static net.nicoulaj.compilecommand.JavaCompilationTester.Report; import static org.apache.commons.io.FilenameUtils.getBaseName; import static org.apache.commons.io.FilenameUtils.getExtension; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; /* * Hotspot compile command annotations - http://compile-command-annotations.nicoulaj.net * Copyright © 2014-2019 Hotspot compile command annotations contributors * * 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 net.nicoulaj.compilecommand; public class IncrementalCompileTest { private static final JavaCompilationTester JAVAC = new JavaCompilationTester(); private static final File TEST_CASES_SOURCES = new File("src/test/java/net/nicoulaj/compilecommand/incrementaltests"); private static final File TEST_CASES_RESOURCES = new File("src/test/resources/net/nicoulaj/compilecommand/incrementaltests"); private static final File TEST_CASES_MERGED = new File("src/test/resources/net/nicoulaj/compilecommand/incrementaltests-merged"); private static final String INCREMENTAL_FRAGMENTS = "INCREMENTAL_FRAGMENTS"; @DataProvider public Object[][] testcases() throws IOException { return getDataProvider(TEST_CASES_SOURCES, TEST_CASES_RESOURCES, TEST_CASES_MERGED); } private Object[][] getDataProvider(File sourceDir, File resourceDir, File mergedDir) { final List<Object[]> data = new ArrayList<Object[]>(); final File[] sources = sourceDir.listFiles(); if (sources == null) throw new IllegalArgumentException("No source in " + sourceDir); sort(sources); for (File source : sources) if ("java".equals(getExtension(source.toString()))) if (!"package-info".equals(getBaseName(source.toString()))) data.add(new Object[]{source, new File(resourceDir, getBaseName(source.toString())), new File(mergedDir, getBaseName(source.toString()))}); return data.toArray(new Object[data.size()][]); } @Test(dataProvider = "testcases") public void test(File source, File expected, File expectedMerged) throws IOException {
final Report compilation = JAVAC.compile(source,
nicoulaj/compile-command-annotations
src/test/java/net/nicoulaj/compilecommand/IncrementalCompileTest.java
// Path: src/main/java/net/nicoulaj/compilecommand/CompileCommandProcessor.java // public static final String COMPILE_COMMAND_FILE_PATH_DEFAULT = "META-INF/hotspot_compiler"; // // Path: src/main/java/net/nicoulaj/compilecommand/CompileCommandProcessor.java // public static final String COMPILE_COMMAND_INCREMENTAL_OUTPUT_OPTION = "compile.command.incremental.output"; // // Path: src/test/java/net/nicoulaj/compilecommand/JavaCompilationTester.java // public static final class Report { // // private final File classesDirectory; // // private final File sourcesDirectory; // // private final boolean successful; // // private final List<Diagnostic<? extends JavaFileObject>> diagnostics; // // private final String stdout; // // Report(final File classesDirectory, // final File sourcesDirectory, // final boolean successful, // final List<Diagnostic<? extends JavaFileObject>> diagnostics, // final String stdout) { // this.classesDirectory = classesDirectory; // this.sourcesDirectory = sourcesDirectory; // this.successful = successful; // this.diagnostics = diagnostics; // this.stdout = stdout; // } // // public File getClassesDirectory() { // return classesDirectory; // } // // public File getSourcesDirectory() { // return sourcesDirectory; // } // // public boolean isSuccessful() { // return successful; // } // // public boolean isFailed() { // return !successful; // } // // public boolean hasErrors() { // return !successful; // } // // public boolean hasWarnings() { // for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) // if (diagnostic.getKind() == WARNING || diagnostic.getKind() == MANDATORY_WARNING) // return true; // return false; // } // // public List<Diagnostic<? extends JavaFileObject>> getDiagnostics() { // return diagnostics; // } // // public String getStdout() { // return stdout; // } // }
import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static java.util.Arrays.sort; import static net.nicoulaj.compilecommand.CompileCommandProcessor.COMPILE_COMMAND_FILE_PATH_DEFAULT; import static net.nicoulaj.compilecommand.CompileCommandProcessor.COMPILE_COMMAND_INCREMENTAL_OUTPUT_OPTION; import static net.nicoulaj.compilecommand.JavaCompilationTester.Report; import static org.apache.commons.io.FilenameUtils.getBaseName; import static org.apache.commons.io.FilenameUtils.getExtension; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue;
/* * Hotspot compile command annotations - http://compile-command-annotations.nicoulaj.net * Copyright © 2014-2019 Hotspot compile command annotations contributors * * 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 net.nicoulaj.compilecommand; public class IncrementalCompileTest { private static final JavaCompilationTester JAVAC = new JavaCompilationTester(); private static final File TEST_CASES_SOURCES = new File("src/test/java/net/nicoulaj/compilecommand/incrementaltests"); private static final File TEST_CASES_RESOURCES = new File("src/test/resources/net/nicoulaj/compilecommand/incrementaltests"); private static final File TEST_CASES_MERGED = new File("src/test/resources/net/nicoulaj/compilecommand/incrementaltests-merged"); private static final String INCREMENTAL_FRAGMENTS = "INCREMENTAL_FRAGMENTS"; @DataProvider public Object[][] testcases() throws IOException { return getDataProvider(TEST_CASES_SOURCES, TEST_CASES_RESOURCES, TEST_CASES_MERGED); } private Object[][] getDataProvider(File sourceDir, File resourceDir, File mergedDir) { final List<Object[]> data = new ArrayList<Object[]>(); final File[] sources = sourceDir.listFiles(); if (sources == null) throw new IllegalArgumentException("No source in " + sourceDir); sort(sources); for (File source : sources) if ("java".equals(getExtension(source.toString()))) if (!"package-info".equals(getBaseName(source.toString()))) data.add(new Object[]{source, new File(resourceDir, getBaseName(source.toString())), new File(mergedDir, getBaseName(source.toString()))}); return data.toArray(new Object[data.size()][]); } @Test(dataProvider = "testcases") public void test(File source, File expected, File expectedMerged) throws IOException { final Report compilation = JAVAC.compile(source,
// Path: src/main/java/net/nicoulaj/compilecommand/CompileCommandProcessor.java // public static final String COMPILE_COMMAND_FILE_PATH_DEFAULT = "META-INF/hotspot_compiler"; // // Path: src/main/java/net/nicoulaj/compilecommand/CompileCommandProcessor.java // public static final String COMPILE_COMMAND_INCREMENTAL_OUTPUT_OPTION = "compile.command.incremental.output"; // // Path: src/test/java/net/nicoulaj/compilecommand/JavaCompilationTester.java // public static final class Report { // // private final File classesDirectory; // // private final File sourcesDirectory; // // private final boolean successful; // // private final List<Diagnostic<? extends JavaFileObject>> diagnostics; // // private final String stdout; // // Report(final File classesDirectory, // final File sourcesDirectory, // final boolean successful, // final List<Diagnostic<? extends JavaFileObject>> diagnostics, // final String stdout) { // this.classesDirectory = classesDirectory; // this.sourcesDirectory = sourcesDirectory; // this.successful = successful; // this.diagnostics = diagnostics; // this.stdout = stdout; // } // // public File getClassesDirectory() { // return classesDirectory; // } // // public File getSourcesDirectory() { // return sourcesDirectory; // } // // public boolean isSuccessful() { // return successful; // } // // public boolean isFailed() { // return !successful; // } // // public boolean hasErrors() { // return !successful; // } // // public boolean hasWarnings() { // for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) // if (diagnostic.getKind() == WARNING || diagnostic.getKind() == MANDATORY_WARNING) // return true; // return false; // } // // public List<Diagnostic<? extends JavaFileObject>> getDiagnostics() { // return diagnostics; // } // // public String getStdout() { // return stdout; // } // } // Path: src/test/java/net/nicoulaj/compilecommand/IncrementalCompileTest.java import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static java.util.Arrays.sort; import static net.nicoulaj.compilecommand.CompileCommandProcessor.COMPILE_COMMAND_FILE_PATH_DEFAULT; import static net.nicoulaj.compilecommand.CompileCommandProcessor.COMPILE_COMMAND_INCREMENTAL_OUTPUT_OPTION; import static net.nicoulaj.compilecommand.JavaCompilationTester.Report; import static org.apache.commons.io.FilenameUtils.getBaseName; import static org.apache.commons.io.FilenameUtils.getExtension; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; /* * Hotspot compile command annotations - http://compile-command-annotations.nicoulaj.net * Copyright © 2014-2019 Hotspot compile command annotations contributors * * 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 net.nicoulaj.compilecommand; public class IncrementalCompileTest { private static final JavaCompilationTester JAVAC = new JavaCompilationTester(); private static final File TEST_CASES_SOURCES = new File("src/test/java/net/nicoulaj/compilecommand/incrementaltests"); private static final File TEST_CASES_RESOURCES = new File("src/test/resources/net/nicoulaj/compilecommand/incrementaltests"); private static final File TEST_CASES_MERGED = new File("src/test/resources/net/nicoulaj/compilecommand/incrementaltests-merged"); private static final String INCREMENTAL_FRAGMENTS = "INCREMENTAL_FRAGMENTS"; @DataProvider public Object[][] testcases() throws IOException { return getDataProvider(TEST_CASES_SOURCES, TEST_CASES_RESOURCES, TEST_CASES_MERGED); } private Object[][] getDataProvider(File sourceDir, File resourceDir, File mergedDir) { final List<Object[]> data = new ArrayList<Object[]>(); final File[] sources = sourceDir.listFiles(); if (sources == null) throw new IllegalArgumentException("No source in " + sourceDir); sort(sources); for (File source : sources) if ("java".equals(getExtension(source.toString()))) if (!"package-info".equals(getBaseName(source.toString()))) data.add(new Object[]{source, new File(resourceDir, getBaseName(source.toString())), new File(mergedDir, getBaseName(source.toString()))}); return data.toArray(new Object[data.size()][]); } @Test(dataProvider = "testcases") public void test(File source, File expected, File expectedMerged) throws IOException { final Report compilation = JAVAC.compile(source,
String.format("-A%s=%s", COMPILE_COMMAND_INCREMENTAL_OUTPUT_OPTION, INCREMENTAL_FRAGMENTS));
nicoulaj/compile-command-annotations
src/test/java/net/nicoulaj/compilecommand/IncrementalCompileTest.java
// Path: src/main/java/net/nicoulaj/compilecommand/CompileCommandProcessor.java // public static final String COMPILE_COMMAND_FILE_PATH_DEFAULT = "META-INF/hotspot_compiler"; // // Path: src/main/java/net/nicoulaj/compilecommand/CompileCommandProcessor.java // public static final String COMPILE_COMMAND_INCREMENTAL_OUTPUT_OPTION = "compile.command.incremental.output"; // // Path: src/test/java/net/nicoulaj/compilecommand/JavaCompilationTester.java // public static final class Report { // // private final File classesDirectory; // // private final File sourcesDirectory; // // private final boolean successful; // // private final List<Diagnostic<? extends JavaFileObject>> diagnostics; // // private final String stdout; // // Report(final File classesDirectory, // final File sourcesDirectory, // final boolean successful, // final List<Diagnostic<? extends JavaFileObject>> diagnostics, // final String stdout) { // this.classesDirectory = classesDirectory; // this.sourcesDirectory = sourcesDirectory; // this.successful = successful; // this.diagnostics = diagnostics; // this.stdout = stdout; // } // // public File getClassesDirectory() { // return classesDirectory; // } // // public File getSourcesDirectory() { // return sourcesDirectory; // } // // public boolean isSuccessful() { // return successful; // } // // public boolean isFailed() { // return !successful; // } // // public boolean hasErrors() { // return !successful; // } // // public boolean hasWarnings() { // for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) // if (diagnostic.getKind() == WARNING || diagnostic.getKind() == MANDATORY_WARNING) // return true; // return false; // } // // public List<Diagnostic<? extends JavaFileObject>> getDiagnostics() { // return diagnostics; // } // // public String getStdout() { // return stdout; // } // }
import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static java.util.Arrays.sort; import static net.nicoulaj.compilecommand.CompileCommandProcessor.COMPILE_COMMAND_FILE_PATH_DEFAULT; import static net.nicoulaj.compilecommand.CompileCommandProcessor.COMPILE_COMMAND_INCREMENTAL_OUTPUT_OPTION; import static net.nicoulaj.compilecommand.JavaCompilationTester.Report; import static org.apache.commons.io.FilenameUtils.getBaseName; import static org.apache.commons.io.FilenameUtils.getExtension; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue;
private static final String INCREMENTAL_FRAGMENTS = "INCREMENTAL_FRAGMENTS"; @DataProvider public Object[][] testcases() throws IOException { return getDataProvider(TEST_CASES_SOURCES, TEST_CASES_RESOURCES, TEST_CASES_MERGED); } private Object[][] getDataProvider(File sourceDir, File resourceDir, File mergedDir) { final List<Object[]> data = new ArrayList<Object[]>(); final File[] sources = sourceDir.listFiles(); if (sources == null) throw new IllegalArgumentException("No source in " + sourceDir); sort(sources); for (File source : sources) if ("java".equals(getExtension(source.toString()))) if (!"package-info".equals(getBaseName(source.toString()))) data.add(new Object[]{source, new File(resourceDir, getBaseName(source.toString())), new File(mergedDir, getBaseName(source.toString()))}); return data.toArray(new Object[data.size()][]); } @Test(dataProvider = "testcases") public void test(File source, File expected, File expectedMerged) throws IOException { final Report compilation = JAVAC.compile(source, String.format("-A%s=%s", COMPILE_COMMAND_INCREMENTAL_OUTPUT_OPTION, INCREMENTAL_FRAGMENTS)); assertTrue(compilation.isSuccessful(), "compilation failed"); assertFalse(compilation.hasErrors(), "compilation has errors"); assertFalse(compilation.hasWarnings(), "compilation has warnings");
// Path: src/main/java/net/nicoulaj/compilecommand/CompileCommandProcessor.java // public static final String COMPILE_COMMAND_FILE_PATH_DEFAULT = "META-INF/hotspot_compiler"; // // Path: src/main/java/net/nicoulaj/compilecommand/CompileCommandProcessor.java // public static final String COMPILE_COMMAND_INCREMENTAL_OUTPUT_OPTION = "compile.command.incremental.output"; // // Path: src/test/java/net/nicoulaj/compilecommand/JavaCompilationTester.java // public static final class Report { // // private final File classesDirectory; // // private final File sourcesDirectory; // // private final boolean successful; // // private final List<Diagnostic<? extends JavaFileObject>> diagnostics; // // private final String stdout; // // Report(final File classesDirectory, // final File sourcesDirectory, // final boolean successful, // final List<Diagnostic<? extends JavaFileObject>> diagnostics, // final String stdout) { // this.classesDirectory = classesDirectory; // this.sourcesDirectory = sourcesDirectory; // this.successful = successful; // this.diagnostics = diagnostics; // this.stdout = stdout; // } // // public File getClassesDirectory() { // return classesDirectory; // } // // public File getSourcesDirectory() { // return sourcesDirectory; // } // // public boolean isSuccessful() { // return successful; // } // // public boolean isFailed() { // return !successful; // } // // public boolean hasErrors() { // return !successful; // } // // public boolean hasWarnings() { // for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) // if (diagnostic.getKind() == WARNING || diagnostic.getKind() == MANDATORY_WARNING) // return true; // return false; // } // // public List<Diagnostic<? extends JavaFileObject>> getDiagnostics() { // return diagnostics; // } // // public String getStdout() { // return stdout; // } // } // Path: src/test/java/net/nicoulaj/compilecommand/IncrementalCompileTest.java import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static java.util.Arrays.sort; import static net.nicoulaj.compilecommand.CompileCommandProcessor.COMPILE_COMMAND_FILE_PATH_DEFAULT; import static net.nicoulaj.compilecommand.CompileCommandProcessor.COMPILE_COMMAND_INCREMENTAL_OUTPUT_OPTION; import static net.nicoulaj.compilecommand.JavaCompilationTester.Report; import static org.apache.commons.io.FilenameUtils.getBaseName; import static org.apache.commons.io.FilenameUtils.getExtension; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; private static final String INCREMENTAL_FRAGMENTS = "INCREMENTAL_FRAGMENTS"; @DataProvider public Object[][] testcases() throws IOException { return getDataProvider(TEST_CASES_SOURCES, TEST_CASES_RESOURCES, TEST_CASES_MERGED); } private Object[][] getDataProvider(File sourceDir, File resourceDir, File mergedDir) { final List<Object[]> data = new ArrayList<Object[]>(); final File[] sources = sourceDir.listFiles(); if (sources == null) throw new IllegalArgumentException("No source in " + sourceDir); sort(sources); for (File source : sources) if ("java".equals(getExtension(source.toString()))) if (!"package-info".equals(getBaseName(source.toString()))) data.add(new Object[]{source, new File(resourceDir, getBaseName(source.toString())), new File(mergedDir, getBaseName(source.toString()))}); return data.toArray(new Object[data.size()][]); } @Test(dataProvider = "testcases") public void test(File source, File expected, File expectedMerged) throws IOException { final Report compilation = JAVAC.compile(source, String.format("-A%s=%s", COMPILE_COMMAND_INCREMENTAL_OUTPUT_OPTION, INCREMENTAL_FRAGMENTS)); assertTrue(compilation.isSuccessful(), "compilation failed"); assertFalse(compilation.hasErrors(), "compilation has errors"); assertFalse(compilation.hasWarnings(), "compilation has warnings");
assertFalse(new File(compilation.getClassesDirectory(), COMPILE_COMMAND_FILE_PATH_DEFAULT).exists(), "default output file exists, but must not exist");
nicoulaj/compile-command-annotations
src/test/java/net/nicoulaj/compilecommand/CompileCommandProcessorTest.java
// Path: src/main/java/net/nicoulaj/compilecommand/CompileCommandProcessor.java // public static final String COMPILE_COMMAND_FILE_PATH_DEFAULT = "META-INF/hotspot_compiler"; // // Path: src/test/java/net/nicoulaj/compilecommand/JavaCompilationTester.java // public static final class Report { // // private final File classesDirectory; // // private final File sourcesDirectory; // // private final boolean successful; // // private final List<Diagnostic<? extends JavaFileObject>> diagnostics; // // private final String stdout; // // Report(final File classesDirectory, // final File sourcesDirectory, // final boolean successful, // final List<Diagnostic<? extends JavaFileObject>> diagnostics, // final String stdout) { // this.classesDirectory = classesDirectory; // this.sourcesDirectory = sourcesDirectory; // this.successful = successful; // this.diagnostics = diagnostics; // this.stdout = stdout; // } // // public File getClassesDirectory() { // return classesDirectory; // } // // public File getSourcesDirectory() { // return sourcesDirectory; // } // // public boolean isSuccessful() { // return successful; // } // // public boolean isFailed() { // return !successful; // } // // public boolean hasErrors() { // return !successful; // } // // public boolean hasWarnings() { // for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) // if (diagnostic.getKind() == WARNING || diagnostic.getKind() == MANDATORY_WARNING) // return true; // return false; // } // // public List<Diagnostic<? extends JavaFileObject>> getDiagnostics() { // return diagnostics; // } // // public String getStdout() { // return stdout; // } // }
import static org.assertj.core.api.Assertions.assertThat; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static com.google.common.collect.ObjectArrays.concat; import static java.util.Arrays.sort; import static net.nicoulaj.compilecommand.CompileCommandProcessor.COMPILE_COMMAND_FILE_PATH_DEFAULT; import static net.nicoulaj.compilecommand.JavaCompilationTester.Report; import static org.apache.commons.io.FilenameUtils.getBaseName; import static org.apache.commons.io.FilenameUtils.getExtension;
/* * Hotspot compile command annotations - http://compile-command-annotations.nicoulaj.net * Copyright © 2014-2019 Hotspot compile command annotations contributors * * 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 net.nicoulaj.compilecommand; /** * Unit tests for {@link CompileCommandProcessor}. * * @author <a href="http://github.com/nicoulaj">Julien Nicoulaud</a> */ public final class CompileCommandProcessorTest { private static final JavaCompilationTester JAVAC = new JavaCompilationTester(); private static final File SAMPLES_SOURCES = new File("src/samples/java/net/nicoulaj/compilecommand"); private static final File SAMPLES_RESOURCES = new File("src/samples/resources/net/nicoulaj/compilecommand"); private static final File TEST_CASES_SOURCES = new File("src/test/java/net/nicoulaj/compilecommand/testcases"); private static final File TEST_CASES_RESOURCES = new File("src/test/resources/net/nicoulaj/compilecommand/testcases"); @DataProvider public Object[][] testcases() throws IOException { return concat(getDataProvider(TEST_CASES_SOURCES, TEST_CASES_RESOURCES), getDataProvider(SAMPLES_SOURCES, SAMPLES_RESOURCES), Object[].class); } private Object[][] getDataProvider(File sourceDir, File resourceDir) throws IOException { final List<Object[]> data = new ArrayList<Object[]>(); final File[] sources = sourceDir.listFiles(); if (sources == null) throw new IllegalArgumentException("No source in " + sourceDir); sort(sources); for (File source : sources) if ("java".equals(getExtension(source.toString()))) if (!"package-info".equals(getBaseName(source.toString()))) data.add(new Object[]{source, new File(resourceDir, getBaseName(source.toString()))}); return data.toArray(new Object[data.size()][]); } @Test(dataProvider = "testcases") public void test(File source, File expected) {
// Path: src/main/java/net/nicoulaj/compilecommand/CompileCommandProcessor.java // public static final String COMPILE_COMMAND_FILE_PATH_DEFAULT = "META-INF/hotspot_compiler"; // // Path: src/test/java/net/nicoulaj/compilecommand/JavaCompilationTester.java // public static final class Report { // // private final File classesDirectory; // // private final File sourcesDirectory; // // private final boolean successful; // // private final List<Diagnostic<? extends JavaFileObject>> diagnostics; // // private final String stdout; // // Report(final File classesDirectory, // final File sourcesDirectory, // final boolean successful, // final List<Diagnostic<? extends JavaFileObject>> diagnostics, // final String stdout) { // this.classesDirectory = classesDirectory; // this.sourcesDirectory = sourcesDirectory; // this.successful = successful; // this.diagnostics = diagnostics; // this.stdout = stdout; // } // // public File getClassesDirectory() { // return classesDirectory; // } // // public File getSourcesDirectory() { // return sourcesDirectory; // } // // public boolean isSuccessful() { // return successful; // } // // public boolean isFailed() { // return !successful; // } // // public boolean hasErrors() { // return !successful; // } // // public boolean hasWarnings() { // for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) // if (diagnostic.getKind() == WARNING || diagnostic.getKind() == MANDATORY_WARNING) // return true; // return false; // } // // public List<Diagnostic<? extends JavaFileObject>> getDiagnostics() { // return diagnostics; // } // // public String getStdout() { // return stdout; // } // } // Path: src/test/java/net/nicoulaj/compilecommand/CompileCommandProcessorTest.java import static org.assertj.core.api.Assertions.assertThat; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static com.google.common.collect.ObjectArrays.concat; import static java.util.Arrays.sort; import static net.nicoulaj.compilecommand.CompileCommandProcessor.COMPILE_COMMAND_FILE_PATH_DEFAULT; import static net.nicoulaj.compilecommand.JavaCompilationTester.Report; import static org.apache.commons.io.FilenameUtils.getBaseName; import static org.apache.commons.io.FilenameUtils.getExtension; /* * Hotspot compile command annotations - http://compile-command-annotations.nicoulaj.net * Copyright © 2014-2019 Hotspot compile command annotations contributors * * 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 net.nicoulaj.compilecommand; /** * Unit tests for {@link CompileCommandProcessor}. * * @author <a href="http://github.com/nicoulaj">Julien Nicoulaud</a> */ public final class CompileCommandProcessorTest { private static final JavaCompilationTester JAVAC = new JavaCompilationTester(); private static final File SAMPLES_SOURCES = new File("src/samples/java/net/nicoulaj/compilecommand"); private static final File SAMPLES_RESOURCES = new File("src/samples/resources/net/nicoulaj/compilecommand"); private static final File TEST_CASES_SOURCES = new File("src/test/java/net/nicoulaj/compilecommand/testcases"); private static final File TEST_CASES_RESOURCES = new File("src/test/resources/net/nicoulaj/compilecommand/testcases"); @DataProvider public Object[][] testcases() throws IOException { return concat(getDataProvider(TEST_CASES_SOURCES, TEST_CASES_RESOURCES), getDataProvider(SAMPLES_SOURCES, SAMPLES_RESOURCES), Object[].class); } private Object[][] getDataProvider(File sourceDir, File resourceDir) throws IOException { final List<Object[]> data = new ArrayList<Object[]>(); final File[] sources = sourceDir.listFiles(); if (sources == null) throw new IllegalArgumentException("No source in " + sourceDir); sort(sources); for (File source : sources) if ("java".equals(getExtension(source.toString()))) if (!"package-info".equals(getBaseName(source.toString()))) data.add(new Object[]{source, new File(resourceDir, getBaseName(source.toString()))}); return data.toArray(new Object[data.size()][]); } @Test(dataProvider = "testcases") public void test(File source, File expected) {
final Report compilation = JAVAC.compile(source);
nicoulaj/compile-command-annotations
src/test/java/net/nicoulaj/compilecommand/CompileCommandProcessorTest.java
// Path: src/main/java/net/nicoulaj/compilecommand/CompileCommandProcessor.java // public static final String COMPILE_COMMAND_FILE_PATH_DEFAULT = "META-INF/hotspot_compiler"; // // Path: src/test/java/net/nicoulaj/compilecommand/JavaCompilationTester.java // public static final class Report { // // private final File classesDirectory; // // private final File sourcesDirectory; // // private final boolean successful; // // private final List<Diagnostic<? extends JavaFileObject>> diagnostics; // // private final String stdout; // // Report(final File classesDirectory, // final File sourcesDirectory, // final boolean successful, // final List<Diagnostic<? extends JavaFileObject>> diagnostics, // final String stdout) { // this.classesDirectory = classesDirectory; // this.sourcesDirectory = sourcesDirectory; // this.successful = successful; // this.diagnostics = diagnostics; // this.stdout = stdout; // } // // public File getClassesDirectory() { // return classesDirectory; // } // // public File getSourcesDirectory() { // return sourcesDirectory; // } // // public boolean isSuccessful() { // return successful; // } // // public boolean isFailed() { // return !successful; // } // // public boolean hasErrors() { // return !successful; // } // // public boolean hasWarnings() { // for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) // if (diagnostic.getKind() == WARNING || diagnostic.getKind() == MANDATORY_WARNING) // return true; // return false; // } // // public List<Diagnostic<? extends JavaFileObject>> getDiagnostics() { // return diagnostics; // } // // public String getStdout() { // return stdout; // } // }
import static org.assertj.core.api.Assertions.assertThat; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static com.google.common.collect.ObjectArrays.concat; import static java.util.Arrays.sort; import static net.nicoulaj.compilecommand.CompileCommandProcessor.COMPILE_COMMAND_FILE_PATH_DEFAULT; import static net.nicoulaj.compilecommand.JavaCompilationTester.Report; import static org.apache.commons.io.FilenameUtils.getBaseName; import static org.apache.commons.io.FilenameUtils.getExtension;
/* * Hotspot compile command annotations - http://compile-command-annotations.nicoulaj.net * Copyright © 2014-2019 Hotspot compile command annotations contributors * * 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 net.nicoulaj.compilecommand; /** * Unit tests for {@link CompileCommandProcessor}. * * @author <a href="http://github.com/nicoulaj">Julien Nicoulaud</a> */ public final class CompileCommandProcessorTest { private static final JavaCompilationTester JAVAC = new JavaCompilationTester(); private static final File SAMPLES_SOURCES = new File("src/samples/java/net/nicoulaj/compilecommand"); private static final File SAMPLES_RESOURCES = new File("src/samples/resources/net/nicoulaj/compilecommand"); private static final File TEST_CASES_SOURCES = new File("src/test/java/net/nicoulaj/compilecommand/testcases"); private static final File TEST_CASES_RESOURCES = new File("src/test/resources/net/nicoulaj/compilecommand/testcases"); @DataProvider public Object[][] testcases() throws IOException { return concat(getDataProvider(TEST_CASES_SOURCES, TEST_CASES_RESOURCES), getDataProvider(SAMPLES_SOURCES, SAMPLES_RESOURCES), Object[].class); } private Object[][] getDataProvider(File sourceDir, File resourceDir) throws IOException { final List<Object[]> data = new ArrayList<Object[]>(); final File[] sources = sourceDir.listFiles(); if (sources == null) throw new IllegalArgumentException("No source in " + sourceDir); sort(sources); for (File source : sources) if ("java".equals(getExtension(source.toString()))) if (!"package-info".equals(getBaseName(source.toString()))) data.add(new Object[]{source, new File(resourceDir, getBaseName(source.toString()))}); return data.toArray(new Object[data.size()][]); } @Test(dataProvider = "testcases") public void test(File source, File expected) { final Report compilation = JAVAC.compile(source); assertTrue(compilation.isSuccessful(), "compilation failed"); assertFalse(compilation.hasErrors(), "compilation has errors"); assertFalse(compilation.hasWarnings(), "compilation has warnings");
// Path: src/main/java/net/nicoulaj/compilecommand/CompileCommandProcessor.java // public static final String COMPILE_COMMAND_FILE_PATH_DEFAULT = "META-INF/hotspot_compiler"; // // Path: src/test/java/net/nicoulaj/compilecommand/JavaCompilationTester.java // public static final class Report { // // private final File classesDirectory; // // private final File sourcesDirectory; // // private final boolean successful; // // private final List<Diagnostic<? extends JavaFileObject>> diagnostics; // // private final String stdout; // // Report(final File classesDirectory, // final File sourcesDirectory, // final boolean successful, // final List<Diagnostic<? extends JavaFileObject>> diagnostics, // final String stdout) { // this.classesDirectory = classesDirectory; // this.sourcesDirectory = sourcesDirectory; // this.successful = successful; // this.diagnostics = diagnostics; // this.stdout = stdout; // } // // public File getClassesDirectory() { // return classesDirectory; // } // // public File getSourcesDirectory() { // return sourcesDirectory; // } // // public boolean isSuccessful() { // return successful; // } // // public boolean isFailed() { // return !successful; // } // // public boolean hasErrors() { // return !successful; // } // // public boolean hasWarnings() { // for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) // if (diagnostic.getKind() == WARNING || diagnostic.getKind() == MANDATORY_WARNING) // return true; // return false; // } // // public List<Diagnostic<? extends JavaFileObject>> getDiagnostics() { // return diagnostics; // } // // public String getStdout() { // return stdout; // } // } // Path: src/test/java/net/nicoulaj/compilecommand/CompileCommandProcessorTest.java import static org.assertj.core.api.Assertions.assertThat; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static com.google.common.collect.ObjectArrays.concat; import static java.util.Arrays.sort; import static net.nicoulaj.compilecommand.CompileCommandProcessor.COMPILE_COMMAND_FILE_PATH_DEFAULT; import static net.nicoulaj.compilecommand.JavaCompilationTester.Report; import static org.apache.commons.io.FilenameUtils.getBaseName; import static org.apache.commons.io.FilenameUtils.getExtension; /* * Hotspot compile command annotations - http://compile-command-annotations.nicoulaj.net * Copyright © 2014-2019 Hotspot compile command annotations contributors * * 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 net.nicoulaj.compilecommand; /** * Unit tests for {@link CompileCommandProcessor}. * * @author <a href="http://github.com/nicoulaj">Julien Nicoulaud</a> */ public final class CompileCommandProcessorTest { private static final JavaCompilationTester JAVAC = new JavaCompilationTester(); private static final File SAMPLES_SOURCES = new File("src/samples/java/net/nicoulaj/compilecommand"); private static final File SAMPLES_RESOURCES = new File("src/samples/resources/net/nicoulaj/compilecommand"); private static final File TEST_CASES_SOURCES = new File("src/test/java/net/nicoulaj/compilecommand/testcases"); private static final File TEST_CASES_RESOURCES = new File("src/test/resources/net/nicoulaj/compilecommand/testcases"); @DataProvider public Object[][] testcases() throws IOException { return concat(getDataProvider(TEST_CASES_SOURCES, TEST_CASES_RESOURCES), getDataProvider(SAMPLES_SOURCES, SAMPLES_RESOURCES), Object[].class); } private Object[][] getDataProvider(File sourceDir, File resourceDir) throws IOException { final List<Object[]> data = new ArrayList<Object[]>(); final File[] sources = sourceDir.listFiles(); if (sources == null) throw new IllegalArgumentException("No source in " + sourceDir); sort(sources); for (File source : sources) if ("java".equals(getExtension(source.toString()))) if (!"package-info".equals(getBaseName(source.toString()))) data.add(new Object[]{source, new File(resourceDir, getBaseName(source.toString()))}); return data.toArray(new Object[data.size()][]); } @Test(dataProvider = "testcases") public void test(File source, File expected) { final Report compilation = JAVAC.compile(source); assertTrue(compilation.isSuccessful(), "compilation failed"); assertFalse(compilation.hasErrors(), "compilation has errors"); assertFalse(compilation.hasWarnings(), "compilation has warnings");
assertThat(new File(compilation.getClassesDirectory(), COMPILE_COMMAND_FILE_PATH_DEFAULT)).hasContentEqualTo(expected);
FibreFoX/javafx-gradle-plugin
src/main/java/de/dynamicfiles/projects/gradle/plugins/javafx/tasks/workarounds/MacAppBundlerWithAdditionalResources.java
// Path: src/main/java/de/dynamicfiles/projects/gradle/plugins/javafx/tasks/internal/JavaDetectionTools.java // public class JavaDetectionTools { // // public static final boolean IS_JAVA_8 = isJavaVersion(8); // public static final boolean IS_JAVA_9 = !IS_JAVA_8 && isJavaVersion(9) || isJavaVersion(9, true); // // public static boolean isJavaVersion(int oracleJavaVersion, boolean noVersionOne) { // String javaVersion = System.getProperty("java.version"); // if( noVersionOne ){ // return javaVersion.startsWith(String.valueOf(oracleJavaVersion)); // } // return javaVersion.startsWith("1." + oracleJavaVersion); // } // // public static boolean isJavaVersion(int oracleJavaVersion) { // return isJavaVersion(oracleJavaVersion, false); // } // // public static boolean isAtLeastOracleJavaUpdateVersion(int updateNumber) { // String javaVersion = System.getProperty("java.version"); // String[] javaVersionSplitted = javaVersion.split("_"); // if( javaVersionSplitted.length <= 1 ){ // return false; // } // String javaUpdateVersionRaw = javaVersionSplitted[1]; // // required for any non-oracle JDK like the openjdk, as the reported version might result something like "1.8.0_45-internal" // String javaUpdateVersion = javaUpdateVersionRaw.replaceAll("[^\\d]", ""); // return Integer.parseInt(javaUpdateVersion, 10) >= updateNumber; // } // }
import com.oracle.tools.packager.BundlerParamInfo; import com.oracle.tools.packager.IOUtils; import com.oracle.tools.packager.Log; import com.oracle.tools.packager.StandardBundlerParam; import static com.oracle.tools.packager.StandardBundlerParam.APP_NAME; import static com.oracle.tools.packager.StandardBundlerParam.BUILD_ROOT; import static com.oracle.tools.packager.StandardBundlerParam.VERBOSE; import com.oracle.tools.packager.mac.MacAppBundler; import com.oracle.tools.packager.mac.MacBaseInstallerBundler; import de.dynamicfiles.projects.gradle.plugins.javafx.tasks.internal.JavaDetectionTools; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.ResourceBundle; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference;
BUILD_ROOT.fetchFrom(p); prepareConfigFiles(p); rootDirectory = new File(outputDirectory, APP_NAME.fetchFrom(p) + ".app"); // this is the root of evil, because we can't just "pre-copy" all additional files needed IOUtils.deleteRecursive(rootDirectory); // recreate rootDirectory.mkdirs(); // this mac app bundler gets called by other mac installer bundlers if( !dependentTask ){ Log.info(MessageFormat.format(I18N.getString("message.creating-app-bundle"), rootDirectory.getAbsolutePath())); } File contentsDirectory = new File(rootDirectory, "Contents"); contentsDirectory.mkdirs(); File macOSDirectory = new File(contentsDirectory, "MacOS"); macOSDirectory.mkdirs(); File javaDirectory = new File(contentsDirectory, "Java"); javaDirectory.mkdirs(); File plugInsDirectory = new File(contentsDirectory, "PlugIns"); File resourcesDirectory = new File(contentsDirectory, "Resources"); resourcesDirectory.mkdirs(); File pkgInfoFile = new File(contentsDirectory, "PkgInfo"); pkgInfoFile.createNewFile(); writePkgInfo(pkgInfoFile); File executableFile = new File(macOSDirectory, getLauncherName(p)); IOUtils.copyFromURL(RAW_EXECUTABLE_URL.fetchFrom(p), executableFile);
// Path: src/main/java/de/dynamicfiles/projects/gradle/plugins/javafx/tasks/internal/JavaDetectionTools.java // public class JavaDetectionTools { // // public static final boolean IS_JAVA_8 = isJavaVersion(8); // public static final boolean IS_JAVA_9 = !IS_JAVA_8 && isJavaVersion(9) || isJavaVersion(9, true); // // public static boolean isJavaVersion(int oracleJavaVersion, boolean noVersionOne) { // String javaVersion = System.getProperty("java.version"); // if( noVersionOne ){ // return javaVersion.startsWith(String.valueOf(oracleJavaVersion)); // } // return javaVersion.startsWith("1." + oracleJavaVersion); // } // // public static boolean isJavaVersion(int oracleJavaVersion) { // return isJavaVersion(oracleJavaVersion, false); // } // // public static boolean isAtLeastOracleJavaUpdateVersion(int updateNumber) { // String javaVersion = System.getProperty("java.version"); // String[] javaVersionSplitted = javaVersion.split("_"); // if( javaVersionSplitted.length <= 1 ){ // return false; // } // String javaUpdateVersionRaw = javaVersionSplitted[1]; // // required for any non-oracle JDK like the openjdk, as the reported version might result something like "1.8.0_45-internal" // String javaUpdateVersion = javaUpdateVersionRaw.replaceAll("[^\\d]", ""); // return Integer.parseInt(javaUpdateVersion, 10) >= updateNumber; // } // } // Path: src/main/java/de/dynamicfiles/projects/gradle/plugins/javafx/tasks/workarounds/MacAppBundlerWithAdditionalResources.java import com.oracle.tools.packager.BundlerParamInfo; import com.oracle.tools.packager.IOUtils; import com.oracle.tools.packager.Log; import com.oracle.tools.packager.StandardBundlerParam; import static com.oracle.tools.packager.StandardBundlerParam.APP_NAME; import static com.oracle.tools.packager.StandardBundlerParam.BUILD_ROOT; import static com.oracle.tools.packager.StandardBundlerParam.VERBOSE; import com.oracle.tools.packager.mac.MacAppBundler; import com.oracle.tools.packager.mac.MacBaseInstallerBundler; import de.dynamicfiles.projects.gradle.plugins.javafx.tasks.internal.JavaDetectionTools; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.ResourceBundle; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; BUILD_ROOT.fetchFrom(p); prepareConfigFiles(p); rootDirectory = new File(outputDirectory, APP_NAME.fetchFrom(p) + ".app"); // this is the root of evil, because we can't just "pre-copy" all additional files needed IOUtils.deleteRecursive(rootDirectory); // recreate rootDirectory.mkdirs(); // this mac app bundler gets called by other mac installer bundlers if( !dependentTask ){ Log.info(MessageFormat.format(I18N.getString("message.creating-app-bundle"), rootDirectory.getAbsolutePath())); } File contentsDirectory = new File(rootDirectory, "Contents"); contentsDirectory.mkdirs(); File macOSDirectory = new File(contentsDirectory, "MacOS"); macOSDirectory.mkdirs(); File javaDirectory = new File(contentsDirectory, "Java"); javaDirectory.mkdirs(); File plugInsDirectory = new File(contentsDirectory, "PlugIns"); File resourcesDirectory = new File(contentsDirectory, "Resources"); resourcesDirectory.mkdirs(); File pkgInfoFile = new File(contentsDirectory, "PkgInfo"); pkgInfoFile.createNewFile(); writePkgInfo(pkgInfoFile); File executableFile = new File(macOSDirectory, getLauncherName(p)); IOUtils.copyFromURL(RAW_EXECUTABLE_URL.fetchFrom(p), executableFile);
if( JavaDetectionTools.IS_JAVA_8 && JavaDetectionTools.isAtLeastOracleJavaUpdateVersion(40) ){
FibreFoX/javafx-gradle-plugin
src/main/java/de/dynamicfiles/projects/gradle/plugins/javafx/tasks/JfxListBundlersTask.java
// Path: src/main/java/de/dynamicfiles/projects/gradle/plugins/javafx/tasks/workers/JfxListBundlersWorker.java // public class JfxListBundlersWorker extends JfxAbstractWorker { // // public void jfxlistbundlers(Project project) { // Logger logger = project.getLogger(); // // Bundlers bundlers = Bundlers.createBundlersInstance(); // logger.info("Available bundlers:"); // logger.info("-------------------"); // Map<String, ? super Object> dummyParams = new HashMap<>(); // bundlers.getBundlers().stream().forEach((bundler) -> { // try{ // bundler.validate(dummyParams); // } catch(UnsupportedPlatformException ex){ // return; // } catch(ConfigException ex){ // // NO-OP // // bundler is supported on this OS // } // // logger.lifecycle("ID: " + bundler.getID()); // logger.lifecycle("Name: " + bundler.getName()); // logger.lifecycle("Description: " + bundler.getDescription()); // // Collection<BundlerParamInfo<?>> bundleParameters = bundler.getBundleParameters(); // Optional.ofNullable(bundleParameters).ifPresent(nonNullBundleArguments -> { // logger.info("Available bundle arguments: "); // nonNullBundleArguments.stream().forEach(bundleArgument -> { // logger.info("\t\tArgument ID: " + bundleArgument.getID()); // logger.info("\t\tArgument Type: " + bundleArgument.getValueType().getName()); // logger.info("\t\tArgument Name: " + bundleArgument.getName()); // logger.info("\t\tArgument Description: " + bundleArgument.getDescription()); // logger.info(""); // }); // }); // logger.lifecycle("-------------------"); // }); // // if( !logger.isEnabled(LogLevel.INFO) ){ // logger.lifecycle("For more information, please use --info parameter."); // } // } // // }
import de.dynamicfiles.projects.gradle.plugins.javafx.tasks.workers.JfxListBundlersWorker; import org.gradle.api.internal.AbstractTask; import org.gradle.api.tasks.TaskAction;
/* * Copyright 2016 Danny Althoff * * 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 de.dynamicfiles.projects.gradle.plugins.javafx.tasks; /** * * @author Danny Althoff */ public class JfxListBundlersTask extends AbstractTask { public static final String JFX_TASK_NAME = "jfxListBundlers"; @TaskAction public void jfxlistbundlers() {
// Path: src/main/java/de/dynamicfiles/projects/gradle/plugins/javafx/tasks/workers/JfxListBundlersWorker.java // public class JfxListBundlersWorker extends JfxAbstractWorker { // // public void jfxlistbundlers(Project project) { // Logger logger = project.getLogger(); // // Bundlers bundlers = Bundlers.createBundlersInstance(); // logger.info("Available bundlers:"); // logger.info("-------------------"); // Map<String, ? super Object> dummyParams = new HashMap<>(); // bundlers.getBundlers().stream().forEach((bundler) -> { // try{ // bundler.validate(dummyParams); // } catch(UnsupportedPlatformException ex){ // return; // } catch(ConfigException ex){ // // NO-OP // // bundler is supported on this OS // } // // logger.lifecycle("ID: " + bundler.getID()); // logger.lifecycle("Name: " + bundler.getName()); // logger.lifecycle("Description: " + bundler.getDescription()); // // Collection<BundlerParamInfo<?>> bundleParameters = bundler.getBundleParameters(); // Optional.ofNullable(bundleParameters).ifPresent(nonNullBundleArguments -> { // logger.info("Available bundle arguments: "); // nonNullBundleArguments.stream().forEach(bundleArgument -> { // logger.info("\t\tArgument ID: " + bundleArgument.getID()); // logger.info("\t\tArgument Type: " + bundleArgument.getValueType().getName()); // logger.info("\t\tArgument Name: " + bundleArgument.getName()); // logger.info("\t\tArgument Description: " + bundleArgument.getDescription()); // logger.info(""); // }); // }); // logger.lifecycle("-------------------"); // }); // // if( !logger.isEnabled(LogLevel.INFO) ){ // logger.lifecycle("For more information, please use --info parameter."); // } // } // // } // Path: src/main/java/de/dynamicfiles/projects/gradle/plugins/javafx/tasks/JfxListBundlersTask.java import de.dynamicfiles.projects.gradle.plugins.javafx.tasks.workers.JfxListBundlersWorker; import org.gradle.api.internal.AbstractTask; import org.gradle.api.tasks.TaskAction; /* * Copyright 2016 Danny Althoff * * 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 de.dynamicfiles.projects.gradle.plugins.javafx.tasks; /** * * @author Danny Althoff */ public class JfxListBundlersTask extends AbstractTask { public static final String JFX_TASK_NAME = "jfxListBundlers"; @TaskAction public void jfxlistbundlers() {
new JfxListBundlersWorker().jfxlistbundlers(this.getProject());
FibreFoX/javafx-gradle-plugin
src/test/java/de/dynamicfiles/projects/gradle/plugins/javafx/tests/exampleprojects/AdditionalBundlerFiles.java
// Path: src/test/java/de/dynamicfiles/projects/gradle/plugins/javafx/tests/exampleprojects/ExampleProjectTest.java // protected static final List<String> GRADLE_VERSIONS_TO_TEST_AGAINST = new ArrayList<>(); // // Path: src/test/java/de/dynamicfiles/projects/gradle/plugins/javafx/tests/exampleprojects/ExampleProjectTest.java // public static void readVersionString() throws IOException { // List<String> versionFileLines = Files.readAllLines(new File("version.gradle").toPath()); // versionFileLines.forEach(line -> { // if( line.contains("currentPluginVersion") ){ // versionString = line.replace("currentPluginVersion", "").replace("=", "").replace("'", "").trim(); // } // }); // }
import static de.dynamicfiles.projects.gradle.plugins.javafx.tests.exampleprojects.ExampleProjectTest.GRADLE_VERSIONS_TO_TEST_AGAINST; import static de.dynamicfiles.projects.gradle.plugins.javafx.tests.exampleprojects.ExampleProjectTest.readVersionString; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import org.gradle.testkit.runner.BuildResult; import org.gradle.testkit.runner.GradleRunner; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test;
/* * Copyright 2016 Danny Althoff * * 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 de.dynamicfiles.projects.gradle.plugins.javafx.tests.exampleprojects; /** * * @author Danny Althoff */ public class AdditionalBundlerFiles extends ExampleProjectTest { @BeforeClass public static void readVersion() throws IOException {
// Path: src/test/java/de/dynamicfiles/projects/gradle/plugins/javafx/tests/exampleprojects/ExampleProjectTest.java // protected static final List<String> GRADLE_VERSIONS_TO_TEST_AGAINST = new ArrayList<>(); // // Path: src/test/java/de/dynamicfiles/projects/gradle/plugins/javafx/tests/exampleprojects/ExampleProjectTest.java // public static void readVersionString() throws IOException { // List<String> versionFileLines = Files.readAllLines(new File("version.gradle").toPath()); // versionFileLines.forEach(line -> { // if( line.contains("currentPluginVersion") ){ // versionString = line.replace("currentPluginVersion", "").replace("=", "").replace("'", "").trim(); // } // }); // } // Path: src/test/java/de/dynamicfiles/projects/gradle/plugins/javafx/tests/exampleprojects/AdditionalBundlerFiles.java import static de.dynamicfiles.projects.gradle.plugins.javafx.tests.exampleprojects.ExampleProjectTest.GRADLE_VERSIONS_TO_TEST_AGAINST; import static de.dynamicfiles.projects.gradle.plugins.javafx.tests.exampleprojects.ExampleProjectTest.readVersionString; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import org.gradle.testkit.runner.BuildResult; import org.gradle.testkit.runner.GradleRunner; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /* * Copyright 2016 Danny Althoff * * 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 de.dynamicfiles.projects.gradle.plugins.javafx.tests.exampleprojects; /** * * @author Danny Althoff */ public class AdditionalBundlerFiles extends ExampleProjectTest { @BeforeClass public static void readVersion() throws IOException {
readVersionString();
FibreFoX/javafx-gradle-plugin
src/test/java/de/dynamicfiles/projects/gradle/plugins/javafx/tests/exampleprojects/AdditionalBundlerFiles.java
// Path: src/test/java/de/dynamicfiles/projects/gradle/plugins/javafx/tests/exampleprojects/ExampleProjectTest.java // protected static final List<String> GRADLE_VERSIONS_TO_TEST_AGAINST = new ArrayList<>(); // // Path: src/test/java/de/dynamicfiles/projects/gradle/plugins/javafx/tests/exampleprojects/ExampleProjectTest.java // public static void readVersionString() throws IOException { // List<String> versionFileLines = Files.readAllLines(new File("version.gradle").toPath()); // versionFileLines.forEach(line -> { // if( line.contains("currentPluginVersion") ){ // versionString = line.replace("currentPluginVersion", "").replace("=", "").replace("'", "").trim(); // } // }); // }
import static de.dynamicfiles.projects.gradle.plugins.javafx.tests.exampleprojects.ExampleProjectTest.GRADLE_VERSIONS_TO_TEST_AGAINST; import static de.dynamicfiles.projects.gradle.plugins.javafx.tests.exampleprojects.ExampleProjectTest.readVersionString; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import org.gradle.testkit.runner.BuildResult; import org.gradle.testkit.runner.GradleRunner; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test;
/* * Copyright 2016 Danny Althoff * * 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 de.dynamicfiles.projects.gradle.plugins.javafx.tests.exampleprojects; /** * * @author Danny Althoff */ public class AdditionalBundlerFiles extends ExampleProjectTest { @BeforeClass public static void readVersion() throws IOException { readVersionString(); } @Test public void additionalBundlerFilesJfxNative() {
// Path: src/test/java/de/dynamicfiles/projects/gradle/plugins/javafx/tests/exampleprojects/ExampleProjectTest.java // protected static final List<String> GRADLE_VERSIONS_TO_TEST_AGAINST = new ArrayList<>(); // // Path: src/test/java/de/dynamicfiles/projects/gradle/plugins/javafx/tests/exampleprojects/ExampleProjectTest.java // public static void readVersionString() throws IOException { // List<String> versionFileLines = Files.readAllLines(new File("version.gradle").toPath()); // versionFileLines.forEach(line -> { // if( line.contains("currentPluginVersion") ){ // versionString = line.replace("currentPluginVersion", "").replace("=", "").replace("'", "").trim(); // } // }); // } // Path: src/test/java/de/dynamicfiles/projects/gradle/plugins/javafx/tests/exampleprojects/AdditionalBundlerFiles.java import static de.dynamicfiles.projects.gradle.plugins.javafx.tests.exampleprojects.ExampleProjectTest.GRADLE_VERSIONS_TO_TEST_AGAINST; import static de.dynamicfiles.projects.gradle.plugins.javafx.tests.exampleprojects.ExampleProjectTest.readVersionString; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import org.gradle.testkit.runner.BuildResult; import org.gradle.testkit.runner.GradleRunner; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /* * Copyright 2016 Danny Althoff * * 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 de.dynamicfiles.projects.gradle.plugins.javafx.tests.exampleprojects; /** * * @author Danny Althoff */ public class AdditionalBundlerFiles extends ExampleProjectTest { @BeforeClass public static void readVersion() throws IOException { readVersionString(); } @Test public void additionalBundlerFilesJfxNative() {
GRADLE_VERSIONS_TO_TEST_AGAINST.forEach(gradleVersion -> {
FibreFoX/javafx-gradle-plugin
src/main/java/de/dynamicfiles/projects/gradle/plugins/javafx/tasks/JfxRunTask.java
// Path: src/main/java/de/dynamicfiles/projects/gradle/plugins/javafx/tasks/workers/JfxRunWorker.java // public class JfxRunWorker extends JfxAbstractWorker { // // public void jfxrun(Project project) { // // get our configuration // JavaFXGradlePluginExtension ext = project.getExtensions().getByType(JavaFXGradlePluginExtension.class); // addDeployDirToSystemClassloader(project, ext); // // // set logger-level // Log.setLogger(new Log.Logger(ext.isVerbose())); // project.getLogger().lifecycle("Running JavaFX Application"); // // List<String> command = new ArrayList<>(); // command.add(getEnvironmentRelativeExecutablePath(ext.isUseEnvironmentRelativeExecutables()) + "java"); // // Optional.ofNullable(ext.getRunJavaParameter()).ifPresent(runJavaParameter -> { // if( runJavaParameter.trim().isEmpty() ){ // return; // } // command.add(runJavaParameter); // }); // // Optional.ofNullable(ext.getRunJavaParameters()).ifPresent(runJavaParameters -> { // if( runJavaParameters.isEmpty() ){ // return; // } // command.addAll(runJavaParameters); // }); // // command.add("-jar"); // command.add(ext.getJfxMainAppJarName()); // Optional.ofNullable(ext.getRunAppParameter()).ifPresent(runAppParameter -> { // if( runAppParameter.trim().isEmpty() ){ // return; // } // command.add(runAppParameter); // }); // // try{ // ProcessBuilder pb = new ProcessBuilder(); // if( !isGradleDaemonMode() ){ // pb.inheritIO(); // } // // if( ext.isVerbose() ){ // project.getLogger().lifecycle("Running command: " + String.join(" ", command)); // } // // pb.directory(getAbsoluteOrProjectRelativeFile(project, ext.getJfxAppOutputDir(), ext.isCheckForAbsolutePaths())) // .command(command); // Process p = pb.start(); // // if( isGradleDaemonMode() ){ // redirectIO(p, project.getLogger()); // } // // p.waitFor(); // if( p.exitValue() != 0 ){ // throw new GradleException("There was an exception while executing JavaFX Application. Please check build-log."); // } // } catch(IOException | InterruptedException ex){ // throw new GradleException("There was an exception while executing JavaFX Application.", ex); // } // } // // }
import de.dynamicfiles.projects.gradle.plugins.javafx.tasks.workers.JfxRunWorker; import org.gradle.api.internal.AbstractTask; import org.gradle.api.tasks.TaskAction;
/* * Copyright 2016 Danny Althoff * * 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 de.dynamicfiles.projects.gradle.plugins.javafx.tasks; /** * * @author Danny Althoff */ public class JfxRunTask extends AbstractTask { public static final String JFX_TASK_NAME = "jfxRun"; @TaskAction public void jfxrun() {
// Path: src/main/java/de/dynamicfiles/projects/gradle/plugins/javafx/tasks/workers/JfxRunWorker.java // public class JfxRunWorker extends JfxAbstractWorker { // // public void jfxrun(Project project) { // // get our configuration // JavaFXGradlePluginExtension ext = project.getExtensions().getByType(JavaFXGradlePluginExtension.class); // addDeployDirToSystemClassloader(project, ext); // // // set logger-level // Log.setLogger(new Log.Logger(ext.isVerbose())); // project.getLogger().lifecycle("Running JavaFX Application"); // // List<String> command = new ArrayList<>(); // command.add(getEnvironmentRelativeExecutablePath(ext.isUseEnvironmentRelativeExecutables()) + "java"); // // Optional.ofNullable(ext.getRunJavaParameter()).ifPresent(runJavaParameter -> { // if( runJavaParameter.trim().isEmpty() ){ // return; // } // command.add(runJavaParameter); // }); // // Optional.ofNullable(ext.getRunJavaParameters()).ifPresent(runJavaParameters -> { // if( runJavaParameters.isEmpty() ){ // return; // } // command.addAll(runJavaParameters); // }); // // command.add("-jar"); // command.add(ext.getJfxMainAppJarName()); // Optional.ofNullable(ext.getRunAppParameter()).ifPresent(runAppParameter -> { // if( runAppParameter.trim().isEmpty() ){ // return; // } // command.add(runAppParameter); // }); // // try{ // ProcessBuilder pb = new ProcessBuilder(); // if( !isGradleDaemonMode() ){ // pb.inheritIO(); // } // // if( ext.isVerbose() ){ // project.getLogger().lifecycle("Running command: " + String.join(" ", command)); // } // // pb.directory(getAbsoluteOrProjectRelativeFile(project, ext.getJfxAppOutputDir(), ext.isCheckForAbsolutePaths())) // .command(command); // Process p = pb.start(); // // if( isGradleDaemonMode() ){ // redirectIO(p, project.getLogger()); // } // // p.waitFor(); // if( p.exitValue() != 0 ){ // throw new GradleException("There was an exception while executing JavaFX Application. Please check build-log."); // } // } catch(IOException | InterruptedException ex){ // throw new GradleException("There was an exception while executing JavaFX Application.", ex); // } // } // // } // Path: src/main/java/de/dynamicfiles/projects/gradle/plugins/javafx/tasks/JfxRunTask.java import de.dynamicfiles.projects.gradle.plugins.javafx.tasks.workers.JfxRunWorker; import org.gradle.api.internal.AbstractTask; import org.gradle.api.tasks.TaskAction; /* * Copyright 2016 Danny Althoff * * 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 de.dynamicfiles.projects.gradle.plugins.javafx.tasks; /** * * @author Danny Althoff */ public class JfxRunTask extends AbstractTask { public static final String JFX_TASK_NAME = "jfxRun"; @TaskAction public void jfxrun() {
new JfxRunWorker().jfxrun(this.getProject());
FibreFoX/javafx-gradle-plugin
src/test/java/de/dynamicfiles/projects/gradle/plugins/javafx/tests/exampleprojects/AdditionalApplicationFiles.java
// Path: src/test/java/de/dynamicfiles/projects/gradle/plugins/javafx/tests/exampleprojects/ExampleProjectTest.java // protected static final List<String> GRADLE_VERSIONS_TO_TEST_AGAINST = new ArrayList<>(); // // Path: src/test/java/de/dynamicfiles/projects/gradle/plugins/javafx/tests/exampleprojects/ExampleProjectTest.java // public static void readVersionString() throws IOException { // List<String> versionFileLines = Files.readAllLines(new File("version.gradle").toPath()); // versionFileLines.forEach(line -> { // if( line.contains("currentPluginVersion") ){ // versionString = line.replace("currentPluginVersion", "").replace("=", "").replace("'", "").trim(); // } // }); // }
import static de.dynamicfiles.projects.gradle.plugins.javafx.tests.exampleprojects.ExampleProjectTest.GRADLE_VERSIONS_TO_TEST_AGAINST; import static de.dynamicfiles.projects.gradle.plugins.javafx.tests.exampleprojects.ExampleProjectTest.readVersionString; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import org.gradle.testkit.runner.BuildResult; import org.gradle.testkit.runner.GradleRunner; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test;
/* * Copyright 2016 Danny Althoff * * 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 de.dynamicfiles.projects.gradle.plugins.javafx.tests.exampleprojects; /** * * @author Danny Althoff */ public class AdditionalApplicationFiles extends ExampleProjectTest { @BeforeClass public static void readVersion() throws IOException {
// Path: src/test/java/de/dynamicfiles/projects/gradle/plugins/javafx/tests/exampleprojects/ExampleProjectTest.java // protected static final List<String> GRADLE_VERSIONS_TO_TEST_AGAINST = new ArrayList<>(); // // Path: src/test/java/de/dynamicfiles/projects/gradle/plugins/javafx/tests/exampleprojects/ExampleProjectTest.java // public static void readVersionString() throws IOException { // List<String> versionFileLines = Files.readAllLines(new File("version.gradle").toPath()); // versionFileLines.forEach(line -> { // if( line.contains("currentPluginVersion") ){ // versionString = line.replace("currentPluginVersion", "").replace("=", "").replace("'", "").trim(); // } // }); // } // Path: src/test/java/de/dynamicfiles/projects/gradle/plugins/javafx/tests/exampleprojects/AdditionalApplicationFiles.java import static de.dynamicfiles.projects.gradle.plugins.javafx.tests.exampleprojects.ExampleProjectTest.GRADLE_VERSIONS_TO_TEST_AGAINST; import static de.dynamicfiles.projects.gradle.plugins.javafx.tests.exampleprojects.ExampleProjectTest.readVersionString; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import org.gradle.testkit.runner.BuildResult; import org.gradle.testkit.runner.GradleRunner; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /* * Copyright 2016 Danny Althoff * * 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 de.dynamicfiles.projects.gradle.plugins.javafx.tests.exampleprojects; /** * * @author Danny Althoff */ public class AdditionalApplicationFiles extends ExampleProjectTest { @BeforeClass public static void readVersion() throws IOException {
readVersionString();
FibreFoX/javafx-gradle-plugin
src/test/java/de/dynamicfiles/projects/gradle/plugins/javafx/tests/exampleprojects/AdditionalApplicationFiles.java
// Path: src/test/java/de/dynamicfiles/projects/gradle/plugins/javafx/tests/exampleprojects/ExampleProjectTest.java // protected static final List<String> GRADLE_VERSIONS_TO_TEST_AGAINST = new ArrayList<>(); // // Path: src/test/java/de/dynamicfiles/projects/gradle/plugins/javafx/tests/exampleprojects/ExampleProjectTest.java // public static void readVersionString() throws IOException { // List<String> versionFileLines = Files.readAllLines(new File("version.gradle").toPath()); // versionFileLines.forEach(line -> { // if( line.contains("currentPluginVersion") ){ // versionString = line.replace("currentPluginVersion", "").replace("=", "").replace("'", "").trim(); // } // }); // }
import static de.dynamicfiles.projects.gradle.plugins.javafx.tests.exampleprojects.ExampleProjectTest.GRADLE_VERSIONS_TO_TEST_AGAINST; import static de.dynamicfiles.projects.gradle.plugins.javafx.tests.exampleprojects.ExampleProjectTest.readVersionString; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import org.gradle.testkit.runner.BuildResult; import org.gradle.testkit.runner.GradleRunner; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test;
/* * Copyright 2016 Danny Althoff * * 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 de.dynamicfiles.projects.gradle.plugins.javafx.tests.exampleprojects; /** * * @author Danny Althoff */ public class AdditionalApplicationFiles extends ExampleProjectTest { @BeforeClass public static void readVersion() throws IOException { readVersionString(); } @Test public void additionalApplicationFilesJfxNative() {
// Path: src/test/java/de/dynamicfiles/projects/gradle/plugins/javafx/tests/exampleprojects/ExampleProjectTest.java // protected static final List<String> GRADLE_VERSIONS_TO_TEST_AGAINST = new ArrayList<>(); // // Path: src/test/java/de/dynamicfiles/projects/gradle/plugins/javafx/tests/exampleprojects/ExampleProjectTest.java // public static void readVersionString() throws IOException { // List<String> versionFileLines = Files.readAllLines(new File("version.gradle").toPath()); // versionFileLines.forEach(line -> { // if( line.contains("currentPluginVersion") ){ // versionString = line.replace("currentPluginVersion", "").replace("=", "").replace("'", "").trim(); // } // }); // } // Path: src/test/java/de/dynamicfiles/projects/gradle/plugins/javafx/tests/exampleprojects/AdditionalApplicationFiles.java import static de.dynamicfiles.projects.gradle.plugins.javafx.tests.exampleprojects.ExampleProjectTest.GRADLE_VERSIONS_TO_TEST_AGAINST; import static de.dynamicfiles.projects.gradle.plugins.javafx.tests.exampleprojects.ExampleProjectTest.readVersionString; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import org.gradle.testkit.runner.BuildResult; import org.gradle.testkit.runner.GradleRunner; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /* * Copyright 2016 Danny Althoff * * 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 de.dynamicfiles.projects.gradle.plugins.javafx.tests.exampleprojects; /** * * @author Danny Althoff */ public class AdditionalApplicationFiles extends ExampleProjectTest { @BeforeClass public static void readVersion() throws IOException { readVersionString(); } @Test public void additionalApplicationFilesJfxNative() {
GRADLE_VERSIONS_TO_TEST_AGAINST.forEach(gradleVersion -> {
FibreFoX/javafx-gradle-plugin
src/main/java/de/dynamicfiles/projects/gradle/plugins/javafx/tasks/internal/MonkeyPatcher.java
// Path: src/main/java/de/dynamicfiles/projects/gradle/plugins/javafx/JavaFXGradlePlugin.java // public static final String ANT_JAVAFX_JAR_FILENAME = "ant-javafx.jar";
import static de.dynamicfiles.projects.gradle.plugins.javafx.JavaFXGradlePlugin.ANT_JAVAFX_JAR_FILENAME; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.util.concurrent.atomic.AtomicBoolean; import java.util.jar.JarFile; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Handle; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.Label;
/* * Copyright 2016 Danny Althoff * * 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 de.dynamicfiles.projects.gradle.plugins.javafx.tasks.internal; /** * * @author Danny Althoff */ public class MonkeyPatcher { private static final String METHOD_TO_MONKEY_PATCH = "copyMSVCDLLs"; private static final String METHOD_SIGNATURE_TO_MONKEY_PATCH = "(Ljava/io/File;Ljava/io/File;)V"; private static final String FAULTY_CLASSFILE_TO_MONKEY_PATCH = "com/oracle/tools/packager/windows/WinAppBundler.class"; public static final String WORKAROUND_DIRECTORY_NAME = "javafx-gradle-plugin-workaround"; public static URL getPatchedJfxAntJar() throws MalformedURLException {
// Path: src/main/java/de/dynamicfiles/projects/gradle/plugins/javafx/JavaFXGradlePlugin.java // public static final String ANT_JAVAFX_JAR_FILENAME = "ant-javafx.jar"; // Path: src/main/java/de/dynamicfiles/projects/gradle/plugins/javafx/tasks/internal/MonkeyPatcher.java import static de.dynamicfiles.projects.gradle.plugins.javafx.JavaFXGradlePlugin.ANT_JAVAFX_JAR_FILENAME; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.util.concurrent.atomic.AtomicBoolean; import java.util.jar.JarFile; import java.util.logging.Level; import java.util.logging.Logger; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Handle; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.Label; /* * Copyright 2016 Danny Althoff * * 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 de.dynamicfiles.projects.gradle.plugins.javafx.tasks.internal; /** * * @author Danny Althoff */ public class MonkeyPatcher { private static final String METHOD_TO_MONKEY_PATCH = "copyMSVCDLLs"; private static final String METHOD_SIGNATURE_TO_MONKEY_PATCH = "(Ljava/io/File;Ljava/io/File;)V"; private static final String FAULTY_CLASSFILE_TO_MONKEY_PATCH = "com/oracle/tools/packager/windows/WinAppBundler.class"; public static final String WORKAROUND_DIRECTORY_NAME = "javafx-gradle-plugin-workaround"; public static URL getPatchedJfxAntJar() throws MalformedURLException {
String jfxAntJarPath = "/../lib/" + ANT_JAVAFX_JAR_FILENAME;
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/emailvalidations/models/ValidationEntryListingOptions.java
// Path: src/main/java/com/verifalia/api/common/ListingOptions.java // @Getter // @SuperBuilder // @NoArgsConstructor // public class ListingOptions { // /** // * The maximum number of items to return with a listing request. The Verifalia API may choose to override the specified // * limit if it is either too small or too big. Note: a single listing operation may automatically perform different // * listing requests to the Verifalia API: this value limits the number of items returned by *each* API request, not // * the overall total number of returned items. // */ // private Integer limit; // // /** // * The direction of the listing. // */ // @Builder.Default // private Direction direction = Direction.Forward; // // public void setLimit(final Integer limit) { // if (limit != null && limit < 0) { // throw new IllegalArgumentException("Limit must be 0 (meaning no limit will be enforced) or greater."); // } // // this.limit = limit; // } // // public void setDirection(@NonNull final Direction direction) { // this.direction = direction; // } // } // // Path: src/main/java/com/verifalia/api/common/filters/SetFilterPredicate.java // public abstract class SetFilterPredicate<T> extends FilterPredicate { // }
import com.verifalia.api.common.ListingOptions; import com.verifalia.api.common.filters.SetFilterPredicate; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.SuperBuilder;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Provides options for a listing of validation entries. */ @Getter @Setter @ToString @SuperBuilder @NoArgsConstructor
// Path: src/main/java/com/verifalia/api/common/ListingOptions.java // @Getter // @SuperBuilder // @NoArgsConstructor // public class ListingOptions { // /** // * The maximum number of items to return with a listing request. The Verifalia API may choose to override the specified // * limit if it is either too small or too big. Note: a single listing operation may automatically perform different // * listing requests to the Verifalia API: this value limits the number of items returned by *each* API request, not // * the overall total number of returned items. // */ // private Integer limit; // // /** // * The direction of the listing. // */ // @Builder.Default // private Direction direction = Direction.Forward; // // public void setLimit(final Integer limit) { // if (limit != null && limit < 0) { // throw new IllegalArgumentException("Limit must be 0 (meaning no limit will be enforced) or greater."); // } // // this.limit = limit; // } // // public void setDirection(@NonNull final Direction direction) { // this.direction = direction; // } // } // // Path: src/main/java/com/verifalia/api/common/filters/SetFilterPredicate.java // public abstract class SetFilterPredicate<T> extends FilterPredicate { // } // Path: src/main/java/com/verifalia/api/emailvalidations/models/ValidationEntryListingOptions.java import com.verifalia.api.common.ListingOptions; import com.verifalia.api.common.filters.SetFilterPredicate; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.SuperBuilder; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Provides options for a listing of validation entries. */ @Getter @Setter @ToString @SuperBuilder @NoArgsConstructor
public class ValidationEntryListingOptions extends ListingOptions {
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/emailvalidations/models/ValidationEntryListingOptions.java
// Path: src/main/java/com/verifalia/api/common/ListingOptions.java // @Getter // @SuperBuilder // @NoArgsConstructor // public class ListingOptions { // /** // * The maximum number of items to return with a listing request. The Verifalia API may choose to override the specified // * limit if it is either too small or too big. Note: a single listing operation may automatically perform different // * listing requests to the Verifalia API: this value limits the number of items returned by *each* API request, not // * the overall total number of returned items. // */ // private Integer limit; // // /** // * The direction of the listing. // */ // @Builder.Default // private Direction direction = Direction.Forward; // // public void setLimit(final Integer limit) { // if (limit != null && limit < 0) { // throw new IllegalArgumentException("Limit must be 0 (meaning no limit will be enforced) or greater."); // } // // this.limit = limit; // } // // public void setDirection(@NonNull final Direction direction) { // this.direction = direction; // } // } // // Path: src/main/java/com/verifalia/api/common/filters/SetFilterPredicate.java // public abstract class SetFilterPredicate<T> extends FilterPredicate { // }
import com.verifalia.api.common.ListingOptions; import com.verifalia.api.common.filters.SetFilterPredicate; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.SuperBuilder;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Provides options for a listing of validation entries. */ @Getter @Setter @ToString @SuperBuilder @NoArgsConstructor public class ValidationEntryListingOptions extends ListingOptions { /** * A predicate which allows to filter the validation entries by their statuses. */
// Path: src/main/java/com/verifalia/api/common/ListingOptions.java // @Getter // @SuperBuilder // @NoArgsConstructor // public class ListingOptions { // /** // * The maximum number of items to return with a listing request. The Verifalia API may choose to override the specified // * limit if it is either too small or too big. Note: a single listing operation may automatically perform different // * listing requests to the Verifalia API: this value limits the number of items returned by *each* API request, not // * the overall total number of returned items. // */ // private Integer limit; // // /** // * The direction of the listing. // */ // @Builder.Default // private Direction direction = Direction.Forward; // // public void setLimit(final Integer limit) { // if (limit != null && limit < 0) { // throw new IllegalArgumentException("Limit must be 0 (meaning no limit will be enforced) or greater."); // } // // this.limit = limit; // } // // public void setDirection(@NonNull final Direction direction) { // this.direction = direction; // } // } // // Path: src/main/java/com/verifalia/api/common/filters/SetFilterPredicate.java // public abstract class SetFilterPredicate<T> extends FilterPredicate { // } // Path: src/main/java/com/verifalia/api/emailvalidations/models/ValidationEntryListingOptions.java import com.verifalia.api.common.ListingOptions; import com.verifalia.api.common.filters.SetFilterPredicate; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.SuperBuilder; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Provides options for a listing of validation entries. */ @Getter @Setter @ToString @SuperBuilder @NoArgsConstructor public class ValidationEntryListingOptions extends ListingOptions { /** * A predicate which allows to filter the validation entries by their statuses. */
private SetFilterPredicate<ValidationEntryStatus> statuses;
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/emailvalidations/models/FileValidationRequest.java
// Path: src/main/java/com/verifalia/api/emailvalidations/serialization/LineEndingModeSerializer.java // public class LineEndingModeSerializer extends JsonSerializer<LineEndingMode> { // @Override // public void serialize(LineEndingMode value, JsonGenerator jgen, SerializerProvider provider) throws IOException { // if (value == null || value == LineEndingMode.Auto) { // jgen.writeNull(); // } else { // jgen.writeString(value.toString()); // } // } // }
import com.verifalia.api.emailvalidations.serialization.LineEndingModeSerializer; import lombok.*; import org.apache.http.entity.ContentType; import org.codehaus.jackson.annotate.JsonIgnore; import org.codehaus.jackson.map.annotate.JsonSerialize; import java.io.*; import static java.util.Objects.nonNull;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Represents an email validation request through a file import, to be submitted against the Verifalia API. * Verifalia offers support for the following file types: * - plain text files (.txt), with one email address per line (MIME type: text/plain) * - comma-separated values (.csv), tab-separated values (.tsv) and other delimiter-separated values files (MIME * types: text/csv and text/tab-separated-values) * - Microsoft Excel spreadsheets - .xls and .xlsx - (MIME types: application/vnd.ms-excel and * application/vnd.openxmlformats-officedocument.spreadsheetml.sheet). */ @Getter @Setter @ToString @AllArgsConstructor @Builder public class FileValidationRequest extends AbstractValidationRequest { /** * An {@link InputStream} (a {@link java.io.FileInputStream}, for example) containing the email addresses to validate. */ @NonNull @JsonIgnore private InputStream inputStream; /** * The {@link ContentType} of the provided input file. */ @NonNull @JsonIgnore private ContentType contentType; /** * An optional {@link Integer} with the zero-based index of the first row to import and process. If not specified, Verifalia * will start processing files from the first (0) row. */ private Integer startingRow; /** * An optional {@link Integer} with the zero-based index of the last row to import and process. If not specified, Verifalia * will process rows until the end of the file. */ private Integer endingRow; /** * An optional {@link Integer} with the zero-based index of the column to import; applies to comma-separated (.csv), * tab-separated (.tsv) and other delimiter-separated values files, and Excel files. If not specified, Verifalia will * use the first (0) column. */ private Integer column; /** * An optional {@link Integer} with the zero-based index of the worksheet to import; applies to Excel files only. * If not specified, Verifalia will use the first (0) worksheet. */ private Integer sheet; /** * Allows to specify the line ending sequence of the provided file; applies to plain-text files, comma-separated (.csv), * tab-separated (.tsv) and other delimiter-separated values files. */
// Path: src/main/java/com/verifalia/api/emailvalidations/serialization/LineEndingModeSerializer.java // public class LineEndingModeSerializer extends JsonSerializer<LineEndingMode> { // @Override // public void serialize(LineEndingMode value, JsonGenerator jgen, SerializerProvider provider) throws IOException { // if (value == null || value == LineEndingMode.Auto) { // jgen.writeNull(); // } else { // jgen.writeString(value.toString()); // } // } // } // Path: src/main/java/com/verifalia/api/emailvalidations/models/FileValidationRequest.java import com.verifalia.api.emailvalidations.serialization.LineEndingModeSerializer; import lombok.*; import org.apache.http.entity.ContentType; import org.codehaus.jackson.annotate.JsonIgnore; import org.codehaus.jackson.map.annotate.JsonSerialize; import java.io.*; import static java.util.Objects.nonNull; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Represents an email validation request through a file import, to be submitted against the Verifalia API. * Verifalia offers support for the following file types: * - plain text files (.txt), with one email address per line (MIME type: text/plain) * - comma-separated values (.csv), tab-separated values (.tsv) and other delimiter-separated values files (MIME * types: text/csv and text/tab-separated-values) * - Microsoft Excel spreadsheets - .xls and .xlsx - (MIME types: application/vnd.ms-excel and * application/vnd.openxmlformats-officedocument.spreadsheetml.sheet). */ @Getter @Setter @ToString @AllArgsConstructor @Builder public class FileValidationRequest extends AbstractValidationRequest { /** * An {@link InputStream} (a {@link java.io.FileInputStream}, for example) containing the email addresses to validate. */ @NonNull @JsonIgnore private InputStream inputStream; /** * The {@link ContentType} of the provided input file. */ @NonNull @JsonIgnore private ContentType contentType; /** * An optional {@link Integer} with the zero-based index of the first row to import and process. If not specified, Verifalia * will start processing files from the first (0) row. */ private Integer startingRow; /** * An optional {@link Integer} with the zero-based index of the last row to import and process. If not specified, Verifalia * will process rows until the end of the file. */ private Integer endingRow; /** * An optional {@link Integer} with the zero-based index of the column to import; applies to comma-separated (.csv), * tab-separated (.tsv) and other delimiter-separated values files, and Excel files. If not specified, Verifalia will * use the first (0) column. */ private Integer column; /** * An optional {@link Integer} with the zero-based index of the worksheet to import; applies to Excel files only. * If not specified, Verifalia will use the first (0) worksheet. */ private Integer sheet; /** * Allows to specify the line ending sequence of the provided file; applies to plain-text files, comma-separated (.csv), * tab-separated (.tsv) and other delimiter-separated values files. */
@JsonSerialize(using = LineEndingModeSerializer.class, include = JsonSerialize.Inclusion.NON_NULL)
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/common/filters/DateBetweenPredicate.java
// Path: src/main/java/com/verifalia/api/common/Utils.java // public class Utils { // /** // * Generates URI for HTTP request. // * // * @param paramMap Map with variable names and values to be passed when making URI for http request. // * @return URI URI for HTTP request based on the input parameters. // */ // public static URI getHttpUri(Map<String, String> paramMap) { // URIBuilder builder = new URIBuilder(); // try { // if (nonNull(paramMap) && paramMap.size() > 0) { // Iterator<String> paramMapIter = paramMap.keySet().iterator(); // while (paramMapIter.hasNext()) { // String paramKey = paramMapIter.next(); // String paramValue = paramMap.get(paramKey); // if (!StringUtils.isEmpty(paramValue)) { // builder.setParameter(paramKey, paramValue); // } // } // } // // return builder.build(); // } catch (URISyntaxException e) { // return null; // } // } // // /** // * Converts local date to string based on the input format. // * // * @param localDate LocalDate object which needs to be formatted. // * @param dateFormat Date format in which the local date object needs to be formatted. // * @return String Converted local date to string as per the input format. // */ // public static String convertLocalDateToString(LocalDate localDate, String dateFormat) { // if (nonNull(localDate)) { // return localDate.format(DateTimeFormatter.ofPattern(dateFormat)); // } // return StringUtils.EMPTY; // } // }
import com.verifalia.api.common.Utils; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import java.time.LocalDate; import java.util.ArrayList;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.common.filters; /** * A filter predicate used to filter dates between two optional values. */ @Getter @Setter public class DateBetweenPredicate extends DateFilterPredicate { /** * The minimum date to be included in the filter. */ private LocalDate since; /** * The maximum date to be included in the filter. */ private LocalDate until; /** * Initializes a filter predicate used to filter dates between two optional values. * * @param since The minimum date to be included in the filter. * @param until The maximum date to be included in the filter. */ public DateBetweenPredicate(final LocalDate since, final LocalDate until) { if (since == null && until == null) { throw new IllegalArgumentException("Both since and until are null."); } if (since != null && until != null) { if (since.isAfter(until)) { throw new IllegalArgumentException("Invalid predicate: since is after until."); } } this.setSince(since); this.setUntil(until); } @Override public FilterPredicateFragment[] serialize(@NonNull final String fieldName) { ArrayList<FilterPredicateFragment> result = new ArrayList<>(); if (this.getSince() != null) {
// Path: src/main/java/com/verifalia/api/common/Utils.java // public class Utils { // /** // * Generates URI for HTTP request. // * // * @param paramMap Map with variable names and values to be passed when making URI for http request. // * @return URI URI for HTTP request based on the input parameters. // */ // public static URI getHttpUri(Map<String, String> paramMap) { // URIBuilder builder = new URIBuilder(); // try { // if (nonNull(paramMap) && paramMap.size() > 0) { // Iterator<String> paramMapIter = paramMap.keySet().iterator(); // while (paramMapIter.hasNext()) { // String paramKey = paramMapIter.next(); // String paramValue = paramMap.get(paramKey); // if (!StringUtils.isEmpty(paramValue)) { // builder.setParameter(paramKey, paramValue); // } // } // } // // return builder.build(); // } catch (URISyntaxException e) { // return null; // } // } // // /** // * Converts local date to string based on the input format. // * // * @param localDate LocalDate object which needs to be formatted. // * @param dateFormat Date format in which the local date object needs to be formatted. // * @return String Converted local date to string as per the input format. // */ // public static String convertLocalDateToString(LocalDate localDate, String dateFormat) { // if (nonNull(localDate)) { // return localDate.format(DateTimeFormatter.ofPattern(dateFormat)); // } // return StringUtils.EMPTY; // } // } // Path: src/main/java/com/verifalia/api/common/filters/DateBetweenPredicate.java import com.verifalia.api.common.Utils; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import java.time.LocalDate; import java.util.ArrayList; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.common.filters; /** * A filter predicate used to filter dates between two optional values. */ @Getter @Setter public class DateBetweenPredicate extends DateFilterPredicate { /** * The minimum date to be included in the filter. */ private LocalDate since; /** * The maximum date to be included in the filter. */ private LocalDate until; /** * Initializes a filter predicate used to filter dates between two optional values. * * @param since The minimum date to be included in the filter. * @param until The maximum date to be included in the filter. */ public DateBetweenPredicate(final LocalDate since, final LocalDate until) { if (since == null && until == null) { throw new IllegalArgumentException("Both since and until are null."); } if (since != null && until != null) { if (since.isAfter(until)) { throw new IllegalArgumentException("Invalid predicate: since is after until."); } } this.setSince(since); this.setUntil(until); } @Override public FilterPredicateFragment[] serialize(@NonNull final String fieldName) { ArrayList<FilterPredicateFragment> result = new ArrayList<>(); if (this.getSince() != null) {
result.add(new FilterPredicateFragment(fieldName + ":since", Utils.convertLocalDateToString(this.getSince(), "yyyy-MM-dd")));
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/credits/models/DailyUsageListingOptions.java
// Path: src/main/java/com/verifalia/api/common/ListingOptions.java // @Getter // @SuperBuilder // @NoArgsConstructor // public class ListingOptions { // /** // * The maximum number of items to return with a listing request. The Verifalia API may choose to override the specified // * limit if it is either too small or too big. Note: a single listing operation may automatically perform different // * listing requests to the Verifalia API: this value limits the number of items returned by *each* API request, not // * the overall total number of returned items. // */ // private Integer limit; // // /** // * The direction of the listing. // */ // @Builder.Default // private Direction direction = Direction.Forward; // // public void setLimit(final Integer limit) { // if (limit != null && limit < 0) { // throw new IllegalArgumentException("Limit must be 0 (meaning no limit will be enforced) or greater."); // } // // this.limit = limit; // } // // public void setDirection(@NonNull final Direction direction) { // this.direction = direction; // } // } // // Path: src/main/java/com/verifalia/api/common/filters/DateFilterPredicate.java // public abstract class DateFilterPredicate extends FilterPredicate { // }
import com.verifalia.api.common.ListingOptions; import com.verifalia.api.common.filters.DateFilterPredicate; import lombok.Getter; import lombok.Setter; import lombok.ToString; import lombok.experimental.SuperBuilder;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.credits.models; /** * The options for a daily usage listing operation against the Verifalia API. */ @Getter @Setter @ToString @SuperBuilder
// Path: src/main/java/com/verifalia/api/common/ListingOptions.java // @Getter // @SuperBuilder // @NoArgsConstructor // public class ListingOptions { // /** // * The maximum number of items to return with a listing request. The Verifalia API may choose to override the specified // * limit if it is either too small or too big. Note: a single listing operation may automatically perform different // * listing requests to the Verifalia API: this value limits the number of items returned by *each* API request, not // * the overall total number of returned items. // */ // private Integer limit; // // /** // * The direction of the listing. // */ // @Builder.Default // private Direction direction = Direction.Forward; // // public void setLimit(final Integer limit) { // if (limit != null && limit < 0) { // throw new IllegalArgumentException("Limit must be 0 (meaning no limit will be enforced) or greater."); // } // // this.limit = limit; // } // // public void setDirection(@NonNull final Direction direction) { // this.direction = direction; // } // } // // Path: src/main/java/com/verifalia/api/common/filters/DateFilterPredicate.java // public abstract class DateFilterPredicate extends FilterPredicate { // } // Path: src/main/java/com/verifalia/api/credits/models/DailyUsageListingOptions.java import com.verifalia.api.common.ListingOptions; import com.verifalia.api.common.filters.DateFilterPredicate; import lombok.Getter; import lombok.Setter; import lombok.ToString; import lombok.experimental.SuperBuilder; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.credits.models; /** * The options for a daily usage listing operation against the Verifalia API. */ @Getter @Setter @ToString @SuperBuilder
public class DailyUsageListingOptions extends ListingOptions {
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/credits/models/DailyUsageListingOptions.java
// Path: src/main/java/com/verifalia/api/common/ListingOptions.java // @Getter // @SuperBuilder // @NoArgsConstructor // public class ListingOptions { // /** // * The maximum number of items to return with a listing request. The Verifalia API may choose to override the specified // * limit if it is either too small or too big. Note: a single listing operation may automatically perform different // * listing requests to the Verifalia API: this value limits the number of items returned by *each* API request, not // * the overall total number of returned items. // */ // private Integer limit; // // /** // * The direction of the listing. // */ // @Builder.Default // private Direction direction = Direction.Forward; // // public void setLimit(final Integer limit) { // if (limit != null && limit < 0) { // throw new IllegalArgumentException("Limit must be 0 (meaning no limit will be enforced) or greater."); // } // // this.limit = limit; // } // // public void setDirection(@NonNull final Direction direction) { // this.direction = direction; // } // } // // Path: src/main/java/com/verifalia/api/common/filters/DateFilterPredicate.java // public abstract class DateFilterPredicate extends FilterPredicate { // }
import com.verifalia.api.common.ListingOptions; import com.verifalia.api.common.filters.DateFilterPredicate; import lombok.Getter; import lombok.Setter; import lombok.ToString; import lombok.experimental.SuperBuilder;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.credits.models; /** * The options for a daily usage listing operation against the Verifalia API. */ @Getter @Setter @ToString @SuperBuilder public class DailyUsageListingOptions extends ListingOptions { /** * If set, apply a filter against the daily usage dates, before returning their usage records. Use either * <tt>DateEqualityPredicate</tt> to specify an exact date to match or <tt>DateBetweenPredicate</tt> to set a * range of dates. */
// Path: src/main/java/com/verifalia/api/common/ListingOptions.java // @Getter // @SuperBuilder // @NoArgsConstructor // public class ListingOptions { // /** // * The maximum number of items to return with a listing request. The Verifalia API may choose to override the specified // * limit if it is either too small or too big. Note: a single listing operation may automatically perform different // * listing requests to the Verifalia API: this value limits the number of items returned by *each* API request, not // * the overall total number of returned items. // */ // private Integer limit; // // /** // * The direction of the listing. // */ // @Builder.Default // private Direction direction = Direction.Forward; // // public void setLimit(final Integer limit) { // if (limit != null && limit < 0) { // throw new IllegalArgumentException("Limit must be 0 (meaning no limit will be enforced) or greater."); // } // // this.limit = limit; // } // // public void setDirection(@NonNull final Direction direction) { // this.direction = direction; // } // } // // Path: src/main/java/com/verifalia/api/common/filters/DateFilterPredicate.java // public abstract class DateFilterPredicate extends FilterPredicate { // } // Path: src/main/java/com/verifalia/api/credits/models/DailyUsageListingOptions.java import com.verifalia.api.common.ListingOptions; import com.verifalia.api.common.filters.DateFilterPredicate; import lombok.Getter; import lombok.Setter; import lombok.ToString; import lombok.experimental.SuperBuilder; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.credits.models; /** * The options for a daily usage listing operation against the Verifalia API. */ @Getter @Setter @ToString @SuperBuilder public class DailyUsageListingOptions extends ListingOptions { /** * If set, apply a filter against the daily usage dates, before returning their usage records. Use either * <tt>DateEqualityPredicate</tt> to specify an exact date to match or <tt>DateBetweenPredicate</tt> to set a * range of dates. */
private DateFilterPredicate dateFilter;
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/rest/RestResponse.java
// Path: src/main/java/com/verifalia/api/exceptions/VerifaliaException.java // public class VerifaliaException extends Exception { // private RestResponse response; // // public VerifaliaException(@NonNull final RestResponse response) { // super(response.getStatusCode() + ": " + response.readAsString()); // this.response = response; // } // // public VerifaliaException(String errorMessage) { // super(errorMessage); // } // // public VerifaliaException(String message, Throwable cause) { // super(message, cause); // } // }
import com.verifalia.api.exceptions.VerifaliaException; import lombok.Getter; import lombok.NonNull; import org.apache.http.HttpEntity; import org.apache.http.entity.ContentType; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.map.DeserializationConfig; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import java.io.IOException; import java.nio.charset.Charset;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.rest; /** * Represents REST service response. */ public class RestResponse { private final ContentType contentType; /** * HTTP response code */ @Getter private final int statusCode; /** * Response data */ private final byte[] data; /** * Creates new object * * @param statusCode Status code * @param result Result string * @param responseDataClass Class in which the response data needs to be mapped * @throws IOException * @throws JsonMappingException * @throws JsonParseException */ public RestResponse(final int statusCode, final HttpEntity entity)
// Path: src/main/java/com/verifalia/api/exceptions/VerifaliaException.java // public class VerifaliaException extends Exception { // private RestResponse response; // // public VerifaliaException(@NonNull final RestResponse response) { // super(response.getStatusCode() + ": " + response.readAsString()); // this.response = response; // } // // public VerifaliaException(String errorMessage) { // super(errorMessage); // } // // public VerifaliaException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/com/verifalia/api/rest/RestResponse.java import com.verifalia.api.exceptions.VerifaliaException; import lombok.Getter; import lombok.NonNull; import org.apache.http.HttpEntity; import org.apache.http.entity.ContentType; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.map.DeserializationConfig; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import java.io.IOException; import java.nio.charset.Charset; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.rest; /** * Represents REST service response. */ public class RestResponse { private final ContentType contentType; /** * HTTP response code */ @Getter private final int statusCode; /** * Response data */ private final byte[] data; /** * Creates new object * * @param statusCode Status code * @param result Result string * @param responseDataClass Class in which the response data needs to be mapped * @throws IOException * @throws JsonMappingException * @throws JsonParseException */ public RestResponse(final int statusCode, final HttpEntity entity)
throws VerifaliaException {
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/emailvalidations/models/ValidationEntry.java
// Path: src/main/java/com/verifalia/api/emailvalidations/serialization/QualityLevelNameDeserializer.java // public class QualityLevelNameDeserializer extends JsonDeserializer<QualityLevelName> { // @Override // public QualityLevelName deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // String qualityLevelNameString = jp.getText(); // // if (qualityLevelNameString == null) { // return null; // } // // return new QualityLevelName(qualityLevelNameString); // } // } // // Path: src/main/java/com/verifalia/api/emailvalidations/serialization/ValidationEntryStatusDeserializer.java // public class ValidationEntryStatusDeserializer extends JsonDeserializer<ValidationEntryStatus> { // @Override // public ValidationEntryStatus deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { // String validationEntryStatusString = jp.getText(); // // if (validationEntryStatusString != null) { // for (ValidationEntryStatus candidate : ValidationEntryStatus.values()) { // if (candidate.name().equalsIgnoreCase(validationEntryStatusString)) { // return candidate; // } // } // } // // return ValidationEntryStatus.Unknown; // } // }
import com.verifalia.api.emailvalidations.serialization.QualityLevelNameDeserializer; import com.verifalia.api.emailvalidations.serialization.ValidationEntryStatusDeserializer; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.map.annotate.JsonDeserialize; import java.util.Date; import static java.util.Objects.nonNull;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Represents a single validated entry within a <tt>Validation</tt>. */ @Getter @Setter @ToString @JsonIgnoreProperties(ignoreUnknown = true) public class ValidationEntry { /** * The index of this entry within its <tt>Validation</tt> container. This property is mostly useful in the event * the API returns a filtered view of the items. */ private Integer index; /** * The input string being validated. */ private String inputData; /** * The <tt>ValidationEntryClassification</tt> for the status of this email address. */ private ValidationEntryClassification classification; /** * The validation status for this entry. */
// Path: src/main/java/com/verifalia/api/emailvalidations/serialization/QualityLevelNameDeserializer.java // public class QualityLevelNameDeserializer extends JsonDeserializer<QualityLevelName> { // @Override // public QualityLevelName deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // String qualityLevelNameString = jp.getText(); // // if (qualityLevelNameString == null) { // return null; // } // // return new QualityLevelName(qualityLevelNameString); // } // } // // Path: src/main/java/com/verifalia/api/emailvalidations/serialization/ValidationEntryStatusDeserializer.java // public class ValidationEntryStatusDeserializer extends JsonDeserializer<ValidationEntryStatus> { // @Override // public ValidationEntryStatus deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { // String validationEntryStatusString = jp.getText(); // // if (validationEntryStatusString != null) { // for (ValidationEntryStatus candidate : ValidationEntryStatus.values()) { // if (candidate.name().equalsIgnoreCase(validationEntryStatusString)) { // return candidate; // } // } // } // // return ValidationEntryStatus.Unknown; // } // } // Path: src/main/java/com/verifalia/api/emailvalidations/models/ValidationEntry.java import com.verifalia.api.emailvalidations.serialization.QualityLevelNameDeserializer; import com.verifalia.api.emailvalidations.serialization.ValidationEntryStatusDeserializer; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.map.annotate.JsonDeserialize; import java.util.Date; import static java.util.Objects.nonNull; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Represents a single validated entry within a <tt>Validation</tt>. */ @Getter @Setter @ToString @JsonIgnoreProperties(ignoreUnknown = true) public class ValidationEntry { /** * The index of this entry within its <tt>Validation</tt> container. This property is mostly useful in the event * the API returns a filtered view of the items. */ private Integer index; /** * The input string being validated. */ private String inputData; /** * The <tt>ValidationEntryClassification</tt> for the status of this email address. */ private ValidationEntryClassification classification; /** * The validation status for this entry. */
@JsonDeserialize(using = ValidationEntryStatusDeserializer.class)
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/credits/models/Balance.java
// Path: src/main/java/com/verifalia/api/common/serialization/DurationDeserializer.java // public class DurationDeserializer extends JsonDeserializer<Duration> { // @Override // public Duration deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { // String durationString = jsonParser.getText(); // // if (durationString == null) { // return null; // } // // return parseDuration(durationString); // } // // private Duration parseDuration(@NonNull String inputData) { // inputData = inputData.trim(); // // // Parse the eventual days information // // String[] dayFields = inputData.split("\\."); // // if (dayFields.length > 2) { // throw new IllegalArgumentException(); // } // // int days = 0; // String timeData = inputData; // // if (dayFields.length == 2) { // days = Integer.parseInt(dayFields[0]); // timeData = dayFields[1]; // } // // // Parse the time information // // String[] timeFields = timeData.split(":"); // // if (timeFields.length != 3) { // throw new IllegalArgumentException(); // } // // return Duration.ofSeconds((days * 24 * 60 * 60) + // (Integer.parseInt(timeFields[0]) * 60 * 60) + // (Integer.parseInt(timeFields[1]) * 60) + // (Integer.parseInt(timeFields[2]))); // } // }
import com.verifalia.api.common.serialization.DurationDeserializer; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.map.annotate.JsonDeserialize; import java.time.Duration;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.credits.models; /** * Represents the credits balance for the Verifalia account.. */ @Getter @Setter @ToString @JsonIgnoreProperties(ignoreUnknown = true) public class Balance { /** * The number of credit packs (that is, the non-expiring credits) available for the account. * Visit https://verifalia.com/client-area#/credits/add to add credit packs to your Verifalia account. */ private Double creditPacks; /** * The number of free daily credits of the account. * Free daily credits depend on the plan of your Verifalia account; visit https://verifalia.com/client-area#/account/change-plan * to change your plan. */ private Double freeCredits; /** * The time required for the free daily credits to reset. */
// Path: src/main/java/com/verifalia/api/common/serialization/DurationDeserializer.java // public class DurationDeserializer extends JsonDeserializer<Duration> { // @Override // public Duration deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { // String durationString = jsonParser.getText(); // // if (durationString == null) { // return null; // } // // return parseDuration(durationString); // } // // private Duration parseDuration(@NonNull String inputData) { // inputData = inputData.trim(); // // // Parse the eventual days information // // String[] dayFields = inputData.split("\\."); // // if (dayFields.length > 2) { // throw new IllegalArgumentException(); // } // // int days = 0; // String timeData = inputData; // // if (dayFields.length == 2) { // days = Integer.parseInt(dayFields[0]); // timeData = dayFields[1]; // } // // // Parse the time information // // String[] timeFields = timeData.split(":"); // // if (timeFields.length != 3) { // throw new IllegalArgumentException(); // } // // return Duration.ofSeconds((days * 24 * 60 * 60) + // (Integer.parseInt(timeFields[0]) * 60 * 60) + // (Integer.parseInt(timeFields[1]) * 60) + // (Integer.parseInt(timeFields[2]))); // } // } // Path: src/main/java/com/verifalia/api/credits/models/Balance.java import com.verifalia.api.common.serialization.DurationDeserializer; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.map.annotate.JsonDeserialize; import java.time.Duration; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.credits.models; /** * Represents the credits balance for the Verifalia account.. */ @Getter @Setter @ToString @JsonIgnoreProperties(ignoreUnknown = true) public class Balance { /** * The number of credit packs (that is, the non-expiring credits) available for the account. * Visit https://verifalia.com/client-area#/credits/add to add credit packs to your Verifalia account. */ private Double creditPacks; /** * The number of free daily credits of the account. * Free daily credits depend on the plan of your Verifalia account; visit https://verifalia.com/client-area#/account/change-plan * to change your plan. */ private Double freeCredits; /** * The time required for the free daily credits to reset. */
@JsonDeserialize(using = DurationDeserializer.class)
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/credits/models/DailyUsage.java
// Path: src/main/java/com/verifalia/api/common/serialization/DateDeserializer.java // public class DateDeserializer extends JsonDeserializer<LocalDate> { // private static LocalDate convertStringToLocalDate(@NonNull final String dateStr) { // if (!StringUtils.isBlank(dateStr)) { // return LocalDate.parse(dateStr, DateTimeFormatter.ofPattern("yyyy-MM-dd")); // } // return null; // } // // @Override // public LocalDate deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { // String dateString = jsonParser.getText(); // // if (dateString == null) { // return null; // } // // return convertStringToLocalDate(dateString); // } // }
import com.verifalia.api.common.serialization.DateDeserializer; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.map.annotate.JsonDeserialize; import java.time.LocalDate;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.credits.models; /** * A total usage of Verifalia credits along a specific day.. */ @Getter @Setter @ToString @JsonIgnoreProperties(ignoreUnknown = true) public class DailyUsage { /** * The date this credits usage refers to. */
// Path: src/main/java/com/verifalia/api/common/serialization/DateDeserializer.java // public class DateDeserializer extends JsonDeserializer<LocalDate> { // private static LocalDate convertStringToLocalDate(@NonNull final String dateStr) { // if (!StringUtils.isBlank(dateStr)) { // return LocalDate.parse(dateStr, DateTimeFormatter.ofPattern("yyyy-MM-dd")); // } // return null; // } // // @Override // public LocalDate deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { // String dateString = jsonParser.getText(); // // if (dateString == null) { // return null; // } // // return convertStringToLocalDate(dateString); // } // } // Path: src/main/java/com/verifalia/api/credits/models/DailyUsage.java import com.verifalia.api.common.serialization.DateDeserializer; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.map.annotate.JsonDeserialize; import java.time.LocalDate; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.credits.models; /** * A total usage of Verifalia credits along a specific day.. */ @Getter @Setter @ToString @JsonIgnoreProperties(ignoreUnknown = true) public class DailyUsage { /** * The date this credits usage refers to. */
@JsonDeserialize(using = DateDeserializer.class)
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/common/filters/DateEqualityPredicate.java
// Path: src/main/java/com/verifalia/api/common/Utils.java // public class Utils { // /** // * Generates URI for HTTP request. // * // * @param paramMap Map with variable names and values to be passed when making URI for http request. // * @return URI URI for HTTP request based on the input parameters. // */ // public static URI getHttpUri(Map<String, String> paramMap) { // URIBuilder builder = new URIBuilder(); // try { // if (nonNull(paramMap) && paramMap.size() > 0) { // Iterator<String> paramMapIter = paramMap.keySet().iterator(); // while (paramMapIter.hasNext()) { // String paramKey = paramMapIter.next(); // String paramValue = paramMap.get(paramKey); // if (!StringUtils.isEmpty(paramValue)) { // builder.setParameter(paramKey, paramValue); // } // } // } // // return builder.build(); // } catch (URISyntaxException e) { // return null; // } // } // // /** // * Converts local date to string based on the input format. // * // * @param localDate LocalDate object which needs to be formatted. // * @param dateFormat Date format in which the local date object needs to be formatted. // * @return String Converted local date to string as per the input format. // */ // public static String convertLocalDateToString(LocalDate localDate, String dateFormat) { // if (nonNull(localDate)) { // return localDate.format(DateTimeFormatter.ofPattern(dateFormat)); // } // return StringUtils.EMPTY; // } // }
import com.verifalia.api.common.Utils; import lombok.Getter; import lombok.NonNull; import java.time.LocalDate;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.common.filters; /** * A filter predicate used to filter dates on a specific value. */ @Getter public class DateEqualityPredicate extends DateFilterPredicate { /** * The date (with no time information) to be included in the filter. */ private LocalDate date; /** * Initializes a filter predicate used to filter dates on a specific value. * * @param date The date (with no time information) to be included in the filter. */ public DateEqualityPredicate(@NonNull final LocalDate date) { this.setLocalDate(date); } @Override public FilterPredicateFragment[] serialize(@NonNull final String fieldName) { return new FilterPredicateFragment[]{
// Path: src/main/java/com/verifalia/api/common/Utils.java // public class Utils { // /** // * Generates URI for HTTP request. // * // * @param paramMap Map with variable names and values to be passed when making URI for http request. // * @return URI URI for HTTP request based on the input parameters. // */ // public static URI getHttpUri(Map<String, String> paramMap) { // URIBuilder builder = new URIBuilder(); // try { // if (nonNull(paramMap) && paramMap.size() > 0) { // Iterator<String> paramMapIter = paramMap.keySet().iterator(); // while (paramMapIter.hasNext()) { // String paramKey = paramMapIter.next(); // String paramValue = paramMap.get(paramKey); // if (!StringUtils.isEmpty(paramValue)) { // builder.setParameter(paramKey, paramValue); // } // } // } // // return builder.build(); // } catch (URISyntaxException e) { // return null; // } // } // // /** // * Converts local date to string based on the input format. // * // * @param localDate LocalDate object which needs to be formatted. // * @param dateFormat Date format in which the local date object needs to be formatted. // * @return String Converted local date to string as per the input format. // */ // public static String convertLocalDateToString(LocalDate localDate, String dateFormat) { // if (nonNull(localDate)) { // return localDate.format(DateTimeFormatter.ofPattern(dateFormat)); // } // return StringUtils.EMPTY; // } // } // Path: src/main/java/com/verifalia/api/common/filters/DateEqualityPredicate.java import com.verifalia.api.common.Utils; import lombok.Getter; import lombok.NonNull; import java.time.LocalDate; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.common.filters; /** * A filter predicate used to filter dates on a specific value. */ @Getter public class DateEqualityPredicate extends DateFilterPredicate { /** * The date (with no time information) to be included in the filter. */ private LocalDate date; /** * Initializes a filter predicate used to filter dates on a specific value. * * @param date The date (with no time information) to be included in the filter. */ public DateEqualityPredicate(@NonNull final LocalDate date) { this.setLocalDate(date); } @Override public FilterPredicateFragment[] serialize(@NonNull final String fieldName) { return new FilterPredicateFragment[]{
new FilterPredicateFragment(fieldName, Utils.convertLocalDateToString(this.getDate(), "yyyy-MM-dd"))
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/emailvalidations/models/ValidationProgress.java
// Path: src/main/java/com/verifalia/api/common/serialization/DurationDeserializer.java // public class DurationDeserializer extends JsonDeserializer<Duration> { // @Override // public Duration deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { // String durationString = jsonParser.getText(); // // if (durationString == null) { // return null; // } // // return parseDuration(durationString); // } // // private Duration parseDuration(@NonNull String inputData) { // inputData = inputData.trim(); // // // Parse the eventual days information // // String[] dayFields = inputData.split("\\."); // // if (dayFields.length > 2) { // throw new IllegalArgumentException(); // } // // int days = 0; // String timeData = inputData; // // if (dayFields.length == 2) { // days = Integer.parseInt(dayFields[0]); // timeData = dayFields[1]; // } // // // Parse the time information // // String[] timeFields = timeData.split(":"); // // if (timeFields.length != 3) { // throw new IllegalArgumentException(); // } // // return Duration.ofSeconds((days * 24 * 60 * 60) + // (Integer.parseInt(timeFields[0]) * 60 * 60) + // (Integer.parseInt(timeFields[1]) * 60) + // (Integer.parseInt(timeFields[2]))); // } // }
import com.verifalia.api.common.serialization.DurationDeserializer; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.codehaus.jackson.map.annotate.JsonDeserialize; import java.time.Duration;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Progress details for a {@link ValidationOverview}, exposed by way of the {@link ValidationOverview#progress} property. */ @Getter @Setter @ToString public class ValidationProgress { /** * The percentage of completed entries, ranging from 0 to 1. */ private Double percentage; /** * An eventual estimated required time span needed to complete the whole job. */
// Path: src/main/java/com/verifalia/api/common/serialization/DurationDeserializer.java // public class DurationDeserializer extends JsonDeserializer<Duration> { // @Override // public Duration deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { // String durationString = jsonParser.getText(); // // if (durationString == null) { // return null; // } // // return parseDuration(durationString); // } // // private Duration parseDuration(@NonNull String inputData) { // inputData = inputData.trim(); // // // Parse the eventual days information // // String[] dayFields = inputData.split("\\."); // // if (dayFields.length > 2) { // throw new IllegalArgumentException(); // } // // int days = 0; // String timeData = inputData; // // if (dayFields.length == 2) { // days = Integer.parseInt(dayFields[0]); // timeData = dayFields[1]; // } // // // Parse the time information // // String[] timeFields = timeData.split(":"); // // if (timeFields.length != 3) { // throw new IllegalArgumentException(); // } // // return Duration.ofSeconds((days * 24 * 60 * 60) + // (Integer.parseInt(timeFields[0]) * 60 * 60) + // (Integer.parseInt(timeFields[1]) * 60) + // (Integer.parseInt(timeFields[2]))); // } // } // Path: src/main/java/com/verifalia/api/emailvalidations/models/ValidationProgress.java import com.verifalia.api.common.serialization.DurationDeserializer; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.codehaus.jackson.map.annotate.JsonDeserialize; import java.time.Duration; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Progress details for a {@link ValidationOverview}, exposed by way of the {@link ValidationOverview#progress} property. */ @Getter @Setter @ToString public class ValidationProgress { /** * The percentage of completed entries, ranging from 0 to 1. */ private Double percentage; /** * An eventual estimated required time span needed to complete the whole job. */
@JsonDeserialize(using = DurationDeserializer.class)
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/emailvalidations/models/AbstractValidationRequest.java
// Path: src/main/java/com/verifalia/api/common/serialization/DurationSerializer.java // public class DurationSerializer extends JsonSerializer<Duration> { // private final long SECONDS_IN_MINUTE = 60; // private final long SECONDS_IN_HOUR = SECONDS_IN_MINUTE * 60; // private final long SECONDS_IN_DAY = SECONDS_IN_HOUR * 24; // // @Override // public void serialize(Duration value, JsonGenerator jgen, SerializerProvider provider) throws IOException { // if (value == null) { // jgen.writeNull(); // } else { // jgen.writeString(toString(value)); // } // } // // private String toString(@NonNull Duration value) { // StringBuffer sb = new StringBuffer(); // long remainingSeconds = value.toMillis() / 1000; // // long days = remainingSeconds / SECONDS_IN_DAY; // // if (days != 0) { // sb.append(days); // sb.append("."); // remainingSeconds = remainingSeconds % SECONDS_IN_DAY; // } // // sb.append(remainingSeconds / SECONDS_IN_HOUR); // sb.append(":"); // remainingSeconds = remainingSeconds % SECONDS_IN_HOUR; // // sb.append(remainingSeconds / SECONDS_IN_MINUTE); // sb.append(":"); // remainingSeconds = remainingSeconds % SECONDS_IN_MINUTE; // // sb.append(remainingSeconds); // // return sb.toString(); // } // } // // Path: src/main/java/com/verifalia/api/emailvalidations/serialization/QualityLevelNameSerializer.java // public class QualityLevelNameSerializer extends JsonSerializer<QualityLevelName> { // @Override // public void serialize(QualityLevelName value, JsonGenerator jgen, SerializerProvider provider) throws IOException { // if (value == null) { // jgen.writeNull(); // } else { // jgen.writeString(value.toString()); // } // } // } // // Path: src/main/java/com/verifalia/api/emailvalidations/serialization/ValidationPrioritySerializer.java // public class ValidationPrioritySerializer extends JsonSerializer<ValidationPriority> { // @Override // public void serialize(ValidationPriority value, JsonGenerator jgen, SerializerProvider provider) throws IOException { // if (value == null || value == ValidationPriority.Normal) { // jgen.writeNull(); // } else { // jgen.writeString(new Byte(value.getValue()).toString()); // } // } // }
import com.verifalia.api.common.serialization.DurationSerializer; import com.verifalia.api.emailvalidations.serialization.QualityLevelNameSerializer; import com.verifalia.api.emailvalidations.serialization.ValidationPrioritySerializer; import lombok.*; import org.apache.commons.lang3.StringUtils; import org.codehaus.jackson.map.annotate.JsonSerialize; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static java.util.Objects.nonNull;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Represents the abstract base class for email validation requests to be submitted against the Verifalia API. */ @Getter @Setter @ToString @NoArgsConstructor @AllArgsConstructor public class AbstractValidationRequest { private static final Integer VALIDATION_INPUT_PRIORITY_MIN_VALUE = 0; private static final Integer VALIDATION_INPUT_PRIORITY_MAX_VALUE = 255; /** * An optional user-defined name for the validation job, for your own reference. The name will be returned on * subsequent API calls and shown on the Verifalia clients area. */ private String name; /** * A reference to the expected results quality level for this request. Quality levels determine how Verifalia validates * email addresses, including whether and how the automatic reprocessing logic occurs (for transient statuses) and the * verification timeouts settings. * Use one of {@link QualityLevelName#Standard}, {@link QualityLevelName#High} or {@link QualityLevelName#Extreme} * values or a custom quality level ID if you have one (custom quality levels are available to premium plans only). */
// Path: src/main/java/com/verifalia/api/common/serialization/DurationSerializer.java // public class DurationSerializer extends JsonSerializer<Duration> { // private final long SECONDS_IN_MINUTE = 60; // private final long SECONDS_IN_HOUR = SECONDS_IN_MINUTE * 60; // private final long SECONDS_IN_DAY = SECONDS_IN_HOUR * 24; // // @Override // public void serialize(Duration value, JsonGenerator jgen, SerializerProvider provider) throws IOException { // if (value == null) { // jgen.writeNull(); // } else { // jgen.writeString(toString(value)); // } // } // // private String toString(@NonNull Duration value) { // StringBuffer sb = new StringBuffer(); // long remainingSeconds = value.toMillis() / 1000; // // long days = remainingSeconds / SECONDS_IN_DAY; // // if (days != 0) { // sb.append(days); // sb.append("."); // remainingSeconds = remainingSeconds % SECONDS_IN_DAY; // } // // sb.append(remainingSeconds / SECONDS_IN_HOUR); // sb.append(":"); // remainingSeconds = remainingSeconds % SECONDS_IN_HOUR; // // sb.append(remainingSeconds / SECONDS_IN_MINUTE); // sb.append(":"); // remainingSeconds = remainingSeconds % SECONDS_IN_MINUTE; // // sb.append(remainingSeconds); // // return sb.toString(); // } // } // // Path: src/main/java/com/verifalia/api/emailvalidations/serialization/QualityLevelNameSerializer.java // public class QualityLevelNameSerializer extends JsonSerializer<QualityLevelName> { // @Override // public void serialize(QualityLevelName value, JsonGenerator jgen, SerializerProvider provider) throws IOException { // if (value == null) { // jgen.writeNull(); // } else { // jgen.writeString(value.toString()); // } // } // } // // Path: src/main/java/com/verifalia/api/emailvalidations/serialization/ValidationPrioritySerializer.java // public class ValidationPrioritySerializer extends JsonSerializer<ValidationPriority> { // @Override // public void serialize(ValidationPriority value, JsonGenerator jgen, SerializerProvider provider) throws IOException { // if (value == null || value == ValidationPriority.Normal) { // jgen.writeNull(); // } else { // jgen.writeString(new Byte(value.getValue()).toString()); // } // } // } // Path: src/main/java/com/verifalia/api/emailvalidations/models/AbstractValidationRequest.java import com.verifalia.api.common.serialization.DurationSerializer; import com.verifalia.api.emailvalidations.serialization.QualityLevelNameSerializer; import com.verifalia.api.emailvalidations.serialization.ValidationPrioritySerializer; import lombok.*; import org.apache.commons.lang3.StringUtils; import org.codehaus.jackson.map.annotate.JsonSerialize; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static java.util.Objects.nonNull; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Represents the abstract base class for email validation requests to be submitted against the Verifalia API. */ @Getter @Setter @ToString @NoArgsConstructor @AllArgsConstructor public class AbstractValidationRequest { private static final Integer VALIDATION_INPUT_PRIORITY_MIN_VALUE = 0; private static final Integer VALIDATION_INPUT_PRIORITY_MAX_VALUE = 255; /** * An optional user-defined name for the validation job, for your own reference. The name will be returned on * subsequent API calls and shown on the Verifalia clients area. */ private String name; /** * A reference to the expected results quality level for this request. Quality levels determine how Verifalia validates * email addresses, including whether and how the automatic reprocessing logic occurs (for transient statuses) and the * verification timeouts settings. * Use one of {@link QualityLevelName#Standard}, {@link QualityLevelName#High} or {@link QualityLevelName#Extreme} * values or a custom quality level ID if you have one (custom quality levels are available to premium plans only). */
@JsonSerialize(using = QualityLevelNameSerializer.class, include = JsonSerialize.Inclusion.NON_NULL)
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/emailvalidations/models/AbstractValidationRequest.java
// Path: src/main/java/com/verifalia/api/common/serialization/DurationSerializer.java // public class DurationSerializer extends JsonSerializer<Duration> { // private final long SECONDS_IN_MINUTE = 60; // private final long SECONDS_IN_HOUR = SECONDS_IN_MINUTE * 60; // private final long SECONDS_IN_DAY = SECONDS_IN_HOUR * 24; // // @Override // public void serialize(Duration value, JsonGenerator jgen, SerializerProvider provider) throws IOException { // if (value == null) { // jgen.writeNull(); // } else { // jgen.writeString(toString(value)); // } // } // // private String toString(@NonNull Duration value) { // StringBuffer sb = new StringBuffer(); // long remainingSeconds = value.toMillis() / 1000; // // long days = remainingSeconds / SECONDS_IN_DAY; // // if (days != 0) { // sb.append(days); // sb.append("."); // remainingSeconds = remainingSeconds % SECONDS_IN_DAY; // } // // sb.append(remainingSeconds / SECONDS_IN_HOUR); // sb.append(":"); // remainingSeconds = remainingSeconds % SECONDS_IN_HOUR; // // sb.append(remainingSeconds / SECONDS_IN_MINUTE); // sb.append(":"); // remainingSeconds = remainingSeconds % SECONDS_IN_MINUTE; // // sb.append(remainingSeconds); // // return sb.toString(); // } // } // // Path: src/main/java/com/verifalia/api/emailvalidations/serialization/QualityLevelNameSerializer.java // public class QualityLevelNameSerializer extends JsonSerializer<QualityLevelName> { // @Override // public void serialize(QualityLevelName value, JsonGenerator jgen, SerializerProvider provider) throws IOException { // if (value == null) { // jgen.writeNull(); // } else { // jgen.writeString(value.toString()); // } // } // } // // Path: src/main/java/com/verifalia/api/emailvalidations/serialization/ValidationPrioritySerializer.java // public class ValidationPrioritySerializer extends JsonSerializer<ValidationPriority> { // @Override // public void serialize(ValidationPriority value, JsonGenerator jgen, SerializerProvider provider) throws IOException { // if (value == null || value == ValidationPriority.Normal) { // jgen.writeNull(); // } else { // jgen.writeString(new Byte(value.getValue()).toString()); // } // } // }
import com.verifalia.api.common.serialization.DurationSerializer; import com.verifalia.api.emailvalidations.serialization.QualityLevelNameSerializer; import com.verifalia.api.emailvalidations.serialization.ValidationPrioritySerializer; import lombok.*; import org.apache.commons.lang3.StringUtils; import org.codehaus.jackson.map.annotate.JsonSerialize; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static java.util.Objects.nonNull;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Represents the abstract base class for email validation requests to be submitted against the Verifalia API. */ @Getter @Setter @ToString @NoArgsConstructor @AllArgsConstructor public class AbstractValidationRequest { private static final Integer VALIDATION_INPUT_PRIORITY_MIN_VALUE = 0; private static final Integer VALIDATION_INPUT_PRIORITY_MAX_VALUE = 255; /** * An optional user-defined name for the validation job, for your own reference. The name will be returned on * subsequent API calls and shown on the Verifalia clients area. */ private String name; /** * A reference to the expected results quality level for this request. Quality levels determine how Verifalia validates * email addresses, including whether and how the automatic reprocessing logic occurs (for transient statuses) and the * verification timeouts settings. * Use one of {@link QualityLevelName#Standard}, {@link QualityLevelName#High} or {@link QualityLevelName#Extreme} * values or a custom quality level ID if you have one (custom quality levels are available to premium plans only). */ @JsonSerialize(using = QualityLevelNameSerializer.class, include = JsonSerialize.Inclusion.NON_NULL) private QualityLevelName quality; /** * The strategy Verifalia follows while determining which email addresses are duplicates, within a multiple items job. * Duplicated items (after the first occurrence) will have the {@link ValidationEntryStatus#Duplicate} status. */ private DeduplicationMode deduplication; /** * The eventual priority (speed) of the validation job, relative to the parent Verifalia account. In the event of an account * with many concurrent validation jobs, this value allows to increase the processing speed of a job with respect to the others. * The allowed range of values spans from {@link ValidationPriority#Lowest} (0 - lowest priority) to * {@link ValidationPriority#Highest} (255 - highest priority), where the midway value * {@link ValidationPriority#Normal} (127) means normal priority; if not specified, Verifalia processes all the * concurrent validation jobs for an account using the same priority. */
// Path: src/main/java/com/verifalia/api/common/serialization/DurationSerializer.java // public class DurationSerializer extends JsonSerializer<Duration> { // private final long SECONDS_IN_MINUTE = 60; // private final long SECONDS_IN_HOUR = SECONDS_IN_MINUTE * 60; // private final long SECONDS_IN_DAY = SECONDS_IN_HOUR * 24; // // @Override // public void serialize(Duration value, JsonGenerator jgen, SerializerProvider provider) throws IOException { // if (value == null) { // jgen.writeNull(); // } else { // jgen.writeString(toString(value)); // } // } // // private String toString(@NonNull Duration value) { // StringBuffer sb = new StringBuffer(); // long remainingSeconds = value.toMillis() / 1000; // // long days = remainingSeconds / SECONDS_IN_DAY; // // if (days != 0) { // sb.append(days); // sb.append("."); // remainingSeconds = remainingSeconds % SECONDS_IN_DAY; // } // // sb.append(remainingSeconds / SECONDS_IN_HOUR); // sb.append(":"); // remainingSeconds = remainingSeconds % SECONDS_IN_HOUR; // // sb.append(remainingSeconds / SECONDS_IN_MINUTE); // sb.append(":"); // remainingSeconds = remainingSeconds % SECONDS_IN_MINUTE; // // sb.append(remainingSeconds); // // return sb.toString(); // } // } // // Path: src/main/java/com/verifalia/api/emailvalidations/serialization/QualityLevelNameSerializer.java // public class QualityLevelNameSerializer extends JsonSerializer<QualityLevelName> { // @Override // public void serialize(QualityLevelName value, JsonGenerator jgen, SerializerProvider provider) throws IOException { // if (value == null) { // jgen.writeNull(); // } else { // jgen.writeString(value.toString()); // } // } // } // // Path: src/main/java/com/verifalia/api/emailvalidations/serialization/ValidationPrioritySerializer.java // public class ValidationPrioritySerializer extends JsonSerializer<ValidationPriority> { // @Override // public void serialize(ValidationPriority value, JsonGenerator jgen, SerializerProvider provider) throws IOException { // if (value == null || value == ValidationPriority.Normal) { // jgen.writeNull(); // } else { // jgen.writeString(new Byte(value.getValue()).toString()); // } // } // } // Path: src/main/java/com/verifalia/api/emailvalidations/models/AbstractValidationRequest.java import com.verifalia.api.common.serialization.DurationSerializer; import com.verifalia.api.emailvalidations.serialization.QualityLevelNameSerializer; import com.verifalia.api.emailvalidations.serialization.ValidationPrioritySerializer; import lombok.*; import org.apache.commons.lang3.StringUtils; import org.codehaus.jackson.map.annotate.JsonSerialize; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static java.util.Objects.nonNull; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Represents the abstract base class for email validation requests to be submitted against the Verifalia API. */ @Getter @Setter @ToString @NoArgsConstructor @AllArgsConstructor public class AbstractValidationRequest { private static final Integer VALIDATION_INPUT_PRIORITY_MIN_VALUE = 0; private static final Integer VALIDATION_INPUT_PRIORITY_MAX_VALUE = 255; /** * An optional user-defined name for the validation job, for your own reference. The name will be returned on * subsequent API calls and shown on the Verifalia clients area. */ private String name; /** * A reference to the expected results quality level for this request. Quality levels determine how Verifalia validates * email addresses, including whether and how the automatic reprocessing logic occurs (for transient statuses) and the * verification timeouts settings. * Use one of {@link QualityLevelName#Standard}, {@link QualityLevelName#High} or {@link QualityLevelName#Extreme} * values or a custom quality level ID if you have one (custom quality levels are available to premium plans only). */ @JsonSerialize(using = QualityLevelNameSerializer.class, include = JsonSerialize.Inclusion.NON_NULL) private QualityLevelName quality; /** * The strategy Verifalia follows while determining which email addresses are duplicates, within a multiple items job. * Duplicated items (after the first occurrence) will have the {@link ValidationEntryStatus#Duplicate} status. */ private DeduplicationMode deduplication; /** * The eventual priority (speed) of the validation job, relative to the parent Verifalia account. In the event of an account * with many concurrent validation jobs, this value allows to increase the processing speed of a job with respect to the others. * The allowed range of values spans from {@link ValidationPriority#Lowest} (0 - lowest priority) to * {@link ValidationPriority#Highest} (255 - highest priority), where the midway value * {@link ValidationPriority#Normal} (127) means normal priority; if not specified, Verifalia processes all the * concurrent validation jobs for an account using the same priority. */
@JsonSerialize(using = ValidationPrioritySerializer.class, include = JsonSerialize.Inclusion.NON_NULL)
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/rest/RestClient.java
// Path: src/main/java/com/verifalia/api/exceptions/EndpointServerErrorException.java // public class EndpointServerErrorException extends VerifaliaException { // public EndpointServerErrorException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/verifalia/api/exceptions/ServiceUnreachableException.java // public class ServiceUnreachableException extends VerifaliaException { // public ServiceUnreachableException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/verifalia/api/exceptions/VerifaliaException.java // public class VerifaliaException extends Exception { // private RestResponse response; // // public VerifaliaException(@NonNull final RestResponse response) { // super(response.getStatusCode() + ": " + response.readAsString()); // this.response = response; // } // // public VerifaliaException(String errorMessage) { // super(errorMessage); // } // // public VerifaliaException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/com/verifalia/api/rest/security/AuthenticationProvider.java // @Getter // @Setter // public abstract class AuthenticationProvider { // public void decorateRequest(RestClient client, HttpRequestBase request) throws VerifaliaException { // } // // public CloseableHttpClient buildClient(RestClient client) throws IOException { // return HttpClients.createDefault(); // } // }
import com.verifalia.api.exceptions.EndpointServerErrorException; import com.verifalia.api.exceptions.ServiceUnreachableException; import com.verifalia.api.exceptions.VerifaliaException; import com.verifalia.api.rest.security.AuthenticationProvider; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.*; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import static java.util.Objects.nonNull;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.rest; /*** * Represents the internal REST client used by the SDK. */ public class RestClient { private final List<URI> baseURIs; private final String apiVersion; private final String userAgent;
// Path: src/main/java/com/verifalia/api/exceptions/EndpointServerErrorException.java // public class EndpointServerErrorException extends VerifaliaException { // public EndpointServerErrorException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/verifalia/api/exceptions/ServiceUnreachableException.java // public class ServiceUnreachableException extends VerifaliaException { // public ServiceUnreachableException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/verifalia/api/exceptions/VerifaliaException.java // public class VerifaliaException extends Exception { // private RestResponse response; // // public VerifaliaException(@NonNull final RestResponse response) { // super(response.getStatusCode() + ": " + response.readAsString()); // this.response = response; // } // // public VerifaliaException(String errorMessage) { // super(errorMessage); // } // // public VerifaliaException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/com/verifalia/api/rest/security/AuthenticationProvider.java // @Getter // @Setter // public abstract class AuthenticationProvider { // public void decorateRequest(RestClient client, HttpRequestBase request) throws VerifaliaException { // } // // public CloseableHttpClient buildClient(RestClient client) throws IOException { // return HttpClients.createDefault(); // } // } // Path: src/main/java/com/verifalia/api/rest/RestClient.java import com.verifalia.api.exceptions.EndpointServerErrorException; import com.verifalia.api.exceptions.ServiceUnreachableException; import com.verifalia.api.exceptions.VerifaliaException; import com.verifalia.api.rest.security.AuthenticationProvider; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.*; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import static java.util.Objects.nonNull; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.rest; /*** * Represents the internal REST client used by the SDK. */ public class RestClient { private final List<URI> baseURIs; private final String apiVersion; private final String userAgent;
private final AuthenticationProvider defaultAuthenticationProvider;
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/rest/RestClient.java
// Path: src/main/java/com/verifalia/api/exceptions/EndpointServerErrorException.java // public class EndpointServerErrorException extends VerifaliaException { // public EndpointServerErrorException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/verifalia/api/exceptions/ServiceUnreachableException.java // public class ServiceUnreachableException extends VerifaliaException { // public ServiceUnreachableException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/verifalia/api/exceptions/VerifaliaException.java // public class VerifaliaException extends Exception { // private RestResponse response; // // public VerifaliaException(@NonNull final RestResponse response) { // super(response.getStatusCode() + ": " + response.readAsString()); // this.response = response; // } // // public VerifaliaException(String errorMessage) { // super(errorMessage); // } // // public VerifaliaException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/com/verifalia/api/rest/security/AuthenticationProvider.java // @Getter // @Setter // public abstract class AuthenticationProvider { // public void decorateRequest(RestClient client, HttpRequestBase request) throws VerifaliaException { // } // // public CloseableHttpClient buildClient(RestClient client) throws IOException { // return HttpClients.createDefault(); // } // }
import com.verifalia.api.exceptions.EndpointServerErrorException; import com.verifalia.api.exceptions.ServiceUnreachableException; import com.verifalia.api.exceptions.VerifaliaException; import com.verifalia.api.rest.security.AuthenticationProvider; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.*; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import static java.util.Objects.nonNull;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.rest; /*** * Represents the internal REST client used by the SDK. */ public class RestClient { private final List<URI> baseURIs; private final String apiVersion; private final String userAgent; private final AuthenticationProvider defaultAuthenticationProvider; private int currentBaseURIIndex; public RestClient(@NonNull final AuthenticationProvider defaultAuthenticationProvider, @NonNull final List<URI> baseURIs, @NonNull final String apiVersion) { this.baseURIs = baseURIs; this.apiVersion = apiVersion; this.userAgent = getUserAgent(); this.defaultAuthenticationProvider = defaultAuthenticationProvider; }
// Path: src/main/java/com/verifalia/api/exceptions/EndpointServerErrorException.java // public class EndpointServerErrorException extends VerifaliaException { // public EndpointServerErrorException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/verifalia/api/exceptions/ServiceUnreachableException.java // public class ServiceUnreachableException extends VerifaliaException { // public ServiceUnreachableException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/verifalia/api/exceptions/VerifaliaException.java // public class VerifaliaException extends Exception { // private RestResponse response; // // public VerifaliaException(@NonNull final RestResponse response) { // super(response.getStatusCode() + ": " + response.readAsString()); // this.response = response; // } // // public VerifaliaException(String errorMessage) { // super(errorMessage); // } // // public VerifaliaException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/com/verifalia/api/rest/security/AuthenticationProvider.java // @Getter // @Setter // public abstract class AuthenticationProvider { // public void decorateRequest(RestClient client, HttpRequestBase request) throws VerifaliaException { // } // // public CloseableHttpClient buildClient(RestClient client) throws IOException { // return HttpClients.createDefault(); // } // } // Path: src/main/java/com/verifalia/api/rest/RestClient.java import com.verifalia.api.exceptions.EndpointServerErrorException; import com.verifalia.api.exceptions.ServiceUnreachableException; import com.verifalia.api.exceptions.VerifaliaException; import com.verifalia.api.rest.security.AuthenticationProvider; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.*; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import static java.util.Objects.nonNull; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.rest; /*** * Represents the internal REST client used by the SDK. */ public class RestClient { private final List<URI> baseURIs; private final String apiVersion; private final String userAgent; private final AuthenticationProvider defaultAuthenticationProvider; private int currentBaseURIIndex; public RestClient(@NonNull final AuthenticationProvider defaultAuthenticationProvider, @NonNull final List<URI> baseURIs, @NonNull final String apiVersion) { this.baseURIs = baseURIs; this.apiVersion = apiVersion; this.userAgent = getUserAgent(); this.defaultAuthenticationProvider = defaultAuthenticationProvider; }
public RestResponse execute(@NonNull final RestRequest request) throws VerifaliaException {
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/rest/RestClient.java
// Path: src/main/java/com/verifalia/api/exceptions/EndpointServerErrorException.java // public class EndpointServerErrorException extends VerifaliaException { // public EndpointServerErrorException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/verifalia/api/exceptions/ServiceUnreachableException.java // public class ServiceUnreachableException extends VerifaliaException { // public ServiceUnreachableException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/verifalia/api/exceptions/VerifaliaException.java // public class VerifaliaException extends Exception { // private RestResponse response; // // public VerifaliaException(@NonNull final RestResponse response) { // super(response.getStatusCode() + ": " + response.readAsString()); // this.response = response; // } // // public VerifaliaException(String errorMessage) { // super(errorMessage); // } // // public VerifaliaException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/com/verifalia/api/rest/security/AuthenticationProvider.java // @Getter // @Setter // public abstract class AuthenticationProvider { // public void decorateRequest(RestClient client, HttpRequestBase request) throws VerifaliaException { // } // // public CloseableHttpClient buildClient(RestClient client) throws IOException { // return HttpClients.createDefault(); // } // }
import com.verifalia.api.exceptions.EndpointServerErrorException; import com.verifalia.api.exceptions.ServiceUnreachableException; import com.verifalia.api.exceptions.VerifaliaException; import com.verifalia.api.rest.security.AuthenticationProvider; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.*; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import static java.util.Objects.nonNull;
URI baseUri; Exception exception; EndpointServerError(@NonNull final URI baseUri, @NonNull final Exception exception) { this.setBaseUri(baseUri); this.setException(exception); } } ArrayList<EndpointServerError> errors = new ArrayList<>(); if (nonNull(this.baseURIs)) { for (int idxAttempt = 0; idxAttempt < this.baseURIs.size(); idxAttempt++) { CloseableHttpResponse response; URI baseURI = this.baseURIs.get(currentBaseURIIndex++ % this.baseURIs.size()); try { response = sendRequest(baseURI, request, authenticationProvider); } catch (IOException e) { // Continue with the next attempt on IO exceptions, if needed errors.add(new EndpointServerError(baseURI, e)); continue; } if (nonNull(response)) { int statusCode = response.getStatusLine().getStatusCode(); // Automatically retry with another host on HTTP 5xx status codes if (statusCode >= 500 && statusCode <= 599) {
// Path: src/main/java/com/verifalia/api/exceptions/EndpointServerErrorException.java // public class EndpointServerErrorException extends VerifaliaException { // public EndpointServerErrorException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/verifalia/api/exceptions/ServiceUnreachableException.java // public class ServiceUnreachableException extends VerifaliaException { // public ServiceUnreachableException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/verifalia/api/exceptions/VerifaliaException.java // public class VerifaliaException extends Exception { // private RestResponse response; // // public VerifaliaException(@NonNull final RestResponse response) { // super(response.getStatusCode() + ": " + response.readAsString()); // this.response = response; // } // // public VerifaliaException(String errorMessage) { // super(errorMessage); // } // // public VerifaliaException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/com/verifalia/api/rest/security/AuthenticationProvider.java // @Getter // @Setter // public abstract class AuthenticationProvider { // public void decorateRequest(RestClient client, HttpRequestBase request) throws VerifaliaException { // } // // public CloseableHttpClient buildClient(RestClient client) throws IOException { // return HttpClients.createDefault(); // } // } // Path: src/main/java/com/verifalia/api/rest/RestClient.java import com.verifalia.api.exceptions.EndpointServerErrorException; import com.verifalia.api.exceptions.ServiceUnreachableException; import com.verifalia.api.exceptions.VerifaliaException; import com.verifalia.api.rest.security.AuthenticationProvider; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.*; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import static java.util.Objects.nonNull; URI baseUri; Exception exception; EndpointServerError(@NonNull final URI baseUri, @NonNull final Exception exception) { this.setBaseUri(baseUri); this.setException(exception); } } ArrayList<EndpointServerError> errors = new ArrayList<>(); if (nonNull(this.baseURIs)) { for (int idxAttempt = 0; idxAttempt < this.baseURIs.size(); idxAttempt++) { CloseableHttpResponse response; URI baseURI = this.baseURIs.get(currentBaseURIIndex++ % this.baseURIs.size()); try { response = sendRequest(baseURI, request, authenticationProvider); } catch (IOException e) { // Continue with the next attempt on IO exceptions, if needed errors.add(new EndpointServerError(baseURI, e)); continue; } if (nonNull(response)) { int statusCode = response.getStatusLine().getStatusCode(); // Automatically retry with another host on HTTP 5xx status codes if (statusCode >= 500 && statusCode <= 599) {
errors.add(new EndpointServerError(baseURI, new EndpointServerErrorException(String.format("The API endpoint %s returned a server error HTTP status code %d.", baseURI, statusCode))));
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/rest/RestClient.java
// Path: src/main/java/com/verifalia/api/exceptions/EndpointServerErrorException.java // public class EndpointServerErrorException extends VerifaliaException { // public EndpointServerErrorException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/verifalia/api/exceptions/ServiceUnreachableException.java // public class ServiceUnreachableException extends VerifaliaException { // public ServiceUnreachableException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/verifalia/api/exceptions/VerifaliaException.java // public class VerifaliaException extends Exception { // private RestResponse response; // // public VerifaliaException(@NonNull final RestResponse response) { // super(response.getStatusCode() + ": " + response.readAsString()); // this.response = response; // } // // public VerifaliaException(String errorMessage) { // super(errorMessage); // } // // public VerifaliaException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/com/verifalia/api/rest/security/AuthenticationProvider.java // @Getter // @Setter // public abstract class AuthenticationProvider { // public void decorateRequest(RestClient client, HttpRequestBase request) throws VerifaliaException { // } // // public CloseableHttpClient buildClient(RestClient client) throws IOException { // return HttpClients.createDefault(); // } // }
import com.verifalia.api.exceptions.EndpointServerErrorException; import com.verifalia.api.exceptions.ServiceUnreachableException; import com.verifalia.api.exceptions.VerifaliaException; import com.verifalia.api.rest.security.AuthenticationProvider; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.*; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import static java.util.Objects.nonNull;
URI baseURI = this.baseURIs.get(currentBaseURIIndex++ % this.baseURIs.size()); try { response = sendRequest(baseURI, request, authenticationProvider); } catch (IOException e) { // Continue with the next attempt on IO exceptions, if needed errors.add(new EndpointServerError(baseURI, e)); continue; } if (nonNull(response)) { int statusCode = response.getStatusLine().getStatusCode(); // Automatically retry with another host on HTTP 5xx status codes if (statusCode >= 500 && statusCode <= 599) { errors.add(new EndpointServerError(baseURI, new EndpointServerErrorException(String.format("The API endpoint %s returned a server error HTTP status code %d.", baseURI, statusCode)))); continue; } return new RestResponse(statusCode, response.getEntity()); } } } // Aggregate exception StringBuilder sbAggregateError = new StringBuilder("All the base URIs are unreachable: "); errors.forEach(e -> sbAggregateError.append(e.baseUri).append(" => ").append(e.exception.getMessage()).append(" "));
// Path: src/main/java/com/verifalia/api/exceptions/EndpointServerErrorException.java // public class EndpointServerErrorException extends VerifaliaException { // public EndpointServerErrorException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/verifalia/api/exceptions/ServiceUnreachableException.java // public class ServiceUnreachableException extends VerifaliaException { // public ServiceUnreachableException(String errorMessage) { // super(errorMessage); // } // } // // Path: src/main/java/com/verifalia/api/exceptions/VerifaliaException.java // public class VerifaliaException extends Exception { // private RestResponse response; // // public VerifaliaException(@NonNull final RestResponse response) { // super(response.getStatusCode() + ": " + response.readAsString()); // this.response = response; // } // // public VerifaliaException(String errorMessage) { // super(errorMessage); // } // // public VerifaliaException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/com/verifalia/api/rest/security/AuthenticationProvider.java // @Getter // @Setter // public abstract class AuthenticationProvider { // public void decorateRequest(RestClient client, HttpRequestBase request) throws VerifaliaException { // } // // public CloseableHttpClient buildClient(RestClient client) throws IOException { // return HttpClients.createDefault(); // } // } // Path: src/main/java/com/verifalia/api/rest/RestClient.java import com.verifalia.api.exceptions.EndpointServerErrorException; import com.verifalia.api.exceptions.ServiceUnreachableException; import com.verifalia.api.exceptions.VerifaliaException; import com.verifalia.api.rest.security.AuthenticationProvider; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.*; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import static java.util.Objects.nonNull; URI baseURI = this.baseURIs.get(currentBaseURIIndex++ % this.baseURIs.size()); try { response = sendRequest(baseURI, request, authenticationProvider); } catch (IOException e) { // Continue with the next attempt on IO exceptions, if needed errors.add(new EndpointServerError(baseURI, e)); continue; } if (nonNull(response)) { int statusCode = response.getStatusLine().getStatusCode(); // Automatically retry with another host on HTTP 5xx status codes if (statusCode >= 500 && statusCode <= 599) { errors.add(new EndpointServerError(baseURI, new EndpointServerErrorException(String.format("The API endpoint %s returned a server error HTTP status code %d.", baseURI, statusCode)))); continue; } return new RestResponse(statusCode, response.getEntity()); } } } // Aggregate exception StringBuilder sbAggregateError = new StringBuilder("All the base URIs are unreachable: "); errors.forEach(e -> sbAggregateError.append(e.baseUri).append(" => ").append(e.exception.getMessage()).append(" "));
throw new ServiceUnreachableException(sbAggregateError.toString());
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/emailvalidations/models/ValidationOverviewListingOptions.java
// Path: src/main/java/com/verifalia/api/common/ListingOptions.java // @Getter // @SuperBuilder // @NoArgsConstructor // public class ListingOptions { // /** // * The maximum number of items to return with a listing request. The Verifalia API may choose to override the specified // * limit if it is either too small or too big. Note: a single listing operation may automatically perform different // * listing requests to the Verifalia API: this value limits the number of items returned by *each* API request, not // * the overall total number of returned items. // */ // private Integer limit; // // /** // * The direction of the listing. // */ // @Builder.Default // private Direction direction = Direction.Forward; // // public void setLimit(final Integer limit) { // if (limit != null && limit < 0) { // throw new IllegalArgumentException("Limit must be 0 (meaning no limit will be enforced) or greater."); // } // // this.limit = limit; // } // // public void setDirection(@NonNull final Direction direction) { // this.direction = direction; // } // } // // Path: src/main/java/com/verifalia/api/common/filters/DateFilterPredicate.java // public abstract class DateFilterPredicate extends FilterPredicate { // } // // Path: src/main/java/com/verifalia/api/common/filters/SetFilterPredicate.java // public abstract class SetFilterPredicate<T> extends FilterPredicate { // } // // Path: src/main/java/com/verifalia/api/common/filters/StringEqualityPredicate.java // @Getter // public class StringEqualityPredicate extends StringFilterPredicate { // /** // * The string to be included in the filter. // */ // private String string; // // /** // * Initializes a filter predicate used to filter strings on a specific value. // * // * @param string The string to be included in the filter. // */ // public StringEqualityPredicate(@NonNull final String string) { // this.setString(string); // } // // @Override // public FilterPredicateFragment[] serialize(@NonNull final String fieldName) { // return new FilterPredicateFragment[]{ // new FilterPredicateFragment(fieldName, this.getString()) // }; // } // // public void setString(@NonNull final String string) { // this.string = string; // } // }
import com.verifalia.api.common.ListingOptions; import com.verifalia.api.common.filters.DateFilterPredicate; import com.verifalia.api.common.filters.SetFilterPredicate; import com.verifalia.api.common.filters.StringEqualityPredicate; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.SuperBuilder;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Provides options for a listing of validation jobs. */ @Getter @Setter @ToString @SuperBuilder @NoArgsConstructor
// Path: src/main/java/com/verifalia/api/common/ListingOptions.java // @Getter // @SuperBuilder // @NoArgsConstructor // public class ListingOptions { // /** // * The maximum number of items to return with a listing request. The Verifalia API may choose to override the specified // * limit if it is either too small or too big. Note: a single listing operation may automatically perform different // * listing requests to the Verifalia API: this value limits the number of items returned by *each* API request, not // * the overall total number of returned items. // */ // private Integer limit; // // /** // * The direction of the listing. // */ // @Builder.Default // private Direction direction = Direction.Forward; // // public void setLimit(final Integer limit) { // if (limit != null && limit < 0) { // throw new IllegalArgumentException("Limit must be 0 (meaning no limit will be enforced) or greater."); // } // // this.limit = limit; // } // // public void setDirection(@NonNull final Direction direction) { // this.direction = direction; // } // } // // Path: src/main/java/com/verifalia/api/common/filters/DateFilterPredicate.java // public abstract class DateFilterPredicate extends FilterPredicate { // } // // Path: src/main/java/com/verifalia/api/common/filters/SetFilterPredicate.java // public abstract class SetFilterPredicate<T> extends FilterPredicate { // } // // Path: src/main/java/com/verifalia/api/common/filters/StringEqualityPredicate.java // @Getter // public class StringEqualityPredicate extends StringFilterPredicate { // /** // * The string to be included in the filter. // */ // private String string; // // /** // * Initializes a filter predicate used to filter strings on a specific value. // * // * @param string The string to be included in the filter. // */ // public StringEqualityPredicate(@NonNull final String string) { // this.setString(string); // } // // @Override // public FilterPredicateFragment[] serialize(@NonNull final String fieldName) { // return new FilterPredicateFragment[]{ // new FilterPredicateFragment(fieldName, this.getString()) // }; // } // // public void setString(@NonNull final String string) { // this.string = string; // } // } // Path: src/main/java/com/verifalia/api/emailvalidations/models/ValidationOverviewListingOptions.java import com.verifalia.api.common.ListingOptions; import com.verifalia.api.common.filters.DateFilterPredicate; import com.verifalia.api.common.filters.SetFilterPredicate; import com.verifalia.api.common.filters.StringEqualityPredicate; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.SuperBuilder; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Provides options for a listing of validation jobs. */ @Getter @Setter @ToString @SuperBuilder @NoArgsConstructor
public class ValidationOverviewListingOptions extends ListingOptions {
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/emailvalidations/models/ValidationOverviewListingOptions.java
// Path: src/main/java/com/verifalia/api/common/ListingOptions.java // @Getter // @SuperBuilder // @NoArgsConstructor // public class ListingOptions { // /** // * The maximum number of items to return with a listing request. The Verifalia API may choose to override the specified // * limit if it is either too small or too big. Note: a single listing operation may automatically perform different // * listing requests to the Verifalia API: this value limits the number of items returned by *each* API request, not // * the overall total number of returned items. // */ // private Integer limit; // // /** // * The direction of the listing. // */ // @Builder.Default // private Direction direction = Direction.Forward; // // public void setLimit(final Integer limit) { // if (limit != null && limit < 0) { // throw new IllegalArgumentException("Limit must be 0 (meaning no limit will be enforced) or greater."); // } // // this.limit = limit; // } // // public void setDirection(@NonNull final Direction direction) { // this.direction = direction; // } // } // // Path: src/main/java/com/verifalia/api/common/filters/DateFilterPredicate.java // public abstract class DateFilterPredicate extends FilterPredicate { // } // // Path: src/main/java/com/verifalia/api/common/filters/SetFilterPredicate.java // public abstract class SetFilterPredicate<T> extends FilterPredicate { // } // // Path: src/main/java/com/verifalia/api/common/filters/StringEqualityPredicate.java // @Getter // public class StringEqualityPredicate extends StringFilterPredicate { // /** // * The string to be included in the filter. // */ // private String string; // // /** // * Initializes a filter predicate used to filter strings on a specific value. // * // * @param string The string to be included in the filter. // */ // public StringEqualityPredicate(@NonNull final String string) { // this.setString(string); // } // // @Override // public FilterPredicateFragment[] serialize(@NonNull final String fieldName) { // return new FilterPredicateFragment[]{ // new FilterPredicateFragment(fieldName, this.getString()) // }; // } // // public void setString(@NonNull final String string) { // this.string = string; // } // }
import com.verifalia.api.common.ListingOptions; import com.verifalia.api.common.filters.DateFilterPredicate; import com.verifalia.api.common.filters.SetFilterPredicate; import com.verifalia.api.common.filters.StringEqualityPredicate; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.SuperBuilder;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Provides options for a listing of validation jobs. */ @Getter @Setter @ToString @SuperBuilder @NoArgsConstructor public class ValidationOverviewListingOptions extends ListingOptions { /** * Allows to filter the resulting list by the creation date of its {@link ValidationOverview} items. */
// Path: src/main/java/com/verifalia/api/common/ListingOptions.java // @Getter // @SuperBuilder // @NoArgsConstructor // public class ListingOptions { // /** // * The maximum number of items to return with a listing request. The Verifalia API may choose to override the specified // * limit if it is either too small or too big. Note: a single listing operation may automatically perform different // * listing requests to the Verifalia API: this value limits the number of items returned by *each* API request, not // * the overall total number of returned items. // */ // private Integer limit; // // /** // * The direction of the listing. // */ // @Builder.Default // private Direction direction = Direction.Forward; // // public void setLimit(final Integer limit) { // if (limit != null && limit < 0) { // throw new IllegalArgumentException("Limit must be 0 (meaning no limit will be enforced) or greater."); // } // // this.limit = limit; // } // // public void setDirection(@NonNull final Direction direction) { // this.direction = direction; // } // } // // Path: src/main/java/com/verifalia/api/common/filters/DateFilterPredicate.java // public abstract class DateFilterPredicate extends FilterPredicate { // } // // Path: src/main/java/com/verifalia/api/common/filters/SetFilterPredicate.java // public abstract class SetFilterPredicate<T> extends FilterPredicate { // } // // Path: src/main/java/com/verifalia/api/common/filters/StringEqualityPredicate.java // @Getter // public class StringEqualityPredicate extends StringFilterPredicate { // /** // * The string to be included in the filter. // */ // private String string; // // /** // * Initializes a filter predicate used to filter strings on a specific value. // * // * @param string The string to be included in the filter. // */ // public StringEqualityPredicate(@NonNull final String string) { // this.setString(string); // } // // @Override // public FilterPredicateFragment[] serialize(@NonNull final String fieldName) { // return new FilterPredicateFragment[]{ // new FilterPredicateFragment(fieldName, this.getString()) // }; // } // // public void setString(@NonNull final String string) { // this.string = string; // } // } // Path: src/main/java/com/verifalia/api/emailvalidations/models/ValidationOverviewListingOptions.java import com.verifalia.api.common.ListingOptions; import com.verifalia.api.common.filters.DateFilterPredicate; import com.verifalia.api.common.filters.SetFilterPredicate; import com.verifalia.api.common.filters.StringEqualityPredicate; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.SuperBuilder; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Provides options for a listing of validation jobs. */ @Getter @Setter @ToString @SuperBuilder @NoArgsConstructor public class ValidationOverviewListingOptions extends ListingOptions { /** * Allows to filter the resulting list by the creation date of its {@link ValidationOverview} items. */
private DateFilterPredicate createdOn;
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/emailvalidations/models/ValidationOverviewListingOptions.java
// Path: src/main/java/com/verifalia/api/common/ListingOptions.java // @Getter // @SuperBuilder // @NoArgsConstructor // public class ListingOptions { // /** // * The maximum number of items to return with a listing request. The Verifalia API may choose to override the specified // * limit if it is either too small or too big. Note: a single listing operation may automatically perform different // * listing requests to the Verifalia API: this value limits the number of items returned by *each* API request, not // * the overall total number of returned items. // */ // private Integer limit; // // /** // * The direction of the listing. // */ // @Builder.Default // private Direction direction = Direction.Forward; // // public void setLimit(final Integer limit) { // if (limit != null && limit < 0) { // throw new IllegalArgumentException("Limit must be 0 (meaning no limit will be enforced) or greater."); // } // // this.limit = limit; // } // // public void setDirection(@NonNull final Direction direction) { // this.direction = direction; // } // } // // Path: src/main/java/com/verifalia/api/common/filters/DateFilterPredicate.java // public abstract class DateFilterPredicate extends FilterPredicate { // } // // Path: src/main/java/com/verifalia/api/common/filters/SetFilterPredicate.java // public abstract class SetFilterPredicate<T> extends FilterPredicate { // } // // Path: src/main/java/com/verifalia/api/common/filters/StringEqualityPredicate.java // @Getter // public class StringEqualityPredicate extends StringFilterPredicate { // /** // * The string to be included in the filter. // */ // private String string; // // /** // * Initializes a filter predicate used to filter strings on a specific value. // * // * @param string The string to be included in the filter. // */ // public StringEqualityPredicate(@NonNull final String string) { // this.setString(string); // } // // @Override // public FilterPredicateFragment[] serialize(@NonNull final String fieldName) { // return new FilterPredicateFragment[]{ // new FilterPredicateFragment(fieldName, this.getString()) // }; // } // // public void setString(@NonNull final String string) { // this.string = string; // } // }
import com.verifalia.api.common.ListingOptions; import com.verifalia.api.common.filters.DateFilterPredicate; import com.verifalia.api.common.filters.SetFilterPredicate; import com.verifalia.api.common.filters.StringEqualityPredicate; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.SuperBuilder;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Provides options for a listing of validation jobs. */ @Getter @Setter @ToString @SuperBuilder @NoArgsConstructor public class ValidationOverviewListingOptions extends ListingOptions { /** * Allows to filter the resulting list by the creation date of its {@link ValidationOverview} items. */ private DateFilterPredicate createdOn; /** * Allows to filter the resulting list by the ID of its owner; if present, the API will return only the jobs * submitted by the specified user. */
// Path: src/main/java/com/verifalia/api/common/ListingOptions.java // @Getter // @SuperBuilder // @NoArgsConstructor // public class ListingOptions { // /** // * The maximum number of items to return with a listing request. The Verifalia API may choose to override the specified // * limit if it is either too small or too big. Note: a single listing operation may automatically perform different // * listing requests to the Verifalia API: this value limits the number of items returned by *each* API request, not // * the overall total number of returned items. // */ // private Integer limit; // // /** // * The direction of the listing. // */ // @Builder.Default // private Direction direction = Direction.Forward; // // public void setLimit(final Integer limit) { // if (limit != null && limit < 0) { // throw new IllegalArgumentException("Limit must be 0 (meaning no limit will be enforced) or greater."); // } // // this.limit = limit; // } // // public void setDirection(@NonNull final Direction direction) { // this.direction = direction; // } // } // // Path: src/main/java/com/verifalia/api/common/filters/DateFilterPredicate.java // public abstract class DateFilterPredicate extends FilterPredicate { // } // // Path: src/main/java/com/verifalia/api/common/filters/SetFilterPredicate.java // public abstract class SetFilterPredicate<T> extends FilterPredicate { // } // // Path: src/main/java/com/verifalia/api/common/filters/StringEqualityPredicate.java // @Getter // public class StringEqualityPredicate extends StringFilterPredicate { // /** // * The string to be included in the filter. // */ // private String string; // // /** // * Initializes a filter predicate used to filter strings on a specific value. // * // * @param string The string to be included in the filter. // */ // public StringEqualityPredicate(@NonNull final String string) { // this.setString(string); // } // // @Override // public FilterPredicateFragment[] serialize(@NonNull final String fieldName) { // return new FilterPredicateFragment[]{ // new FilterPredicateFragment(fieldName, this.getString()) // }; // } // // public void setString(@NonNull final String string) { // this.string = string; // } // } // Path: src/main/java/com/verifalia/api/emailvalidations/models/ValidationOverviewListingOptions.java import com.verifalia.api.common.ListingOptions; import com.verifalia.api.common.filters.DateFilterPredicate; import com.verifalia.api.common.filters.SetFilterPredicate; import com.verifalia.api.common.filters.StringEqualityPredicate; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.SuperBuilder; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Provides options for a listing of validation jobs. */ @Getter @Setter @ToString @SuperBuilder @NoArgsConstructor public class ValidationOverviewListingOptions extends ListingOptions { /** * Allows to filter the resulting list by the creation date of its {@link ValidationOverview} items. */ private DateFilterPredicate createdOn; /** * Allows to filter the resulting list by the ID of its owner; if present, the API will return only the jobs * submitted by the specified user. */
private StringEqualityPredicate owner;
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/emailvalidations/models/ValidationOverviewListingOptions.java
// Path: src/main/java/com/verifalia/api/common/ListingOptions.java // @Getter // @SuperBuilder // @NoArgsConstructor // public class ListingOptions { // /** // * The maximum number of items to return with a listing request. The Verifalia API may choose to override the specified // * limit if it is either too small or too big. Note: a single listing operation may automatically perform different // * listing requests to the Verifalia API: this value limits the number of items returned by *each* API request, not // * the overall total number of returned items. // */ // private Integer limit; // // /** // * The direction of the listing. // */ // @Builder.Default // private Direction direction = Direction.Forward; // // public void setLimit(final Integer limit) { // if (limit != null && limit < 0) { // throw new IllegalArgumentException("Limit must be 0 (meaning no limit will be enforced) or greater."); // } // // this.limit = limit; // } // // public void setDirection(@NonNull final Direction direction) { // this.direction = direction; // } // } // // Path: src/main/java/com/verifalia/api/common/filters/DateFilterPredicate.java // public abstract class DateFilterPredicate extends FilterPredicate { // } // // Path: src/main/java/com/verifalia/api/common/filters/SetFilterPredicate.java // public abstract class SetFilterPredicate<T> extends FilterPredicate { // } // // Path: src/main/java/com/verifalia/api/common/filters/StringEqualityPredicate.java // @Getter // public class StringEqualityPredicate extends StringFilterPredicate { // /** // * The string to be included in the filter. // */ // private String string; // // /** // * Initializes a filter predicate used to filter strings on a specific value. // * // * @param string The string to be included in the filter. // */ // public StringEqualityPredicate(@NonNull final String string) { // this.setString(string); // } // // @Override // public FilterPredicateFragment[] serialize(@NonNull final String fieldName) { // return new FilterPredicateFragment[]{ // new FilterPredicateFragment(fieldName, this.getString()) // }; // } // // public void setString(@NonNull final String string) { // this.string = string; // } // }
import com.verifalia.api.common.ListingOptions; import com.verifalia.api.common.filters.DateFilterPredicate; import com.verifalia.api.common.filters.SetFilterPredicate; import com.verifalia.api.common.filters.StringEqualityPredicate; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.SuperBuilder;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Provides options for a listing of validation jobs. */ @Getter @Setter @ToString @SuperBuilder @NoArgsConstructor public class ValidationOverviewListingOptions extends ListingOptions { /** * Allows to filter the resulting list by the creation date of its {@link ValidationOverview} items. */ private DateFilterPredicate createdOn; /** * Allows to filter the resulting list by the ID of its owner; if present, the API will return only the jobs * submitted by the specified user. */ private StringEqualityPredicate owner; /** * Allows to filter the results by their {@link ValidationStatus}. */
// Path: src/main/java/com/verifalia/api/common/ListingOptions.java // @Getter // @SuperBuilder // @NoArgsConstructor // public class ListingOptions { // /** // * The maximum number of items to return with a listing request. The Verifalia API may choose to override the specified // * limit if it is either too small or too big. Note: a single listing operation may automatically perform different // * listing requests to the Verifalia API: this value limits the number of items returned by *each* API request, not // * the overall total number of returned items. // */ // private Integer limit; // // /** // * The direction of the listing. // */ // @Builder.Default // private Direction direction = Direction.Forward; // // public void setLimit(final Integer limit) { // if (limit != null && limit < 0) { // throw new IllegalArgumentException("Limit must be 0 (meaning no limit will be enforced) or greater."); // } // // this.limit = limit; // } // // public void setDirection(@NonNull final Direction direction) { // this.direction = direction; // } // } // // Path: src/main/java/com/verifalia/api/common/filters/DateFilterPredicate.java // public abstract class DateFilterPredicate extends FilterPredicate { // } // // Path: src/main/java/com/verifalia/api/common/filters/SetFilterPredicate.java // public abstract class SetFilterPredicate<T> extends FilterPredicate { // } // // Path: src/main/java/com/verifalia/api/common/filters/StringEqualityPredicate.java // @Getter // public class StringEqualityPredicate extends StringFilterPredicate { // /** // * The string to be included in the filter. // */ // private String string; // // /** // * Initializes a filter predicate used to filter strings on a specific value. // * // * @param string The string to be included in the filter. // */ // public StringEqualityPredicate(@NonNull final String string) { // this.setString(string); // } // // @Override // public FilterPredicateFragment[] serialize(@NonNull final String fieldName) { // return new FilterPredicateFragment[]{ // new FilterPredicateFragment(fieldName, this.getString()) // }; // } // // public void setString(@NonNull final String string) { // this.string = string; // } // } // Path: src/main/java/com/verifalia/api/emailvalidations/models/ValidationOverviewListingOptions.java import com.verifalia.api.common.ListingOptions; import com.verifalia.api.common.filters.DateFilterPredicate; import com.verifalia.api.common.filters.SetFilterPredicate; import com.verifalia.api.common.filters.StringEqualityPredicate; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import lombok.experimental.SuperBuilder; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Provides options for a listing of validation jobs. */ @Getter @Setter @ToString @SuperBuilder @NoArgsConstructor public class ValidationOverviewListingOptions extends ListingOptions { /** * Allows to filter the resulting list by the creation date of its {@link ValidationOverview} items. */ private DateFilterPredicate createdOn; /** * Allows to filter the resulting list by the ID of its owner; if present, the API will return only the jobs * submitted by the specified user. */ private StringEqualityPredicate owner; /** * Allows to filter the results by their {@link ValidationStatus}. */
private SetFilterPredicate<ValidationStatus> statuses;
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/common/iterables/IterableHelper.java
// Path: src/main/java/com/verifalia/api/common/ListingCursor.java // @Getter // @Setter // @ToString // public class ListingCursor extends ListingOptions { // private String cursor; // } // // Path: src/main/java/com/verifalia/api/common/ListingOptions.java // @Getter // @SuperBuilder // @NoArgsConstructor // public class ListingOptions { // /** // * The maximum number of items to return with a listing request. The Verifalia API may choose to override the specified // * limit if it is either too small or too big. Note: a single listing operation may automatically perform different // * listing requests to the Verifalia API: this value limits the number of items returned by *each* API request, not // * the overall total number of returned items. // */ // private Integer limit; // // /** // * The direction of the listing. // */ // @Builder.Default // private Direction direction = Direction.Forward; // // public void setLimit(final Integer limit) { // if (limit != null && limit < 0) { // throw new IllegalArgumentException("Limit must be 0 (meaning no limit will be enforced) or greater."); // } // // this.limit = limit; // } // // public void setDirection(@NonNull final Direction direction) { // this.direction = direction; // } // } // // Path: src/main/java/com/verifalia/api/common/models/ListSegment.java // @Getter // @Setter // @ToString // public abstract class ListSegment<T> { // /** // * The meta-data for this list segment. // */ // private ListSegmentMeta meta; // // /** // * The items of type <tt>T</tt> included in this segment. // */ // private List<T> data; // } // // Path: src/main/java/com/verifalia/api/exceptions/VerifaliaException.java // public class VerifaliaException extends Exception { // private RestResponse response; // // public VerifaliaException(@NonNull final RestResponse response) { // super(response.getStatusCode() + ": " + response.readAsString()); // this.response = response; // } // // public VerifaliaException(String errorMessage) { // super(errorMessage); // } // // public VerifaliaException(String message, Throwable cause) { // super(message, cause); // } // }
import com.verifalia.api.common.ListingCursor; import com.verifalia.api.common.ListingOptions; import com.verifalia.api.common.models.ListSegment; import com.verifalia.api.exceptions.VerifaliaException; import lombok.NonNull; import lombok.SneakyThrows; import java.util.Iterator; import java.util.NoSuchElementException;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.common.iterables; /** * Internal class used for keyset pagination against the Verifalia API. */ public class IterableHelper { public static <TItem, TOptions extends ListingOptions> Iterable<TItem> buildIterator(FirstSegmentFetcher<TItem, TOptions> firstSegmentFetcher, NextSegmentFetcher<TItem> nextSegmentFetcher,
// Path: src/main/java/com/verifalia/api/common/ListingCursor.java // @Getter // @Setter // @ToString // public class ListingCursor extends ListingOptions { // private String cursor; // } // // Path: src/main/java/com/verifalia/api/common/ListingOptions.java // @Getter // @SuperBuilder // @NoArgsConstructor // public class ListingOptions { // /** // * The maximum number of items to return with a listing request. The Verifalia API may choose to override the specified // * limit if it is either too small or too big. Note: a single listing operation may automatically perform different // * listing requests to the Verifalia API: this value limits the number of items returned by *each* API request, not // * the overall total number of returned items. // */ // private Integer limit; // // /** // * The direction of the listing. // */ // @Builder.Default // private Direction direction = Direction.Forward; // // public void setLimit(final Integer limit) { // if (limit != null && limit < 0) { // throw new IllegalArgumentException("Limit must be 0 (meaning no limit will be enforced) or greater."); // } // // this.limit = limit; // } // // public void setDirection(@NonNull final Direction direction) { // this.direction = direction; // } // } // // Path: src/main/java/com/verifalia/api/common/models/ListSegment.java // @Getter // @Setter // @ToString // public abstract class ListSegment<T> { // /** // * The meta-data for this list segment. // */ // private ListSegmentMeta meta; // // /** // * The items of type <tt>T</tt> included in this segment. // */ // private List<T> data; // } // // Path: src/main/java/com/verifalia/api/exceptions/VerifaliaException.java // public class VerifaliaException extends Exception { // private RestResponse response; // // public VerifaliaException(@NonNull final RestResponse response) { // super(response.getStatusCode() + ": " + response.readAsString()); // this.response = response; // } // // public VerifaliaException(String errorMessage) { // super(errorMessage); // } // // public VerifaliaException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/com/verifalia/api/common/iterables/IterableHelper.java import com.verifalia.api.common.ListingCursor; import com.verifalia.api.common.ListingOptions; import com.verifalia.api.common.models.ListSegment; import com.verifalia.api.exceptions.VerifaliaException; import lombok.NonNull; import lombok.SneakyThrows; import java.util.Iterator; import java.util.NoSuchElementException; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.common.iterables; /** * Internal class used for keyset pagination against the Verifalia API. */ public class IterableHelper { public static <TItem, TOptions extends ListingOptions> Iterable<TItem> buildIterator(FirstSegmentFetcher<TItem, TOptions> firstSegmentFetcher, NextSegmentFetcher<TItem> nextSegmentFetcher,
TOptions options) throws VerifaliaException {
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/common/iterables/IterableHelper.java
// Path: src/main/java/com/verifalia/api/common/ListingCursor.java // @Getter // @Setter // @ToString // public class ListingCursor extends ListingOptions { // private String cursor; // } // // Path: src/main/java/com/verifalia/api/common/ListingOptions.java // @Getter // @SuperBuilder // @NoArgsConstructor // public class ListingOptions { // /** // * The maximum number of items to return with a listing request. The Verifalia API may choose to override the specified // * limit if it is either too small or too big. Note: a single listing operation may automatically perform different // * listing requests to the Verifalia API: this value limits the number of items returned by *each* API request, not // * the overall total number of returned items. // */ // private Integer limit; // // /** // * The direction of the listing. // */ // @Builder.Default // private Direction direction = Direction.Forward; // // public void setLimit(final Integer limit) { // if (limit != null && limit < 0) { // throw new IllegalArgumentException("Limit must be 0 (meaning no limit will be enforced) or greater."); // } // // this.limit = limit; // } // // public void setDirection(@NonNull final Direction direction) { // this.direction = direction; // } // } // // Path: src/main/java/com/verifalia/api/common/models/ListSegment.java // @Getter // @Setter // @ToString // public abstract class ListSegment<T> { // /** // * The meta-data for this list segment. // */ // private ListSegmentMeta meta; // // /** // * The items of type <tt>T</tt> included in this segment. // */ // private List<T> data; // } // // Path: src/main/java/com/verifalia/api/exceptions/VerifaliaException.java // public class VerifaliaException extends Exception { // private RestResponse response; // // public VerifaliaException(@NonNull final RestResponse response) { // super(response.getStatusCode() + ": " + response.readAsString()); // this.response = response; // } // // public VerifaliaException(String errorMessage) { // super(errorMessage); // } // // public VerifaliaException(String message, Throwable cause) { // super(message, cause); // } // }
import com.verifalia.api.common.ListingCursor; import com.verifalia.api.common.ListingOptions; import com.verifalia.api.common.models.ListSegment; import com.verifalia.api.exceptions.VerifaliaException; import lombok.NonNull; import lombok.SneakyThrows; import java.util.Iterator; import java.util.NoSuchElementException;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.common.iterables; /** * Internal class used for keyset pagination against the Verifalia API. */ public class IterableHelper { public static <TItem, TOptions extends ListingOptions> Iterable<TItem> buildIterator(FirstSegmentFetcher<TItem, TOptions> firstSegmentFetcher, NextSegmentFetcher<TItem> nextSegmentFetcher, TOptions options) throws VerifaliaException {
// Path: src/main/java/com/verifalia/api/common/ListingCursor.java // @Getter // @Setter // @ToString // public class ListingCursor extends ListingOptions { // private String cursor; // } // // Path: src/main/java/com/verifalia/api/common/ListingOptions.java // @Getter // @SuperBuilder // @NoArgsConstructor // public class ListingOptions { // /** // * The maximum number of items to return with a listing request. The Verifalia API may choose to override the specified // * limit if it is either too small or too big. Note: a single listing operation may automatically perform different // * listing requests to the Verifalia API: this value limits the number of items returned by *each* API request, not // * the overall total number of returned items. // */ // private Integer limit; // // /** // * The direction of the listing. // */ // @Builder.Default // private Direction direction = Direction.Forward; // // public void setLimit(final Integer limit) { // if (limit != null && limit < 0) { // throw new IllegalArgumentException("Limit must be 0 (meaning no limit will be enforced) or greater."); // } // // this.limit = limit; // } // // public void setDirection(@NonNull final Direction direction) { // this.direction = direction; // } // } // // Path: src/main/java/com/verifalia/api/common/models/ListSegment.java // @Getter // @Setter // @ToString // public abstract class ListSegment<T> { // /** // * The meta-data for this list segment. // */ // private ListSegmentMeta meta; // // /** // * The items of type <tt>T</tt> included in this segment. // */ // private List<T> data; // } // // Path: src/main/java/com/verifalia/api/exceptions/VerifaliaException.java // public class VerifaliaException extends Exception { // private RestResponse response; // // public VerifaliaException(@NonNull final RestResponse response) { // super(response.getStatusCode() + ": " + response.readAsString()); // this.response = response; // } // // public VerifaliaException(String errorMessage) { // super(errorMessage); // } // // public VerifaliaException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/com/verifalia/api/common/iterables/IterableHelper.java import com.verifalia.api.common.ListingCursor; import com.verifalia.api.common.ListingOptions; import com.verifalia.api.common.models.ListSegment; import com.verifalia.api.exceptions.VerifaliaException; import lombok.NonNull; import lombok.SneakyThrows; import java.util.Iterator; import java.util.NoSuchElementException; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.common.iterables; /** * Internal class used for keyset pagination against the Verifalia API. */ public class IterableHelper { public static <TItem, TOptions extends ListingOptions> Iterable<TItem> buildIterator(FirstSegmentFetcher<TItem, TOptions> firstSegmentFetcher, NextSegmentFetcher<TItem> nextSegmentFetcher, TOptions options) throws VerifaliaException {
ListSegment<TItem> firstSegment = firstSegmentFetcher.fetch(options);
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/common/iterables/IterableHelper.java
// Path: src/main/java/com/verifalia/api/common/ListingCursor.java // @Getter // @Setter // @ToString // public class ListingCursor extends ListingOptions { // private String cursor; // } // // Path: src/main/java/com/verifalia/api/common/ListingOptions.java // @Getter // @SuperBuilder // @NoArgsConstructor // public class ListingOptions { // /** // * The maximum number of items to return with a listing request. The Verifalia API may choose to override the specified // * limit if it is either too small or too big. Note: a single listing operation may automatically perform different // * listing requests to the Verifalia API: this value limits the number of items returned by *each* API request, not // * the overall total number of returned items. // */ // private Integer limit; // // /** // * The direction of the listing. // */ // @Builder.Default // private Direction direction = Direction.Forward; // // public void setLimit(final Integer limit) { // if (limit != null && limit < 0) { // throw new IllegalArgumentException("Limit must be 0 (meaning no limit will be enforced) or greater."); // } // // this.limit = limit; // } // // public void setDirection(@NonNull final Direction direction) { // this.direction = direction; // } // } // // Path: src/main/java/com/verifalia/api/common/models/ListSegment.java // @Getter // @Setter // @ToString // public abstract class ListSegment<T> { // /** // * The meta-data for this list segment. // */ // private ListSegmentMeta meta; // // /** // * The items of type <tt>T</tt> included in this segment. // */ // private List<T> data; // } // // Path: src/main/java/com/verifalia/api/exceptions/VerifaliaException.java // public class VerifaliaException extends Exception { // private RestResponse response; // // public VerifaliaException(@NonNull final RestResponse response) { // super(response.getStatusCode() + ": " + response.readAsString()); // this.response = response; // } // // public VerifaliaException(String errorMessage) { // super(errorMessage); // } // // public VerifaliaException(String message, Throwable cause) { // super(message, cause); // } // }
import com.verifalia.api.common.ListingCursor; import com.verifalia.api.common.ListingOptions; import com.verifalia.api.common.models.ListSegment; import com.verifalia.api.exceptions.VerifaliaException; import lombok.NonNull; import lombok.SneakyThrows; import java.util.Iterator; import java.util.NoSuchElementException;
this.segment = segment; this.nextSegmentFetcher = nextSegmentFetcher; this.options = options; } @SneakyThrows @Override public boolean hasNext() { fetchNextSegmentIfNeeded(); return segment != null && (consumedInSegment < segment.getData().size()); } @SneakyThrows @Override public Object next() { fetchNextSegmentIfNeeded(); if (segment == null) { throw new NoSuchElementException(); } return segment.getData().get(consumedInSegment++); } private void fetchNextSegmentIfNeeded() throws VerifaliaException { if (consumedInSegment >= segment.getData().size()) { consumedInSegment = 0; if (segment.getMeta() != null && segment.getMeta().getIsTruncated()) {
// Path: src/main/java/com/verifalia/api/common/ListingCursor.java // @Getter // @Setter // @ToString // public class ListingCursor extends ListingOptions { // private String cursor; // } // // Path: src/main/java/com/verifalia/api/common/ListingOptions.java // @Getter // @SuperBuilder // @NoArgsConstructor // public class ListingOptions { // /** // * The maximum number of items to return with a listing request. The Verifalia API may choose to override the specified // * limit if it is either too small or too big. Note: a single listing operation may automatically perform different // * listing requests to the Verifalia API: this value limits the number of items returned by *each* API request, not // * the overall total number of returned items. // */ // private Integer limit; // // /** // * The direction of the listing. // */ // @Builder.Default // private Direction direction = Direction.Forward; // // public void setLimit(final Integer limit) { // if (limit != null && limit < 0) { // throw new IllegalArgumentException("Limit must be 0 (meaning no limit will be enforced) or greater."); // } // // this.limit = limit; // } // // public void setDirection(@NonNull final Direction direction) { // this.direction = direction; // } // } // // Path: src/main/java/com/verifalia/api/common/models/ListSegment.java // @Getter // @Setter // @ToString // public abstract class ListSegment<T> { // /** // * The meta-data for this list segment. // */ // private ListSegmentMeta meta; // // /** // * The items of type <tt>T</tt> included in this segment. // */ // private List<T> data; // } // // Path: src/main/java/com/verifalia/api/exceptions/VerifaliaException.java // public class VerifaliaException extends Exception { // private RestResponse response; // // public VerifaliaException(@NonNull final RestResponse response) { // super(response.getStatusCode() + ": " + response.readAsString()); // this.response = response; // } // // public VerifaliaException(String errorMessage) { // super(errorMessage); // } // // public VerifaliaException(String message, Throwable cause) { // super(message, cause); // } // } // Path: src/main/java/com/verifalia/api/common/iterables/IterableHelper.java import com.verifalia.api.common.ListingCursor; import com.verifalia.api.common.ListingOptions; import com.verifalia.api.common.models.ListSegment; import com.verifalia.api.exceptions.VerifaliaException; import lombok.NonNull; import lombok.SneakyThrows; import java.util.Iterator; import java.util.NoSuchElementException; this.segment = segment; this.nextSegmentFetcher = nextSegmentFetcher; this.options = options; } @SneakyThrows @Override public boolean hasNext() { fetchNextSegmentIfNeeded(); return segment != null && (consumedInSegment < segment.getData().size()); } @SneakyThrows @Override public Object next() { fetchNextSegmentIfNeeded(); if (segment == null) { throw new NoSuchElementException(); } return segment.getData().get(consumedInSegment++); } private void fetchNextSegmentIfNeeded() throws VerifaliaException { if (consumedInSegment >= segment.getData().size()) { consumedInSegment = 0; if (segment.getMeta() != null && segment.getMeta().getIsTruncated()) {
ListingCursor cursor = new ListingCursor();
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/emailvalidations/models/ValidationOverview.java
// Path: src/main/java/com/verifalia/api/common/serialization/DurationDeserializer.java // public class DurationDeserializer extends JsonDeserializer<Duration> { // @Override // public Duration deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { // String durationString = jsonParser.getText(); // // if (durationString == null) { // return null; // } // // return parseDuration(durationString); // } // // private Duration parseDuration(@NonNull String inputData) { // inputData = inputData.trim(); // // // Parse the eventual days information // // String[] dayFields = inputData.split("\\."); // // if (dayFields.length > 2) { // throw new IllegalArgumentException(); // } // // int days = 0; // String timeData = inputData; // // if (dayFields.length == 2) { // days = Integer.parseInt(dayFields[0]); // timeData = dayFields[1]; // } // // // Parse the time information // // String[] timeFields = timeData.split(":"); // // if (timeFields.length != 3) { // throw new IllegalArgumentException(); // } // // return Duration.ofSeconds((days * 24 * 60 * 60) + // (Integer.parseInt(timeFields[0]) * 60 * 60) + // (Integer.parseInt(timeFields[1]) * 60) + // (Integer.parseInt(timeFields[2]))); // } // } // // Path: src/main/java/com/verifalia/api/emailvalidations/serialization/QualityLevelNameDeserializer.java // public class QualityLevelNameDeserializer extends JsonDeserializer<QualityLevelName> { // @Override // public QualityLevelName deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // String qualityLevelNameString = jp.getText(); // // if (qualityLevelNameString == null) { // return null; // } // // return new QualityLevelName(qualityLevelNameString); // } // } // // Path: src/main/java/com/verifalia/api/emailvalidations/serialization/ValidationPriorityDeserializer.java // public class ValidationPriorityDeserializer extends JsonDeserializer<ValidationPriority> { // @Override // public ValidationPriority deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // String value = jp.getText(); // // if (value == null) { // return null; // } // // return new ValidationPriority(Byte.parseByte(value)); // } // }
import com.verifalia.api.common.serialization.DurationDeserializer; import com.verifalia.api.emailvalidations.serialization.QualityLevelNameDeserializer; import com.verifalia.api.emailvalidations.serialization.ValidationPriorityDeserializer; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.codehaus.jackson.map.annotate.JsonDeserialize; import java.time.Duration; import java.util.Date;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Overview information for a {@link Validation}. */ @Getter @Setter @ToString public class ValidationOverview { /** * The unique identifier for the validation job. */ private String id; /** * The processing {@link ValidationStatus} for the validation job. */ private ValidationStatus status; /** * An optional user-defined name for the validation job, for your own reference. */ private String name; /** * The unique ID of the Verifalia user who submitted the validation job. */ private String owner; /** * The IP address of the client which submitted the validation job. */ private String clientIP; /** * The eventual priority (speed) of the validation job, relative to the parent Verifalia account. In the event of an account * with many concurrent validation jobs, this value allows to increase the processing speed of a job with respect to the others. * The allowed range of values spans from {@link ValidationPriority#Lowest} (0 - lowest priority) to * {@link ValidationPriority#Highest} (255 - highest priority), where the midway value * {@link ValidationPriority#Normal} (127) means normal priority; if not specified, Verifalia processes all the * concurrent validation jobs for an account using the same priority. */
// Path: src/main/java/com/verifalia/api/common/serialization/DurationDeserializer.java // public class DurationDeserializer extends JsonDeserializer<Duration> { // @Override // public Duration deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { // String durationString = jsonParser.getText(); // // if (durationString == null) { // return null; // } // // return parseDuration(durationString); // } // // private Duration parseDuration(@NonNull String inputData) { // inputData = inputData.trim(); // // // Parse the eventual days information // // String[] dayFields = inputData.split("\\."); // // if (dayFields.length > 2) { // throw new IllegalArgumentException(); // } // // int days = 0; // String timeData = inputData; // // if (dayFields.length == 2) { // days = Integer.parseInt(dayFields[0]); // timeData = dayFields[1]; // } // // // Parse the time information // // String[] timeFields = timeData.split(":"); // // if (timeFields.length != 3) { // throw new IllegalArgumentException(); // } // // return Duration.ofSeconds((days * 24 * 60 * 60) + // (Integer.parseInt(timeFields[0]) * 60 * 60) + // (Integer.parseInt(timeFields[1]) * 60) + // (Integer.parseInt(timeFields[2]))); // } // } // // Path: src/main/java/com/verifalia/api/emailvalidations/serialization/QualityLevelNameDeserializer.java // public class QualityLevelNameDeserializer extends JsonDeserializer<QualityLevelName> { // @Override // public QualityLevelName deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // String qualityLevelNameString = jp.getText(); // // if (qualityLevelNameString == null) { // return null; // } // // return new QualityLevelName(qualityLevelNameString); // } // } // // Path: src/main/java/com/verifalia/api/emailvalidations/serialization/ValidationPriorityDeserializer.java // public class ValidationPriorityDeserializer extends JsonDeserializer<ValidationPriority> { // @Override // public ValidationPriority deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // String value = jp.getText(); // // if (value == null) { // return null; // } // // return new ValidationPriority(Byte.parseByte(value)); // } // } // Path: src/main/java/com/verifalia/api/emailvalidations/models/ValidationOverview.java import com.verifalia.api.common.serialization.DurationDeserializer; import com.verifalia.api.emailvalidations.serialization.QualityLevelNameDeserializer; import com.verifalia.api.emailvalidations.serialization.ValidationPriorityDeserializer; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.codehaus.jackson.map.annotate.JsonDeserialize; import java.time.Duration; import java.util.Date; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Overview information for a {@link Validation}. */ @Getter @Setter @ToString public class ValidationOverview { /** * The unique identifier for the validation job. */ private String id; /** * The processing {@link ValidationStatus} for the validation job. */ private ValidationStatus status; /** * An optional user-defined name for the validation job, for your own reference. */ private String name; /** * The unique ID of the Verifalia user who submitted the validation job. */ private String owner; /** * The IP address of the client which submitted the validation job. */ private String clientIP; /** * The eventual priority (speed) of the validation job, relative to the parent Verifalia account. In the event of an account * with many concurrent validation jobs, this value allows to increase the processing speed of a job with respect to the others. * The allowed range of values spans from {@link ValidationPriority#Lowest} (0 - lowest priority) to * {@link ValidationPriority#Highest} (255 - highest priority), where the midway value * {@link ValidationPriority#Normal} (127) means normal priority; if not specified, Verifalia processes all the * concurrent validation jobs for an account using the same priority. */
@JsonDeserialize(using = ValidationPriorityDeserializer.class)
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/emailvalidations/models/ValidationOverview.java
// Path: src/main/java/com/verifalia/api/common/serialization/DurationDeserializer.java // public class DurationDeserializer extends JsonDeserializer<Duration> { // @Override // public Duration deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { // String durationString = jsonParser.getText(); // // if (durationString == null) { // return null; // } // // return parseDuration(durationString); // } // // private Duration parseDuration(@NonNull String inputData) { // inputData = inputData.trim(); // // // Parse the eventual days information // // String[] dayFields = inputData.split("\\."); // // if (dayFields.length > 2) { // throw new IllegalArgumentException(); // } // // int days = 0; // String timeData = inputData; // // if (dayFields.length == 2) { // days = Integer.parseInt(dayFields[0]); // timeData = dayFields[1]; // } // // // Parse the time information // // String[] timeFields = timeData.split(":"); // // if (timeFields.length != 3) { // throw new IllegalArgumentException(); // } // // return Duration.ofSeconds((days * 24 * 60 * 60) + // (Integer.parseInt(timeFields[0]) * 60 * 60) + // (Integer.parseInt(timeFields[1]) * 60) + // (Integer.parseInt(timeFields[2]))); // } // } // // Path: src/main/java/com/verifalia/api/emailvalidations/serialization/QualityLevelNameDeserializer.java // public class QualityLevelNameDeserializer extends JsonDeserializer<QualityLevelName> { // @Override // public QualityLevelName deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // String qualityLevelNameString = jp.getText(); // // if (qualityLevelNameString == null) { // return null; // } // // return new QualityLevelName(qualityLevelNameString); // } // } // // Path: src/main/java/com/verifalia/api/emailvalidations/serialization/ValidationPriorityDeserializer.java // public class ValidationPriorityDeserializer extends JsonDeserializer<ValidationPriority> { // @Override // public ValidationPriority deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // String value = jp.getText(); // // if (value == null) { // return null; // } // // return new ValidationPriority(Byte.parseByte(value)); // } // }
import com.verifalia.api.common.serialization.DurationDeserializer; import com.verifalia.api.emailvalidations.serialization.QualityLevelNameDeserializer; import com.verifalia.api.emailvalidations.serialization.ValidationPriorityDeserializer; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.codehaus.jackson.map.annotate.JsonDeserialize; import java.time.Duration; import java.util.Date;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Overview information for a {@link Validation}. */ @Getter @Setter @ToString public class ValidationOverview { /** * The unique identifier for the validation job. */ private String id; /** * The processing {@link ValidationStatus} for the validation job. */ private ValidationStatus status; /** * An optional user-defined name for the validation job, for your own reference. */ private String name; /** * The unique ID of the Verifalia user who submitted the validation job. */ private String owner; /** * The IP address of the client which submitted the validation job. */ private String clientIP; /** * The eventual priority (speed) of the validation job, relative to the parent Verifalia account. In the event of an account * with many concurrent validation jobs, this value allows to increase the processing speed of a job with respect to the others. * The allowed range of values spans from {@link ValidationPriority#Lowest} (0 - lowest priority) to * {@link ValidationPriority#Highest} (255 - highest priority), where the midway value * {@link ValidationPriority#Normal} (127) means normal priority; if not specified, Verifalia processes all the * concurrent validation jobs for an account using the same priority. */ @JsonDeserialize(using = ValidationPriorityDeserializer.class) private ValidationPriority priority; /** * A reference to the quality level this job was validated against. */
// Path: src/main/java/com/verifalia/api/common/serialization/DurationDeserializer.java // public class DurationDeserializer extends JsonDeserializer<Duration> { // @Override // public Duration deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { // String durationString = jsonParser.getText(); // // if (durationString == null) { // return null; // } // // return parseDuration(durationString); // } // // private Duration parseDuration(@NonNull String inputData) { // inputData = inputData.trim(); // // // Parse the eventual days information // // String[] dayFields = inputData.split("\\."); // // if (dayFields.length > 2) { // throw new IllegalArgumentException(); // } // // int days = 0; // String timeData = inputData; // // if (dayFields.length == 2) { // days = Integer.parseInt(dayFields[0]); // timeData = dayFields[1]; // } // // // Parse the time information // // String[] timeFields = timeData.split(":"); // // if (timeFields.length != 3) { // throw new IllegalArgumentException(); // } // // return Duration.ofSeconds((days * 24 * 60 * 60) + // (Integer.parseInt(timeFields[0]) * 60 * 60) + // (Integer.parseInt(timeFields[1]) * 60) + // (Integer.parseInt(timeFields[2]))); // } // } // // Path: src/main/java/com/verifalia/api/emailvalidations/serialization/QualityLevelNameDeserializer.java // public class QualityLevelNameDeserializer extends JsonDeserializer<QualityLevelName> { // @Override // public QualityLevelName deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // String qualityLevelNameString = jp.getText(); // // if (qualityLevelNameString == null) { // return null; // } // // return new QualityLevelName(qualityLevelNameString); // } // } // // Path: src/main/java/com/verifalia/api/emailvalidations/serialization/ValidationPriorityDeserializer.java // public class ValidationPriorityDeserializer extends JsonDeserializer<ValidationPriority> { // @Override // public ValidationPriority deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // String value = jp.getText(); // // if (value == null) { // return null; // } // // return new ValidationPriority(Byte.parseByte(value)); // } // } // Path: src/main/java/com/verifalia/api/emailvalidations/models/ValidationOverview.java import com.verifalia.api.common.serialization.DurationDeserializer; import com.verifalia.api.emailvalidations.serialization.QualityLevelNameDeserializer; import com.verifalia.api.emailvalidations.serialization.ValidationPriorityDeserializer; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.codehaus.jackson.map.annotate.JsonDeserialize; import java.time.Duration; import java.util.Date; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Overview information for a {@link Validation}. */ @Getter @Setter @ToString public class ValidationOverview { /** * The unique identifier for the validation job. */ private String id; /** * The processing {@link ValidationStatus} for the validation job. */ private ValidationStatus status; /** * An optional user-defined name for the validation job, for your own reference. */ private String name; /** * The unique ID of the Verifalia user who submitted the validation job. */ private String owner; /** * The IP address of the client which submitted the validation job. */ private String clientIP; /** * The eventual priority (speed) of the validation job, relative to the parent Verifalia account. In the event of an account * with many concurrent validation jobs, this value allows to increase the processing speed of a job with respect to the others. * The allowed range of values spans from {@link ValidationPriority#Lowest} (0 - lowest priority) to * {@link ValidationPriority#Highest} (255 - highest priority), where the midway value * {@link ValidationPriority#Normal} (127) means normal priority; if not specified, Verifalia processes all the * concurrent validation jobs for an account using the same priority. */ @JsonDeserialize(using = ValidationPriorityDeserializer.class) private ValidationPriority priority; /** * A reference to the quality level this job was validated against. */
@JsonDeserialize(using = QualityLevelNameDeserializer.class)
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/emailvalidations/models/ValidationOverview.java
// Path: src/main/java/com/verifalia/api/common/serialization/DurationDeserializer.java // public class DurationDeserializer extends JsonDeserializer<Duration> { // @Override // public Duration deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { // String durationString = jsonParser.getText(); // // if (durationString == null) { // return null; // } // // return parseDuration(durationString); // } // // private Duration parseDuration(@NonNull String inputData) { // inputData = inputData.trim(); // // // Parse the eventual days information // // String[] dayFields = inputData.split("\\."); // // if (dayFields.length > 2) { // throw new IllegalArgumentException(); // } // // int days = 0; // String timeData = inputData; // // if (dayFields.length == 2) { // days = Integer.parseInt(dayFields[0]); // timeData = dayFields[1]; // } // // // Parse the time information // // String[] timeFields = timeData.split(":"); // // if (timeFields.length != 3) { // throw new IllegalArgumentException(); // } // // return Duration.ofSeconds((days * 24 * 60 * 60) + // (Integer.parseInt(timeFields[0]) * 60 * 60) + // (Integer.parseInt(timeFields[1]) * 60) + // (Integer.parseInt(timeFields[2]))); // } // } // // Path: src/main/java/com/verifalia/api/emailvalidations/serialization/QualityLevelNameDeserializer.java // public class QualityLevelNameDeserializer extends JsonDeserializer<QualityLevelName> { // @Override // public QualityLevelName deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // String qualityLevelNameString = jp.getText(); // // if (qualityLevelNameString == null) { // return null; // } // // return new QualityLevelName(qualityLevelNameString); // } // } // // Path: src/main/java/com/verifalia/api/emailvalidations/serialization/ValidationPriorityDeserializer.java // public class ValidationPriorityDeserializer extends JsonDeserializer<ValidationPriority> { // @Override // public ValidationPriority deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // String value = jp.getText(); // // if (value == null) { // return null; // } // // return new ValidationPriority(Byte.parseByte(value)); // } // }
import com.verifalia.api.common.serialization.DurationDeserializer; import com.verifalia.api.emailvalidations.serialization.QualityLevelNameDeserializer; import com.verifalia.api.emailvalidations.serialization.ValidationPriorityDeserializer; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.codehaus.jackson.map.annotate.JsonDeserialize; import java.time.Duration; import java.util.Date;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Overview information for a {@link Validation}. */ @Getter @Setter @ToString public class ValidationOverview { /** * The unique identifier for the validation job. */ private String id; /** * The processing {@link ValidationStatus} for the validation job. */ private ValidationStatus status; /** * An optional user-defined name for the validation job, for your own reference. */ private String name; /** * The unique ID of the Verifalia user who submitted the validation job. */ private String owner; /** * The IP address of the client which submitted the validation job. */ private String clientIP; /** * The eventual priority (speed) of the validation job, relative to the parent Verifalia account. In the event of an account * with many concurrent validation jobs, this value allows to increase the processing speed of a job with respect to the others. * The allowed range of values spans from {@link ValidationPriority#Lowest} (0 - lowest priority) to * {@link ValidationPriority#Highest} (255 - highest priority), where the midway value * {@link ValidationPriority#Normal} (127) means normal priority; if not specified, Verifalia processes all the * concurrent validation jobs for an account using the same priority. */ @JsonDeserialize(using = ValidationPriorityDeserializer.class) private ValidationPriority priority; /** * A reference to the quality level this job was validated against. */ @JsonDeserialize(using = QualityLevelNameDeserializer.class) private QualityLevelName quality; /** * A {@link DeduplicationMode} option which affected the way Verifalia eventually marked entries as duplicates upon * processing. */ private DeduplicationMode deduplication; /** * The number of entries the validation job contains. */ private Integer noOfEntries; /** * The eventual completion progress for the validation job. */ private ValidationProgress progress; /** * The maximum data retention period Verifalia observes for this verification job, after which the job will be * automatically deleted. * A verification job can be deleted anytime prior to its retention period through the * {@link com.verifalia.api.emailvalidations.EmailValidationsRestClient#delete(String)} method. */
// Path: src/main/java/com/verifalia/api/common/serialization/DurationDeserializer.java // public class DurationDeserializer extends JsonDeserializer<Duration> { // @Override // public Duration deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { // String durationString = jsonParser.getText(); // // if (durationString == null) { // return null; // } // // return parseDuration(durationString); // } // // private Duration parseDuration(@NonNull String inputData) { // inputData = inputData.trim(); // // // Parse the eventual days information // // String[] dayFields = inputData.split("\\."); // // if (dayFields.length > 2) { // throw new IllegalArgumentException(); // } // // int days = 0; // String timeData = inputData; // // if (dayFields.length == 2) { // days = Integer.parseInt(dayFields[0]); // timeData = dayFields[1]; // } // // // Parse the time information // // String[] timeFields = timeData.split(":"); // // if (timeFields.length != 3) { // throw new IllegalArgumentException(); // } // // return Duration.ofSeconds((days * 24 * 60 * 60) + // (Integer.parseInt(timeFields[0]) * 60 * 60) + // (Integer.parseInt(timeFields[1]) * 60) + // (Integer.parseInt(timeFields[2]))); // } // } // // Path: src/main/java/com/verifalia/api/emailvalidations/serialization/QualityLevelNameDeserializer.java // public class QualityLevelNameDeserializer extends JsonDeserializer<QualityLevelName> { // @Override // public QualityLevelName deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // String qualityLevelNameString = jp.getText(); // // if (qualityLevelNameString == null) { // return null; // } // // return new QualityLevelName(qualityLevelNameString); // } // } // // Path: src/main/java/com/verifalia/api/emailvalidations/serialization/ValidationPriorityDeserializer.java // public class ValidationPriorityDeserializer extends JsonDeserializer<ValidationPriority> { // @Override // public ValidationPriority deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // String value = jp.getText(); // // if (value == null) { // return null; // } // // return new ValidationPriority(Byte.parseByte(value)); // } // } // Path: src/main/java/com/verifalia/api/emailvalidations/models/ValidationOverview.java import com.verifalia.api.common.serialization.DurationDeserializer; import com.verifalia.api.emailvalidations.serialization.QualityLevelNameDeserializer; import com.verifalia.api.emailvalidations.serialization.ValidationPriorityDeserializer; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.codehaus.jackson.map.annotate.JsonDeserialize; import java.time.Duration; import java.util.Date; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations.models; /** * Overview information for a {@link Validation}. */ @Getter @Setter @ToString public class ValidationOverview { /** * The unique identifier for the validation job. */ private String id; /** * The processing {@link ValidationStatus} for the validation job. */ private ValidationStatus status; /** * An optional user-defined name for the validation job, for your own reference. */ private String name; /** * The unique ID of the Verifalia user who submitted the validation job. */ private String owner; /** * The IP address of the client which submitted the validation job. */ private String clientIP; /** * The eventual priority (speed) of the validation job, relative to the parent Verifalia account. In the event of an account * with many concurrent validation jobs, this value allows to increase the processing speed of a job with respect to the others. * The allowed range of values spans from {@link ValidationPriority#Lowest} (0 - lowest priority) to * {@link ValidationPriority#Highest} (255 - highest priority), where the midway value * {@link ValidationPriority#Normal} (127) means normal priority; if not specified, Verifalia processes all the * concurrent validation jobs for an account using the same priority. */ @JsonDeserialize(using = ValidationPriorityDeserializer.class) private ValidationPriority priority; /** * A reference to the quality level this job was validated against. */ @JsonDeserialize(using = QualityLevelNameDeserializer.class) private QualityLevelName quality; /** * A {@link DeduplicationMode} option which affected the way Verifalia eventually marked entries as duplicates upon * processing. */ private DeduplicationMode deduplication; /** * The number of entries the validation job contains. */ private Integer noOfEntries; /** * The eventual completion progress for the validation job. */ private ValidationProgress progress; /** * The maximum data retention period Verifalia observes for this verification job, after which the job will be * automatically deleted. * A verification job can be deleted anytime prior to its retention period through the * {@link com.verifalia.api.emailvalidations.EmailValidationsRestClient#delete(String)} method. */
@JsonDeserialize(using = DurationDeserializer.class)
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/emailvalidations/WaitingStrategy.java
// Path: src/main/java/com/verifalia/api/common/ProgressProvider.java // public interface ProgressProvider<T> { // /** // * Reports progress information of type <tt>T</tt> to a consumer. // * @param value The type of progress information. // */ // void report(@NonNull T value); // } // // Path: src/main/java/com/verifalia/api/emailvalidations/models/ValidationOverview.java // @Getter // @Setter // @ToString // public class ValidationOverview { // // /** // * The unique identifier for the validation job. // */ // private String id; // // /** // * The processing {@link ValidationStatus} for the validation job. // */ // private ValidationStatus status; // // /** // * An optional user-defined name for the validation job, for your own reference. // */ // private String name; // // /** // * The unique ID of the Verifalia user who submitted the validation job. // */ // private String owner; // // /** // * The IP address of the client which submitted the validation job. // */ // private String clientIP; // // /** // * The eventual priority (speed) of the validation job, relative to the parent Verifalia account. In the event of an account // * with many concurrent validation jobs, this value allows to increase the processing speed of a job with respect to the others. // * The allowed range of values spans from {@link ValidationPriority#Lowest} (0 - lowest priority) to // * {@link ValidationPriority#Highest} (255 - highest priority), where the midway value // * {@link ValidationPriority#Normal} (127) means normal priority; if not specified, Verifalia processes all the // * concurrent validation jobs for an account using the same priority. // */ // @JsonDeserialize(using = ValidationPriorityDeserializer.class) // private ValidationPriority priority; // // /** // * A reference to the quality level this job was validated against. // */ // @JsonDeserialize(using = QualityLevelNameDeserializer.class) // private QualityLevelName quality; // // /** // * A {@link DeduplicationMode} option which affected the way Verifalia eventually marked entries as duplicates upon // * processing. // */ // private DeduplicationMode deduplication; // // /** // * The number of entries the validation job contains. // */ // private Integer noOfEntries; // // /** // * The eventual completion progress for the validation job. // */ // private ValidationProgress progress; // // /** // * The maximum data retention period Verifalia observes for this verification job, after which the job will be // * automatically deleted. // * A verification job can be deleted anytime prior to its retention period through the // * {@link com.verifalia.api.emailvalidations.EmailValidationsRestClient#delete(String)} method. // */ // @JsonDeserialize(using = DurationDeserializer.class) // private Duration retention; // // /** // * The date and time this validation job has been submitted to Verifalia. // */ // private Date submittedOn; // // /** // * The date and time the validation job was created. // */ // private Date createdOn; // // /** // * The date and time this validation job has been eventually completed. // */ // private Date completedOn; // } // // Path: src/main/java/com/verifalia/api/emailvalidations/models/ValidationProgress.java // @Getter // @Setter // @ToString // public class ValidationProgress { // // /** // * The percentage of completed entries, ranging from 0 to 1. // */ // private Double percentage; // // /** // * An eventual estimated required time span needed to complete the whole job. // */ // @JsonDeserialize(using = DurationDeserializer.class) // private Duration estimatedTimeRemaining; // }
import com.verifalia.api.common.ProgressProvider; import com.verifalia.api.emailvalidations.models.ValidationOverview; import com.verifalia.api.emailvalidations.models.ValidationProgress; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import java.time.Duration;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations; /** * A strategy to use while waiting for the completion of an email validation job. */ @Getter public class WaitingStrategy { /** * Gets a value that controls whether to wait for the completion of an email validation job. */ boolean waitForCompletion; /** * Gets a {@link ProgressProvider} instance which eventually receives completion progress updates for an email * validation job. */
// Path: src/main/java/com/verifalia/api/common/ProgressProvider.java // public interface ProgressProvider<T> { // /** // * Reports progress information of type <tt>T</tt> to a consumer. // * @param value The type of progress information. // */ // void report(@NonNull T value); // } // // Path: src/main/java/com/verifalia/api/emailvalidations/models/ValidationOverview.java // @Getter // @Setter // @ToString // public class ValidationOverview { // // /** // * The unique identifier for the validation job. // */ // private String id; // // /** // * The processing {@link ValidationStatus} for the validation job. // */ // private ValidationStatus status; // // /** // * An optional user-defined name for the validation job, for your own reference. // */ // private String name; // // /** // * The unique ID of the Verifalia user who submitted the validation job. // */ // private String owner; // // /** // * The IP address of the client which submitted the validation job. // */ // private String clientIP; // // /** // * The eventual priority (speed) of the validation job, relative to the parent Verifalia account. In the event of an account // * with many concurrent validation jobs, this value allows to increase the processing speed of a job with respect to the others. // * The allowed range of values spans from {@link ValidationPriority#Lowest} (0 - lowest priority) to // * {@link ValidationPriority#Highest} (255 - highest priority), where the midway value // * {@link ValidationPriority#Normal} (127) means normal priority; if not specified, Verifalia processes all the // * concurrent validation jobs for an account using the same priority. // */ // @JsonDeserialize(using = ValidationPriorityDeserializer.class) // private ValidationPriority priority; // // /** // * A reference to the quality level this job was validated against. // */ // @JsonDeserialize(using = QualityLevelNameDeserializer.class) // private QualityLevelName quality; // // /** // * A {@link DeduplicationMode} option which affected the way Verifalia eventually marked entries as duplicates upon // * processing. // */ // private DeduplicationMode deduplication; // // /** // * The number of entries the validation job contains. // */ // private Integer noOfEntries; // // /** // * The eventual completion progress for the validation job. // */ // private ValidationProgress progress; // // /** // * The maximum data retention period Verifalia observes for this verification job, after which the job will be // * automatically deleted. // * A verification job can be deleted anytime prior to its retention period through the // * {@link com.verifalia.api.emailvalidations.EmailValidationsRestClient#delete(String)} method. // */ // @JsonDeserialize(using = DurationDeserializer.class) // private Duration retention; // // /** // * The date and time this validation job has been submitted to Verifalia. // */ // private Date submittedOn; // // /** // * The date and time the validation job was created. // */ // private Date createdOn; // // /** // * The date and time this validation job has been eventually completed. // */ // private Date completedOn; // } // // Path: src/main/java/com/verifalia/api/emailvalidations/models/ValidationProgress.java // @Getter // @Setter // @ToString // public class ValidationProgress { // // /** // * The percentage of completed entries, ranging from 0 to 1. // */ // private Double percentage; // // /** // * An eventual estimated required time span needed to complete the whole job. // */ // @JsonDeserialize(using = DurationDeserializer.class) // private Duration estimatedTimeRemaining; // } // Path: src/main/java/com/verifalia/api/emailvalidations/WaitingStrategy.java import com.verifalia.api.common.ProgressProvider; import com.verifalia.api.emailvalidations.models.ValidationOverview; import com.verifalia.api.emailvalidations.models.ValidationProgress; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import java.time.Duration; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations; /** * A strategy to use while waiting for the completion of an email validation job. */ @Getter public class WaitingStrategy { /** * Gets a value that controls whether to wait for the completion of an email validation job. */ boolean waitForCompletion; /** * Gets a {@link ProgressProvider} instance which eventually receives completion progress updates for an email * validation job. */
ProgressProvider<ValidationOverview> progressProvider;
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/emailvalidations/WaitingStrategy.java
// Path: src/main/java/com/verifalia/api/common/ProgressProvider.java // public interface ProgressProvider<T> { // /** // * Reports progress information of type <tt>T</tt> to a consumer. // * @param value The type of progress information. // */ // void report(@NonNull T value); // } // // Path: src/main/java/com/verifalia/api/emailvalidations/models/ValidationOverview.java // @Getter // @Setter // @ToString // public class ValidationOverview { // // /** // * The unique identifier for the validation job. // */ // private String id; // // /** // * The processing {@link ValidationStatus} for the validation job. // */ // private ValidationStatus status; // // /** // * An optional user-defined name for the validation job, for your own reference. // */ // private String name; // // /** // * The unique ID of the Verifalia user who submitted the validation job. // */ // private String owner; // // /** // * The IP address of the client which submitted the validation job. // */ // private String clientIP; // // /** // * The eventual priority (speed) of the validation job, relative to the parent Verifalia account. In the event of an account // * with many concurrent validation jobs, this value allows to increase the processing speed of a job with respect to the others. // * The allowed range of values spans from {@link ValidationPriority#Lowest} (0 - lowest priority) to // * {@link ValidationPriority#Highest} (255 - highest priority), where the midway value // * {@link ValidationPriority#Normal} (127) means normal priority; if not specified, Verifalia processes all the // * concurrent validation jobs for an account using the same priority. // */ // @JsonDeserialize(using = ValidationPriorityDeserializer.class) // private ValidationPriority priority; // // /** // * A reference to the quality level this job was validated against. // */ // @JsonDeserialize(using = QualityLevelNameDeserializer.class) // private QualityLevelName quality; // // /** // * A {@link DeduplicationMode} option which affected the way Verifalia eventually marked entries as duplicates upon // * processing. // */ // private DeduplicationMode deduplication; // // /** // * The number of entries the validation job contains. // */ // private Integer noOfEntries; // // /** // * The eventual completion progress for the validation job. // */ // private ValidationProgress progress; // // /** // * The maximum data retention period Verifalia observes for this verification job, after which the job will be // * automatically deleted. // * A verification job can be deleted anytime prior to its retention period through the // * {@link com.verifalia.api.emailvalidations.EmailValidationsRestClient#delete(String)} method. // */ // @JsonDeserialize(using = DurationDeserializer.class) // private Duration retention; // // /** // * The date and time this validation job has been submitted to Verifalia. // */ // private Date submittedOn; // // /** // * The date and time the validation job was created. // */ // private Date createdOn; // // /** // * The date and time this validation job has been eventually completed. // */ // private Date completedOn; // } // // Path: src/main/java/com/verifalia/api/emailvalidations/models/ValidationProgress.java // @Getter // @Setter // @ToString // public class ValidationProgress { // // /** // * The percentage of completed entries, ranging from 0 to 1. // */ // private Double percentage; // // /** // * An eventual estimated required time span needed to complete the whole job. // */ // @JsonDeserialize(using = DurationDeserializer.class) // private Duration estimatedTimeRemaining; // }
import com.verifalia.api.common.ProgressProvider; import com.verifalia.api.emailvalidations.models.ValidationOverview; import com.verifalia.api.emailvalidations.models.ValidationProgress; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import java.time.Duration;
/* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations; /** * A strategy to use while waiting for the completion of an email validation job. */ @Getter public class WaitingStrategy { /** * Gets a value that controls whether to wait for the completion of an email validation job. */ boolean waitForCompletion; /** * Gets a {@link ProgressProvider} instance which eventually receives completion progress updates for an email * validation job. */
// Path: src/main/java/com/verifalia/api/common/ProgressProvider.java // public interface ProgressProvider<T> { // /** // * Reports progress information of type <tt>T</tt> to a consumer. // * @param value The type of progress information. // */ // void report(@NonNull T value); // } // // Path: src/main/java/com/verifalia/api/emailvalidations/models/ValidationOverview.java // @Getter // @Setter // @ToString // public class ValidationOverview { // // /** // * The unique identifier for the validation job. // */ // private String id; // // /** // * The processing {@link ValidationStatus} for the validation job. // */ // private ValidationStatus status; // // /** // * An optional user-defined name for the validation job, for your own reference. // */ // private String name; // // /** // * The unique ID of the Verifalia user who submitted the validation job. // */ // private String owner; // // /** // * The IP address of the client which submitted the validation job. // */ // private String clientIP; // // /** // * The eventual priority (speed) of the validation job, relative to the parent Verifalia account. In the event of an account // * with many concurrent validation jobs, this value allows to increase the processing speed of a job with respect to the others. // * The allowed range of values spans from {@link ValidationPriority#Lowest} (0 - lowest priority) to // * {@link ValidationPriority#Highest} (255 - highest priority), where the midway value // * {@link ValidationPriority#Normal} (127) means normal priority; if not specified, Verifalia processes all the // * concurrent validation jobs for an account using the same priority. // */ // @JsonDeserialize(using = ValidationPriorityDeserializer.class) // private ValidationPriority priority; // // /** // * A reference to the quality level this job was validated against. // */ // @JsonDeserialize(using = QualityLevelNameDeserializer.class) // private QualityLevelName quality; // // /** // * A {@link DeduplicationMode} option which affected the way Verifalia eventually marked entries as duplicates upon // * processing. // */ // private DeduplicationMode deduplication; // // /** // * The number of entries the validation job contains. // */ // private Integer noOfEntries; // // /** // * The eventual completion progress for the validation job. // */ // private ValidationProgress progress; // // /** // * The maximum data retention period Verifalia observes for this verification job, after which the job will be // * automatically deleted. // * A verification job can be deleted anytime prior to its retention period through the // * {@link com.verifalia.api.emailvalidations.EmailValidationsRestClient#delete(String)} method. // */ // @JsonDeserialize(using = DurationDeserializer.class) // private Duration retention; // // /** // * The date and time this validation job has been submitted to Verifalia. // */ // private Date submittedOn; // // /** // * The date and time the validation job was created. // */ // private Date createdOn; // // /** // * The date and time this validation job has been eventually completed. // */ // private Date completedOn; // } // // Path: src/main/java/com/verifalia/api/emailvalidations/models/ValidationProgress.java // @Getter // @Setter // @ToString // public class ValidationProgress { // // /** // * The percentage of completed entries, ranging from 0 to 1. // */ // private Double percentage; // // /** // * An eventual estimated required time span needed to complete the whole job. // */ // @JsonDeserialize(using = DurationDeserializer.class) // private Duration estimatedTimeRemaining; // } // Path: src/main/java/com/verifalia/api/emailvalidations/WaitingStrategy.java import com.verifalia.api.common.ProgressProvider; import com.verifalia.api.emailvalidations.models.ValidationOverview; import com.verifalia.api.emailvalidations.models.ValidationProgress; import lombok.Getter; import lombok.NonNull; import lombok.Setter; import java.time.Duration; /* * Verifalia - Email list cleaning and real-time email verification service * https://verifalia.com/ * [email protected] * * Copyright (c) 2005-2020 Cobisi Research * * Cobisi Research * Via Prima Strada, 35 * 35129, Padova * Italy - European Union * * 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. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.verifalia.api.emailvalidations; /** * A strategy to use while waiting for the completion of an email validation job. */ @Getter public class WaitingStrategy { /** * Gets a value that controls whether to wait for the completion of an email validation job. */ boolean waitForCompletion; /** * Gets a {@link ProgressProvider} instance which eventually receives completion progress updates for an email * validation job. */
ProgressProvider<ValidationOverview> progressProvider;
verifalia/verifalia-java-sdk
src/main/java/com/verifalia/api/rest/security/ClientCertificateAuthenticationProvider.java
// Path: src/main/java/com/verifalia/api/rest/RestClient.java // public class RestClient { // private final List<URI> baseURIs; // private final String apiVersion; // private final String userAgent; // private final AuthenticationProvider defaultAuthenticationProvider; // private int currentBaseURIIndex; // // public RestClient(@NonNull final AuthenticationProvider defaultAuthenticationProvider, @NonNull final List<URI> baseURIs, @NonNull final String apiVersion) { // this.baseURIs = baseURIs; // this.apiVersion = apiVersion; // this.userAgent = getUserAgent(); // this.defaultAuthenticationProvider = defaultAuthenticationProvider; // } // // public RestResponse execute(@NonNull final RestRequest request) throws VerifaliaException { // return execute(request, this.defaultAuthenticationProvider); // } // // public RestResponse execute(@NonNull final RestRequest request, @NonNull final AuthenticationProvider authenticationProvider) // throws VerifaliaException { // @Getter // @Setter // class EndpointServerError { // URI baseUri; // Exception exception; // // EndpointServerError(@NonNull final URI baseUri, @NonNull final Exception exception) { // this.setBaseUri(baseUri); // this.setException(exception); // } // } // // ArrayList<EndpointServerError> errors = new ArrayList<>(); // // if (nonNull(this.baseURIs)) { // for (int idxAttempt = 0; idxAttempt < this.baseURIs.size(); idxAttempt++) { // CloseableHttpResponse response; // URI baseURI = this.baseURIs.get(currentBaseURIIndex++ % this.baseURIs.size()); // // try { // response = sendRequest(baseURI, request, authenticationProvider); // } catch (IOException e) { // // Continue with the next attempt on IO exceptions, if needed // errors.add(new EndpointServerError(baseURI, e)); // continue; // } // // if (nonNull(response)) { // int statusCode = response.getStatusLine().getStatusCode(); // // // Automatically retry with another host on HTTP 5xx status codes // // if (statusCode >= 500 && statusCode <= 599) { // errors.add(new EndpointServerError(baseURI, new EndpointServerErrorException(String.format("The API endpoint %s returned a server error HTTP status code %d.", baseURI, statusCode)))); // continue; // } // // return new RestResponse(statusCode, response.getEntity()); // } // } // } // // // Aggregate exception // // StringBuilder sbAggregateError = new StringBuilder("All the base URIs are unreachable: "); // errors.forEach(e -> sbAggregateError.append(e.baseUri).append(" => ").append(e.exception.getMessage()).append(" ")); // // throw new ServiceUnreachableException(sbAggregateError.toString()); // } // // private CloseableHttpResponse sendRequest(@NonNull final URI baseURI, @NonNull final RestRequest restRequest, @NonNull final AuthenticationProvider authenticationProviderOverride) // throws VerifaliaException, IOException { // // // Determine the intermediate URI, including the API version, for this invocation // // StringBuilder sbApiVersionURI = new StringBuilder(); // sbApiVersionURI.append(baseURI.toString()).append("/").append(apiVersion).append("/"); // // URI apiVersionURI; // // try { // apiVersionURI = new URI(sbApiVersionURI.toString()); // } catch (URISyntaxException e) { // throw new IOException("Invalid URI " + sbApiVersionURI); // } // // // Build the HTTP client and the HTTP request out of the provided RestRequest // // CloseableHttpClient client = authenticationProviderOverride.buildClient(this); // HttpRequestBase request = restRequest.buildHttpRequest(apiVersionURI); // // // Common headers and authentication handling // // request.setHeader(HttpHeaders.USER_AGENT, this.userAgent); // authenticationProviderOverride.decorateRequest(this, request); // // return client.execute(request); // } // // private String getUserAgent() { // StringBuilder sbUserAgent = new StringBuilder("verifalia-rest-client/java"); // // // Java version // // sbUserAgent.append(System.getProperty("java.version")); // // // Package version // // String packageVersion = getClass().getPackage().getImplementationVersion(); // // if (packageVersion != null) { // sbUserAgent.append("/"); // sbUserAgent.append(packageVersion); // } // // return sbUserAgent.toString(); // } // }
import com.verifalia.api.rest.RestClient; import lombok.Getter; import lombok.Setter; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContexts; import javax.net.ssl.SSLContext; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.KeyStore; import static java.util.Objects.nonNull;
// Load identity key store KeyStore identityKeyStore = KeyStore.getInstance(TLS_AUTHENTICATION_JKS); FileInputStream identityKeyStoreFile = new FileInputStream(identityStoreJksFile); identityKeyStore.load(identityKeyStoreFile, certPassword.toCharArray()); // Load trust key store KeyStore trustKeyStore = KeyStore.getInstance(TLS_AUTHENTICATION_JKS); FileInputStream trustKeyStoreFile = new FileInputStream(trustKeyStoreJksFile); trustKeyStore.load(trustKeyStoreFile, certPassword.toCharArray()); // Load SSL context SSLContext sslContext = SSLContexts .custom() .loadKeyMaterial(identityKeyStore, certPassword.toCharArray(), (aliases, socket) -> certAlias) .loadTrustMaterial(trustKeyStore, null) .build(); // Initialize socket factory return new SSLConnectionSocketFactory(sslContext, new String[]{ "TLSv1.1", "TLSv1.2" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); } @Override
// Path: src/main/java/com/verifalia/api/rest/RestClient.java // public class RestClient { // private final List<URI> baseURIs; // private final String apiVersion; // private final String userAgent; // private final AuthenticationProvider defaultAuthenticationProvider; // private int currentBaseURIIndex; // // public RestClient(@NonNull final AuthenticationProvider defaultAuthenticationProvider, @NonNull final List<URI> baseURIs, @NonNull final String apiVersion) { // this.baseURIs = baseURIs; // this.apiVersion = apiVersion; // this.userAgent = getUserAgent(); // this.defaultAuthenticationProvider = defaultAuthenticationProvider; // } // // public RestResponse execute(@NonNull final RestRequest request) throws VerifaliaException { // return execute(request, this.defaultAuthenticationProvider); // } // // public RestResponse execute(@NonNull final RestRequest request, @NonNull final AuthenticationProvider authenticationProvider) // throws VerifaliaException { // @Getter // @Setter // class EndpointServerError { // URI baseUri; // Exception exception; // // EndpointServerError(@NonNull final URI baseUri, @NonNull final Exception exception) { // this.setBaseUri(baseUri); // this.setException(exception); // } // } // // ArrayList<EndpointServerError> errors = new ArrayList<>(); // // if (nonNull(this.baseURIs)) { // for (int idxAttempt = 0; idxAttempt < this.baseURIs.size(); idxAttempt++) { // CloseableHttpResponse response; // URI baseURI = this.baseURIs.get(currentBaseURIIndex++ % this.baseURIs.size()); // // try { // response = sendRequest(baseURI, request, authenticationProvider); // } catch (IOException e) { // // Continue with the next attempt on IO exceptions, if needed // errors.add(new EndpointServerError(baseURI, e)); // continue; // } // // if (nonNull(response)) { // int statusCode = response.getStatusLine().getStatusCode(); // // // Automatically retry with another host on HTTP 5xx status codes // // if (statusCode >= 500 && statusCode <= 599) { // errors.add(new EndpointServerError(baseURI, new EndpointServerErrorException(String.format("The API endpoint %s returned a server error HTTP status code %d.", baseURI, statusCode)))); // continue; // } // // return new RestResponse(statusCode, response.getEntity()); // } // } // } // // // Aggregate exception // // StringBuilder sbAggregateError = new StringBuilder("All the base URIs are unreachable: "); // errors.forEach(e -> sbAggregateError.append(e.baseUri).append(" => ").append(e.exception.getMessage()).append(" ")); // // throw new ServiceUnreachableException(sbAggregateError.toString()); // } // // private CloseableHttpResponse sendRequest(@NonNull final URI baseURI, @NonNull final RestRequest restRequest, @NonNull final AuthenticationProvider authenticationProviderOverride) // throws VerifaliaException, IOException { // // // Determine the intermediate URI, including the API version, for this invocation // // StringBuilder sbApiVersionURI = new StringBuilder(); // sbApiVersionURI.append(baseURI.toString()).append("/").append(apiVersion).append("/"); // // URI apiVersionURI; // // try { // apiVersionURI = new URI(sbApiVersionURI.toString()); // } catch (URISyntaxException e) { // throw new IOException("Invalid URI " + sbApiVersionURI); // } // // // Build the HTTP client and the HTTP request out of the provided RestRequest // // CloseableHttpClient client = authenticationProviderOverride.buildClient(this); // HttpRequestBase request = restRequest.buildHttpRequest(apiVersionURI); // // // Common headers and authentication handling // // request.setHeader(HttpHeaders.USER_AGENT, this.userAgent); // authenticationProviderOverride.decorateRequest(this, request); // // return client.execute(request); // } // // private String getUserAgent() { // StringBuilder sbUserAgent = new StringBuilder("verifalia-rest-client/java"); // // // Java version // // sbUserAgent.append(System.getProperty("java.version")); // // // Package version // // String packageVersion = getClass().getPackage().getImplementationVersion(); // // if (packageVersion != null) { // sbUserAgent.append("/"); // sbUserAgent.append(packageVersion); // } // // return sbUserAgent.toString(); // } // } // Path: src/main/java/com/verifalia/api/rest/security/ClientCertificateAuthenticationProvider.java import com.verifalia.api.rest.RestClient; import lombok.Getter; import lombok.Setter; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContexts; import javax.net.ssl.SSLContext; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.KeyStore; import static java.util.Objects.nonNull; // Load identity key store KeyStore identityKeyStore = KeyStore.getInstance(TLS_AUTHENTICATION_JKS); FileInputStream identityKeyStoreFile = new FileInputStream(identityStoreJksFile); identityKeyStore.load(identityKeyStoreFile, certPassword.toCharArray()); // Load trust key store KeyStore trustKeyStore = KeyStore.getInstance(TLS_AUTHENTICATION_JKS); FileInputStream trustKeyStoreFile = new FileInputStream(trustKeyStoreJksFile); trustKeyStore.load(trustKeyStoreFile, certPassword.toCharArray()); // Load SSL context SSLContext sslContext = SSLContexts .custom() .loadKeyMaterial(identityKeyStore, certPassword.toCharArray(), (aliases, socket) -> certAlias) .loadTrustMaterial(trustKeyStore, null) .build(); // Initialize socket factory return new SSLConnectionSocketFactory(sslContext, new String[]{ "TLSv1.1", "TLSv1.2" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); } @Override
public CloseableHttpClient buildClient(RestClient client) throws IOException {
nowucca/SimpleAffableBean
src/main/java/controller/admin/AdminSessionServlet.java
// Path: src/main/java/viewmodel/admin/AdminSessionViewModel.java // public class AdminSessionViewModel extends BaseAdminViewModel { // // private Date creationTime; // private Date lastAccessedTime; // // private ShoppingCart cart; // private Map<String, Object> sessionAttributes; // // // public AdminSessionViewModel(HttpServletRequest request) { // super(request); // // this.creationTime = new Date(session.getCreationTime()); // this.lastAccessedTime = new Date(session.getLastAccessedTime()); // this.cart = (ShoppingCart) session.getAttribute("cart"); // // this.sessionAttributes = new LinkedHashMap<>(); // final Enumeration<String> attributeNames = session.getAttributeNames(); // while (attributeNames.hasMoreElements()) { // String attributeName = attributeNames.nextElement(); // sessionAttributes.put(attributeName, session.getAttribute(attributeName)); // } // // } // // public Date getCreationTime() { // return creationTime; // } // // public Date getLastAccessedTime() { // return lastAccessedTime; // } // // public ShoppingCart getCart() { // return cart; // } // // public Map<String, Object> getSessionAttributes() { // return sessionAttributes; // } // // }
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.HttpConstraint; import javax.servlet.annotation.ServletSecurity; import javax.servlet.annotation.ServletSecurity.TransportGuarantee; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import viewmodel.admin.AdminSessionViewModel;
/** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package controller.admin; /** * */ @WebServlet(name = "AdminSessionServlet", urlPatterns = {"/admin/session"}) @ServletSecurity( @HttpConstraint(transportGuarantee = TransportGuarantee.CONFIDENTIAL, rolesAllowed = {"simpleAffableBeanAdmin"}) ) public class AdminSessionServlet extends AdminServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Path: src/main/java/viewmodel/admin/AdminSessionViewModel.java // public class AdminSessionViewModel extends BaseAdminViewModel { // // private Date creationTime; // private Date lastAccessedTime; // // private ShoppingCart cart; // private Map<String, Object> sessionAttributes; // // // public AdminSessionViewModel(HttpServletRequest request) { // super(request); // // this.creationTime = new Date(session.getCreationTime()); // this.lastAccessedTime = new Date(session.getLastAccessedTime()); // this.cart = (ShoppingCart) session.getAttribute("cart"); // // this.sessionAttributes = new LinkedHashMap<>(); // final Enumeration<String> attributeNames = session.getAttributeNames(); // while (attributeNames.hasMoreElements()) { // String attributeName = attributeNames.nextElement(); // sessionAttributes.put(attributeName, session.getAttribute(attributeName)); // } // // } // // public Date getCreationTime() { // return creationTime; // } // // public Date getLastAccessedTime() { // return lastAccessedTime; // } // // public ShoppingCart getCart() { // return cart; // } // // public Map<String, Object> getSessionAttributes() { // return sessionAttributes; // } // // } // Path: src/main/java/controller/admin/AdminSessionServlet.java import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.HttpConstraint; import javax.servlet.annotation.ServletSecurity; import javax.servlet.annotation.ServletSecurity.TransportGuarantee; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import viewmodel.admin.AdminSessionViewModel; /** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package controller.admin; /** * */ @WebServlet(name = "AdminSessionServlet", urlPatterns = {"/admin/session"}) @ServletSecurity( @HttpConstraint(transportGuarantee = TransportGuarantee.CONFIDENTIAL, rolesAllowed = {"simpleAffableBeanAdmin"}) ) public class AdminSessionServlet extends AdminServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("p", new AdminSessionViewModel(request));
nowucca/SimpleAffableBean
src/main/java/business/product/ProductDaoJdbc.java
// Path: src/main/java/business/SimpleAffableDbException.java // public static class SimpleAffableQueryDbException extends SimpleAffableDbException { // public SimpleAffableQueryDbException(String message) { // super(message); // } // // public SimpleAffableQueryDbException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/business/JdbcUtils.java // public static Connection getConnection() { // if (dataSource == null) { // dataSource = getDataSource(JDBC_SIMPLEAFFABLEBEAN); // } // // try { // return dataSource.getConnection(); // } catch (SQLException e) { // throw new SimpleAffableConnectionDbException("Encountered a SQL issue getting a connection", e); // } // // }
import business.SimpleAffableDbException.SimpleAffableQueryDbException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import static business.JdbcUtils.getConnection;
/** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package business.product; /** */ public class ProductDaoJdbc implements ProductDao { private static final String FIND_BY_CATEGORY_SQL = "SELECT " + "p.product_id, " + "p.category_id, " + "p.name, " + "p.price, " + "p.last_update " + "FROM " + "product p " + "WHERE " + "p.category_id = ?"; private static final String FIND_BY_PRODUCT_ID_SQL = "SELECT " + " p.product_id, " + " p.category_id, " + " p.name, " + " p.price, " + " p.last_update " + "FROM " + " product p " + "WHERE " + "p.product_id = ?"; @Override public List<Product> findByCategoryId(long categoryId) { List<Product> result = new ArrayList<>(16);
// Path: src/main/java/business/SimpleAffableDbException.java // public static class SimpleAffableQueryDbException extends SimpleAffableDbException { // public SimpleAffableQueryDbException(String message) { // super(message); // } // // public SimpleAffableQueryDbException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/business/JdbcUtils.java // public static Connection getConnection() { // if (dataSource == null) { // dataSource = getDataSource(JDBC_SIMPLEAFFABLEBEAN); // } // // try { // return dataSource.getConnection(); // } catch (SQLException e) { // throw new SimpleAffableConnectionDbException("Encountered a SQL issue getting a connection", e); // } // // } // Path: src/main/java/business/product/ProductDaoJdbc.java import business.SimpleAffableDbException.SimpleAffableQueryDbException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import static business.JdbcUtils.getConnection; /** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package business.product; /** */ public class ProductDaoJdbc implements ProductDao { private static final String FIND_BY_CATEGORY_SQL = "SELECT " + "p.product_id, " + "p.category_id, " + "p.name, " + "p.price, " + "p.last_update " + "FROM " + "product p " + "WHERE " + "p.category_id = ?"; private static final String FIND_BY_PRODUCT_ID_SQL = "SELECT " + " p.product_id, " + " p.category_id, " + " p.name, " + " p.price, " + " p.last_update " + "FROM " + " product p " + "WHERE " + "p.product_id = ?"; @Override public List<Product> findByCategoryId(long categoryId) { List<Product> result = new ArrayList<>(16);
try (Connection connection = getConnection();
nowucca/SimpleAffableBean
src/main/java/business/product/ProductDaoJdbc.java
// Path: src/main/java/business/SimpleAffableDbException.java // public static class SimpleAffableQueryDbException extends SimpleAffableDbException { // public SimpleAffableQueryDbException(String message) { // super(message); // } // // public SimpleAffableQueryDbException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/business/JdbcUtils.java // public static Connection getConnection() { // if (dataSource == null) { // dataSource = getDataSource(JDBC_SIMPLEAFFABLEBEAN); // } // // try { // return dataSource.getConnection(); // } catch (SQLException e) { // throw new SimpleAffableConnectionDbException("Encountered a SQL issue getting a connection", e); // } // // }
import business.SimpleAffableDbException.SimpleAffableQueryDbException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import static business.JdbcUtils.getConnection;
"product p " + "WHERE " + "p.category_id = ?"; private static final String FIND_BY_PRODUCT_ID_SQL = "SELECT " + " p.product_id, " + " p.category_id, " + " p.name, " + " p.price, " + " p.last_update " + "FROM " + " product p " + "WHERE " + "p.product_id = ?"; @Override public List<Product> findByCategoryId(long categoryId) { List<Product> result = new ArrayList<>(16); try (Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(FIND_BY_CATEGORY_SQL)) { statement.setLong(1, categoryId); try (ResultSet resultSet = statement.executeQuery()) { while (resultSet.next()) { result.add(readProduct(resultSet)); } } } catch (SQLException e) {
// Path: src/main/java/business/SimpleAffableDbException.java // public static class SimpleAffableQueryDbException extends SimpleAffableDbException { // public SimpleAffableQueryDbException(String message) { // super(message); // } // // public SimpleAffableQueryDbException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/business/JdbcUtils.java // public static Connection getConnection() { // if (dataSource == null) { // dataSource = getDataSource(JDBC_SIMPLEAFFABLEBEAN); // } // // try { // return dataSource.getConnection(); // } catch (SQLException e) { // throw new SimpleAffableConnectionDbException("Encountered a SQL issue getting a connection", e); // } // // } // Path: src/main/java/business/product/ProductDaoJdbc.java import business.SimpleAffableDbException.SimpleAffableQueryDbException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import static business.JdbcUtils.getConnection; "product p " + "WHERE " + "p.category_id = ?"; private static final String FIND_BY_PRODUCT_ID_SQL = "SELECT " + " p.product_id, " + " p.category_id, " + " p.name, " + " p.price, " + " p.last_update " + "FROM " + " product p " + "WHERE " + "p.product_id = ?"; @Override public List<Product> findByCategoryId(long categoryId) { List<Product> result = new ArrayList<>(16); try (Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(FIND_BY_CATEGORY_SQL)) { statement.setLong(1, categoryId); try (ResultSet resultSet = statement.executeQuery()) { while (resultSet.next()) { result.add(readProduct(resultSet)); } } } catch (SQLException e) {
throw new SimpleAffableQueryDbException("Encountered problem reading products by category", e);
nowucca/SimpleAffableBean
src/main/java/controller/ConfirmationServlet.java
// Path: src/main/java/viewmodel/ConfirmationViewModel.java // @SuppressWarnings("unchecked") // public class ConfirmationViewModel extends BaseViewModel { // // private Long orderId; // private CustomerOrderDetails orderDetails; // // // public ConfirmationViewModel(HttpServletRequest request) { // super(request); // // this.orderId = (Long) session.getAttribute("customerOrderId"); // // get order details // this.orderDetails = getCustomerOrderService().getOrderDetails(orderId); // } // // public Long getOrderId() { // return orderId; // } // // public CustomerOrderDetails getOrderDetails() { // return orderDetails; // } // }
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import viewmodel.ConfirmationViewModel;
/** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package controller; /** * */ @WebServlet(name = "Confirmation", urlPatterns = {"/confirmation"}) public class ConfirmationServlet extends SimpleAffableBeanServlet { // do not cache the confirmation in the browser protected boolean allowBrowserCaching() { return false; } /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // use RequestDispatcher to forward request internally
// Path: src/main/java/viewmodel/ConfirmationViewModel.java // @SuppressWarnings("unchecked") // public class ConfirmationViewModel extends BaseViewModel { // // private Long orderId; // private CustomerOrderDetails orderDetails; // // // public ConfirmationViewModel(HttpServletRequest request) { // super(request); // // this.orderId = (Long) session.getAttribute("customerOrderId"); // // get order details // this.orderDetails = getCustomerOrderService().getOrderDetails(orderId); // } // // public Long getOrderId() { // return orderId; // } // // public CustomerOrderDetails getOrderDetails() { // return orderDetails; // } // } // Path: src/main/java/controller/ConfirmationServlet.java import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import viewmodel.ConfirmationViewModel; /** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package controller; /** * */ @WebServlet(name = "Confirmation", urlPatterns = {"/confirmation"}) public class ConfirmationServlet extends SimpleAffableBeanServlet { // do not cache the confirmation in the browser protected boolean allowBrowserCaching() { return false; } /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // use RequestDispatcher to forward request internally
request.setAttribute("p", new ConfirmationViewModel(request));
nowucca/SimpleAffableBean
src/main/java/business/cart/ShoppingCart.java
// Path: src/main/java/business/ValidationException.java // public class ValidationException extends Exception { // // // private List<String> invalidFieldNames = new ArrayList<>(); // // public ValidationException() { // } // // public ValidationException(String invalidFieldName) { // super(); // fieldError(invalidFieldName); // } // // public ValidationException fieldError(String fieldName) { // invalidFieldNames.add(fieldName); // return this; // } // // // public boolean hasErrors() { // return !invalidFieldNames.isEmpty(); // } // // public List<String> getInvalidFieldNames() { // return invalidFieldNames; // } // // public boolean hasInvalidField(String name) { // return invalidFieldNames.contains(name); // } // } // // Path: src/main/java/business/product/Product.java // public class Product { // // private long productId; // private String name; // private int price; // private Date lastUpdate; // // public Product(long productId, String name, int price, Date lastUpdate) { // this.productId = productId; // this.name = name; // this.price = price; // this.lastUpdate = lastUpdate; // } // // public long getProductId() { // return productId; // } // public String getName() { // return name; // } // // public int getPrice() { // return price; // } // // public Date getLastUpdate() { // return lastUpdate; // } // // @Override // public String toString() { // return "business.product.Product[product_id=" + productId + "]"; // } // // }
import business.ValidationException; import business.product.Product; import java.util.ArrayList; import java.util.List;
/** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package business.cart; /** * */ public class ShoppingCart { List<ShoppingCartItem> items; int numberOfItems; int total; public ShoppingCart() { items = new ArrayList<>(); numberOfItems = 0; total = 0; } /** * Adds a <code>ShoppingCartItem</code> to the <code>ShoppingCart</code>'s * <code>items</code> list. If item of the specified <code>product</code> * already exists in shopping cart list, the quantity of that item is * incremented, and the original price remains unchanged. * * @see ShoppingCartItem */
// Path: src/main/java/business/ValidationException.java // public class ValidationException extends Exception { // // // private List<String> invalidFieldNames = new ArrayList<>(); // // public ValidationException() { // } // // public ValidationException(String invalidFieldName) { // super(); // fieldError(invalidFieldName); // } // // public ValidationException fieldError(String fieldName) { // invalidFieldNames.add(fieldName); // return this; // } // // // public boolean hasErrors() { // return !invalidFieldNames.isEmpty(); // } // // public List<String> getInvalidFieldNames() { // return invalidFieldNames; // } // // public boolean hasInvalidField(String name) { // return invalidFieldNames.contains(name); // } // } // // Path: src/main/java/business/product/Product.java // public class Product { // // private long productId; // private String name; // private int price; // private Date lastUpdate; // // public Product(long productId, String name, int price, Date lastUpdate) { // this.productId = productId; // this.name = name; // this.price = price; // this.lastUpdate = lastUpdate; // } // // public long getProductId() { // return productId; // } // public String getName() { // return name; // } // // public int getPrice() { // return price; // } // // public Date getLastUpdate() { // return lastUpdate; // } // // @Override // public String toString() { // return "business.product.Product[product_id=" + productId + "]"; // } // // } // Path: src/main/java/business/cart/ShoppingCart.java import business.ValidationException; import business.product.Product; import java.util.ArrayList; import java.util.List; /** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package business.cart; /** * */ public class ShoppingCart { List<ShoppingCartItem> items; int numberOfItems; int total; public ShoppingCart() { items = new ArrayList<>(); numberOfItems = 0; total = 0; } /** * Adds a <code>ShoppingCartItem</code> to the <code>ShoppingCart</code>'s * <code>items</code> list. If item of the specified <code>product</code> * already exists in shopping cart list, the quantity of that item is * incremented, and the original price remains unchanged. * * @see ShoppingCartItem */
public synchronized void addItem(Product product) {
nowucca/SimpleAffableBean
src/main/java/business/cart/ShoppingCart.java
// Path: src/main/java/business/ValidationException.java // public class ValidationException extends Exception { // // // private List<String> invalidFieldNames = new ArrayList<>(); // // public ValidationException() { // } // // public ValidationException(String invalidFieldName) { // super(); // fieldError(invalidFieldName); // } // // public ValidationException fieldError(String fieldName) { // invalidFieldNames.add(fieldName); // return this; // } // // // public boolean hasErrors() { // return !invalidFieldNames.isEmpty(); // } // // public List<String> getInvalidFieldNames() { // return invalidFieldNames; // } // // public boolean hasInvalidField(String name) { // return invalidFieldNames.contains(name); // } // } // // Path: src/main/java/business/product/Product.java // public class Product { // // private long productId; // private String name; // private int price; // private Date lastUpdate; // // public Product(long productId, String name, int price, Date lastUpdate) { // this.productId = productId; // this.name = name; // this.price = price; // this.lastUpdate = lastUpdate; // } // // public long getProductId() { // return productId; // } // public String getName() { // return name; // } // // public int getPrice() { // return price; // } // // public Date getLastUpdate() { // return lastUpdate; // } // // @Override // public String toString() { // return "business.product.Product[product_id=" + productId + "]"; // } // // }
import business.ValidationException; import business.product.Product; import java.util.ArrayList; import java.util.List;
/** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package business.cart; /** * */ public class ShoppingCart { List<ShoppingCartItem> items; int numberOfItems; int total; public ShoppingCart() { items = new ArrayList<>(); numberOfItems = 0; total = 0; } /** * Adds a <code>ShoppingCartItem</code> to the <code>ShoppingCart</code>'s * <code>items</code> list. If item of the specified <code>product</code> * already exists in shopping cart list, the quantity of that item is * incremented, and the original price remains unchanged. * * @see ShoppingCartItem */ public synchronized void addItem(Product product) { boolean newItem = true; for (ShoppingCartItem scItem : items) { if (scItem.getProductId() == product.getProductId()) { newItem = false; scItem.quantity++; } } if (newItem) { ShoppingCartItem scItem = new ShoppingCartItem(product); items.add(scItem); } } /** * Updates the <code>ShoppingCartItem</code> of the specified * <code>product</code> to the specified quantity. If '<code>0</code>' * is the given quantity, the <code>ShoppingCartItem</code> is removed * from the <code>ShoppingCart</code>'s <code>items</code> list. * * @param quantity the number which the <code>ShoppingCartItem</code> is updated to * @see ShoppingCartItem */
// Path: src/main/java/business/ValidationException.java // public class ValidationException extends Exception { // // // private List<String> invalidFieldNames = new ArrayList<>(); // // public ValidationException() { // } // // public ValidationException(String invalidFieldName) { // super(); // fieldError(invalidFieldName); // } // // public ValidationException fieldError(String fieldName) { // invalidFieldNames.add(fieldName); // return this; // } // // // public boolean hasErrors() { // return !invalidFieldNames.isEmpty(); // } // // public List<String> getInvalidFieldNames() { // return invalidFieldNames; // } // // public boolean hasInvalidField(String name) { // return invalidFieldNames.contains(name); // } // } // // Path: src/main/java/business/product/Product.java // public class Product { // // private long productId; // private String name; // private int price; // private Date lastUpdate; // // public Product(long productId, String name, int price, Date lastUpdate) { // this.productId = productId; // this.name = name; // this.price = price; // this.lastUpdate = lastUpdate; // } // // public long getProductId() { // return productId; // } // public String getName() { // return name; // } // // public int getPrice() { // return price; // } // // public Date getLastUpdate() { // return lastUpdate; // } // // @Override // public String toString() { // return "business.product.Product[product_id=" + productId + "]"; // } // // } // Path: src/main/java/business/cart/ShoppingCart.java import business.ValidationException; import business.product.Product; import java.util.ArrayList; import java.util.List; /** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package business.cart; /** * */ public class ShoppingCart { List<ShoppingCartItem> items; int numberOfItems; int total; public ShoppingCart() { items = new ArrayList<>(); numberOfItems = 0; total = 0; } /** * Adds a <code>ShoppingCartItem</code> to the <code>ShoppingCart</code>'s * <code>items</code> list. If item of the specified <code>product</code> * already exists in shopping cart list, the quantity of that item is * incremented, and the original price remains unchanged. * * @see ShoppingCartItem */ public synchronized void addItem(Product product) { boolean newItem = true; for (ShoppingCartItem scItem : items) { if (scItem.getProductId() == product.getProductId()) { newItem = false; scItem.quantity++; } } if (newItem) { ShoppingCartItem scItem = new ShoppingCartItem(product); items.add(scItem); } } /** * Updates the <code>ShoppingCartItem</code> of the specified * <code>product</code> to the specified quantity. If '<code>0</code>' * is the given quantity, the <code>ShoppingCartItem</code> is removed * from the <code>ShoppingCart</code>'s <code>items</code> list. * * @param quantity the number which the <code>ShoppingCartItem</code> is updated to * @see ShoppingCartItem */
public synchronized void update(Product product , short quantity) throws ValidationException {
nowucca/SimpleAffableBean
src/main/java/business/order/CustomerOrderLineItemDaoJdbc.java
// Path: src/main/java/business/SimpleAffableDbException.java // public static class SimpleAffableQueryDbException extends SimpleAffableDbException { // public SimpleAffableQueryDbException(String message) { // super(message); // } // // public SimpleAffableQueryDbException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/business/SimpleAffableDbException.java // public static class SimpleAffableUpdateDbException extends SimpleAffableDbException { // public SimpleAffableUpdateDbException(String message) { // super(message); // } // // public SimpleAffableUpdateDbException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: src/main/java/business/JdbcUtils.java // public static Connection getConnection() { // if (dataSource == null) { // dataSource = getDataSource(JDBC_SIMPLEAFFABLEBEAN); // } // // try { // return dataSource.getConnection(); // } catch (SQLException e) { // throw new SimpleAffableConnectionDbException("Encountered a SQL issue getting a connection", e); // } // // }
import business.SimpleAffableDbException.SimpleAffableQueryDbException; import business.SimpleAffableDbException.SimpleAffableUpdateDbException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static business.JdbcUtils.getConnection;
/** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package business.order; /** */ public class CustomerOrderLineItemDaoJdbc implements CustomerOrderLineItemDao { private static final String CREATE_LINE_ITEM_SQL = "INSERT INTO customer_order_line_item (customer_order_id, product_id, quantity) " + "VALUES (?, ?, ?)"; private static final String FIND_BY_CUSTOMER_ORDER_ID_SQL = "SELECT " + "li.customer_order_id, li.product_id, li.quantity " + "FROM " + "customer_order_line_item li " + "WHERE " + "li.customer_order_id = ?"; @Override public void create(Connection connection, long customerOrderId, long productId, short quantity) { try (PreparedStatement statement = connection.prepareStatement(CREATE_LINE_ITEM_SQL)) { statement.setLong(1, customerOrderId); statement.setLong(2, productId); statement.setShort(3, quantity); int affected = statement.executeUpdate(); if (affected != 1) {
// Path: src/main/java/business/SimpleAffableDbException.java // public static class SimpleAffableQueryDbException extends SimpleAffableDbException { // public SimpleAffableQueryDbException(String message) { // super(message); // } // // public SimpleAffableQueryDbException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/business/SimpleAffableDbException.java // public static class SimpleAffableUpdateDbException extends SimpleAffableDbException { // public SimpleAffableUpdateDbException(String message) { // super(message); // } // // public SimpleAffableUpdateDbException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: src/main/java/business/JdbcUtils.java // public static Connection getConnection() { // if (dataSource == null) { // dataSource = getDataSource(JDBC_SIMPLEAFFABLEBEAN); // } // // try { // return dataSource.getConnection(); // } catch (SQLException e) { // throw new SimpleAffableConnectionDbException("Encountered a SQL issue getting a connection", e); // } // // } // Path: src/main/java/business/order/CustomerOrderLineItemDaoJdbc.java import business.SimpleAffableDbException.SimpleAffableQueryDbException; import business.SimpleAffableDbException.SimpleAffableUpdateDbException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static business.JdbcUtils.getConnection; /** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package business.order; /** */ public class CustomerOrderLineItemDaoJdbc implements CustomerOrderLineItemDao { private static final String CREATE_LINE_ITEM_SQL = "INSERT INTO customer_order_line_item (customer_order_id, product_id, quantity) " + "VALUES (?, ?, ?)"; private static final String FIND_BY_CUSTOMER_ORDER_ID_SQL = "SELECT " + "li.customer_order_id, li.product_id, li.quantity " + "FROM " + "customer_order_line_item li " + "WHERE " + "li.customer_order_id = ?"; @Override public void create(Connection connection, long customerOrderId, long productId, short quantity) { try (PreparedStatement statement = connection.prepareStatement(CREATE_LINE_ITEM_SQL)) { statement.setLong(1, customerOrderId); statement.setLong(2, productId); statement.setShort(3, quantity); int affected = statement.executeUpdate(); if (affected != 1) {
throw new SimpleAffableUpdateDbException("Failed to insert an order line item, affected row count = "
nowucca/SimpleAffableBean
src/main/java/business/order/CustomerOrderLineItemDaoJdbc.java
// Path: src/main/java/business/SimpleAffableDbException.java // public static class SimpleAffableQueryDbException extends SimpleAffableDbException { // public SimpleAffableQueryDbException(String message) { // super(message); // } // // public SimpleAffableQueryDbException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/business/SimpleAffableDbException.java // public static class SimpleAffableUpdateDbException extends SimpleAffableDbException { // public SimpleAffableUpdateDbException(String message) { // super(message); // } // // public SimpleAffableUpdateDbException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: src/main/java/business/JdbcUtils.java // public static Connection getConnection() { // if (dataSource == null) { // dataSource = getDataSource(JDBC_SIMPLEAFFABLEBEAN); // } // // try { // return dataSource.getConnection(); // } catch (SQLException e) { // throw new SimpleAffableConnectionDbException("Encountered a SQL issue getting a connection", e); // } // // }
import business.SimpleAffableDbException.SimpleAffableQueryDbException; import business.SimpleAffableDbException.SimpleAffableUpdateDbException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static business.JdbcUtils.getConnection;
/** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package business.order; /** */ public class CustomerOrderLineItemDaoJdbc implements CustomerOrderLineItemDao { private static final String CREATE_LINE_ITEM_SQL = "INSERT INTO customer_order_line_item (customer_order_id, product_id, quantity) " + "VALUES (?, ?, ?)"; private static final String FIND_BY_CUSTOMER_ORDER_ID_SQL = "SELECT " + "li.customer_order_id, li.product_id, li.quantity " + "FROM " + "customer_order_line_item li " + "WHERE " + "li.customer_order_id = ?"; @Override public void create(Connection connection, long customerOrderId, long productId, short quantity) { try (PreparedStatement statement = connection.prepareStatement(CREATE_LINE_ITEM_SQL)) { statement.setLong(1, customerOrderId); statement.setLong(2, productId); statement.setShort(3, quantity); int affected = statement.executeUpdate(); if (affected != 1) { throw new SimpleAffableUpdateDbException("Failed to insert an order line item, affected row count = " + affected); } } catch (SQLException e) {
// Path: src/main/java/business/SimpleAffableDbException.java // public static class SimpleAffableQueryDbException extends SimpleAffableDbException { // public SimpleAffableQueryDbException(String message) { // super(message); // } // // public SimpleAffableQueryDbException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/business/SimpleAffableDbException.java // public static class SimpleAffableUpdateDbException extends SimpleAffableDbException { // public SimpleAffableUpdateDbException(String message) { // super(message); // } // // public SimpleAffableUpdateDbException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: src/main/java/business/JdbcUtils.java // public static Connection getConnection() { // if (dataSource == null) { // dataSource = getDataSource(JDBC_SIMPLEAFFABLEBEAN); // } // // try { // return dataSource.getConnection(); // } catch (SQLException e) { // throw new SimpleAffableConnectionDbException("Encountered a SQL issue getting a connection", e); // } // // } // Path: src/main/java/business/order/CustomerOrderLineItemDaoJdbc.java import business.SimpleAffableDbException.SimpleAffableQueryDbException; import business.SimpleAffableDbException.SimpleAffableUpdateDbException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static business.JdbcUtils.getConnection; /** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package business.order; /** */ public class CustomerOrderLineItemDaoJdbc implements CustomerOrderLineItemDao { private static final String CREATE_LINE_ITEM_SQL = "INSERT INTO customer_order_line_item (customer_order_id, product_id, quantity) " + "VALUES (?, ?, ?)"; private static final String FIND_BY_CUSTOMER_ORDER_ID_SQL = "SELECT " + "li.customer_order_id, li.product_id, li.quantity " + "FROM " + "customer_order_line_item li " + "WHERE " + "li.customer_order_id = ?"; @Override public void create(Connection connection, long customerOrderId, long productId, short quantity) { try (PreparedStatement statement = connection.prepareStatement(CREATE_LINE_ITEM_SQL)) { statement.setLong(1, customerOrderId); statement.setLong(2, productId); statement.setShort(3, quantity); int affected = statement.executeUpdate(); if (affected != 1) { throw new SimpleAffableUpdateDbException("Failed to insert an order line item, affected row count = " + affected); } } catch (SQLException e) {
throw new SimpleAffableQueryDbException("Encountered problem creating a new customer ", e);
nowucca/SimpleAffableBean
src/main/java/business/order/CustomerOrderLineItemDaoJdbc.java
// Path: src/main/java/business/SimpleAffableDbException.java // public static class SimpleAffableQueryDbException extends SimpleAffableDbException { // public SimpleAffableQueryDbException(String message) { // super(message); // } // // public SimpleAffableQueryDbException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/business/SimpleAffableDbException.java // public static class SimpleAffableUpdateDbException extends SimpleAffableDbException { // public SimpleAffableUpdateDbException(String message) { // super(message); // } // // public SimpleAffableUpdateDbException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: src/main/java/business/JdbcUtils.java // public static Connection getConnection() { // if (dataSource == null) { // dataSource = getDataSource(JDBC_SIMPLEAFFABLEBEAN); // } // // try { // return dataSource.getConnection(); // } catch (SQLException e) { // throw new SimpleAffableConnectionDbException("Encountered a SQL issue getting a connection", e); // } // // }
import business.SimpleAffableDbException.SimpleAffableQueryDbException; import business.SimpleAffableDbException.SimpleAffableUpdateDbException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static business.JdbcUtils.getConnection;
/** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package business.order; /** */ public class CustomerOrderLineItemDaoJdbc implements CustomerOrderLineItemDao { private static final String CREATE_LINE_ITEM_SQL = "INSERT INTO customer_order_line_item (customer_order_id, product_id, quantity) " + "VALUES (?, ?, ?)"; private static final String FIND_BY_CUSTOMER_ORDER_ID_SQL = "SELECT " + "li.customer_order_id, li.product_id, li.quantity " + "FROM " + "customer_order_line_item li " + "WHERE " + "li.customer_order_id = ?"; @Override public void create(Connection connection, long customerOrderId, long productId, short quantity) { try (PreparedStatement statement = connection.prepareStatement(CREATE_LINE_ITEM_SQL)) { statement.setLong(1, customerOrderId); statement.setLong(2, productId); statement.setShort(3, quantity); int affected = statement.executeUpdate(); if (affected != 1) { throw new SimpleAffableUpdateDbException("Failed to insert an order line item, affected row count = " + affected); } } catch (SQLException e) { throw new SimpleAffableQueryDbException("Encountered problem creating a new customer ", e); } } @Override public Collection<CustomerOrderLineItem> findByCustomerOrderId(long customerOrderId) { List<CustomerOrderLineItem> result = new ArrayList<>(16);
// Path: src/main/java/business/SimpleAffableDbException.java // public static class SimpleAffableQueryDbException extends SimpleAffableDbException { // public SimpleAffableQueryDbException(String message) { // super(message); // } // // public SimpleAffableQueryDbException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: src/main/java/business/SimpleAffableDbException.java // public static class SimpleAffableUpdateDbException extends SimpleAffableDbException { // public SimpleAffableUpdateDbException(String message) { // super(message); // } // // public SimpleAffableUpdateDbException(String message, Throwable cause) { // super(message, cause); // } // // } // // Path: src/main/java/business/JdbcUtils.java // public static Connection getConnection() { // if (dataSource == null) { // dataSource = getDataSource(JDBC_SIMPLEAFFABLEBEAN); // } // // try { // return dataSource.getConnection(); // } catch (SQLException e) { // throw new SimpleAffableConnectionDbException("Encountered a SQL issue getting a connection", e); // } // // } // Path: src/main/java/business/order/CustomerOrderLineItemDaoJdbc.java import business.SimpleAffableDbException.SimpleAffableQueryDbException; import business.SimpleAffableDbException.SimpleAffableUpdateDbException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static business.JdbcUtils.getConnection; /** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package business.order; /** */ public class CustomerOrderLineItemDaoJdbc implements CustomerOrderLineItemDao { private static final String CREATE_LINE_ITEM_SQL = "INSERT INTO customer_order_line_item (customer_order_id, product_id, quantity) " + "VALUES (?, ?, ?)"; private static final String FIND_BY_CUSTOMER_ORDER_ID_SQL = "SELECT " + "li.customer_order_id, li.product_id, li.quantity " + "FROM " + "customer_order_line_item li " + "WHERE " + "li.customer_order_id = ?"; @Override public void create(Connection connection, long customerOrderId, long productId, short quantity) { try (PreparedStatement statement = connection.prepareStatement(CREATE_LINE_ITEM_SQL)) { statement.setLong(1, customerOrderId); statement.setLong(2, productId); statement.setShort(3, quantity); int affected = statement.executeUpdate(); if (affected != 1) { throw new SimpleAffableUpdateDbException("Failed to insert an order line item, affected row count = " + affected); } } catch (SQLException e) { throw new SimpleAffableQueryDbException("Encountered problem creating a new customer ", e); } } @Override public Collection<CustomerOrderLineItem> findByCustomerOrderId(long customerOrderId) { List<CustomerOrderLineItem> result = new ArrayList<>(16);
try (Connection connection = getConnection();
nowucca/SimpleAffableBean
src/main/java/controller/admin/AdminOrdersServlet.java
// Path: src/main/java/viewmodel/admin/AdminOrdersViewModel.java // public class AdminOrdersViewModel extends BaseAdminViewModel { // // private List<CustomerOrder> orderList; // // public AdminOrdersViewModel(HttpServletRequest request) { // super(request); // // this.orderList = customerOrderService.findAll(); // } // // public List<CustomerOrder> getOrderList() { // return orderList; // } // // }
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.HttpConstraint; import javax.servlet.annotation.ServletSecurity; import javax.servlet.annotation.ServletSecurity.TransportGuarantee; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import viewmodel.admin.AdminOrdersViewModel;
/** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package controller.admin; /** * */ @WebServlet(name = "AdminOrdersServlet", urlPatterns = {"/admin/orders"}) @ServletSecurity( @HttpConstraint(transportGuarantee = TransportGuarantee.CONFIDENTIAL, rolesAllowed = {"simpleAffableBeanAdmin"}) ) public class AdminOrdersServlet extends AdminServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Path: src/main/java/viewmodel/admin/AdminOrdersViewModel.java // public class AdminOrdersViewModel extends BaseAdminViewModel { // // private List<CustomerOrder> orderList; // // public AdminOrdersViewModel(HttpServletRequest request) { // super(request); // // this.orderList = customerOrderService.findAll(); // } // // public List<CustomerOrder> getOrderList() { // return orderList; // } // // } // Path: src/main/java/controller/admin/AdminOrdersServlet.java import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.HttpConstraint; import javax.servlet.annotation.ServletSecurity; import javax.servlet.annotation.ServletSecurity.TransportGuarantee; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import viewmodel.admin.AdminOrdersViewModel; /** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package controller.admin; /** * */ @WebServlet(name = "AdminOrdersServlet", urlPatterns = {"/admin/orders"}) @ServletSecurity( @HttpConstraint(transportGuarantee = TransportGuarantee.CONFIDENTIAL, rolesAllowed = {"simpleAffableBeanAdmin"}) ) public class AdminOrdersServlet extends AdminServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("p", new AdminOrdersViewModel(request));
nowucca/SimpleAffableBean
src/main/java/controller/admin/AdminOrderServlet.java
// Path: src/main/java/viewmodel/admin/AdminOrderViewModel.java // public class AdminOrderViewModel extends BaseAdminViewModel { // // private String orderId; // private CustomerOrderDetails details; // private Customer customer; // private List<Product> products; // private CustomerOrder orderRecord; // private List<CustomerOrderLineItem> orderedProducts; // // public AdminOrderViewModel(HttpServletRequest request) { // super(request); // // this.orderId = request.getPathInfo().split("/")[1]; // this.details = customerOrderService.getOrderDetails(Long.parseLong(orderId)); // this.customer = details.getCustomer(); // this.products = details.getProducts(); // this.orderRecord = details.getCustomerOrder(); // this.orderedProducts = details.getCustomerOrderLineItems(); // } // // public Customer getCustomer() { // return customer; // } // // public List<Product> getProducts() { // return products; // } // // public CustomerOrder getOrderRecord() { // return orderRecord; // } // // public List<CustomerOrderLineItem> getOrderedProducts() { // return orderedProducts; // } // // }
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.HttpConstraint; import javax.servlet.annotation.ServletSecurity; import javax.servlet.annotation.ServletSecurity.TransportGuarantee; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import viewmodel.admin.AdminOrderViewModel;
/** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package controller.admin; /** * */ @WebServlet(name = "AdminOrderServlet", urlPatterns = {"/admin/order/*"}) @ServletSecurity( @HttpConstraint(transportGuarantee = TransportGuarantee.CONFIDENTIAL, rolesAllowed = {"simpleAffableBeanAdmin"}) ) public class AdminOrderServlet extends AdminServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Path: src/main/java/viewmodel/admin/AdminOrderViewModel.java // public class AdminOrderViewModel extends BaseAdminViewModel { // // private String orderId; // private CustomerOrderDetails details; // private Customer customer; // private List<Product> products; // private CustomerOrder orderRecord; // private List<CustomerOrderLineItem> orderedProducts; // // public AdminOrderViewModel(HttpServletRequest request) { // super(request); // // this.orderId = request.getPathInfo().split("/")[1]; // this.details = customerOrderService.getOrderDetails(Long.parseLong(orderId)); // this.customer = details.getCustomer(); // this.products = details.getProducts(); // this.orderRecord = details.getCustomerOrder(); // this.orderedProducts = details.getCustomerOrderLineItems(); // } // // public Customer getCustomer() { // return customer; // } // // public List<Product> getProducts() { // return products; // } // // public CustomerOrder getOrderRecord() { // return orderRecord; // } // // public List<CustomerOrderLineItem> getOrderedProducts() { // return orderedProducts; // } // // } // Path: src/main/java/controller/admin/AdminOrderServlet.java import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.HttpConstraint; import javax.servlet.annotation.ServletSecurity; import javax.servlet.annotation.ServletSecurity.TransportGuarantee; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import viewmodel.admin.AdminOrderViewModel; /** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package controller.admin; /** * */ @WebServlet(name = "AdminOrderServlet", urlPatterns = {"/admin/order/*"}) @ServletSecurity( @HttpConstraint(transportGuarantee = TransportGuarantee.CONFIDENTIAL, rolesAllowed = {"simpleAffableBeanAdmin"}) ) public class AdminOrderServlet extends AdminServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("p", new AdminOrderViewModel(request));
nowucca/SimpleAffableBean
src/main/java/viewmodel/admin/BaseAdminViewModel.java
// Path: src/main/java/business/ApplicationContext.java // public final class ApplicationContext { // // private final Logger logger = LoggerFactory.getLogger(getClass()); // // private ProductService productService; // // private CategoryService categoryService; // // private CustomerService customerService; // // private CustomerOrderService customerOrderService; // // private ScheduledExecutorService executorService; // // public static ApplicationContext INSTANCE = new ApplicationContext(); // // private ApplicationContext() { // // executorService = new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors()); // // // wire up the business.dao layer "by hand" // ProductDao productDao = new ProductDaoJdbc(); // // ProductDaoGuava cachedProductDao = new ProductDaoGuava(productDao); // // productService = new DefaultProductService(); // ((DefaultProductService) productService).setProductDao(cachedProductDao); // // CategoryDao categoryDao = new CategoryDaoJdbc(); // // CategoryDaoGuava cachedCategoryDao = new CategoryDaoGuava(categoryDao); // // categoryService = new DefaultCategoryService(); // ((DefaultCategoryService) categoryService).setCategoryDao(cachedCategoryDao); // // CustomerDao customerDao = new CustomerDaoJdbc(); // customerService = new DefaultCustomerService(); // ((DefaultCustomerService) customerService).setCustomerDao(customerDao); // // CustomerOrderLineItemDao customerOrderLineItemDao = new CustomerOrderLineItemDaoJdbc(); // CustomerOrderDao customerOrderDao = new CustomerOrderDaoJdbc(); // // customerOrderService = new DefaultCustomerOrderService(); // DefaultCustomerOrderService service = (DefaultCustomerOrderService) customerOrderService; // service.setProductDao(cachedProductDao); // service.setCustomerService(customerService); // service.setCustomerOrderDao(customerOrderDao); // service.setCustomerOrderLineItemDao(customerOrderLineItemDao); // // executorService.scheduleWithFixedDelay(() -> { // try { // logger.info("Refreshing category and product caches....commencing"); // cachedCategoryDao.bulkload(); // cachedProductDao.clear(); // logger.info("Refreshing category and product caches....complete!"); // } catch (Throwable t) { // logger.error("Encountered trouble refreshing category and product caches.", t); // } // }, 10, 60, TimeUnit.MINUTES); // } // // // // public ProductService getProductService() { // return productService; // } // // public CategoryService getCategoryService() { // return categoryService; // } // // public CustomerService getCustomerService() { // return customerService; // } // // public CustomerOrderService getCustomerOrderService() { // return customerOrderService; // } // // public void shutdown() { // executorService.shutdown(); // } // } // // Path: src/main/java/business/customer/CustomerService.java // public interface CustomerService { // long create(Connection connection, CustomerForm customerForm) throws ValidationException; // // Customer findByCustomerId(long customerId); // // List<Customer> findAll(); // } // // Path: src/main/java/business/order/CustomerOrderService.java // public interface CustomerOrderService { // // long placeOrder(CustomerForm customerForm, ShoppingCart cart) throws ValidationException; // // CustomerOrderDetails getOrderDetails(long customerOrderId); // // List<CustomerOrder> findAll(); // // CustomerOrder findByCustomerId(long customerId); // // CustomerOrder findByCustomerOrderId(long customerOrderId); // }
import business.ApplicationContext; import business.customer.CustomerService; import business.order.CustomerOrderService; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession;
/** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package viewmodel; /** * A base class for all view models for admin pages. * Put access to data here that are potentially useful on all pages. * For example this is a good place to put support for common header * and footer elements that are dynamic. */ public class BaseAdminViewModel { // The relative path to product images // private static final String PRODUCT_IMAGE_PATH = "/img/products/"; private static final String PRODUCT_IMAGE_PATH = BaseViewModel.PRODUCT_IMAGE_PATH; // Every view model knows the request and session protected HttpServletRequest request; protected HttpSession session; // All customer/order pages need the following service objects
// Path: src/main/java/business/ApplicationContext.java // public final class ApplicationContext { // // private final Logger logger = LoggerFactory.getLogger(getClass()); // // private ProductService productService; // // private CategoryService categoryService; // // private CustomerService customerService; // // private CustomerOrderService customerOrderService; // // private ScheduledExecutorService executorService; // // public static ApplicationContext INSTANCE = new ApplicationContext(); // // private ApplicationContext() { // // executorService = new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors()); // // // wire up the business.dao layer "by hand" // ProductDao productDao = new ProductDaoJdbc(); // // ProductDaoGuava cachedProductDao = new ProductDaoGuava(productDao); // // productService = new DefaultProductService(); // ((DefaultProductService) productService).setProductDao(cachedProductDao); // // CategoryDao categoryDao = new CategoryDaoJdbc(); // // CategoryDaoGuava cachedCategoryDao = new CategoryDaoGuava(categoryDao); // // categoryService = new DefaultCategoryService(); // ((DefaultCategoryService) categoryService).setCategoryDao(cachedCategoryDao); // // CustomerDao customerDao = new CustomerDaoJdbc(); // customerService = new DefaultCustomerService(); // ((DefaultCustomerService) customerService).setCustomerDao(customerDao); // // CustomerOrderLineItemDao customerOrderLineItemDao = new CustomerOrderLineItemDaoJdbc(); // CustomerOrderDao customerOrderDao = new CustomerOrderDaoJdbc(); // // customerOrderService = new DefaultCustomerOrderService(); // DefaultCustomerOrderService service = (DefaultCustomerOrderService) customerOrderService; // service.setProductDao(cachedProductDao); // service.setCustomerService(customerService); // service.setCustomerOrderDao(customerOrderDao); // service.setCustomerOrderLineItemDao(customerOrderLineItemDao); // // executorService.scheduleWithFixedDelay(() -> { // try { // logger.info("Refreshing category and product caches....commencing"); // cachedCategoryDao.bulkload(); // cachedProductDao.clear(); // logger.info("Refreshing category and product caches....complete!"); // } catch (Throwable t) { // logger.error("Encountered trouble refreshing category and product caches.", t); // } // }, 10, 60, TimeUnit.MINUTES); // } // // // // public ProductService getProductService() { // return productService; // } // // public CategoryService getCategoryService() { // return categoryService; // } // // public CustomerService getCustomerService() { // return customerService; // } // // public CustomerOrderService getCustomerOrderService() { // return customerOrderService; // } // // public void shutdown() { // executorService.shutdown(); // } // } // // Path: src/main/java/business/customer/CustomerService.java // public interface CustomerService { // long create(Connection connection, CustomerForm customerForm) throws ValidationException; // // Customer findByCustomerId(long customerId); // // List<Customer> findAll(); // } // // Path: src/main/java/business/order/CustomerOrderService.java // public interface CustomerOrderService { // // long placeOrder(CustomerForm customerForm, ShoppingCart cart) throws ValidationException; // // CustomerOrderDetails getOrderDetails(long customerOrderId); // // List<CustomerOrder> findAll(); // // CustomerOrder findByCustomerId(long customerId); // // CustomerOrder findByCustomerOrderId(long customerOrderId); // } // Path: src/main/java/viewmodel/admin/BaseAdminViewModel.java import business.ApplicationContext; import business.customer.CustomerService; import business.order.CustomerOrderService; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package viewmodel; /** * A base class for all view models for admin pages. * Put access to data here that are potentially useful on all pages. * For example this is a good place to put support for common header * and footer elements that are dynamic. */ public class BaseAdminViewModel { // The relative path to product images // private static final String PRODUCT_IMAGE_PATH = "/img/products/"; private static final String PRODUCT_IMAGE_PATH = BaseViewModel.PRODUCT_IMAGE_PATH; // Every view model knows the request and session protected HttpServletRequest request; protected HttpSession session; // All customer/order pages need the following service objects
protected CustomerService customerService;
nowucca/SimpleAffableBean
src/main/java/viewmodel/admin/BaseAdminViewModel.java
// Path: src/main/java/business/ApplicationContext.java // public final class ApplicationContext { // // private final Logger logger = LoggerFactory.getLogger(getClass()); // // private ProductService productService; // // private CategoryService categoryService; // // private CustomerService customerService; // // private CustomerOrderService customerOrderService; // // private ScheduledExecutorService executorService; // // public static ApplicationContext INSTANCE = new ApplicationContext(); // // private ApplicationContext() { // // executorService = new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors()); // // // wire up the business.dao layer "by hand" // ProductDao productDao = new ProductDaoJdbc(); // // ProductDaoGuava cachedProductDao = new ProductDaoGuava(productDao); // // productService = new DefaultProductService(); // ((DefaultProductService) productService).setProductDao(cachedProductDao); // // CategoryDao categoryDao = new CategoryDaoJdbc(); // // CategoryDaoGuava cachedCategoryDao = new CategoryDaoGuava(categoryDao); // // categoryService = new DefaultCategoryService(); // ((DefaultCategoryService) categoryService).setCategoryDao(cachedCategoryDao); // // CustomerDao customerDao = new CustomerDaoJdbc(); // customerService = new DefaultCustomerService(); // ((DefaultCustomerService) customerService).setCustomerDao(customerDao); // // CustomerOrderLineItemDao customerOrderLineItemDao = new CustomerOrderLineItemDaoJdbc(); // CustomerOrderDao customerOrderDao = new CustomerOrderDaoJdbc(); // // customerOrderService = new DefaultCustomerOrderService(); // DefaultCustomerOrderService service = (DefaultCustomerOrderService) customerOrderService; // service.setProductDao(cachedProductDao); // service.setCustomerService(customerService); // service.setCustomerOrderDao(customerOrderDao); // service.setCustomerOrderLineItemDao(customerOrderLineItemDao); // // executorService.scheduleWithFixedDelay(() -> { // try { // logger.info("Refreshing category and product caches....commencing"); // cachedCategoryDao.bulkload(); // cachedProductDao.clear(); // logger.info("Refreshing category and product caches....complete!"); // } catch (Throwable t) { // logger.error("Encountered trouble refreshing category and product caches.", t); // } // }, 10, 60, TimeUnit.MINUTES); // } // // // // public ProductService getProductService() { // return productService; // } // // public CategoryService getCategoryService() { // return categoryService; // } // // public CustomerService getCustomerService() { // return customerService; // } // // public CustomerOrderService getCustomerOrderService() { // return customerOrderService; // } // // public void shutdown() { // executorService.shutdown(); // } // } // // Path: src/main/java/business/customer/CustomerService.java // public interface CustomerService { // long create(Connection connection, CustomerForm customerForm) throws ValidationException; // // Customer findByCustomerId(long customerId); // // List<Customer> findAll(); // } // // Path: src/main/java/business/order/CustomerOrderService.java // public interface CustomerOrderService { // // long placeOrder(CustomerForm customerForm, ShoppingCart cart) throws ValidationException; // // CustomerOrderDetails getOrderDetails(long customerOrderId); // // List<CustomerOrder> findAll(); // // CustomerOrder findByCustomerId(long customerId); // // CustomerOrder findByCustomerOrderId(long customerOrderId); // }
import business.ApplicationContext; import business.customer.CustomerService; import business.order.CustomerOrderService; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession;
/** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package viewmodel; /** * A base class for all view models for admin pages. * Put access to data here that are potentially useful on all pages. * For example this is a good place to put support for common header * and footer elements that are dynamic. */ public class BaseAdminViewModel { // The relative path to product images // private static final String PRODUCT_IMAGE_PATH = "/img/products/"; private static final String PRODUCT_IMAGE_PATH = BaseViewModel.PRODUCT_IMAGE_PATH; // Every view model knows the request and session protected HttpServletRequest request; protected HttpSession session; // All customer/order pages need the following service objects protected CustomerService customerService;
// Path: src/main/java/business/ApplicationContext.java // public final class ApplicationContext { // // private final Logger logger = LoggerFactory.getLogger(getClass()); // // private ProductService productService; // // private CategoryService categoryService; // // private CustomerService customerService; // // private CustomerOrderService customerOrderService; // // private ScheduledExecutorService executorService; // // public static ApplicationContext INSTANCE = new ApplicationContext(); // // private ApplicationContext() { // // executorService = new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors()); // // // wire up the business.dao layer "by hand" // ProductDao productDao = new ProductDaoJdbc(); // // ProductDaoGuava cachedProductDao = new ProductDaoGuava(productDao); // // productService = new DefaultProductService(); // ((DefaultProductService) productService).setProductDao(cachedProductDao); // // CategoryDao categoryDao = new CategoryDaoJdbc(); // // CategoryDaoGuava cachedCategoryDao = new CategoryDaoGuava(categoryDao); // // categoryService = new DefaultCategoryService(); // ((DefaultCategoryService) categoryService).setCategoryDao(cachedCategoryDao); // // CustomerDao customerDao = new CustomerDaoJdbc(); // customerService = new DefaultCustomerService(); // ((DefaultCustomerService) customerService).setCustomerDao(customerDao); // // CustomerOrderLineItemDao customerOrderLineItemDao = new CustomerOrderLineItemDaoJdbc(); // CustomerOrderDao customerOrderDao = new CustomerOrderDaoJdbc(); // // customerOrderService = new DefaultCustomerOrderService(); // DefaultCustomerOrderService service = (DefaultCustomerOrderService) customerOrderService; // service.setProductDao(cachedProductDao); // service.setCustomerService(customerService); // service.setCustomerOrderDao(customerOrderDao); // service.setCustomerOrderLineItemDao(customerOrderLineItemDao); // // executorService.scheduleWithFixedDelay(() -> { // try { // logger.info("Refreshing category and product caches....commencing"); // cachedCategoryDao.bulkload(); // cachedProductDao.clear(); // logger.info("Refreshing category and product caches....complete!"); // } catch (Throwable t) { // logger.error("Encountered trouble refreshing category and product caches.", t); // } // }, 10, 60, TimeUnit.MINUTES); // } // // // // public ProductService getProductService() { // return productService; // } // // public CategoryService getCategoryService() { // return categoryService; // } // // public CustomerService getCustomerService() { // return customerService; // } // // public CustomerOrderService getCustomerOrderService() { // return customerOrderService; // } // // public void shutdown() { // executorService.shutdown(); // } // } // // Path: src/main/java/business/customer/CustomerService.java // public interface CustomerService { // long create(Connection connection, CustomerForm customerForm) throws ValidationException; // // Customer findByCustomerId(long customerId); // // List<Customer> findAll(); // } // // Path: src/main/java/business/order/CustomerOrderService.java // public interface CustomerOrderService { // // long placeOrder(CustomerForm customerForm, ShoppingCart cart) throws ValidationException; // // CustomerOrderDetails getOrderDetails(long customerOrderId); // // List<CustomerOrder> findAll(); // // CustomerOrder findByCustomerId(long customerId); // // CustomerOrder findByCustomerOrderId(long customerOrderId); // } // Path: src/main/java/viewmodel/admin/BaseAdminViewModel.java import business.ApplicationContext; import business.customer.CustomerService; import business.order.CustomerOrderService; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package viewmodel; /** * A base class for all view models for admin pages. * Put access to data here that are potentially useful on all pages. * For example this is a good place to put support for common header * and footer elements that are dynamic. */ public class BaseAdminViewModel { // The relative path to product images // private static final String PRODUCT_IMAGE_PATH = "/img/products/"; private static final String PRODUCT_IMAGE_PATH = BaseViewModel.PRODUCT_IMAGE_PATH; // Every view model knows the request and session protected HttpServletRequest request; protected HttpSession session; // All customer/order pages need the following service objects protected CustomerService customerService;
protected CustomerOrderService customerOrderService;
nowucca/SimpleAffableBean
src/main/java/viewmodel/admin/BaseAdminViewModel.java
// Path: src/main/java/business/ApplicationContext.java // public final class ApplicationContext { // // private final Logger logger = LoggerFactory.getLogger(getClass()); // // private ProductService productService; // // private CategoryService categoryService; // // private CustomerService customerService; // // private CustomerOrderService customerOrderService; // // private ScheduledExecutorService executorService; // // public static ApplicationContext INSTANCE = new ApplicationContext(); // // private ApplicationContext() { // // executorService = new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors()); // // // wire up the business.dao layer "by hand" // ProductDao productDao = new ProductDaoJdbc(); // // ProductDaoGuava cachedProductDao = new ProductDaoGuava(productDao); // // productService = new DefaultProductService(); // ((DefaultProductService) productService).setProductDao(cachedProductDao); // // CategoryDao categoryDao = new CategoryDaoJdbc(); // // CategoryDaoGuava cachedCategoryDao = new CategoryDaoGuava(categoryDao); // // categoryService = new DefaultCategoryService(); // ((DefaultCategoryService) categoryService).setCategoryDao(cachedCategoryDao); // // CustomerDao customerDao = new CustomerDaoJdbc(); // customerService = new DefaultCustomerService(); // ((DefaultCustomerService) customerService).setCustomerDao(customerDao); // // CustomerOrderLineItemDao customerOrderLineItemDao = new CustomerOrderLineItemDaoJdbc(); // CustomerOrderDao customerOrderDao = new CustomerOrderDaoJdbc(); // // customerOrderService = new DefaultCustomerOrderService(); // DefaultCustomerOrderService service = (DefaultCustomerOrderService) customerOrderService; // service.setProductDao(cachedProductDao); // service.setCustomerService(customerService); // service.setCustomerOrderDao(customerOrderDao); // service.setCustomerOrderLineItemDao(customerOrderLineItemDao); // // executorService.scheduleWithFixedDelay(() -> { // try { // logger.info("Refreshing category and product caches....commencing"); // cachedCategoryDao.bulkload(); // cachedProductDao.clear(); // logger.info("Refreshing category and product caches....complete!"); // } catch (Throwable t) { // logger.error("Encountered trouble refreshing category and product caches.", t); // } // }, 10, 60, TimeUnit.MINUTES); // } // // // // public ProductService getProductService() { // return productService; // } // // public CategoryService getCategoryService() { // return categoryService; // } // // public CustomerService getCustomerService() { // return customerService; // } // // public CustomerOrderService getCustomerOrderService() { // return customerOrderService; // } // // public void shutdown() { // executorService.shutdown(); // } // } // // Path: src/main/java/business/customer/CustomerService.java // public interface CustomerService { // long create(Connection connection, CustomerForm customerForm) throws ValidationException; // // Customer findByCustomerId(long customerId); // // List<Customer> findAll(); // } // // Path: src/main/java/business/order/CustomerOrderService.java // public interface CustomerOrderService { // // long placeOrder(CustomerForm customerForm, ShoppingCart cart) throws ValidationException; // // CustomerOrderDetails getOrderDetails(long customerOrderId); // // List<CustomerOrder> findAll(); // // CustomerOrder findByCustomerId(long customerId); // // CustomerOrder findByCustomerOrderId(long customerOrderId); // }
import business.ApplicationContext; import business.customer.CustomerService; import business.order.CustomerOrderService; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession;
/** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package viewmodel; /** * A base class for all view models for admin pages. * Put access to data here that are potentially useful on all pages. * For example this is a good place to put support for common header * and footer elements that are dynamic. */ public class BaseAdminViewModel { // The relative path to product images // private static final String PRODUCT_IMAGE_PATH = "/img/products/"; private static final String PRODUCT_IMAGE_PATH = BaseViewModel.PRODUCT_IMAGE_PATH; // Every view model knows the request and session protected HttpServletRequest request; protected HttpSession session; // All customer/order pages need the following service objects protected CustomerService customerService; protected CustomerOrderService customerOrderService; // Delivery surcharge protected int deliverySurcharge; @SuppressWarnings("unchecked") public BaseAdminViewModel(HttpServletRequest request) {
// Path: src/main/java/business/ApplicationContext.java // public final class ApplicationContext { // // private final Logger logger = LoggerFactory.getLogger(getClass()); // // private ProductService productService; // // private CategoryService categoryService; // // private CustomerService customerService; // // private CustomerOrderService customerOrderService; // // private ScheduledExecutorService executorService; // // public static ApplicationContext INSTANCE = new ApplicationContext(); // // private ApplicationContext() { // // executorService = new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors()); // // // wire up the business.dao layer "by hand" // ProductDao productDao = new ProductDaoJdbc(); // // ProductDaoGuava cachedProductDao = new ProductDaoGuava(productDao); // // productService = new DefaultProductService(); // ((DefaultProductService) productService).setProductDao(cachedProductDao); // // CategoryDao categoryDao = new CategoryDaoJdbc(); // // CategoryDaoGuava cachedCategoryDao = new CategoryDaoGuava(categoryDao); // // categoryService = new DefaultCategoryService(); // ((DefaultCategoryService) categoryService).setCategoryDao(cachedCategoryDao); // // CustomerDao customerDao = new CustomerDaoJdbc(); // customerService = new DefaultCustomerService(); // ((DefaultCustomerService) customerService).setCustomerDao(customerDao); // // CustomerOrderLineItemDao customerOrderLineItemDao = new CustomerOrderLineItemDaoJdbc(); // CustomerOrderDao customerOrderDao = new CustomerOrderDaoJdbc(); // // customerOrderService = new DefaultCustomerOrderService(); // DefaultCustomerOrderService service = (DefaultCustomerOrderService) customerOrderService; // service.setProductDao(cachedProductDao); // service.setCustomerService(customerService); // service.setCustomerOrderDao(customerOrderDao); // service.setCustomerOrderLineItemDao(customerOrderLineItemDao); // // executorService.scheduleWithFixedDelay(() -> { // try { // logger.info("Refreshing category and product caches....commencing"); // cachedCategoryDao.bulkload(); // cachedProductDao.clear(); // logger.info("Refreshing category and product caches....complete!"); // } catch (Throwable t) { // logger.error("Encountered trouble refreshing category and product caches.", t); // } // }, 10, 60, TimeUnit.MINUTES); // } // // // // public ProductService getProductService() { // return productService; // } // // public CategoryService getCategoryService() { // return categoryService; // } // // public CustomerService getCustomerService() { // return customerService; // } // // public CustomerOrderService getCustomerOrderService() { // return customerOrderService; // } // // public void shutdown() { // executorService.shutdown(); // } // } // // Path: src/main/java/business/customer/CustomerService.java // public interface CustomerService { // long create(Connection connection, CustomerForm customerForm) throws ValidationException; // // Customer findByCustomerId(long customerId); // // List<Customer> findAll(); // } // // Path: src/main/java/business/order/CustomerOrderService.java // public interface CustomerOrderService { // // long placeOrder(CustomerForm customerForm, ShoppingCart cart) throws ValidationException; // // CustomerOrderDetails getOrderDetails(long customerOrderId); // // List<CustomerOrder> findAll(); // // CustomerOrder findByCustomerId(long customerId); // // CustomerOrder findByCustomerOrderId(long customerOrderId); // } // Path: src/main/java/viewmodel/admin/BaseAdminViewModel.java import business.ApplicationContext; import business.customer.CustomerService; import business.order.CustomerOrderService; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package viewmodel; /** * A base class for all view models for admin pages. * Put access to data here that are potentially useful on all pages. * For example this is a good place to put support for common header * and footer elements that are dynamic. */ public class BaseAdminViewModel { // The relative path to product images // private static final String PRODUCT_IMAGE_PATH = "/img/products/"; private static final String PRODUCT_IMAGE_PATH = BaseViewModel.PRODUCT_IMAGE_PATH; // Every view model knows the request and session protected HttpServletRequest request; protected HttpSession session; // All customer/order pages need the following service objects protected CustomerService customerService; protected CustomerOrderService customerOrderService; // Delivery surcharge protected int deliverySurcharge; @SuppressWarnings("unchecked") public BaseAdminViewModel(HttpServletRequest request) {
ApplicationContext applicationContext = ApplicationContext.INSTANCE;
nowucca/SimpleAffableBean
src/main/java/viewmodel/CheckoutViewModel.java
// Path: src/main/java/business/ValidationException.java // public class ValidationException extends Exception { // // // private List<String> invalidFieldNames = new ArrayList<>(); // // public ValidationException() { // } // // public ValidationException(String invalidFieldName) { // super(); // fieldError(invalidFieldName); // } // // public ValidationException fieldError(String fieldName) { // invalidFieldNames.add(fieldName); // return this; // } // // // public boolean hasErrors() { // return !invalidFieldNames.isEmpty(); // } // // public List<String> getInvalidFieldNames() { // return invalidFieldNames; // } // // public boolean hasInvalidField(String name) { // return invalidFieldNames.contains(name); // } // }
import business.ValidationException; import javax.servlet.http.HttpServletRequest;
/** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package viewmodel; /** * */ @SuppressWarnings("unchecked") public class CheckoutViewModel extends BaseViewModel { private Boolean hasValidationErrorFlag; private Boolean hasOrderFailureFlag;
// Path: src/main/java/business/ValidationException.java // public class ValidationException extends Exception { // // // private List<String> invalidFieldNames = new ArrayList<>(); // // public ValidationException() { // } // // public ValidationException(String invalidFieldName) { // super(); // fieldError(invalidFieldName); // } // // public ValidationException fieldError(String fieldName) { // invalidFieldNames.add(fieldName); // return this; // } // // // public boolean hasErrors() { // return !invalidFieldNames.isEmpty(); // } // // public List<String> getInvalidFieldNames() { // return invalidFieldNames; // } // // public boolean hasInvalidField(String name) { // return invalidFieldNames.contains(name); // } // } // Path: src/main/java/viewmodel/CheckoutViewModel.java import business.ValidationException; import javax.servlet.http.HttpServletRequest; /** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package viewmodel; /** * */ @SuppressWarnings("unchecked") public class CheckoutViewModel extends BaseViewModel { private Boolean hasValidationErrorFlag; private Boolean hasOrderFailureFlag;
private ValidationException validationException;
nowucca/SimpleAffableBean
src/main/java/business/product/ProductDaoGuava.java
// Path: src/main/java/business/GuavaUtils.java // public final class GuavaUtils { // // private GuavaUtils() { // } // // public static <K,V> LoadingCache<K,V> makeCache(com.google.common.base.Function<K,V> cacheLoadFunction) { // return CacheBuilder.newBuilder(). // expireAfterWrite(1, TimeUnit.HOURS). // concurrencyLevel(8). // recordStats(). // maximumSize(1000). // initialCapacity(100). // build(CacheLoader.from(cacheLoadFunction)); // } // // // } // // Path: src/main/java/business/SimpleAffableDbException.java // public class SimpleAffableDbException extends RuntimeException { // // public SimpleAffableDbException(String message) { // super(message); // } // // public SimpleAffableDbException(String message, Throwable cause) { // super(message, cause); // } // // public static class SimpleAffableConnectionDbException extends SimpleAffableDbException { // public SimpleAffableConnectionDbException(String message, Throwable cause) { // super(message, cause); // } // } // // public static class SimpleAffableQueryDbException extends SimpleAffableDbException { // public SimpleAffableQueryDbException(String message) { // super(message); // } // // public SimpleAffableQueryDbException(String message, Throwable cause) { // super(message, cause); // } // } // // public static class SimpleAffableUpdateDbException extends SimpleAffableDbException { // public SimpleAffableUpdateDbException(String message) { // super(message); // } // // public SimpleAffableUpdateDbException(String message, Throwable cause) { // super(message, cause); // } // // } // }
import business.GuavaUtils; import business.SimpleAffableDbException; import com.google.common.cache.LoadingCache; import java.util.List;
/** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package business.product; /** */ public class ProductDaoGuava implements ProductDao { private ProductDao origin; private LoadingCache<Long, Product> productIdToProductCache; private LoadingCache<Long, List<Product>> categoryIdToProductsCache; @SuppressWarnings("ConstantConditions") public ProductDaoGuava(ProductDao origin) { this.origin = origin;
// Path: src/main/java/business/GuavaUtils.java // public final class GuavaUtils { // // private GuavaUtils() { // } // // public static <K,V> LoadingCache<K,V> makeCache(com.google.common.base.Function<K,V> cacheLoadFunction) { // return CacheBuilder.newBuilder(). // expireAfterWrite(1, TimeUnit.HOURS). // concurrencyLevel(8). // recordStats(). // maximumSize(1000). // initialCapacity(100). // build(CacheLoader.from(cacheLoadFunction)); // } // // // } // // Path: src/main/java/business/SimpleAffableDbException.java // public class SimpleAffableDbException extends RuntimeException { // // public SimpleAffableDbException(String message) { // super(message); // } // // public SimpleAffableDbException(String message, Throwable cause) { // super(message, cause); // } // // public static class SimpleAffableConnectionDbException extends SimpleAffableDbException { // public SimpleAffableConnectionDbException(String message, Throwable cause) { // super(message, cause); // } // } // // public static class SimpleAffableQueryDbException extends SimpleAffableDbException { // public SimpleAffableQueryDbException(String message) { // super(message); // } // // public SimpleAffableQueryDbException(String message, Throwable cause) { // super(message, cause); // } // } // // public static class SimpleAffableUpdateDbException extends SimpleAffableDbException { // public SimpleAffableUpdateDbException(String message) { // super(message); // } // // public SimpleAffableUpdateDbException(String message, Throwable cause) { // super(message, cause); // } // // } // } // Path: src/main/java/business/product/ProductDaoGuava.java import business.GuavaUtils; import business.SimpleAffableDbException; import com.google.common.cache.LoadingCache; import java.util.List; /** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package business.product; /** */ public class ProductDaoGuava implements ProductDao { private ProductDao origin; private LoadingCache<Long, Product> productIdToProductCache; private LoadingCache<Long, List<Product>> categoryIdToProductsCache; @SuppressWarnings("ConstantConditions") public ProductDaoGuava(ProductDao origin) { this.origin = origin;
productIdToProductCache = GuavaUtils.makeCache(origin::findByProductId);
nowucca/SimpleAffableBean
src/main/java/business/product/ProductDaoGuava.java
// Path: src/main/java/business/GuavaUtils.java // public final class GuavaUtils { // // private GuavaUtils() { // } // // public static <K,V> LoadingCache<K,V> makeCache(com.google.common.base.Function<K,V> cacheLoadFunction) { // return CacheBuilder.newBuilder(). // expireAfterWrite(1, TimeUnit.HOURS). // concurrencyLevel(8). // recordStats(). // maximumSize(1000). // initialCapacity(100). // build(CacheLoader.from(cacheLoadFunction)); // } // // // } // // Path: src/main/java/business/SimpleAffableDbException.java // public class SimpleAffableDbException extends RuntimeException { // // public SimpleAffableDbException(String message) { // super(message); // } // // public SimpleAffableDbException(String message, Throwable cause) { // super(message, cause); // } // // public static class SimpleAffableConnectionDbException extends SimpleAffableDbException { // public SimpleAffableConnectionDbException(String message, Throwable cause) { // super(message, cause); // } // } // // public static class SimpleAffableQueryDbException extends SimpleAffableDbException { // public SimpleAffableQueryDbException(String message) { // super(message); // } // // public SimpleAffableQueryDbException(String message, Throwable cause) { // super(message, cause); // } // } // // public static class SimpleAffableUpdateDbException extends SimpleAffableDbException { // public SimpleAffableUpdateDbException(String message) { // super(message); // } // // public SimpleAffableUpdateDbException(String message, Throwable cause) { // super(message, cause); // } // // } // }
import business.GuavaUtils; import business.SimpleAffableDbException; import com.google.common.cache.LoadingCache; import java.util.List;
/** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package business.product; /** */ public class ProductDaoGuava implements ProductDao { private ProductDao origin; private LoadingCache<Long, Product> productIdToProductCache; private LoadingCache<Long, List<Product>> categoryIdToProductsCache; @SuppressWarnings("ConstantConditions") public ProductDaoGuava(ProductDao origin) { this.origin = origin; productIdToProductCache = GuavaUtils.makeCache(origin::findByProductId); categoryIdToProductsCache = GuavaUtils.makeCache(origin::findByCategoryId); } public void clear() { // Clear the caches periodically productIdToProductCache.invalidateAll(); categoryIdToProductsCache.invalidateAll(); } @Override public Product findByProductId(long productId) { try { return productIdToProductCache.get(productId); } catch (Exception e) {
// Path: src/main/java/business/GuavaUtils.java // public final class GuavaUtils { // // private GuavaUtils() { // } // // public static <K,V> LoadingCache<K,V> makeCache(com.google.common.base.Function<K,V> cacheLoadFunction) { // return CacheBuilder.newBuilder(). // expireAfterWrite(1, TimeUnit.HOURS). // concurrencyLevel(8). // recordStats(). // maximumSize(1000). // initialCapacity(100). // build(CacheLoader.from(cacheLoadFunction)); // } // // // } // // Path: src/main/java/business/SimpleAffableDbException.java // public class SimpleAffableDbException extends RuntimeException { // // public SimpleAffableDbException(String message) { // super(message); // } // // public SimpleAffableDbException(String message, Throwable cause) { // super(message, cause); // } // // public static class SimpleAffableConnectionDbException extends SimpleAffableDbException { // public SimpleAffableConnectionDbException(String message, Throwable cause) { // super(message, cause); // } // } // // public static class SimpleAffableQueryDbException extends SimpleAffableDbException { // public SimpleAffableQueryDbException(String message) { // super(message); // } // // public SimpleAffableQueryDbException(String message, Throwable cause) { // super(message, cause); // } // } // // public static class SimpleAffableUpdateDbException extends SimpleAffableDbException { // public SimpleAffableUpdateDbException(String message) { // super(message); // } // // public SimpleAffableUpdateDbException(String message, Throwable cause) { // super(message, cause); // } // // } // } // Path: src/main/java/business/product/ProductDaoGuava.java import business.GuavaUtils; import business.SimpleAffableDbException; import com.google.common.cache.LoadingCache; import java.util.List; /** * BSD 3-Clause License * * Copyright (C) 2018 Steven Atkinson <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package business.product; /** */ public class ProductDaoGuava implements ProductDao { private ProductDao origin; private LoadingCache<Long, Product> productIdToProductCache; private LoadingCache<Long, List<Product>> categoryIdToProductsCache; @SuppressWarnings("ConstantConditions") public ProductDaoGuava(ProductDao origin) { this.origin = origin; productIdToProductCache = GuavaUtils.makeCache(origin::findByProductId); categoryIdToProductsCache = GuavaUtils.makeCache(origin::findByCategoryId); } public void clear() { // Clear the caches periodically productIdToProductCache.invalidateAll(); categoryIdToProductsCache.invalidateAll(); } @Override public Product findByProductId(long productId) { try { return productIdToProductCache.get(productId); } catch (Exception e) {
throw new SimpleAffableDbException("Encountered problem loading product id "+productId+" into cache", e);