├── .gitignore ├── LICENSE-2.0.txt ├── README.md ├── pom.xml ├── src ├── main │ ├── java │ │ └── io │ │ │ └── github │ │ │ └── rhkiswani │ │ │ └── javaff │ │ │ ├── beans │ │ │ └── ValuesHolder.java │ │ │ ├── detector │ │ │ ├── ApiDetector.java │ │ │ ├── ApiDetectorFactory.java │ │ │ ├── ApiDetectorUtil.java │ │ │ ├── ApiMetadata.java │ │ │ └── DefaultApiDetectorHandler.java │ │ │ ├── exceptions │ │ │ ├── DefaultExceptionHandler.java │ │ │ ├── ExceptionHandler.java │ │ │ ├── ExceptionHandlersFactory.java │ │ │ ├── ExceptionUtil.java │ │ │ └── SmartException.java │ │ │ ├── factory │ │ │ ├── AbstractFactory.java │ │ │ └── exceptions │ │ │ │ └── NoImplementationFoundException.java │ │ │ ├── format │ │ │ ├── DateFormatter.java │ │ │ ├── DefaultFormatter.java │ │ │ ├── FormatFactory.java │ │ │ ├── FormatUtil.java │ │ │ ├── Formatter.java │ │ │ ├── NumberFormatter.java │ │ │ ├── StringFormatter.java │ │ │ └── exception │ │ │ │ └── FormatException.java │ │ │ ├── httpclient │ │ │ ├── ApacheHttpClient.java │ │ │ ├── HttpClient.java │ │ │ ├── HttpClientFactory.java │ │ │ ├── HttpClientWrapper.java │ │ │ ├── exceptions │ │ │ │ └── HttpClientException.java │ │ │ └── util │ │ │ │ └── IOUtil.java │ │ │ ├── json │ │ │ ├── GsonHandler.java │ │ │ ├── JacksonHandler.java │ │ │ ├── JsonHandler.java │ │ │ ├── JsonHandlerFactory.java │ │ │ ├── annotations │ │ │ │ ├── GsonBean.java │ │ │ │ └── JacksonBean.java │ │ │ └── exceptions │ │ │ │ └── JsonException.java │ │ │ ├── lang │ │ │ ├── AbstractObjectHelper.java │ │ │ ├── EqualsHelper.java │ │ │ ├── HashCodeHelper.java │ │ │ ├── ToStringHelper.java │ │ │ ├── annotations │ │ │ │ ├── EqualsField.java │ │ │ │ ├── HashcodeField.java │ │ │ │ └── ToString.java │ │ │ ├── exceptions │ │ │ │ └── IllegalParamException.java │ │ │ └── utils │ │ │ │ ├── ArraysUtils.java │ │ │ │ ├── ObjectUtils.java │ │ │ │ └── StringUtils.java │ │ │ ├── locale │ │ │ ├── DefaultLocaleWorker.java │ │ │ ├── LocaleUtil.java │ │ │ ├── LocaleWorker.java │ │ │ ├── LocaleWorkerBuilder.java │ │ │ ├── LocaleWorkersFactory.java │ │ │ └── exceptions │ │ │ │ └── LocaleException.java │ │ │ ├── log │ │ │ ├── DefaultLog.java │ │ │ ├── Log.java │ │ │ ├── LogFactory.java │ │ │ ├── LogWrapper.java │ │ │ ├── Slf4jLog.java │ │ │ └── annotations │ │ │ │ └── Slf4jLogger.java │ │ │ ├── reflection │ │ │ ├── DefaultReflectionHelper.java │ │ │ ├── ReflectionHelper.java │ │ │ ├── ReflectionHelpersFactory.java │ │ │ ├── ReflectionUtil.java │ │ │ └── exception │ │ │ │ └── ReflectionException.java │ │ │ └── validation │ │ │ ├── Validator.java │ │ │ ├── ValidatorFactory.java │ │ │ ├── ValidatorWrapper.java │ │ │ └── exceptions │ │ │ └── ValidationException.java │ └── resources │ │ ├── app │ │ └── messages_en.properties │ │ └── exceptions │ │ └── messages_en.properties └── test │ └── java │ └── io │ └── github │ └── rhkiswani │ └── javaff │ ├── beans │ ├── Employee.java │ ├── EmployeeByIdAnnotation.java │ ├── EmployeeX.java │ ├── Person.java │ ├── PersonByIdAnnotation.java │ ├── PersonX.java │ └── ValuesHolderTest.java │ ├── detector │ ├── ApiMeadataTest.java │ └── DetectorFactoryTest.java │ ├── exceptions │ └── ExceptionHandlersFactoryTest.java │ ├── factory │ └── AbstractFactoryTest.java │ ├── format │ ├── AbstractFormatTest.java │ ├── DateFormatTest.java │ ├── FormatFactoryTest.java │ ├── FormatUtilTest.java │ ├── NumberFormatTest.java │ └── TextFormatTest.java │ ├── http │ ├── HttpClientTest.java │ └── WebTester.java │ ├── json │ └── JsonHandlerFactoryTest.java │ ├── lang │ ├── ArraysUtilsTest.java │ ├── ObjectUtilsTest.java │ └── StringUtilsTest.java │ ├── locale │ └── LocaleTest.java │ ├── logging │ ├── DefaultLoggersTest.java │ └── Slf4jLoggersTest.java │ ├── reflection │ └── ReflectionTest.java │ └── validation │ └── ValidatorFactoryTest.java └── tools ├── deploy.sh └── update_version.sh /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | samples/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | pom.xml.releaseBackup 5 | release.properties 6 | .DS_Store 7 | *.DS_Store 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | nbproject/private/ 24 | build/ 25 | nbbuild/ 26 | dist/ 27 | nbdist/ 28 | .nb-gradle/ -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/beans/ValuesHolder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.beans; 17 | 18 | import io.github.rhkiswani.javaff.json.JsonHandler; 19 | import io.github.rhkiswani.javaff.json.JsonHandlerFactory; 20 | import io.github.rhkiswani.javaff.lang.utils.ObjectUtils; 21 | import io.github.rhkiswani.javaff.lang.utils.StringUtils; 22 | 23 | import java.io.Serializable; 24 | /** 25 | * @author Mohamed Kiswani 26 | * @since 0.0.1 27 | * 28 | */ 29 | public class ValuesHolder implements Serializable{ 30 | 31 | @Override 32 | public boolean equals(Object obj) { 33 | return ObjectUtils.isEqual(this, obj); 34 | } 35 | 36 | @Override 37 | public int hashCode() { 38 | return ObjectUtils.toHashCode(this); 39 | } 40 | 41 | @Override 42 | public String toString() { 43 | return StringUtils.toString(this); 44 | } 45 | 46 | public T clone() { 47 | JsonHandler jh = JsonHandlerFactory.getJsonHandler(this.getClass()); 48 | String json = jh.toJson(this); 49 | return (T) jh.fromJson(json, getClass()); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/detector/ApiDetector.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.detector; 17 | 18 | /** 19 | * @author Mohamed Kiswani 20 | * @since 0.0.1 21 | * 22 | */ 23 | public interface ApiDetector { 24 | boolean isAvailable(ApiMetadata apiMetadata); 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/detector/ApiDetectorFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.detector; 17 | 18 | import io.github.rhkiswani.javaff.factory.AbstractFactory; 19 | 20 | /** 21 | * @author Mohamed Kiswani 22 | * @since 0.0.1 23 | * @see io.github.rhkiswani.javaff.factory.AbstractFactory 24 | * 25 | */ 26 | public class ApiDetectorFactory extends AbstractFactory{ 27 | private static ApiDetectorFactory instance = new ApiDetectorFactory(); 28 | 29 | private ApiDetectorFactory(){ 30 | } 31 | 32 | public static ApiDetectorFactory instance(){ 33 | return instance; 34 | } 35 | 36 | @Override 37 | protected ApiDetector getDefault(Class targetClazz) { 38 | return new DefaultApiDetectorHandler(); 39 | } 40 | 41 | public static ApiDetector getDetector() { 42 | return instance.create(ApiDetectorFactory.class); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/detector/ApiDetectorUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.detector; 17 | 18 | /** 19 | * @author Mohamed Kiswani 20 | * @since 0.0.1 21 | * 22 | */ 23 | public class ApiDetectorUtil { 24 | 25 | public static final ApiMetadata JPA_API_METADATA = new ApiMetadata("javax.persistence", "javax.persistence.Id"); 26 | public static final ApiMetadata SLF4_API_METADATA = new ApiMetadata("org.slf4j", "org.slf4j.Logger"); 27 | public static final ApiMetadata JACKSON_API_METADATA = new ApiMetadata("com.fasterxml.jackson.core", "com.fasterxml.jackson.databind.ObjectMapper"); 28 | public static final ApiMetadata APACHE_HTTPCLIENT_API_METADATA = new ApiMetadata("org.apache.httpcomponents", "org.apache.http.NameValuePair"); 29 | public static final ApiMetadata GSON_METADATA = new ApiMetadata("com.google.code.gson", "com.google.gson.Gson"); 30 | 31 | private static final Boolean isJPAAvailable = ApiDetectorFactory.getDetector().isAvailable(JPA_API_METADATA); 32 | private static final Boolean isSlf4jAvailable = ApiDetectorFactory.getDetector().isAvailable(SLF4_API_METADATA); 33 | private static final Boolean isJacksonAvailable = ApiDetectorFactory.getDetector().isAvailable(JACKSON_API_METADATA); 34 | private static final Boolean isGsonAvailable = ApiDetectorFactory.getDetector().isAvailable(GSON_METADATA); 35 | private static final Boolean isApacheHttpClientAvailable = ApiDetectorFactory.getDetector().isAvailable(APACHE_HTTPCLIENT_API_METADATA); 36 | 37 | 38 | public static Boolean isJPAAvailable() { 39 | return isJPAAvailable; 40 | } 41 | 42 | public static Boolean isSlf4jAvailable() { 43 | return isSlf4jAvailable; 44 | } 45 | 46 | public static Boolean isJacksonAvailable() { 47 | return isJacksonAvailable; 48 | } 49 | 50 | public static Boolean isGsonAvailable() { 51 | return isGsonAvailable; 52 | } 53 | 54 | public static Boolean isApacheHttpClientAvailable() { 55 | return isApacheHttpClientAvailable; 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/detector/ApiMetadata.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.detector; 2 | 3 | import io.github.rhkiswani.javaff.beans.ValuesHolder; 4 | import io.github.rhkiswani.javaff.lang.annotations.EqualsField; 5 | 6 | /** 7 | * @author Mohamed Kiswani 8 | * @since 0.0.1 9 | * @see io.github.rhkiswani.javaff.beans.ValuesHolder 10 | * 11 | */ 12 | public class ApiMetadata extends ValuesHolder{ 13 | 14 | private String name; 15 | @EqualsField 16 | private String groupId; 17 | @EqualsField 18 | private String mainClassName; 19 | private String frameworkUrl; 20 | 21 | public ApiMetadata(){ 22 | 23 | } 24 | 25 | public ApiMetadata(String groupId, String mainClassName){ 26 | this(null, groupId, mainClassName, null); 27 | } 28 | 29 | public ApiMetadata(String name, String groupId, String mainClassName, String frameworkUrl){ 30 | this.name = name; 31 | this.groupId = groupId; 32 | this.mainClassName = mainClassName; 33 | this.frameworkUrl = frameworkUrl; 34 | } 35 | 36 | public String getName() { 37 | return name; 38 | } 39 | 40 | public void setName(String name) { 41 | this.name = name; 42 | } 43 | 44 | public String getGroupId() { 45 | return groupId; 46 | } 47 | 48 | public void setGroupId(String groupId) { 49 | this.groupId = groupId; 50 | } 51 | 52 | public String getMainClassName() { 53 | return mainClassName; 54 | } 55 | 56 | public void setMainClassName(String mainClassName) { 57 | this.mainClassName = mainClassName; 58 | } 59 | 60 | public String getFrameworkUrl() { 61 | return frameworkUrl; 62 | } 63 | 64 | public void setFrameworkUrl(String frameworkUrl) { 65 | this.frameworkUrl = frameworkUrl; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/detector/DefaultApiDetectorHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.detector; 17 | 18 | import io.github.rhkiswani.javaff.exceptions.SmartException; 19 | import io.github.rhkiswani.javaff.lang.exceptions.IllegalParamException; 20 | import io.github.rhkiswani.javaff.reflection.ReflectionUtil; 21 | 22 | /** 23 | * @author Mohamed Kiswani 24 | * @since 0.0.1 25 | * @see io.github.rhkiswani.javaff.detector.ApiDetector 26 | * 27 | */ 28 | class DefaultApiDetectorHandler implements ApiDetector{ 29 | public boolean isAvailable(ApiMetadata apiMetadata){ 30 | if (apiMetadata == null){ 31 | throw new IllegalParamException(SmartException.NULL_VAL, "Api Metadata"); 32 | } 33 | if (apiMetadata.getMainClassName() == null){ 34 | throw new IllegalParamException(SmartException.NULL_VAL, "Api Main Class Name"); 35 | } 36 | return ReflectionUtil.isPresent(apiMetadata.getMainClassName()); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/exceptions/DefaultExceptionHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.exceptions; 17 | 18 | import io.github.rhkiswani.javaff.log.Log; 19 | import io.github.rhkiswani.javaff.log.LogFactory; 20 | 21 | /** 22 | * @author Mohamed Kiswani 23 | * @since 0.0.1 24 | * @see io.github.rhkiswani.javaff.exceptions.ExceptionHandler 25 | * 26 | */ 27 | class DefaultExceptionHandler implements ExceptionHandler{ 28 | private static final Log LOGGER = LogFactory.getLogger(DefaultExceptionHandler.class); 29 | 30 | public void handle(Throwable t){ 31 | if (!Boolean.valueOf(System.getProperty("isTest", "false"))) { 32 | LOGGER.error(t.getMessage(), t); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/exceptions/ExceptionHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.exceptions; 17 | 18 | /** 19 | * @author Mohamed Kiswani 20 | * @since 0.0.1 21 | * 22 | */ 23 | public interface ExceptionHandler { 24 | void handle(Throwable t); 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/exceptions/ExceptionHandlersFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.exceptions; 17 | 18 | import io.github.rhkiswani.javaff.factory.AbstractFactory; 19 | 20 | /** 21 | * @author Mohamed Kiswani 22 | * @see io.github.rhkiswani.javaff.factory.AbstractFactory 23 | * @since 0.0.1 24 | * 25 | */ 26 | public class ExceptionHandlersFactory extends AbstractFactory{ 27 | private static ExceptionHandlersFactory instance = new ExceptionHandlersFactory(); 28 | 29 | private ExceptionHandlersFactory(){ 30 | add(Throwable.class, new DefaultExceptionHandler()); 31 | } 32 | 33 | public static ExceptionHandlersFactory instance(){ 34 | return instance; 35 | } 36 | 37 | @Override 38 | protected ExceptionHandler getDefault(Class targetClazz) { 39 | return new DefaultExceptionHandler(); 40 | } 41 | 42 | public static ExceptionHandler getExceptionHandler(Class aClass) { 43 | return instance.create(aClass); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/exceptions/ExceptionUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.exceptions; 17 | 18 | import io.github.rhkiswani.javaff.lang.exceptions.IllegalParamException; 19 | 20 | /** 21 | * @author Mohamed Kiswani 22 | * @since 0.0.1 23 | * 24 | */ 25 | public class ExceptionUtil { 26 | 27 | public static void handle(Throwable t){ 28 | if (t == null){ 29 | throw new IllegalParamException(SmartException.NULL_VAL, "Exception"); 30 | } 31 | ExceptionHandlersFactory.getExceptionHandler(t.getClass()).handle(t); 32 | } 33 | 34 | public static Throwable getRootCause(Throwable throwable) { 35 | if (throwable == null) { 36 | return null; 37 | } 38 | 39 | Throwable cause = throwable; 40 | Throwable rootCause; 41 | while ((rootCause = cause.getCause()) != null) { 42 | cause = rootCause; 43 | } 44 | 45 | return cause; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/exceptions/SmartException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.exceptions; 17 | 18 | import io.github.rhkiswani.javaff.lang.utils.ArraysUtils; 19 | import io.github.rhkiswani.javaff.locale.LocaleUtil; 20 | 21 | /** 22 | * @author Mohamed Kiswani 23 | * @since 0.0.1 24 | * 25 | */ 26 | public class SmartException extends RuntimeException{ 27 | 28 | 29 | public static final String NULL_VAL = "NULL_VAL"; 30 | public static final String NOT_FOUND = "NOT_FOUND"; 31 | public static final String TYPE_ERROR = "TYPE_ERROR"; 32 | public static final String EXCEEDS_LIMIT = "EXCEEDS_LIMIT"; 33 | public static final String FORMAT_EXCEPTION = "FORMAT_EXCEPTION"; 34 | public static final String ALREADY_EXIST = "ALREADY_EXIST"; 35 | public static final String NEGATIVE_VAL = "NEGATIVE_VAL"; 36 | public static final String HTTP_ERROR = "HTTP_ERROR"; 37 | public static final String NO_IMPLEMENTATION_FOUND = "NO_IMPLEMENTATION_FOUND"; 38 | public static final String NO_IMPLEMENTATION_FOUND_WITH_NO_LINK = "NO_IMPLEMENTATION_FOUND_WITH_NO_LINK"; 39 | 40 | private Object[] errorMsgParams = null; 41 | 42 | public SmartException(String message) { 43 | super(message); 44 | } 45 | 46 | public SmartException(String message, Object... errorMsgParams) { 47 | super(message); 48 | this.errorMsgParams = errorMsgParams; 49 | } 50 | 51 | public SmartException(String message, Throwable cause) { 52 | super(message, cause); 53 | } 54 | 55 | public SmartException(Throwable cause) { 56 | super(cause); 57 | } 58 | 59 | @Override 60 | public String getMessage() { 61 | if (!ArraysUtils.isEmpty(errorMsgParams)){ 62 | return LocaleUtil.getString(super.getMessage(), SmartException.class, errorMsgParams); 63 | } else { 64 | return LocaleUtil.getString(super.getMessage(), SmartException.class, null); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/factory/AbstractFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.factory; 17 | 18 | import io.github.rhkiswani.javaff.exceptions.SmartException; 19 | import io.github.rhkiswani.javaff.factory.exceptions.NoImplementationFoundException; 20 | import io.github.rhkiswani.javaff.lang.exceptions.IllegalParamException; 21 | import io.github.rhkiswani.javaff.lang.utils.ObjectUtils; 22 | import io.github.rhkiswani.javaff.lang.utils.StringUtils; 23 | 24 | import java.util.Collection; 25 | import java.util.LinkedHashMap; 26 | import java.util.Map; 27 | import java.util.Set; 28 | 29 | /** 30 | * @author Mohamed Kiswani 31 | * @since 0.0.1 32 | * 33 | */ 34 | public abstract class AbstractFactory { 35 | 36 | private Map map = new LinkedHashMap<>(); 37 | 38 | private T userDefaultImpl = null; 39 | 40 | public void add(Class targetClass, T t){ 41 | if (map.get(targetClass) != null){ 42 | throw new IllegalParamException(SmartException.ALREADY_EXIST, targetClass, "please use overrideImp method instated"); 43 | } 44 | Class tmpClass = checkClass(targetClass); 45 | map.put(tmpClass, t); 46 | } 47 | 48 | private Class checkClass(Class targetClass) { 49 | Class tmpClass = targetClass; 50 | if (tmpClass.isPrimitive()){ 51 | tmpClass = ObjectUtils.primitiveToWrapper(targetClass); 52 | } 53 | return tmpClass; 54 | } 55 | 56 | public void overrideImp(Class targetClass, T t){ 57 | Class tmpClass = checkClass(targetClass); 58 | map.put(tmpClass, t); 59 | } 60 | 61 | public T remove(Class targetClass){ 62 | Class tmpClass = checkClass(targetClass); 63 | return map.remove(tmpClass); 64 | } 65 | 66 | protected T create(Class clazz){ 67 | if (clazz == null){ 68 | throw new IllegalParamException(SmartException.NULL_VAL, "Target Class"); 69 | } 70 | if (userDefaultImpl != null){ 71 | return userDefaultImpl; 72 | } 73 | Class targetClass = checkClass(clazz); 74 | Set classSet = map.keySet(); 75 | Class[] keys = classSet.toArray(new Class[classSet.size()]); 76 | for (int i = keys.length - 1 ; i >=0 ; i--){ 77 | Class aClass = keys[i]; 78 | if (aClass.isAssignableFrom(targetClass) || targetClass.isAnnotationPresent(aClass)){ 79 | return map.get(aClass); 80 | } 81 | } 82 | return getDefault(targetClass); 83 | } 84 | 85 | public Collection listImplementations(){ 86 | return map.values(); 87 | } 88 | 89 | public void setDefault(T userDefaultImpl) { 90 | this.userDefaultImpl = userDefaultImpl; 91 | } 92 | 93 | protected T getDefault(Class targetClazz) { 94 | if (StringUtils.isNotEmpty(getDefaultImplementationUrl())){ 95 | throw new NoImplementationFoundException(SmartException.NO_IMPLEMENTATION_FOUND, targetClazz, this.getClass().getSimpleName(), getDefaultImplementationUrl()); 96 | } else { 97 | throw new NoImplementationFoundException(SmartException.NO_IMPLEMENTATION_FOUND_WITH_NO_LINK, targetClazz, this.getClass().getSimpleName()); 98 | } 99 | } 100 | 101 | protected String getDefaultImplementationUrl(){ 102 | return ""; 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/factory/exceptions/NoImplementationFoundException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.factory.exceptions; 17 | 18 | import io.github.rhkiswani.javaff.exceptions.SmartException; 19 | 20 | /** 21 | * @author Mohamed Kiswani 22 | * @since 0.0.1 23 | * @see SmartException 24 | */ 25 | public class NoImplementationFoundException extends SmartException { 26 | public NoImplementationFoundException(String errorMsg, Object... errorMsgParams) { 27 | super(errorMsg, errorMsgParams); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/format/DateFormatter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.format; 17 | 18 | import io.github.rhkiswani.javaff.exceptions.SmartException; 19 | import io.github.rhkiswani.javaff.format.exception.FormatException; 20 | import io.github.rhkiswani.javaff.lang.utils.StringUtils; 21 | import io.github.rhkiswani.javaff.log.Log; 22 | import io.github.rhkiswani.javaff.log.LogFactory; 23 | 24 | import java.text.MessageFormat; 25 | import java.text.SimpleDateFormat; 26 | import java.util.Date; 27 | 28 | /** 29 | * @author Mohamed Kiswani 30 | * @since 0.0.1 31 | * @see io.github.rhkiswani.javaff.format.DefaultFormatter 32 | * @see io.github.rhkiswani.javaff.format.Formatter 33 | * 34 | */ 35 | class DateFormatter extends DefaultFormatter { 36 | 37 | private final Log LOGGER = LogFactory.getLogger(this.getClass()); 38 | 39 | @Override 40 | protected String formatVal(Date date, Object... params) { 41 | if (params.length > 0 && params[0] != null){ 42 | try { 43 | if (StringUtils.isEmpty(params[0] + "")){ 44 | throw new FormatException(SmartException.TYPE_ERROR, "Date format", date); 45 | } 46 | SimpleDateFormat format = new SimpleDateFormat(params[0].toString()); 47 | return format.format(date); 48 | }catch (Throwable t){ 49 | LOGGER.error("Failed to format {0} due to {1} ", date, t.getMessage()); 50 | throw new FormatException(SmartException.TYPE_ERROR, "Date format", date); 51 | } 52 | } else { 53 | return MessageFormat.format("{0}", date); 54 | } 55 | } 56 | 57 | public String format(Date date, String pattern){ 58 | return format(date , new Object[]{pattern}); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/format/DefaultFormatter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.format; 17 | 18 | import io.github.rhkiswani.javaff.format.exception.FormatException; 19 | import io.github.rhkiswani.javaff.lang.utils.ArraysUtils; 20 | 21 | /** 22 | * @author Mohamed Kiswani 23 | * @since 0.0.1 24 | * @see io.github.rhkiswani.javaff.format.Formatter 25 | */ 26 | public abstract class DefaultFormatter extends Formatter { 27 | 28 | protected abstract O formatVal(I i, Object[] params); 29 | 30 | @Override 31 | protected O format(I i, Object[] params) throws FormatException { 32 | if (i == null){ 33 | return null; 34 | } 35 | if (!ArraysUtils.isEmpty(params)){ 36 | ArraysUtils.replace(params, null, ""); 37 | return formatVal(i, params); 38 | } 39 | return formatVal(i, new Object[]{}); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/format/FormatFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.format; 17 | 18 | import io.github.rhkiswani.javaff.factory.AbstractFactory; 19 | 20 | import java.util.Date; 21 | 22 | /** 23 | * @author Mohamed Kiswani 24 | * @since 0.0.1 25 | * @see io.github.rhkiswani.javaff.factory.AbstractFactory 26 | * 27 | */ 28 | public class FormatFactory extends AbstractFactory { 29 | 30 | private static FormatFactory instance = new FormatFactory(); 31 | 32 | private FormatFactory(){ 33 | add(Date.class, new DateFormatter()); 34 | add(String.class, new StringFormatter()); 35 | add(Number.class, new NumberFormatter()); 36 | } 37 | 38 | public static FormatFactory instance(){ 39 | return instance; 40 | } 41 | 42 | protected Formatter getDefault(Class targetClazz){ 43 | return new StringFormatter(); 44 | } 45 | 46 | public static Formatter getFormatter(Class aClass) { 47 | return instance.create(aClass); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/format/FormatUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.format; 17 | 18 | /** 19 | * @author Mohamed Kiswani 20 | * @since 0.0.1 21 | * 22 | */ 23 | public class FormatUtil { 24 | 25 | public static String formatString(String str, Object... params){ 26 | return format(str, params); 27 | } 28 | 29 | public static T format(Object obj, Object... params){ 30 | if (obj == null){ 31 | return null; 32 | } 33 | return (T) FormatFactory.getFormatter(obj.getClass()).format(obj, params); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/format/Formatter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.format; 17 | 18 | import io.github.rhkiswani.javaff.format.exception.FormatException; 19 | 20 | /** 21 | * @author Mohamed Kiswani 22 | * @since 0.0.1 23 | * 24 | */ 25 | public abstract class Formatter { 26 | 27 | protected abstract O format(I in, Object[] params) throws FormatException; 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/format/NumberFormatter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.format; 17 | 18 | import java.text.MessageFormat; 19 | 20 | /** 21 | * @author Mohamed Kiswani 22 | * @since 0.0.1 23 | * @see io.github.rhkiswani.javaff.format.DefaultFormatter 24 | * @see io.github.rhkiswani.javaff.format.Formatter 25 | */ 26 | class NumberFormatter extends DefaultFormatter { 27 | 28 | @Override 29 | protected String formatVal(Number number, Object... params) { 30 | return MessageFormat.format("{0}", number); 31 | } 32 | 33 | public String format(Number num){ 34 | return format(num, new Object[]{}); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/format/StringFormatter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.format; 17 | 18 | import io.github.rhkiswani.javaff.log.Log; 19 | import io.github.rhkiswani.javaff.log.LogFactory; 20 | 21 | import java.text.MessageFormat; 22 | 23 | /** 24 | * @author Mohamed Kiswani 25 | * @since 0.0.1 26 | * @see io.github.rhkiswani.javaff.format.DefaultFormatter 27 | * @see io.github.rhkiswani.javaff.format.Formatter 28 | */ 29 | class StringFormatter extends DefaultFormatter { 30 | private static final Log LOGGER = LogFactory.getLogger(StringFormatter.class); 31 | 32 | @Override 33 | protected String formatVal(String string, Object... params) { 34 | try { 35 | return MessageFormat.format(string, params); 36 | } catch (Exception e){ 37 | LOGGER.error("Failed to format {0}", string); 38 | return string; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/format/exception/FormatException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.format.exception; 17 | 18 | import io.github.rhkiswani.javaff.exceptions.SmartException; 19 | 20 | /** 21 | * @author Mohamed Kiswani 22 | * @since 0.0.1 23 | * @see io.github.rhkiswani.javaff.exceptions.SmartException 24 | * 25 | */ 26 | public class FormatException extends SmartException{ 27 | 28 | public FormatException(String errorMsg, Object... errorMsgParams) { 29 | super(errorMsg, errorMsgParams); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/httpclient/ApacheHttpClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.httpclient; 17 | 18 | import io.github.rhkiswani.javaff.exceptions.SmartException; 19 | import io.github.rhkiswani.javaff.httpclient.exceptions.HttpClientException; 20 | import io.github.rhkiswani.javaff.httpclient.util.IOUtil; 21 | import io.github.rhkiswani.javaff.json.JsonHandlerFactory; 22 | import io.github.rhkiswani.javaff.reflection.ReflectionUtil; 23 | import org.apache.http.Header; 24 | import org.apache.http.HttpResponse; 25 | import org.apache.http.HttpStatus; 26 | import org.apache.http.NameValuePair; 27 | import org.apache.http.client.entity.UrlEncodedFormEntity; 28 | import org.apache.http.client.methods.*; 29 | import org.apache.http.entity.StringEntity; 30 | import org.apache.http.impl.client.CloseableHttpClient; 31 | import org.apache.http.impl.client.HttpClientBuilder; 32 | import org.apache.http.message.BasicNameValuePair; 33 | 34 | import java.io.UnsupportedEncodingException; 35 | import java.util.ArrayList; 36 | import java.util.HashMap; 37 | import java.util.List; 38 | import java.util.Map; 39 | 40 | /** 41 | * @author Mohamed Kiswani 42 | * @since 0.0.20 43 | * 44 | */ 45 | public class ApacheHttpClient implements HttpClient{ 46 | 47 | @Override 48 | public String postJson(String url, String json, Map headers) throws HttpClientException { 49 | return doJsonRequest(new HttpPost(url), json, headers); 50 | } 51 | 52 | @Override 53 | public String putJson(String url, String json, Map headers) throws HttpClientException { 54 | return doJsonRequest(new HttpPut(url), json, headers); 55 | } 56 | 57 | private String doJsonRequest(HttpRequestBase method, String json, Map headers) { 58 | try { 59 | if (json == null){ 60 | throw new HttpClientException(SmartException.NULL_VAL, "Json Object"); 61 | } 62 | CloseableHttpClient c = HttpClientBuilder.create().build(); 63 | ((HttpEntityEnclosingRequestBase) method).setEntity(new StringEntity(json)); 64 | method.setHeader("Accept", "application/json"); 65 | method.setHeader("Content-type", "application/json"); 66 | setHeaders(method, headers); 67 | return handleResponse(method, c); 68 | } catch (Exception e) { 69 | throw new HttpClientException(e.getMessage()); 70 | } 71 | } 72 | 73 | private String handleResponse(HttpRequestBase method, CloseableHttpClient c) { 74 | HashMap hashMap = new HashMap<>(); 75 | try { 76 | HttpResponse response = c.execute(method); 77 | hashMap.put("response", IOUtil.inputStreamToString(response.getEntity().getContent())); 78 | hashMap.put("status", response.getStatusLine().getStatusCode()); 79 | hashMap.put("headers", IOUtil.headersToMap(response.getAllHeaders())); 80 | } catch (Exception ex) { 81 | hashMap.put("status", HttpStatus.SC_BAD_REQUEST ); 82 | hashMap.put("errors", ReflectionUtil.getErrorsAsArray(ex)); 83 | } 84 | return JsonHandlerFactory.getJsonHandler(HashMap.class).toJson(hashMap); 85 | } 86 | 87 | @Override 88 | public String post(String url, Map params, Map headers) throws HttpClientException { 89 | return doRequest(new HttpPost(url), params, headers); 90 | } 91 | 92 | @Override 93 | public String put(String url, Map params, Map headers) throws HttpClientException { 94 | return doRequest(new HttpPut(url), params, headers); 95 | } 96 | 97 | private String doRequest(HttpRequestBase method, Map params, Map headers) { 98 | try { 99 | CloseableHttpClient c = prepareRequest(method, params); 100 | setHeaders(method, headers); 101 | return handleResponse(method, c); 102 | } catch (Exception e) { 103 | throw new HttpClientException(e.getMessage()); 104 | } 105 | } 106 | 107 | private CloseableHttpClient prepareRequest(HttpRequestBase method, Map params) throws UnsupportedEncodingException { 108 | CloseableHttpClient c = HttpClientBuilder.create().build(); 109 | if(params != null){ 110 | List urlParameters = new ArrayList<>(); 111 | for (String key : params.keySet()) { 112 | 113 | urlParameters.add(new BasicNameValuePair(key, params.get(key))); 114 | } 115 | if (method instanceof HttpEntityEnclosingRequestBase){ 116 | ((HttpEntityEnclosingRequestBase) method).setEntity(new UrlEncodedFormEntity(urlParameters)); 117 | } 118 | } 119 | return c; 120 | } 121 | 122 | private void setHeaders(HttpRequestBase method, Map headers) { 123 | if(headers != null){ 124 | for (String header : headers.keySet()) { 125 | method.setHeader(header, headers.get(header)); 126 | } 127 | } 128 | } 129 | 130 | @Override 131 | public String get(String url, Map params, Map headers) throws HttpClientException { 132 | String urlWithParams = paramsToString(url, params); 133 | return doRequest(new HttpGet(urlWithParams), params, headers); 134 | } 135 | 136 | private String paramsToString(String url, Map params) { 137 | String urlWithParams = url; 138 | if(params != null){ 139 | urlWithParams += "?"; 140 | for (String key : params.keySet()) { 141 | urlWithParams += key + "=" + params.get(key) +"&"; 142 | } 143 | } 144 | return urlWithParams; 145 | } 146 | 147 | @Override 148 | public Map head(String url, Map params, Map headers) throws HttpClientException { 149 | try { 150 | HttpHead method = new HttpHead(url); 151 | CloseableHttpClient client = prepareRequest(method, params); 152 | setHeaders(method, headers); 153 | HttpResponse response = client.execute(method); 154 | Header[] s = response.getAllHeaders(); 155 | Map returnedHeaders = new HashMap<>(); 156 | for (Header header : s) { 157 | returnedHeaders.put(header.getName(), header.getValue()); 158 | } 159 | return returnedHeaders; 160 | } catch (Exception e) { 161 | throw new HttpClientException(e.getMessage()); 162 | } 163 | } 164 | 165 | @Override 166 | public String delete(String url, Map params, Map headers) throws HttpClientException { 167 | String urlWithParams = paramsToString(url, params); 168 | return doRequest(new HttpDelete(urlWithParams), params, headers); 169 | } 170 | 171 | @Override 172 | public Map options(String url, Map params, Map headers) throws HttpClientException { 173 | return head(url, params, headers); 174 | } 175 | 176 | 177 | @Override 178 | public String patchJson(String url, String json, Map headers) throws HttpClientException { 179 | return doJsonRequest(new HttpPatch(url), json, headers); 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/httpclient/HttpClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.httpclient; 17 | 18 | import io.github.rhkiswani.javaff.httpclient.exceptions.HttpClientException; 19 | 20 | import java.util.Map; 21 | 22 | /** 23 | * @author Mohamed Kiswani 24 | * @since 0.0.20 25 | * 26 | */ 27 | public interface HttpClient { 28 | 29 | String postJson(String url, String json, Map headers) throws HttpClientException; 30 | 31 | String putJson(String url, String json, Map headers) throws HttpClientException; 32 | 33 | String post(String url, Map params, Map headers) throws HttpClientException; 34 | 35 | String put(String url, Map params, Map headers) throws HttpClientException; 36 | 37 | String get(String url, Map params, Map headers) throws HttpClientException; 38 | 39 | Map head(String url, Map params, Map headers) throws HttpClientException; 40 | 41 | String delete(String url, Map params, Map headers) throws HttpClientException; 42 | 43 | Map options(String url, Map params, Map headers) throws HttpClientException; 44 | 45 | String patchJson(String url, String json, Map headers) throws HttpClientException; 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/httpclient/HttpClientFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.httpclient; 17 | 18 | import io.github.rhkiswani.javaff.detector.ApiDetectorUtil; 19 | import io.github.rhkiswani.javaff.factory.AbstractFactory; 20 | 21 | /** 22 | * @author Mohamed Kiswani 23 | * @since 0.0.20 24 | * @see AbstractFactory 25 | */ 26 | public class HttpClientFactory extends AbstractFactory{ 27 | 28 | private static HttpClientFactory instance = new HttpClientFactory(); 29 | 30 | private HttpClientFactory(){ 31 | if (ApiDetectorUtil.isApacheHttpClientAvailable()){ 32 | add(Object.class, new ApacheHttpClient()); 33 | } 34 | } 35 | 36 | public static HttpClientFactory instance(){ 37 | return instance; 38 | } 39 | 40 | @Override 41 | protected String getDefaultImplementationUrl() { 42 | return "https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient"; 43 | } 44 | 45 | public static HttpClient getHttpClient(Class aClass) { 46 | return new HttpClientWrapper(instance.create(aClass)); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/httpclient/HttpClientWrapper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.httpclient; 17 | 18 | import io.github.rhkiswani.javaff.httpclient.exceptions.HttpClientException; 19 | 20 | import java.util.Map; 21 | 22 | /** 23 | * @author Mohamed Kiswani 24 | * @since 0.0.20 25 | * @see io.github.rhkiswani.javaff.httpclient.HttpClient 26 | */ 27 | public class HttpClientWrapper implements HttpClient{ 28 | private HttpClient httpClient; 29 | 30 | public HttpClientWrapper(HttpClient httpClient){ 31 | this.httpClient = httpClient; 32 | } 33 | 34 | @Override 35 | public String postJson(String url, String json, Map headers) throws HttpClientException { 36 | return httpClient.postJson(url, json, headers); 37 | } 38 | 39 | @Override 40 | public String putJson(String url, String json, Map headers) throws HttpClientException { 41 | return httpClient.putJson(url, json, headers); 42 | } 43 | 44 | @Override 45 | public String post(String url, Map params, Map headers) throws HttpClientException { 46 | return httpClient.post(url, params, headers); 47 | } 48 | 49 | @Override 50 | public String put(String url, Map params, Map headers) throws HttpClientException { 51 | return httpClient.put(url, params, headers); 52 | } 53 | 54 | @Override 55 | public String get(String url, Map params, Map headers) throws HttpClientException { 56 | return httpClient.get(url, params, headers); 57 | } 58 | 59 | @Override 60 | public Map head(String url, Map params, Map headers) throws HttpClientException { 61 | return httpClient.head(url, params, headers); 62 | } 63 | 64 | @Override 65 | public String delete(String url, Map params, Map headers) throws HttpClientException { 66 | return httpClient.delete(url, params, headers); 67 | } 68 | 69 | @Override 70 | public Map options(String url, Map params, Map headers) throws HttpClientException { 71 | return httpClient.options(url, params, headers); 72 | } 73 | 74 | @Override 75 | public String patchJson(String url, String json, Map headers) throws HttpClientException { 76 | return httpClient.patchJson(url, json, headers); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/httpclient/exceptions/HttpClientException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.httpclient.exceptions; 17 | 18 | import io.github.rhkiswani.javaff.exceptions.SmartException; 19 | 20 | /** 21 | * @author Mohamed Kiswani 22 | * @since 0.0.20 23 | * @see SmartException 24 | */ 25 | public class HttpClientException extends SmartException{ 26 | 27 | public HttpClientException(String errorMsg, Object... errorMsgParams) { 28 | super(errorMsg, errorMsgParams); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/httpclient/util/IOUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.github.rhkiswani.javaff.httpclient.util; 18 | 19 | import org.apache.http.Header; 20 | 21 | import java.io.BufferedReader; 22 | import java.io.IOException; 23 | import java.io.InputStream; 24 | import java.io.InputStreamReader; 25 | import java.util.HashMap; 26 | import java.util.Map; 27 | 28 | /** 29 | * @author Mohamed Kiswani 30 | * @since 0.0.25 31 | * 32 | */ 33 | public class IOUtil { 34 | 35 | public static String inputStreamToString(InputStream inputStream) throws IOException { 36 | BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream)); 37 | StringBuilder result = new StringBuilder(); 38 | String line = ""; 39 | while ((line = rd.readLine()) != null) { 40 | result.append(line); 41 | } 42 | return result.toString(); 43 | } 44 | 45 | public static Map headersToMap(Header[] headers) { 46 | HashMap map = new HashMap<>(); 47 | for (Header header : headers) { 48 | map.put(header.getName(), header.getValue()); 49 | } 50 | return map; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/json/GsonHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.json; 17 | 18 | import com.google.gson.Gson; 19 | import com.google.gson.GsonBuilder; 20 | import io.github.rhkiswani.javaff.json.exceptions.JsonException; 21 | 22 | import java.lang.reflect.Modifier; 23 | 24 | /** 25 | * @author Mohamed Kiswani 26 | * @since 0.0.1 27 | * @see io.github.rhkiswani.javaff.json.JsonHandler 28 | */ 29 | class GsonHandler implements JsonHandler { 30 | private final Gson gson = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.STATIC) .create(); 31 | 32 | 33 | @Override 34 | public T fromJson(String json, Class clazz) { 35 | try { 36 | return (T) gson.fromJson(json, clazz); 37 | } catch (Throwable t){ 38 | throw new JsonException(t.getMessage()); 39 | } 40 | } 41 | 42 | @Override 43 | public String toJson(Object object) { 44 | return gson.toJson(object); 45 | } 46 | 47 | @Override 48 | public Object getImplementation() { 49 | return gson; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/json/JacksonHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.json; 17 | 18 | import com.fasterxml.jackson.databind.ObjectMapper; 19 | import io.github.rhkiswani.javaff.json.exceptions.JsonException; 20 | 21 | /** 22 | * @author Mohamed Kiswani 23 | * @since 0.0.1 24 | * @see io.github.rhkiswani.javaff.json.JsonHandler 25 | */ 26 | class JacksonHandler implements JsonHandler { 27 | private final ObjectMapper mapper = new ObjectMapper(); 28 | 29 | 30 | @Override 31 | public T fromJson(String json, Class clazz) { 32 | try { 33 | return (T) mapper.readValue(json, clazz); 34 | } catch (Throwable e) { 35 | throw new JsonException(e.getMessage()); 36 | } 37 | } 38 | 39 | @Override 40 | public String toJson(Object object) { 41 | try { 42 | return mapper.writeValueAsString(object); 43 | } catch (Throwable e) { 44 | throw new JsonException(e.getMessage()); 45 | } 46 | } 47 | 48 | @Override 49 | public Object getImplementation() { 50 | return mapper; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/json/JsonHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.json; 17 | 18 | import io.github.rhkiswani.javaff.json.exceptions.JsonException; 19 | 20 | /** 21 | * @author Mohamed Kiswani 22 | * @since 0.0.1 23 | * 24 | */ 25 | public interface JsonHandler { 26 | 27 | T fromJson(String json, Class clazz) throws JsonException; 28 | 29 | String toJson(Object object) throws JsonException; 30 | 31 | Object getImplementation(); 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/json/JsonHandlerFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.json; 17 | 18 | import io.github.rhkiswani.javaff.detector.ApiDetectorUtil; 19 | import io.github.rhkiswani.javaff.factory.AbstractFactory; 20 | import io.github.rhkiswani.javaff.json.annotations.GsonBean; 21 | import io.github.rhkiswani.javaff.json.annotations.JacksonBean; 22 | 23 | /** 24 | * @author Mohamed Kiswani 25 | * @since 0.0.1 26 | * @see io.github.rhkiswani.javaff.factory.AbstractFactory 27 | */ 28 | public class JsonHandlerFactory extends AbstractFactory{ 29 | 30 | private static JsonHandlerFactory instance = new JsonHandlerFactory(); 31 | 32 | private JsonHandlerFactory(){ 33 | if (ApiDetectorUtil.isGsonAvailable()) { 34 | add(Object.class, new GsonHandler()); 35 | add(GsonBean.class, new GsonHandler()); 36 | } 37 | if (ApiDetectorUtil.isJacksonAvailable()) { 38 | add(JacksonBean.class, new JacksonHandler()); 39 | } 40 | } 41 | 42 | public static JsonHandlerFactory instance(){ 43 | return instance; 44 | } 45 | 46 | @Override 47 | protected String getDefaultImplementationUrl() { 48 | return "https://mvnrepository.com/artifact/com.google.code.gson/gson"; 49 | } 50 | 51 | public static JsonHandler getJsonHandler(Class aClass) { 52 | return instance.create(aClass); 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/json/annotations/GsonBean.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.json.annotations; 17 | 18 | import java.lang.annotation.ElementType; 19 | import java.lang.annotation.Retention; 20 | import java.lang.annotation.RetentionPolicy; 21 | import java.lang.annotation.Target; 22 | 23 | /** 24 | * @author Mohamed Kiswani 25 | * @since 0.0.1 26 | * 27 | */ 28 | @Retention(RetentionPolicy.RUNTIME) 29 | @Target(ElementType.TYPE) 30 | public @interface GsonBean { 31 | 32 | } -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/json/annotations/JacksonBean.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.json.annotations; 17 | 18 | import java.lang.annotation.ElementType; 19 | import java.lang.annotation.Retention; 20 | import java.lang.annotation.RetentionPolicy; 21 | import java.lang.annotation.Target; 22 | 23 | /** 24 | * @author Mohamed Kiswani 25 | * @since 0.0.1 26 | * 27 | */ 28 | @Retention(RetentionPolicy.RUNTIME) 29 | @Target(ElementType.TYPE) 30 | public @interface JacksonBean { 31 | 32 | } -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/json/exceptions/JsonException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.json.exceptions; 17 | 18 | import io.github.rhkiswani.javaff.exceptions.SmartException; 19 | 20 | /** 21 | * @author Mohamed Kiswani 22 | * @since 0.0.1 23 | * @see io.github.rhkiswani.javaff.exceptions.SmartException 24 | */ 25 | public class JsonException extends SmartException{ 26 | public JsonException(String errorMsg, Object... errorMsgParams) { 27 | super(errorMsg, errorMsgParams); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/lang/AbstractObjectHelper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.lang; 17 | 18 | import io.github.rhkiswani.javaff.detector.ApiDetectorUtil; 19 | import io.github.rhkiswani.javaff.lang.utils.ArraysUtils; 20 | import io.github.rhkiswani.javaff.reflection.ReflectionHelper; 21 | import io.github.rhkiswani.javaff.reflection.ReflectionHelpersFactory; 22 | 23 | import javax.persistence.Id; 24 | import java.lang.reflect.Field; 25 | import java.util.List; 26 | 27 | /** 28 | * @author Mohamed Kiswani 29 | * @since 0.0.1 30 | * 31 | */ 32 | public abstract class AbstractObjectHelper { 33 | 34 | protected final ReflectionHelper reflectionHelper = ReflectionHelpersFactory.getReflectionHelper(this.getClass()); 35 | 36 | protected abstract O doAction(I i); 37 | 38 | protected List getFieldsByAnnotation(Object obj,Class annotation){ 39 | return getFieldsByAnnotation(obj, annotation, true); 40 | } 41 | 42 | protected List getFieldsByAnnotation(Object obj,Class annotation, boolean returnAllOfNotFound){ 43 | List fields = reflectionHelper.scanFieldsByAnnotation(obj.getClass(), annotation); 44 | if (ArraysUtils.isEmpty(fields)){ 45 | if (ApiDetectorUtil.isJPAAvailable()){ 46 | fields = reflectionHelper.scanFieldsByAnnotation(obj.getClass(), Id.class); 47 | } 48 | if (ArraysUtils.isEmpty(fields) && returnAllOfNotFound){ 49 | fields = reflectionHelper.getFields(obj.getClass()); 50 | } 51 | } 52 | return fields; 53 | } 54 | 55 | 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/lang/EqualsHelper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.lang; 17 | 18 | import io.github.rhkiswani.javaff.lang.annotations.EqualsField; 19 | import org.apache.commons.lang3.builder.EqualsBuilder; 20 | 21 | import java.lang.reflect.Field; 22 | import java.util.List; 23 | 24 | /** 25 | * @author Mohamed Kiswani 26 | * @since 0.0.1 27 | * @see io.github.rhkiswani.javaff.lang.AbstractObjectHelper 28 | */ 29 | public class EqualsHelper extends AbstractObjectHelper{ 30 | 31 | @Override 32 | protected Boolean doAction(Object... objects) { 33 | if (objects.length < 2 ){ 34 | return false; 35 | } 36 | if (objects[0] == null && objects[1] == null){ 37 | return true; 38 | } 39 | if (objects[0] == null ){ 40 | return false; 41 | } 42 | if (objects[1] == null){ 43 | return false; 44 | } 45 | if (!objects[0].getClass().equals(objects[1].getClass())){ 46 | return false; 47 | } 48 | List fields = getFieldsByAnnotation(objects[0], EqualsField.class); 49 | if (fields.size() == 0){ 50 | return objects[0].equals(objects[1]); 51 | } 52 | EqualsBuilder equalsBuilder = new EqualsBuilder(); 53 | for (Field field : fields) { 54 | equalsBuilder.append(reflectionHelper.getFieldValue(objects[0], field.getName()), reflectionHelper.getFieldValue(objects[1], field.getName())); 55 | } 56 | return equalsBuilder.isEquals(); 57 | } 58 | 59 | public boolean isEqual(Object obj1, Object obj2) { 60 | return doAction(obj1, obj2); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/lang/HashCodeHelper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.lang; 17 | 18 | import io.github.rhkiswani.javaff.lang.annotations.HashcodeField; 19 | import org.apache.commons.lang3.builder.HashCodeBuilder; 20 | 21 | import java.lang.reflect.Field; 22 | 23 | /** 24 | * @author Mohamed Kiswani 25 | * @since 0.0.1 26 | * @see io.github.rhkiswani.javaff.lang.AbstractObjectHelper 27 | */ 28 | public class HashCodeHelper extends AbstractObjectHelper{ 29 | 30 | protected Integer doAction(Object obj) { 31 | if (obj == null ){ 32 | return -1; 33 | } 34 | HashCodeBuilder hashCodeBuilder = new HashCodeBuilder(); 35 | boolean atLestOneValueInserted = false; 36 | for (Field field : getFieldsByAnnotation(obj, HashcodeField.class)) { 37 | Object val = reflectionHelper.getFieldValue(obj, field.getName()); 38 | if (val != null){ 39 | atLestOneValueInserted = true; 40 | hashCodeBuilder.append(val); 41 | } 42 | 43 | } 44 | return atLestOneValueInserted ? hashCodeBuilder.toHashCode() : -1; 45 | } 46 | 47 | public int toHashCode(Object obj) { 48 | return doAction(obj); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/lang/ToStringHelper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.lang; 17 | 18 | import io.github.rhkiswani.javaff.format.FormatUtil; 19 | import io.github.rhkiswani.javaff.json.JsonHandlerFactory; 20 | import io.github.rhkiswani.javaff.json.annotations.GsonBean; 21 | import io.github.rhkiswani.javaff.lang.annotations.EqualsField; 22 | import io.github.rhkiswani.javaff.lang.annotations.HashcodeField; 23 | import io.github.rhkiswani.javaff.lang.annotations.ToString; 24 | import io.github.rhkiswani.javaff.lang.utils.ArraysUtils; 25 | 26 | import java.lang.reflect.Field; 27 | import java.util.Collection; 28 | import java.util.List; 29 | 30 | /** 31 | * @author Mohamed Kiswani 32 | * @since 0.0.1 33 | * @see io.github.rhkiswani.javaff.lang.AbstractObjectHelper 34 | */ 35 | public class ToStringHelper extends AbstractObjectHelper{ 36 | 37 | @Override 38 | protected String doAction(Object obj) { 39 | if (obj == null){ 40 | return null; 41 | } 42 | StringBuilder builder = new StringBuilder(); 43 | builder.append(obj.getClass().getSimpleName()); 44 | builder.append("["); 45 | builder.append(normalToString(obj)); 46 | builder.append("]"); 47 | return builder.toString(); 48 | } 49 | 50 | private String gosnToString(Object obj) { 51 | String json = JsonHandlerFactory.getJsonHandler(GsonBean.class).toJson(obj); 52 | json = json.replace("{", "["); 53 | json = json.replace("}", "]"); 54 | json = json.replace("\"", ""); 55 | return json; 56 | } 57 | 58 | private String normalToString(Object obj) { 59 | StringBuilder builder = new StringBuilder(); 60 | List fields = getFieldsByAnnotation(obj, ToString.class, false); 61 | if (ArraysUtils.isEmpty(fields)){ 62 | fields = getFieldsByAnnotation(obj, EqualsField.class, false); 63 | } 64 | if (ArraysUtils.isEmpty(fields)){ 65 | fields = getFieldsByAnnotation(obj, HashcodeField.class, true); 66 | } 67 | for (int i = 0; i < fields.size() ; i++) { 68 | Field f = fields.get(i); 69 | Object fieldValue = reflectionHelper.getFieldValue(obj, f.getName()); 70 | if (fieldValue == null){ 71 | continue; 72 | } 73 | builder.append(f.getName()); 74 | builder.append("="); 75 | if ((fieldValue.getClass().isArray() || Collection.class.isInstance(fieldValue))){ 76 | builder.append(gosnToString(fieldValue)); 77 | } else { 78 | builder.append(FormatUtil.format("{0}", fieldValue)); 79 | } 80 | if ( i < fields.size() -1){ 81 | builder.append(", "); 82 | } 83 | } 84 | return builder.toString(); 85 | } 86 | 87 | public String toString(Object obj) { 88 | return doAction(obj); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/lang/annotations/EqualsField.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.lang.annotations; 17 | 18 | import java.lang.annotation.ElementType; 19 | import java.lang.annotation.Retention; 20 | import java.lang.annotation.RetentionPolicy; 21 | import java.lang.annotation.Target; 22 | 23 | /** 24 | * @author Mohamed Kiswani 25 | * @since 0.0.1 26 | * 27 | */ 28 | @Retention(RetentionPolicy.RUNTIME) 29 | @Target(ElementType.FIELD) 30 | public @interface EqualsField { 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/lang/annotations/HashcodeField.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.lang.annotations; 17 | 18 | import java.lang.annotation.ElementType; 19 | import java.lang.annotation.Retention; 20 | import java.lang.annotation.RetentionPolicy; 21 | import java.lang.annotation.Target; 22 | 23 | /** 24 | * @author Mohamed Kiswani 25 | * @since 0.0.1 26 | * 27 | */ 28 | @Retention(RetentionPolicy.RUNTIME) 29 | @Target(ElementType.FIELD) 30 | public @interface HashcodeField { 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/lang/annotations/ToString.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.lang.annotations; 17 | 18 | import java.lang.annotation.ElementType; 19 | import java.lang.annotation.Retention; 20 | import java.lang.annotation.RetentionPolicy; 21 | import java.lang.annotation.Target; 22 | 23 | /** 24 | * @author Mohamed Kiswani 25 | * @since 0.0.1 26 | * 27 | */ 28 | @Retention(RetentionPolicy.RUNTIME) 29 | @Target(ElementType.FIELD) 30 | public @interface ToString { 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/lang/exceptions/IllegalParamException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.lang.exceptions; 17 | 18 | import io.github.rhkiswani.javaff.exceptions.SmartException; 19 | 20 | /** 21 | * @author Mohamed Kiswani 22 | * @since 0.0.1 23 | * @see io.github.rhkiswani.javaff.exceptions.SmartException 24 | */ 25 | public class IllegalParamException extends SmartException { 26 | public IllegalParamException(String errorMsg, Object... errorMsgParams) { 27 | super(errorMsg, errorMsgParams); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/lang/utils/ArraysUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.lang.utils; 17 | 18 | import io.github.rhkiswani.javaff.exceptions.SmartException; 19 | import io.github.rhkiswani.javaff.lang.exceptions.IllegalParamException; 20 | import org.apache.commons.lang3.ObjectUtils; 21 | 22 | import java.util.List; 23 | 24 | /** 25 | * @author Mohamed Kiswani 26 | * @since 0.0.1 27 | * 28 | */ 29 | public class ArraysUtils { 30 | 31 | public static final int MAX_ARRAY_SIZE = 500000; 32 | 33 | public static boolean isEmpty(Object[] arr) { 34 | if (arr == null){ 35 | return true; 36 | } 37 | if (arr.length == 0){ 38 | return true; 39 | } 40 | if (arr.length >= MAX_ARRAY_SIZE){ 41 | throw new IllegalParamException(SmartException.EXCEEDS_LIMIT, "Array", 500000); 42 | } 43 | return ObjectUtils.firstNonNull(arr) == null; 44 | } 45 | 46 | public static boolean isEmpty(List list) { 47 | return isEmpty(list.toArray()); 48 | } 49 | 50 | public static void replace(Object[] arr, Object find, Object replace) { 51 | if (isEmpty(arr)){ 52 | return; 53 | } 54 | for (int i = 0; i < arr.length; i++) { 55 | if ((arr[i] == null && find == null ) || (arr[i].equals(find))) { 56 | arr[i] = replace; 57 | } 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/lang/utils/ObjectUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.lang.utils; 17 | 18 | import io.github.rhkiswani.javaff.exceptions.SmartException; 19 | import io.github.rhkiswani.javaff.lang.EqualsHelper; 20 | import io.github.rhkiswani.javaff.lang.HashCodeHelper; 21 | import io.github.rhkiswani.javaff.lang.exceptions.IllegalParamException; 22 | 23 | /** 24 | * @author Mohamed Kiswani 25 | * @since 0.0.1 26 | * 27 | */ 28 | public class ObjectUtils { 29 | 30 | public static boolean isEqual(Object obj1, Object obj2) { 31 | return new EqualsHelper().isEqual(obj1, obj2); 32 | } 33 | 34 | public static int toHashCode(Object obj) { 35 | return new HashCodeHelper().toHashCode(obj); 36 | } 37 | 38 | public static Class primitiveToWrapper(Class targetClass) { 39 | if (targetClass == null){ 40 | throw new IllegalParamException(SmartException.NULL_VAL, "Target Class"); 41 | } 42 | if (!targetClass.isPrimitive()){ 43 | throw new IllegalParamException("{0} is not primitive", targetClass.getSimpleName()); 44 | } 45 | if (targetClass.equals(byte.class)){ 46 | return Byte.class; 47 | } else if (targetClass.equals(char.class)) { 48 | return Character.class; 49 | } else if (targetClass.equals(short.class)) { 50 | return Short.class; 51 | } else if (targetClass.equals(int.class)) { 52 | return Integer.class; 53 | } else if (targetClass.equals(long.class)) { 54 | return Long.class; 55 | } else if (targetClass.equals(float.class)) { 56 | return Float.class; 57 | } else if (targetClass.equals(double.class)) { 58 | return Double.class; 59 | } else if (targetClass.equals(boolean.class)) { 60 | return Boolean.class; 61 | } 62 | return targetClass; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/lang/utils/StringUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.lang.utils; 17 | 18 | import io.github.rhkiswani.javaff.lang.ToStringHelper; 19 | 20 | /** 21 | * @author Mohamed Kiswani 22 | * @since 0.0.1 23 | * 24 | */ 25 | public class StringUtils { 26 | 27 | public static String toString(Object obj) { 28 | return new ToStringHelper().toString(obj); 29 | } 30 | 31 | public static boolean isEmpty(String input){ 32 | return input == null || input.isEmpty(); 33 | } 34 | 35 | public static boolean isNotEmpty(String input){ 36 | return !isEmpty(input); 37 | } 38 | 39 | public static boolean isNull(String input){ 40 | return isEmpty(input) || "NULL".equalsIgnoreCase(input); 41 | } 42 | 43 | public static boolean isNotNull(String input){ 44 | return !isNull(input); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/locale/DefaultLocaleWorker.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.locale; 17 | 18 | import io.github.rhkiswani.javaff.beans.ValuesHolder; 19 | import io.github.rhkiswani.javaff.format.FormatUtil; 20 | import io.github.rhkiswani.javaff.lang.annotations.EqualsField; 21 | import io.github.rhkiswani.javaff.locale.exceptions.LocaleException; 22 | 23 | import java.util.Locale; 24 | import java.util.MissingResourceException; 25 | import java.util.ResourceBundle; 26 | 27 | /** 28 | * @author Mohamed Kiswani 29 | * @since 0.0.1 30 | * @see io.github.rhkiswani.javaff.beans.ValuesHolder 31 | * @see io.github.rhkiswani.javaff.locale.LocaleWorker 32 | * 33 | */ 34 | class DefaultLocaleWorker extends ValuesHolder implements LocaleWorker { 35 | @EqualsField 36 | private String name = "messages"; 37 | private String path = ""; 38 | private Locale locale = Locale.US; 39 | private ResourceBundle bundle = null; 40 | 41 | @Override 42 | public void setName(String name) { 43 | this.name = name; 44 | } 45 | 46 | public String getName() { 47 | return name; 48 | } 49 | 50 | @Override 51 | public void setLocale(Locale locale) { 52 | this.locale = locale; 53 | } 54 | 55 | public Locale getLocale() { 56 | return locale; 57 | } 58 | 59 | @Override 60 | public void setPath(String path) { 61 | String tmpPath = path; 62 | if (tmpPath == null || tmpPath.isEmpty()){ 63 | this.path = ""; 64 | return ; 65 | } 66 | if (tmpPath.startsWith("/")){ 67 | tmpPath = tmpPath.substring(1); 68 | } 69 | if (!tmpPath.endsWith("/") && tmpPath.length() > 1){ 70 | tmpPath = tmpPath + "/"; 71 | } 72 | this.path = tmpPath; 73 | } 74 | 75 | public String getPath() { 76 | return path; 77 | } 78 | 79 | @Override 80 | public String getString(String key, Object... params) { 81 | if (bundle == null){ 82 | reload(); 83 | } 84 | if (key == null){ 85 | return null; 86 | } 87 | String val = ""; 88 | try { 89 | val = bundle.getString(key); 90 | }catch (MissingResourceException e){ 91 | val = key; 92 | } 93 | return FormatUtil.format(val, params); 94 | } 95 | 96 | @Override 97 | public void reload() { 98 | synchronized (DefaultLocaleWorker.class){ 99 | try { 100 | bundle = ResourceBundle.getBundle(getPath() + getName(), locale); 101 | }catch (Exception e){ 102 | throw new LocaleException (e.getMessage()); 103 | } 104 | } 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/locale/LocaleUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.locale; 17 | 18 | import io.github.rhkiswani.javaff.exceptions.SmartException; 19 | import io.github.rhkiswani.javaff.format.FormatUtil; 20 | import io.github.rhkiswani.javaff.lang.utils.StringUtils; 21 | 22 | import java.util.HashMap; 23 | import java.util.Map; 24 | 25 | /** 26 | * @author Mohamed Kiswani 27 | * @since 0.0.1 28 | * 29 | */ 30 | public class LocaleUtil { 31 | 32 | private static Map DEFAULT_MSGS = null; 33 | 34 | static { 35 | DEFAULT_MSGS = new HashMap<>(); 36 | DEFAULT_MSGS.put(SmartException.EXCEEDS_LIMIT, "{0} MaxSize is {1}"); 37 | DEFAULT_MSGS.put(SmartException.ALREADY_EXIST, "{0} is already exist {1}"); 38 | DEFAULT_MSGS.put(SmartException.NULL_VAL, "{0} can't be null"); 39 | DEFAULT_MSGS.put(SmartException.NOT_FOUND, "{0} not found"); 40 | DEFAULT_MSGS.put(SmartException.TYPE_ERROR, "{0} is not fit to {1}"); 41 | DEFAULT_MSGS.put(SmartException.FORMAT_EXCEPTION, "Can't format {0} {1}"); 42 | DEFAULT_MSGS.put(SmartException.NEGATIVE_VAL, "{0} should be greater or equal 0"); 43 | DEFAULT_MSGS.put(SmartException.HTTP_ERROR, "failed to connect to {0}"); 44 | DEFAULT_MSGS.put(SmartException.NO_IMPLEMENTATION_FOUND, "No implementation found for {0} you need to set implementation through {1}.instance().add or add {2} to your classpath"); 45 | DEFAULT_MSGS.put(SmartException.NO_IMPLEMENTATION_FOUND_WITH_NO_LINK, "No implementation found for {0} you need to set implementation through {1}.instance().add "); 46 | } 47 | 48 | public static String getString(String key, Class targetClass, Object[] params) { 49 | LocaleWorker worker = LocaleWorkersFactory.getLocalWorker(targetClass); 50 | String label = worker.getString(key, params); 51 | if (!StringUtils.isEmpty(label) && label.equals(key) && DEFAULT_MSGS.get(key) != null){ 52 | return FormatUtil.formatString(DEFAULT_MSGS.get(key), params); 53 | } 54 | return label; 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/locale/LocaleWorker.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.locale; 17 | 18 | import java.util.Locale; 19 | 20 | /** 21 | * @author Mohamed Kiswani 22 | * @since 0.0.1 23 | * 24 | */ 25 | public interface LocaleWorker { 26 | 27 | void setName(String name); 28 | 29 | void setLocale(Locale locale); 30 | 31 | void reload(); 32 | 33 | void setPath(String path); 34 | 35 | String getString(String key, Object... params); 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/locale/LocaleWorkerBuilder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.locale; 17 | 18 | import java.util.Locale; 19 | 20 | /** 21 | * @author Mohamed Kiswani 22 | * @since 0.0.1 23 | * 24 | */ 25 | public class LocaleWorkerBuilder { 26 | private LocaleWorker worker = new DefaultLocaleWorker(); 27 | 28 | public LocaleWorkerBuilder name(String name){ 29 | worker.setName(name); 30 | return this; 31 | } 32 | 33 | public LocaleWorkerBuilder path(String path){ 34 | worker.setPath(path); 35 | return this; 36 | } 37 | 38 | public LocaleWorkerBuilder locale(Locale locale){ 39 | worker.setLocale(locale); 40 | return this; 41 | } 42 | 43 | public LocaleWorker build(){ 44 | worker.reload(); 45 | return worker; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/locale/LocaleWorkersFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.locale; 17 | 18 | import io.github.rhkiswani.javaff.factory.AbstractFactory; 19 | 20 | /** 21 | * @author Mohamed Kiswani 22 | * @since 0.0.1 23 | * @see io.github.rhkiswani.javaff.factory.AbstractFactory 24 | * 25 | */ 26 | public class LocaleWorkersFactory extends AbstractFactory{ 27 | private static LocaleWorkersFactory instance = new LocaleWorkersFactory(); 28 | 29 | private LocaleWorkersFactory(){ 30 | add(Object.class, new LocaleWorkerBuilder().path("app/").build()); 31 | add(Throwable.class, new LocaleWorkerBuilder().path("exceptions/").build()); 32 | } 33 | 34 | public static LocaleWorkersFactory instance(){ 35 | return instance; 36 | } 37 | 38 | public static LocaleWorker getLocalWorker(Class clazz){ 39 | return instance.create(clazz); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/locale/exceptions/LocaleException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.locale.exceptions; 17 | 18 | import io.github.rhkiswani.javaff.exceptions.SmartException; 19 | 20 | /** 21 | * @author Mohamed Kiswani 22 | * @since 0.0.1 23 | * @see SmartException 24 | */ 25 | public class LocaleException extends SmartException { 26 | public LocaleException(String errorMsg, Object... errorMsgParams) { 27 | super(errorMsg, errorMsgParams); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/log/DefaultLog.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.log; 17 | 18 | import java.util.logging.Level; 19 | import java.util.logging.Logger; 20 | 21 | /** 22 | * @author Mohamed Kiswani 23 | * @since 0.0.1 24 | * @see io.github.rhkiswani.javaff.log.Log 25 | */ 26 | public class DefaultLog implements Log { 27 | private Logger logger = null ; 28 | 29 | public DefaultLog(Class clazz){ 30 | this.logger = Logger.getLogger(clazz.getName()); 31 | } 32 | 33 | public void debug(String message, Object... params) { 34 | logger.log(Level.FINE, message); 35 | } 36 | 37 | public void info(String message, Object... params) { 38 | logger.log(Level.INFO, message); 39 | } 40 | 41 | public void warn(String message, Object... params) { 42 | logger.log(Level.WARNING, message); 43 | } 44 | 45 | public void error(String message, Object... params) { 46 | logger.log(Level.SEVERE, message); 47 | } 48 | 49 | public void error(String message, Exception e, Object... params) { 50 | logger.log(Level.SEVERE, message, e); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/log/Log.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.log; 17 | 18 | /** 19 | * @author Mohamed Kiswani 20 | * @since 0.0.1 21 | * 22 | */ 23 | public interface Log { 24 | 25 | void debug(String message, Object... params); 26 | 27 | void info(String message, Object... params); 28 | 29 | void warn(String message, Object... params); 30 | 31 | void error(String message, Object... params); 32 | 33 | void error(String message, Exception e, Object... params); 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/log/LogFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.log; 17 | 18 | import io.github.rhkiswani.javaff.detector.ApiDetectorUtil; 19 | import io.github.rhkiswani.javaff.factory.AbstractFactory; 20 | 21 | /** 22 | * @author Mohamed Kiswani 23 | * @since 0.0.1 24 | * @see io.github.rhkiswani.javaff.factory.AbstractFactory 25 | */ 26 | public class LogFactory extends AbstractFactory{ 27 | private static LogFactory instance = new LogFactory(); 28 | 29 | private LogFactory(){ 30 | } 31 | 32 | public static LogFactory instance(){ 33 | return instance; 34 | } 35 | 36 | @Override 37 | protected Log getDefault(Class targetClazz) { 38 | if (ApiDetectorUtil.isSlf4jAvailable()){ 39 | return new Slf4jLog(targetClazz); 40 | } 41 | return new DefaultLog(targetClazz.getClass()); 42 | } 43 | 44 | public static Log getLogger(Class aClass) { 45 | return new LogWrapper(instance().create(aClass)); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/log/LogWrapper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.github.rhkiswani.javaff.log; 18 | 19 | import io.github.rhkiswani.javaff.locale.LocaleUtil; 20 | 21 | /** 22 | * @author Mohamed Kiswani 23 | * @since 0.0.17 24 | * 25 | */ 26 | public class LogWrapper implements Log{ 27 | 28 | private final Log log; 29 | 30 | public LogWrapper(Log log) { 31 | this.log = log; 32 | } 33 | 34 | @Override 35 | public void debug(String message, Object... params) { 36 | log.debug(LocaleUtil.getString(message, LogWrapper.class, params)); 37 | } 38 | 39 | @Override 40 | public void info(String message, Object... params) { 41 | log.info(LocaleUtil.getString(message, LogWrapper.class, params)); 42 | } 43 | 44 | @Override 45 | public void warn(String message, Object... params) { 46 | log.warn(LocaleUtil.getString(message, LogWrapper.class, params)); 47 | } 48 | 49 | @Override 50 | public void error(String message, Object... params) { 51 | log.error(LocaleUtil.getString(message, LogWrapper.class, params)); 52 | } 53 | 54 | public void error(String message, Exception e, Object... params) { 55 | log.error(LocaleUtil.getString(message, LogWrapper.class, params), e); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/log/Slf4jLog.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.log; 17 | 18 | import org.slf4j.Logger; 19 | 20 | /** 21 | * @author Mohamed Kiswani 22 | * @since 0.0.1 23 | * @see io.github.rhkiswani.javaff.log.Log 24 | */ 25 | class Slf4jLog implements Log { 26 | private final Logger logger; 27 | 28 | public Slf4jLog(Class clazz){ 29 | logger = org.slf4j.LoggerFactory.getLogger(clazz); 30 | } 31 | 32 | public void debug(String message, Object... params) { 33 | logger.debug(message); 34 | } 35 | 36 | public void info(String message, Object... params) { 37 | logger.info(message); 38 | } 39 | 40 | public void warn(String message, Object... params) { 41 | logger.warn(message); 42 | } 43 | 44 | public void error(String message, Object... params) { 45 | logger.error(message); 46 | } 47 | 48 | public void error(String message, Exception e, Object... params) { 49 | logger.error(message, e); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/log/annotations/Slf4jLogger.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.log.annotations; 17 | 18 | import java.lang.annotation.ElementType; 19 | import java.lang.annotation.Retention; 20 | import java.lang.annotation.RetentionPolicy; 21 | import java.lang.annotation.Target; 22 | 23 | /** 24 | * @author Mohamed Kiswani 25 | * @since 0.0.1 26 | * 27 | */ 28 | @Retention(RetentionPolicy.RUNTIME) 29 | @Target(ElementType.TYPE) 30 | public @interface Slf4jLogger { 31 | 32 | } -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/reflection/DefaultReflectionHelper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.reflection; 17 | 18 | import io.github.rhkiswani.javaff.exceptions.SmartException; 19 | import io.github.rhkiswani.javaff.lang.utils.ArraysUtils; 20 | import io.github.rhkiswani.javaff.lang.utils.ObjectUtils; 21 | import io.github.rhkiswani.javaff.reflection.exception.ReflectionException; 22 | 23 | import java.lang.reflect.Field; 24 | import java.lang.reflect.Modifier; 25 | import java.util.ArrayList; 26 | import java.util.LinkedList; 27 | import java.util.List; 28 | 29 | /** 30 | * @author Mohamed Kiswani 31 | * @since 0.0.1 32 | * @see io.github.rhkiswani.javaff.reflection.ReflectionHelper 33 | */ 34 | public class DefaultReflectionHelper implements ReflectionHelper{ 35 | private static final ArrayList IGNORE_NAMES = new ArrayList<>(); 36 | 37 | static { 38 | IGNORE_NAMES.add("$jacocoData"); 39 | IGNORE_NAMES.add("__cobertura_counters"); 40 | IGNORE_NAMES.add("this$"); 41 | } 42 | @Override 43 | public List scanFieldsByAnnotation(Class clazz, Class... annotations) throws ReflectionException { 44 | if (clazz == null){ 45 | return null; 46 | } 47 | if (ArraysUtils.isEmpty(annotations)){ 48 | return null; 49 | } 50 | LinkedList list = new LinkedList<>(); 51 | Field[] fields = clazz.getDeclaredFields(); 52 | for (Field field : fields) { 53 | for (Class aClass : annotations) { 54 | if (field.isAnnotationPresent(aClass)){ 55 | list.add(field); 56 | } 57 | } 58 | } 59 | if (list.size() == 0 && !clazz.getSuperclass().equals(Object.class)){ 60 | return scanFieldsByAnnotation(clazz.getSuperclass(), annotations); 61 | } 62 | return list; 63 | } 64 | 65 | @Override 66 | public void setFieldValue(T obj, String fieldName, Object value) throws ReflectionException { 67 | if (obj == null){ 68 | throw new ReflectionException(SmartException.NULL_VAL, "target object"); 69 | } 70 | Field field = getField(obj.getClass(), fieldName); 71 | validateType(value, field); 72 | try { 73 | field.set(obj, value); 74 | } catch (Exception e) { 75 | throw new ReflectionException(e); 76 | } 77 | } 78 | 79 | private void validateType(Object value, Field field) { 80 | boolean valueNotNull = (value != null); 81 | if (valueNotNull){ 82 | boolean isPrimitive = field.getType().isPrimitive(); 83 | boolean isInstanceOfType = field.getType().isInstance(value); 84 | if (isPrimitive){ 85 | boolean isInstanceOfWrapperClass = ObjectUtils.primitiveToWrapper(field.getType()).isInstance(value); 86 | if (!isInstanceOfWrapperClass){ 87 | throw new ReflectionException(SmartException.TYPE_ERROR, value.getClass(), field.getType()); 88 | } 89 | }else if (!isInstanceOfType){ 90 | throw new ReflectionException(SmartException.TYPE_ERROR, value.getClass(), field.getType()); 91 | } 92 | } 93 | } 94 | 95 | @Override 96 | public void setStaticFieldValue(Class clazz, String fieldName, Object value) throws ReflectionException { 97 | Field field = getField(clazz, fieldName); 98 | try { 99 | Field modifiersField = Field.class.getDeclaredField("modifiers"); 100 | modifiersField.setAccessible(true); 101 | modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); 102 | field.set(null, value); 103 | }catch (Exception e){ 104 | throw new ReflectionException(e.getMessage()); 105 | } 106 | } 107 | 108 | @Override 109 | public Field getField(Class clazz, String fieldName) throws ReflectionException { 110 | if (clazz == null){ 111 | throw new ReflectionException(SmartException.NULL_VAL, "target class"); 112 | } 113 | Field[] fields = clazz.getDeclaredFields(); 114 | for (Field field : fields) { 115 | if (isIgnored(field)){ 116 | continue; 117 | } 118 | if (field.getName().equals(fieldName)){ 119 | field.setAccessible(true); 120 | return field; 121 | } 122 | } 123 | if (!clazz.getSuperclass().equals(Object.class)){ 124 | return getField(clazz.getSuperclass(), fieldName); 125 | } 126 | throw new ReflectionException(SmartException.NOT_FOUND, fieldName); 127 | } 128 | 129 | @Override 130 | public Class forName(String className) throws ReflectionException { 131 | try { 132 | return Class.forName(className); 133 | } catch (Exception e) { 134 | throw new ReflectionException(e); 135 | } 136 | } 137 | 138 | @Override 139 | public List getFields(Class clazz) { 140 | if (clazz == null){ 141 | throw new ReflectionException(SmartException.NULL_VAL, "Class"); 142 | } 143 | LinkedList list = new LinkedList(); 144 | Field[] fields = clazz.getDeclaredFields(); 145 | for (Field field : fields) { 146 | if (isIgnored(field)){ 147 | continue; 148 | } 149 | field.setAccessible(true); 150 | list.add(field); 151 | } 152 | if (!clazz.getSuperclass().equals(Object.class)){ 153 | list.addAll(getFields(clazz.getSuperclass())); 154 | } 155 | return list; 156 | } 157 | 158 | private boolean isIgnored(Field field) { 159 | for (String ignoreName : IGNORE_NAMES) { 160 | if (field != null && field.getName().contains(ignoreName)){ 161 | return true; 162 | } 163 | } 164 | return false; 165 | } 166 | 167 | public V getFieldValue(T obj, String fieldName) throws ReflectionException { 168 | try { 169 | if (obj == null){ 170 | throw new ReflectionException(SmartException.NULL_VAL, "Object"); 171 | } 172 | if (fieldName == null){ 173 | throw new ReflectionException(SmartException.NULL_VAL, "Field Name"); 174 | } 175 | return (V) getField(obj.getClass(), fieldName).get(obj); 176 | } catch (Exception e) { 177 | throw new ReflectionException(e); 178 | } 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/reflection/ReflectionHelper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.reflection; 17 | 18 | import io.github.rhkiswani.javaff.reflection.exception.ReflectionException; 19 | 20 | import java.lang.reflect.Field; 21 | import java.util.List; 22 | 23 | /** 24 | * @author Mohamed Kiswani 25 | * @since 0.0.1 26 | * 27 | */ 28 | public interface ReflectionHelper { 29 | 30 | List scanFieldsByAnnotation(Class clazz, Class... annotations) throws ReflectionException; 31 | 32 | void setFieldValue(T obj,String fieldName, Object value) throws ReflectionException; 33 | 34 | void setStaticFieldValue(Class clazz,String fieldName, Object value) throws ReflectionException; 35 | 36 | Field getField(Class clazz, String fieldName) throws ReflectionException; 37 | 38 | V getFieldValue(T obj, String fieldName) throws ReflectionException; 39 | 40 | Class forName(String className) throws ReflectionException; 41 | 42 | List getFields(Class clazz); 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/reflection/ReflectionHelpersFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.reflection; 17 | 18 | import io.github.rhkiswani.javaff.factory.AbstractFactory; 19 | 20 | /** 21 | * @author Mohamed Kiswani 22 | * @since 0.0.1 23 | * @see io.github.rhkiswani.javaff.factory.AbstractFactory 24 | */ 25 | public class ReflectionHelpersFactory extends AbstractFactory { 26 | private static ReflectionHelpersFactory instance = new ReflectionHelpersFactory(); 27 | 28 | private ReflectionHelpersFactory(){ 29 | } 30 | 31 | public static ReflectionHelpersFactory instance(){ 32 | return instance; 33 | } 34 | 35 | @Override 36 | public ReflectionHelper getDefault(Class targetClazz) { 37 | return new DefaultReflectionHelper(); 38 | } 39 | 40 | public static ReflectionHelper getReflectionHelper(Class targetClazz){ 41 | return instance.create(targetClazz); 42 | 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/reflection/ReflectionUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.reflection; 17 | 18 | import io.github.rhkiswani.javaff.exceptions.SmartException; 19 | import io.github.rhkiswani.javaff.lang.exceptions.IllegalParamException; 20 | 21 | import java.lang.reflect.Field; 22 | import java.util.ArrayList; 23 | import java.util.List; 24 | 25 | /** 26 | * @author Mohamed Kiswani 27 | * @since 0.0.1 28 | * 29 | */ 30 | public class ReflectionUtil { 31 | private static final ReflectionHelper REFLECTION_HELPER = ReflectionHelpersFactory.getReflectionHelper(ReflectionUtil.class); 32 | 33 | public static boolean isPresent(String className) { 34 | return isPresent(className, Thread.currentThread().getContextClassLoader()); 35 | } 36 | 37 | public static boolean isPresent(String className, ClassLoader classLoader) { 38 | try { 39 | classLoader.loadClass(className); 40 | return true; 41 | } catch (Throwable ex) { 42 | // Class or one of its dependencies is not present... 43 | return false; 44 | } 45 | } 46 | 47 | public static void setFieldValue(Object obj, String fieldName, Object val) { 48 | REFLECTION_HELPER.setFieldValue(obj, fieldName, val); 49 | } 50 | 51 | public static Class getCallerClass(int numberOfLevels){ 52 | StackTraceElement[] stackTraceElements = new Exception().getStackTrace(); 53 | if (numberOfLevels < 0){ 54 | throw new IllegalParamException(SmartException.NEGATIVE_VAL, "Number Of Levels"); 55 | } 56 | if (numberOfLevels + 1 > stackTraceElements.length){ 57 | throw new IllegalParamException(SmartException.EXCEEDS_LIMIT, "StackTrace", stackTraceElements.length); 58 | } 59 | return forName(stackTraceElements[numberOfLevels+1].getClassName()); 60 | } 61 | 62 | public static Class forName(String className) { 63 | return ReflectionHelpersFactory.getReflectionHelper(ReflectionUtil.class).forName(className); 64 | } 65 | 66 | public static T getFieldValue(Object obj, String fieldName) { 67 | return (T) REFLECTION_HELPER.getFieldValue(obj, fieldName); 68 | } 69 | 70 | public static void setStaticFieldValue(Class clazz, String fieldName, Object value) { 71 | REFLECTION_HELPER.setStaticFieldValue(clazz, fieldName, value); 72 | } 73 | 74 | public static List getFields(Class clazz) { 75 | return REFLECTION_HELPER.getFields(clazz); 76 | } 77 | 78 | public static String[] getErrorsAsArray(Throwable ex) { 79 | ArrayList strings = new ArrayList<>(); 80 | StackTraceElement[] st = ex.getStackTrace(); 81 | strings.add(ex.getMessage()); 82 | for (int i = 0; i < st.length; i++) { 83 | strings.add(st[i].toString()); 84 | } 85 | return strings.toArray(new String[strings.size()]); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/reflection/exception/ReflectionException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.reflection.exception; 17 | 18 | import io.github.rhkiswani.javaff.exceptions.SmartException; 19 | 20 | /** 21 | * @author Mohamed Kiswani 22 | * @since 0.0.1 23 | * @see io.github.rhkiswani.javaff.exceptions.SmartException 24 | */ 25 | public class ReflectionException extends SmartException{ 26 | 27 | public ReflectionException(String errorMsg, Object... errorMsgParams) { 28 | super(errorMsg, errorMsgParams); 29 | } 30 | 31 | public ReflectionException(Throwable e) { 32 | super(e); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/validation/Validator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.validation; 17 | 18 | import io.github.rhkiswani.javaff.validation.exceptions.ValidationException; 19 | 20 | import java.lang.reflect.Field; 21 | import java.lang.reflect.Method; 22 | import java.util.List; 23 | 24 | /** 25 | * @author Mohamed Kiswani 26 | * @since 0.0.23 27 | * 28 | */ 29 | public interface Validator { 30 | void validate(T t) throws ValidationException; 31 | void validateList(List t) throws ValidationException; 32 | void validateField(Field field, T t) throws ValidationException; 33 | void validateMethod(Method method, T t) throws ValidationException; 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/validation/ValidatorFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.validation; 17 | 18 | import io.github.rhkiswani.javaff.factory.AbstractFactory; 19 | 20 | /** 21 | * @author Mohamed Kiswani 22 | * @since 0.0.23 23 | * @see AbstractFactory 24 | */ 25 | public class ValidatorFactory extends AbstractFactory{ 26 | 27 | private static ValidatorFactory instance = new ValidatorFactory(); 28 | 29 | private ValidatorFactory(){ 30 | } 31 | 32 | public static ValidatorFactory instance(){ 33 | return instance; 34 | } 35 | 36 | public static Validator getValidator(Class aClass) { 37 | return new ValidatorWrapper(instance.create(aClass)); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/validation/ValidatorWrapper.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.validation; 17 | 18 | import io.github.rhkiswani.javaff.validation.exceptions.*; 19 | 20 | import java.lang.reflect.Field; 21 | import java.lang.reflect.Method; 22 | import java.util.List; 23 | 24 | /** 25 | * @author Mohamed Kiswani 26 | * @since 0.0.23 27 | * @see Validator 28 | */ 29 | public class ValidatorWrapper implements Validator { 30 | private Validator validator; 31 | 32 | public ValidatorWrapper(Validator validator){ 33 | this.validator = validator; 34 | } 35 | 36 | @Override 37 | public void validate(T t) throws ValidationException { 38 | this.validator.validate(t); 39 | } 40 | 41 | @Override 42 | public void validateList(List t) throws ValidationException { 43 | this.validator.validateList(t); 44 | } 45 | 46 | @Override 47 | public void validateField(Field field, T t) throws ValidationException { 48 | this.validator.validateField(field, t); 49 | } 50 | 51 | @Override 52 | public void validateMethod(Method method, T t) throws ValidationException { 53 | this.validator.validateMethod(method, t); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/io/github/rhkiswani/javaff/validation/exceptions/ValidationException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Mohamed Kiswani. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package io.github.rhkiswani.javaff.validation.exceptions; 17 | 18 | import io.github.rhkiswani.javaff.exceptions.SmartException; 19 | 20 | /** 21 | * @author Mohamed Kiswani 22 | * @since 0.0.23 23 | * @see SmartException 24 | */ 25 | public class ValidationException extends SmartException{ 26 | 27 | public ValidationException(String errorMsg, Object... errorMsgParams) { 28 | super(errorMsg, errorMsgParams); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/resources/app/messages_en.properties: -------------------------------------------------------------------------------- 1 | LOCALIZED_MSG=this is localized msg from messages_en.properties thanks for Mr {0} -------------------------------------------------------------------------------- /src/main/resources/exceptions/messages_en.properties: -------------------------------------------------------------------------------- 1 | ## exceptions 2 | EXCEEDS_LIMIT={0} MaxSize is {1} 3 | ALREADY_EXIST={0} is already exist {1} 4 | NULL_VAL={0} can't be null 5 | NOT_FOUND={0} not found 6 | TYPE_ERROR={0} is not fit to {1} 7 | FORMAT_EXCEPTION=can't format {0} {1} 8 | NEGATIVE_VAL={0} should be greater or equal 0 9 | NO_IMPLEMENTATION_FOUND=No implementation found for type [{0}] you need to set implementation through {1}.instance().add or add {2} to your classpath 10 | NO_IMPLEMENTATION_FOUND_WITH_NO_LINK=No implementation found for type [{0}] you need to set implementation through {1}.instance().add -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/beans/Employee.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.beans; 2 | 3 | public class Employee extends Person { 4 | 5 | private int empId; 6 | 7 | public Employee() { 8 | 9 | } 10 | 11 | public Employee(int empId) { 12 | super(); 13 | this.empId = empId; 14 | } 15 | 16 | public int getEmpId() { 17 | return empId; 18 | } 19 | 20 | public void setEmpId(int empId) { 21 | this.empId = empId; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/beans/EmployeeByIdAnnotation.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.beans; 2 | 3 | public class EmployeeByIdAnnotation extends PersonByIdAnnotation { 4 | 5 | private int empId; 6 | 7 | public int getEmpId() { 8 | return empId; 9 | } 10 | 11 | public void setEmpId(int empId) { 12 | this.empId = empId; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/beans/EmployeeX.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.beans; 2 | 3 | public class EmployeeX extends PersonX { 4 | 5 | private int empId; 6 | 7 | public int getEmpId() { 8 | return empId; 9 | } 10 | 11 | public void setEmpId(int empId) { 12 | this.empId = empId; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/beans/Person.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.beans; 2 | 3 | import io.github.rhkiswani.javaff.beans.ValuesHolder; 4 | import io.github.rhkiswani.javaff.lang.annotations.EqualsField; 5 | 6 | public class Person extends ValuesHolder { 7 | 8 | @EqualsField 9 | private int id; 10 | private String name; 11 | 12 | public int getId() { 13 | return id; 14 | } 15 | 16 | public void setId(int id) { 17 | this.id = id; 18 | } 19 | 20 | public String getName() { 21 | return name; 22 | } 23 | 24 | public void setName(String name) { 25 | this.name = name; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/beans/PersonByIdAnnotation.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.beans; 2 | 3 | import io.github.rhkiswani.javaff.beans.ValuesHolder; 4 | import io.github.rhkiswani.javaff.lang.annotations.HashcodeField; 5 | 6 | import javax.persistence.Id; 7 | 8 | public class PersonByIdAnnotation extends ValuesHolder { 9 | 10 | @Id 11 | @HashcodeField 12 | private Integer id; 13 | @HashcodeField 14 | private String name; 15 | 16 | private transient String transientVal; 17 | public static String staticVal; 18 | 19 | public Integer getId() { 20 | return id; 21 | } 22 | 23 | public void setId(Integer id) { 24 | this.id = id; 25 | } 26 | 27 | public String getName() { 28 | return name; 29 | } 30 | 31 | public void setName(String name) { 32 | this.name = name; 33 | } 34 | 35 | 36 | public String getTransientVal() { 37 | return transientVal; 38 | } 39 | 40 | public void setTransientVal(String transientVal) { 41 | this.transientVal = transientVal; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/beans/PersonX.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.beans; 2 | 3 | import io.github.rhkiswani.javaff.beans.ValuesHolder; 4 | 5 | public class PersonX extends ValuesHolder { 6 | 7 | private int id; 8 | private String name; 9 | 10 | public int getId() { 11 | return id; 12 | } 13 | 14 | public void setId(int id) { 15 | this.id = id; 16 | } 17 | 18 | public String getName() { 19 | return name; 20 | } 21 | 22 | public void setName(String name) { 23 | this.name = name; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/beans/ValuesHolderTest.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.beans; 2 | 3 | import io.github.rhkiswani.javaff.lang.annotations.EqualsField; 4 | import io.github.rhkiswani.javaff.lang.annotations.HashcodeField; 5 | import io.github.rhkiswani.javaff.lang.annotations.ToString; 6 | import org.apache.commons.lang3.builder.HashCodeBuilder; 7 | import org.junit.Before; 8 | import org.junit.Test; 9 | 10 | import javax.persistence.Id; 11 | import java.text.SimpleDateFormat; 12 | import java.util.Arrays; 13 | import java.util.Collection; 14 | import java.util.Date; 15 | 16 | import static org.assertj.core.api.Assertions.assertThat; 17 | 18 | public class ValuesHolderTest { 19 | 20 | private EmployeeByIdAnnotation e; 21 | private EmployeeByIdAnnotation e1; 22 | @Before 23 | public void setUp(){ 24 | e = new EmployeeByIdAnnotation(); 25 | e.setId(100000); 26 | e.setName("Kiswani"); 27 | e.setEmpId(1000); 28 | e1 = new EmployeeByIdAnnotation(); 29 | e1.setId(100000); 30 | e1.setName("Kiswani123"); 31 | e1.setTransientVal("Kiswani"); 32 | e1.staticVal = "Static"; 33 | } 34 | @Test 35 | public void testEquals() throws Exception { 36 | assertThat(e.equals(e1)).isEqualTo(true); 37 | e.setId(4); 38 | assertThat(e.equals(e1)).isEqualTo(false); 39 | } 40 | 41 | @Test 42 | public void testHashcode() throws Exception { 43 | int hashCode = new HashCodeBuilder().append(100000).append("Kiswani123").hashCode(); 44 | assertThat(e1.hashCode()).isEqualTo(hashCode); 45 | e1.setName("New Name"); 46 | assertThat(e1.hashCode()).isNotEqualTo(hashCode); 47 | e1.setName(null); 48 | e1.setId(null); 49 | assertThat(e1.hashCode()).isEqualTo(-1); 50 | } 51 | 52 | @Test 53 | public void testClone() throws Exception { 54 | EmployeeByIdAnnotation clone = e1.clone(); 55 | assertThat(clone.getName()).isEqualTo(e1.getName()); 56 | assertThat(clone.getId()).isEqualTo(e1.getId()); 57 | assertThat(clone.getEmpId()).isEqualTo(e1.getEmpId()); 58 | assertThat(clone.getTransientVal()).isEqualTo(e1.getTransientVal()); 59 | assertThat(clone.staticVal).isEqualTo(e1.staticVal); 60 | } 61 | 62 | @Test 63 | public void testToString() throws Exception { 64 | e1.setEmpId(500000); 65 | assertThat(e1.toString()).isEqualTo("EmployeeByIdAnnotation[id=100,000]"); 66 | ToStringTestClass stringTestClass = new ToStringTestClass(); 67 | stringTestClass.date = new SimpleDateFormat("yyyy-MM-dd").parse("2016-11-21"); 68 | assertThat(stringTestClass.toString()).isEqualTo("ToStringTestClass[i=123,123,123, f=123,123,120, d=123,123,123, date=11/21/16 12:00 AM, c=\n, l=123,123,123, s=Kiswani, arr=[1,2,3], coll=[[1,2,3]]]"); 69 | ToStringTestClassX x = new ToStringTestClassX(); 70 | assertThat(x.toString()).isEqualTo("ToStringTestClassX[i=123,123,123, f=123,123,120]"); 71 | ToStringTestClassXX xx = new ToStringTestClassXX(); 72 | assertThat(xx.toString()).isEqualTo("ToStringTestClassXX[f=4,444,111]"); 73 | ToStringTestClassXXX xxx = new ToStringTestClassXXX(); 74 | assertThat(xxx.toString()).isEqualTo("ToStringTestClassXXX[i=10,000]"); 75 | ToStringTestClassXXXX xxxx = new ToStringTestClassXXXX(); 76 | assertThat(xxxx.toString()).isEqualTo("ToStringTestClassXXXX[d=99,900,011]"); 77 | } 78 | 79 | @Test 80 | public void testX() throws Exception { 81 | assertThat(PersonByIdAnnotation.class.isInstance(e1)).isEqualTo(true); 82 | } 83 | 84 | private class ToStringTestClass extends ValuesHolder{ 85 | private int i = 123123123; 86 | private float f = 123123123; 87 | private double d = 123123123; 88 | private Date date = new Date(); 89 | private char c = '\n'; 90 | private long l = 123123123; 91 | private String s = "Kiswani"; 92 | private int[] arr = new int[]{1, 2, 3}; 93 | private Collection coll = Arrays.asList(arr); 94 | } 95 | 96 | private class ToStringTestClassX extends ValuesHolder{ 97 | @ToString 98 | private int i = 123123123; 99 | @ToString 100 | private float f = 123123123; 101 | private double d = 123123123; 102 | } 103 | 104 | private class ToStringTestClassXX extends ValuesHolder{ 105 | private int i = 9090909; 106 | @HashcodeField 107 | private float f = 4444111; 108 | private double d = 123123123; 109 | } 110 | 111 | private class ToStringTestClassXXX extends ValuesHolder{ 112 | @EqualsField 113 | private int i = 10000; 114 | private float f = 123123123; 115 | private double d = 123123123; 116 | } 117 | 118 | private class ToStringTestClassXXXX extends ValuesHolder{ 119 | private int i = 50000; 120 | private float f = 123123123; 121 | @Id 122 | private double d = 99900011; 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/detector/ApiMeadataTest.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.detector; 2 | 3 | import io.github.rhkiswani.javaff.exceptions.ExceptionUtil; 4 | import io.github.rhkiswani.javaff.format.FormatUtil; 5 | import io.github.rhkiswani.javaff.reflection.ReflectionUtil; 6 | import org.junit.Before; 7 | import org.junit.Test; 8 | import static io.github.rhkiswani.javaff.detector.ApiDetectorUtil.*; 9 | 10 | import static io.github.rhkiswani.javaff.detector.ApiDetectorUtil.JACKSON_API_METADATA; 11 | import static org.assertj.core.api.Assertions.assertThat; 12 | 13 | public class ApiMeadataTest { 14 | private ApiMetadata apiMetadata; 15 | private ApiMetadata apiMetadata2; 16 | 17 | @Before 18 | public void setUp(){ 19 | apiMetadata = new ApiMetadata(null, null, null, null); 20 | apiMetadata2 = JACKSON_API_METADATA; 21 | } 22 | 23 | @Test 24 | public void testEquals() throws Exception { 25 | assertThat(apiMetadata.equals(apiMetadata2)).isEqualTo(false); 26 | apiMetadata.setMainClassName(JACKSON_API_METADATA.getMainClassName()); 27 | assertThat(apiMetadata.equals(apiMetadata2)).isEqualTo(false); 28 | apiMetadata.setGroupId(JACKSON_API_METADATA.getGroupId()); 29 | assertThat(apiMetadata.equals(apiMetadata2)).isEqualTo(true); 30 | } 31 | 32 | @Test 33 | public void testClone() throws Exception { 34 | new ApiDetectorUtil();// for test coverage 35 | new ExceptionUtil(); 36 | new FormatUtil(); 37 | new ReflectionUtil(); 38 | assertThat(apiMetadata).isNotNull(); 39 | apiMetadata2.setName("Test"); 40 | apiMetadata2.setFrameworkUrl("URL"); 41 | ApiMetadata clone = apiMetadata2.clone(); 42 | assertThat(clone).isNotNull(); 43 | assertThat(apiMetadata2.getName()).isEqualTo(clone.getName()); 44 | assertThat(apiMetadata2.getGroupId()).isEqualTo(clone.getGroupId()); 45 | assertThat(apiMetadata2.getMainClassName()).isEqualTo(clone.getMainClassName()); 46 | assertThat(apiMetadata2.getFrameworkUrl()).isEqualTo(clone.getFrameworkUrl()); 47 | } 48 | 49 | 50 | } 51 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/detector/DetectorFactoryTest.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.detector; 2 | 3 | import io.github.rhkiswani.javaff.lang.exceptions.IllegalParamException; 4 | import org.junit.Test; 5 | 6 | import static org.assertj.core.api.Assertions.assertThat; 7 | 8 | public class DetectorFactoryTest { 9 | 10 | @Test 11 | public void testRegistry() throws Exception { 12 | assertThat(ApiDetectorFactory.instance()).isNotNull(); 13 | assertThat(ApiDetectorFactory.instance() == ApiDetectorFactory.instance()).isEqualTo(true); 14 | assertThat(ApiDetectorFactory.getDetector().isAvailable(ApiDetectorUtil.JPA_API_METADATA)).isEqualTo(true); 15 | assertThat(ApiDetectorFactory.getDetector().isAvailable(ApiDetectorUtil.APACHE_HTTPCLIENT_API_METADATA)).isEqualTo(true); 16 | try{ 17 | ApiDetectorFactory.getDetector().isAvailable(null); 18 | }catch (Exception e){ 19 | assertThat(e).isInstanceOf(IllegalParamException.class).hasMessage("Api Metadata cant be null"); 20 | } 21 | try{ 22 | ApiDetectorFactory.getDetector().isAvailable(new ApiMetadata()); 23 | }catch (Exception e){ 24 | assertThat(e).isInstanceOf(IllegalParamException.class).hasMessage("Api Main Class Name cant be null"); 25 | } 26 | 27 | } 28 | 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/exceptions/ExceptionHandlersFactoryTest.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.exceptions; 2 | 3 | import io.github.rhkiswani.javaff.beans.EmployeeX; 4 | import io.github.rhkiswani.javaff.format.FormatUtil; 5 | import io.github.rhkiswani.javaff.lang.exceptions.IllegalParamException; 6 | import org.junit.Before; 7 | import org.junit.FixMethodOrder; 8 | import org.junit.Test; 9 | import org.junit.runners.MethodSorters; 10 | 11 | import java.sql.SQLException; 12 | 13 | import static org.assertj.core.api.Assertions.assertThat; 14 | 15 | @FixMethodOrder(MethodSorters.NAME_ASCENDING) 16 | public class ExceptionHandlersFactoryTest { 17 | 18 | private String exceptionMsg = "dummyMsg"; 19 | private ExceptionHandler exceptionHandler ; 20 | 21 | @Before 22 | public void setUp(){ 23 | exceptionHandler = new TestExceptionHandler(); 24 | } 25 | 26 | @Test 27 | public void testRegistry() throws Exception { 28 | assertThat(ExceptionHandlersFactory.instance()).isNotNull(); 29 | assertThat(ExceptionHandlersFactory.instance() == ExceptionHandlersFactory.instance()).isEqualTo(true); 30 | assertThat(ExceptionHandlersFactory.instance().listImplementations().size()).isEqualTo(1); 31 | ExceptionHandlersFactory.instance().add(SQLException.class, new ExceptionHandler() { 32 | @Override 33 | public void handle(Throwable t) { 34 | t.printStackTrace(); 35 | } 36 | }); 37 | assertThat(ExceptionHandlersFactory.instance().listImplementations().size()).isEqualTo(2); 38 | try{ 39 | ExceptionHandlersFactory.instance().add(Throwable.class, exceptionHandler); 40 | }catch (Exception e){ 41 | assertThat(e).isInstanceOf(IllegalParamException.class).hasMessage("class java.lang.Throwable is already exist please use overrideImp method instated"); 42 | } 43 | 44 | ExceptionHandlersFactory.instance().overrideImp(Throwable.class, exceptionHandler); 45 | assertThat(ExceptionHandlersFactory.instance().listImplementations().size()).isEqualTo(2); 46 | ExceptionHandlersFactory.instance().add(ArrayIndexOutOfBoundsException.class, exceptionHandler); 47 | ExceptionHandlersFactory.instance().overrideImp(ArrayIndexOutOfBoundsException.class, exceptionHandler); 48 | assertThat(ExceptionHandlersFactory.instance().listImplementations().size()).isEqualTo(3); 49 | ExceptionHandlersFactory.instance().remove(ArrayIndexOutOfBoundsException.class); 50 | assertThat(ExceptionHandlersFactory.instance().listImplementations().size()).isEqualTo(2); 51 | } 52 | 53 | 54 | @Test 55 | public void testFactory() throws Exception { 56 | assertThat(ExceptionHandlersFactory.getExceptionHandler(Throwable.class).getClass()).isEqualTo(DefaultExceptionHandler.class); 57 | ExceptionHandlersFactory.instance().overrideImp(Throwable.class, exceptionHandler); 58 | assertThat(ExceptionHandlersFactory.getExceptionHandler(Throwable.class).getClass()).isEqualTo(TestExceptionHandler.class); 59 | assertThat(ExceptionHandlersFactory.getExceptionHandler(SQLException.class).getClass()).isEqualTo(TestExceptionHandler.class); 60 | assertThat(ExceptionHandlersFactory.getExceptionHandler(EmployeeX.class).getClass()).isEqualTo(DefaultExceptionHandler.class); 61 | 62 | try { 63 | ExceptionHandlersFactory.getExceptionHandler(null); 64 | }catch (Throwable t) { 65 | assertThat(t).isInstanceOf(IllegalParamException.class).hasMessage("Target Class cant be null"); 66 | } 67 | } 68 | 69 | @Test 70 | public void testSmartException() throws Exception { 71 | try { 72 | throw new SmartException(SmartException.EXCEEDS_LIMIT, "Test Name", 1000000); 73 | }catch (Throwable t) { 74 | assertThat(t).isInstanceOf(SmartException.class).hasMessage(FormatUtil.formatString("{0} MaxSize is {1}", "Test Name", 1000000)); 75 | } 76 | try { 77 | throw new SmartException(new RuntimeException(new NullPointerException(SmartException.NOT_FOUND))); 78 | }catch (Throwable t) { 79 | assertThat(t).isInstanceOf(SmartException.class).hasMessage("java.lang.RuntimeException: java.lang.NullPointerException: NOT_FOUND"); 80 | } 81 | try { 82 | throw new SmartException(SmartException.NOT_FOUND, new RuntimeException(new NullPointerException())); 83 | }catch (Throwable t) { 84 | assertThat(t).isInstanceOf(SmartException.class).hasMessage("{0} not found"); 85 | } 86 | 87 | } 88 | 89 | @Test 90 | public void testGetRootCause() throws Exception { 91 | assertThat(ExceptionUtil.getRootCause(null)).isNull(); 92 | try { 93 | throw new SmartException(new RuntimeException(new NullPointerException(SmartException.NOT_FOUND))); 94 | }catch (Throwable t) { 95 | assertThat(ExceptionUtil.getRootCause(t).getClass()).isEqualTo(NullPointerException.class); 96 | assertThat(ExceptionUtil.getRootCause(t).getMessage()).isEqualTo("NOT_FOUND"); 97 | } 98 | try { 99 | throw new SmartException(new NullPointerException(SmartException.NOT_FOUND)); 100 | }catch (Throwable t) { 101 | assertThat(ExceptionUtil.getRootCause(t).getClass()).isEqualTo(NullPointerException.class); 102 | assertThat(ExceptionUtil.getRootCause(t).getMessage()).isEqualTo("NOT_FOUND"); 103 | } 104 | try { 105 | throw new SmartException(SmartException.NOT_FOUND, "Kiswani"); 106 | }catch (Throwable t) { 107 | assertThat(ExceptionUtil.getRootCause(t).getClass()).isEqualTo(SmartException.class); 108 | assertThat(ExceptionUtil.getRootCause(t).getMessage()).isEqualTo("Kiswani not found"); 109 | } 110 | } 111 | 112 | @Test 113 | public void testHandle() throws Exception { 114 | try { 115 | ExceptionUtil.handle(null); 116 | }catch (Throwable t) { 117 | assertThat(ExceptionUtil.getRootCause(t).getClass()).isEqualTo(IllegalParamException.class); 118 | assertThat(ExceptionUtil.getRootCause(t).getMessage()).isEqualTo("Exception cant be null"); 119 | } 120 | ExceptionHandlersFactory.instance().setDefault(new ExceptionHandler() { 121 | @Override 122 | public void handle(Throwable t) { 123 | exceptionMsg = "userDefaultHandler"; 124 | } 125 | }); 126 | ExceptionUtil.handle(new NullPointerException()); 127 | assertThat(exceptionMsg).isEqualTo("userDefaultHandler"); 128 | 129 | //Any class is instance of ConsoleException will be handled here 130 | ExceptionHandlersFactory.instance().add(ConsoleException.class, new ExceptionHandler() { 131 | @Override 132 | public void handle(Throwable t) { 133 | exceptionMsg = "ConsoleException handler"; 134 | } 135 | }); 136 | 137 | //Any class is instance of MailException will be handled here 138 | ExceptionHandlersFactory.instance().add(MailException.class, new ExceptionHandler() { 139 | @Override 140 | public void handle(Throwable t) { 141 | exceptionMsg = "MailException handler"; 142 | } 143 | }); 144 | 145 | 146 | ExceptionUtil.handle(new ConsoleException()); 147 | assertThat(exceptionMsg).isEqualTo("userDefaultHandler"); 148 | ExceptionHandlersFactory.instance().setDefault(null); 149 | ExceptionUtil.handle(new ConsoleException()); 150 | assertThat(exceptionMsg).isEqualTo("ConsoleException handler"); 151 | ExceptionUtil.handle(new SubConsoleException()); 152 | assertThat(exceptionMsg).isEqualTo("ConsoleException handler"); 153 | ExceptionUtil.handle(new MailException()); 154 | assertThat(exceptionMsg).isEqualTo("MailException handler"); 155 | ExceptionUtil.handle(new SubMailException()); 156 | assertThat(exceptionMsg).isEqualTo("MailException handler"); 157 | 158 | //We decided to override the default implantation for Throwable.class 159 | ExceptionHandlersFactory.instance().overrideImp(Throwable.class, new ExceptionHandler() { 160 | @Override 161 | public void handle(Throwable t) { 162 | exceptionMsg = "Overridden handler"; 163 | } 164 | }); 165 | 166 | ExceptionUtil.handle(new NullPointerException()); 167 | assertThat(exceptionMsg).isEqualTo("Overridden handler"); 168 | ExceptionHandlersFactory.instance().remove(MailException.class); 169 | ExceptionHandlersFactory.instance().remove(ConsoleException.class); 170 | } 171 | 172 | private static class ConsoleException extends RuntimeException{ 173 | 174 | } 175 | 176 | private static class SubConsoleException extends ConsoleException{ 177 | 178 | } 179 | 180 | private static class MailException extends RuntimeException{ 181 | 182 | } 183 | 184 | private static class SubMailException extends MailException { 185 | 186 | } 187 | 188 | private class TestExceptionHandler extends DefaultExceptionHandler { 189 | }; 190 | } 191 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/factory/AbstractFactoryTest.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.factory; 2 | 3 | import io.github.rhkiswani.javaff.factory.exceptions.NoImplementationFoundException; 4 | import io.github.rhkiswani.javaff.lang.exceptions.IllegalParamException; 5 | import org.junit.Test; 6 | 7 | import java.util.Date; 8 | 9 | import static org.assertj.core.api.Assertions.assertThat; 10 | 11 | public class AbstractFactoryTest { 12 | 13 | @Test 14 | public void testRegistry() throws Exception { 15 | assertThat(TestFactory.instance()).isNotNull(); 16 | assertThat(TestFactory.instance() == TestFactory.instance()).isEqualTo(true); 17 | assertThat(TestFactory.instance().listImplementations().size()).isEqualTo(10); 18 | TestFactory.instance().add(Character.class, new DummyObject()); 19 | assertThat(TestFactory.instance().listImplementations().size()).isEqualTo(11); 20 | TestFactory.instance().remove(char.class); 21 | assertThat(TestFactory.instance().listImplementations().size()).isEqualTo(10); 22 | } 23 | 24 | @Test 25 | public void testOverride() throws Exception { 26 | try{ 27 | TestFactory.instance().add(Date.class, new DummyObject()); 28 | } catch (Exception e){ 29 | assertThat(e).isInstanceOf(IllegalParamException.class).hasMessage("class java.util.Date is already exist please use overrideImp method instated"); 30 | } 31 | TestFactory.instance().overrideImp(char.class, new DummyObject()); 32 | testPrimitive(char.class, Character.class); 33 | } 34 | 35 | @Test 36 | public void testGet() throws Exception { 37 | DummyObject dummyObjectForNumber = TestFactory.instance().create(Number.class); 38 | DummyObject dummyObject2ForNumber = TestFactory.instance().create(Number.class); 39 | assertThat(dummyObjectForNumber).isNotNull(); 40 | assertThat(dummyObject2ForNumber).isNotNull(); 41 | assertThat(dummyObjectForNumber.toString()).isEqualTo(dummyObject2ForNumber.toString()); 42 | 43 | testPrimitive(byte.class, Byte.class); 44 | testPrimitive(short.class, Short.class); 45 | testPrimitive(int.class, Integer.class); 46 | testPrimitive(long.class, Long.class); 47 | testPrimitive(float.class, Float.class); 48 | testPrimitive(double.class, Double.class); 49 | testPrimitive(boolean.class, Boolean.class); 50 | } 51 | 52 | @Test 53 | public void testGetWithNoImpl() throws Exception { 54 | try{ 55 | TestFactory.instance().create(void.class); 56 | } catch (Exception e) { 57 | assertThat(e).isInstanceOf(NoImplementationFoundException.class).hasMessage("No implementation found for type [void] you need to set implementation through TestFactory.instance().add"); 58 | } 59 | } 60 | 61 | private void testPrimitive(Class primitive, Class wrapperClass) { 62 | DummyObject dummyObject = TestFactory.instance().create(wrapperClass); 63 | assertThat(dummyObject).isNotNull(); 64 | DummyObject dummyObject1 = TestFactory.instance().create(primitive); 65 | assertThat(dummyObject1).isNotNull(); 66 | assertThat(dummyObject1).isEqualTo(dummyObject); 67 | } 68 | 69 | private static class TestFactory extends AbstractFactory { 70 | 71 | private static TestFactory instance = new TestFactory(); 72 | 73 | private TestFactory(){ 74 | add(Date.class, new DummyObject()); 75 | add(String.class, new DummyObject()); 76 | add(Number.class, new DummyObject()); 77 | add(Byte.class, new DummyObject()); 78 | add(short.class, new DummyObject()); 79 | add(int.class, new DummyObject()); 80 | add(Long.class, new DummyObject()); 81 | add(Float.class, new DummyObject()); 82 | add(Double.class, new DummyObject()); 83 | add(Boolean.class, new DummyObject()); 84 | } 85 | 86 | public static TestFactory instance(){ 87 | return instance; 88 | } 89 | 90 | } 91 | 92 | private static class DummyObject { 93 | 94 | } 95 | 96 | // @After 97 | // public void tearDown(){ 98 | // TestFactory.instance().remove(Date.class); 99 | // TestFactory.instance().remove(String.class); 100 | // TestFactory.instance().remove(Number.class); 101 | // TestFactory.instance().remove(Byte.class); 102 | // TestFactory.instance().remove(Character.class); 103 | // TestFactory.instance().remove(short.class); 104 | // TestFactory.instance().remove(int.class); 105 | // TestFactory.instance().remove(Long.class); 106 | // TestFactory.instance().remove(Float.class); 107 | // TestFactory.instance().remove(Double.class); 108 | // TestFactory.instance().remove(Boolean.class); 109 | // } 110 | } 111 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/format/AbstractFormatTest.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.format; 2 | 3 | import org.assertj.core.util.Arrays; 4 | 5 | import static org.assertj.core.api.Assertions.assertThat; 6 | 7 | public class AbstractFormatTest { 8 | 9 | public void testNulls(Formatter formatter, T value) { 10 | assertThat(formatter.format(null, Arrays.array(null))).isNull(); 11 | assertThat(formatter.format(null, Arrays.array(null, null))).isNull(); 12 | assertThat(formatter.format(value, null)).isNotNull(); 13 | } 14 | 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/format/DateFormatTest.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.format; 2 | 3 | import io.github.rhkiswani.javaff.format.exception.FormatException; 4 | import org.junit.Test; 5 | 6 | import java.text.ParseException; 7 | import java.text.SimpleDateFormat; 8 | import java.util.Date; 9 | 10 | import static org.assertj.core.api.Assertions.assertThat; 11 | 12 | public class DateFormatTest extends AbstractFormatTest{ 13 | 14 | private static final String DATE_FORMAT = "MM/dd/yy HH:mm a"; 15 | private static final String DATE = "11/24/16 12:00 PM"; 16 | 17 | @Test 18 | public void testDateFormatter() { 19 | testNulls(new DateFormatter(), getDate()); 20 | assertThat(new DateFormatter().format(getDate(), DATE_FORMAT)).isEqualTo(DATE); 21 | try { 22 | new DateFormatter().format(getDate(), "dfghdfg"); 23 | } catch (Exception e){ 24 | assertThat(e).isInstanceOf(FormatException.class).hasMessage("Date format is not fit to 11/24/16 12:00 PM"); 25 | } 26 | try { 27 | new DateFormatter().format(getDate(), ""); 28 | } catch (Exception e){ 29 | assertThat(e).isInstanceOf(FormatException.class).hasMessage("Date format is not fit to 11/24/16 12:00 PM"); 30 | } 31 | } 32 | 33 | private Date getDate(){ 34 | return getDate(DATE_FORMAT); 35 | } 36 | 37 | private Date getDate(String format){ 38 | try { 39 | return new SimpleDateFormat(format).parse(DATE); 40 | } catch (ParseException e) { 41 | // never happen 42 | return null; 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/format/FormatFactoryTest.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.format; 2 | 3 | import io.github.rhkiswani.javaff.format.exception.FormatException; 4 | import org.junit.Test; 5 | 6 | import static org.assertj.core.api.Assertions.assertThat; 7 | 8 | public class FormatFactoryTest { 9 | 10 | @Test 11 | public void testRegistry() throws Exception { 12 | assertThat(FormatFactory.instance()).isNotNull(); 13 | assertThat(FormatFactory.instance() == FormatFactory.instance()).isEqualTo(true); 14 | assertThat(FormatFactory.instance().listImplementations().size()).isEqualTo(3); 15 | FormatFactory.instance().add(Character.class, new Formatter() { 16 | 17 | @Override 18 | protected String format(Character in, Object... params) throws FormatException { 19 | return FormatUtil.format(in, params); 20 | } 21 | }); 22 | assertThat(FormatFactory.instance().listImplementations().size()).isEqualTo(4); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/format/FormatUtilTest.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.format; 2 | 3 | import io.github.rhkiswani.javaff.beans.EmployeeX; 4 | import org.assertj.core.util.Arrays; 5 | import org.junit.Test; 6 | 7 | import static org.assertj.core.api.Assertions.assertThat; 8 | 9 | public class FormatUtilTest extends AbstractFormatTest{ 10 | 11 | @Test 12 | public void testTextFormatter() { 13 | assertThat(FormatUtil.format(null, null)).isNull(); 14 | assertThat(FormatUtil.format("Kiswani {0}", Arrays.array("", "1"))).isEqualTo("Kiswani "); 15 | assertThat(FormatUtil.format("Kiswani {0}", null)).isEqualTo("Kiswani {0}"); 16 | assertThat(FormatUtil.format("Kiswani {0} {1}", Arrays.array(Arrays.array(1, 2 , 3)))).isEqualTo("Kiswani 1 2"); 17 | assertThat(FormatUtil.format("Kiswani {0} {1}", Arrays.array(Arrays.array(Arrays.array(1, 2 , 3))))).isEqualTo("Kiswani 1 2"); 18 | } 19 | 20 | @Test 21 | public void testDefault() { 22 | assertThat(FormatFactory.getFormatter(EmployeeX.class)).isInstanceOf(StringFormatter.class); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/format/NumberFormatTest.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.format; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.assertj.core.api.Assertions.assertThat; 6 | 7 | public class NumberFormatTest extends AbstractFormatTest{ 8 | 9 | @Test 10 | public void testNumberFormatter() { 11 | testNulls(new NumberFormatter(), 10000); 12 | 13 | assertThat(new NumberFormatter().format(Float.MAX_VALUE / Math.pow(10, 10))).isEqualTo("34,028,234,663,852,887,000,000,000,000"); 14 | assertThat(new NumberFormatter().format(Double.MAX_VALUE / Math.pow(10, 300))).isEqualTo("179,769,313.486"); 15 | assertThat(new NumberFormatter().format(Long.MAX_VALUE / Math.pow(10, 10))).isEqualTo("922,337,203.685"); 16 | assertThat(new NumberFormatter().format(Integer.MAX_VALUE)).isEqualTo("2,147,483,647"); 17 | assertThat(new NumberFormatter().format(Short.MAX_VALUE)).isEqualTo("32,767"); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/format/TextFormatTest.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.format; 2 | 3 | import org.assertj.core.util.Arrays; 4 | import org.junit.Test; 5 | 6 | import static org.assertj.core.api.Assertions.assertThat; 7 | 8 | public class TextFormatTest extends AbstractFormatTest{ 9 | 10 | @Test 11 | public void testTextFormatter() { 12 | testNulls(new StringFormatter(), "Kiswani"); 13 | 14 | assertThat(new StringFormatter().format("Kiswani", Arrays.array(3))).isEqualTo("Kiswani"); 15 | assertThat(new StringFormatter().format("Kiswani {1}", Arrays.array(null, "1"))).isEqualTo("Kiswani 1"); 16 | assertThat(new StringFormatter().format("Kiswani {0}", Arrays.array(null, "1"))).isEqualTo("Kiswani "); 17 | assertThat(new StringFormatter().format("Kiswani {0}", Arrays.array("", "1"))).isEqualTo("Kiswani "); 18 | assertThat(new StringFormatter().format("Kiswani {0}", null)).isEqualTo("Kiswani {0}"); 19 | assertThat(new StringFormatter().format("Kiswani {0} {1}", Arrays.array(Arrays.array(1, 2 , 3)))).isEqualTo("Kiswani 1 2"); 20 | assertThat(new StringFormatter().format("Kiswani {0} {1}", Arrays.array(Arrays.array(Arrays.array(1, 2 , 3))))).isEqualTo("Kiswani 1 2"); 21 | 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/http/HttpClientTest.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.http; 2 | 3 | import io.github.rhkiswani.javaff.exceptions.ExceptionUtil; 4 | import io.github.rhkiswani.javaff.factory.exceptions.NoImplementationFoundException; 5 | import io.github.rhkiswani.javaff.httpclient.ApacheHttpClient; 6 | import io.github.rhkiswani.javaff.httpclient.HttpClient; 7 | import io.github.rhkiswani.javaff.httpclient.HttpClientFactory; 8 | import io.github.rhkiswani.javaff.httpclient.exceptions.HttpClientException; 9 | import io.github.rhkiswani.javaff.json.JsonHandler; 10 | import io.github.rhkiswani.javaff.json.JsonHandlerFactory; 11 | import org.junit.Test; 12 | 13 | import java.util.HashMap; 14 | import java.util.Map; 15 | 16 | import static org.assertj.core.api.Assertions.assertThat; 17 | 18 | public class HttpClientTest extends WebTester{ 19 | 20 | @Test 21 | public void testFactory() throws Exception { 22 | // check default 23 | HttpClient httpClient = HttpClientFactory.getHttpClient(Object.class); 24 | assertThat(httpClient).isNotNull(); 25 | 26 | HttpClientFactory.instance().remove(Object.class); 27 | try { 28 | HttpClientFactory.getHttpClient(Object.class); 29 | }catch (Exception e){ 30 | assertThat(e).isInstanceOf(NoImplementationFoundException.class).hasMessage("No implementation found for type [class java.lang.Object] you need to set implementation through HttpClientFactory.instance().add or add https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient to your classpath"); 31 | } 32 | HttpClientFactory.instance().add(Object.class, new ApacheHttpClient()); 33 | } 34 | 35 | @Test 36 | public void testExceptions() throws Exception{ 37 | HttpClient httpClient = HttpClientFactory.getHttpClient(HttpClientTest.class); 38 | try { 39 | httpClient.post("http://xyaaaaaxzcsdrwerwefv.com", null, null); 40 | }catch (Exception e){ 41 | assertThat(e).isInstanceOf(HttpClientException.class); 42 | ExceptionUtil.handle(e); 43 | } 44 | try { 45 | httpClient.postJson("http://xyaaaaaxzcsdrwerwefv.com", null, null); 46 | }catch (Exception e){ 47 | assertThat(e).isInstanceOf(HttpClientException.class).hasMessage("Json Object cant be null"); 48 | } 49 | try { 50 | httpClient.postJson("http://asdadasdasdasdasasd.com", "{}", null); 51 | }catch (Exception e){ 52 | assertThat(e).isInstanceOf(HttpClientException.class); 53 | ExceptionUtil.handle(e); 54 | } 55 | try { 56 | httpClient.postJson("http://asdasd.com", "{}", null); 57 | }catch (Exception e){ 58 | assertThat(e).isInstanceOf(HttpClientException.class); 59 | ExceptionUtil.handle(e); 60 | } 61 | } 62 | 63 | 64 | @Test 65 | public void testPost() throws Exception{ 66 | HttpClient httpClient = HttpClientFactory.getHttpClient(HttpClientTest.class); 67 | Map params = prepareParams(); 68 | String post = httpClient.post(BASE_URL, params, null); 69 | assertValues("POST", params, post); 70 | } 71 | 72 | @Test 73 | public void testPostJson() throws Exception{ 74 | HttpClient httpClient = HttpClientFactory.getHttpClient(HttpClientTest.class); 75 | String post = httpClient.postJson(BASE_URL,"{\"method\":\"POST\"}", null); 76 | assertJsonResponse(post, "POST"); 77 | } 78 | 79 | @Test 80 | public void testPatchJson() throws Exception{ 81 | HttpClient httpClient = HttpClientFactory.getHttpClient(HttpClientTest.class); 82 | String post = httpClient.patchJson(BASE_URL,"{\"method\":\"PATCH\"}", null); 83 | assertJsonResponse(post, "PATCH"); 84 | } 85 | 86 | @Test 87 | public void testPut() throws Exception{ 88 | String method = "PUT"; 89 | HttpClient httpClient = HttpClientFactory.getHttpClient(HttpClientTest.class); 90 | Map params = prepareParams(); 91 | Map headers = prepareHeaders(); 92 | String put = httpClient.put(BASE_URL, params, headers); 93 | assertValues(method, params, put); 94 | } 95 | 96 | private Map prepareParams() { 97 | Map params = new HashMap<>(); 98 | params.put("paramsEmail", "rhkiswani@gmail.com"); 99 | return params; 100 | } 101 | 102 | private Map prepareHeaders() { 103 | Map params = new HashMap<>(); 104 | params.put("header1", "rhkiswani@gmail.com"); 105 | return params; 106 | } 107 | 108 | private void assertValues(String method, Map params, String post) { 109 | assertValues(method, params, post, "application/x-www-form-urlencoded"); 110 | } 111 | 112 | private void assertValues(String method, Map params, String post, String contentType) { 113 | JsonHandler handler = JsonHandlerFactory.getJsonHandler(HttpClientTest.class); 114 | Map map = handler.fromJson(post, Map.class); 115 | Response receivedRespond = handler.fromJson(map.get("response").toString(), Response.class); 116 | 117 | assertThat(receivedRespond.requestHeaders).isNotNull(); 118 | assertThat(receivedRespond.params).isEqualTo(params); 119 | assertThat(receivedRespond.method).isEqualTo(method); 120 | assertThat(receivedRespond.contentType).isEqualTo(contentType); 121 | } 122 | 123 | @Test 124 | public void testPutJson() throws Exception{ 125 | HttpClient httpClient = HttpClientFactory.getHttpClient(HttpClientTest.class); 126 | String put = httpClient.putJson(BASE_URL,"{\"method\":\"PUT\"}", null); 127 | assertJsonResponse(put, "PUT"); 128 | } 129 | 130 | @Test 131 | public void testGet() throws Exception{ 132 | String method = "GET"; 133 | HttpClient httpClient = HttpClientFactory.getHttpClient(HttpClientTest.class); 134 | Map params = prepareParams(); 135 | String get = httpClient.get(BASE_URL, params, null); 136 | assertValues(method, params, get, null); 137 | } 138 | 139 | @Test 140 | public void testDelete() throws Exception{ 141 | String method = "DELETE"; 142 | HttpClient httpClient = HttpClientFactory.getHttpClient(HttpClientTest.class); 143 | Map params = prepareParams(); 144 | String get = httpClient.delete(BASE_URL, params, null); 145 | assertValues(method, params, get, null); 146 | } 147 | 148 | @Test 149 | public void testHead() throws Exception{ 150 | HttpClient httpClient = HttpClientFactory.getHttpClient(HttpClientTest.class); 151 | Map params = prepareParams(); 152 | Map head = httpClient.head(BASE_URL, params, null); 153 | assertThat(head.get("Server")).isEqualTo("Jetty(9.4.0.RC2)"); 154 | } 155 | 156 | @Test 157 | public void testHeadException() throws Exception{ 158 | HttpClient httpClient = HttpClientFactory.getHttpClient(HttpClientTest.class); 159 | try { 160 | httpClient.head("http://qwerqwerqwerqwer.com", null, null); 161 | } catch (Exception e){ 162 | assertThat(e).isInstanceOf(HttpClientException.class); 163 | } 164 | } 165 | 166 | @Test 167 | public void testOptions() throws Exception{ 168 | HttpClient httpClient = HttpClientFactory.getHttpClient(HttpClientTest.class); 169 | Map params = prepareParams(); 170 | Map head = httpClient.options(BASE_URL, params, null); 171 | assertThat(head.get("Server")).isEqualTo("Jetty(9.4.0.RC2)"); 172 | } 173 | 174 | private void assertJsonResponse(String response, String method) { 175 | JsonHandler handler = JsonHandlerFactory.getJsonHandler(HttpClientTest.class); 176 | Map map = handler.fromJson(response, Map.class); 177 | Response receivedRespond = handler.fromJson(map.get("response").toString(), Response.class); 178 | 179 | assertThat(receivedRespond.jsonParams).isEqualTo("{\"method\":\""+ method +"\"}"); 180 | assertThat(receivedRespond.method).isEqualTo(method); 181 | assertThat(receivedRespond.contentType).isEqualTo("application/json"); 182 | } 183 | } 184 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/http/WebTester.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.http; 2 | 3 | import io.github.rhkiswani.javaff.json.JsonHandlerFactory; 4 | import io.github.rhkiswani.javaff.lang.exceptions.IllegalParamException; 5 | import org.eclipse.jetty.server.Request; 6 | import org.eclipse.jetty.server.Server; 7 | import org.eclipse.jetty.server.ServerConnector; 8 | import org.eclipse.jetty.server.handler.AbstractHandler; 9 | import org.junit.After; 10 | import org.junit.Before; 11 | 12 | import javax.servlet.ServletException; 13 | import javax.servlet.http.HttpServletRequest; 14 | import javax.servlet.http.HttpServletResponse; 15 | import java.io.BufferedReader; 16 | import java.io.IOException; 17 | import java.net.BindException; 18 | import java.util.Enumeration; 19 | import java.util.HashMap; 20 | import java.util.Map; 21 | 22 | public class WebTester { 23 | protected static final String BASE_URL = "http://localhost:9999/testHttp"; 24 | 25 | protected Server server = new Server(9999); 26 | protected ServerConnector connector = null; 27 | 28 | @Before 29 | public void startJetty() throws Exception { 30 | // Create Server 31 | server.setHandler(new MyServlet()); 32 | // Start Server 33 | try { 34 | server.start(); 35 | }catch (BindException b){ 36 | if (b.getMessage().contains("Address already in use")){ 37 | server.stop(); 38 | throw b ; 39 | } 40 | } 41 | } 42 | 43 | @After 44 | public void stopJetty() { 45 | try { 46 | server.stop(); 47 | } 48 | catch (Exception e) { 49 | throw new IllegalParamException(e.getMessage()); 50 | } 51 | } 52 | 53 | private class MyServlet extends AbstractHandler { 54 | 55 | @Override 56 | public void handle(String s, Request request, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { 57 | httpServletResponse.setContentType(request.getContentType()); 58 | httpServletResponse.setStatus(HttpServletResponse.SC_OK); 59 | sendWhatReceived(httpServletRequest, httpServletResponse); 60 | request.setHandled(true); 61 | } 62 | 63 | private void sendWhatReceived(HttpServletRequest req, HttpServletResponse resp) throws IOException { 64 | Response r = new Response(); 65 | r.method = req.getMethod(); 66 | r.contentType = req.getContentType(); 67 | for (String o : req.getParameterMap().keySet()) { 68 | r.params.put(o, req.getParameter(o)); 69 | } 70 | Enumeration headerNames = req.getHeaderNames(); 71 | while (headerNames.hasMoreElements()){ 72 | String headerName = headerNames.nextElement(); 73 | r.requestHeaders.put(headerName, req.getHeader(headerName)); 74 | } 75 | if (r.contentType != null && r.contentType.equalsIgnoreCase("application/json")){ 76 | BufferedReader br = req.getReader(); 77 | String str; 78 | while( (str = br.readLine()) != null ){ 79 | r.jsonParams += str; 80 | } 81 | } 82 | resp.getWriter().println(JsonHandlerFactory.getJsonHandler(WebTester.class).toJson(r)); 83 | } 84 | } 85 | 86 | protected class Response { 87 | protected String method; 88 | protected String contentType; 89 | protected Map params = new HashMap<>(); 90 | protected Map requestHeaders = new HashMap<>(); 91 | protected String jsonParams = ""; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/json/JsonHandlerFactoryTest.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.json; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.google.gson.Gson; 5 | import io.github.rhkiswani.javaff.beans.EmployeeX; 6 | import io.github.rhkiswani.javaff.factory.exceptions.NoImplementationFoundException; 7 | import io.github.rhkiswani.javaff.format.FormatUtil; 8 | import io.github.rhkiswani.javaff.json.annotations.GsonBean; 9 | import io.github.rhkiswani.javaff.json.annotations.JacksonBean; 10 | import io.github.rhkiswani.javaff.json.exceptions.JsonException; 11 | import io.github.rhkiswani.javaff.lang.exceptions.IllegalParamException; 12 | import org.junit.Before; 13 | import org.junit.Test; 14 | 15 | import java.util.Date; 16 | 17 | import static org.assertj.core.api.Assertions.assertThat; 18 | public class JsonHandlerFactoryTest { 19 | 20 | private EmployeeX employeeX = null; 21 | @Before 22 | public void setUp(){ 23 | employeeX = new EmployeeX(); 24 | employeeX.setEmpId(1000); 25 | employeeX.setName("Kiswani"); 26 | employeeX.setId(10); 27 | } 28 | @Test 29 | public void testJsonHandler() { 30 | assertThat(JsonHandlerFactory.getJsonHandler(JacksonBean.class).getImplementation()).isInstanceOf(ObjectMapper.class); 31 | assertThat(JsonHandlerFactory.getJsonHandler(GsonBean.class).getImplementation()).isInstanceOf(Gson.class); 32 | try { 33 | JsonHandlerFactory.getJsonHandler(null); 34 | } catch (Exception e){ 35 | assertThat(e).isInstanceOf(IllegalParamException.class).hasMessage("Target Class cant be null"); 36 | } 37 | } 38 | 39 | @Test 40 | public void testObjectToJson() { 41 | String jacksonJson = "{\"id\":10,\"name\":\"Kiswani\",\"empId\":1000}"; 42 | String gsonJson = "{\"empId\":1000,\"id\":10,\"name\":\"Kiswani\"}"; 43 | assertThat(JsonHandlerFactory.getJsonHandler(GsonBean.class).toJson(employeeX)).isEqualTo(gsonJson); 44 | assertThat(JsonHandlerFactory.getJsonHandler(JacksonBean.class).toJson(employeeX)).isEqualTo(jacksonJson); 45 | } 46 | 47 | @Test 48 | public void testJsonHandlerFactory() { 49 | assertThat(JsonHandlerFactory.instance()).isEqualTo(JsonHandlerFactory.instance()); 50 | } 51 | 52 | @Test 53 | public void testJsonToObject() { 54 | String jacksonJson = "{\"id\":10,\"name\":\"Kiswani\",\"empId\":1000}"; 55 | String gsonJson = "{\"empId\":1000,\"id\":10,\"name\":\"Kiswani\"}"; 56 | assertThat(JsonHandlerFactory.getJsonHandler(GsonBean.class).fromJson(gsonJson,EmployeeX.class)).isEqualTo(employeeX); 57 | assertThat(JsonHandlerFactory.getJsonHandler(GsonBean.class).fromJson(jacksonJson,EmployeeX.class)).isEqualTo(employeeX); 58 | assertThat(JsonHandlerFactory.getJsonHandler(JacksonBean.class).fromJson(gsonJson,EmployeeX.class)).isEqualTo(employeeX); 59 | assertThat(JsonHandlerFactory.getJsonHandler(JacksonBean.class).fromJson(jacksonJson,EmployeeX.class)).isEqualTo(employeeX); 60 | } 61 | 62 | @Test 63 | public void testNoImplementationFoundException() { 64 | JsonHandlerFactory.instance().remove(Object.class); 65 | try { 66 | JsonHandlerFactory.getJsonHandler(Object.class); 67 | } catch (Exception e) { 68 | assertThat(e).isInstanceOf(NoImplementationFoundException.class).hasMessage("No implementation found for type [class java.lang.Object] you need to set implementation through JsonHandlerFactory.instance().add or add https://mvnrepository.com/artifact/com.google.code.gson/gson to your classpath"); 69 | } 70 | } 71 | @Test 72 | public void testJsonException() { 73 | String gsonJson = "{\"empId\":1000,\"id\":10,\"name"; 74 | try { 75 | JsonHandlerFactory.getJsonHandler(GsonBeanX.class).fromJson(gsonJson, Integer.class); 76 | } catch (Exception e){ 77 | assertThat(e).isInstanceOf(JsonException.class).hasMessage("java.lang.IllegalStateException: Expected an int but was BEGIN_OBJECT at line 1 column 2 path $"); 78 | } 79 | try { 80 | JsonHandlerFactory.getJsonHandler(JacksonBeanX.class).fromJson(gsonJson, Integer.class); 81 | } catch (Exception e){ 82 | assertThat(e).isInstanceOf(JsonException.class).hasMessage("Can not deserialize instance of java.lang.Integer out of START_OBJECT token\n" + 83 | " at [Source: {\"empId\":1000,\"id\":10,\"name; line: 1, column: 1]"); 84 | } 85 | try { 86 | JsonHandlerFactory.getJsonHandler(JacksonBeanX.class).toJson(new ToFailJsonJackson()); 87 | } catch (Exception e) { 88 | assertThat(e).isInstanceOf(JsonException.class).hasMessageContaining("(through reference chain: io.github.rhkiswani.javaff.json.JsonHandlerFactoryTest$ToFailJsonJackson[\"toFailJson\"])"); 89 | } 90 | } 91 | 92 | @GsonBean 93 | private class GsonBeanX extends EmployeeX{ 94 | 95 | } 96 | 97 | @JacksonBean 98 | private class JacksonBeanX extends EmployeeX{ 99 | 100 | } 101 | 102 | @JacksonBean 103 | private class ToFailJsonJackson{ 104 | private Date toFailDate = new Date(); 105 | 106 | public String getToFailJson() { 107 | return FormatUtil.format(toFailDate, "34523452345234sadfasd"); 108 | } 109 | 110 | } 111 | 112 | @GsonBean 113 | private class ToFailJsonGson{ 114 | private Date toFailDate = FormatUtil.format(new Date(), "34523452345234sadfasd"); 115 | 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/lang/ArraysUtilsTest.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.lang; 2 | 3 | import io.github.rhkiswani.javaff.format.FormatUtil; 4 | import io.github.rhkiswani.javaff.lang.exceptions.IllegalParamException; 5 | import io.github.rhkiswani.javaff.lang.utils.*; 6 | import io.github.rhkiswani.javaff.locale.LocaleUtil; 7 | import org.junit.Test; 8 | 9 | import static org.assertj.core.api.Assertions.assertThat; 10 | 11 | public class ArraysUtilsTest { 12 | 13 | @Test 14 | public void testArraysIsEmpty() { 15 | Integer[] arr = null; 16 | assertThat(ArraysUtils.isEmpty(arr)).isEqualTo(true); 17 | arr = new Integer[0]; 18 | assertThat(ArraysUtils.isEmpty(arr)).isEqualTo(true); 19 | arr = new Integer[]{null, null, null}; 20 | assertThat(arr.length).isEqualTo(3); 21 | assertThat(ArraysUtils.isEmpty(arr)).isEqualTo(true); 22 | arr = new Integer[]{null, null, 1}; 23 | assertThat(ArraysUtils.isEmpty(arr)).isEqualTo(false); 24 | } 25 | 26 | @Test 27 | public void testArraysSize() throws Exception { 28 | Integer[] arr = new Integer[ArraysUtils.MAX_ARRAY_SIZE]; 29 | try { 30 | ArraysUtils.isEmpty(arr); 31 | }catch (Throwable t) { 32 | assertThat(t).isInstanceOf(IllegalParamException.class).hasMessage(FormatUtil.formatString("{0} MaxSize is {1}", "Array", ArraysUtils.MAX_ARRAY_SIZE)); 33 | } 34 | } 35 | 36 | @Test 37 | public void testReplace() throws Exception { 38 | new ArraysUtils(); 39 | new ObjectUtils(); 40 | new StringUtils(); 41 | new LocaleUtil();// for coverage 42 | Integer[] arr = {1, 2 , 4}; 43 | String[] strings = {null}; 44 | ArraysUtils.replace(strings, null, "1"); 45 | assertThat(strings[0]).isNull(); 46 | ArraysUtils.replace(arr, 1, 4); 47 | assertThat(arr[0]).isEqualTo(4); 48 | ArraysUtils.replace(arr, 4, null); 49 | assertThat(arr[0]).isNull(); 50 | assertThat(arr[2]).isNull(); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/lang/ObjectUtilsTest.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.lang; 2 | 3 | import io.github.rhkiswani.javaff.beans.Employee; 4 | import io.github.rhkiswani.javaff.beans.Person; 5 | import io.github.rhkiswani.javaff.beans.EmployeeByIdAnnotation; 6 | import io.github.rhkiswani.javaff.beans.PersonByIdAnnotation; 7 | import io.github.rhkiswani.javaff.beans.EmployeeX; 8 | import io.github.rhkiswani.javaff.lang.exceptions.IllegalParamException; 9 | import io.github.rhkiswani.javaff.lang.utils.ObjectUtils; 10 | import org.junit.Test; 11 | 12 | import static org.assertj.core.api.Assertions.assertThat; 13 | 14 | public class ObjectUtilsTest { 15 | 16 | @Test 17 | public void testEqualsWithSuperClassWithoutAnnotation() throws Exception { 18 | EmployeeX e = new EmployeeX(); 19 | e.setId(1); 20 | e.setName("Kiswani"); 21 | e.setEmpId(1000); 22 | EmployeeX e1 = new EmployeeX(); 23 | e1.setId(1); 24 | e1.setName("Kiswani123"); 25 | assertThat(ObjectUtils.isEqual(e, e1)).isEqualTo(false); 26 | e1.setId(-1); 27 | e1.setEmpId(1000); 28 | e1.setName("Kiswani"); 29 | assertThat(ObjectUtils.isEqual(e, e1)).isEqualTo(false); 30 | e1.setId(1); 31 | assertThat(ObjectUtils.isEqual(e, e1)).isEqualTo(true); 32 | e1.setName(null); 33 | e.setName(null); 34 | assertThat(ObjectUtils.isEqual(e, e1)).isEqualTo(true); 35 | } 36 | 37 | @Test 38 | public void testEqualsWithSuperClassByEqualsAnnotation() throws Exception { 39 | Employee e = new Employee(); 40 | e.setId(1); 41 | e.setName("Kiswani"); 42 | e.setEmpId(1000); 43 | Employee e1 = new Employee(); 44 | e1.setId(1); 45 | e1.setName("Kiswani123"); 46 | assertThat(ObjectUtils.isEqual(e, e1)).isEqualTo(true); 47 | } 48 | 49 | @Test 50 | public void testEqualsByEqualsAnnotation() throws Exception { 51 | Person e = new Person(); 52 | e.setId(1); 53 | e.setName("Kiswani"); 54 | Person e1 = new Person(); 55 | e1.setId(1); 56 | e1.setName("Kiswani123"); 57 | assertThat(ObjectUtils.isEqual(e, e1)).isEqualTo(true); 58 | Employee e2 = new Employee(); 59 | e2.setId(1); 60 | e2.setName("Kiswani123"); 61 | assertThat(ObjectUtils.isEqual(e, e2)).isEqualTo(false); 62 | Person e3 = new Employee(); 63 | e3.setId(1); 64 | e3.setName("Kiswani123"); 65 | assertThat(ObjectUtils.isEqual(e, e3)).isEqualTo(false); 66 | assertThat(ObjectUtils.isEqual(null, null)).isEqualTo(true); 67 | assertThat(ObjectUtils.isEqual(e, null)).isEqualTo(false); 68 | assertThat(ObjectUtils.isEqual(null, e)).isEqualTo(false); 69 | } 70 | 71 | @Test 72 | public void testEquals() throws Exception { 73 | assertThat(new EqualsHelper().doAction()).isEqualTo(false); 74 | assertThat(new EqualsHelper().doAction("String")).isEqualTo(false); 75 | assertThat(new EqualsHelper().doAction("String", null)).isEqualTo(false); 76 | assertThat(new EqualsHelper().doAction(null, "String")).isEqualTo(false); 77 | assertThat(new EqualsHelper().doAction("String", "String")).isEqualTo(true); 78 | assertThat(new EqualsHelper().doAction(1, 1)).isEqualTo(true); 79 | assertThat(new EqualsHelper().doAction(1, 2)).isEqualTo(false); 80 | assertThat(new EqualsHelper().doAction(new EmptyClass(), new EmptyClass())).isEqualTo(false); 81 | } 82 | 83 | @Test 84 | public void testEqualsWithSuperClassByIdAnnotation() throws Exception { 85 | EmployeeByIdAnnotation e = new EmployeeByIdAnnotation(); 86 | e.setId(1); 87 | e.setName("Kiswani"); 88 | e.setEmpId(1000); 89 | EmployeeByIdAnnotation e1 = new EmployeeByIdAnnotation(); 90 | e1.setId(1); 91 | e1.setName("Kiswani123"); 92 | assertThat(ObjectUtils.isEqual(e, e1)).isEqualTo(true); 93 | } 94 | 95 | @Test 96 | public void testEqualsByIdAnnotation() throws Exception { 97 | PersonByIdAnnotation e = new PersonByIdAnnotation(); 98 | e.setId(1); 99 | e.setName("Kiswani"); 100 | PersonByIdAnnotation e1 = new PersonByIdAnnotation(); 101 | e1.setId(1); 102 | e1.setName("Kiswani123"); 103 | assertThat(ObjectUtils.isEqual(e, e1)).isEqualTo(true); 104 | EmployeeByIdAnnotation e2 = new EmployeeByIdAnnotation(); 105 | e2.setId(1); 106 | e2.setName("Kiswani123"); 107 | assertThat(ObjectUtils.isEqual(e, e2)).isEqualTo(false); 108 | PersonByIdAnnotation e3 = new EmployeeByIdAnnotation(); 109 | e3.setId(1); 110 | e3.setName("Kiswani123"); 111 | assertThat(ObjectUtils.isEqual(e, e3)).isEqualTo(false); 112 | assertThat(ObjectUtils.isEqual(null, null)).isEqualTo(true); 113 | assertThat(ObjectUtils.isEqual(e, null)).isEqualTo(false); 114 | assertThat(ObjectUtils.isEqual(null, e)).isEqualTo(false); 115 | } 116 | 117 | 118 | @Test 119 | public void testHashcode() throws Exception { 120 | assertThat(ObjectUtils.toHashCode(null)).isEqualTo(-1); 121 | } 122 | 123 | @Test 124 | public void testPrimitiveToWrapper() throws Exception { 125 | try{ 126 | ObjectUtils.primitiveToWrapper(null); 127 | } catch (Exception e){ 128 | assertThat(e).isInstanceOf(IllegalParamException.class).hasMessage("Target Class cant be null"); 129 | } 130 | try{ 131 | ObjectUtils.primitiveToWrapper(Employee.class); 132 | } catch (Exception e){ 133 | assertThat(e).isInstanceOf(IllegalParamException.class).hasMessage("Employee is not primitive"); 134 | } 135 | assertThat(ObjectUtils.primitiveToWrapper(int.class)).isEqualTo(Integer.class); 136 | } 137 | 138 | private class EmptyClass { 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/lang/StringUtilsTest.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.lang; 2 | 3 | import io.github.rhkiswani.javaff.beans.EmployeeX; 4 | import io.github.rhkiswani.javaff.lang.utils.StringUtils; 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | 8 | import static org.assertj.core.api.Assertions.assertThat; 9 | 10 | public class StringUtilsTest { 11 | 12 | private EmployeeXWithArray employeeX = new EmployeeXWithArray(); 13 | 14 | @Before 15 | public void setUp(){ 16 | employeeX.setName("Kiswani"); 17 | employeeX.setEmpId(12); 18 | employeeX.setId(13); 19 | } 20 | 21 | @Test 22 | public void testToString() { 23 | assertThat(StringUtils.toString(null)).isNull(); 24 | assertThat(StringUtils.toString(employeeX)).isEqualTo("EmployeeXWithArray[empId=12, id=13, name=Kiswani]"); 25 | } 26 | 27 | @Test 28 | public void testToStringWithArrays() { 29 | employeeX.setAddresses(new String[]{"Address1", "Address2"}); 30 | assertThat(StringUtils.toString(employeeX)).isEqualTo("EmployeeXWithArray[addresses=[Address1,Address2], empId=12, id=13, name=Kiswani]"); 31 | } 32 | 33 | @Test 34 | public void testIsEmpty() { 35 | assertThat(StringUtils.isEmpty(null)).isEqualTo(true); 36 | assertThat(StringUtils.isEmpty("")).isEqualTo(true); 37 | assertThat(StringUtils.isEmpty("A")).isEqualTo(false); 38 | } 39 | 40 | @Test 41 | public void testIsNotEmpty() { 42 | assertThat(StringUtils.isNotEmpty(null)).isEqualTo(false); 43 | assertThat(StringUtils.isNotEmpty("")).isEqualTo(false); 44 | assertThat(StringUtils.isNotEmpty("A")).isEqualTo(true); 45 | } 46 | 47 | @Test 48 | public void testIsNull() { 49 | assertThat(StringUtils.isNull(null)).isEqualTo(true); 50 | assertThat(StringUtils.isNull("")).isEqualTo(true); 51 | assertThat(StringUtils.isNull("A")).isEqualTo(false); 52 | assertThat(StringUtils.isNull("Null")).isEqualTo(true); 53 | assertThat(StringUtils.isNull("NULL")).isEqualTo(true); 54 | assertThat(StringUtils.isNull("null")).isEqualTo(true); 55 | } 56 | 57 | @Test 58 | public void testIsNotNull() { 59 | assertThat(StringUtils.isNotNull(null)).isEqualTo(false); 60 | assertThat(StringUtils.isNotNull("")).isEqualTo(false); 61 | assertThat(StringUtils.isNotNull("A")).isEqualTo(true); 62 | assertThat(StringUtils.isNotNull("Null")).isEqualTo(false); 63 | assertThat(StringUtils.isNotNull("NULL")).isEqualTo(false); 64 | assertThat(StringUtils.isNotNull("null")).isEqualTo(false); 65 | } 66 | 67 | private static class EmployeeXWithArray extends EmployeeX{ 68 | private String[] addresses ; 69 | private Object[] unparsableArray ; 70 | 71 | public void setAddresses(String[] addresses) { 72 | this.addresses = addresses; 73 | } 74 | 75 | public void setUnparsableArray(Object[] unparsableArray) { 76 | this.unparsableArray = unparsableArray; 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/locale/LocaleTest.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.locale; 2 | 3 | import io.github.rhkiswani.javaff.exceptions.SmartException; 4 | import io.github.rhkiswani.javaff.locale.exceptions.LocaleException; 5 | import org.junit.Test; 6 | 7 | import java.util.Locale; 8 | 9 | import static org.assertj.core.api.Assertions.assertThat; 10 | public class LocaleTest { 11 | 12 | @Test 13 | public void testSetPath() throws Exception { 14 | DefaultLocaleWorker worker = new DefaultLocaleWorker(); 15 | worker.setPath("kiswani/new"); 16 | assertThat(worker.getPath()).isEqualTo("kiswani/new/"); 17 | worker.setPath("/"); 18 | assertThat(worker.getPath()).isEqualTo(""); 19 | worker.setPath("/kiswani/kiswani"); 20 | assertThat(worker.getPath()).isEqualTo("kiswani/kiswani/"); 21 | worker.setPath(null); 22 | assertThat(worker.getPath()).isEqualTo(""); 23 | } 24 | 25 | @Test 26 | public void testDefaultWorker() throws Exception { 27 | DefaultLocaleWorker worker = new DefaultLocaleWorker(); 28 | assertThat(worker.getPath()).isEqualTo(""); 29 | assertThat(worker.getName()).isEqualTo("messages"); 30 | assertThat(worker.getLocale()).isEqualTo(Locale.US); 31 | try{ 32 | assertThat(worker.getString(null, null)).isNull(); 33 | }catch (Throwable t) { 34 | assertThat(t).isInstanceOf(LocaleException.class).hasMessage("Cant find bundle for base name messages, locale en_US"); 35 | } 36 | worker.setPath("app"); 37 | assertThat(worker.getString(null, null)).isNull(); 38 | } 39 | 40 | @Test 41 | public void testLocaleUtil() throws Exception { 42 | assertThat(LocaleUtil.getString(SmartException.EXCEEDS_LIMIT, LocaleTest.class, new Object[]{"Array", 1000})).isEqualTo("Array MaxSize is 1,000"); 43 | assertThat(LocaleUtil.getString(SmartException.HTTP_ERROR, LocaleTest.class, new Object[]{"google.com"})).isEqualTo("failed to connect to google.com"); 44 | assertThat(LocaleUtil.getString("LOCALIZED_MSG", LocaleTest.class, new Object[]{"Kiswani"})).isEqualTo("this is localized msg from messages_en.properties thanks for Mr Kiswani"); 45 | assertThat(LocaleUtil.getString(null, LocaleTest.class, null)).isNull(); 46 | assertThat(LocaleUtil.getString("LOCALIZED_MSG", LocaleTest.class, null)).isEqualTo("this is localized msg from messages_en.properties thanks for Mr {0}"); 47 | } 48 | 49 | @Test 50 | public void testLocaleWorkerBuilder() throws Exception { 51 | LocaleWorker localeWorker = new LocaleWorkerBuilder().name("messages").path("/app").locale(Locale.CANADA).build(); 52 | assertThat(localeWorker).isInstanceOf(DefaultLocaleWorker.class); 53 | DefaultLocaleWorker defaultLocaleWorker = (DefaultLocaleWorker) localeWorker; 54 | assertThat(defaultLocaleWorker.getName()).isEqualTo("messages"); 55 | assertThat(defaultLocaleWorker.getPath()).isEqualTo("app/"); 56 | assertThat(defaultLocaleWorker.getLocale()).isEqualTo(Locale.CANADA); 57 | } 58 | 59 | @Test 60 | public void testLocaleWorkerBuilderException() throws Exception { 61 | try { 62 | new LocaleWorkerBuilder().name("Kiswani").path("/SS").locale(Locale.CANADA).build(); 63 | } catch (Exception e){ 64 | assertThat(e).isInstanceOf(LocaleException.class).hasMessage("Cant find bundle for base name SS/Kiswani, locale en_CA"); 65 | } 66 | } 67 | 68 | @Test 69 | public void testLocaleWorkerFactory() throws Exception { 70 | assertThat(LocaleWorkersFactory.instance() == LocaleWorkersFactory.instance()).isEqualTo(true); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/logging/DefaultLoggersTest.java: -------------------------------------------------------------------------------- 1 | 2 | package io.github.rhkiswani.javaff.logging; 3 | 4 | import io.github.rhkiswani.javaff.detector.ApiDetectorUtil; 5 | import io.github.rhkiswani.javaff.log.DefaultLog; 6 | import io.github.rhkiswani.javaff.log.LogFactory; 7 | import io.github.rhkiswani.javaff.log.LogWrapper; 8 | import io.github.rhkiswani.javaff.reflection.ReflectionHelper; 9 | import io.github.rhkiswani.javaff.reflection.ReflectionHelpersFactory; 10 | import org.junit.After; 11 | import org.junit.Before; 12 | import org.junit.Test; 13 | 14 | import static org.assertj.core.api.Assertions.assertThat; 15 | public class DefaultLoggersTest { 16 | private ReflectionHelper helper = ReflectionHelpersFactory.getReflectionHelper(DefaultLoggersTest.class); 17 | @Before 18 | public void setUp(){ 19 | helper.setStaticFieldValue(ApiDetectorUtil.class, "isSlf4jAvailable", Boolean.FALSE); 20 | } 21 | 22 | @Test 23 | public void testDefaultLogger(){ 24 | assertThat(LogFactory.getLogger(DefaultLoggersTest.class)).isInstanceOf(LogWrapper.class); 25 | assertThat(helper.getFieldValue(LogFactory.getLogger(DefaultLoggersTest.class), "log")).isInstanceOf(DefaultLog.class); 26 | //to fix coverage 27 | LogFactory.getLogger(DefaultLoggersTest.class).info(""); 28 | LogFactory.getLogger(DefaultLoggersTest.class).debug(""); 29 | LogFactory.getLogger(DefaultLoggersTest.class).warn(""); 30 | LogFactory.getLogger(DefaultLoggersTest.class).error(""); 31 | LogFactory.getLogger(DefaultLoggersTest.class).error("", new NullPointerException()); 32 | } 33 | 34 | @After 35 | public void afterTest(){ 36 | helper.setStaticFieldValue(ApiDetectorUtil.class, "isSlf4jAvailable", Boolean.TRUE); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/logging/Slf4jLoggersTest.java: -------------------------------------------------------------------------------- 1 | 2 | package io.github.rhkiswani.javaff.logging; 3 | 4 | import io.github.rhkiswani.javaff.log.Log; 5 | import io.github.rhkiswani.javaff.log.LogFactory; 6 | import org.junit.Before; 7 | import org.junit.Test; 8 | import uk.org.lidalia.slf4jext.Level; 9 | import uk.org.lidalia.slf4jtest.LoggingEvent; 10 | import uk.org.lidalia.slf4jtest.TestLogger; 11 | import uk.org.lidalia.slf4jtest.TestLoggerFactory; 12 | 13 | import static org.assertj.core.api.Assertions.assertThat; 14 | public class Slf4jLoggersTest { 15 | 16 | private Log logger = null; 17 | private TestLogger testLogger = null; 18 | 19 | @Before 20 | public void setUp(){ 21 | logger = LogFactory.getLogger(Slf4jLoggersTest.class); 22 | testLogger = TestLoggerFactory.getTestLogger(Slf4jLoggersTest.class); 23 | } 24 | @Test 25 | public void testInfoLog() { 26 | logger.info("{0}", "Hi"); 27 | testLog("Hi", Level.INFO); 28 | } 29 | 30 | @Test 31 | public void testDebugLog() { 32 | logger.debug("{0}", "Hi"); 33 | testLog("Hi", Level.DEBUG); 34 | } 35 | 36 | @Test 37 | public void testErrorLog() { 38 | logger.error("{0}", "Hi"); 39 | testLog("Hi", Level.ERROR); 40 | } 41 | 42 | @Test 43 | public void testErrorWithExceptionLog() { 44 | logger.error("{0}", new NullPointerException(), "Hi"); 45 | testLog("Hi", Level.ERROR); 46 | } 47 | 48 | @Test 49 | public void testWarnLog() { 50 | logger.warn("{0}", "Hi"); 51 | testLog("Hi", Level.WARN); 52 | } 53 | 54 | private void testLog(String msg, Level level) { 55 | assertThat(testLogger.getLoggingEvents().size()).isEqualTo(1); 56 | LoggingEvent[] objects = testLogger.getLoggingEvents().toArray(new LoggingEvent[testLogger.getLoggingEvents().size()]); 57 | assertThat(objects[0].getMessage()).isEqualTo(msg); 58 | assertThat(objects[0].getLevel()).isEqualTo(level); 59 | TestLoggerFactory.clear(); 60 | } 61 | 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/reflection/ReflectionTest.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.reflection; 2 | 3 | import io.github.rhkiswani.javaff.beans.EmployeeX; 4 | import io.github.rhkiswani.javaff.detector.ApiDetectorUtil; 5 | import io.github.rhkiswani.javaff.exceptions.SmartException; 6 | import io.github.rhkiswani.javaff.lang.exceptions.IllegalParamException; 7 | import io.github.rhkiswani.javaff.reflection.exception.ReflectionException; 8 | import org.junit.Before; 9 | import org.junit.Test; 10 | 11 | import static org.assertj.core.api.Assertions.assertThat; 12 | public class ReflectionTest { 13 | 14 | private ReflectionHelper reflectionHelper; 15 | 16 | @Before 17 | public void setUp(){ 18 | reflectionHelper = new DefaultReflectionHelper(); 19 | } 20 | 21 | @Test 22 | public void testFieldsByAnnotation() { 23 | assertThat(reflectionHelper.scanFieldsByAnnotation(null, null)).isNull(); 24 | assertThat(reflectionHelper.scanFieldsByAnnotation(Integer.class, null)).isNull(); 25 | assertThat(reflectionHelper.scanFieldsByAnnotation(Integer.class, null, null)).isNull(); 26 | assertThat(reflectionHelper.scanFieldsByAnnotation(null, Integer.class, null, null)).isNull(); 27 | } 28 | 29 | @Test 30 | public void testGetCallerClass() { 31 | new X().doX(); 32 | assertThat(Throwable.class.isInstance(new SmartException(""))).isEqualTo(true); 33 | try{ 34 | ReflectionUtil.getCallerClass(-1); 35 | }catch (Exception e){ 36 | assertThat(e).isInstanceOf(IllegalParamException.class).hasMessage("Number Of Levels should be greater or equal 0"); 37 | } 38 | try{ 39 | ReflectionUtil.getCallerClass(10000); 40 | }catch (Exception e){ 41 | assertThat(e).isInstanceOf(IllegalParamException.class).hasMessageContaining("StackTrace MaxSize is"); 42 | } 43 | } 44 | 45 | 46 | @Test 47 | public void testExceptions() { 48 | try { 49 | reflectionHelper.getField(ReflectionTest.class, "non_exist_field"); 50 | }catch (Exception e){ 51 | assertThat(e).isInstanceOf(ReflectionException.class).hasMessage("non_exist_field not found"); 52 | } 53 | try { 54 | reflectionHelper.getField(null, "non_exist_field"); 55 | }catch (Exception e){ 56 | assertThat(e).isInstanceOf(ReflectionException.class).hasMessage("target class cant be null"); 57 | } 58 | // these fields will be ignored because they are added by frameworks 59 | try { 60 | reflectionHelper.getField(X.class, "$jacocoData"); 61 | }catch (Exception e){ 62 | assertThat(e).isInstanceOf(ReflectionException.class).hasMessage("$jacocoData not found"); 63 | } 64 | try { 65 | reflectionHelper.getField(X.class, "__cobertura_counters"); 66 | }catch (Exception e){ 67 | assertThat(e).isInstanceOf(ReflectionException.class).hasMessage("__cobertura_counters not found"); 68 | } 69 | try { 70 | reflectionHelper.getField(X.class, "this$"); 71 | }catch (Exception e){ 72 | assertThat(e).isInstanceOf(ReflectionException.class).hasMessage("this$ not found"); 73 | } 74 | 75 | try { 76 | reflectionHelper.forName("this$"); 77 | }catch (Exception e){ 78 | assertThat(e).isInstanceOf(ReflectionException.class).hasMessage("java.lang.ClassNotFoundException: this$"); 79 | } 80 | try { 81 | reflectionHelper.getFields(null); 82 | }catch (Exception e){ 83 | assertThat(e).isInstanceOf(ReflectionException.class).hasMessage("Class cant be null"); 84 | } 85 | try { 86 | reflectionHelper.getFieldValue(null, ""); 87 | }catch (Exception e){ 88 | assertThat(e).isInstanceOf(ReflectionException.class).hasMessage("io.github.rhkiswani.javaff.reflection.exception.ReflectionException: Object cant be null"); 89 | } 90 | try { 91 | reflectionHelper.getFieldValue(new EmployeeX(), null); 92 | }catch (Exception e){ 93 | assertThat(e).isInstanceOf(ReflectionException.class).hasMessage("io.github.rhkiswani.javaff.reflection.exception.ReflectionException: Field Name cant be null"); 94 | } 95 | try { 96 | reflectionHelper.getFieldValue(new EmployeeX(), "kiswani"); 97 | }catch (Exception e){ 98 | assertThat(e).isInstanceOf(ReflectionException.class).hasMessage("io.github.rhkiswani.javaff.reflection.exception.ReflectionException: kiswani not found"); 99 | } 100 | assertThat(Throwable.class.isInstance(new SmartException(""))).isEqualTo(true); 101 | } 102 | 103 | @Test 104 | public void testSetStaticFinalVal() { 105 | reflectionHelper.setStaticFieldValue(ApiDetectorUtil.class, "isSlf4jAvailable", false); 106 | assertThat(ApiDetectorUtil.isSlf4jAvailable()).isEqualTo(false); 107 | reflectionHelper.setStaticFieldValue(ApiDetectorUtil.class, "isSlf4jAvailable", true); 108 | assertThat(ApiDetectorUtil.isSlf4jAvailable()).isEqualTo(true); 109 | try{ 110 | reflectionHelper.setStaticFieldValue(ApiDetectorUtil.class, "xxxx", false); 111 | }catch (Exception e){ 112 | assertThat(e).isInstanceOf(ReflectionException.class).hasMessage("xxxx not found"); 113 | } 114 | try{ 115 | ReflectionUtil.getCallerClass(-1); 116 | }catch (Exception e){ 117 | assertThat(e).isInstanceOf(IllegalParamException.class).hasMessage("Number Of Levels should be greater or equal 0"); 118 | } 119 | try{ 120 | ReflectionUtil.getCallerClass(10000); 121 | }catch (Exception e){ 122 | assertThat(e).isInstanceOf(IllegalParamException.class).hasMessageContaining("StackTrace MaxSize is"); 123 | } 124 | } 125 | 126 | @Test 127 | public void testIsPresent() { 128 | assertThat(ReflectionUtil.isPresent(Integer.class.getName())).isEqualTo(true); 129 | assertThat(ReflectionUtil.isPresent("com.xyz.xyz")).isEqualTo(false); 130 | } 131 | 132 | @Test 133 | public void testSetVal() { 134 | X x = new X(); 135 | reflectionHelper.setFieldValue(x, "privateStr", "Value"); 136 | assertThat(x.privateStr).isEqualTo("Value"); 137 | try{ 138 | reflectionHelper.setFieldValue(null, "privateStr", "Value"); 139 | }catch (Exception e){ 140 | assertThat(e).isInstanceOf(ReflectionException.class).hasMessage("target object cant be null"); 141 | } 142 | try{ 143 | reflectionHelper.setFieldValue(x, "privateStr", Integer.valueOf(1)); 144 | }catch (Exception e){ 145 | assertThat(e).isInstanceOf(ReflectionException.class).hasMessage("class java.lang.Integer is not fit to class java.lang.String"); 146 | } 147 | try{ 148 | reflectionHelper.setFieldValue(x, "privatePrimitive", null); 149 | }catch (Exception e){ 150 | assertThat(e).isInstanceOf(ReflectionException.class).hasMessage("java.lang.IllegalArgumentException: Can not set int field io.github.rhkiswani.javaff.reflection.ReflectionTest$X.privatePrimitive to null value"); 151 | } 152 | try{ 153 | ReflectionUtil.setFieldValue(x, "privatePrimitive", null); 154 | }catch (Exception e){ 155 | assertThat(e).isInstanceOf(ReflectionException.class).hasMessage("java.lang.IllegalArgumentException: Can not set int field io.github.rhkiswani.javaff.reflection.ReflectionTest$X.privatePrimitive to null value"); 156 | } 157 | ReflectionUtil.setFieldValue(x, "privatePrimitive", 1); 158 | assertThat(ReflectionUtil.getFieldValue(x, "privatePrimitive")).isEqualTo(1); 159 | 160 | try{ 161 | ReflectionUtil.setFieldValue(x, "privatePrimitive", new EmployeeX()); 162 | }catch (Exception e){ 163 | assertThat(e).isInstanceOf(ReflectionException.class).hasMessage("class io.github.rhkiswani.javaff.beans.EmployeeX is not fit to int"); 164 | } 165 | 166 | try{ 167 | ReflectionUtil.setStaticFieldValue(ApiDetectorUtil.class, "isJPAAvailable", new EmployeeX()); 168 | }catch (Exception e){ 169 | assertThat(e).isInstanceOf(ReflectionException.class).hasMessage("Can not set static java.lang.Boolean field io.github.rhkiswani.javaff.detector.ApiDetectorUtil.isJPAAvailable to io.github.rhkiswani.javaff.beans.EmployeeX"); 170 | } 171 | 172 | ReflectionUtil.setStaticFieldValue(ApiDetectorUtil.class, "isJPAAvailable", ApiDetectorUtil.isJPAAvailable()); 173 | } 174 | 175 | @Test 176 | public void testFactory() { 177 | assertThat(ReflectionHelpersFactory.instance() == ReflectionHelpersFactory.instance()).isEqualTo(true); 178 | } 179 | 180 | private class X { 181 | private Object $jacocoData; 182 | private Object __cobertura_counters; 183 | private Object this$; 184 | private String privateStr; 185 | private int privatePrimitive; 186 | public void doX(){ 187 | assertThat(ReflectionUtil.getCallerClass(1)).isEqualTo(ReflectionTest.class); 188 | } 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /src/test/java/io/github/rhkiswani/javaff/validation/ValidatorFactoryTest.java: -------------------------------------------------------------------------------- 1 | package io.github.rhkiswani.javaff.validation; 2 | 3 | import io.github.rhkiswani.javaff.exceptions.SmartException; 4 | import io.github.rhkiswani.javaff.lang.exceptions.IllegalParamException; 5 | import io.github.rhkiswani.javaff.reflection.ReflectionUtil; 6 | import io.github.rhkiswani.javaff.validation.exceptions.*; 7 | import io.github.rhkiswani.javaff.beans.EmployeeX; 8 | import org.junit.Test; 9 | 10 | import javax.validation.constraints.NotNull; 11 | import java.lang.reflect.Field; 12 | import java.lang.reflect.Method; 13 | import java.util.Arrays; 14 | import java.util.List; 15 | 16 | import static org.assertj.core.api.Assertions.assertThat; 17 | 18 | public class ValidatorFactoryTest { 19 | 20 | @Test 21 | // for coverage only , the actual implementation will be in JavaValidation 22 | public void testValidatorFactory() { 23 | assertThat(ValidatorFactory.instance() == ValidatorFactory.instance()).isEqualTo(true); 24 | ValidatorFactory.instance().add(EmployeeX.class, new Validator() { 25 | @Override 26 | public void validate(EmployeeX o) throws ValidationException { 27 | List fields = ReflectionUtil.getFields(EmployeeX.class); 28 | for (Field field : fields) { 29 | validateField(field, o); 30 | } 31 | } 32 | 33 | @Override 34 | public void validateList(List t) throws ValidationException { 35 | for (EmployeeX employeeX : t) { 36 | validate(employeeX); 37 | } 38 | } 39 | 40 | @Override 41 | public void validateField(Field field, EmployeeX o) throws ValidationException { 42 | if (field.isAnnotationPresent(NotNull.class) && ReflectionUtil.getFieldValue(o, field.getName()) == null ){ 43 | throw new IllegalParamException(SmartException.NULL_VAL, field.getName()); 44 | } 45 | } 46 | 47 | @Override 48 | public void validateMethod(Method method, EmployeeX o) throws ValidationException { 49 | throw new ValidationException(SmartException.NO_IMPLEMENTATION_FOUND); 50 | } 51 | }); 52 | 53 | Validator xValidator = ValidatorFactory.getValidator(EmployeeX.class); 54 | xValidator.validateList(Arrays.asList(new EmployeeX())); 55 | try { 56 | xValidator.validateMethod(null, null); 57 | } catch (Exception e){ 58 | 59 | } 60 | assertThat(xValidator).isNotNull(); 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /tools/deploy.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | function getVersion(){ 4 | mvn_version=$(mvn -q \ 5 | -Dexec.executable="echo" \ 6 | -Dexec.args='${project.version}' \ 7 | --non-recursive \ 8 | org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) 9 | 10 | if [[ $mvn_version == *"SNAPSHOT"* ]] 11 | then 12 | for str in $(echo "$mvn_version" | grep -o -e "[^-SNAPSHOT]*"); do 13 | version="$str"; 14 | done 15 | fi 16 | } 17 | 18 | function prepare(){ 19 | git checkout master 20 | git reset --hard 21 | git pull origin master 22 | getVersion 23 | } 24 | 25 | function release(){ 26 | mvn release:clean release:prepare -DperformRelease=true -B 27 | mvn release:perform 28 | git commit . -m"release $version" 29 | git push origin master 30 | } 31 | 32 | function postRelease(){ 33 | git checkout develop 34 | git reset --hard 35 | git pull origin develop 36 | git pull origin master 37 | git push origin develop 38 | } 39 | 40 | function main(){ 41 | prepare 42 | release 43 | postRelease 44 | } 45 | 46 | main 47 | 48 | -------------------------------------------------------------------------------- /tools/update_version.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | function getVersion(){ 4 | mvn_version=$(mvn -q \ 5 | -Dexec.executable="echo" \ 6 | -Dexec.args='${project.version}' \ 7 | --non-recursive \ 8 | org.codehaus.mojo:exec-maven-plugin:1.3.1:exec) 9 | 10 | if [[ $mvn_version == *"SNAPSHOT"* ]] 11 | then 12 | for str in $(echo "$mvn_version" | grep -o -e "[^-SNAPSHOT]*"); do 13 | version="$str"; 14 | done 15 | fi 16 | } 17 | 18 | function update(){ 19 | mvn release:update-versions -DperformRelease=true -B 20 | getVersion 21 | } 22 | 23 | function afterUpdate(){ 24 | git commit . -m"develop $version updated" 25 | git pull origin develop 26 | git push origin develop 27 | } 28 | 29 | function main(){ 30 | if [ "$TRAVIS_BRANCH" = "develop" ]; then 31 | update 32 | afterUpdate 33 | fi 34 | } 35 | 36 | main 37 | 38 | --------------------------------------------------------------------------------