repo_name stringlengths 7 104 | file_path stringlengths 13 198 | context stringlengths 67 7.15k | import_statement stringlengths 16 4.43k | code stringlengths 40 6.98k | prompt stringlengths 227 8.27k | next_line stringlengths 8 795 |
|---|---|---|---|---|---|---|
easyJsonApi/easyJsonApi | src/main/java/com/github/easyjsonapi/adapters/EasyJsonApiMachine.java | // Path: src/main/java/com/github/easyjsonapi/core/EasyJsonApiConfig.java
// public class EasyJsonApiConfig {
//
// private Map<EasyJsonApiTypeToken, List<Class<?>>> classesParsed = new HashMap<>();
//
// private String[] packagesSearched;
//
// /**
// * The default constructor
// */
// public EasyJsonApiConfig() {}
//
// /**
// * The constructor with packages attributes
// *
// * @param packages
// * the packages needs to be search and parsing
// * @throws EasyJsonApiInvalidPackageException
// */
// public EasyJsonApiConfig(String... packages) throws EasyJsonApiInvalidPackageException {
// setPackagesToSearch(packages);
// }
//
// /**
// * Get the array with all classes parsed
// *
// * @return the classesParsed the classes parsed
// */
// public Map<EasyJsonApiTypeToken, List<Class<?>>> getClassesParsed() {
// return classesParsed;
// }
//
// /**
// * Get the array with packages searched
// *
// * @return the packagesSearched the packages searched
// */
// public String[] getPackagesSearched() {
// return packagesSearched;
// }
//
// /**
// * Set the packages to search
// *
// * @param packages
// * the packages needs to be search and parsing
// * @throws EasyJsonApiInvalidPackageException
// */
// public void setPackagesToSearch(String... packages) throws EasyJsonApiInvalidPackageException {
//
// this.packagesSearched = packages;
//
// for (String packageToSearch : packages) {
// try {
// ClassPath classpath = ClassPath.from(getClass().getClassLoader());
//
// List<Class<?>> attrClasses = new ArrayList<>();
// List<Class<?>> metaClasses = new ArrayList<>();
// List<Class<?>> metaRelationshipsClasses = new ArrayList<>();
//
// for (ClassPath.ClassInfo classInfo : classpath.getTopLevelClasses(packageToSearch)) {
//
// Class<?> clazz = classInfo.load();
//
// if (Assert.notNull(clazz.getAnnotation(Attributes.class))) {
// attrClasses.add(clazz);
// } else if (Assert.notNull(clazz.getAnnotation(Meta.class))) {
// metaClasses.add(clazz);
// } else if (Assert.notNull(clazz.getAnnotation(MetaRelationship.class))) {
// metaRelationshipsClasses.add(clazz);
// }
// }
//
// this.classesParsed.put(EasyJsonApiTypeToken.TOKEN_ATTR, attrClasses);
// this.classesParsed.put(EasyJsonApiTypeToken.TOKEN_META, metaClasses);
// this.classesParsed.put(EasyJsonApiTypeToken.TOKEN_META_RELATIONSHIP, metaRelationshipsClasses);
//
// } catch (IOException ex) {
// throw new EasyJsonApiInvalidPackageException("Invalid packages inserted!", ex);
// }
// }
// }
//
// }
| import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.github.easyjsonapi.core.EasyJsonApiConfig;
import com.google.gson.reflect.TypeToken; | /*
* #%L
* EasyJsonApi
* %%
* Copyright (C) 2016 EasyJsonApi
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.github.easyjsonapi.adapters;
/**
* Abstract class with logic to decide which classes
* {@link EasyJsonApiDeserializer} and {@link EasyJsonApiSerializer} will use to
* create the json api structure, independently if you convert one json string
* to object or vice-versa
*
* @author Nuno Bento (nbento.neves@gmail.com)
*/
public abstract class EasyJsonApiMachine {
private Set<Class<?>> classesUsedInJson = new HashSet<>();
| // Path: src/main/java/com/github/easyjsonapi/core/EasyJsonApiConfig.java
// public class EasyJsonApiConfig {
//
// private Map<EasyJsonApiTypeToken, List<Class<?>>> classesParsed = new HashMap<>();
//
// private String[] packagesSearched;
//
// /**
// * The default constructor
// */
// public EasyJsonApiConfig() {}
//
// /**
// * The constructor with packages attributes
// *
// * @param packages
// * the packages needs to be search and parsing
// * @throws EasyJsonApiInvalidPackageException
// */
// public EasyJsonApiConfig(String... packages) throws EasyJsonApiInvalidPackageException {
// setPackagesToSearch(packages);
// }
//
// /**
// * Get the array with all classes parsed
// *
// * @return the classesParsed the classes parsed
// */
// public Map<EasyJsonApiTypeToken, List<Class<?>>> getClassesParsed() {
// return classesParsed;
// }
//
// /**
// * Get the array with packages searched
// *
// * @return the packagesSearched the packages searched
// */
// public String[] getPackagesSearched() {
// return packagesSearched;
// }
//
// /**
// * Set the packages to search
// *
// * @param packages
// * the packages needs to be search and parsing
// * @throws EasyJsonApiInvalidPackageException
// */
// public void setPackagesToSearch(String... packages) throws EasyJsonApiInvalidPackageException {
//
// this.packagesSearched = packages;
//
// for (String packageToSearch : packages) {
// try {
// ClassPath classpath = ClassPath.from(getClass().getClassLoader());
//
// List<Class<?>> attrClasses = new ArrayList<>();
// List<Class<?>> metaClasses = new ArrayList<>();
// List<Class<?>> metaRelationshipsClasses = new ArrayList<>();
//
// for (ClassPath.ClassInfo classInfo : classpath.getTopLevelClasses(packageToSearch)) {
//
// Class<?> clazz = classInfo.load();
//
// if (Assert.notNull(clazz.getAnnotation(Attributes.class))) {
// attrClasses.add(clazz);
// } else if (Assert.notNull(clazz.getAnnotation(Meta.class))) {
// metaClasses.add(clazz);
// } else if (Assert.notNull(clazz.getAnnotation(MetaRelationship.class))) {
// metaRelationshipsClasses.add(clazz);
// }
// }
//
// this.classesParsed.put(EasyJsonApiTypeToken.TOKEN_ATTR, attrClasses);
// this.classesParsed.put(EasyJsonApiTypeToken.TOKEN_META, metaClasses);
// this.classesParsed.put(EasyJsonApiTypeToken.TOKEN_META_RELATIONSHIP, metaRelationshipsClasses);
//
// } catch (IOException ex) {
// throw new EasyJsonApiInvalidPackageException("Invalid packages inserted!", ex);
// }
// }
// }
//
// }
// Path: src/main/java/com/github/easyjsonapi/adapters/EasyJsonApiMachine.java
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.github.easyjsonapi.core.EasyJsonApiConfig;
import com.google.gson.reflect.TypeToken;
/*
* #%L
* EasyJsonApi
* %%
* Copyright (C) 2016 EasyJsonApi
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.github.easyjsonapi.adapters;
/**
* Abstract class with logic to decide which classes
* {@link EasyJsonApiDeserializer} and {@link EasyJsonApiSerializer} will use to
* create the json api structure, independently if you convert one json string
* to object or vice-versa
*
* @author Nuno Bento (nbento.neves@gmail.com)
*/
public abstract class EasyJsonApiMachine {
private Set<Class<?>> classesUsedInJson = new HashSet<>();
| private EasyJsonApiConfig config; |
easyJsonApi/easyJsonApi | src/main/java/com/github/easyjsonapi/core/EasyJsonApiConfig.java | // Path: src/main/java/com/github/easyjsonapi/adapters/EasyJsonApiTypeToken.java
// public enum EasyJsonApiTypeToken {
//
// TOKEN_ATTR("TOKEN_ATTR"), TOKEN_DEFAULT("TOKEN_DEFAULT"), TOKEN_LINKS("TOKEN_LINKS"), TOKEN_META("TOKEN_META"), TOKEN_META_RELATIONSHIP(
// "TOKEN_META_RELATIONSHIP");
//
// private String key;
//
// private EasyJsonApiTypeToken(String key) {
// this.key = key;
// }
//
// /**
// * @return the key
// */
// public String getKey() {
// return key;
// }
//
// }
//
// Path: src/main/java/com/github/easyjsonapi/asserts/Assert.java
// public class Assert {
//
// /**
// * Check if string is null or empty
// *
// * @param value the string value
// * @return true if string is null or empty and false when occur the opposite
// */
// public static boolean isEmpty(String value) {
//
// if (value != null && !value.isEmpty()) {
// return false;
// }
// return true;
// }
//
// /**
// * Check if object is null
// *
// * @param value the object value
// * @return true if object is null and false when occur the opposite
// */
// public static boolean isNull(Object value) {
// if (value == null) {
// return true;
// }
//
// return false;
// }
//
// /**
// * Check if list of objects are null
// *
// * @param values the list with objects
// * @return true if list with objects are null and false when occur the
// * opposite
// */
// public static boolean isNull(Object... values) {
//
// boolean anyNotNullable = false;
//
// int index = 0;
//
// while (index < values.length && !anyNotNullable) {
// if (notNull(values[index])) {
// anyNotNullable = true;
// }
// index++;
// }
//
// return !anyNotNullable;
// }
//
// /**
// * Check if string is not null or empty
// *
// * @param value the string value
// * @return true if string has value and false when string is null or empty
// */
// public static boolean notEmpty(String value) {
// return !isEmpty(value);
// }
//
// /**
// * Check if object is null
// *
// * @param value the object value
// * @return true if object has value and false when object is null
// */
// public static boolean notNull(Object value) {
// return !isNull(value);
// }
//
// }
//
// Path: src/main/java/com/github/easyjsonapi/exceptions/EasyJsonApiInvalidPackageException.java
// public class EasyJsonApiInvalidPackageException extends EasyJsonApiException {
//
// /**
// * UID Generated
// */
// private static final long serialVersionUID = -1850836160599521183L;
//
// public EasyJsonApiInvalidPackageException(String message) {
// super(message);
// }
//
// public EasyJsonApiInvalidPackageException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
| import com.github.easyjsonapi.exceptions.EasyJsonApiInvalidPackageException;
import com.google.common.reflect.ClassPath;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.github.easyjsonapi.adapters.EasyJsonApiTypeToken;
import com.github.easyjsonapi.annotations.Attributes;
import com.github.easyjsonapi.annotations.Meta;
import com.github.easyjsonapi.annotations.MetaRelationship;
import com.github.easyjsonapi.asserts.Assert; | /*
* #%L
* EasyJsonApi
* %%
* Copyright (C) 2016 EasyJsonApi
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.github.easyjsonapi.core;
/**
* The EasyJsonApiConfig it is necessary to configure the {@link EasyJsonApi}.
* This class allows to parsing the packages defined into the
* {@link EasyJsonApiConfig#packagesSearched} inside the class
*
* @author Nuno Bento (nbento.neves@gmail.com)
* @version %I%, %G%
*/
public class EasyJsonApiConfig {
private Map<EasyJsonApiTypeToken, List<Class<?>>> classesParsed = new HashMap<>();
private String[] packagesSearched;
/**
* The default constructor
*/
public EasyJsonApiConfig() {}
/**
* The constructor with packages attributes
*
* @param packages
* the packages needs to be search and parsing
* @throws EasyJsonApiInvalidPackageException
*/ | // Path: src/main/java/com/github/easyjsonapi/adapters/EasyJsonApiTypeToken.java
// public enum EasyJsonApiTypeToken {
//
// TOKEN_ATTR("TOKEN_ATTR"), TOKEN_DEFAULT("TOKEN_DEFAULT"), TOKEN_LINKS("TOKEN_LINKS"), TOKEN_META("TOKEN_META"), TOKEN_META_RELATIONSHIP(
// "TOKEN_META_RELATIONSHIP");
//
// private String key;
//
// private EasyJsonApiTypeToken(String key) {
// this.key = key;
// }
//
// /**
// * @return the key
// */
// public String getKey() {
// return key;
// }
//
// }
//
// Path: src/main/java/com/github/easyjsonapi/asserts/Assert.java
// public class Assert {
//
// /**
// * Check if string is null or empty
// *
// * @param value the string value
// * @return true if string is null or empty and false when occur the opposite
// */
// public static boolean isEmpty(String value) {
//
// if (value != null && !value.isEmpty()) {
// return false;
// }
// return true;
// }
//
// /**
// * Check if object is null
// *
// * @param value the object value
// * @return true if object is null and false when occur the opposite
// */
// public static boolean isNull(Object value) {
// if (value == null) {
// return true;
// }
//
// return false;
// }
//
// /**
// * Check if list of objects are null
// *
// * @param values the list with objects
// * @return true if list with objects are null and false when occur the
// * opposite
// */
// public static boolean isNull(Object... values) {
//
// boolean anyNotNullable = false;
//
// int index = 0;
//
// while (index < values.length && !anyNotNullable) {
// if (notNull(values[index])) {
// anyNotNullable = true;
// }
// index++;
// }
//
// return !anyNotNullable;
// }
//
// /**
// * Check if string is not null or empty
// *
// * @param value the string value
// * @return true if string has value and false when string is null or empty
// */
// public static boolean notEmpty(String value) {
// return !isEmpty(value);
// }
//
// /**
// * Check if object is null
// *
// * @param value the object value
// * @return true if object has value and false when object is null
// */
// public static boolean notNull(Object value) {
// return !isNull(value);
// }
//
// }
//
// Path: src/main/java/com/github/easyjsonapi/exceptions/EasyJsonApiInvalidPackageException.java
// public class EasyJsonApiInvalidPackageException extends EasyJsonApiException {
//
// /**
// * UID Generated
// */
// private static final long serialVersionUID = -1850836160599521183L;
//
// public EasyJsonApiInvalidPackageException(String message) {
// super(message);
// }
//
// public EasyJsonApiInvalidPackageException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
// Path: src/main/java/com/github/easyjsonapi/core/EasyJsonApiConfig.java
import com.github.easyjsonapi.exceptions.EasyJsonApiInvalidPackageException;
import com.google.common.reflect.ClassPath;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.github.easyjsonapi.adapters.EasyJsonApiTypeToken;
import com.github.easyjsonapi.annotations.Attributes;
import com.github.easyjsonapi.annotations.Meta;
import com.github.easyjsonapi.annotations.MetaRelationship;
import com.github.easyjsonapi.asserts.Assert;
/*
* #%L
* EasyJsonApi
* %%
* Copyright (C) 2016 EasyJsonApi
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.github.easyjsonapi.core;
/**
* The EasyJsonApiConfig it is necessary to configure the {@link EasyJsonApi}.
* This class allows to parsing the packages defined into the
* {@link EasyJsonApiConfig#packagesSearched} inside the class
*
* @author Nuno Bento (nbento.neves@gmail.com)
* @version %I%, %G%
*/
public class EasyJsonApiConfig {
private Map<EasyJsonApiTypeToken, List<Class<?>>> classesParsed = new HashMap<>();
private String[] packagesSearched;
/**
* The default constructor
*/
public EasyJsonApiConfig() {}
/**
* The constructor with packages attributes
*
* @param packages
* the packages needs to be search and parsing
* @throws EasyJsonApiInvalidPackageException
*/ | public EasyJsonApiConfig(String... packages) throws EasyJsonApiInvalidPackageException { |
easyJsonApi/easyJsonApi | src/test/java/com/github/easyjsonapi/tools/JsonToolsTest.java | // Path: src/main/java/com/github/easyjsonapi/exceptions/EasyJsonApiRuntimeException.java
// public class EasyJsonApiRuntimeException extends RuntimeException {
//
// /**
// * UID Generated
// */
// private static final long serialVersionUID = 6382099926165220367L;
//
// public EasyJsonApiRuntimeException(String message) {
// super(message);
// }
//
// public EasyJsonApiRuntimeException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/github/easyjsonapi/tools/JsonTools.java
// public class JsonTools {
//
// /**
// * Get string inside json
// *
// * @param name
// * the name of attribute
// * @param json
// * the json object
// * @return string with json object value
// */
// public static String getStringInsideJson(String name, JsonObject json) {
//
// if (Assert.isNull(json.get(name))) {
// return null;
// }
//
// return json.get(name).getAsString();
//
// }
//
// /**
// * Put json object inside the json structure submitted
// *
// * @param jsonObj
// * the concat json structure
// * @param name
// * the name of json attribute
// * @param objectInsert
// * the json object needs to insert inside json structure, you must choose two types:
// * String or JsonElement otherwise you will get {@link EasyJsonApiRuntimeException} exception.
// */
// public static void insertObject(JsonObject jsonObj, String name, Object objectInsert) {
//
// if (Assert.notNull(jsonObj)) {
// if (Assert.notNull(objectInsert)) {
// if (objectInsert instanceof String) {
// if (Assert.notEmpty((String) objectInsert)) {
// jsonObj.addProperty(name, (String) objectInsert);
// }
// } else if (objectInsert instanceof JsonElement) {
// jsonObj.add(name, (JsonElement) objectInsert);
// } else {
// throw new EasyJsonApiRuntimeException("Invalid object inserted!");
// }
// }
// }
//
// }
//
// }
| import org.junit.Assert;
import org.junit.Test;
import com.github.easyjsonapi.exceptions.EasyJsonApiRuntimeException;
import com.github.easyjsonapi.tools.JsonTools;
import com.google.gson.JsonObject; | /*
* #%L
* EasyJsonApi
* %%
* Copyright (C) 2016 EasyJsonApi
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.github.easyjsonapi.tools;
public class JsonToolsTest {
@Test
public void getStringInsideJsonTest() {
JsonObject objTest = new JsonObject();
objTest.addProperty("Type", "Books");
objTest.addProperty("Car", "Mercedes");
| // Path: src/main/java/com/github/easyjsonapi/exceptions/EasyJsonApiRuntimeException.java
// public class EasyJsonApiRuntimeException extends RuntimeException {
//
// /**
// * UID Generated
// */
// private static final long serialVersionUID = 6382099926165220367L;
//
// public EasyJsonApiRuntimeException(String message) {
// super(message);
// }
//
// public EasyJsonApiRuntimeException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/github/easyjsonapi/tools/JsonTools.java
// public class JsonTools {
//
// /**
// * Get string inside json
// *
// * @param name
// * the name of attribute
// * @param json
// * the json object
// * @return string with json object value
// */
// public static String getStringInsideJson(String name, JsonObject json) {
//
// if (Assert.isNull(json.get(name))) {
// return null;
// }
//
// return json.get(name).getAsString();
//
// }
//
// /**
// * Put json object inside the json structure submitted
// *
// * @param jsonObj
// * the concat json structure
// * @param name
// * the name of json attribute
// * @param objectInsert
// * the json object needs to insert inside json structure, you must choose two types:
// * String or JsonElement otherwise you will get {@link EasyJsonApiRuntimeException} exception.
// */
// public static void insertObject(JsonObject jsonObj, String name, Object objectInsert) {
//
// if (Assert.notNull(jsonObj)) {
// if (Assert.notNull(objectInsert)) {
// if (objectInsert instanceof String) {
// if (Assert.notEmpty((String) objectInsert)) {
// jsonObj.addProperty(name, (String) objectInsert);
// }
// } else if (objectInsert instanceof JsonElement) {
// jsonObj.add(name, (JsonElement) objectInsert);
// } else {
// throw new EasyJsonApiRuntimeException("Invalid object inserted!");
// }
// }
// }
//
// }
//
// }
// Path: src/test/java/com/github/easyjsonapi/tools/JsonToolsTest.java
import org.junit.Assert;
import org.junit.Test;
import com.github.easyjsonapi.exceptions.EasyJsonApiRuntimeException;
import com.github.easyjsonapi.tools.JsonTools;
import com.google.gson.JsonObject;
/*
* #%L
* EasyJsonApi
* %%
* Copyright (C) 2016 EasyJsonApi
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.github.easyjsonapi.tools;
public class JsonToolsTest {
@Test
public void getStringInsideJsonTest() {
JsonObject objTest = new JsonObject();
objTest.addProperty("Type", "Books");
objTest.addProperty("Car", "Mercedes");
| String mercedes = JsonTools.getStringInsideJson("Car", objTest); |
easyJsonApi/easyJsonApi | src/test/java/com/github/easyjsonapi/tools/JsonToolsTest.java | // Path: src/main/java/com/github/easyjsonapi/exceptions/EasyJsonApiRuntimeException.java
// public class EasyJsonApiRuntimeException extends RuntimeException {
//
// /**
// * UID Generated
// */
// private static final long serialVersionUID = 6382099926165220367L;
//
// public EasyJsonApiRuntimeException(String message) {
// super(message);
// }
//
// public EasyJsonApiRuntimeException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/github/easyjsonapi/tools/JsonTools.java
// public class JsonTools {
//
// /**
// * Get string inside json
// *
// * @param name
// * the name of attribute
// * @param json
// * the json object
// * @return string with json object value
// */
// public static String getStringInsideJson(String name, JsonObject json) {
//
// if (Assert.isNull(json.get(name))) {
// return null;
// }
//
// return json.get(name).getAsString();
//
// }
//
// /**
// * Put json object inside the json structure submitted
// *
// * @param jsonObj
// * the concat json structure
// * @param name
// * the name of json attribute
// * @param objectInsert
// * the json object needs to insert inside json structure, you must choose two types:
// * String or JsonElement otherwise you will get {@link EasyJsonApiRuntimeException} exception.
// */
// public static void insertObject(JsonObject jsonObj, String name, Object objectInsert) {
//
// if (Assert.notNull(jsonObj)) {
// if (Assert.notNull(objectInsert)) {
// if (objectInsert instanceof String) {
// if (Assert.notEmpty((String) objectInsert)) {
// jsonObj.addProperty(name, (String) objectInsert);
// }
// } else if (objectInsert instanceof JsonElement) {
// jsonObj.add(name, (JsonElement) objectInsert);
// } else {
// throw new EasyJsonApiRuntimeException("Invalid object inserted!");
// }
// }
// }
//
// }
//
// }
| import org.junit.Assert;
import org.junit.Test;
import com.github.easyjsonapi.exceptions.EasyJsonApiRuntimeException;
import com.github.easyjsonapi.tools.JsonTools;
import com.google.gson.JsonObject; | /*
* #%L
* EasyJsonApi
* %%
* Copyright (C) 2016 EasyJsonApi
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.github.easyjsonapi.tools;
public class JsonToolsTest {
@Test
public void getStringInsideJsonTest() {
JsonObject objTest = new JsonObject();
objTest.addProperty("Type", "Books");
objTest.addProperty("Car", "Mercedes");
String mercedes = JsonTools.getStringInsideJson("Car", objTest);
Assert.assertEquals(mercedes, "Mercedes");
Assert.assertNull(JsonTools.getStringInsideJson("", objTest));
Assert.assertNull(JsonTools.getStringInsideJson("InvalidTest", objTest));
}
| // Path: src/main/java/com/github/easyjsonapi/exceptions/EasyJsonApiRuntimeException.java
// public class EasyJsonApiRuntimeException extends RuntimeException {
//
// /**
// * UID Generated
// */
// private static final long serialVersionUID = 6382099926165220367L;
//
// public EasyJsonApiRuntimeException(String message) {
// super(message);
// }
//
// public EasyJsonApiRuntimeException(String message, Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/github/easyjsonapi/tools/JsonTools.java
// public class JsonTools {
//
// /**
// * Get string inside json
// *
// * @param name
// * the name of attribute
// * @param json
// * the json object
// * @return string with json object value
// */
// public static String getStringInsideJson(String name, JsonObject json) {
//
// if (Assert.isNull(json.get(name))) {
// return null;
// }
//
// return json.get(name).getAsString();
//
// }
//
// /**
// * Put json object inside the json structure submitted
// *
// * @param jsonObj
// * the concat json structure
// * @param name
// * the name of json attribute
// * @param objectInsert
// * the json object needs to insert inside json structure, you must choose two types:
// * String or JsonElement otherwise you will get {@link EasyJsonApiRuntimeException} exception.
// */
// public static void insertObject(JsonObject jsonObj, String name, Object objectInsert) {
//
// if (Assert.notNull(jsonObj)) {
// if (Assert.notNull(objectInsert)) {
// if (objectInsert instanceof String) {
// if (Assert.notEmpty((String) objectInsert)) {
// jsonObj.addProperty(name, (String) objectInsert);
// }
// } else if (objectInsert instanceof JsonElement) {
// jsonObj.add(name, (JsonElement) objectInsert);
// } else {
// throw new EasyJsonApiRuntimeException("Invalid object inserted!");
// }
// }
// }
//
// }
//
// }
// Path: src/test/java/com/github/easyjsonapi/tools/JsonToolsTest.java
import org.junit.Assert;
import org.junit.Test;
import com.github.easyjsonapi.exceptions.EasyJsonApiRuntimeException;
import com.github.easyjsonapi.tools.JsonTools;
import com.google.gson.JsonObject;
/*
* #%L
* EasyJsonApi
* %%
* Copyright (C) 2016 EasyJsonApi
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.github.easyjsonapi.tools;
public class JsonToolsTest {
@Test
public void getStringInsideJsonTest() {
JsonObject objTest = new JsonObject();
objTest.addProperty("Type", "Books");
objTest.addProperty("Car", "Mercedes");
String mercedes = JsonTools.getStringInsideJson("Car", objTest);
Assert.assertEquals(mercedes, "Mercedes");
Assert.assertNull(JsonTools.getStringInsideJson("", objTest));
Assert.assertNull(JsonTools.getStringInsideJson("InvalidTest", objTest));
}
| @Test(expected = EasyJsonApiRuntimeException.class) |
CommonsLab/CommonsLab | app/src/main/java/com/commonslab/commonslab/Activities/SplashScreenActivity.java | // Path: app/src/main/java/com/commonslab/commonslab/Utils/SharedPreferencesUtils/StorageUtil.java
// public class StorageUtil {
// private SharedPreferences preferences;
// private Context context;
//
// public StorageUtil(Context context) {
// this.context = context;
// }
//
//
// public void storeUserCredentials(String username) {
// //Store user credentials in SharedPreferences
// preferences = context.getSharedPreferences(context.getString(R.string.User_Credentials), Context.MODE_PRIVATE);
// preferences.edit().putString("username", username).apply();
// preferences.edit().putBoolean("loggedIn", true).apply();
// }
//
// public boolean validUserSession() {
// preferences = context.getSharedPreferences(context.getString(R.string.User_Credentials), Context.MODE_PRIVATE);
// String username = preferences.getString("username", null);
// boolean loggedIn = preferences.getBoolean("loggedIn", false);
// return (username != null && loggedIn);
// }
//
// public String loadUserCredentials() {
// preferences = context.getSharedPreferences(context.getString(R.string.User_Credentials), Context.MODE_PRIVATE);
// return preferences.getString("username", null);
// }
//
// public void clearUserSession() {
// preferences = context.getSharedPreferences(context.getString(R.string.User_Credentials), Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = preferences.edit();
// editor.clear();
// editor.apply();
// }
//
//
// public void storeUserContributions(ArrayList<Contribution> contributions) {
// preferences = context.getSharedPreferences(context.getString(R.string.User_Contributions), Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = preferences.edit();
//
// //clear existing data
// editor.clear();
// editor.apply();
//
// if (contributions == null || contributions.size() == 0) {
// //No contributions yet
// editor.putString("Contributions", "");
// editor.apply();
// } else {
// Gson gson = new Gson();
// String json = gson.toJson(contributions);
// //Store contributions
// editor.putString("Contributions", json);
// editor.apply();
// }
// }
//
// public void setUserContributionsStatus(boolean status) {
// preferences = context.getSharedPreferences(context.getString(R.string.User_Contributions), Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = preferences.edit();
// editor.putBoolean("ContributionsAvailable", status);
// editor.apply();
// }
//
// public boolean usersContributionsAvailable() {
// preferences = context.getSharedPreferences(context.getString(R.string.User_Contributions), Context.MODE_PRIVATE);
// return preferences.getBoolean("ContributionsAvailable", false);
// }
//
// public ArrayList<Contribution> retrieveUserContributions() {
// preferences = context.getSharedPreferences(context.getString(R.string.User_Contributions), Context.MODE_PRIVATE);
// String contributions;
// //Check if contributions are previously stored
// if ((contributions = preferences.getString("Contributions", null)) == null) return null;
// if (contributions.equals("")) return null;//no uploads from this user
//
// Gson gson = new Gson();
// Type type = new TypeToken<ArrayList<Contribution>>() {
// }.getType();
// return gson.fromJson(contributions, type);
// }
//
//
// //Store RSS feed, Picture and Media of the day
// public void storeRSS_Feed(ArrayList<FeedItem> list, MediaType mediaType) {
// if (mediaType == MediaType.PICTURE) {
// preferences = context.getSharedPreferences(context.getString(R.string.Picture_of_the_day), Context.MODE_PRIVATE);
// } else {
// preferences = context.getSharedPreferences(context.getString(R.string.Media_of_the_day), Context.MODE_PRIVATE);
// }
// SharedPreferences.Editor prefsEditor = preferences.edit();
// Gson gson = new Gson();
// String json = gson.toJson(list);
// //Store date of this RSS feed
// prefsEditor.putString("Date", new Today().date());
// prefsEditor.putString("RSS_Feed", json);
// prefsEditor.apply();
// }
//
// //Retrieve RSS feed, Picture and Media of the day
// public ArrayList<FeedItem> retrieveRSS_Feed(MediaType mediaType) {
// if (mediaType == MediaType.PICTURE) {
// preferences = context.getSharedPreferences(context.getString(R.string.Picture_of_the_day), Context.MODE_PRIVATE);
// } else {
// preferences = context.getSharedPreferences(context.getString(R.string.Media_of_the_day), Context.MODE_PRIVATE);
// }
//
// //Check if the feed is valid
// if (!preferences.getString("Date", "").equals(new Today().date())) return null;
//
// Gson gson = new Gson();
// String json = preferences.getString("RSS_Feed", null);
// Type type = new TypeToken<ArrayList<FeedItem>>() {
// }.getType();
// return gson.fromJson(json, type);
// }
//
// }
| import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import com.commonslab.commonslab.R;
import com.commonslab.commonslab.Utils.SharedPreferencesUtils.StorageUtil; | @Override
public void run() {
dismissSplash();
}
};
// click to dismiss the splash screen prematurely
View rootView = findViewById(android.R.id.content);
rootView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismissSplash();
}
});
}
@Override
protected void onResume() {
super.onResume();
handler.postDelayed(runnable, SPLASH_DURATION);
}
@Override
protected void onPause() {
super.onPause();
handler.removeCallbacks(runnable);
}
private void dismissSplash() { | // Path: app/src/main/java/com/commonslab/commonslab/Utils/SharedPreferencesUtils/StorageUtil.java
// public class StorageUtil {
// private SharedPreferences preferences;
// private Context context;
//
// public StorageUtil(Context context) {
// this.context = context;
// }
//
//
// public void storeUserCredentials(String username) {
// //Store user credentials in SharedPreferences
// preferences = context.getSharedPreferences(context.getString(R.string.User_Credentials), Context.MODE_PRIVATE);
// preferences.edit().putString("username", username).apply();
// preferences.edit().putBoolean("loggedIn", true).apply();
// }
//
// public boolean validUserSession() {
// preferences = context.getSharedPreferences(context.getString(R.string.User_Credentials), Context.MODE_PRIVATE);
// String username = preferences.getString("username", null);
// boolean loggedIn = preferences.getBoolean("loggedIn", false);
// return (username != null && loggedIn);
// }
//
// public String loadUserCredentials() {
// preferences = context.getSharedPreferences(context.getString(R.string.User_Credentials), Context.MODE_PRIVATE);
// return preferences.getString("username", null);
// }
//
// public void clearUserSession() {
// preferences = context.getSharedPreferences(context.getString(R.string.User_Credentials), Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = preferences.edit();
// editor.clear();
// editor.apply();
// }
//
//
// public void storeUserContributions(ArrayList<Contribution> contributions) {
// preferences = context.getSharedPreferences(context.getString(R.string.User_Contributions), Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = preferences.edit();
//
// //clear existing data
// editor.clear();
// editor.apply();
//
// if (contributions == null || contributions.size() == 0) {
// //No contributions yet
// editor.putString("Contributions", "");
// editor.apply();
// } else {
// Gson gson = new Gson();
// String json = gson.toJson(contributions);
// //Store contributions
// editor.putString("Contributions", json);
// editor.apply();
// }
// }
//
// public void setUserContributionsStatus(boolean status) {
// preferences = context.getSharedPreferences(context.getString(R.string.User_Contributions), Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = preferences.edit();
// editor.putBoolean("ContributionsAvailable", status);
// editor.apply();
// }
//
// public boolean usersContributionsAvailable() {
// preferences = context.getSharedPreferences(context.getString(R.string.User_Contributions), Context.MODE_PRIVATE);
// return preferences.getBoolean("ContributionsAvailable", false);
// }
//
// public ArrayList<Contribution> retrieveUserContributions() {
// preferences = context.getSharedPreferences(context.getString(R.string.User_Contributions), Context.MODE_PRIVATE);
// String contributions;
// //Check if contributions are previously stored
// if ((contributions = preferences.getString("Contributions", null)) == null) return null;
// if (contributions.equals("")) return null;//no uploads from this user
//
// Gson gson = new Gson();
// Type type = new TypeToken<ArrayList<Contribution>>() {
// }.getType();
// return gson.fromJson(contributions, type);
// }
//
//
// //Store RSS feed, Picture and Media of the day
// public void storeRSS_Feed(ArrayList<FeedItem> list, MediaType mediaType) {
// if (mediaType == MediaType.PICTURE) {
// preferences = context.getSharedPreferences(context.getString(R.string.Picture_of_the_day), Context.MODE_PRIVATE);
// } else {
// preferences = context.getSharedPreferences(context.getString(R.string.Media_of_the_day), Context.MODE_PRIVATE);
// }
// SharedPreferences.Editor prefsEditor = preferences.edit();
// Gson gson = new Gson();
// String json = gson.toJson(list);
// //Store date of this RSS feed
// prefsEditor.putString("Date", new Today().date());
// prefsEditor.putString("RSS_Feed", json);
// prefsEditor.apply();
// }
//
// //Retrieve RSS feed, Picture and Media of the day
// public ArrayList<FeedItem> retrieveRSS_Feed(MediaType mediaType) {
// if (mediaType == MediaType.PICTURE) {
// preferences = context.getSharedPreferences(context.getString(R.string.Picture_of_the_day), Context.MODE_PRIVATE);
// } else {
// preferences = context.getSharedPreferences(context.getString(R.string.Media_of_the_day), Context.MODE_PRIVATE);
// }
//
// //Check if the feed is valid
// if (!preferences.getString("Date", "").equals(new Today().date())) return null;
//
// Gson gson = new Gson();
// String json = preferences.getString("RSS_Feed", null);
// Type type = new TypeToken<ArrayList<FeedItem>>() {
// }.getType();
// return gson.fromJson(json, type);
// }
//
// }
// Path: app/src/main/java/com/commonslab/commonslab/Activities/SplashScreenActivity.java
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import com.commonslab.commonslab.R;
import com.commonslab.commonslab.Utils.SharedPreferencesUtils.StorageUtil;
@Override
public void run() {
dismissSplash();
}
};
// click to dismiss the splash screen prematurely
View rootView = findViewById(android.R.id.content);
rootView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismissSplash();
}
});
}
@Override
protected void onResume() {
super.onResume();
handler.postDelayed(runnable, SPLASH_DURATION);
}
@Override
protected void onPause() {
super.onPause();
handler.removeCallbacks(runnable);
}
private void dismissSplash() { | if (new StorageUtil(getApplicationContext()).validUserSession()) { |
CommonsLab/CommonsLab | app/src/main/java/com/commonslab/commonslab/AudioPlayer/OpusPlayer.java | // Path: app/src/main/java/com/commonslab/commonslab/Activities/MainActivity.java
// public static final String PAUSE_OPUS = "org.wikimedia.commons.wikimedia.PAUSE_OPUS";
//
// Path: app/src/main/java/com/commonslab/commonslab/Activities/MainActivity.java
// public static final String PLAY_OPUS = "org.wikimedia.commons.wikimedia.PLAY_OPUS";
//
// Path: app/src/main/java/com/commonslab/commonslab/Activities/MainActivity.java
// public static final String SEEKBAR_UPDATE_OPUS = "org.wikimedia.commons.wikimedia.SEEKBAR_UPDATE_OPUS";
//
// Path: app/src/main/java/com/commonslab/commonslab/Activities/MainActivity.java
// public static final String STOP_OPUS = "org.wikimedia.commons.wikimedia.STOP_OPUS";
| import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import com.audionowdigital.android.openplayer.Player;
import com.audionowdigital.android.openplayer.PlayerEvents;
import com.commonslab.commonslab.R;
import static com.commonslab.commonslab.Activities.MainActivity.PAUSE_OPUS;
import static com.commonslab.commonslab.Activities.MainActivity.PLAY_OPUS;
import static com.commonslab.commonslab.Activities.MainActivity.SEEKBAR_UPDATE_OPUS;
import static com.commonslab.commonslab.Activities.MainActivity.STOP_OPUS; | package com.commonslab.commonslab.AudioPlayer;
/**
* Created by Valdio Veliu on 25/03/2017.
*/
public class OpusPlayer {
Intent broadcastIntent = new Intent(STOP_OPUS);
private Player player;
// Playback handler for callbacks
private Handler playbackHandler;
private int LENGTH = 0;
private Player.DecoderType type = Player.DecoderType.OPUS;
private String TAG = "OPUS_MEDIA";
private String mediaURL;
private Context context; | // Path: app/src/main/java/com/commonslab/commonslab/Activities/MainActivity.java
// public static final String PAUSE_OPUS = "org.wikimedia.commons.wikimedia.PAUSE_OPUS";
//
// Path: app/src/main/java/com/commonslab/commonslab/Activities/MainActivity.java
// public static final String PLAY_OPUS = "org.wikimedia.commons.wikimedia.PLAY_OPUS";
//
// Path: app/src/main/java/com/commonslab/commonslab/Activities/MainActivity.java
// public static final String SEEKBAR_UPDATE_OPUS = "org.wikimedia.commons.wikimedia.SEEKBAR_UPDATE_OPUS";
//
// Path: app/src/main/java/com/commonslab/commonslab/Activities/MainActivity.java
// public static final String STOP_OPUS = "org.wikimedia.commons.wikimedia.STOP_OPUS";
// Path: app/src/main/java/com/commonslab/commonslab/AudioPlayer/OpusPlayer.java
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import com.audionowdigital.android.openplayer.Player;
import com.audionowdigital.android.openplayer.PlayerEvents;
import com.commonslab.commonslab.R;
import static com.commonslab.commonslab.Activities.MainActivity.PAUSE_OPUS;
import static com.commonslab.commonslab.Activities.MainActivity.PLAY_OPUS;
import static com.commonslab.commonslab.Activities.MainActivity.SEEKBAR_UPDATE_OPUS;
import static com.commonslab.commonslab.Activities.MainActivity.STOP_OPUS;
package com.commonslab.commonslab.AudioPlayer;
/**
* Created by Valdio Veliu on 25/03/2017.
*/
public class OpusPlayer {
Intent broadcastIntent = new Intent(STOP_OPUS);
private Player player;
// Playback handler for callbacks
private Handler playbackHandler;
private int LENGTH = 0;
private Player.DecoderType type = Player.DecoderType.OPUS;
private String TAG = "OPUS_MEDIA";
private String mediaURL;
private Context context; | private Intent seekBarIntent = new Intent(SEEKBAR_UPDATE_OPUS); |
CommonsLab/CommonsLab | app/src/main/java/com/commonslab/commonslab/AudioPlayer/OpusPlayer.java | // Path: app/src/main/java/com/commonslab/commonslab/Activities/MainActivity.java
// public static final String PAUSE_OPUS = "org.wikimedia.commons.wikimedia.PAUSE_OPUS";
//
// Path: app/src/main/java/com/commonslab/commonslab/Activities/MainActivity.java
// public static final String PLAY_OPUS = "org.wikimedia.commons.wikimedia.PLAY_OPUS";
//
// Path: app/src/main/java/com/commonslab/commonslab/Activities/MainActivity.java
// public static final String SEEKBAR_UPDATE_OPUS = "org.wikimedia.commons.wikimedia.SEEKBAR_UPDATE_OPUS";
//
// Path: app/src/main/java/com/commonslab/commonslab/Activities/MainActivity.java
// public static final String STOP_OPUS = "org.wikimedia.commons.wikimedia.STOP_OPUS";
| import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import com.audionowdigital.android.openplayer.Player;
import com.audionowdigital.android.openplayer.PlayerEvents;
import com.commonslab.commonslab.R;
import static com.commonslab.commonslab.Activities.MainActivity.PAUSE_OPUS;
import static com.commonslab.commonslab.Activities.MainActivity.PLAY_OPUS;
import static com.commonslab.commonslab.Activities.MainActivity.SEEKBAR_UPDATE_OPUS;
import static com.commonslab.commonslab.Activities.MainActivity.STOP_OPUS; | public OpusPlayer(Context context, int LENGTH, String mediaURL) {
this.LENGTH = LENGTH;
this.mediaURL = mediaURL;
this.context = context;
init();
}
private void init() {
playbackHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case PlayerEvents.PLAYING_FAILED:
showToastMessage(context.getString(R.string.the_decoder_failed_to_playback_the_file));
context.sendBroadcast(broadcastIntent);
Log.d(TAG, "The decoder failed to playback the file, check logs for more details");
break;
case PlayerEvents.PLAYING_FINISHED:
Log.d(TAG, "The decoder finished successfully");
context.sendBroadcast(broadcastIntent);
break;
case PlayerEvents.READING_HEADER:
Log.d(TAG, "Starting to read header");
break;
case PlayerEvents.READY_TO_PLAY:
Log.d(TAG, "READY to play - press play :)");
if (player != null && player.isReadyToPlay()) {
player.play(); | // Path: app/src/main/java/com/commonslab/commonslab/Activities/MainActivity.java
// public static final String PAUSE_OPUS = "org.wikimedia.commons.wikimedia.PAUSE_OPUS";
//
// Path: app/src/main/java/com/commonslab/commonslab/Activities/MainActivity.java
// public static final String PLAY_OPUS = "org.wikimedia.commons.wikimedia.PLAY_OPUS";
//
// Path: app/src/main/java/com/commonslab/commonslab/Activities/MainActivity.java
// public static final String SEEKBAR_UPDATE_OPUS = "org.wikimedia.commons.wikimedia.SEEKBAR_UPDATE_OPUS";
//
// Path: app/src/main/java/com/commonslab/commonslab/Activities/MainActivity.java
// public static final String STOP_OPUS = "org.wikimedia.commons.wikimedia.STOP_OPUS";
// Path: app/src/main/java/com/commonslab/commonslab/AudioPlayer/OpusPlayer.java
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import com.audionowdigital.android.openplayer.Player;
import com.audionowdigital.android.openplayer.PlayerEvents;
import com.commonslab.commonslab.R;
import static com.commonslab.commonslab.Activities.MainActivity.PAUSE_OPUS;
import static com.commonslab.commonslab.Activities.MainActivity.PLAY_OPUS;
import static com.commonslab.commonslab.Activities.MainActivity.SEEKBAR_UPDATE_OPUS;
import static com.commonslab.commonslab.Activities.MainActivity.STOP_OPUS;
public OpusPlayer(Context context, int LENGTH, String mediaURL) {
this.LENGTH = LENGTH;
this.mediaURL = mediaURL;
this.context = context;
init();
}
private void init() {
playbackHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case PlayerEvents.PLAYING_FAILED:
showToastMessage(context.getString(R.string.the_decoder_failed_to_playback_the_file));
context.sendBroadcast(broadcastIntent);
Log.d(TAG, "The decoder failed to playback the file, check logs for more details");
break;
case PlayerEvents.PLAYING_FINISHED:
Log.d(TAG, "The decoder finished successfully");
context.sendBroadcast(broadcastIntent);
break;
case PlayerEvents.READING_HEADER:
Log.d(TAG, "Starting to read header");
break;
case PlayerEvents.READY_TO_PLAY:
Log.d(TAG, "READY to play - press play :)");
if (player != null && player.isReadyToPlay()) {
player.play(); | Intent intent = new Intent(PLAY_OPUS); |
CommonsLab/CommonsLab | app/src/main/java/com/commonslab/commonslab/AudioPlayer/OpusPlayer.java | // Path: app/src/main/java/com/commonslab/commonslab/Activities/MainActivity.java
// public static final String PAUSE_OPUS = "org.wikimedia.commons.wikimedia.PAUSE_OPUS";
//
// Path: app/src/main/java/com/commonslab/commonslab/Activities/MainActivity.java
// public static final String PLAY_OPUS = "org.wikimedia.commons.wikimedia.PLAY_OPUS";
//
// Path: app/src/main/java/com/commonslab/commonslab/Activities/MainActivity.java
// public static final String SEEKBAR_UPDATE_OPUS = "org.wikimedia.commons.wikimedia.SEEKBAR_UPDATE_OPUS";
//
// Path: app/src/main/java/com/commonslab/commonslab/Activities/MainActivity.java
// public static final String STOP_OPUS = "org.wikimedia.commons.wikimedia.STOP_OPUS";
| import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import com.audionowdigital.android.openplayer.Player;
import com.audionowdigital.android.openplayer.PlayerEvents;
import com.commonslab.commonslab.R;
import static com.commonslab.commonslab.Activities.MainActivity.PAUSE_OPUS;
import static com.commonslab.commonslab.Activities.MainActivity.PLAY_OPUS;
import static com.commonslab.commonslab.Activities.MainActivity.SEEKBAR_UPDATE_OPUS;
import static com.commonslab.commonslab.Activities.MainActivity.STOP_OPUS; | Log.d(TAG, "Starting to read header");
break;
case PlayerEvents.READY_TO_PLAY:
Log.d(TAG, "READY to play - press play :)");
if (player != null && player.isReadyToPlay()) {
player.play();
Intent intent = new Intent(PLAY_OPUS);
context.sendBroadcast(intent);
}
break;
case PlayerEvents.PLAY_UPDATE:
Log.d(TAG, "Playing:" + (msg.arg1 / 60) + ":" + (msg.arg1 % 60) + " (" + (msg.arg1) + "s)");
seekBarIntent.putExtra("progressPosition", String.valueOf((int) (msg.arg1 * 100 / player.getDuration())));
context.sendBroadcast(seekBarIntent);
break;
case PlayerEvents.TRACK_INFO:
Bundle data = msg.getData();
Log.d(TAG, "title:" + data.getString("title") + " artist:" + data.getString("artist") + " album:" + data.getString("album") +
" date:" + data.getString("date") + " track:" + data.getString("track"));
break;
}
}
};
// quick test for a quick player
player = new Player(playbackHandler, type);
}
public void toggleOpusPlayer() {
if (player.isPlaying()) {
pauseOpusMedia(); | // Path: app/src/main/java/com/commonslab/commonslab/Activities/MainActivity.java
// public static final String PAUSE_OPUS = "org.wikimedia.commons.wikimedia.PAUSE_OPUS";
//
// Path: app/src/main/java/com/commonslab/commonslab/Activities/MainActivity.java
// public static final String PLAY_OPUS = "org.wikimedia.commons.wikimedia.PLAY_OPUS";
//
// Path: app/src/main/java/com/commonslab/commonslab/Activities/MainActivity.java
// public static final String SEEKBAR_UPDATE_OPUS = "org.wikimedia.commons.wikimedia.SEEKBAR_UPDATE_OPUS";
//
// Path: app/src/main/java/com/commonslab/commonslab/Activities/MainActivity.java
// public static final String STOP_OPUS = "org.wikimedia.commons.wikimedia.STOP_OPUS";
// Path: app/src/main/java/com/commonslab/commonslab/AudioPlayer/OpusPlayer.java
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import com.audionowdigital.android.openplayer.Player;
import com.audionowdigital.android.openplayer.PlayerEvents;
import com.commonslab.commonslab.R;
import static com.commonslab.commonslab.Activities.MainActivity.PAUSE_OPUS;
import static com.commonslab.commonslab.Activities.MainActivity.PLAY_OPUS;
import static com.commonslab.commonslab.Activities.MainActivity.SEEKBAR_UPDATE_OPUS;
import static com.commonslab.commonslab.Activities.MainActivity.STOP_OPUS;
Log.d(TAG, "Starting to read header");
break;
case PlayerEvents.READY_TO_PLAY:
Log.d(TAG, "READY to play - press play :)");
if (player != null && player.isReadyToPlay()) {
player.play();
Intent intent = new Intent(PLAY_OPUS);
context.sendBroadcast(intent);
}
break;
case PlayerEvents.PLAY_UPDATE:
Log.d(TAG, "Playing:" + (msg.arg1 / 60) + ":" + (msg.arg1 % 60) + " (" + (msg.arg1) + "s)");
seekBarIntent.putExtra("progressPosition", String.valueOf((int) (msg.arg1 * 100 / player.getDuration())));
context.sendBroadcast(seekBarIntent);
break;
case PlayerEvents.TRACK_INFO:
Bundle data = msg.getData();
Log.d(TAG, "title:" + data.getString("title") + " artist:" + data.getString("artist") + " album:" + data.getString("album") +
" date:" + data.getString("date") + " track:" + data.getString("track"));
break;
}
}
};
// quick test for a quick player
player = new Player(playbackHandler, type);
}
public void toggleOpusPlayer() {
if (player.isPlaying()) {
pauseOpusMedia(); | Intent broadcastIntent = new Intent(PAUSE_OPUS); |
CommonsLab/CommonsLab | app/src/main/java/com/commonslab/commonslab/Utils/SharedPreferencesUtils/StorageUtil.java | // Path: app/src/main/java/com/commonslab/commonslab/Utils/Today.java
// public class Today {
// public String date() {
// Calendar c = Calendar.getInstance();
// SimpleDateFormat month = new SimpleDateFormat("MMMM");
// SimpleDateFormat day = new SimpleDateFormat("d");
// String formattedMonth = month.format(c.getTime());
// String formattedDay = day.format(c.getTime());
// return formattedMonth + " " + formattedDay;
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.commonslab.commonslab.R;
import com.commonslab.commonslab.Utils.Today;
import java.lang.reflect.Type;
import java.util.ArrayList;
import apiwrapper.commons.wikimedia.org.Models.FeedItem;
import apiwrapper.commons.wikimedia.org.Enums.MediaType;
import apiwrapper.commons.wikimedia.org.Models.Contribution; | public boolean usersContributionsAvailable() {
preferences = context.getSharedPreferences(context.getString(R.string.User_Contributions), Context.MODE_PRIVATE);
return preferences.getBoolean("ContributionsAvailable", false);
}
public ArrayList<Contribution> retrieveUserContributions() {
preferences = context.getSharedPreferences(context.getString(R.string.User_Contributions), Context.MODE_PRIVATE);
String contributions;
//Check if contributions are previously stored
if ((contributions = preferences.getString("Contributions", null)) == null) return null;
if (contributions.equals("")) return null;//no uploads from this user
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<Contribution>>() {
}.getType();
return gson.fromJson(contributions, type);
}
//Store RSS feed, Picture and Media of the day
public void storeRSS_Feed(ArrayList<FeedItem> list, MediaType mediaType) {
if (mediaType == MediaType.PICTURE) {
preferences = context.getSharedPreferences(context.getString(R.string.Picture_of_the_day), Context.MODE_PRIVATE);
} else {
preferences = context.getSharedPreferences(context.getString(R.string.Media_of_the_day), Context.MODE_PRIVATE);
}
SharedPreferences.Editor prefsEditor = preferences.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
//Store date of this RSS feed | // Path: app/src/main/java/com/commonslab/commonslab/Utils/Today.java
// public class Today {
// public String date() {
// Calendar c = Calendar.getInstance();
// SimpleDateFormat month = new SimpleDateFormat("MMMM");
// SimpleDateFormat day = new SimpleDateFormat("d");
// String formattedMonth = month.format(c.getTime());
// String formattedDay = day.format(c.getTime());
// return formattedMonth + " " + formattedDay;
// }
// }
// Path: app/src/main/java/com/commonslab/commonslab/Utils/SharedPreferencesUtils/StorageUtil.java
import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.commonslab.commonslab.R;
import com.commonslab.commonslab.Utils.Today;
import java.lang.reflect.Type;
import java.util.ArrayList;
import apiwrapper.commons.wikimedia.org.Models.FeedItem;
import apiwrapper.commons.wikimedia.org.Enums.MediaType;
import apiwrapper.commons.wikimedia.org.Models.Contribution;
public boolean usersContributionsAvailable() {
preferences = context.getSharedPreferences(context.getString(R.string.User_Contributions), Context.MODE_PRIVATE);
return preferences.getBoolean("ContributionsAvailable", false);
}
public ArrayList<Contribution> retrieveUserContributions() {
preferences = context.getSharedPreferences(context.getString(R.string.User_Contributions), Context.MODE_PRIVATE);
String contributions;
//Check if contributions are previously stored
if ((contributions = preferences.getString("Contributions", null)) == null) return null;
if (contributions.equals("")) return null;//no uploads from this user
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<Contribution>>() {
}.getType();
return gson.fromJson(contributions, type);
}
//Store RSS feed, Picture and Media of the day
public void storeRSS_Feed(ArrayList<FeedItem> list, MediaType mediaType) {
if (mediaType == MediaType.PICTURE) {
preferences = context.getSharedPreferences(context.getString(R.string.Picture_of_the_day), Context.MODE_PRIVATE);
} else {
preferences = context.getSharedPreferences(context.getString(R.string.Media_of_the_day), Context.MODE_PRIVATE);
}
SharedPreferences.Editor prefsEditor = preferences.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
//Store date of this RSS feed | prefsEditor.putString("Date", new Today().date()); |
fikr4n/itl-java | itl/src/main/java/org/arabeyes/itl/prayertime/AstroModule.java | // Path: itl/src/main/java/org/arabeyes/itl/prayertime/PrayerModule.java
// static class Location {
// double degreeLong; /* Longitude in decimal degree. */
// double degreeLat; /* Latitude in decimal degree. */
// double gmtDiff; /* GMT difference at regular time. */
// int dst; /* Daylight savings time switch (0 if not used).
// Setting this to 1 should add 1 hour to all the
// calculated prayer times */
// double seaLevel; /* Height above Sea level in meters */
// double pressure; /* Atmospheric pressure in millibars (the
// astronomical standard value is 1010) */
// double temperature; /* Temperature in Celsius degree (the astronomical
// standard value is 10) */
//
// Location() {
// }
//
// Location(Location src) {
// this.degreeLong = src.degreeLong;
// this.degreeLat = src.degreeLat;
// this.gmtDiff = src.gmtDiff;
// this.dst = src.dst;
// this.seaLevel = src.seaLevel;
// this.pressure = src.pressure;
// this.temperature = src.temperature;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/prayertime/PrayerModule.java
// static class SDate {
// int day;
// int month;
// int year;
//
// SDate() {
// }
//
// SDate(SDate src) {
// this.day = src.day;
// this.month = src.month;
// this.year = src.year;
// }
// }
| import org.arabeyes.itl.prayertime.PrayerModule.Location;
import org.arabeyes.itl.prayertime.PrayerModule.SDate;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan;
import static java.lang.Math.atan2;
import static java.lang.Math.cos;
import static java.lang.Math.floor;
import static java.lang.Math.pow;
import static java.lang.Math.sin;
import static java.lang.Math.tan; | /* Copyright (c) 2003-2006, 2009-2010 Arabeyes, Thamer Mahmoud
*
* A full featured Muslim Prayer Times calculator
*
* Most of the astronomical values and formulas used in this file are based
* upon a subset of the VSOP87 planetary theory developed by Jean Meeus. Page
* and formula numbers in-line below are references to his book: Astronomical
* Algorithms. Willmann-Bell, second edition, 1998.
*
* (www.arabeyes.org - under LGPL license - see COPYING file)
*/
package org.arabeyes.itl.prayertime;
class AstroModule {
// Compatible with ITL 59bd87234aa87712a92b3fffb5497a43f121abf2
/* Defaults */
static final int INVALID_TRIGGER = 1;
private static final double PI = 3.1415926535898;
private static final double CENTER_OF_SUN_ANGLE = -0.833370; /* ..of sun's upper limb angle */
private static final double EARTH_RADIUS = 6378140.0; /* Equatorial radius in meters */
private static final double ALTITUDE_REFRACTION = 0.0347;
static final double DEG_TO_10_BASE = 1 / 15.0;
/* UTILITIES */
static double DEG_TO_RAD(double A) {
return ((A) * (PI / 180.0));
}
static double RAD_TO_DEG(double A) {
return ((A) / (PI / 180.0));
}
static class Astro {
double jd; /* Astronomical Julian day (for local time with Delta-t) */
double[] dec = new double[3]; /* Declination */
double[] ra = new double[3]; /* Right Ascensions */
double[] sid = new double[3]; /* Apparent sidereal time */
double[] dra = new double[3]; /* Delta Right Ascensions */
double[] rsum = new double[3]; /* Sum of periodic values for radius vector R */
Astro() {
}
Astro(Astro src) {
this.jd = src.jd;
this.dec = src.dec;
this.ra = src.ra;
this.sid = src.sid;
this.dra = src.dra;
this.rsum = src.rsum;
}
}
private static class AstroDay {
double dec;
double ra;
double sidtime;
double dra;
double rsum;
}
private enum Type {
SUNRISE,
SUNSET
}
private AstroModule() {
}
| // Path: itl/src/main/java/org/arabeyes/itl/prayertime/PrayerModule.java
// static class Location {
// double degreeLong; /* Longitude in decimal degree. */
// double degreeLat; /* Latitude in decimal degree. */
// double gmtDiff; /* GMT difference at regular time. */
// int dst; /* Daylight savings time switch (0 if not used).
// Setting this to 1 should add 1 hour to all the
// calculated prayer times */
// double seaLevel; /* Height above Sea level in meters */
// double pressure; /* Atmospheric pressure in millibars (the
// astronomical standard value is 1010) */
// double temperature; /* Temperature in Celsius degree (the astronomical
// standard value is 10) */
//
// Location() {
// }
//
// Location(Location src) {
// this.degreeLong = src.degreeLong;
// this.degreeLat = src.degreeLat;
// this.gmtDiff = src.gmtDiff;
// this.dst = src.dst;
// this.seaLevel = src.seaLevel;
// this.pressure = src.pressure;
// this.temperature = src.temperature;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/prayertime/PrayerModule.java
// static class SDate {
// int day;
// int month;
// int year;
//
// SDate() {
// }
//
// SDate(SDate src) {
// this.day = src.day;
// this.month = src.month;
// this.year = src.year;
// }
// }
// Path: itl/src/main/java/org/arabeyes/itl/prayertime/AstroModule.java
import org.arabeyes.itl.prayertime.PrayerModule.Location;
import org.arabeyes.itl.prayertime.PrayerModule.SDate;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan;
import static java.lang.Math.atan2;
import static java.lang.Math.cos;
import static java.lang.Math.floor;
import static java.lang.Math.pow;
import static java.lang.Math.sin;
import static java.lang.Math.tan;
/* Copyright (c) 2003-2006, 2009-2010 Arabeyes, Thamer Mahmoud
*
* A full featured Muslim Prayer Times calculator
*
* Most of the astronomical values and formulas used in this file are based
* upon a subset of the VSOP87 planetary theory developed by Jean Meeus. Page
* and formula numbers in-line below are references to his book: Astronomical
* Algorithms. Willmann-Bell, second edition, 1998.
*
* (www.arabeyes.org - under LGPL license - see COPYING file)
*/
package org.arabeyes.itl.prayertime;
class AstroModule {
// Compatible with ITL 59bd87234aa87712a92b3fffb5497a43f121abf2
/* Defaults */
static final int INVALID_TRIGGER = 1;
private static final double PI = 3.1415926535898;
private static final double CENTER_OF_SUN_ANGLE = -0.833370; /* ..of sun's upper limb angle */
private static final double EARTH_RADIUS = 6378140.0; /* Equatorial radius in meters */
private static final double ALTITUDE_REFRACTION = 0.0347;
static final double DEG_TO_10_BASE = 1 / 15.0;
/* UTILITIES */
static double DEG_TO_RAD(double A) {
return ((A) * (PI / 180.0));
}
static double RAD_TO_DEG(double A) {
return ((A) / (PI / 180.0));
}
static class Astro {
double jd; /* Astronomical Julian day (for local time with Delta-t) */
double[] dec = new double[3]; /* Declination */
double[] ra = new double[3]; /* Right Ascensions */
double[] sid = new double[3]; /* Apparent sidereal time */
double[] dra = new double[3]; /* Delta Right Ascensions */
double[] rsum = new double[3]; /* Sum of periodic values for radius vector R */
Astro() {
}
Astro(Astro src) {
this.jd = src.jd;
this.dec = src.dec;
this.ra = src.ra;
this.sid = src.sid;
this.dra = src.dra;
this.rsum = src.rsum;
}
}
private static class AstroDay {
double dec;
double ra;
double sidtime;
double dra;
double rsum;
}
private enum Type {
SUNRISE,
SUNSET
}
private AstroModule() {
}
| static double getSunrise(Location loc, Astro tastro) { |
fikr4n/itl-java | itl/src/main/java/org/arabeyes/itl/prayertime/AstroModule.java | // Path: itl/src/main/java/org/arabeyes/itl/prayertime/PrayerModule.java
// static class Location {
// double degreeLong; /* Longitude in decimal degree. */
// double degreeLat; /* Latitude in decimal degree. */
// double gmtDiff; /* GMT difference at regular time. */
// int dst; /* Daylight savings time switch (0 if not used).
// Setting this to 1 should add 1 hour to all the
// calculated prayer times */
// double seaLevel; /* Height above Sea level in meters */
// double pressure; /* Atmospheric pressure in millibars (the
// astronomical standard value is 1010) */
// double temperature; /* Temperature in Celsius degree (the astronomical
// standard value is 10) */
//
// Location() {
// }
//
// Location(Location src) {
// this.degreeLong = src.degreeLong;
// this.degreeLat = src.degreeLat;
// this.gmtDiff = src.gmtDiff;
// this.dst = src.dst;
// this.seaLevel = src.seaLevel;
// this.pressure = src.pressure;
// this.temperature = src.temperature;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/prayertime/PrayerModule.java
// static class SDate {
// int day;
// int month;
// int year;
//
// SDate() {
// }
//
// SDate(SDate src) {
// this.day = src.day;
// this.month = src.month;
// this.year = src.year;
// }
// }
| import org.arabeyes.itl.prayertime.PrayerModule.Location;
import org.arabeyes.itl.prayertime.PrayerModule.SDate;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan;
import static java.lang.Math.atan2;
import static java.lang.Math.cos;
import static java.lang.Math.floor;
import static java.lang.Math.pow;
import static java.lang.Math.sin;
import static java.lang.Math.tan; | else if (year >= 1620 && year <= 1998)
return 0; /* FIXIT: Support historical delta-t values for years before
* 1998. In the DT table above, each line represents 5 even
* years in the range 1620-1998. We should first complete the
* table to include data for both odd and even years. */
else if ((year > 1998 && year < 2100) || year < 1620) {
/* NOTE: The "2017" found below this comment should be changed to
reflect the last year added to the DT2 table. */
if (year >= 1999 && year <= 2017) {
i = (int) (year - 1999);
return DT2[i];
}
/* As of 2007, the two formulas given by Meeus seem to be off by
many seconds when compared to observed values found at
<http://maia.usno.navy.mil>. The DT2 table overrides these values
with observed and predicted ones for delta-t (on January, other
months not yet supported). Extrapolated (and wrong) values are still
used for years after 2017. */
else tempdt = 102 + (102 * t) + (25.3 * pow(t, 2));
if (year >= 2000)
return tempdt + (0.37 * (year - 2100));
else return tempdt;
}
return 0;
}
/**
* Returns the astronomical Julian day (for local time with delta-t)
*/ | // Path: itl/src/main/java/org/arabeyes/itl/prayertime/PrayerModule.java
// static class Location {
// double degreeLong; /* Longitude in decimal degree. */
// double degreeLat; /* Latitude in decimal degree. */
// double gmtDiff; /* GMT difference at regular time. */
// int dst; /* Daylight savings time switch (0 if not used).
// Setting this to 1 should add 1 hour to all the
// calculated prayer times */
// double seaLevel; /* Height above Sea level in meters */
// double pressure; /* Atmospheric pressure in millibars (the
// astronomical standard value is 1010) */
// double temperature; /* Temperature in Celsius degree (the astronomical
// standard value is 10) */
//
// Location() {
// }
//
// Location(Location src) {
// this.degreeLong = src.degreeLong;
// this.degreeLat = src.degreeLat;
// this.gmtDiff = src.gmtDiff;
// this.dst = src.dst;
// this.seaLevel = src.seaLevel;
// this.pressure = src.pressure;
// this.temperature = src.temperature;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/prayertime/PrayerModule.java
// static class SDate {
// int day;
// int month;
// int year;
//
// SDate() {
// }
//
// SDate(SDate src) {
// this.day = src.day;
// this.month = src.month;
// this.year = src.year;
// }
// }
// Path: itl/src/main/java/org/arabeyes/itl/prayertime/AstroModule.java
import org.arabeyes.itl.prayertime.PrayerModule.Location;
import org.arabeyes.itl.prayertime.PrayerModule.SDate;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan;
import static java.lang.Math.atan2;
import static java.lang.Math.cos;
import static java.lang.Math.floor;
import static java.lang.Math.pow;
import static java.lang.Math.sin;
import static java.lang.Math.tan;
else if (year >= 1620 && year <= 1998)
return 0; /* FIXIT: Support historical delta-t values for years before
* 1998. In the DT table above, each line represents 5 even
* years in the range 1620-1998. We should first complete the
* table to include data for both odd and even years. */
else if ((year > 1998 && year < 2100) || year < 1620) {
/* NOTE: The "2017" found below this comment should be changed to
reflect the last year added to the DT2 table. */
if (year >= 1999 && year <= 2017) {
i = (int) (year - 1999);
return DT2[i];
}
/* As of 2007, the two formulas given by Meeus seem to be off by
many seconds when compared to observed values found at
<http://maia.usno.navy.mil>. The DT2 table overrides these values
with observed and predicted ones for delta-t (on January, other
months not yet supported). Extrapolated (and wrong) values are still
used for years after 2017. */
else tempdt = 102 + (102 * t) + (25.3 * pow(t, 2));
if (year >= 2000)
return tempdt + (0.37 * (year - 2100));
else return tempdt;
}
return 0;
}
/**
* Returns the astronomical Julian day (for local time with delta-t)
*/ | static double getJulianDay(SDate date, double gmt) { |
fikr4n/itl-java | itl/src/main/java/org/arabeyes/itl/newmethod/Prayer.java | // Path: itl/src/main/java/org/arabeyes/itl/prayertime/Dms.java
// @SuppressWarnings("WeakerAccess")
// public class Dms implements Comparable<Dms> {
// private final int deg;
// private final int min;
// private final double sec;
//
// /**
// * All numbers should be either positive or negative. Mixed sign has no meaning.
// *
// * @param deg degree
// * @param min -60 <= minute <= 60
// * @param sec -60 <= second <= 60
// * @throws IllegalArgumentException if sign is not consistent or exceeds the range
// */
// public Dms(int deg, int min, double sec) {
// if (min > 60 || sec > 60.0 ||
// (deg > 0 && (min < 0 || sec < 0)) ||
// (deg < 0 && (min > 0 || sec > 0)))
// throw new IllegalArgumentException(String.format("deg=%s, min=%s, sec=%s", deg, min, sec));
// this.deg = deg;
// this.min = min;
// this.sec = sec;
// }
//
// public static Dms fromDecimal(double decimal) {
// return PrayerModule.decimal2Dms(decimal);
// }
//
// public int getDegree() {
// return deg;
// }
//
// public int getMinute() {
// return min;
// }
//
// public double getSecond() {
// return sec;
// }
//
// public double toDecimal() {
// return PrayerModule.dms2Decimal(deg, min, sec, ' ');
// }
//
// /**
// * Returns string representation in d°m′s.sss...″ format.
// */
// @Override
// public String toString() {
// String sign = "";
// if (deg < 0 || min < 0 || sec < 0.0)
// sign = "-";
// return sign + abs(deg) + '°' + abs(min) + '′' + abs(sec) + '″';
// }
//
// /**
// * Returns string representation in d°m′s.sss...″ format.
// *
// * @param secFormat used for positive/negative prefix/suffix of DMS and decimal format of
// * second
// */
// public String toString(DecimalFormat secFormat) {
// String pre = deg < 0 || min < 0 || sec < 0.0 ? secFormat.getNegativePrefix() :
// secFormat.getPositivePrefix();
// String post = deg < 0 || min < 0 || sec < 0.0 ? secFormat.getNegativeSuffix() :
// secFormat.getPositiveSuffix();
// return pre + abs(deg) + '°' + abs(min) + '′' + secFormat.format(abs(sec)) + '″' + post;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Dms dms = (Dms) o;
// return deg == dms.deg && min == dms.min && Double.compare(dms.sec, sec) == 0;
// }
//
// @Override
// public int hashCode() {
// int result = deg;
// result = 31 * result + min;
// long temp = Double.doubleToLongBits(sec);
// result = 31 * result + (int) (temp ^ (temp >>> 32));
// return result;
// }
//
// /**
// * See {@link Comparable#compareTo(Object)}
// *
// * @throws ClassCastException if different class
// */
// @Override
// public int compareTo(Dms dms) {
// if (getClass() != dms.getClass())
// throw new ClassCastException("Can't compare with instance of " + dms.getClass());
//
// if (deg != dms.deg) return deg - dms.deg;
// if (min != dms.min) return min - dms.min;
// return Double.compare(sec, dms.sec);
// }
// }
| import org.arabeyes.itl.prayertime.Dms;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone; | location.latitude = latitude;
location.longitude = longitude;
location.altitude = altitude;
return this;
}
public Prayer setDate(GregorianCalendar cal) {
this.date = new DefsModule.date_t().set(cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR));
this.location.timezone = cal.get(Calendar.ZONE_OFFSET) / (1000.0 * 60 * 60);
this.location.daylight = (int) Math.round(cal.get(Calendar.DST_OFFSET) / (1000.0 * 60 * 60));
return this;
}
public Prayer setDate(Date date, TimeZone timeZone) {
GregorianCalendar cal = new GregorianCalendar(timeZone);
cal.setTime(date);
return setDate(cal);
}
public PrayerTimes getPrayerTimes() {
requireMethods();
requireDate();
requireLocation();
PrayerTimes result = new PrayerTimes();
PrayerModule.get_prayer_times(date, location, result);
return result;
}
| // Path: itl/src/main/java/org/arabeyes/itl/prayertime/Dms.java
// @SuppressWarnings("WeakerAccess")
// public class Dms implements Comparable<Dms> {
// private final int deg;
// private final int min;
// private final double sec;
//
// /**
// * All numbers should be either positive or negative. Mixed sign has no meaning.
// *
// * @param deg degree
// * @param min -60 <= minute <= 60
// * @param sec -60 <= second <= 60
// * @throws IllegalArgumentException if sign is not consistent or exceeds the range
// */
// public Dms(int deg, int min, double sec) {
// if (min > 60 || sec > 60.0 ||
// (deg > 0 && (min < 0 || sec < 0)) ||
// (deg < 0 && (min > 0 || sec > 0)))
// throw new IllegalArgumentException(String.format("deg=%s, min=%s, sec=%s", deg, min, sec));
// this.deg = deg;
// this.min = min;
// this.sec = sec;
// }
//
// public static Dms fromDecimal(double decimal) {
// return PrayerModule.decimal2Dms(decimal);
// }
//
// public int getDegree() {
// return deg;
// }
//
// public int getMinute() {
// return min;
// }
//
// public double getSecond() {
// return sec;
// }
//
// public double toDecimal() {
// return PrayerModule.dms2Decimal(deg, min, sec, ' ');
// }
//
// /**
// * Returns string representation in d°m′s.sss...″ format.
// */
// @Override
// public String toString() {
// String sign = "";
// if (deg < 0 || min < 0 || sec < 0.0)
// sign = "-";
// return sign + abs(deg) + '°' + abs(min) + '′' + abs(sec) + '″';
// }
//
// /**
// * Returns string representation in d°m′s.sss...″ format.
// *
// * @param secFormat used for positive/negative prefix/suffix of DMS and decimal format of
// * second
// */
// public String toString(DecimalFormat secFormat) {
// String pre = deg < 0 || min < 0 || sec < 0.0 ? secFormat.getNegativePrefix() :
// secFormat.getPositivePrefix();
// String post = deg < 0 || min < 0 || sec < 0.0 ? secFormat.getNegativeSuffix() :
// secFormat.getPositiveSuffix();
// return pre + abs(deg) + '°' + abs(min) + '′' + secFormat.format(abs(sec)) + '″' + post;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Dms dms = (Dms) o;
// return deg == dms.deg && min == dms.min && Double.compare(dms.sec, sec) == 0;
// }
//
// @Override
// public int hashCode() {
// int result = deg;
// result = 31 * result + min;
// long temp = Double.doubleToLongBits(sec);
// result = 31 * result + (int) (temp ^ (temp >>> 32));
// return result;
// }
//
// /**
// * See {@link Comparable#compareTo(Object)}
// *
// * @throws ClassCastException if different class
// */
// @Override
// public int compareTo(Dms dms) {
// if (getClass() != dms.getClass())
// throw new ClassCastException("Can't compare with instance of " + dms.getClass());
//
// if (deg != dms.deg) return deg - dms.deg;
// if (min != dms.min) return min - dms.min;
// return Double.compare(sec, dms.sec);
// }
// }
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/Prayer.java
import org.arabeyes.itl.prayertime.Dms;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
location.latitude = latitude;
location.longitude = longitude;
location.altitude = altitude;
return this;
}
public Prayer setDate(GregorianCalendar cal) {
this.date = new DefsModule.date_t().set(cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR));
this.location.timezone = cal.get(Calendar.ZONE_OFFSET) / (1000.0 * 60 * 60);
this.location.daylight = (int) Math.round(cal.get(Calendar.DST_OFFSET) / (1000.0 * 60 * 60));
return this;
}
public Prayer setDate(Date date, TimeZone timeZone) {
GregorianCalendar cal = new GregorianCalendar(timeZone);
cal.setTime(date);
return setDate(cal);
}
public PrayerTimes getPrayerTimes() {
requireMethods();
requireDate();
requireLocation();
PrayerTimes result = new PrayerTimes();
PrayerModule.get_prayer_times(date, location, result);
return result;
}
| public Dms getQiblaDirection() { |
fikr4n/itl-java | itl/src/main/java/org/arabeyes/itl/newmethod/PrayerModule.java | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class approx_sun_coord {
// double D; /* Declination of the Sun */
// double EqT; /* The Equation of Time */
// double R; /* The distance of the Sun from the Earth
// in astronomical units (AU) */
// double SD; /* The angular semidiameter of the Sun in degrees */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class date_t {
// int year, month, day;
//
// /**
// * @param day starts from 1
// * @param month starts from 1, like the old ITL
// */
// date_t set(int day, int month, int year) {
// this.year = year;
// this.month = month;
// this.day = day;
// return this;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class location {
// /* In original C: The struct members ordering guarantees that the compiler does
// * not add any padding bytes when compiling for 64-bit machines */
//
// double longitude; /* Observer's longitude */
// double latitude; /* Observer's latitude */
// double altitude; /* Observer's altitude in meters */
// double timezone; /* Observer's timezone (in hours) relative
// to Universal Coordinated Time (UTC) */
// int daylight; /* Daylight Savings Time (DST) Flag
// Set to 1 if DST is on, 0 otherwise */
// AsrMethod asr_method; /* Asr Method: Shafii or Hanafi */
// CalcMethod calc_method; /* Fajr and Isha Calculation method */
// ExtremeMethod extr_method; /* Extreme latitude method */
// String name; /* Observer's location name */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// enum round_t {
// UP, DOWN, NEAREST
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LATITUDE = (21.42249);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LONGITUDE = (39.82620);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double M_PI = (3.141592653589793);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double ONE_MINUTE = (60.0 / 3600.0);
| import static org.arabeyes.itl.newmethod.DefsModule.ONE_MINUTE;
import org.arabeyes.itl.newmethod.DefsModule.approx_sun_coord;
import org.arabeyes.itl.newmethod.DefsModule.date_t;
import org.arabeyes.itl.newmethod.DefsModule.location;
import org.arabeyes.itl.newmethod.DefsModule.round_t;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan2;
import static java.lang.Math.ceil;
import static java.lang.Math.cos;
import static java.lang.Math.floor;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
import static java.lang.Math.tan;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LATITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LONGITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.M_PI; | /*
Islamic Prayer Times and Qibla Direction Library
By Mohamed A.M. Bamakhrama (mohamed@alumni.tum.de)
Licensed under the BSD license shown in file LICENSE
This is a "clean-room" implementation that uses simpler but
approximate methods. This implementation should be easier
to maintain and debug. However, we need to first to test it
throughly before replacing the old method. Currently, it
supports calculating the prayer times and qibla location for
"normal" latitudes. However, "extreme latitude" methods are
still missing.
*/
package org.arabeyes.itl.newmethod;
class PrayerModule {
static CalcMethod calc_methods[] = {
new CalcMethod(MethodId.MWL, "Muslim World League (MWL)",
IshaFlag.ANGLE, 18, 17),
new CalcMethod(MethodId.ISNA, "Islamic Society of North America (ISNA)",
IshaFlag.ANGLE, 15, 15),
new CalcMethod(MethodId.EGAS, "Egyptian General Authority of Survey",
IshaFlag.ANGLE, 19.5, 17.5),
new CalcMethod(MethodId.UMAQ, "Umm Al-Qura University, Makkah",
IshaFlag.OFFSET, 18.5, 90),
new CalcMethod(MethodId.UIS, "University of Islamic Sciences, Karachi",
IshaFlag.ANGLE, 18, 18)
};
/**
* Convert a given angle specified in degrees into radians
*/
private static double to_radians(double x) { | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class approx_sun_coord {
// double D; /* Declination of the Sun */
// double EqT; /* The Equation of Time */
// double R; /* The distance of the Sun from the Earth
// in astronomical units (AU) */
// double SD; /* The angular semidiameter of the Sun in degrees */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class date_t {
// int year, month, day;
//
// /**
// * @param day starts from 1
// * @param month starts from 1, like the old ITL
// */
// date_t set(int day, int month, int year) {
// this.year = year;
// this.month = month;
// this.day = day;
// return this;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class location {
// /* In original C: The struct members ordering guarantees that the compiler does
// * not add any padding bytes when compiling for 64-bit machines */
//
// double longitude; /* Observer's longitude */
// double latitude; /* Observer's latitude */
// double altitude; /* Observer's altitude in meters */
// double timezone; /* Observer's timezone (in hours) relative
// to Universal Coordinated Time (UTC) */
// int daylight; /* Daylight Savings Time (DST) Flag
// Set to 1 if DST is on, 0 otherwise */
// AsrMethod asr_method; /* Asr Method: Shafii or Hanafi */
// CalcMethod calc_method; /* Fajr and Isha Calculation method */
// ExtremeMethod extr_method; /* Extreme latitude method */
// String name; /* Observer's location name */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// enum round_t {
// UP, DOWN, NEAREST
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LATITUDE = (21.42249);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LONGITUDE = (39.82620);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double M_PI = (3.141592653589793);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double ONE_MINUTE = (60.0 / 3600.0);
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/PrayerModule.java
import static org.arabeyes.itl.newmethod.DefsModule.ONE_MINUTE;
import org.arabeyes.itl.newmethod.DefsModule.approx_sun_coord;
import org.arabeyes.itl.newmethod.DefsModule.date_t;
import org.arabeyes.itl.newmethod.DefsModule.location;
import org.arabeyes.itl.newmethod.DefsModule.round_t;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan2;
import static java.lang.Math.ceil;
import static java.lang.Math.cos;
import static java.lang.Math.floor;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
import static java.lang.Math.tan;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LATITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LONGITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.M_PI;
/*
Islamic Prayer Times and Qibla Direction Library
By Mohamed A.M. Bamakhrama (mohamed@alumni.tum.de)
Licensed under the BSD license shown in file LICENSE
This is a "clean-room" implementation that uses simpler but
approximate methods. This implementation should be easier
to maintain and debug. However, we need to first to test it
throughly before replacing the old method. Currently, it
supports calculating the prayer times and qibla location for
"normal" latitudes. However, "extreme latitude" methods are
still missing.
*/
package org.arabeyes.itl.newmethod;
class PrayerModule {
static CalcMethod calc_methods[] = {
new CalcMethod(MethodId.MWL, "Muslim World League (MWL)",
IshaFlag.ANGLE, 18, 17),
new CalcMethod(MethodId.ISNA, "Islamic Society of North America (ISNA)",
IshaFlag.ANGLE, 15, 15),
new CalcMethod(MethodId.EGAS, "Egyptian General Authority of Survey",
IshaFlag.ANGLE, 19.5, 17.5),
new CalcMethod(MethodId.UMAQ, "Umm Al-Qura University, Makkah",
IshaFlag.OFFSET, 18.5, 90),
new CalcMethod(MethodId.UIS, "University of Islamic Sciences, Karachi",
IshaFlag.ANGLE, 18, 18)
};
/**
* Convert a given angle specified in degrees into radians
*/
private static double to_radians(double x) { | return ((x) * M_PI) / 180.0; |
fikr4n/itl-java | itl/src/main/java/org/arabeyes/itl/newmethod/PrayerModule.java | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class approx_sun_coord {
// double D; /* Declination of the Sun */
// double EqT; /* The Equation of Time */
// double R; /* The distance of the Sun from the Earth
// in astronomical units (AU) */
// double SD; /* The angular semidiameter of the Sun in degrees */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class date_t {
// int year, month, day;
//
// /**
// * @param day starts from 1
// * @param month starts from 1, like the old ITL
// */
// date_t set(int day, int month, int year) {
// this.year = year;
// this.month = month;
// this.day = day;
// return this;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class location {
// /* In original C: The struct members ordering guarantees that the compiler does
// * not add any padding bytes when compiling for 64-bit machines */
//
// double longitude; /* Observer's longitude */
// double latitude; /* Observer's latitude */
// double altitude; /* Observer's altitude in meters */
// double timezone; /* Observer's timezone (in hours) relative
// to Universal Coordinated Time (UTC) */
// int daylight; /* Daylight Savings Time (DST) Flag
// Set to 1 if DST is on, 0 otherwise */
// AsrMethod asr_method; /* Asr Method: Shafii or Hanafi */
// CalcMethod calc_method; /* Fajr and Isha Calculation method */
// ExtremeMethod extr_method; /* Extreme latitude method */
// String name; /* Observer's location name */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// enum round_t {
// UP, DOWN, NEAREST
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LATITUDE = (21.42249);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LONGITUDE = (39.82620);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double M_PI = (3.141592653589793);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double ONE_MINUTE = (60.0 / 3600.0);
| import static org.arabeyes.itl.newmethod.DefsModule.ONE_MINUTE;
import org.arabeyes.itl.newmethod.DefsModule.approx_sun_coord;
import org.arabeyes.itl.newmethod.DefsModule.date_t;
import org.arabeyes.itl.newmethod.DefsModule.location;
import org.arabeyes.itl.newmethod.DefsModule.round_t;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan2;
import static java.lang.Math.ceil;
import static java.lang.Math.cos;
import static java.lang.Math.floor;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
import static java.lang.Math.tan;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LATITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LONGITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.M_PI; | private static double arccot(double x) {
return atan2(1.0, (x));
}
/**
* Normalizes the given value x to be within the range [0,N]
*/
private static double normalize(double x, double N) {
double n;
assert (N > 0.0);
n = x - (N * floor(x / N));
assert (n <= N);
return n;
}
/**
* round is avalilable only in C99. Therefore, we use a custom one
*
* @return The rounded value of x
*/
private static double custom_round(double x) {
return floor(x + 0.5);
}
/**
* Compute the Julian Day Number for a given date
* Source: https://en.wikipedia.org/wiki/Julian_day
*
* @return The Julian day number
*/ | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class approx_sun_coord {
// double D; /* Declination of the Sun */
// double EqT; /* The Equation of Time */
// double R; /* The distance of the Sun from the Earth
// in astronomical units (AU) */
// double SD; /* The angular semidiameter of the Sun in degrees */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class date_t {
// int year, month, day;
//
// /**
// * @param day starts from 1
// * @param month starts from 1, like the old ITL
// */
// date_t set(int day, int month, int year) {
// this.year = year;
// this.month = month;
// this.day = day;
// return this;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class location {
// /* In original C: The struct members ordering guarantees that the compiler does
// * not add any padding bytes when compiling for 64-bit machines */
//
// double longitude; /* Observer's longitude */
// double latitude; /* Observer's latitude */
// double altitude; /* Observer's altitude in meters */
// double timezone; /* Observer's timezone (in hours) relative
// to Universal Coordinated Time (UTC) */
// int daylight; /* Daylight Savings Time (DST) Flag
// Set to 1 if DST is on, 0 otherwise */
// AsrMethod asr_method; /* Asr Method: Shafii or Hanafi */
// CalcMethod calc_method; /* Fajr and Isha Calculation method */
// ExtremeMethod extr_method; /* Extreme latitude method */
// String name; /* Observer's location name */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// enum round_t {
// UP, DOWN, NEAREST
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LATITUDE = (21.42249);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LONGITUDE = (39.82620);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double M_PI = (3.141592653589793);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double ONE_MINUTE = (60.0 / 3600.0);
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/PrayerModule.java
import static org.arabeyes.itl.newmethod.DefsModule.ONE_MINUTE;
import org.arabeyes.itl.newmethod.DefsModule.approx_sun_coord;
import org.arabeyes.itl.newmethod.DefsModule.date_t;
import org.arabeyes.itl.newmethod.DefsModule.location;
import org.arabeyes.itl.newmethod.DefsModule.round_t;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan2;
import static java.lang.Math.ceil;
import static java.lang.Math.cos;
import static java.lang.Math.floor;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
import static java.lang.Math.tan;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LATITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LONGITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.M_PI;
private static double arccot(double x) {
return atan2(1.0, (x));
}
/**
* Normalizes the given value x to be within the range [0,N]
*/
private static double normalize(double x, double N) {
double n;
assert (N > 0.0);
n = x - (N * floor(x / N));
assert (n <= N);
return n;
}
/**
* round is avalilable only in C99. Therefore, we use a custom one
*
* @return The rounded value of x
*/
private static double custom_round(double x) {
return floor(x + 0.5);
}
/**
* Compute the Julian Day Number for a given date
* Source: https://en.wikipedia.org/wiki/Julian_day
*
* @return The Julian day number
*/ | private static int get_julian_day_number(date_t date) { |
fikr4n/itl-java | itl/src/main/java/org/arabeyes/itl/newmethod/PrayerModule.java | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class approx_sun_coord {
// double D; /* Declination of the Sun */
// double EqT; /* The Equation of Time */
// double R; /* The distance of the Sun from the Earth
// in astronomical units (AU) */
// double SD; /* The angular semidiameter of the Sun in degrees */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class date_t {
// int year, month, day;
//
// /**
// * @param day starts from 1
// * @param month starts from 1, like the old ITL
// */
// date_t set(int day, int month, int year) {
// this.year = year;
// this.month = month;
// this.day = day;
// return this;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class location {
// /* In original C: The struct members ordering guarantees that the compiler does
// * not add any padding bytes when compiling for 64-bit machines */
//
// double longitude; /* Observer's longitude */
// double latitude; /* Observer's latitude */
// double altitude; /* Observer's altitude in meters */
// double timezone; /* Observer's timezone (in hours) relative
// to Universal Coordinated Time (UTC) */
// int daylight; /* Daylight Savings Time (DST) Flag
// Set to 1 if DST is on, 0 otherwise */
// AsrMethod asr_method; /* Asr Method: Shafii or Hanafi */
// CalcMethod calc_method; /* Fajr and Isha Calculation method */
// ExtremeMethod extr_method; /* Extreme latitude method */
// String name; /* Observer's location name */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// enum round_t {
// UP, DOWN, NEAREST
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LATITUDE = (21.42249);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LONGITUDE = (39.82620);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double M_PI = (3.141592653589793);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double ONE_MINUTE = (60.0 / 3600.0);
| import static org.arabeyes.itl.newmethod.DefsModule.ONE_MINUTE;
import org.arabeyes.itl.newmethod.DefsModule.approx_sun_coord;
import org.arabeyes.itl.newmethod.DefsModule.date_t;
import org.arabeyes.itl.newmethod.DefsModule.location;
import org.arabeyes.itl.newmethod.DefsModule.round_t;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan2;
import static java.lang.Math.ceil;
import static java.lang.Math.cos;
import static java.lang.Math.floor;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
import static java.lang.Math.tan;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LATITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LONGITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.M_PI; | * Source: https://en.wikipedia.org/wiki/Julian_day
*
* @return The Julian day number
*/
private static int get_julian_day_number(date_t date) {
double a, y, m, jdn;
assert (date != null);
a = floor((14.0 - (double) (date.month)) / 12.0);
y = (double) (date.year) + 4800.0 - a;
m = (double) (date.month) + 12.0 * a - 3.0;
jdn = (double) date.day +
floor((153.0 * m + 2.0) / 5.0) +
365.0 * y +
floor(y / 4.0) -
floor(y / 100.0) +
floor(y / 400.0) -
32045.0;
return (int) jdn;
}
/**
* Compute the approximate Sun coordinates from the given Julian Day
* Number jdn according to the method given the US Naval Observatory (USNO)
* on: http://aa.usno.navy.mil/faq/docs/SunApprox.php
* The computed values are stored in struct coord.
*/
private static void get_approx_sun_coord(final int jdn, | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class approx_sun_coord {
// double D; /* Declination of the Sun */
// double EqT; /* The Equation of Time */
// double R; /* The distance of the Sun from the Earth
// in astronomical units (AU) */
// double SD; /* The angular semidiameter of the Sun in degrees */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class date_t {
// int year, month, day;
//
// /**
// * @param day starts from 1
// * @param month starts from 1, like the old ITL
// */
// date_t set(int day, int month, int year) {
// this.year = year;
// this.month = month;
// this.day = day;
// return this;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class location {
// /* In original C: The struct members ordering guarantees that the compiler does
// * not add any padding bytes when compiling for 64-bit machines */
//
// double longitude; /* Observer's longitude */
// double latitude; /* Observer's latitude */
// double altitude; /* Observer's altitude in meters */
// double timezone; /* Observer's timezone (in hours) relative
// to Universal Coordinated Time (UTC) */
// int daylight; /* Daylight Savings Time (DST) Flag
// Set to 1 if DST is on, 0 otherwise */
// AsrMethod asr_method; /* Asr Method: Shafii or Hanafi */
// CalcMethod calc_method; /* Fajr and Isha Calculation method */
// ExtremeMethod extr_method; /* Extreme latitude method */
// String name; /* Observer's location name */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// enum round_t {
// UP, DOWN, NEAREST
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LATITUDE = (21.42249);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LONGITUDE = (39.82620);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double M_PI = (3.141592653589793);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double ONE_MINUTE = (60.0 / 3600.0);
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/PrayerModule.java
import static org.arabeyes.itl.newmethod.DefsModule.ONE_MINUTE;
import org.arabeyes.itl.newmethod.DefsModule.approx_sun_coord;
import org.arabeyes.itl.newmethod.DefsModule.date_t;
import org.arabeyes.itl.newmethod.DefsModule.location;
import org.arabeyes.itl.newmethod.DefsModule.round_t;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan2;
import static java.lang.Math.ceil;
import static java.lang.Math.cos;
import static java.lang.Math.floor;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
import static java.lang.Math.tan;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LATITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LONGITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.M_PI;
* Source: https://en.wikipedia.org/wiki/Julian_day
*
* @return The Julian day number
*/
private static int get_julian_day_number(date_t date) {
double a, y, m, jdn;
assert (date != null);
a = floor((14.0 - (double) (date.month)) / 12.0);
y = (double) (date.year) + 4800.0 - a;
m = (double) (date.month) + 12.0 * a - 3.0;
jdn = (double) date.day +
floor((153.0 * m + 2.0) / 5.0) +
365.0 * y +
floor(y / 4.0) -
floor(y / 100.0) +
floor(y / 400.0) -
32045.0;
return (int) jdn;
}
/**
* Compute the approximate Sun coordinates from the given Julian Day
* Number jdn according to the method given the US Naval Observatory (USNO)
* on: http://aa.usno.navy.mil/faq/docs/SunApprox.php
* The computed values are stored in struct coord.
*/
private static void get_approx_sun_coord(final int jdn, | approx_sun_coord coord) { |
fikr4n/itl-java | itl/src/main/java/org/arabeyes/itl/newmethod/PrayerModule.java | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class approx_sun_coord {
// double D; /* Declination of the Sun */
// double EqT; /* The Equation of Time */
// double R; /* The distance of the Sun from the Earth
// in astronomical units (AU) */
// double SD; /* The angular semidiameter of the Sun in degrees */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class date_t {
// int year, month, day;
//
// /**
// * @param day starts from 1
// * @param month starts from 1, like the old ITL
// */
// date_t set(int day, int month, int year) {
// this.year = year;
// this.month = month;
// this.day = day;
// return this;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class location {
// /* In original C: The struct members ordering guarantees that the compiler does
// * not add any padding bytes when compiling for 64-bit machines */
//
// double longitude; /* Observer's longitude */
// double latitude; /* Observer's latitude */
// double altitude; /* Observer's altitude in meters */
// double timezone; /* Observer's timezone (in hours) relative
// to Universal Coordinated Time (UTC) */
// int daylight; /* Daylight Savings Time (DST) Flag
// Set to 1 if DST is on, 0 otherwise */
// AsrMethod asr_method; /* Asr Method: Shafii or Hanafi */
// CalcMethod calc_method; /* Fajr and Isha Calculation method */
// ExtremeMethod extr_method; /* Extreme latitude method */
// String name; /* Observer's location name */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// enum round_t {
// UP, DOWN, NEAREST
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LATITUDE = (21.42249);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LONGITUDE = (39.82620);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double M_PI = (3.141592653589793);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double ONE_MINUTE = (60.0 / 3600.0);
| import static org.arabeyes.itl.newmethod.DefsModule.ONE_MINUTE;
import org.arabeyes.itl.newmethod.DefsModule.approx_sun_coord;
import org.arabeyes.itl.newmethod.DefsModule.date_t;
import org.arabeyes.itl.newmethod.DefsModule.location;
import org.arabeyes.itl.newmethod.DefsModule.round_t;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan2;
import static java.lang.Math.ceil;
import static java.lang.Math.cos;
import static java.lang.Math.floor;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
import static java.lang.Math.tan;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LATITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LONGITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.M_PI; | double p1 = 1.0 / 15.0;
double p2 = cos(to_radians(latitude)) * cos(to_radians(D));
double p3 = sin(to_radians(latitude)) * sin(to_radians(D));
double p4 = -1.0 * sin(to_radians(alpha));
double p5 = to_degrees(acos((p4 - p3) / p2));
double r = p1 * p5;
return r;
}
/**
* A function used to compute Asr
* Taken from: http://praytimes.org/calculation/
*/
private static double A(final double t,
final double latitude,
final double D) {
double p1 = 1.0 / 15.0;
double p2 = cos(to_radians(latitude)) * cos(to_radians(D));
double p3 = sin(to_radians(latitude)) * sin(to_radians(D));
double p4 = tan(to_radians((latitude - D)));
double p5 = arccot(t + p4);
double p6 = sin(p5);
double p7 = acos((p6 - p3) / p2);
double r = p1 * to_degrees(p7);
return r;
}
/**
* Compute the Dhuhr prayer time
*/ | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class approx_sun_coord {
// double D; /* Declination of the Sun */
// double EqT; /* The Equation of Time */
// double R; /* The distance of the Sun from the Earth
// in astronomical units (AU) */
// double SD; /* The angular semidiameter of the Sun in degrees */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class date_t {
// int year, month, day;
//
// /**
// * @param day starts from 1
// * @param month starts from 1, like the old ITL
// */
// date_t set(int day, int month, int year) {
// this.year = year;
// this.month = month;
// this.day = day;
// return this;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class location {
// /* In original C: The struct members ordering guarantees that the compiler does
// * not add any padding bytes when compiling for 64-bit machines */
//
// double longitude; /* Observer's longitude */
// double latitude; /* Observer's latitude */
// double altitude; /* Observer's altitude in meters */
// double timezone; /* Observer's timezone (in hours) relative
// to Universal Coordinated Time (UTC) */
// int daylight; /* Daylight Savings Time (DST) Flag
// Set to 1 if DST is on, 0 otherwise */
// AsrMethod asr_method; /* Asr Method: Shafii or Hanafi */
// CalcMethod calc_method; /* Fajr and Isha Calculation method */
// ExtremeMethod extr_method; /* Extreme latitude method */
// String name; /* Observer's location name */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// enum round_t {
// UP, DOWN, NEAREST
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LATITUDE = (21.42249);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LONGITUDE = (39.82620);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double M_PI = (3.141592653589793);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double ONE_MINUTE = (60.0 / 3600.0);
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/PrayerModule.java
import static org.arabeyes.itl.newmethod.DefsModule.ONE_MINUTE;
import org.arabeyes.itl.newmethod.DefsModule.approx_sun_coord;
import org.arabeyes.itl.newmethod.DefsModule.date_t;
import org.arabeyes.itl.newmethod.DefsModule.location;
import org.arabeyes.itl.newmethod.DefsModule.round_t;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan2;
import static java.lang.Math.ceil;
import static java.lang.Math.cos;
import static java.lang.Math.floor;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
import static java.lang.Math.tan;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LATITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LONGITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.M_PI;
double p1 = 1.0 / 15.0;
double p2 = cos(to_radians(latitude)) * cos(to_radians(D));
double p3 = sin(to_radians(latitude)) * sin(to_radians(D));
double p4 = -1.0 * sin(to_radians(alpha));
double p5 = to_degrees(acos((p4 - p3) / p2));
double r = p1 * p5;
return r;
}
/**
* A function used to compute Asr
* Taken from: http://praytimes.org/calculation/
*/
private static double A(final double t,
final double latitude,
final double D) {
double p1 = 1.0 / 15.0;
double p2 = cos(to_radians(latitude)) * cos(to_radians(D));
double p3 = sin(to_radians(latitude)) * sin(to_radians(D));
double p4 = tan(to_radians((latitude - D)));
double p5 = arccot(t + p4);
double p6 = sin(p5);
double p7 = acos((p6 - p3) / p2);
double r = p1 * to_degrees(p7);
return r;
}
/**
* Compute the Dhuhr prayer time
*/ | private static double get_dhuhr(location loc, |
fikr4n/itl-java | itl/src/main/java/org/arabeyes/itl/newmethod/PrayerModule.java | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class approx_sun_coord {
// double D; /* Declination of the Sun */
// double EqT; /* The Equation of Time */
// double R; /* The distance of the Sun from the Earth
// in astronomical units (AU) */
// double SD; /* The angular semidiameter of the Sun in degrees */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class date_t {
// int year, month, day;
//
// /**
// * @param day starts from 1
// * @param month starts from 1, like the old ITL
// */
// date_t set(int day, int month, int year) {
// this.year = year;
// this.month = month;
// this.day = day;
// return this;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class location {
// /* In original C: The struct members ordering guarantees that the compiler does
// * not add any padding bytes when compiling for 64-bit machines */
//
// double longitude; /* Observer's longitude */
// double latitude; /* Observer's latitude */
// double altitude; /* Observer's altitude in meters */
// double timezone; /* Observer's timezone (in hours) relative
// to Universal Coordinated Time (UTC) */
// int daylight; /* Daylight Savings Time (DST) Flag
// Set to 1 if DST is on, 0 otherwise */
// AsrMethod asr_method; /* Asr Method: Shafii or Hanafi */
// CalcMethod calc_method; /* Fajr and Isha Calculation method */
// ExtremeMethod extr_method; /* Extreme latitude method */
// String name; /* Observer's location name */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// enum round_t {
// UP, DOWN, NEAREST
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LATITUDE = (21.42249);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LONGITUDE = (39.82620);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double M_PI = (3.141592653589793);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double ONE_MINUTE = (60.0 / 3600.0);
| import static org.arabeyes.itl.newmethod.DefsModule.ONE_MINUTE;
import org.arabeyes.itl.newmethod.DefsModule.approx_sun_coord;
import org.arabeyes.itl.newmethod.DefsModule.date_t;
import org.arabeyes.itl.newmethod.DefsModule.location;
import org.arabeyes.itl.newmethod.DefsModule.round_t;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan2;
import static java.lang.Math.ceil;
import static java.lang.Math.cos;
import static java.lang.Math.floor;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
import static java.lang.Math.tan;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LATITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LONGITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.M_PI; | if (loc.extr_method == ExtremeMethod.NONE) {
/* Normal latitude. Use the classical methods */
fajr = dhuhr - T(loc.calc_method.fajr,
loc.latitude,
coord.D);
} else {
/* TODO: Extreme methods */
throw new UnsupportedOperationException("Extreme methods are not implemented yet");
}
return fajr;
}
/**
* Compute the Isha prayer time
*/
private static double get_isha(final double dhuhr,
final double sunset,
final double sunrise,
location loc,
approx_sun_coord coord) {
double isha = 0.0;
assert (dhuhr > 0.0);
assert (loc != null);
assert (coord != null);
if (loc.extr_method == ExtremeMethod.NONE) {
if (loc.calc_method.isha_type == IshaFlag.OFFSET) {
/* Umm Al-Qura uses a fixed offset */ | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class approx_sun_coord {
// double D; /* Declination of the Sun */
// double EqT; /* The Equation of Time */
// double R; /* The distance of the Sun from the Earth
// in astronomical units (AU) */
// double SD; /* The angular semidiameter of the Sun in degrees */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class date_t {
// int year, month, day;
//
// /**
// * @param day starts from 1
// * @param month starts from 1, like the old ITL
// */
// date_t set(int day, int month, int year) {
// this.year = year;
// this.month = month;
// this.day = day;
// return this;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class location {
// /* In original C: The struct members ordering guarantees that the compiler does
// * not add any padding bytes when compiling for 64-bit machines */
//
// double longitude; /* Observer's longitude */
// double latitude; /* Observer's latitude */
// double altitude; /* Observer's altitude in meters */
// double timezone; /* Observer's timezone (in hours) relative
// to Universal Coordinated Time (UTC) */
// int daylight; /* Daylight Savings Time (DST) Flag
// Set to 1 if DST is on, 0 otherwise */
// AsrMethod asr_method; /* Asr Method: Shafii or Hanafi */
// CalcMethod calc_method; /* Fajr and Isha Calculation method */
// ExtremeMethod extr_method; /* Extreme latitude method */
// String name; /* Observer's location name */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// enum round_t {
// UP, DOWN, NEAREST
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LATITUDE = (21.42249);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LONGITUDE = (39.82620);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double M_PI = (3.141592653589793);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double ONE_MINUTE = (60.0 / 3600.0);
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/PrayerModule.java
import static org.arabeyes.itl.newmethod.DefsModule.ONE_MINUTE;
import org.arabeyes.itl.newmethod.DefsModule.approx_sun_coord;
import org.arabeyes.itl.newmethod.DefsModule.date_t;
import org.arabeyes.itl.newmethod.DefsModule.location;
import org.arabeyes.itl.newmethod.DefsModule.round_t;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan2;
import static java.lang.Math.ceil;
import static java.lang.Math.cos;
import static java.lang.Math.floor;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
import static java.lang.Math.tan;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LATITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LONGITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.M_PI;
if (loc.extr_method == ExtremeMethod.NONE) {
/* Normal latitude. Use the classical methods */
fajr = dhuhr - T(loc.calc_method.fajr,
loc.latitude,
coord.D);
} else {
/* TODO: Extreme methods */
throw new UnsupportedOperationException("Extreme methods are not implemented yet");
}
return fajr;
}
/**
* Compute the Isha prayer time
*/
private static double get_isha(final double dhuhr,
final double sunset,
final double sunrise,
location loc,
approx_sun_coord coord) {
double isha = 0.0;
assert (dhuhr > 0.0);
assert (loc != null);
assert (coord != null);
if (loc.extr_method == ExtremeMethod.NONE) {
if (loc.calc_method.isha_type == IshaFlag.OFFSET) {
/* Umm Al-Qura uses a fixed offset */ | isha = sunset + loc.calc_method.isha * ONE_MINUTE; |
fikr4n/itl-java | itl/src/main/java/org/arabeyes/itl/newmethod/PrayerModule.java | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class approx_sun_coord {
// double D; /* Declination of the Sun */
// double EqT; /* The Equation of Time */
// double R; /* The distance of the Sun from the Earth
// in astronomical units (AU) */
// double SD; /* The angular semidiameter of the Sun in degrees */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class date_t {
// int year, month, day;
//
// /**
// * @param day starts from 1
// * @param month starts from 1, like the old ITL
// */
// date_t set(int day, int month, int year) {
// this.year = year;
// this.month = month;
// this.day = day;
// return this;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class location {
// /* In original C: The struct members ordering guarantees that the compiler does
// * not add any padding bytes when compiling for 64-bit machines */
//
// double longitude; /* Observer's longitude */
// double latitude; /* Observer's latitude */
// double altitude; /* Observer's altitude in meters */
// double timezone; /* Observer's timezone (in hours) relative
// to Universal Coordinated Time (UTC) */
// int daylight; /* Daylight Savings Time (DST) Flag
// Set to 1 if DST is on, 0 otherwise */
// AsrMethod asr_method; /* Asr Method: Shafii or Hanafi */
// CalcMethod calc_method; /* Fajr and Isha Calculation method */
// ExtremeMethod extr_method; /* Extreme latitude method */
// String name; /* Observer's location name */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// enum round_t {
// UP, DOWN, NEAREST
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LATITUDE = (21.42249);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LONGITUDE = (39.82620);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double M_PI = (3.141592653589793);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double ONE_MINUTE = (60.0 / 3600.0);
| import static org.arabeyes.itl.newmethod.DefsModule.ONE_MINUTE;
import org.arabeyes.itl.newmethod.DefsModule.approx_sun_coord;
import org.arabeyes.itl.newmethod.DefsModule.date_t;
import org.arabeyes.itl.newmethod.DefsModule.location;
import org.arabeyes.itl.newmethod.DefsModule.round_t;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan2;
import static java.lang.Math.ceil;
import static java.lang.Math.cos;
import static java.lang.Math.floor;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
import static java.lang.Math.tan;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LATITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LONGITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.M_PI; | assert (dhuhr > 0.0);
assert (loc != null);
assert (coord != null);
if (loc.extr_method == ExtremeMethod.NONE) {
if (loc.calc_method.isha_type == IshaFlag.OFFSET) {
/* Umm Al-Qura uses a fixed offset */
isha = sunset + loc.calc_method.isha * ONE_MINUTE;
} else {
isha = dhuhr + T(loc.calc_method.isha,
loc.latitude,
coord.D);
}
} else {
/* TODO: Extreme latitude */
throw new UnsupportedOperationException("Extreme altitudes are not implemented yet!");
}
isha = normalize(isha, 24.0);
return isha;
}
/**
* Convert a given time in decimal format to
* hh:mm format and store it in the given event struct.
* The minutes part can be rounded up or down based on the
* round flag
*/
private static void conv_time_to_event(final int julian_day,
final double decimal_time, | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class approx_sun_coord {
// double D; /* Declination of the Sun */
// double EqT; /* The Equation of Time */
// double R; /* The distance of the Sun from the Earth
// in astronomical units (AU) */
// double SD; /* The angular semidiameter of the Sun in degrees */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class date_t {
// int year, month, day;
//
// /**
// * @param day starts from 1
// * @param month starts from 1, like the old ITL
// */
// date_t set(int day, int month, int year) {
// this.year = year;
// this.month = month;
// this.day = day;
// return this;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class location {
// /* In original C: The struct members ordering guarantees that the compiler does
// * not add any padding bytes when compiling for 64-bit machines */
//
// double longitude; /* Observer's longitude */
// double latitude; /* Observer's latitude */
// double altitude; /* Observer's altitude in meters */
// double timezone; /* Observer's timezone (in hours) relative
// to Universal Coordinated Time (UTC) */
// int daylight; /* Daylight Savings Time (DST) Flag
// Set to 1 if DST is on, 0 otherwise */
// AsrMethod asr_method; /* Asr Method: Shafii or Hanafi */
// CalcMethod calc_method; /* Fajr and Isha Calculation method */
// ExtremeMethod extr_method; /* Extreme latitude method */
// String name; /* Observer's location name */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// enum round_t {
// UP, DOWN, NEAREST
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LATITUDE = (21.42249);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LONGITUDE = (39.82620);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double M_PI = (3.141592653589793);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double ONE_MINUTE = (60.0 / 3600.0);
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/PrayerModule.java
import static org.arabeyes.itl.newmethod.DefsModule.ONE_MINUTE;
import org.arabeyes.itl.newmethod.DefsModule.approx_sun_coord;
import org.arabeyes.itl.newmethod.DefsModule.date_t;
import org.arabeyes.itl.newmethod.DefsModule.location;
import org.arabeyes.itl.newmethod.DefsModule.round_t;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan2;
import static java.lang.Math.ceil;
import static java.lang.Math.cos;
import static java.lang.Math.floor;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
import static java.lang.Math.tan;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LATITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LONGITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.M_PI;
assert (dhuhr > 0.0);
assert (loc != null);
assert (coord != null);
if (loc.extr_method == ExtremeMethod.NONE) {
if (loc.calc_method.isha_type == IshaFlag.OFFSET) {
/* Umm Al-Qura uses a fixed offset */
isha = sunset + loc.calc_method.isha * ONE_MINUTE;
} else {
isha = dhuhr + T(loc.calc_method.isha,
loc.latitude,
coord.D);
}
} else {
/* TODO: Extreme latitude */
throw new UnsupportedOperationException("Extreme altitudes are not implemented yet!");
}
isha = normalize(isha, 24.0);
return isha;
}
/**
* Convert a given time in decimal format to
* hh:mm format and store it in the given event struct.
* The minutes part can be rounded up or down based on the
* round flag
*/
private static void conv_time_to_event(final int julian_day,
final double decimal_time, | final round_t rounding, |
fikr4n/itl-java | itl/src/main/java/org/arabeyes/itl/newmethod/PrayerModule.java | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class approx_sun_coord {
// double D; /* Declination of the Sun */
// double EqT; /* The Equation of Time */
// double R; /* The distance of the Sun from the Earth
// in astronomical units (AU) */
// double SD; /* The angular semidiameter of the Sun in degrees */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class date_t {
// int year, month, day;
//
// /**
// * @param day starts from 1
// * @param month starts from 1, like the old ITL
// */
// date_t set(int day, int month, int year) {
// this.year = year;
// this.month = month;
// this.day = day;
// return this;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class location {
// /* In original C: The struct members ordering guarantees that the compiler does
// * not add any padding bytes when compiling for 64-bit machines */
//
// double longitude; /* Observer's longitude */
// double latitude; /* Observer's latitude */
// double altitude; /* Observer's altitude in meters */
// double timezone; /* Observer's timezone (in hours) relative
// to Universal Coordinated Time (UTC) */
// int daylight; /* Daylight Savings Time (DST) Flag
// Set to 1 if DST is on, 0 otherwise */
// AsrMethod asr_method; /* Asr Method: Shafii or Hanafi */
// CalcMethod calc_method; /* Fajr and Isha Calculation method */
// ExtremeMethod extr_method; /* Extreme latitude method */
// String name; /* Observer's location name */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// enum round_t {
// UP, DOWN, NEAREST
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LATITUDE = (21.42249);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LONGITUDE = (39.82620);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double M_PI = (3.141592653589793);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double ONE_MINUTE = (60.0 / 3600.0);
| import static org.arabeyes.itl.newmethod.DefsModule.ONE_MINUTE;
import org.arabeyes.itl.newmethod.DefsModule.approx_sun_coord;
import org.arabeyes.itl.newmethod.DefsModule.date_t;
import org.arabeyes.itl.newmethod.DefsModule.location;
import org.arabeyes.itl.newmethod.DefsModule.round_t;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan2;
import static java.lang.Math.ceil;
import static java.lang.Math.cos;
import static java.lang.Math.floor;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
import static java.lang.Math.tan;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LATITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LONGITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.M_PI; | assert (rounding == round_t.UP ||
rounding == round_t.DOWN ||
rounding == round_t.NEAREST);
t.julian_day = julian_day;
f = floor(decimal_time);
t.hour = (int) f;
r = (decimal_time - f) * 60.0;
switch (rounding) {
case UP:
t.minute = (int) (ceil(r));
break;
case DOWN:
t.minute = (int) (floor(r));
break;
case NEAREST:
t.minute = (int) (custom_round(r));
break;
}
}
/**
* Compute the Qibla direction from North clockwise
* using the Equation (1) given in references/qibla.pdf
*/
static double get_qibla_direction(location loc) {
double p1, p2, p3, qibla;
assert (loc != null);
| // Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class approx_sun_coord {
// double D; /* Declination of the Sun */
// double EqT; /* The Equation of Time */
// double R; /* The distance of the Sun from the Earth
// in astronomical units (AU) */
// double SD; /* The angular semidiameter of the Sun in degrees */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class date_t {
// int year, month, day;
//
// /**
// * @param day starts from 1
// * @param month starts from 1, like the old ITL
// */
// date_t set(int day, int month, int year) {
// this.year = year;
// this.month = month;
// this.day = day;
// return this;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class location {
// /* In original C: The struct members ordering guarantees that the compiler does
// * not add any padding bytes when compiling for 64-bit machines */
//
// double longitude; /* Observer's longitude */
// double latitude; /* Observer's latitude */
// double altitude; /* Observer's altitude in meters */
// double timezone; /* Observer's timezone (in hours) relative
// to Universal Coordinated Time (UTC) */
// int daylight; /* Daylight Savings Time (DST) Flag
// Set to 1 if DST is on, 0 otherwise */
// AsrMethod asr_method; /* Asr Method: Shafii or Hanafi */
// CalcMethod calc_method; /* Fajr and Isha Calculation method */
// ExtremeMethod extr_method; /* Extreme latitude method */
// String name; /* Observer's location name */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// enum round_t {
// UP, DOWN, NEAREST
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LATITUDE = (21.42249);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LONGITUDE = (39.82620);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double M_PI = (3.141592653589793);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double ONE_MINUTE = (60.0 / 3600.0);
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/PrayerModule.java
import static org.arabeyes.itl.newmethod.DefsModule.ONE_MINUTE;
import org.arabeyes.itl.newmethod.DefsModule.approx_sun_coord;
import org.arabeyes.itl.newmethod.DefsModule.date_t;
import org.arabeyes.itl.newmethod.DefsModule.location;
import org.arabeyes.itl.newmethod.DefsModule.round_t;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan2;
import static java.lang.Math.ceil;
import static java.lang.Math.cos;
import static java.lang.Math.floor;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
import static java.lang.Math.tan;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LATITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LONGITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.M_PI;
assert (rounding == round_t.UP ||
rounding == round_t.DOWN ||
rounding == round_t.NEAREST);
t.julian_day = julian_day;
f = floor(decimal_time);
t.hour = (int) f;
r = (decimal_time - f) * 60.0;
switch (rounding) {
case UP:
t.minute = (int) (ceil(r));
break;
case DOWN:
t.minute = (int) (floor(r));
break;
case NEAREST:
t.minute = (int) (custom_round(r));
break;
}
}
/**
* Compute the Qibla direction from North clockwise
* using the Equation (1) given in references/qibla.pdf
*/
static double get_qibla_direction(location loc) {
double p1, p2, p3, qibla;
assert (loc != null);
| p1 = sin(to_radians(KAABA_LONGITUDE - loc.longitude)); |
fikr4n/itl-java | itl/src/main/java/org/arabeyes/itl/newmethod/PrayerModule.java | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class approx_sun_coord {
// double D; /* Declination of the Sun */
// double EqT; /* The Equation of Time */
// double R; /* The distance of the Sun from the Earth
// in astronomical units (AU) */
// double SD; /* The angular semidiameter of the Sun in degrees */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class date_t {
// int year, month, day;
//
// /**
// * @param day starts from 1
// * @param month starts from 1, like the old ITL
// */
// date_t set(int day, int month, int year) {
// this.year = year;
// this.month = month;
// this.day = day;
// return this;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class location {
// /* In original C: The struct members ordering guarantees that the compiler does
// * not add any padding bytes when compiling for 64-bit machines */
//
// double longitude; /* Observer's longitude */
// double latitude; /* Observer's latitude */
// double altitude; /* Observer's altitude in meters */
// double timezone; /* Observer's timezone (in hours) relative
// to Universal Coordinated Time (UTC) */
// int daylight; /* Daylight Savings Time (DST) Flag
// Set to 1 if DST is on, 0 otherwise */
// AsrMethod asr_method; /* Asr Method: Shafii or Hanafi */
// CalcMethod calc_method; /* Fajr and Isha Calculation method */
// ExtremeMethod extr_method; /* Extreme latitude method */
// String name; /* Observer's location name */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// enum round_t {
// UP, DOWN, NEAREST
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LATITUDE = (21.42249);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LONGITUDE = (39.82620);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double M_PI = (3.141592653589793);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double ONE_MINUTE = (60.0 / 3600.0);
| import static org.arabeyes.itl.newmethod.DefsModule.ONE_MINUTE;
import org.arabeyes.itl.newmethod.DefsModule.approx_sun_coord;
import org.arabeyes.itl.newmethod.DefsModule.date_t;
import org.arabeyes.itl.newmethod.DefsModule.location;
import org.arabeyes.itl.newmethod.DefsModule.round_t;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan2;
import static java.lang.Math.ceil;
import static java.lang.Math.cos;
import static java.lang.Math.floor;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
import static java.lang.Math.tan;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LATITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LONGITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.M_PI; | rounding == round_t.NEAREST);
t.julian_day = julian_day;
f = floor(decimal_time);
t.hour = (int) f;
r = (decimal_time - f) * 60.0;
switch (rounding) {
case UP:
t.minute = (int) (ceil(r));
break;
case DOWN:
t.minute = (int) (floor(r));
break;
case NEAREST:
t.minute = (int) (custom_round(r));
break;
}
}
/**
* Compute the Qibla direction from North clockwise
* using the Equation (1) given in references/qibla.pdf
*/
static double get_qibla_direction(location loc) {
double p1, p2, p3, qibla;
assert (loc != null);
p1 = sin(to_radians(KAABA_LONGITUDE - loc.longitude));
p2 = cos(to_radians(loc.latitude)) * | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class approx_sun_coord {
// double D; /* Declination of the Sun */
// double EqT; /* The Equation of Time */
// double R; /* The distance of the Sun from the Earth
// in astronomical units (AU) */
// double SD; /* The angular semidiameter of the Sun in degrees */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class date_t {
// int year, month, day;
//
// /**
// * @param day starts from 1
// * @param month starts from 1, like the old ITL
// */
// date_t set(int day, int month, int year) {
// this.year = year;
// this.month = month;
// this.day = day;
// return this;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class location {
// /* In original C: The struct members ordering guarantees that the compiler does
// * not add any padding bytes when compiling for 64-bit machines */
//
// double longitude; /* Observer's longitude */
// double latitude; /* Observer's latitude */
// double altitude; /* Observer's altitude in meters */
// double timezone; /* Observer's timezone (in hours) relative
// to Universal Coordinated Time (UTC) */
// int daylight; /* Daylight Savings Time (DST) Flag
// Set to 1 if DST is on, 0 otherwise */
// AsrMethod asr_method; /* Asr Method: Shafii or Hanafi */
// CalcMethod calc_method; /* Fajr and Isha Calculation method */
// ExtremeMethod extr_method; /* Extreme latitude method */
// String name; /* Observer's location name */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// enum round_t {
// UP, DOWN, NEAREST
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LATITUDE = (21.42249);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double KAABA_LONGITUDE = (39.82620);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double M_PI = (3.141592653589793);
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static final double ONE_MINUTE = (60.0 / 3600.0);
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/PrayerModule.java
import static org.arabeyes.itl.newmethod.DefsModule.ONE_MINUTE;
import org.arabeyes.itl.newmethod.DefsModule.approx_sun_coord;
import org.arabeyes.itl.newmethod.DefsModule.date_t;
import org.arabeyes.itl.newmethod.DefsModule.location;
import org.arabeyes.itl.newmethod.DefsModule.round_t;
import static java.lang.Math.acos;
import static java.lang.Math.asin;
import static java.lang.Math.atan2;
import static java.lang.Math.ceil;
import static java.lang.Math.cos;
import static java.lang.Math.floor;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
import static java.lang.Math.tan;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LATITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.KAABA_LONGITUDE;
import static org.arabeyes.itl.newmethod.DefsModule.M_PI;
rounding == round_t.NEAREST);
t.julian_day = julian_day;
f = floor(decimal_time);
t.hour = (int) f;
r = (decimal_time - f) * 60.0;
switch (rounding) {
case UP:
t.minute = (int) (ceil(r));
break;
case DOWN:
t.minute = (int) (floor(r));
break;
case NEAREST:
t.minute = (int) (custom_round(r));
break;
}
}
/**
* Compute the Qibla direction from North clockwise
* using the Equation (1) given in references/qibla.pdf
*/
static double get_qibla_direction(location loc) {
double p1, p2, p3, qibla;
assert (loc != null);
p1 = sin(to_radians(KAABA_LONGITUDE - loc.longitude));
p2 = cos(to_radians(loc.latitude)) * | tan(to_radians(KAABA_LATITUDE)); |
fikr4n/itl-java | itl/src/main/java/org/arabeyes/itl/newmethod/ConfigModule.java | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class date_t {
// int year, month, day;
//
// /**
// * @param day starts from 1
// * @param month starts from 1, like the old ITL
// */
// date_t set(int day, int month, int year) {
// this.year = year;
// this.month = month;
// this.day = day;
// return this;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class location {
// /* In original C: The struct members ordering guarantees that the compiler does
// * not add any padding bytes when compiling for 64-bit machines */
//
// double longitude; /* Observer's longitude */
// double latitude; /* Observer's latitude */
// double altitude; /* Observer's altitude in meters */
// double timezone; /* Observer's timezone (in hours) relative
// to Universal Coordinated Time (UTC) */
// int daylight; /* Daylight Savings Time (DST) Flag
// Set to 1 if DST is on, 0 otherwise */
// AsrMethod asr_method; /* Asr Method: Shafii or Hanafi */
// CalcMethod calc_method; /* Fajr and Isha Calculation method */
// ExtremeMethod extr_method; /* Extreme latitude method */
// String name; /* Observer's location name */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/PrayerModule.java
// static CalcMethod calc_methods[] = {
// new CalcMethod(MethodId.MWL, "Muslim World League (MWL)",
// IshaFlag.ANGLE, 18, 17),
// new CalcMethod(MethodId.ISNA, "Islamic Society of North America (ISNA)",
// IshaFlag.ANGLE, 15, 15),
// new CalcMethod(MethodId.EGAS, "Egyptian General Authority of Survey",
// IshaFlag.ANGLE, 19.5, 17.5),
// new CalcMethod(MethodId.UMAQ, "Umm Al-Qura University, Makkah",
// IshaFlag.OFFSET, 18.5, 90),
// new CalcMethod(MethodId.UIS, "University of Islamic Sciences, Karachi",
// IshaFlag.ANGLE, 18, 18)
// };
| import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.arabeyes.itl.newmethod.PrayerModule.calc_methods;
import org.arabeyes.itl.newmethod.DefsModule.date_t;
import org.arabeyes.itl.newmethod.DefsModule.location;
import java.io.BufferedReader;
import java.io.FileReader; | static {
valid_keys.name = "name";
valid_keys.latitude = "latitude";
valid_keys.longitude = "longitude";
valid_keys.altitude = "altitude";
valid_keys.asr_method = "asr_method";
valid_keys.calc_method = "calc_method";
valid_keys.extr_method = "extr_method";
valid_keys.timezone = "timezone";
valid_keys.daylight = "daylight";
}
/**
* Trims the leading and trailing whitespace from a string
* Original C: Taken from: http://stackoverflow.com/a/122721
* Java: slightly different in defining what space is
*
* @return Trimmed string
*/
private static String trim_whitespace(String str) {
return str.trim();
}
/**
* Adds a new <key,value> pair to the loc struct
*
* @return 0 if successful, 1 otherwise
*/
private static int add_key_value(String key,
String value, | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class date_t {
// int year, month, day;
//
// /**
// * @param day starts from 1
// * @param month starts from 1, like the old ITL
// */
// date_t set(int day, int month, int year) {
// this.year = year;
// this.month = month;
// this.day = day;
// return this;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class location {
// /* In original C: The struct members ordering guarantees that the compiler does
// * not add any padding bytes when compiling for 64-bit machines */
//
// double longitude; /* Observer's longitude */
// double latitude; /* Observer's latitude */
// double altitude; /* Observer's altitude in meters */
// double timezone; /* Observer's timezone (in hours) relative
// to Universal Coordinated Time (UTC) */
// int daylight; /* Daylight Savings Time (DST) Flag
// Set to 1 if DST is on, 0 otherwise */
// AsrMethod asr_method; /* Asr Method: Shafii or Hanafi */
// CalcMethod calc_method; /* Fajr and Isha Calculation method */
// ExtremeMethod extr_method; /* Extreme latitude method */
// String name; /* Observer's location name */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/PrayerModule.java
// static CalcMethod calc_methods[] = {
// new CalcMethod(MethodId.MWL, "Muslim World League (MWL)",
// IshaFlag.ANGLE, 18, 17),
// new CalcMethod(MethodId.ISNA, "Islamic Society of North America (ISNA)",
// IshaFlag.ANGLE, 15, 15),
// new CalcMethod(MethodId.EGAS, "Egyptian General Authority of Survey",
// IshaFlag.ANGLE, 19.5, 17.5),
// new CalcMethod(MethodId.UMAQ, "Umm Al-Qura University, Makkah",
// IshaFlag.OFFSET, 18.5, 90),
// new CalcMethod(MethodId.UIS, "University of Islamic Sciences, Karachi",
// IshaFlag.ANGLE, 18, 18)
// };
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/ConfigModule.java
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.arabeyes.itl.newmethod.PrayerModule.calc_methods;
import org.arabeyes.itl.newmethod.DefsModule.date_t;
import org.arabeyes.itl.newmethod.DefsModule.location;
import java.io.BufferedReader;
import java.io.FileReader;
static {
valid_keys.name = "name";
valid_keys.latitude = "latitude";
valid_keys.longitude = "longitude";
valid_keys.altitude = "altitude";
valid_keys.asr_method = "asr_method";
valid_keys.calc_method = "calc_method";
valid_keys.extr_method = "extr_method";
valid_keys.timezone = "timezone";
valid_keys.daylight = "daylight";
}
/**
* Trims the leading and trailing whitespace from a string
* Original C: Taken from: http://stackoverflow.com/a/122721
* Java: slightly different in defining what space is
*
* @return Trimmed string
*/
private static String trim_whitespace(String str) {
return str.trim();
}
/**
* Adds a new <key,value> pair to the loc struct
*
* @return 0 if successful, 1 otherwise
*/
private static int add_key_value(String key,
String value, | location loc) { |
fikr4n/itl-java | itl/src/main/java/org/arabeyes/itl/newmethod/ConfigModule.java | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class date_t {
// int year, month, day;
//
// /**
// * @param day starts from 1
// * @param month starts from 1, like the old ITL
// */
// date_t set(int day, int month, int year) {
// this.year = year;
// this.month = month;
// this.day = day;
// return this;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class location {
// /* In original C: The struct members ordering guarantees that the compiler does
// * not add any padding bytes when compiling for 64-bit machines */
//
// double longitude; /* Observer's longitude */
// double latitude; /* Observer's latitude */
// double altitude; /* Observer's altitude in meters */
// double timezone; /* Observer's timezone (in hours) relative
// to Universal Coordinated Time (UTC) */
// int daylight; /* Daylight Savings Time (DST) Flag
// Set to 1 if DST is on, 0 otherwise */
// AsrMethod asr_method; /* Asr Method: Shafii or Hanafi */
// CalcMethod calc_method; /* Fajr and Isha Calculation method */
// ExtremeMethod extr_method; /* Extreme latitude method */
// String name; /* Observer's location name */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/PrayerModule.java
// static CalcMethod calc_methods[] = {
// new CalcMethod(MethodId.MWL, "Muslim World League (MWL)",
// IshaFlag.ANGLE, 18, 17),
// new CalcMethod(MethodId.ISNA, "Islamic Society of North America (ISNA)",
// IshaFlag.ANGLE, 15, 15),
// new CalcMethod(MethodId.EGAS, "Egyptian General Authority of Survey",
// IshaFlag.ANGLE, 19.5, 17.5),
// new CalcMethod(MethodId.UMAQ, "Umm Al-Qura University, Makkah",
// IshaFlag.OFFSET, 18.5, 90),
// new CalcMethod(MethodId.UIS, "University of Islamic Sciences, Karachi",
// IshaFlag.ANGLE, 18, 18)
// };
| import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.arabeyes.itl.newmethod.PrayerModule.calc_methods;
import org.arabeyes.itl.newmethod.DefsModule.date_t;
import org.arabeyes.itl.newmethod.DefsModule.location;
import java.io.BufferedReader;
import java.io.FileReader; | return str.trim();
}
/**
* Adds a new <key,value> pair to the loc struct
*
* @return 0 if successful, 1 otherwise
*/
private static int add_key_value(String key,
String value,
location loc) {
int method_id;
assert (key != null);
assert (value != null);
assert (loc != null);
try {
if (valid_keys.name.equals(key)) {
loc.name = value;
} else if (valid_keys.latitude.equals(key)) {
loc.latitude = Double.parseDouble(value);
} else if (valid_keys.longitude.equals(key)) {
loc.longitude = Double.parseDouble(value);
} else if (valid_keys.altitude.equals(key)) {
loc.altitude = Double.parseDouble(value);
} else if (valid_keys.asr_method.equals(key)) {
loc.asr_method = AsrMethod.values()[Integer.parseInt(value)];
} else if (valid_keys.calc_method.equals(key)) {
method_id = Integer.parseInt(value); | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class date_t {
// int year, month, day;
//
// /**
// * @param day starts from 1
// * @param month starts from 1, like the old ITL
// */
// date_t set(int day, int month, int year) {
// this.year = year;
// this.month = month;
// this.day = day;
// return this;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class location {
// /* In original C: The struct members ordering guarantees that the compiler does
// * not add any padding bytes when compiling for 64-bit machines */
//
// double longitude; /* Observer's longitude */
// double latitude; /* Observer's latitude */
// double altitude; /* Observer's altitude in meters */
// double timezone; /* Observer's timezone (in hours) relative
// to Universal Coordinated Time (UTC) */
// int daylight; /* Daylight Savings Time (DST) Flag
// Set to 1 if DST is on, 0 otherwise */
// AsrMethod asr_method; /* Asr Method: Shafii or Hanafi */
// CalcMethod calc_method; /* Fajr and Isha Calculation method */
// ExtremeMethod extr_method; /* Extreme latitude method */
// String name; /* Observer's location name */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/PrayerModule.java
// static CalcMethod calc_methods[] = {
// new CalcMethod(MethodId.MWL, "Muslim World League (MWL)",
// IshaFlag.ANGLE, 18, 17),
// new CalcMethod(MethodId.ISNA, "Islamic Society of North America (ISNA)",
// IshaFlag.ANGLE, 15, 15),
// new CalcMethod(MethodId.EGAS, "Egyptian General Authority of Survey",
// IshaFlag.ANGLE, 19.5, 17.5),
// new CalcMethod(MethodId.UMAQ, "Umm Al-Qura University, Makkah",
// IshaFlag.OFFSET, 18.5, 90),
// new CalcMethod(MethodId.UIS, "University of Islamic Sciences, Karachi",
// IshaFlag.ANGLE, 18, 18)
// };
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/ConfigModule.java
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.arabeyes.itl.newmethod.PrayerModule.calc_methods;
import org.arabeyes.itl.newmethod.DefsModule.date_t;
import org.arabeyes.itl.newmethod.DefsModule.location;
import java.io.BufferedReader;
import java.io.FileReader;
return str.trim();
}
/**
* Adds a new <key,value> pair to the loc struct
*
* @return 0 if successful, 1 otherwise
*/
private static int add_key_value(String key,
String value,
location loc) {
int method_id;
assert (key != null);
assert (value != null);
assert (loc != null);
try {
if (valid_keys.name.equals(key)) {
loc.name = value;
} else if (valid_keys.latitude.equals(key)) {
loc.latitude = Double.parseDouble(value);
} else if (valid_keys.longitude.equals(key)) {
loc.longitude = Double.parseDouble(value);
} else if (valid_keys.altitude.equals(key)) {
loc.altitude = Double.parseDouble(value);
} else if (valid_keys.asr_method.equals(key)) {
loc.asr_method = AsrMethod.values()[Integer.parseInt(value)];
} else if (valid_keys.calc_method.equals(key)) {
method_id = Integer.parseInt(value); | loc.calc_method = calc_methods[method_id]; |
fikr4n/itl-java | itl/src/main/java/org/arabeyes/itl/newmethod/ConfigModule.java | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class date_t {
// int year, month, day;
//
// /**
// * @param day starts from 1
// * @param month starts from 1, like the old ITL
// */
// date_t set(int day, int month, int year) {
// this.year = year;
// this.month = month;
// this.day = day;
// return this;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class location {
// /* In original C: The struct members ordering guarantees that the compiler does
// * not add any padding bytes when compiling for 64-bit machines */
//
// double longitude; /* Observer's longitude */
// double latitude; /* Observer's latitude */
// double altitude; /* Observer's altitude in meters */
// double timezone; /* Observer's timezone (in hours) relative
// to Universal Coordinated Time (UTC) */
// int daylight; /* Daylight Savings Time (DST) Flag
// Set to 1 if DST is on, 0 otherwise */
// AsrMethod asr_method; /* Asr Method: Shafii or Hanafi */
// CalcMethod calc_method; /* Fajr and Isha Calculation method */
// ExtremeMethod extr_method; /* Extreme latitude method */
// String name; /* Observer's location name */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/PrayerModule.java
// static CalcMethod calc_methods[] = {
// new CalcMethod(MethodId.MWL, "Muslim World League (MWL)",
// IshaFlag.ANGLE, 18, 17),
// new CalcMethod(MethodId.ISNA, "Islamic Society of North America (ISNA)",
// IshaFlag.ANGLE, 15, 15),
// new CalcMethod(MethodId.EGAS, "Egyptian General Authority of Survey",
// IshaFlag.ANGLE, 19.5, 17.5),
// new CalcMethod(MethodId.UMAQ, "Umm Al-Qura University, Makkah",
// IshaFlag.OFFSET, 18.5, 90),
// new CalcMethod(MethodId.UIS, "University of Islamic Sciences, Karachi",
// IshaFlag.ANGLE, 18, 18)
// };
| import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.arabeyes.itl.newmethod.PrayerModule.calc_methods;
import org.arabeyes.itl.newmethod.DefsModule.date_t;
import org.arabeyes.itl.newmethod.DefsModule.location;
import java.io.BufferedReader;
import java.io.FileReader; | while ((line = fp.readLine()) != null) {
String[] tokens = line.split(delimiter);
if (tokens.length < 2) throw new IOException();
key = tokens[0];
key = trim_whitespace(key);
value = tokens[1];
value = trim_whitespace(value);
r = add_key_value(key, value, loc);
if (r != 0) throw new IOException();
}
fp.close();
return 0;
} catch (IOException e) {
try {
if (fp != null) fp.close();
} catch (IOException ignored) {
assert false;
}
return 1;
}
}
/**
* Parses the command line arguments and constructs the loc
* data structure out of it
*
* @return 0 if all went fine, 1 otherwise
*/
static int parse_arguments(String[] args,
location loc, | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class date_t {
// int year, month, day;
//
// /**
// * @param day starts from 1
// * @param month starts from 1, like the old ITL
// */
// date_t set(int day, int month, int year) {
// this.year = year;
// this.month = month;
// this.day = day;
// return this;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/DefsModule.java
// static class location {
// /* In original C: The struct members ordering guarantees that the compiler does
// * not add any padding bytes when compiling for 64-bit machines */
//
// double longitude; /* Observer's longitude */
// double latitude; /* Observer's latitude */
// double altitude; /* Observer's altitude in meters */
// double timezone; /* Observer's timezone (in hours) relative
// to Universal Coordinated Time (UTC) */
// int daylight; /* Daylight Savings Time (DST) Flag
// Set to 1 if DST is on, 0 otherwise */
// AsrMethod asr_method; /* Asr Method: Shafii or Hanafi */
// CalcMethod calc_method; /* Fajr and Isha Calculation method */
// ExtremeMethod extr_method; /* Extreme latitude method */
// String name; /* Observer's location name */
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/PrayerModule.java
// static CalcMethod calc_methods[] = {
// new CalcMethod(MethodId.MWL, "Muslim World League (MWL)",
// IshaFlag.ANGLE, 18, 17),
// new CalcMethod(MethodId.ISNA, "Islamic Society of North America (ISNA)",
// IshaFlag.ANGLE, 15, 15),
// new CalcMethod(MethodId.EGAS, "Egyptian General Authority of Survey",
// IshaFlag.ANGLE, 19.5, 17.5),
// new CalcMethod(MethodId.UMAQ, "Umm Al-Qura University, Makkah",
// IshaFlag.OFFSET, 18.5, 90),
// new CalcMethod(MethodId.UIS, "University of Islamic Sciences, Karachi",
// IshaFlag.ANGLE, 18, 18)
// };
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/ConfigModule.java
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.arabeyes.itl.newmethod.PrayerModule.calc_methods;
import org.arabeyes.itl.newmethod.DefsModule.date_t;
import org.arabeyes.itl.newmethod.DefsModule.location;
import java.io.BufferedReader;
import java.io.FileReader;
while ((line = fp.readLine()) != null) {
String[] tokens = line.split(delimiter);
if (tokens.length < 2) throw new IOException();
key = tokens[0];
key = trim_whitespace(key);
value = tokens[1];
value = trim_whitespace(value);
r = add_key_value(key, value, loc);
if (r != 0) throw new IOException();
}
fp.close();
return 0;
} catch (IOException e) {
try {
if (fp != null) fp.close();
} catch (IOException ignored) {
assert false;
}
return 1;
}
}
/**
* Parses the command line arguments and constructs the loc
* data structure out of it
*
* @return 0 if all went fine, 1 otherwise
*/
static int parse_arguments(String[] args,
location loc, | date_t date, |
fikr4n/itl-java | app/src/main/java/example/NewMethod.java | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/MethodId.java
// public enum MethodId {MWL, ISNA, EGAS, UMAQ, UIS}
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/Prayer.java
// public class Prayer {
// private DefsModule.date_t date;
// private DefsModule.location location;
//
// public Prayer() {
// location = new DefsModule.location();
// location.latitude = Double.NaN;
// location.longitude = Double.NaN;
// location.extr_method = ExtremeMethod.NONE;
// location.asr_method = AsrMethod.SHAFII;
// }
//
// private void requireLocation() {
// if (Double.isNaN(location.latitude) || Double.isNaN(location.longitude))
// throw new IllegalStateException("Location is not set");
// }
//
// private void requireMethods() {
// if (location.asr_method == null || location.calc_method == null ||
// location.extr_method == null)
// throw new IllegalStateException("Method is not set");
// }
//
// private void requireDate() {
// if (date == null)
// throw new IllegalStateException("Date is not set");
// }
//
// public Prayer setCalculationMethod(CalcMethod method) {
// this.location.calc_method = method;
// return this;
// }
//
// public Prayer setCalculationMethod(MethodId method) {
// for (CalcMethod i : PrayerModule.calc_methods) {
// if (i.id == method) {
// setCalculationMethod(i);
// return this;
// }
// }
// throw new IllegalArgumentException("Unknown method: " + method);
// }
//
// /**
// * Default value is {@link AsrMethod#SHAFII}
// */
// public Prayer setAsrMethod(AsrMethod method) {
// this.location.asr_method = method;
// return this;
// }
//
// /**
// * Default value is {@link ExtremeMethod#NONE}
// */
// public Prayer setExtremeMethod(ExtremeMethod method) {
// this.location.extr_method = method;
// return this;
// }
//
// public Prayer setLocation(double latitude, double longitude, double altitude) {
// location.latitude = latitude;
// location.longitude = longitude;
// location.altitude = altitude;
// return this;
// }
//
// public Prayer setDate(GregorianCalendar cal) {
// this.date = new DefsModule.date_t().set(cal.get(Calendar.DAY_OF_MONTH),
// cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR));
// this.location.timezone = cal.get(Calendar.ZONE_OFFSET) / (1000.0 * 60 * 60);
// this.location.daylight = (int) Math.round(cal.get(Calendar.DST_OFFSET) / (1000.0 * 60 * 60));
// return this;
// }
//
// public Prayer setDate(Date date, TimeZone timeZone) {
// GregorianCalendar cal = new GregorianCalendar(timeZone);
// cal.setTime(date);
// return setDate(cal);
// }
//
// public PrayerTimes getPrayerTimes() {
// requireMethods();
// requireDate();
// requireLocation();
//
// PrayerTimes result = new PrayerTimes();
// PrayerModule.get_prayer_times(date, location, result);
// return result;
// }
//
// public Dms getQiblaDirection() {
// requireLocation();
// return Dms.fromDecimal(PrayerModule.get_qibla_direction(location));
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/PrayerTimes.java
// public class PrayerTimes {
// Event fajr = new Event();
// Event sunrise = new Event();
// Event dhuhr = new Event();
// Event asr = new Event();
// Event maghrib = new Event();
// Event isha = new Event();
//
// public Event getFajr() {
// return fajr;
// }
//
// public Event getSunrise() {
// return sunrise;
// }
//
// public Event getDhuhr() {
// return dhuhr;
// }
//
// public Event getAsr() {
// return asr;
// }
//
// public Event getMaghrib() {
// return maghrib;
// }
//
// public Event getIsha() {
// return isha;
// }
// }
| import org.arabeyes.itl.newmethod.MethodId;
import org.arabeyes.itl.newmethod.Prayer;
import org.arabeyes.itl.newmethod.PrayerTimes;
import java.util.GregorianCalendar; | package example;
public class NewMethod {
public static void main(String[] args) {
System.out.println("=== PRAYER TIME (NEW METHOD) ===");
| // Path: itl/src/main/java/org/arabeyes/itl/newmethod/MethodId.java
// public enum MethodId {MWL, ISNA, EGAS, UMAQ, UIS}
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/Prayer.java
// public class Prayer {
// private DefsModule.date_t date;
// private DefsModule.location location;
//
// public Prayer() {
// location = new DefsModule.location();
// location.latitude = Double.NaN;
// location.longitude = Double.NaN;
// location.extr_method = ExtremeMethod.NONE;
// location.asr_method = AsrMethod.SHAFII;
// }
//
// private void requireLocation() {
// if (Double.isNaN(location.latitude) || Double.isNaN(location.longitude))
// throw new IllegalStateException("Location is not set");
// }
//
// private void requireMethods() {
// if (location.asr_method == null || location.calc_method == null ||
// location.extr_method == null)
// throw new IllegalStateException("Method is not set");
// }
//
// private void requireDate() {
// if (date == null)
// throw new IllegalStateException("Date is not set");
// }
//
// public Prayer setCalculationMethod(CalcMethod method) {
// this.location.calc_method = method;
// return this;
// }
//
// public Prayer setCalculationMethod(MethodId method) {
// for (CalcMethod i : PrayerModule.calc_methods) {
// if (i.id == method) {
// setCalculationMethod(i);
// return this;
// }
// }
// throw new IllegalArgumentException("Unknown method: " + method);
// }
//
// /**
// * Default value is {@link AsrMethod#SHAFII}
// */
// public Prayer setAsrMethod(AsrMethod method) {
// this.location.asr_method = method;
// return this;
// }
//
// /**
// * Default value is {@link ExtremeMethod#NONE}
// */
// public Prayer setExtremeMethod(ExtremeMethod method) {
// this.location.extr_method = method;
// return this;
// }
//
// public Prayer setLocation(double latitude, double longitude, double altitude) {
// location.latitude = latitude;
// location.longitude = longitude;
// location.altitude = altitude;
// return this;
// }
//
// public Prayer setDate(GregorianCalendar cal) {
// this.date = new DefsModule.date_t().set(cal.get(Calendar.DAY_OF_MONTH),
// cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR));
// this.location.timezone = cal.get(Calendar.ZONE_OFFSET) / (1000.0 * 60 * 60);
// this.location.daylight = (int) Math.round(cal.get(Calendar.DST_OFFSET) / (1000.0 * 60 * 60));
// return this;
// }
//
// public Prayer setDate(Date date, TimeZone timeZone) {
// GregorianCalendar cal = new GregorianCalendar(timeZone);
// cal.setTime(date);
// return setDate(cal);
// }
//
// public PrayerTimes getPrayerTimes() {
// requireMethods();
// requireDate();
// requireLocation();
//
// PrayerTimes result = new PrayerTimes();
// PrayerModule.get_prayer_times(date, location, result);
// return result;
// }
//
// public Dms getQiblaDirection() {
// requireLocation();
// return Dms.fromDecimal(PrayerModule.get_qibla_direction(location));
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/PrayerTimes.java
// public class PrayerTimes {
// Event fajr = new Event();
// Event sunrise = new Event();
// Event dhuhr = new Event();
// Event asr = new Event();
// Event maghrib = new Event();
// Event isha = new Event();
//
// public Event getFajr() {
// return fajr;
// }
//
// public Event getSunrise() {
// return sunrise;
// }
//
// public Event getDhuhr() {
// return dhuhr;
// }
//
// public Event getAsr() {
// return asr;
// }
//
// public Event getMaghrib() {
// return maghrib;
// }
//
// public Event getIsha() {
// return isha;
// }
// }
// Path: app/src/main/java/example/NewMethod.java
import org.arabeyes.itl.newmethod.MethodId;
import org.arabeyes.itl.newmethod.Prayer;
import org.arabeyes.itl.newmethod.PrayerTimes;
import java.util.GregorianCalendar;
package example;
public class NewMethod {
public static void main(String[] args) {
System.out.println("=== PRAYER TIME (NEW METHOD) ===");
| Prayer calculator = new Prayer() |
fikr4n/itl-java | app/src/main/java/example/NewMethod.java | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/MethodId.java
// public enum MethodId {MWL, ISNA, EGAS, UMAQ, UIS}
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/Prayer.java
// public class Prayer {
// private DefsModule.date_t date;
// private DefsModule.location location;
//
// public Prayer() {
// location = new DefsModule.location();
// location.latitude = Double.NaN;
// location.longitude = Double.NaN;
// location.extr_method = ExtremeMethod.NONE;
// location.asr_method = AsrMethod.SHAFII;
// }
//
// private void requireLocation() {
// if (Double.isNaN(location.latitude) || Double.isNaN(location.longitude))
// throw new IllegalStateException("Location is not set");
// }
//
// private void requireMethods() {
// if (location.asr_method == null || location.calc_method == null ||
// location.extr_method == null)
// throw new IllegalStateException("Method is not set");
// }
//
// private void requireDate() {
// if (date == null)
// throw new IllegalStateException("Date is not set");
// }
//
// public Prayer setCalculationMethod(CalcMethod method) {
// this.location.calc_method = method;
// return this;
// }
//
// public Prayer setCalculationMethod(MethodId method) {
// for (CalcMethod i : PrayerModule.calc_methods) {
// if (i.id == method) {
// setCalculationMethod(i);
// return this;
// }
// }
// throw new IllegalArgumentException("Unknown method: " + method);
// }
//
// /**
// * Default value is {@link AsrMethod#SHAFII}
// */
// public Prayer setAsrMethod(AsrMethod method) {
// this.location.asr_method = method;
// return this;
// }
//
// /**
// * Default value is {@link ExtremeMethod#NONE}
// */
// public Prayer setExtremeMethod(ExtremeMethod method) {
// this.location.extr_method = method;
// return this;
// }
//
// public Prayer setLocation(double latitude, double longitude, double altitude) {
// location.latitude = latitude;
// location.longitude = longitude;
// location.altitude = altitude;
// return this;
// }
//
// public Prayer setDate(GregorianCalendar cal) {
// this.date = new DefsModule.date_t().set(cal.get(Calendar.DAY_OF_MONTH),
// cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR));
// this.location.timezone = cal.get(Calendar.ZONE_OFFSET) / (1000.0 * 60 * 60);
// this.location.daylight = (int) Math.round(cal.get(Calendar.DST_OFFSET) / (1000.0 * 60 * 60));
// return this;
// }
//
// public Prayer setDate(Date date, TimeZone timeZone) {
// GregorianCalendar cal = new GregorianCalendar(timeZone);
// cal.setTime(date);
// return setDate(cal);
// }
//
// public PrayerTimes getPrayerTimes() {
// requireMethods();
// requireDate();
// requireLocation();
//
// PrayerTimes result = new PrayerTimes();
// PrayerModule.get_prayer_times(date, location, result);
// return result;
// }
//
// public Dms getQiblaDirection() {
// requireLocation();
// return Dms.fromDecimal(PrayerModule.get_qibla_direction(location));
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/PrayerTimes.java
// public class PrayerTimes {
// Event fajr = new Event();
// Event sunrise = new Event();
// Event dhuhr = new Event();
// Event asr = new Event();
// Event maghrib = new Event();
// Event isha = new Event();
//
// public Event getFajr() {
// return fajr;
// }
//
// public Event getSunrise() {
// return sunrise;
// }
//
// public Event getDhuhr() {
// return dhuhr;
// }
//
// public Event getAsr() {
// return asr;
// }
//
// public Event getMaghrib() {
// return maghrib;
// }
//
// public Event getIsha() {
// return isha;
// }
// }
| import org.arabeyes.itl.newmethod.MethodId;
import org.arabeyes.itl.newmethod.Prayer;
import org.arabeyes.itl.newmethod.PrayerTimes;
import java.util.GregorianCalendar; | package example;
public class NewMethod {
public static void main(String[] args) {
System.out.println("=== PRAYER TIME (NEW METHOD) ===");
Prayer calculator = new Prayer() | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/MethodId.java
// public enum MethodId {MWL, ISNA, EGAS, UMAQ, UIS}
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/Prayer.java
// public class Prayer {
// private DefsModule.date_t date;
// private DefsModule.location location;
//
// public Prayer() {
// location = new DefsModule.location();
// location.latitude = Double.NaN;
// location.longitude = Double.NaN;
// location.extr_method = ExtremeMethod.NONE;
// location.asr_method = AsrMethod.SHAFII;
// }
//
// private void requireLocation() {
// if (Double.isNaN(location.latitude) || Double.isNaN(location.longitude))
// throw new IllegalStateException("Location is not set");
// }
//
// private void requireMethods() {
// if (location.asr_method == null || location.calc_method == null ||
// location.extr_method == null)
// throw new IllegalStateException("Method is not set");
// }
//
// private void requireDate() {
// if (date == null)
// throw new IllegalStateException("Date is not set");
// }
//
// public Prayer setCalculationMethod(CalcMethod method) {
// this.location.calc_method = method;
// return this;
// }
//
// public Prayer setCalculationMethod(MethodId method) {
// for (CalcMethod i : PrayerModule.calc_methods) {
// if (i.id == method) {
// setCalculationMethod(i);
// return this;
// }
// }
// throw new IllegalArgumentException("Unknown method: " + method);
// }
//
// /**
// * Default value is {@link AsrMethod#SHAFII}
// */
// public Prayer setAsrMethod(AsrMethod method) {
// this.location.asr_method = method;
// return this;
// }
//
// /**
// * Default value is {@link ExtremeMethod#NONE}
// */
// public Prayer setExtremeMethod(ExtremeMethod method) {
// this.location.extr_method = method;
// return this;
// }
//
// public Prayer setLocation(double latitude, double longitude, double altitude) {
// location.latitude = latitude;
// location.longitude = longitude;
// location.altitude = altitude;
// return this;
// }
//
// public Prayer setDate(GregorianCalendar cal) {
// this.date = new DefsModule.date_t().set(cal.get(Calendar.DAY_OF_MONTH),
// cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR));
// this.location.timezone = cal.get(Calendar.ZONE_OFFSET) / (1000.0 * 60 * 60);
// this.location.daylight = (int) Math.round(cal.get(Calendar.DST_OFFSET) / (1000.0 * 60 * 60));
// return this;
// }
//
// public Prayer setDate(Date date, TimeZone timeZone) {
// GregorianCalendar cal = new GregorianCalendar(timeZone);
// cal.setTime(date);
// return setDate(cal);
// }
//
// public PrayerTimes getPrayerTimes() {
// requireMethods();
// requireDate();
// requireLocation();
//
// PrayerTimes result = new PrayerTimes();
// PrayerModule.get_prayer_times(date, location, result);
// return result;
// }
//
// public Dms getQiblaDirection() {
// requireLocation();
// return Dms.fromDecimal(PrayerModule.get_qibla_direction(location));
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/PrayerTimes.java
// public class PrayerTimes {
// Event fajr = new Event();
// Event sunrise = new Event();
// Event dhuhr = new Event();
// Event asr = new Event();
// Event maghrib = new Event();
// Event isha = new Event();
//
// public Event getFajr() {
// return fajr;
// }
//
// public Event getSunrise() {
// return sunrise;
// }
//
// public Event getDhuhr() {
// return dhuhr;
// }
//
// public Event getAsr() {
// return asr;
// }
//
// public Event getMaghrib() {
// return maghrib;
// }
//
// public Event getIsha() {
// return isha;
// }
// }
// Path: app/src/main/java/example/NewMethod.java
import org.arabeyes.itl.newmethod.MethodId;
import org.arabeyes.itl.newmethod.Prayer;
import org.arabeyes.itl.newmethod.PrayerTimes;
import java.util.GregorianCalendar;
package example;
public class NewMethod {
public static void main(String[] args) {
System.out.println("=== PRAYER TIME (NEW METHOD) ===");
Prayer calculator = new Prayer() | .setCalculationMethod(MethodId.EGAS) |
fikr4n/itl-java | app/src/main/java/example/NewMethod.java | // Path: itl/src/main/java/org/arabeyes/itl/newmethod/MethodId.java
// public enum MethodId {MWL, ISNA, EGAS, UMAQ, UIS}
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/Prayer.java
// public class Prayer {
// private DefsModule.date_t date;
// private DefsModule.location location;
//
// public Prayer() {
// location = new DefsModule.location();
// location.latitude = Double.NaN;
// location.longitude = Double.NaN;
// location.extr_method = ExtremeMethod.NONE;
// location.asr_method = AsrMethod.SHAFII;
// }
//
// private void requireLocation() {
// if (Double.isNaN(location.latitude) || Double.isNaN(location.longitude))
// throw new IllegalStateException("Location is not set");
// }
//
// private void requireMethods() {
// if (location.asr_method == null || location.calc_method == null ||
// location.extr_method == null)
// throw new IllegalStateException("Method is not set");
// }
//
// private void requireDate() {
// if (date == null)
// throw new IllegalStateException("Date is not set");
// }
//
// public Prayer setCalculationMethod(CalcMethod method) {
// this.location.calc_method = method;
// return this;
// }
//
// public Prayer setCalculationMethod(MethodId method) {
// for (CalcMethod i : PrayerModule.calc_methods) {
// if (i.id == method) {
// setCalculationMethod(i);
// return this;
// }
// }
// throw new IllegalArgumentException("Unknown method: " + method);
// }
//
// /**
// * Default value is {@link AsrMethod#SHAFII}
// */
// public Prayer setAsrMethod(AsrMethod method) {
// this.location.asr_method = method;
// return this;
// }
//
// /**
// * Default value is {@link ExtremeMethod#NONE}
// */
// public Prayer setExtremeMethod(ExtremeMethod method) {
// this.location.extr_method = method;
// return this;
// }
//
// public Prayer setLocation(double latitude, double longitude, double altitude) {
// location.latitude = latitude;
// location.longitude = longitude;
// location.altitude = altitude;
// return this;
// }
//
// public Prayer setDate(GregorianCalendar cal) {
// this.date = new DefsModule.date_t().set(cal.get(Calendar.DAY_OF_MONTH),
// cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR));
// this.location.timezone = cal.get(Calendar.ZONE_OFFSET) / (1000.0 * 60 * 60);
// this.location.daylight = (int) Math.round(cal.get(Calendar.DST_OFFSET) / (1000.0 * 60 * 60));
// return this;
// }
//
// public Prayer setDate(Date date, TimeZone timeZone) {
// GregorianCalendar cal = new GregorianCalendar(timeZone);
// cal.setTime(date);
// return setDate(cal);
// }
//
// public PrayerTimes getPrayerTimes() {
// requireMethods();
// requireDate();
// requireLocation();
//
// PrayerTimes result = new PrayerTimes();
// PrayerModule.get_prayer_times(date, location, result);
// return result;
// }
//
// public Dms getQiblaDirection() {
// requireLocation();
// return Dms.fromDecimal(PrayerModule.get_qibla_direction(location));
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/PrayerTimes.java
// public class PrayerTimes {
// Event fajr = new Event();
// Event sunrise = new Event();
// Event dhuhr = new Event();
// Event asr = new Event();
// Event maghrib = new Event();
// Event isha = new Event();
//
// public Event getFajr() {
// return fajr;
// }
//
// public Event getSunrise() {
// return sunrise;
// }
//
// public Event getDhuhr() {
// return dhuhr;
// }
//
// public Event getAsr() {
// return asr;
// }
//
// public Event getMaghrib() {
// return maghrib;
// }
//
// public Event getIsha() {
// return isha;
// }
// }
| import org.arabeyes.itl.newmethod.MethodId;
import org.arabeyes.itl.newmethod.Prayer;
import org.arabeyes.itl.newmethod.PrayerTimes;
import java.util.GregorianCalendar; | package example;
public class NewMethod {
public static void main(String[] args) {
System.out.println("=== PRAYER TIME (NEW METHOD) ===");
Prayer calculator = new Prayer()
.setCalculationMethod(MethodId.EGAS)
.setDate(new GregorianCalendar())
.setLocation(-6.37812775, 106.8342445, 0); // lat, lng, height AMSL
| // Path: itl/src/main/java/org/arabeyes/itl/newmethod/MethodId.java
// public enum MethodId {MWL, ISNA, EGAS, UMAQ, UIS}
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/Prayer.java
// public class Prayer {
// private DefsModule.date_t date;
// private DefsModule.location location;
//
// public Prayer() {
// location = new DefsModule.location();
// location.latitude = Double.NaN;
// location.longitude = Double.NaN;
// location.extr_method = ExtremeMethod.NONE;
// location.asr_method = AsrMethod.SHAFII;
// }
//
// private void requireLocation() {
// if (Double.isNaN(location.latitude) || Double.isNaN(location.longitude))
// throw new IllegalStateException("Location is not set");
// }
//
// private void requireMethods() {
// if (location.asr_method == null || location.calc_method == null ||
// location.extr_method == null)
// throw new IllegalStateException("Method is not set");
// }
//
// private void requireDate() {
// if (date == null)
// throw new IllegalStateException("Date is not set");
// }
//
// public Prayer setCalculationMethod(CalcMethod method) {
// this.location.calc_method = method;
// return this;
// }
//
// public Prayer setCalculationMethod(MethodId method) {
// for (CalcMethod i : PrayerModule.calc_methods) {
// if (i.id == method) {
// setCalculationMethod(i);
// return this;
// }
// }
// throw new IllegalArgumentException("Unknown method: " + method);
// }
//
// /**
// * Default value is {@link AsrMethod#SHAFII}
// */
// public Prayer setAsrMethod(AsrMethod method) {
// this.location.asr_method = method;
// return this;
// }
//
// /**
// * Default value is {@link ExtremeMethod#NONE}
// */
// public Prayer setExtremeMethod(ExtremeMethod method) {
// this.location.extr_method = method;
// return this;
// }
//
// public Prayer setLocation(double latitude, double longitude, double altitude) {
// location.latitude = latitude;
// location.longitude = longitude;
// location.altitude = altitude;
// return this;
// }
//
// public Prayer setDate(GregorianCalendar cal) {
// this.date = new DefsModule.date_t().set(cal.get(Calendar.DAY_OF_MONTH),
// cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR));
// this.location.timezone = cal.get(Calendar.ZONE_OFFSET) / (1000.0 * 60 * 60);
// this.location.daylight = (int) Math.round(cal.get(Calendar.DST_OFFSET) / (1000.0 * 60 * 60));
// return this;
// }
//
// public Prayer setDate(Date date, TimeZone timeZone) {
// GregorianCalendar cal = new GregorianCalendar(timeZone);
// cal.setTime(date);
// return setDate(cal);
// }
//
// public PrayerTimes getPrayerTimes() {
// requireMethods();
// requireDate();
// requireLocation();
//
// PrayerTimes result = new PrayerTimes();
// PrayerModule.get_prayer_times(date, location, result);
// return result;
// }
//
// public Dms getQiblaDirection() {
// requireLocation();
// return Dms.fromDecimal(PrayerModule.get_qibla_direction(location));
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/newmethod/PrayerTimes.java
// public class PrayerTimes {
// Event fajr = new Event();
// Event sunrise = new Event();
// Event dhuhr = new Event();
// Event asr = new Event();
// Event maghrib = new Event();
// Event isha = new Event();
//
// public Event getFajr() {
// return fajr;
// }
//
// public Event getSunrise() {
// return sunrise;
// }
//
// public Event getDhuhr() {
// return dhuhr;
// }
//
// public Event getAsr() {
// return asr;
// }
//
// public Event getMaghrib() {
// return maghrib;
// }
//
// public Event getIsha() {
// return isha;
// }
// }
// Path: app/src/main/java/example/NewMethod.java
import org.arabeyes.itl.newmethod.MethodId;
import org.arabeyes.itl.newmethod.Prayer;
import org.arabeyes.itl.newmethod.PrayerTimes;
import java.util.GregorianCalendar;
package example;
public class NewMethod {
public static void main(String[] args) {
System.out.println("=== PRAYER TIME (NEW METHOD) ===");
Prayer calculator = new Prayer()
.setCalculationMethod(MethodId.EGAS)
.setDate(new GregorianCalendar())
.setLocation(-6.37812775, 106.8342445, 0); // lat, lng, height AMSL
| PrayerTimes times = calculator.getPrayerTimes(); |
fikr4n/itl-java | itl/src/main/java/org/arabeyes/itl/prayertime/Prayer.java | // Path: itl/src/main/java/org/arabeyes/itl/prayertime/PrayerModule.java
// static class Location {
// double degreeLong; /* Longitude in decimal degree. */
// double degreeLat; /* Latitude in decimal degree. */
// double gmtDiff; /* GMT difference at regular time. */
// int dst; /* Daylight savings time switch (0 if not used).
// Setting this to 1 should add 1 hour to all the
// calculated prayer times */
// double seaLevel; /* Height above Sea level in meters */
// double pressure; /* Atmospheric pressure in millibars (the
// astronomical standard value is 1010) */
// double temperature; /* Temperature in Celsius degree (the astronomical
// standard value is 10) */
//
// Location() {
// }
//
// Location(Location src) {
// this.degreeLong = src.degreeLong;
// this.degreeLat = src.degreeLat;
// this.gmtDiff = src.gmtDiff;
// this.dst = src.dst;
// this.seaLevel = src.seaLevel;
// this.pressure = src.pressure;
// this.temperature = src.temperature;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/prayertime/PrayerModule.java
// static class SDate {
// int day;
// int month;
// int year;
//
// SDate() {
// }
//
// SDate(SDate src) {
// this.day = src.day;
// this.month = src.month;
// this.year = src.year;
// }
// }
| import org.arabeyes.itl.prayertime.PrayerModule.Location;
import org.arabeyes.itl.prayertime.PrayerModule.SDate;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedHashMap;
import java.util.TimeZone; | /* Copyright (c) 2017, Fikrul Arif
* (under LGPL license - see COPYING file)
*/
package org.arabeyes.itl.prayertime;
public class Prayer {
private static final Method[] METHODS_CACHE = new Method[StandardMethod.values().length];
| // Path: itl/src/main/java/org/arabeyes/itl/prayertime/PrayerModule.java
// static class Location {
// double degreeLong; /* Longitude in decimal degree. */
// double degreeLat; /* Latitude in decimal degree. */
// double gmtDiff; /* GMT difference at regular time. */
// int dst; /* Daylight savings time switch (0 if not used).
// Setting this to 1 should add 1 hour to all the
// calculated prayer times */
// double seaLevel; /* Height above Sea level in meters */
// double pressure; /* Atmospheric pressure in millibars (the
// astronomical standard value is 1010) */
// double temperature; /* Temperature in Celsius degree (the astronomical
// standard value is 10) */
//
// Location() {
// }
//
// Location(Location src) {
// this.degreeLong = src.degreeLong;
// this.degreeLat = src.degreeLat;
// this.gmtDiff = src.gmtDiff;
// this.dst = src.dst;
// this.seaLevel = src.seaLevel;
// this.pressure = src.pressure;
// this.temperature = src.temperature;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/prayertime/PrayerModule.java
// static class SDate {
// int day;
// int month;
// int year;
//
// SDate() {
// }
//
// SDate(SDate src) {
// this.day = src.day;
// this.month = src.month;
// this.year = src.year;
// }
// }
// Path: itl/src/main/java/org/arabeyes/itl/prayertime/Prayer.java
import org.arabeyes.itl.prayertime.PrayerModule.Location;
import org.arabeyes.itl.prayertime.PrayerModule.SDate;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedHashMap;
import java.util.TimeZone;
/* Copyright (c) 2017, Fikrul Arif
* (under LGPL license - see COPYING file)
*/
package org.arabeyes.itl.prayertime;
public class Prayer {
private static final Method[] METHODS_CACHE = new Method[StandardMethod.values().length];
| private final Location location; |
fikr4n/itl-java | itl/src/main/java/org/arabeyes/itl/prayertime/Prayer.java | // Path: itl/src/main/java/org/arabeyes/itl/prayertime/PrayerModule.java
// static class Location {
// double degreeLong; /* Longitude in decimal degree. */
// double degreeLat; /* Latitude in decimal degree. */
// double gmtDiff; /* GMT difference at regular time. */
// int dst; /* Daylight savings time switch (0 if not used).
// Setting this to 1 should add 1 hour to all the
// calculated prayer times */
// double seaLevel; /* Height above Sea level in meters */
// double pressure; /* Atmospheric pressure in millibars (the
// astronomical standard value is 1010) */
// double temperature; /* Temperature in Celsius degree (the astronomical
// standard value is 10) */
//
// Location() {
// }
//
// Location(Location src) {
// this.degreeLong = src.degreeLong;
// this.degreeLat = src.degreeLat;
// this.gmtDiff = src.gmtDiff;
// this.dst = src.dst;
// this.seaLevel = src.seaLevel;
// this.pressure = src.pressure;
// this.temperature = src.temperature;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/prayertime/PrayerModule.java
// static class SDate {
// int day;
// int month;
// int year;
//
// SDate() {
// }
//
// SDate(SDate src) {
// this.day = src.day;
// this.month = src.month;
// this.year = src.year;
// }
// }
| import org.arabeyes.itl.prayertime.PrayerModule.Location;
import org.arabeyes.itl.prayertime.PrayerModule.SDate;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedHashMap;
import java.util.TimeZone; | /* Copyright (c) 2017, Fikrul Arif
* (under LGPL license - see COPYING file)
*/
package org.arabeyes.itl.prayertime;
public class Prayer {
private static final Method[] METHODS_CACHE = new Method[StandardMethod.values().length];
private final Location location;
private Method method; | // Path: itl/src/main/java/org/arabeyes/itl/prayertime/PrayerModule.java
// static class Location {
// double degreeLong; /* Longitude in decimal degree. */
// double degreeLat; /* Latitude in decimal degree. */
// double gmtDiff; /* GMT difference at regular time. */
// int dst; /* Daylight savings time switch (0 if not used).
// Setting this to 1 should add 1 hour to all the
// calculated prayer times */
// double seaLevel; /* Height above Sea level in meters */
// double pressure; /* Atmospheric pressure in millibars (the
// astronomical standard value is 1010) */
// double temperature; /* Temperature in Celsius degree (the astronomical
// standard value is 10) */
//
// Location() {
// }
//
// Location(Location src) {
// this.degreeLong = src.degreeLong;
// this.degreeLat = src.degreeLat;
// this.gmtDiff = src.gmtDiff;
// this.dst = src.dst;
// this.seaLevel = src.seaLevel;
// this.pressure = src.pressure;
// this.temperature = src.temperature;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/prayertime/PrayerModule.java
// static class SDate {
// int day;
// int month;
// int year;
//
// SDate() {
// }
//
// SDate(SDate src) {
// this.day = src.day;
// this.month = src.month;
// this.year = src.year;
// }
// }
// Path: itl/src/main/java/org/arabeyes/itl/prayertime/Prayer.java
import org.arabeyes.itl.prayertime.PrayerModule.Location;
import org.arabeyes.itl.prayertime.PrayerModule.SDate;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedHashMap;
import java.util.TimeZone;
/* Copyright (c) 2017, Fikrul Arif
* (under LGPL license - see COPYING file)
*/
package org.arabeyes.itl.prayertime;
public class Prayer {
private static final Method[] METHODS_CACHE = new Method[StandardMethod.values().length];
private final Location location;
private Method method; | private SDate date; |
fikr4n/itl-java | itl/src/main/java/org/arabeyes/itl/hijri/ConvertedDate.java | // Path: itl/src/main/java/org/arabeyes/itl/hijri/HijriModule.java
// static class sDate {
// int day; /* Day */
// int month; /* Month */
// int year; /* Year */
// int weekday; /* Day of the week (0:Sunday, 1:Monday...) */
// int frm_numdays; /* Number of days in specified input month */
// int to_numdays; /* Number of days in resulting output month */
// int to_numdays2; /* Number of days in resulting output month+1 */
// String units; /* Units used to denote before/after epoch */
// String frm_dname; /* Converting from - Name of day */
// String frm_mname; /* Converting from - Name of month */
// String frm_dname_sh; /* Converting from - Name of day in short format */
// String frm_mname_sh; /* Converting from - Name of month in short format */
// String to_dname; /* Converting to - Name of day */
// String to_mname; /* Converting to - Name of month */
// String to_mname2; /* Converting to - Name of month+1 */
// String to_dname_sh; /* Converting to - Name of day in short format */
// String to_mname_sh; /* Converting to - Name of month in short format */
// String[] event; /* Important event pertaining to date at hand */
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// sDate that = (sDate) o;
// return day == that.day && month == that.month && year == that.year &&
// weekday == that.weekday &&
// (units != null ? units.equals(that.units) : that.units == null);
// }
//
// @Override
// public int hashCode() {
// int result = day;
// result = 31 * result + month;
// result = 31 * result + year;
// result = 31 * result + weekday;
// result = 31 * result + (units != null ? units.hashCode() : 0);
// return result;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/util/Formatter.java
// public class Formatter {
// public static String format(String f, Mapper mapper) {
// NumberFormat nf = NumberFormat.getNumberInstance(Locale.ROOT);
// nf.setGroupingUsed(false);
//
// StringBuilder result = new StringBuilder();
// int count = 0;
// boolean inQuote = false;
// for (int i = 0, last = f.length() - 1; i <= last; ++i) {
// char c = f.charAt(i);
// if (i > 0 && c == f.charAt(i - 1))
// count++;
// else
// count = 1;
//
// // handle quote and in-quote
// if (c == '\'') {
// if (inQuote) {
// if (count == 2) result.append(c);
// inQuote = false;
// count = 0;
// } else {
// inQuote = true;
// }
// continue;
// } else if (inQuote) {
// result.append(c);
// continue;
// }
//
// if (i != last && c == f.charAt(i + 1)) // collect and count first
// continue;
//
// // handle format pattern and punctuation
// if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
// Object val = mapper.applyFormat(c, count);
// if (val == null) {
// throw new IllegalArgumentException("Illegal pattern character '" + c + "'");
// } else if (val instanceof Number) {
// nf.setMinimumIntegerDigits(count);
// result.append(nf.format(val));
// } else {
// result.append(val);
// }
// } else {
// // punctuation
// for (int j = 0; j < count; ++j) result.append(c);
// }
// }
// return result.toString();
// }
//
// public interface Mapper {
// Object applyFormat(char pattern, int count);
// }
// }
| import java.util.Date;
import java.util.GregorianCalendar;
import org.arabeyes.itl.hijri.HijriModule.sDate;
import org.arabeyes.itl.util.Formatter; | /* Copyright (c) 2017, Fikrul Arif
* (under LGPL license - see COPYING file)
*/
package org.arabeyes.itl.hijri;
/**
* Represents converted date as well as the input date.
*/
@SuppressWarnings("WeakerAccess")
public class ConvertedDate implements Comparable<ConvertedDate> {
static final int TYPE_HIJRI = 0;
static final int TYPE_UMM_ALQURA = 1;
static final int TYPE_GREGORIAN = 2;
| // Path: itl/src/main/java/org/arabeyes/itl/hijri/HijriModule.java
// static class sDate {
// int day; /* Day */
// int month; /* Month */
// int year; /* Year */
// int weekday; /* Day of the week (0:Sunday, 1:Monday...) */
// int frm_numdays; /* Number of days in specified input month */
// int to_numdays; /* Number of days in resulting output month */
// int to_numdays2; /* Number of days in resulting output month+1 */
// String units; /* Units used to denote before/after epoch */
// String frm_dname; /* Converting from - Name of day */
// String frm_mname; /* Converting from - Name of month */
// String frm_dname_sh; /* Converting from - Name of day in short format */
// String frm_mname_sh; /* Converting from - Name of month in short format */
// String to_dname; /* Converting to - Name of day */
// String to_mname; /* Converting to - Name of month */
// String to_mname2; /* Converting to - Name of month+1 */
// String to_dname_sh; /* Converting to - Name of day in short format */
// String to_mname_sh; /* Converting to - Name of month in short format */
// String[] event; /* Important event pertaining to date at hand */
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// sDate that = (sDate) o;
// return day == that.day && month == that.month && year == that.year &&
// weekday == that.weekday &&
// (units != null ? units.equals(that.units) : that.units == null);
// }
//
// @Override
// public int hashCode() {
// int result = day;
// result = 31 * result + month;
// result = 31 * result + year;
// result = 31 * result + weekday;
// result = 31 * result + (units != null ? units.hashCode() : 0);
// return result;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/util/Formatter.java
// public class Formatter {
// public static String format(String f, Mapper mapper) {
// NumberFormat nf = NumberFormat.getNumberInstance(Locale.ROOT);
// nf.setGroupingUsed(false);
//
// StringBuilder result = new StringBuilder();
// int count = 0;
// boolean inQuote = false;
// for (int i = 0, last = f.length() - 1; i <= last; ++i) {
// char c = f.charAt(i);
// if (i > 0 && c == f.charAt(i - 1))
// count++;
// else
// count = 1;
//
// // handle quote and in-quote
// if (c == '\'') {
// if (inQuote) {
// if (count == 2) result.append(c);
// inQuote = false;
// count = 0;
// } else {
// inQuote = true;
// }
// continue;
// } else if (inQuote) {
// result.append(c);
// continue;
// }
//
// if (i != last && c == f.charAt(i + 1)) // collect and count first
// continue;
//
// // handle format pattern and punctuation
// if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
// Object val = mapper.applyFormat(c, count);
// if (val == null) {
// throw new IllegalArgumentException("Illegal pattern character '" + c + "'");
// } else if (val instanceof Number) {
// nf.setMinimumIntegerDigits(count);
// result.append(nf.format(val));
// } else {
// result.append(val);
// }
// } else {
// // punctuation
// for (int j = 0; j < count; ++j) result.append(c);
// }
// }
// return result.toString();
// }
//
// public interface Mapper {
// Object applyFormat(char pattern, int count);
// }
// }
// Path: itl/src/main/java/org/arabeyes/itl/hijri/ConvertedDate.java
import java.util.Date;
import java.util.GregorianCalendar;
import org.arabeyes.itl.hijri.HijriModule.sDate;
import org.arabeyes.itl.util.Formatter;
/* Copyright (c) 2017, Fikrul Arif
* (under LGPL license - see COPYING file)
*/
package org.arabeyes.itl.hijri;
/**
* Represents converted date as well as the input date.
*/
@SuppressWarnings("WeakerAccess")
public class ConvertedDate implements Comparable<ConvertedDate> {
static final int TYPE_HIJRI = 0;
static final int TYPE_UMM_ALQURA = 1;
static final int TYPE_GREGORIAN = 2;
| private final sDate date; |
fikr4n/itl-java | itl/src/main/java/org/arabeyes/itl/hijri/ConvertedDate.java | // Path: itl/src/main/java/org/arabeyes/itl/hijri/HijriModule.java
// static class sDate {
// int day; /* Day */
// int month; /* Month */
// int year; /* Year */
// int weekday; /* Day of the week (0:Sunday, 1:Monday...) */
// int frm_numdays; /* Number of days in specified input month */
// int to_numdays; /* Number of days in resulting output month */
// int to_numdays2; /* Number of days in resulting output month+1 */
// String units; /* Units used to denote before/after epoch */
// String frm_dname; /* Converting from - Name of day */
// String frm_mname; /* Converting from - Name of month */
// String frm_dname_sh; /* Converting from - Name of day in short format */
// String frm_mname_sh; /* Converting from - Name of month in short format */
// String to_dname; /* Converting to - Name of day */
// String to_mname; /* Converting to - Name of month */
// String to_mname2; /* Converting to - Name of month+1 */
// String to_dname_sh; /* Converting to - Name of day in short format */
// String to_mname_sh; /* Converting to - Name of month in short format */
// String[] event; /* Important event pertaining to date at hand */
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// sDate that = (sDate) o;
// return day == that.day && month == that.month && year == that.year &&
// weekday == that.weekday &&
// (units != null ? units.equals(that.units) : that.units == null);
// }
//
// @Override
// public int hashCode() {
// int result = day;
// result = 31 * result + month;
// result = 31 * result + year;
// result = 31 * result + weekday;
// result = 31 * result + (units != null ? units.hashCode() : 0);
// return result;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/util/Formatter.java
// public class Formatter {
// public static String format(String f, Mapper mapper) {
// NumberFormat nf = NumberFormat.getNumberInstance(Locale.ROOT);
// nf.setGroupingUsed(false);
//
// StringBuilder result = new StringBuilder();
// int count = 0;
// boolean inQuote = false;
// for (int i = 0, last = f.length() - 1; i <= last; ++i) {
// char c = f.charAt(i);
// if (i > 0 && c == f.charAt(i - 1))
// count++;
// else
// count = 1;
//
// // handle quote and in-quote
// if (c == '\'') {
// if (inQuote) {
// if (count == 2) result.append(c);
// inQuote = false;
// count = 0;
// } else {
// inQuote = true;
// }
// continue;
// } else if (inQuote) {
// result.append(c);
// continue;
// }
//
// if (i != last && c == f.charAt(i + 1)) // collect and count first
// continue;
//
// // handle format pattern and punctuation
// if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
// Object val = mapper.applyFormat(c, count);
// if (val == null) {
// throw new IllegalArgumentException("Illegal pattern character '" + c + "'");
// } else if (val instanceof Number) {
// nf.setMinimumIntegerDigits(count);
// result.append(nf.format(val));
// } else {
// result.append(val);
// }
// } else {
// // punctuation
// for (int j = 0; j < count; ++j) result.append(c);
// }
// }
// return result.toString();
// }
//
// public interface Mapper {
// Object applyFormat(char pattern, int count);
// }
// }
| import java.util.Date;
import java.util.GregorianCalendar;
import org.arabeyes.itl.hijri.HijriModule.sDate;
import org.arabeyes.itl.util.Formatter; | /* Copyright (c) 2017, Fikrul Arif
* (under LGPL license - see COPYING file)
*/
package org.arabeyes.itl.hijri;
/**
* Represents converted date as well as the input date.
*/
@SuppressWarnings("WeakerAccess")
public class ConvertedDate implements Comparable<ConvertedDate> {
static final int TYPE_HIJRI = 0;
static final int TYPE_UMM_ALQURA = 1;
static final int TYPE_GREGORIAN = 2;
private final sDate date;
private final int sourceYear, sourceMonth, sourceDay;
private final HijriNames names;
private final int type;
ConvertedDate(sDate date, int sourceYear, int sourceMonth, int sourceDay, HijriNames names,
int type) {
this.date = date;
this.sourceYear = sourceYear;
this.sourceMonth = sourceMonth;
this.sourceDay = sourceDay;
this.names = names;
this.type = type;
}
/**
* Format converted date. The format is subset of {@link java.text.SimpleDateFormat} format
* pattern. Use single quote " ' " for escaping and double single-quote " '' " for single quote.
* <ul>
* <li>E - day of week (text)
* <li>d - day of moth (number)
* <li>M - month (text if >= 3 characters, otherwise number)
* <li>y - year (number, if == 2 characters will be truncated to 2 last digits)
* <li>G - era (text, empty string if not available)
* </ul>
* Notes:
* <ul>
* <li>text: full text if >= 4 characters, otherwise short/abbreviated form
* <li>number: will be zero padded based on number of characters
* <li>era is not always available
* <li>character other than 'a'-'z', 'A'-'Z', and single quote will be formatted as is
* </ul>
*
* @param f format pattern, must not be null
* @return formatted date
* @throws IllegalArgumentException if contains unquoted character 'a'-'z' or 'A'-'Z' other than
* format patterns above
*/
public String format(String f) { | // Path: itl/src/main/java/org/arabeyes/itl/hijri/HijriModule.java
// static class sDate {
// int day; /* Day */
// int month; /* Month */
// int year; /* Year */
// int weekday; /* Day of the week (0:Sunday, 1:Monday...) */
// int frm_numdays; /* Number of days in specified input month */
// int to_numdays; /* Number of days in resulting output month */
// int to_numdays2; /* Number of days in resulting output month+1 */
// String units; /* Units used to denote before/after epoch */
// String frm_dname; /* Converting from - Name of day */
// String frm_mname; /* Converting from - Name of month */
// String frm_dname_sh; /* Converting from - Name of day in short format */
// String frm_mname_sh; /* Converting from - Name of month in short format */
// String to_dname; /* Converting to - Name of day */
// String to_mname; /* Converting to - Name of month */
// String to_mname2; /* Converting to - Name of month+1 */
// String to_dname_sh; /* Converting to - Name of day in short format */
// String to_mname_sh; /* Converting to - Name of month in short format */
// String[] event; /* Important event pertaining to date at hand */
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// sDate that = (sDate) o;
// return day == that.day && month == that.month && year == that.year &&
// weekday == that.weekday &&
// (units != null ? units.equals(that.units) : that.units == null);
// }
//
// @Override
// public int hashCode() {
// int result = day;
// result = 31 * result + month;
// result = 31 * result + year;
// result = 31 * result + weekday;
// result = 31 * result + (units != null ? units.hashCode() : 0);
// return result;
// }
// }
//
// Path: itl/src/main/java/org/arabeyes/itl/util/Formatter.java
// public class Formatter {
// public static String format(String f, Mapper mapper) {
// NumberFormat nf = NumberFormat.getNumberInstance(Locale.ROOT);
// nf.setGroupingUsed(false);
//
// StringBuilder result = new StringBuilder();
// int count = 0;
// boolean inQuote = false;
// for (int i = 0, last = f.length() - 1; i <= last; ++i) {
// char c = f.charAt(i);
// if (i > 0 && c == f.charAt(i - 1))
// count++;
// else
// count = 1;
//
// // handle quote and in-quote
// if (c == '\'') {
// if (inQuote) {
// if (count == 2) result.append(c);
// inQuote = false;
// count = 0;
// } else {
// inQuote = true;
// }
// continue;
// } else if (inQuote) {
// result.append(c);
// continue;
// }
//
// if (i != last && c == f.charAt(i + 1)) // collect and count first
// continue;
//
// // handle format pattern and punctuation
// if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
// Object val = mapper.applyFormat(c, count);
// if (val == null) {
// throw new IllegalArgumentException("Illegal pattern character '" + c + "'");
// } else if (val instanceof Number) {
// nf.setMinimumIntegerDigits(count);
// result.append(nf.format(val));
// } else {
// result.append(val);
// }
// } else {
// // punctuation
// for (int j = 0; j < count; ++j) result.append(c);
// }
// }
// return result.toString();
// }
//
// public interface Mapper {
// Object applyFormat(char pattern, int count);
// }
// }
// Path: itl/src/main/java/org/arabeyes/itl/hijri/ConvertedDate.java
import java.util.Date;
import java.util.GregorianCalendar;
import org.arabeyes.itl.hijri.HijriModule.sDate;
import org.arabeyes.itl.util.Formatter;
/* Copyright (c) 2017, Fikrul Arif
* (under LGPL license - see COPYING file)
*/
package org.arabeyes.itl.hijri;
/**
* Represents converted date as well as the input date.
*/
@SuppressWarnings("WeakerAccess")
public class ConvertedDate implements Comparable<ConvertedDate> {
static final int TYPE_HIJRI = 0;
static final int TYPE_UMM_ALQURA = 1;
static final int TYPE_GREGORIAN = 2;
private final sDate date;
private final int sourceYear, sourceMonth, sourceDay;
private final HijriNames names;
private final int type;
ConvertedDate(sDate date, int sourceYear, int sourceMonth, int sourceDay, HijriNames names,
int type) {
this.date = date;
this.sourceYear = sourceYear;
this.sourceMonth = sourceMonth;
this.sourceDay = sourceDay;
this.names = names;
this.type = type;
}
/**
* Format converted date. The format is subset of {@link java.text.SimpleDateFormat} format
* pattern. Use single quote " ' " for escaping and double single-quote " '' " for single quote.
* <ul>
* <li>E - day of week (text)
* <li>d - day of moth (number)
* <li>M - month (text if >= 3 characters, otherwise number)
* <li>y - year (number, if == 2 characters will be truncated to 2 last digits)
* <li>G - era (text, empty string if not available)
* </ul>
* Notes:
* <ul>
* <li>text: full text if >= 4 characters, otherwise short/abbreviated form
* <li>number: will be zero padded based on number of characters
* <li>era is not always available
* <li>character other than 'a'-'z', 'A'-'Z', and single quote will be formatted as is
* </ul>
*
* @param f format pattern, must not be null
* @return formatted date
* @throws IllegalArgumentException if contains unquoted character 'a'-'z' or 'A'-'Z' other than
* format patterns above
*/
public String format(String f) { | return Formatter.format(f, new TargetFormat()); |
bmoliveira/snake-yaml | src/main/java/org/yaml/snakeyaml/events/ScalarEvent.java | // Path: src/main/java/org/yaml/snakeyaml/error/Mark.java
// public final class Mark {
// private String name;
// private int index;
// private int line;
// private int column;
// private String buffer;
// private int pointer;
//
// public Mark(String name, int index, int line, int column, String buffer, int pointer) {
// super();
// this.name = name;
// this.index = index;
// this.line = line;
// this.column = column;
// this.buffer = buffer;
// this.pointer = pointer;
// }
//
// private boolean isLineBreak(char ch) {
// return Constant.NULL_OR_LINEBR.has(ch);
// }
//
// public String get_snippet(int indent, int max_length) {
// if (buffer == null) {
// return null;
// }
// float half = max_length / 2 - 1;
// int start = pointer;
// String head = "";
// while ((start > 0) && !isLineBreak(buffer.charAt(start - 1))) {
// start -= 1;
// if (pointer - start > half) {
// head = " ... ";
// start += 5;
// break;
// }
// }
// String tail = "";
// int end = pointer;
// while ((end < buffer.length()) && !isLineBreak(buffer.charAt(end))) {
// end += 1;
// if (end - pointer > half) {
// tail = " ... ";
// end -= 5;
// break;
// }
// }
// String snippet = buffer.substring(start, end);
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < indent; i++) {
// result.append(" ");
// }
// result.append(head);
// result.append(snippet);
// result.append(tail);
// result.append("\n");
// for (int i = 0; i < indent + pointer - start + head.length(); i++) {
// result.append(" ");
// }
// result.append("^");
// return result.toString();
// }
//
// public String get_snippet() {
// return get_snippet(4, 75);
// }
//
// @Override
// public String toString() {
// String snippet = get_snippet();
// StringBuilder where = new StringBuilder(" in ");
// where.append(name);
// where.append(", line ");
// where.append(line + 1);
// where.append(", column ");
// where.append(column + 1);
// if (snippet != null) {
// where.append(":\n");
// where.append(snippet);
// }
// return where.toString();
// }
//
// public String getName() {
// return name;
// }
//
//
// // starts with 0
// public int getLine() {
// return line;
// }
//
// // starts with 0
// public int getColumn() {
// return column;
// }
//
// // starts with 0
// public int getIndex() {
// return index;
// }
//
// }
| import org.yaml.snakeyaml.error.Mark; | /**
* Copyright (c) 2008, http://www.snakeyaml.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yaml.snakeyaml.events;
/**
* Marks a scalar value.
*/
public final class ScalarEvent extends NodeEvent {
private final String tag;
// style flag of a scalar event indicates the style of the scalar. Possible
// values are None, '', '\'', '"', '|', '>'
private final Character style;
private final String value;
// The implicit flag of a scalar event is a pair of boolean values that
// indicate if the tag may be omitted when the scalar is emitted in a plain
// and non-plain style correspondingly.
private final ImplicitTuple implicit;
public ScalarEvent(String anchor, String tag, ImplicitTuple implicit, String value, | // Path: src/main/java/org/yaml/snakeyaml/error/Mark.java
// public final class Mark {
// private String name;
// private int index;
// private int line;
// private int column;
// private String buffer;
// private int pointer;
//
// public Mark(String name, int index, int line, int column, String buffer, int pointer) {
// super();
// this.name = name;
// this.index = index;
// this.line = line;
// this.column = column;
// this.buffer = buffer;
// this.pointer = pointer;
// }
//
// private boolean isLineBreak(char ch) {
// return Constant.NULL_OR_LINEBR.has(ch);
// }
//
// public String get_snippet(int indent, int max_length) {
// if (buffer == null) {
// return null;
// }
// float half = max_length / 2 - 1;
// int start = pointer;
// String head = "";
// while ((start > 0) && !isLineBreak(buffer.charAt(start - 1))) {
// start -= 1;
// if (pointer - start > half) {
// head = " ... ";
// start += 5;
// break;
// }
// }
// String tail = "";
// int end = pointer;
// while ((end < buffer.length()) && !isLineBreak(buffer.charAt(end))) {
// end += 1;
// if (end - pointer > half) {
// tail = " ... ";
// end -= 5;
// break;
// }
// }
// String snippet = buffer.substring(start, end);
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < indent; i++) {
// result.append(" ");
// }
// result.append(head);
// result.append(snippet);
// result.append(tail);
// result.append("\n");
// for (int i = 0; i < indent + pointer - start + head.length(); i++) {
// result.append(" ");
// }
// result.append("^");
// return result.toString();
// }
//
// public String get_snippet() {
// return get_snippet(4, 75);
// }
//
// @Override
// public String toString() {
// String snippet = get_snippet();
// StringBuilder where = new StringBuilder(" in ");
// where.append(name);
// where.append(", line ");
// where.append(line + 1);
// where.append(", column ");
// where.append(column + 1);
// if (snippet != null) {
// where.append(":\n");
// where.append(snippet);
// }
// return where.toString();
// }
//
// public String getName() {
// return name;
// }
//
//
// // starts with 0
// public int getLine() {
// return line;
// }
//
// // starts with 0
// public int getColumn() {
// return column;
// }
//
// // starts with 0
// public int getIndex() {
// return index;
// }
//
// }
// Path: src/main/java/org/yaml/snakeyaml/events/ScalarEvent.java
import org.yaml.snakeyaml.error.Mark;
/**
* Copyright (c) 2008, http://www.snakeyaml.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yaml.snakeyaml.events;
/**
* Marks a scalar value.
*/
public final class ScalarEvent extends NodeEvent {
private final String tag;
// style flag of a scalar event indicates the style of the scalar. Possible
// values are None, '', '\'', '"', '|', '>'
private final Character style;
private final String value;
// The implicit flag of a scalar event is a pair of boolean values that
// indicate if the tag may be omitted when the scalar is emitted in a plain
// and non-plain style correspondingly.
private final ImplicitTuple implicit;
public ScalarEvent(String anchor, String tag, ImplicitTuple implicit, String value, | Mark startMark, Mark endMark, Character style) { |
bmoliveira/snake-yaml | src/main/java/org/yaml/snakeyaml/events/Event.java | // Path: src/main/java/org/yaml/snakeyaml/error/Mark.java
// public final class Mark {
// private String name;
// private int index;
// private int line;
// private int column;
// private String buffer;
// private int pointer;
//
// public Mark(String name, int index, int line, int column, String buffer, int pointer) {
// super();
// this.name = name;
// this.index = index;
// this.line = line;
// this.column = column;
// this.buffer = buffer;
// this.pointer = pointer;
// }
//
// private boolean isLineBreak(char ch) {
// return Constant.NULL_OR_LINEBR.has(ch);
// }
//
// public String get_snippet(int indent, int max_length) {
// if (buffer == null) {
// return null;
// }
// float half = max_length / 2 - 1;
// int start = pointer;
// String head = "";
// while ((start > 0) && !isLineBreak(buffer.charAt(start - 1))) {
// start -= 1;
// if (pointer - start > half) {
// head = " ... ";
// start += 5;
// break;
// }
// }
// String tail = "";
// int end = pointer;
// while ((end < buffer.length()) && !isLineBreak(buffer.charAt(end))) {
// end += 1;
// if (end - pointer > half) {
// tail = " ... ";
// end -= 5;
// break;
// }
// }
// String snippet = buffer.substring(start, end);
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < indent; i++) {
// result.append(" ");
// }
// result.append(head);
// result.append(snippet);
// result.append(tail);
// result.append("\n");
// for (int i = 0; i < indent + pointer - start + head.length(); i++) {
// result.append(" ");
// }
// result.append("^");
// return result.toString();
// }
//
// public String get_snippet() {
// return get_snippet(4, 75);
// }
//
// @Override
// public String toString() {
// String snippet = get_snippet();
// StringBuilder where = new StringBuilder(" in ");
// where.append(name);
// where.append(", line ");
// where.append(line + 1);
// where.append(", column ");
// where.append(column + 1);
// if (snippet != null) {
// where.append(":\n");
// where.append(snippet);
// }
// return where.toString();
// }
//
// public String getName() {
// return name;
// }
//
//
// // starts with 0
// public int getLine() {
// return line;
// }
//
// // starts with 0
// public int getColumn() {
// return column;
// }
//
// // starts with 0
// public int getIndex() {
// return index;
// }
//
// }
| import org.yaml.snakeyaml.error.Mark; | /**
* Copyright (c) 2008, http://www.snakeyaml.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yaml.snakeyaml.events;
/**
* Basic unit of output from a {@link org.yaml.snakeyaml.parser.Parser} or input
* of a {@link org.yaml.snakeyaml.emitter.Emitter}.
*/
public abstract class Event {
public enum ID {
Alias, DocumentEnd, DocumentStart, MappingEnd, MappingStart, Scalar, SequenceEnd, SequenceStart, StreamEnd, StreamStart
}
| // Path: src/main/java/org/yaml/snakeyaml/error/Mark.java
// public final class Mark {
// private String name;
// private int index;
// private int line;
// private int column;
// private String buffer;
// private int pointer;
//
// public Mark(String name, int index, int line, int column, String buffer, int pointer) {
// super();
// this.name = name;
// this.index = index;
// this.line = line;
// this.column = column;
// this.buffer = buffer;
// this.pointer = pointer;
// }
//
// private boolean isLineBreak(char ch) {
// return Constant.NULL_OR_LINEBR.has(ch);
// }
//
// public String get_snippet(int indent, int max_length) {
// if (buffer == null) {
// return null;
// }
// float half = max_length / 2 - 1;
// int start = pointer;
// String head = "";
// while ((start > 0) && !isLineBreak(buffer.charAt(start - 1))) {
// start -= 1;
// if (pointer - start > half) {
// head = " ... ";
// start += 5;
// break;
// }
// }
// String tail = "";
// int end = pointer;
// while ((end < buffer.length()) && !isLineBreak(buffer.charAt(end))) {
// end += 1;
// if (end - pointer > half) {
// tail = " ... ";
// end -= 5;
// break;
// }
// }
// String snippet = buffer.substring(start, end);
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < indent; i++) {
// result.append(" ");
// }
// result.append(head);
// result.append(snippet);
// result.append(tail);
// result.append("\n");
// for (int i = 0; i < indent + pointer - start + head.length(); i++) {
// result.append(" ");
// }
// result.append("^");
// return result.toString();
// }
//
// public String get_snippet() {
// return get_snippet(4, 75);
// }
//
// @Override
// public String toString() {
// String snippet = get_snippet();
// StringBuilder where = new StringBuilder(" in ");
// where.append(name);
// where.append(", line ");
// where.append(line + 1);
// where.append(", column ");
// where.append(column + 1);
// if (snippet != null) {
// where.append(":\n");
// where.append(snippet);
// }
// return where.toString();
// }
//
// public String getName() {
// return name;
// }
//
//
// // starts with 0
// public int getLine() {
// return line;
// }
//
// // starts with 0
// public int getColumn() {
// return column;
// }
//
// // starts with 0
// public int getIndex() {
// return index;
// }
//
// }
// Path: src/main/java/org/yaml/snakeyaml/events/Event.java
import org.yaml.snakeyaml.error.Mark;
/**
* Copyright (c) 2008, http://www.snakeyaml.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yaml.snakeyaml.events;
/**
* Basic unit of output from a {@link org.yaml.snakeyaml.parser.Parser} or input
* of a {@link org.yaml.snakeyaml.emitter.Emitter}.
*/
public abstract class Event {
public enum ID {
Alias, DocumentEnd, DocumentStart, MappingEnd, MappingStart, Scalar, SequenceEnd, SequenceStart, StreamEnd, StreamStart
}
| private final Mark startMark; |
bmoliveira/snake-yaml | src/test/java/org/pyyaml/PyMarkTest.java | // Path: src/main/java/org/yaml/snakeyaml/error/Mark.java
// public final class Mark {
// private String name;
// private int index;
// private int line;
// private int column;
// private String buffer;
// private int pointer;
//
// public Mark(String name, int index, int line, int column, String buffer, int pointer) {
// super();
// this.name = name;
// this.index = index;
// this.line = line;
// this.column = column;
// this.buffer = buffer;
// this.pointer = pointer;
// }
//
// private boolean isLineBreak(char ch) {
// return Constant.NULL_OR_LINEBR.has(ch);
// }
//
// public String get_snippet(int indent, int max_length) {
// if (buffer == null) {
// return null;
// }
// float half = max_length / 2 - 1;
// int start = pointer;
// String head = "";
// while ((start > 0) && !isLineBreak(buffer.charAt(start - 1))) {
// start -= 1;
// if (pointer - start > half) {
// head = " ... ";
// start += 5;
// break;
// }
// }
// String tail = "";
// int end = pointer;
// while ((end < buffer.length()) && !isLineBreak(buffer.charAt(end))) {
// end += 1;
// if (end - pointer > half) {
// tail = " ... ";
// end -= 5;
// break;
// }
// }
// String snippet = buffer.substring(start, end);
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < indent; i++) {
// result.append(" ");
// }
// result.append(head);
// result.append(snippet);
// result.append(tail);
// result.append("\n");
// for (int i = 0; i < indent + pointer - start + head.length(); i++) {
// result.append(" ");
// }
// result.append("^");
// return result.toString();
// }
//
// public String get_snippet() {
// return get_snippet(4, 75);
// }
//
// @Override
// public String toString() {
// String snippet = get_snippet();
// StringBuilder where = new StringBuilder(" in ");
// where.append(name);
// where.append(", line ");
// where.append(line + 1);
// where.append(", column ");
// where.append(column + 1);
// if (snippet != null) {
// where.append(":\n");
// where.append(snippet);
// }
// return where.toString();
// }
//
// public String getName() {
// return name;
// }
//
//
// // starts with 0
// public int getLine() {
// return line;
// }
//
// // starts with 0
// public int getColumn() {
// return column;
// }
//
// // starts with 0
// public int getIndex() {
// return index;
// }
//
// }
| import org.yaml.snakeyaml.error.Mark; | /**
* Copyright (c) 2008, http://www.snakeyaml.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pyyaml;
/**
* imported from PyYAML
*/
public class PyMarkTest extends PyImportTest {
public void testMarks() {
String content = getResource("test_mark.marks");
String[] inputs = content.split("---\n");
for (int i = 1; i < inputs.length; i++) {
String input = inputs[i];
int index = 0;
int line = 0;
int column = 0;
while (input.charAt(index) != '*') {
if (input.charAt(index) != '\n') {
line += 1;
column = 0;
} else {
column += 1;
}
index += 1;
} | // Path: src/main/java/org/yaml/snakeyaml/error/Mark.java
// public final class Mark {
// private String name;
// private int index;
// private int line;
// private int column;
// private String buffer;
// private int pointer;
//
// public Mark(String name, int index, int line, int column, String buffer, int pointer) {
// super();
// this.name = name;
// this.index = index;
// this.line = line;
// this.column = column;
// this.buffer = buffer;
// this.pointer = pointer;
// }
//
// private boolean isLineBreak(char ch) {
// return Constant.NULL_OR_LINEBR.has(ch);
// }
//
// public String get_snippet(int indent, int max_length) {
// if (buffer == null) {
// return null;
// }
// float half = max_length / 2 - 1;
// int start = pointer;
// String head = "";
// while ((start > 0) && !isLineBreak(buffer.charAt(start - 1))) {
// start -= 1;
// if (pointer - start > half) {
// head = " ... ";
// start += 5;
// break;
// }
// }
// String tail = "";
// int end = pointer;
// while ((end < buffer.length()) && !isLineBreak(buffer.charAt(end))) {
// end += 1;
// if (end - pointer > half) {
// tail = " ... ";
// end -= 5;
// break;
// }
// }
// String snippet = buffer.substring(start, end);
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < indent; i++) {
// result.append(" ");
// }
// result.append(head);
// result.append(snippet);
// result.append(tail);
// result.append("\n");
// for (int i = 0; i < indent + pointer - start + head.length(); i++) {
// result.append(" ");
// }
// result.append("^");
// return result.toString();
// }
//
// public String get_snippet() {
// return get_snippet(4, 75);
// }
//
// @Override
// public String toString() {
// String snippet = get_snippet();
// StringBuilder where = new StringBuilder(" in ");
// where.append(name);
// where.append(", line ");
// where.append(line + 1);
// where.append(", column ");
// where.append(column + 1);
// if (snippet != null) {
// where.append(":\n");
// where.append(snippet);
// }
// return where.toString();
// }
//
// public String getName() {
// return name;
// }
//
//
// // starts with 0
// public int getLine() {
// return line;
// }
//
// // starts with 0
// public int getColumn() {
// return column;
// }
//
// // starts with 0
// public int getIndex() {
// return index;
// }
//
// }
// Path: src/test/java/org/pyyaml/PyMarkTest.java
import org.yaml.snakeyaml.error.Mark;
/**
* Copyright (c) 2008, http://www.snakeyaml.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pyyaml;
/**
* imported from PyYAML
*/
public class PyMarkTest extends PyImportTest {
public void testMarks() {
String content = getResource("test_mark.marks");
String[] inputs = content.split("---\n");
for (int i = 1; i < inputs.length; i++) {
String input = inputs[i];
int index = 0;
int line = 0;
int column = 0;
while (input.charAt(index) != '*') {
if (input.charAt(index) != '\n') {
line += 1;
column = 0;
} else {
column += 1;
}
index += 1;
} | Mark mark = new Mark("testMarks", index, line, column, input, index); |
bmoliveira/snake-yaml | src/test/java/org/yaml/snakeyaml/tokens/BlockEndTokenTest.java | // Path: src/main/java/org/yaml/snakeyaml/error/Mark.java
// public final class Mark {
// private String name;
// private int index;
// private int line;
// private int column;
// private String buffer;
// private int pointer;
//
// public Mark(String name, int index, int line, int column, String buffer, int pointer) {
// super();
// this.name = name;
// this.index = index;
// this.line = line;
// this.column = column;
// this.buffer = buffer;
// this.pointer = pointer;
// }
//
// private boolean isLineBreak(char ch) {
// return Constant.NULL_OR_LINEBR.has(ch);
// }
//
// public String get_snippet(int indent, int max_length) {
// if (buffer == null) {
// return null;
// }
// float half = max_length / 2 - 1;
// int start = pointer;
// String head = "";
// while ((start > 0) && !isLineBreak(buffer.charAt(start - 1))) {
// start -= 1;
// if (pointer - start > half) {
// head = " ... ";
// start += 5;
// break;
// }
// }
// String tail = "";
// int end = pointer;
// while ((end < buffer.length()) && !isLineBreak(buffer.charAt(end))) {
// end += 1;
// if (end - pointer > half) {
// tail = " ... ";
// end -= 5;
// break;
// }
// }
// String snippet = buffer.substring(start, end);
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < indent; i++) {
// result.append(" ");
// }
// result.append(head);
// result.append(snippet);
// result.append(tail);
// result.append("\n");
// for (int i = 0; i < indent + pointer - start + head.length(); i++) {
// result.append(" ");
// }
// result.append("^");
// return result.toString();
// }
//
// public String get_snippet() {
// return get_snippet(4, 75);
// }
//
// @Override
// public String toString() {
// String snippet = get_snippet();
// StringBuilder where = new StringBuilder(" in ");
// where.append(name);
// where.append(", line ");
// where.append(line + 1);
// where.append(", column ");
// where.append(column + 1);
// if (snippet != null) {
// where.append(":\n");
// where.append(snippet);
// }
// return where.toString();
// }
//
// public String getName() {
// return name;
// }
//
//
// // starts with 0
// public int getLine() {
// return line;
// }
//
// // starts with 0
// public int getColumn() {
// return column;
// }
//
// // starts with 0
// public int getIndex() {
// return index;
// }
//
// }
| import junit.framework.TestCase;
import org.yaml.snakeyaml.error.Mark;
import org.yaml.snakeyaml.tokens.Token.ID; | /**
* Copyright (c) 2008, http://www.snakeyaml.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yaml.snakeyaml.tokens;
public class BlockEndTokenTest extends TestCase {
public void testGetArguments() { | // Path: src/main/java/org/yaml/snakeyaml/error/Mark.java
// public final class Mark {
// private String name;
// private int index;
// private int line;
// private int column;
// private String buffer;
// private int pointer;
//
// public Mark(String name, int index, int line, int column, String buffer, int pointer) {
// super();
// this.name = name;
// this.index = index;
// this.line = line;
// this.column = column;
// this.buffer = buffer;
// this.pointer = pointer;
// }
//
// private boolean isLineBreak(char ch) {
// return Constant.NULL_OR_LINEBR.has(ch);
// }
//
// public String get_snippet(int indent, int max_length) {
// if (buffer == null) {
// return null;
// }
// float half = max_length / 2 - 1;
// int start = pointer;
// String head = "";
// while ((start > 0) && !isLineBreak(buffer.charAt(start - 1))) {
// start -= 1;
// if (pointer - start > half) {
// head = " ... ";
// start += 5;
// break;
// }
// }
// String tail = "";
// int end = pointer;
// while ((end < buffer.length()) && !isLineBreak(buffer.charAt(end))) {
// end += 1;
// if (end - pointer > half) {
// tail = " ... ";
// end -= 5;
// break;
// }
// }
// String snippet = buffer.substring(start, end);
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < indent; i++) {
// result.append(" ");
// }
// result.append(head);
// result.append(snippet);
// result.append(tail);
// result.append("\n");
// for (int i = 0; i < indent + pointer - start + head.length(); i++) {
// result.append(" ");
// }
// result.append("^");
// return result.toString();
// }
//
// public String get_snippet() {
// return get_snippet(4, 75);
// }
//
// @Override
// public String toString() {
// String snippet = get_snippet();
// StringBuilder where = new StringBuilder(" in ");
// where.append(name);
// where.append(", line ");
// where.append(line + 1);
// where.append(", column ");
// where.append(column + 1);
// if (snippet != null) {
// where.append(":\n");
// where.append(snippet);
// }
// return where.toString();
// }
//
// public String getName() {
// return name;
// }
//
//
// // starts with 0
// public int getLine() {
// return line;
// }
//
// // starts with 0
// public int getColumn() {
// return column;
// }
//
// // starts with 0
// public int getIndex() {
// return index;
// }
//
// }
// Path: src/test/java/org/yaml/snakeyaml/tokens/BlockEndTokenTest.java
import junit.framework.TestCase;
import org.yaml.snakeyaml.error.Mark;
import org.yaml.snakeyaml.tokens.Token.ID;
/**
* Copyright (c) 2008, http://www.snakeyaml.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yaml.snakeyaml.tokens;
public class BlockEndTokenTest extends TestCase {
public void testGetArguments() { | Mark mark = new Mark("test1", 0, 0, 0, "*The first line.\nThe last line.", 0); |
bmoliveira/snake-yaml | src/test/java/org/yaml/snakeyaml/scanner/ScannerImplTest.java | // Path: src/main/java/org/yaml/snakeyaml/error/Mark.java
// public final class Mark {
// private String name;
// private int index;
// private int line;
// private int column;
// private String buffer;
// private int pointer;
//
// public Mark(String name, int index, int line, int column, String buffer, int pointer) {
// super();
// this.name = name;
// this.index = index;
// this.line = line;
// this.column = column;
// this.buffer = buffer;
// this.pointer = pointer;
// }
//
// private boolean isLineBreak(char ch) {
// return Constant.NULL_OR_LINEBR.has(ch);
// }
//
// public String get_snippet(int indent, int max_length) {
// if (buffer == null) {
// return null;
// }
// float half = max_length / 2 - 1;
// int start = pointer;
// String head = "";
// while ((start > 0) && !isLineBreak(buffer.charAt(start - 1))) {
// start -= 1;
// if (pointer - start > half) {
// head = " ... ";
// start += 5;
// break;
// }
// }
// String tail = "";
// int end = pointer;
// while ((end < buffer.length()) && !isLineBreak(buffer.charAt(end))) {
// end += 1;
// if (end - pointer > half) {
// tail = " ... ";
// end -= 5;
// break;
// }
// }
// String snippet = buffer.substring(start, end);
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < indent; i++) {
// result.append(" ");
// }
// result.append(head);
// result.append(snippet);
// result.append(tail);
// result.append("\n");
// for (int i = 0; i < indent + pointer - start + head.length(); i++) {
// result.append(" ");
// }
// result.append("^");
// return result.toString();
// }
//
// public String get_snippet() {
// return get_snippet(4, 75);
// }
//
// @Override
// public String toString() {
// String snippet = get_snippet();
// StringBuilder where = new StringBuilder(" in ");
// where.append(name);
// where.append(", line ");
// where.append(line + 1);
// where.append(", column ");
// where.append(column + 1);
// if (snippet != null) {
// where.append(":\n");
// where.append(snippet);
// }
// return where.toString();
// }
//
// public String getName() {
// return name;
// }
//
//
// // starts with 0
// public int getLine() {
// return line;
// }
//
// // starts with 0
// public int getColumn() {
// return column;
// }
//
// // starts with 0
// public int getIndex() {
// return index;
// }
//
// }
| import java.util.LinkedList;
import junit.framework.TestCase;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.error.Mark;
import org.yaml.snakeyaml.reader.StreamReader;
import org.yaml.snakeyaml.tokens.BlockEndToken;
import org.yaml.snakeyaml.tokens.BlockMappingStartToken;
import org.yaml.snakeyaml.tokens.KeyToken;
import org.yaml.snakeyaml.tokens.ScalarToken;
import org.yaml.snakeyaml.tokens.StreamEndToken;
import org.yaml.snakeyaml.tokens.StreamStartToken;
import org.yaml.snakeyaml.tokens.Token;
import org.yaml.snakeyaml.tokens.ValueToken; | /**
* Copyright (c) 2008, http://www.snakeyaml.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yaml.snakeyaml.scanner;
public class ScannerImplTest extends TestCase {
public void testGetToken() {
String data = "string: abcd";
StreamReader reader = new StreamReader(data);
Scanner scanner = new ScannerImpl(reader); | // Path: src/main/java/org/yaml/snakeyaml/error/Mark.java
// public final class Mark {
// private String name;
// private int index;
// private int line;
// private int column;
// private String buffer;
// private int pointer;
//
// public Mark(String name, int index, int line, int column, String buffer, int pointer) {
// super();
// this.name = name;
// this.index = index;
// this.line = line;
// this.column = column;
// this.buffer = buffer;
// this.pointer = pointer;
// }
//
// private boolean isLineBreak(char ch) {
// return Constant.NULL_OR_LINEBR.has(ch);
// }
//
// public String get_snippet(int indent, int max_length) {
// if (buffer == null) {
// return null;
// }
// float half = max_length / 2 - 1;
// int start = pointer;
// String head = "";
// while ((start > 0) && !isLineBreak(buffer.charAt(start - 1))) {
// start -= 1;
// if (pointer - start > half) {
// head = " ... ";
// start += 5;
// break;
// }
// }
// String tail = "";
// int end = pointer;
// while ((end < buffer.length()) && !isLineBreak(buffer.charAt(end))) {
// end += 1;
// if (end - pointer > half) {
// tail = " ... ";
// end -= 5;
// break;
// }
// }
// String snippet = buffer.substring(start, end);
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < indent; i++) {
// result.append(" ");
// }
// result.append(head);
// result.append(snippet);
// result.append(tail);
// result.append("\n");
// for (int i = 0; i < indent + pointer - start + head.length(); i++) {
// result.append(" ");
// }
// result.append("^");
// return result.toString();
// }
//
// public String get_snippet() {
// return get_snippet(4, 75);
// }
//
// @Override
// public String toString() {
// String snippet = get_snippet();
// StringBuilder where = new StringBuilder(" in ");
// where.append(name);
// where.append(", line ");
// where.append(line + 1);
// where.append(", column ");
// where.append(column + 1);
// if (snippet != null) {
// where.append(":\n");
// where.append(snippet);
// }
// return where.toString();
// }
//
// public String getName() {
// return name;
// }
//
//
// // starts with 0
// public int getLine() {
// return line;
// }
//
// // starts with 0
// public int getColumn() {
// return column;
// }
//
// // starts with 0
// public int getIndex() {
// return index;
// }
//
// }
// Path: src/test/java/org/yaml/snakeyaml/scanner/ScannerImplTest.java
import java.util.LinkedList;
import junit.framework.TestCase;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.error.Mark;
import org.yaml.snakeyaml.reader.StreamReader;
import org.yaml.snakeyaml.tokens.BlockEndToken;
import org.yaml.snakeyaml.tokens.BlockMappingStartToken;
import org.yaml.snakeyaml.tokens.KeyToken;
import org.yaml.snakeyaml.tokens.ScalarToken;
import org.yaml.snakeyaml.tokens.StreamEndToken;
import org.yaml.snakeyaml.tokens.StreamStartToken;
import org.yaml.snakeyaml.tokens.Token;
import org.yaml.snakeyaml.tokens.ValueToken;
/**
* Copyright (c) 2008, http://www.snakeyaml.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yaml.snakeyaml.scanner;
public class ScannerImplTest extends TestCase {
public void testGetToken() {
String data = "string: abcd";
StreamReader reader = new StreamReader(data);
Scanner scanner = new ScannerImpl(reader); | Mark dummy = new Mark("dummy", 0, 0, 0, "", 0); |
bmoliveira/snake-yaml | src/main/java/org/yaml/snakeyaml/nodes/Node.java | // Path: src/main/java/org/yaml/snakeyaml/error/Mark.java
// public final class Mark {
// private String name;
// private int index;
// private int line;
// private int column;
// private String buffer;
// private int pointer;
//
// public Mark(String name, int index, int line, int column, String buffer, int pointer) {
// super();
// this.name = name;
// this.index = index;
// this.line = line;
// this.column = column;
// this.buffer = buffer;
// this.pointer = pointer;
// }
//
// private boolean isLineBreak(char ch) {
// return Constant.NULL_OR_LINEBR.has(ch);
// }
//
// public String get_snippet(int indent, int max_length) {
// if (buffer == null) {
// return null;
// }
// float half = max_length / 2 - 1;
// int start = pointer;
// String head = "";
// while ((start > 0) && !isLineBreak(buffer.charAt(start - 1))) {
// start -= 1;
// if (pointer - start > half) {
// head = " ... ";
// start += 5;
// break;
// }
// }
// String tail = "";
// int end = pointer;
// while ((end < buffer.length()) && !isLineBreak(buffer.charAt(end))) {
// end += 1;
// if (end - pointer > half) {
// tail = " ... ";
// end -= 5;
// break;
// }
// }
// String snippet = buffer.substring(start, end);
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < indent; i++) {
// result.append(" ");
// }
// result.append(head);
// result.append(snippet);
// result.append(tail);
// result.append("\n");
// for (int i = 0; i < indent + pointer - start + head.length(); i++) {
// result.append(" ");
// }
// result.append("^");
// return result.toString();
// }
//
// public String get_snippet() {
// return get_snippet(4, 75);
// }
//
// @Override
// public String toString() {
// String snippet = get_snippet();
// StringBuilder where = new StringBuilder(" in ");
// where.append(name);
// where.append(", line ");
// where.append(line + 1);
// where.append(", column ");
// where.append(column + 1);
// if (snippet != null) {
// where.append(":\n");
// where.append(snippet);
// }
// return where.toString();
// }
//
// public String getName() {
// return name;
// }
//
//
// // starts with 0
// public int getLine() {
// return line;
// }
//
// // starts with 0
// public int getColumn() {
// return column;
// }
//
// // starts with 0
// public int getIndex() {
// return index;
// }
//
// }
| import org.yaml.snakeyaml.error.Mark; | /**
* Copyright (c) 2008, http://www.snakeyaml.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yaml.snakeyaml.nodes;
/**
* Base class for all nodes.
* <p>
* The nodes form the node-graph described in the <a
* href="http://yaml.org/spec/1.1/">YAML Specification</a>.
* </p>
* <p>
* While loading, the node graph is usually created by the
* {@link org.yaml.snakeyaml.composer.Composer}, and later transformed into
* application specific Java classes by the classes from the
* {@link org.yaml.snakeyaml.constructor} package.
* </p>
*/
public abstract class Node {
private Tag tag; | // Path: src/main/java/org/yaml/snakeyaml/error/Mark.java
// public final class Mark {
// private String name;
// private int index;
// private int line;
// private int column;
// private String buffer;
// private int pointer;
//
// public Mark(String name, int index, int line, int column, String buffer, int pointer) {
// super();
// this.name = name;
// this.index = index;
// this.line = line;
// this.column = column;
// this.buffer = buffer;
// this.pointer = pointer;
// }
//
// private boolean isLineBreak(char ch) {
// return Constant.NULL_OR_LINEBR.has(ch);
// }
//
// public String get_snippet(int indent, int max_length) {
// if (buffer == null) {
// return null;
// }
// float half = max_length / 2 - 1;
// int start = pointer;
// String head = "";
// while ((start > 0) && !isLineBreak(buffer.charAt(start - 1))) {
// start -= 1;
// if (pointer - start > half) {
// head = " ... ";
// start += 5;
// break;
// }
// }
// String tail = "";
// int end = pointer;
// while ((end < buffer.length()) && !isLineBreak(buffer.charAt(end))) {
// end += 1;
// if (end - pointer > half) {
// tail = " ... ";
// end -= 5;
// break;
// }
// }
// String snippet = buffer.substring(start, end);
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < indent; i++) {
// result.append(" ");
// }
// result.append(head);
// result.append(snippet);
// result.append(tail);
// result.append("\n");
// for (int i = 0; i < indent + pointer - start + head.length(); i++) {
// result.append(" ");
// }
// result.append("^");
// return result.toString();
// }
//
// public String get_snippet() {
// return get_snippet(4, 75);
// }
//
// @Override
// public String toString() {
// String snippet = get_snippet();
// StringBuilder where = new StringBuilder(" in ");
// where.append(name);
// where.append(", line ");
// where.append(line + 1);
// where.append(", column ");
// where.append(column + 1);
// if (snippet != null) {
// where.append(":\n");
// where.append(snippet);
// }
// return where.toString();
// }
//
// public String getName() {
// return name;
// }
//
//
// // starts with 0
// public int getLine() {
// return line;
// }
//
// // starts with 0
// public int getColumn() {
// return column;
// }
//
// // starts with 0
// public int getIndex() {
// return index;
// }
//
// }
// Path: src/main/java/org/yaml/snakeyaml/nodes/Node.java
import org.yaml.snakeyaml.error.Mark;
/**
* Copyright (c) 2008, http://www.snakeyaml.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yaml.snakeyaml.nodes;
/**
* Base class for all nodes.
* <p>
* The nodes form the node-graph described in the <a
* href="http://yaml.org/spec/1.1/">YAML Specification</a>.
* </p>
* <p>
* While loading, the node graph is usually created by the
* {@link org.yaml.snakeyaml.composer.Composer}, and later transformed into
* application specific Java classes by the classes from the
* {@link org.yaml.snakeyaml.constructor} package.
* </p>
*/
public abstract class Node {
private Tag tag; | private Mark startMark; |
bmoliveira/snake-yaml | src/test/java/org/pyyaml/PyCanonicalTest.java | // Path: src/main/java/org/yaml/snakeyaml/events/Event.java
// public abstract class Event {
// public enum ID {
// Alias, DocumentEnd, DocumentStart, MappingEnd, MappingStart, Scalar, SequenceEnd, SequenceStart, StreamEnd, StreamStart
// }
//
// private final Mark startMark;
// private final Mark endMark;
//
// public Event(Mark startMark, Mark endMark) {
// this.startMark = startMark;
// this.endMark = endMark;
// }
//
// public String toString() {
// return "<" + this.getClass().getName() + "(" + getArguments() + ")>";
// }
//
// public Mark getStartMark() {
// return startMark;
// }
//
// public Mark getEndMark() {
// return endMark;
// }
//
//
// // @see "__repr__ for Event in PyYAML"
// protected String getArguments() {
// return "";
// }
//
// public abstract boolean is(Event.ID id);
//
// /*
// * for tests only
// */
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof Event) {
// return toString().equals(obj.toString());
// } else {
// return false;
// }
// }
//
// /*
// * for tests only
// */
// @Override
// public int hashCode() {
// return toString().hashCode();
// }
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.yaml.snakeyaml.events.Event;
import org.yaml.snakeyaml.tokens.Token; | File[] files = getStreamsByExtension(".canonical");
assertTrue("No test files found.", files.length > 0);
for (int i = 0; i < files.length; i++) {
InputStream input = new FileInputStream(files[i]);
List<Token> tokens = canonicalScan(input);
input.close();
assertFalse(tokens.isEmpty());
}
}
private List<Token> canonicalScan(InputStream input) throws IOException {
int ch = input.read();
StringBuilder buffer = new StringBuilder();
while (ch != -1) {
buffer.append((char) ch);
ch = input.read();
}
CanonicalScanner scanner = new CanonicalScanner(buffer.toString());
List<Token> result = new ArrayList<Token>();
while (scanner.peekToken() != null) {
result.add(scanner.getToken());
}
return result;
}
public void testCanonicalParser() throws IOException {
File[] files = getStreamsByExtension(".canonical");
assertTrue("No test files found.", files.length > 0);
for (int i = 0; i < files.length; i++) {
InputStream input = new FileInputStream(files[i]); | // Path: src/main/java/org/yaml/snakeyaml/events/Event.java
// public abstract class Event {
// public enum ID {
// Alias, DocumentEnd, DocumentStart, MappingEnd, MappingStart, Scalar, SequenceEnd, SequenceStart, StreamEnd, StreamStart
// }
//
// private final Mark startMark;
// private final Mark endMark;
//
// public Event(Mark startMark, Mark endMark) {
// this.startMark = startMark;
// this.endMark = endMark;
// }
//
// public String toString() {
// return "<" + this.getClass().getName() + "(" + getArguments() + ")>";
// }
//
// public Mark getStartMark() {
// return startMark;
// }
//
// public Mark getEndMark() {
// return endMark;
// }
//
//
// // @see "__repr__ for Event in PyYAML"
// protected String getArguments() {
// return "";
// }
//
// public abstract boolean is(Event.ID id);
//
// /*
// * for tests only
// */
// @Override
// public boolean equals(Object obj) {
// if (obj instanceof Event) {
// return toString().equals(obj.toString());
// } else {
// return false;
// }
// }
//
// /*
// * for tests only
// */
// @Override
// public int hashCode() {
// return toString().hashCode();
// }
// }
// Path: src/test/java/org/pyyaml/PyCanonicalTest.java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.yaml.snakeyaml.events.Event;
import org.yaml.snakeyaml.tokens.Token;
File[] files = getStreamsByExtension(".canonical");
assertTrue("No test files found.", files.length > 0);
for (int i = 0; i < files.length; i++) {
InputStream input = new FileInputStream(files[i]);
List<Token> tokens = canonicalScan(input);
input.close();
assertFalse(tokens.isEmpty());
}
}
private List<Token> canonicalScan(InputStream input) throws IOException {
int ch = input.read();
StringBuilder buffer = new StringBuilder();
while (ch != -1) {
buffer.append((char) ch);
ch = input.read();
}
CanonicalScanner scanner = new CanonicalScanner(buffer.toString());
List<Token> result = new ArrayList<Token>();
while (scanner.peekToken() != null) {
result.add(scanner.getToken());
}
return result;
}
public void testCanonicalParser() throws IOException {
File[] files = getStreamsByExtension(".canonical");
assertTrue("No test files found.", files.length > 0);
for (int i = 0; i < files.length; i++) {
InputStream input = new FileInputStream(files[i]); | List<Event> tokens = canonicalParse(input); |
bmoliveira/snake-yaml | src/test/java/org/yaml/snakeyaml/constructor/AbstractConstructTest.java | // Path: src/main/java/org/yaml/snakeyaml/nodes/Node.java
// public abstract class Node {
// private Tag tag;
// private Mark startMark;
// protected Mark endMark;
// private Class<? extends Object> type;
// private boolean twoStepsConstruction;
// /**
// * true when the tag is assigned by the resolver
// */
// protected boolean resolved;
// protected Boolean useClassConstructor;
//
// public Node(Tag tag, Mark startMark, Mark endMark) {
// setTag(tag);
// this.startMark = startMark;
// this.endMark = endMark;
// this.type = Object.class;
// this.twoStepsConstruction = false;
// this.resolved = true;
// this.useClassConstructor = null;
// }
//
// /**
// * Tag of this node.
// * <p>
// * Every node has a tag assigned. The tag is either local or global.
// *
// * @return Tag of this node.
// */
// public Tag getTag() {
// return this.tag;
// }
//
// public Mark getEndMark() {
// return endMark;
// }
//
// /**
// * For error reporting.
// *
// * @see "class variable 'id' in PyYAML"
// * @return scalar, sequence, mapping
// */
// public abstract NodeId getNodeId();
//
// public Mark getStartMark() {
// return startMark;
// }
//
// public void setTag(Tag tag) {
// if (tag == null) {
// throw new NullPointerException("tag in a Node is required.");
// }
// this.tag = tag;
// }
//
// /**
// * Two Nodes are never equal.
// */
// @Override
// public final boolean equals(Object obj) {
// return super.equals(obj);
// }
//
// public Class<? extends Object> getType() {
// return type;
// }
//
// public void setType(Class<? extends Object> type) {
// if (!type.isAssignableFrom(this.type)) {
// this.type = type;
// }
// }
//
// public void setTwoStepsConstruction(boolean twoStepsConstruction) {
// this.twoStepsConstruction = twoStepsConstruction;
// }
//
// /**
// * Indicates if this node must be constructed in two steps.
// * <p>
// * Two-step construction is required whenever a node is a child (direct or
// * indirect) of it self. That is, if a recursive structure is build using
// * anchors and aliases.
// * </p>
// * <p>
// * Set by {@link org.yaml.snakeyaml.composer.Composer}, used during the
// * construction process.
// * </p>
// * <p>
// * Only relevant during loading.
// * </p>
// *
// * @return <code>true</code> if the node is self referenced.
// */
// public boolean isTwoStepsConstruction() {
// return twoStepsConstruction;
// }
//
// @Override
// public final int hashCode() {
// return super.hashCode();
// }
//
// public boolean useClassConstructor() {
// if (useClassConstructor == null) {
// if (!tag.isSecondary() && isResolved() && !Object.class.equals(type)
// && !tag.equals(Tag.NULL)) {
// return true;
// } else if (tag.isCompatible(getType())) {
// // the tag is compatible with the runtime class
// // the tag will be ignored
// return true;
// } else {
// return false;
// }
// }
// return useClassConstructor.booleanValue();
// }
//
// public void setUseClassConstructor(Boolean useClassConstructor) {
// this.useClassConstructor = useClassConstructor;
// }
//
// /**
// * Indicates if the tag was added by
// *
// * @return <code>true</code> if the tag of this node was resolved
// */
// public boolean isResolved() {
// return resolved;
// }
// }
| import junit.framework.TestCase;
import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.SequenceNode;
import org.yaml.snakeyaml.nodes.Tag;
import java.util.ArrayList; | /**
* Copyright (c) 2008, http://www.snakeyaml.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yaml.snakeyaml.constructor;
public class AbstractConstructTest extends TestCase {
public void testNotRecursive() {
AbstractConstruct abstractConstruct = new AbstractConstruct() { | // Path: src/main/java/org/yaml/snakeyaml/nodes/Node.java
// public abstract class Node {
// private Tag tag;
// private Mark startMark;
// protected Mark endMark;
// private Class<? extends Object> type;
// private boolean twoStepsConstruction;
// /**
// * true when the tag is assigned by the resolver
// */
// protected boolean resolved;
// protected Boolean useClassConstructor;
//
// public Node(Tag tag, Mark startMark, Mark endMark) {
// setTag(tag);
// this.startMark = startMark;
// this.endMark = endMark;
// this.type = Object.class;
// this.twoStepsConstruction = false;
// this.resolved = true;
// this.useClassConstructor = null;
// }
//
// /**
// * Tag of this node.
// * <p>
// * Every node has a tag assigned. The tag is either local or global.
// *
// * @return Tag of this node.
// */
// public Tag getTag() {
// return this.tag;
// }
//
// public Mark getEndMark() {
// return endMark;
// }
//
// /**
// * For error reporting.
// *
// * @see "class variable 'id' in PyYAML"
// * @return scalar, sequence, mapping
// */
// public abstract NodeId getNodeId();
//
// public Mark getStartMark() {
// return startMark;
// }
//
// public void setTag(Tag tag) {
// if (tag == null) {
// throw new NullPointerException("tag in a Node is required.");
// }
// this.tag = tag;
// }
//
// /**
// * Two Nodes are never equal.
// */
// @Override
// public final boolean equals(Object obj) {
// return super.equals(obj);
// }
//
// public Class<? extends Object> getType() {
// return type;
// }
//
// public void setType(Class<? extends Object> type) {
// if (!type.isAssignableFrom(this.type)) {
// this.type = type;
// }
// }
//
// public void setTwoStepsConstruction(boolean twoStepsConstruction) {
// this.twoStepsConstruction = twoStepsConstruction;
// }
//
// /**
// * Indicates if this node must be constructed in two steps.
// * <p>
// * Two-step construction is required whenever a node is a child (direct or
// * indirect) of it self. That is, if a recursive structure is build using
// * anchors and aliases.
// * </p>
// * <p>
// * Set by {@link org.yaml.snakeyaml.composer.Composer}, used during the
// * construction process.
// * </p>
// * <p>
// * Only relevant during loading.
// * </p>
// *
// * @return <code>true</code> if the node is self referenced.
// */
// public boolean isTwoStepsConstruction() {
// return twoStepsConstruction;
// }
//
// @Override
// public final int hashCode() {
// return super.hashCode();
// }
//
// public boolean useClassConstructor() {
// if (useClassConstructor == null) {
// if (!tag.isSecondary() && isResolved() && !Object.class.equals(type)
// && !tag.equals(Tag.NULL)) {
// return true;
// } else if (tag.isCompatible(getType())) {
// // the tag is compatible with the runtime class
// // the tag will be ignored
// return true;
// } else {
// return false;
// }
// }
// return useClassConstructor.booleanValue();
// }
//
// public void setUseClassConstructor(Boolean useClassConstructor) {
// this.useClassConstructor = useClassConstructor;
// }
//
// /**
// * Indicates if the tag was added by
// *
// * @return <code>true</code> if the tag of this node was resolved
// */
// public boolean isResolved() {
// return resolved;
// }
// }
// Path: src/test/java/org/yaml/snakeyaml/constructor/AbstractConstructTest.java
import junit.framework.TestCase;
import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.SequenceNode;
import org.yaml.snakeyaml.nodes.Tag;
import java.util.ArrayList;
/**
* Copyright (c) 2008, http://www.snakeyaml.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yaml.snakeyaml.constructor;
public class AbstractConstructTest extends TestCase {
public void testNotRecursive() {
AbstractConstruct abstractConstruct = new AbstractConstruct() { | public Object construct(Node node) { |
bmoliveira/snake-yaml | src/test/java/org/yaml/snakeyaml/nodes/NodeTest.java | // Path: src/main/java/org/yaml/snakeyaml/error/Mark.java
// public final class Mark {
// private String name;
// private int index;
// private int line;
// private int column;
// private String buffer;
// private int pointer;
//
// public Mark(String name, int index, int line, int column, String buffer, int pointer) {
// super();
// this.name = name;
// this.index = index;
// this.line = line;
// this.column = column;
// this.buffer = buffer;
// this.pointer = pointer;
// }
//
// private boolean isLineBreak(char ch) {
// return Constant.NULL_OR_LINEBR.has(ch);
// }
//
// public String get_snippet(int indent, int max_length) {
// if (buffer == null) {
// return null;
// }
// float half = max_length / 2 - 1;
// int start = pointer;
// String head = "";
// while ((start > 0) && !isLineBreak(buffer.charAt(start - 1))) {
// start -= 1;
// if (pointer - start > half) {
// head = " ... ";
// start += 5;
// break;
// }
// }
// String tail = "";
// int end = pointer;
// while ((end < buffer.length()) && !isLineBreak(buffer.charAt(end))) {
// end += 1;
// if (end - pointer > half) {
// tail = " ... ";
// end -= 5;
// break;
// }
// }
// String snippet = buffer.substring(start, end);
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < indent; i++) {
// result.append(" ");
// }
// result.append(head);
// result.append(snippet);
// result.append(tail);
// result.append("\n");
// for (int i = 0; i < indent + pointer - start + head.length(); i++) {
// result.append(" ");
// }
// result.append("^");
// return result.toString();
// }
//
// public String get_snippet() {
// return get_snippet(4, 75);
// }
//
// @Override
// public String toString() {
// String snippet = get_snippet();
// StringBuilder where = new StringBuilder(" in ");
// where.append(name);
// where.append(", line ");
// where.append(line + 1);
// where.append(", column ");
// where.append(column + 1);
// if (snippet != null) {
// where.append(":\n");
// where.append(snippet);
// }
// return where.toString();
// }
//
// public String getName() {
// return name;
// }
//
//
// // starts with 0
// public int getLine() {
// return line;
// }
//
// // starts with 0
// public int getColumn() {
// return column;
// }
//
// // starts with 0
// public int getIndex() {
// return index;
// }
//
// }
| import junit.framework.TestCase;
import org.yaml.snakeyaml.error.Mark; | /**
* Copyright (c) 2008, http://www.snakeyaml.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yaml.snakeyaml.nodes;
public class NodeTest extends TestCase {
public void testNode() {
try {
new ScalarNode(new Tag("!foo"), null, null, null, '"');
fail("Value must be required.");
} catch (Exception e) {
assertEquals("value in a Node is required.", e.getMessage());
}
}
public void testSetTag() {
try {
ScalarNode node = new ScalarNode(new Tag("!foo"), "Value1", null, null, '"');
node.setTag((Tag) null);
fail("Value must be required.");
} catch (Exception e) {
assertEquals("tag in a Node is required.", e.getMessage());
}
}
public void testGetEndMark() { | // Path: src/main/java/org/yaml/snakeyaml/error/Mark.java
// public final class Mark {
// private String name;
// private int index;
// private int line;
// private int column;
// private String buffer;
// private int pointer;
//
// public Mark(String name, int index, int line, int column, String buffer, int pointer) {
// super();
// this.name = name;
// this.index = index;
// this.line = line;
// this.column = column;
// this.buffer = buffer;
// this.pointer = pointer;
// }
//
// private boolean isLineBreak(char ch) {
// return Constant.NULL_OR_LINEBR.has(ch);
// }
//
// public String get_snippet(int indent, int max_length) {
// if (buffer == null) {
// return null;
// }
// float half = max_length / 2 - 1;
// int start = pointer;
// String head = "";
// while ((start > 0) && !isLineBreak(buffer.charAt(start - 1))) {
// start -= 1;
// if (pointer - start > half) {
// head = " ... ";
// start += 5;
// break;
// }
// }
// String tail = "";
// int end = pointer;
// while ((end < buffer.length()) && !isLineBreak(buffer.charAt(end))) {
// end += 1;
// if (end - pointer > half) {
// tail = " ... ";
// end -= 5;
// break;
// }
// }
// String snippet = buffer.substring(start, end);
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < indent; i++) {
// result.append(" ");
// }
// result.append(head);
// result.append(snippet);
// result.append(tail);
// result.append("\n");
// for (int i = 0; i < indent + pointer - start + head.length(); i++) {
// result.append(" ");
// }
// result.append("^");
// return result.toString();
// }
//
// public String get_snippet() {
// return get_snippet(4, 75);
// }
//
// @Override
// public String toString() {
// String snippet = get_snippet();
// StringBuilder where = new StringBuilder(" in ");
// where.append(name);
// where.append(", line ");
// where.append(line + 1);
// where.append(", column ");
// where.append(column + 1);
// if (snippet != null) {
// where.append(":\n");
// where.append(snippet);
// }
// return where.toString();
// }
//
// public String getName() {
// return name;
// }
//
//
// // starts with 0
// public int getLine() {
// return line;
// }
//
// // starts with 0
// public int getColumn() {
// return column;
// }
//
// // starts with 0
// public int getIndex() {
// return index;
// }
//
// }
// Path: src/test/java/org/yaml/snakeyaml/nodes/NodeTest.java
import junit.framework.TestCase;
import org.yaml.snakeyaml.error.Mark;
/**
* Copyright (c) 2008, http://www.snakeyaml.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yaml.snakeyaml.nodes;
public class NodeTest extends TestCase {
public void testNode() {
try {
new ScalarNode(new Tag("!foo"), null, null, null, '"');
fail("Value must be required.");
} catch (Exception e) {
assertEquals("value in a Node is required.", e.getMessage());
}
}
public void testSetTag() {
try {
ScalarNode node = new ScalarNode(new Tag("!foo"), "Value1", null, null, '"');
node.setTag((Tag) null);
fail("Value must be required.");
} catch (Exception e) {
assertEquals("tag in a Node is required.", e.getMessage());
}
}
public void testGetEndMark() { | Mark mark1 = new Mark("name", 5, 2, 12, "afd asd asd", 7); |
bmoliveira/snake-yaml | src/main/java/org/yaml/snakeyaml/nodes/ScalarNode.java | // Path: src/main/java/org/yaml/snakeyaml/error/Mark.java
// public final class Mark {
// private String name;
// private int index;
// private int line;
// private int column;
// private String buffer;
// private int pointer;
//
// public Mark(String name, int index, int line, int column, String buffer, int pointer) {
// super();
// this.name = name;
// this.index = index;
// this.line = line;
// this.column = column;
// this.buffer = buffer;
// this.pointer = pointer;
// }
//
// private boolean isLineBreak(char ch) {
// return Constant.NULL_OR_LINEBR.has(ch);
// }
//
// public String get_snippet(int indent, int max_length) {
// if (buffer == null) {
// return null;
// }
// float half = max_length / 2 - 1;
// int start = pointer;
// String head = "";
// while ((start > 0) && !isLineBreak(buffer.charAt(start - 1))) {
// start -= 1;
// if (pointer - start > half) {
// head = " ... ";
// start += 5;
// break;
// }
// }
// String tail = "";
// int end = pointer;
// while ((end < buffer.length()) && !isLineBreak(buffer.charAt(end))) {
// end += 1;
// if (end - pointer > half) {
// tail = " ... ";
// end -= 5;
// break;
// }
// }
// String snippet = buffer.substring(start, end);
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < indent; i++) {
// result.append(" ");
// }
// result.append(head);
// result.append(snippet);
// result.append(tail);
// result.append("\n");
// for (int i = 0; i < indent + pointer - start + head.length(); i++) {
// result.append(" ");
// }
// result.append("^");
// return result.toString();
// }
//
// public String get_snippet() {
// return get_snippet(4, 75);
// }
//
// @Override
// public String toString() {
// String snippet = get_snippet();
// StringBuilder where = new StringBuilder(" in ");
// where.append(name);
// where.append(", line ");
// where.append(line + 1);
// where.append(", column ");
// where.append(column + 1);
// if (snippet != null) {
// where.append(":\n");
// where.append(snippet);
// }
// return where.toString();
// }
//
// public String getName() {
// return name;
// }
//
//
// // starts with 0
// public int getLine() {
// return line;
// }
//
// // starts with 0
// public int getColumn() {
// return column;
// }
//
// // starts with 0
// public int getIndex() {
// return index;
// }
//
// }
| import org.yaml.snakeyaml.error.Mark; | /**
* Copyright (c) 2008, http://www.snakeyaml.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yaml.snakeyaml.nodes;
/**
* Represents a scalar node.
* <p>
* Scalar nodes form the leaves in the node graph.
* </p>
*/
public class ScalarNode extends Node {
private Character style;
private String value;
| // Path: src/main/java/org/yaml/snakeyaml/error/Mark.java
// public final class Mark {
// private String name;
// private int index;
// private int line;
// private int column;
// private String buffer;
// private int pointer;
//
// public Mark(String name, int index, int line, int column, String buffer, int pointer) {
// super();
// this.name = name;
// this.index = index;
// this.line = line;
// this.column = column;
// this.buffer = buffer;
// this.pointer = pointer;
// }
//
// private boolean isLineBreak(char ch) {
// return Constant.NULL_OR_LINEBR.has(ch);
// }
//
// public String get_snippet(int indent, int max_length) {
// if (buffer == null) {
// return null;
// }
// float half = max_length / 2 - 1;
// int start = pointer;
// String head = "";
// while ((start > 0) && !isLineBreak(buffer.charAt(start - 1))) {
// start -= 1;
// if (pointer - start > half) {
// head = " ... ";
// start += 5;
// break;
// }
// }
// String tail = "";
// int end = pointer;
// while ((end < buffer.length()) && !isLineBreak(buffer.charAt(end))) {
// end += 1;
// if (end - pointer > half) {
// tail = " ... ";
// end -= 5;
// break;
// }
// }
// String snippet = buffer.substring(start, end);
// StringBuilder result = new StringBuilder();
// for (int i = 0; i < indent; i++) {
// result.append(" ");
// }
// result.append(head);
// result.append(snippet);
// result.append(tail);
// result.append("\n");
// for (int i = 0; i < indent + pointer - start + head.length(); i++) {
// result.append(" ");
// }
// result.append("^");
// return result.toString();
// }
//
// public String get_snippet() {
// return get_snippet(4, 75);
// }
//
// @Override
// public String toString() {
// String snippet = get_snippet();
// StringBuilder where = new StringBuilder(" in ");
// where.append(name);
// where.append(", line ");
// where.append(line + 1);
// where.append(", column ");
// where.append(column + 1);
// if (snippet != null) {
// where.append(":\n");
// where.append(snippet);
// }
// return where.toString();
// }
//
// public String getName() {
// return name;
// }
//
//
// // starts with 0
// public int getLine() {
// return line;
// }
//
// // starts with 0
// public int getColumn() {
// return column;
// }
//
// // starts with 0
// public int getIndex() {
// return index;
// }
//
// }
// Path: src/main/java/org/yaml/snakeyaml/nodes/ScalarNode.java
import org.yaml.snakeyaml.error.Mark;
/**
* Copyright (c) 2008, http://www.snakeyaml.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yaml.snakeyaml.nodes;
/**
* Represents a scalar node.
* <p>
* Scalar nodes form the leaves in the node graph.
* </p>
*/
public class ScalarNode extends Node {
private Character style;
private String value;
| public ScalarNode(Tag tag, String value, Mark startMark, Mark endMark, Character style) { |
bmoliveira/snake-yaml | src/test/java/org/yaml/snakeyaml/Chapter2_3Test.java | // Path: src/main/java/org/yaml/snakeyaml/DumperOptions.java
// public enum ScalarStyle {
// DOUBLE_QUOTED(Character.valueOf('"')), SINGLE_QUOTED(Character.valueOf('\'')), LITERAL(
// Character.valueOf('|')), FOLDED(Character.valueOf('>')), PLAIN(null);
// private Character styleChar;
//
// private ScalarStyle(Character style) {
// this.styleChar = style;
// }
//
// public Character getChar() {
// return styleChar;
// }
//
// @Override
// public String toString() {
// return "Scalar style: '" + styleChar + "'";
// }
//
// public static ScalarStyle createStyle(Character style) {
// if (style == null) {
// return PLAIN;
// } else {
// switch (style) {
// case '"':
// return DOUBLE_QUOTED;
// case '\'':
// return SINGLE_QUOTED;
// case '|':
// return LITERAL;
// case '>':
// return FOLDED;
// default:
// throw new YAMLException("Unknown scalar style character: " + style);
// }
// }
// }
// }
| import java.io.InputStream;
import java.util.Map;
import junit.framework.TestCase;
import org.yaml.snakeyaml.DumperOptions.ScalarStyle; | /**
* Copyright (c) 2008, http://www.snakeyaml.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yaml.snakeyaml;
/**
* Test Chapter 2.3 from the YAML specification
*
* @see <a href="http://yaml.org/spec/1.1/"></a>
*/
public class Chapter2_3Test extends TestCase {
public void testExample_2_13() {
YamlDocument document = new YamlDocument("example2_13.yaml");
String data = (String) document.getNativeData();
assertEquals("\\//||\\/||\n// || ||__\n", data);
}
public void testExample_2_14() {
YamlDocument document = new YamlDocument("example2_14.yaml");
String data = (String) document.getNativeData();
assertEquals("Mark McGwire's year was crippled by a knee injury.", data);
}
public void testExample_2_15() {
String etalon = "Sammy Sosa completed another fine season with great stats.\n\n 63 Home Runs\n 0.288 Batting Average\n\nWhat a year!\n";
InputStream input = YamlDocument.class.getClassLoader().getResourceAsStream(
YamlDocument.ROOT + "example2_15.yaml");
DumperOptions options = new DumperOptions(); | // Path: src/main/java/org/yaml/snakeyaml/DumperOptions.java
// public enum ScalarStyle {
// DOUBLE_QUOTED(Character.valueOf('"')), SINGLE_QUOTED(Character.valueOf('\'')), LITERAL(
// Character.valueOf('|')), FOLDED(Character.valueOf('>')), PLAIN(null);
// private Character styleChar;
//
// private ScalarStyle(Character style) {
// this.styleChar = style;
// }
//
// public Character getChar() {
// return styleChar;
// }
//
// @Override
// public String toString() {
// return "Scalar style: '" + styleChar + "'";
// }
//
// public static ScalarStyle createStyle(Character style) {
// if (style == null) {
// return PLAIN;
// } else {
// switch (style) {
// case '"':
// return DOUBLE_QUOTED;
// case '\'':
// return SINGLE_QUOTED;
// case '|':
// return LITERAL;
// case '>':
// return FOLDED;
// default:
// throw new YAMLException("Unknown scalar style character: " + style);
// }
// }
// }
// }
// Path: src/test/java/org/yaml/snakeyaml/Chapter2_3Test.java
import java.io.InputStream;
import java.util.Map;
import junit.framework.TestCase;
import org.yaml.snakeyaml.DumperOptions.ScalarStyle;
/**
* Copyright (c) 2008, http://www.snakeyaml.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yaml.snakeyaml;
/**
* Test Chapter 2.3 from the YAML specification
*
* @see <a href="http://yaml.org/spec/1.1/"></a>
*/
public class Chapter2_3Test extends TestCase {
public void testExample_2_13() {
YamlDocument document = new YamlDocument("example2_13.yaml");
String data = (String) document.getNativeData();
assertEquals("\\//||\\/||\n// || ||__\n", data);
}
public void testExample_2_14() {
YamlDocument document = new YamlDocument("example2_14.yaml");
String data = (String) document.getNativeData();
assertEquals("Mark McGwire's year was crippled by a knee injury.", data);
}
public void testExample_2_15() {
String etalon = "Sammy Sosa completed another fine season with great stats.\n\n 63 Home Runs\n 0.288 Batting Average\n\nWhat a year!\n";
InputStream input = YamlDocument.class.getClassLoader().getResourceAsStream(
YamlDocument.ROOT + "example2_15.yaml");
DumperOptions options = new DumperOptions(); | options.setDefaultScalarStyle(ScalarStyle.FOLDED); |
olap4j/olap4j | src/org/olap4j/driver/xmla/XmlaOlap4jCube.java | // Path: src/org/olap4j/driver/xmla/XmlaOlap4jConnection.java
// enum BackendFlavor {
// MONDRIAN("Mondrian"),
// SSAS("Microsoft"),
// PALO("Palo"),
// SAP("SAP"),
// ESSBASE("Essbase"),
// UNKNOWN("");
//
// private final String token;
//
// private BackendFlavor(String token) {
// this.token = token;
// }
//
// static BackendFlavor getFlavor(OlapConnection conn, boolean fail)
// throws OlapException
// {
// return getFlavor(
// conn.getOlapDatabase().getDataSourceInfo(),
// conn.getOlapDatabase().getProviderName(),
// fail);
// }
//
// static BackendFlavor getFlavor(
// String dataSourceInfo, String providerName, boolean fail)
// {
// for (BackendFlavor flavor : BackendFlavor.values()) {
// if (providerName.toUpperCase()
// .contains(flavor.token.toUpperCase())
// || dataSourceInfo.toUpperCase()
// .contains(flavor.token.toUpperCase()))
// {
// return flavor;
// }
// }
// if (fail) {
// throw new AssertionError("Can't determine the backend vendor.");
// } else {
// return UNKNOWN;
// }
// }
// }
| import org.olap4j.OlapException;
import org.olap4j.driver.xmla.XmlaOlap4jConnection.BackendFlavor;
import org.olap4j.impl.*;
import org.olap4j.mdx.IdentifierSegment;
import org.olap4j.metadata.*;
import java.lang.ref.SoftReference;
import java.util.*; | new NamedListImpl<XmlaOlap4jMember>();
lookupMemberRelatives(
Olap4jUtil.enumSetOf(Member.TreeOp.SELF),
memberUniqueName,
list);
switch (list.size()) {
case 0:
return null;
case 1:
return list.get(0);
default:
String providerName =
olap4jSchema.olap4jCatalog.olap4jDatabaseMetaData
.olap4jConnection.getOlapDatabase().getProviderName();
if ("Microsoft Analysis Services".equals(providerName)) {
return list.get(0);
}
throw new IllegalArgumentException(
"more than one member with unique name '"
+ memberUniqueName
+ "'");
}
}
public void lookupMembersByUniqueName(
List<String> memberUniqueNames,
Map<String, XmlaOlap4jMember> memberMap) throws OlapException
{
final XmlaOlap4jDatabaseMetaData m =
olap4jSchema.olap4jCatalog.olap4jDatabaseMetaData; | // Path: src/org/olap4j/driver/xmla/XmlaOlap4jConnection.java
// enum BackendFlavor {
// MONDRIAN("Mondrian"),
// SSAS("Microsoft"),
// PALO("Palo"),
// SAP("SAP"),
// ESSBASE("Essbase"),
// UNKNOWN("");
//
// private final String token;
//
// private BackendFlavor(String token) {
// this.token = token;
// }
//
// static BackendFlavor getFlavor(OlapConnection conn, boolean fail)
// throws OlapException
// {
// return getFlavor(
// conn.getOlapDatabase().getDataSourceInfo(),
// conn.getOlapDatabase().getProviderName(),
// fail);
// }
//
// static BackendFlavor getFlavor(
// String dataSourceInfo, String providerName, boolean fail)
// {
// for (BackendFlavor flavor : BackendFlavor.values()) {
// if (providerName.toUpperCase()
// .contains(flavor.token.toUpperCase())
// || dataSourceInfo.toUpperCase()
// .contains(flavor.token.toUpperCase()))
// {
// return flavor;
// }
// }
// if (fail) {
// throw new AssertionError("Can't determine the backend vendor.");
// } else {
// return UNKNOWN;
// }
// }
// }
// Path: src/org/olap4j/driver/xmla/XmlaOlap4jCube.java
import org.olap4j.OlapException;
import org.olap4j.driver.xmla.XmlaOlap4jConnection.BackendFlavor;
import org.olap4j.impl.*;
import org.olap4j.mdx.IdentifierSegment;
import org.olap4j.metadata.*;
import java.lang.ref.SoftReference;
import java.util.*;
new NamedListImpl<XmlaOlap4jMember>();
lookupMemberRelatives(
Olap4jUtil.enumSetOf(Member.TreeOp.SELF),
memberUniqueName,
list);
switch (list.size()) {
case 0:
return null;
case 1:
return list.get(0);
default:
String providerName =
olap4jSchema.olap4jCatalog.olap4jDatabaseMetaData
.olap4jConnection.getOlapDatabase().getProviderName();
if ("Microsoft Analysis Services".equals(providerName)) {
return list.get(0);
}
throw new IllegalArgumentException(
"more than one member with unique name '"
+ memberUniqueName
+ "'");
}
}
public void lookupMembersByUniqueName(
List<String> memberUniqueNames,
Map<String, XmlaOlap4jMember> memberMap) throws OlapException
{
final XmlaOlap4jDatabaseMetaData m =
olap4jSchema.olap4jCatalog.olap4jDatabaseMetaData; | switch (BackendFlavor.getFlavor(m.olap4jConnection, false)) { |
olap4j/olap4j | src/org/olap4j/driver/xmla/XmlaOlap4jStatement.java | // Path: src/org/olap4j/driver/xmla/XmlaOlap4jConnection.java
// enum BackendFlavor {
// MONDRIAN("Mondrian"),
// SSAS("Microsoft"),
// PALO("Palo"),
// SAP("SAP"),
// ESSBASE("Essbase"),
// UNKNOWN("");
//
// private final String token;
//
// private BackendFlavor(String token) {
// this.token = token;
// }
//
// static BackendFlavor getFlavor(OlapConnection conn, boolean fail)
// throws OlapException
// {
// return getFlavor(
// conn.getOlapDatabase().getDataSourceInfo(),
// conn.getOlapDatabase().getProviderName(),
// fail);
// }
//
// static BackendFlavor getFlavor(
// String dataSourceInfo, String providerName, boolean fail)
// {
// for (BackendFlavor flavor : BackendFlavor.values()) {
// if (providerName.toUpperCase()
// .contains(flavor.token.toUpperCase())
// || dataSourceInfo.toUpperCase()
// .contains(flavor.token.toUpperCase()))
// {
// return flavor;
// }
// }
// if (fail) {
// throw new AssertionError("Can't determine the backend vendor.");
// } else {
// return UNKNOWN;
// }
// }
// }
| import org.olap4j.*;
import org.olap4j.driver.xmla.XmlaOlap4jConnection.BackendFlavor;
import org.olap4j.mdx.*;
import java.io.StringWriter;
import java.sql.*;
import java.util.concurrent.*; | public void setPoolable(boolean poolable) throws SQLException {
throw new UnsupportedOperationException();
}
public boolean isPoolable() throws SQLException {
throw new UnsupportedOperationException();
}
// implement Wrapper
public <T> T unwrap(Class<T> iface) throws SQLException {
if (iface.isInstance(this)) {
return iface.cast(this);
}
throw getHelper().createException(
"does not implement '" + iface + "'");
}
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return iface.isInstance(this);
}
// implement OlapStatement
public CellSet executeOlapQuery(String mdx) throws OlapException {
final String catalog = olap4jConnection.getCatalog();
final String roleName = olap4jConnection.getRoleName();
final String propList = olap4jConnection.makeConnectionPropertyList();
final String dataSourceInfo; | // Path: src/org/olap4j/driver/xmla/XmlaOlap4jConnection.java
// enum BackendFlavor {
// MONDRIAN("Mondrian"),
// SSAS("Microsoft"),
// PALO("Palo"),
// SAP("SAP"),
// ESSBASE("Essbase"),
// UNKNOWN("");
//
// private final String token;
//
// private BackendFlavor(String token) {
// this.token = token;
// }
//
// static BackendFlavor getFlavor(OlapConnection conn, boolean fail)
// throws OlapException
// {
// return getFlavor(
// conn.getOlapDatabase().getDataSourceInfo(),
// conn.getOlapDatabase().getProviderName(),
// fail);
// }
//
// static BackendFlavor getFlavor(
// String dataSourceInfo, String providerName, boolean fail)
// {
// for (BackendFlavor flavor : BackendFlavor.values()) {
// if (providerName.toUpperCase()
// .contains(flavor.token.toUpperCase())
// || dataSourceInfo.toUpperCase()
// .contains(flavor.token.toUpperCase()))
// {
// return flavor;
// }
// }
// if (fail) {
// throw new AssertionError("Can't determine the backend vendor.");
// } else {
// return UNKNOWN;
// }
// }
// }
// Path: src/org/olap4j/driver/xmla/XmlaOlap4jStatement.java
import org.olap4j.*;
import org.olap4j.driver.xmla.XmlaOlap4jConnection.BackendFlavor;
import org.olap4j.mdx.*;
import java.io.StringWriter;
import java.sql.*;
import java.util.concurrent.*;
public void setPoolable(boolean poolable) throws SQLException {
throw new UnsupportedOperationException();
}
public boolean isPoolable() throws SQLException {
throw new UnsupportedOperationException();
}
// implement Wrapper
public <T> T unwrap(Class<T> iface) throws SQLException {
if (iface.isInstance(this)) {
return iface.cast(this);
}
throw getHelper().createException(
"does not implement '" + iface + "'");
}
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return iface.isInstance(this);
}
// implement OlapStatement
public CellSet executeOlapQuery(String mdx) throws OlapException {
final String catalog = olap4jConnection.getCatalog();
final String roleName = olap4jConnection.getRoleName();
final String propList = olap4jConnection.makeConnectionPropertyList();
final String dataSourceInfo; | switch (BackendFlavor.getFlavor(olap4jConnection, true)) { |
HugoGresse/Anecdote | app/src/main/java/io/gresse/hugo/anecdote/api/model/Content.java | // Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/model/Anecdote.java
// @Entity
// public class Anecdote implements Cloneable {
//
// @Id
// public long id;
// @Index
// @Nullable
// public String type;
// public String text;
// @Nullable
// @Index
// public String permalink;
// @Nullable
// public String media;
// @Index
// public String websitePageSlug;
// public long favoritesTimestamp; // Favorites date, if not favorite: 0L
//
// public Anecdote(String text, String permalink) {
// this(MediaType.TEXT, text, permalink, null);
// }
//
// public Anecdote(@Nullable String type, String text, @Nullable String permalink, @Nullable String media) {
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// }
//
// @Generated(1799107445)
// @Internal
// /** This constructor was generated by ObjectBox and may change any time. */
// public Anecdote(long id, String type, String text, String permalink, String media, String websitePageSlug,
// long favoritesTimestamp) {
// this.id = id;
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// this.websitePageSlug = websitePageSlug;
// this.favoritesTimestamp = favoritesTimestamp;
// }
//
// @Generated(443678178)
// public Anecdote() {
// }
//
// /**
// * Return the text without html
// *
// * @return plain text text
// */
// public String getPlainTextContent() {
// return Jsoup.parse(text.replace("<br>", "#lb#")).text().replace("#lb#", System.getProperty("line.separator"));
// }
//
// /**
// * Get the share string of the
// * @param context app context
// * @return the shareable string description of this anecdote
// */
// public String getShareString(Context context){
// String copyString = getPlainTextContent();
//
// if(!TextUtils.isEmpty(permalink)){
// copyString += " " + permalink;
// }
//
// copyString += " " + context.getString(R.string.app_share_credits);
//
// return copyString;
// }
//
// /**
// * Return if the anecdote has been favorited by the user, in the current session (meaning it is not stored).
// */
// public boolean isFavorite(){
// return favoritesTimestamp != 0L;
// }
//
// @Override
// public Anecdote clone() throws CloneNotSupportedException {
// Object o = null;
// try {
// o = super.clone();
// } catch(CloneNotSupportedException cnse) {
// cnse.printStackTrace(System.err);
// }
// return (Anecdote) o;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Anecdote anecdote = (Anecdote) o;
//
// if (type != null ? !type.equals(anecdote.type) : anecdote.type != null) return false;
// if (text != null ? !text.equals(anecdote.text) : anecdote.text != null) return false;
// //noinspection SimplifiableIfStatement
// if (permalink != null ? !permalink.equals(anecdote.permalink) : anecdote.permalink != null) return false;
// return media != null ? media.equals(anecdote.media) : anecdote.media == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = type != null ? type.hashCode() : 0;
// result = 31 * result + (text != null ? text.hashCode() : 0);
// result = 31 * result + (permalink != null ? permalink.hashCode() : 0);
// result = 31 * result + (media != null ? media.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Anecdote text='" + text + "'\', permalink='" + permalink + '\'';
// }
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/model/MediaType.java
// public class MediaType {
//
// public static final String URL = "url";
// public static final String TEXT = "text";
// public static final String IMAGE = "image";
// public static final String VIDEO = "video";
//
// }
| import android.support.annotation.Nullable;
import android.support.v4.util.Pair;
import android.text.TextUtils;
import org.jsoup.nodes.Element;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import io.gresse.hugo.anecdote.anecdote.model.Anecdote;
import io.gresse.hugo.anecdote.anecdote.model.MediaType; | package io.gresse.hugo.anecdote.api.model;
/**
* Represent the text parsing option for a {@link WebsitePage}
*
* Created by Hugo Gresse on 08/06/16.
*/
public class Content {
@Nullable
public Item url;
public List<ContentItem> items;
public Content() {
items = new ArrayList<>();
}
| // Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/model/Anecdote.java
// @Entity
// public class Anecdote implements Cloneable {
//
// @Id
// public long id;
// @Index
// @Nullable
// public String type;
// public String text;
// @Nullable
// @Index
// public String permalink;
// @Nullable
// public String media;
// @Index
// public String websitePageSlug;
// public long favoritesTimestamp; // Favorites date, if not favorite: 0L
//
// public Anecdote(String text, String permalink) {
// this(MediaType.TEXT, text, permalink, null);
// }
//
// public Anecdote(@Nullable String type, String text, @Nullable String permalink, @Nullable String media) {
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// }
//
// @Generated(1799107445)
// @Internal
// /** This constructor was generated by ObjectBox and may change any time. */
// public Anecdote(long id, String type, String text, String permalink, String media, String websitePageSlug,
// long favoritesTimestamp) {
// this.id = id;
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// this.websitePageSlug = websitePageSlug;
// this.favoritesTimestamp = favoritesTimestamp;
// }
//
// @Generated(443678178)
// public Anecdote() {
// }
//
// /**
// * Return the text without html
// *
// * @return plain text text
// */
// public String getPlainTextContent() {
// return Jsoup.parse(text.replace("<br>", "#lb#")).text().replace("#lb#", System.getProperty("line.separator"));
// }
//
// /**
// * Get the share string of the
// * @param context app context
// * @return the shareable string description of this anecdote
// */
// public String getShareString(Context context){
// String copyString = getPlainTextContent();
//
// if(!TextUtils.isEmpty(permalink)){
// copyString += " " + permalink;
// }
//
// copyString += " " + context.getString(R.string.app_share_credits);
//
// return copyString;
// }
//
// /**
// * Return if the anecdote has been favorited by the user, in the current session (meaning it is not stored).
// */
// public boolean isFavorite(){
// return favoritesTimestamp != 0L;
// }
//
// @Override
// public Anecdote clone() throws CloneNotSupportedException {
// Object o = null;
// try {
// o = super.clone();
// } catch(CloneNotSupportedException cnse) {
// cnse.printStackTrace(System.err);
// }
// return (Anecdote) o;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Anecdote anecdote = (Anecdote) o;
//
// if (type != null ? !type.equals(anecdote.type) : anecdote.type != null) return false;
// if (text != null ? !text.equals(anecdote.text) : anecdote.text != null) return false;
// //noinspection SimplifiableIfStatement
// if (permalink != null ? !permalink.equals(anecdote.permalink) : anecdote.permalink != null) return false;
// return media != null ? media.equals(anecdote.media) : anecdote.media == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = type != null ? type.hashCode() : 0;
// result = 31 * result + (text != null ? text.hashCode() : 0);
// result = 31 * result + (permalink != null ? permalink.hashCode() : 0);
// result = 31 * result + (media != null ? media.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Anecdote text='" + text + "'\', permalink='" + permalink + '\'';
// }
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/model/MediaType.java
// public class MediaType {
//
// public static final String URL = "url";
// public static final String TEXT = "text";
// public static final String IMAGE = "image";
// public static final String VIDEO = "video";
//
// }
// Path: app/src/main/java/io/gresse/hugo/anecdote/api/model/Content.java
import android.support.annotation.Nullable;
import android.support.v4.util.Pair;
import android.text.TextUtils;
import org.jsoup.nodes.Element;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import io.gresse.hugo.anecdote.anecdote.model.Anecdote;
import io.gresse.hugo.anecdote.anecdote.model.MediaType;
package io.gresse.hugo.anecdote.api.model;
/**
* Represent the text parsing option for a {@link WebsitePage}
*
* Created by Hugo Gresse on 08/06/16.
*/
public class Content {
@Nullable
public Item url;
public List<ContentItem> items;
public Content() {
items = new ArrayList<>();
}
| public Anecdote getAnecdote(Element element, Element tempElement){ |
HugoGresse/Anecdote | app/src/main/java/io/gresse/hugo/anecdote/api/model/Content.java | // Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/model/Anecdote.java
// @Entity
// public class Anecdote implements Cloneable {
//
// @Id
// public long id;
// @Index
// @Nullable
// public String type;
// public String text;
// @Nullable
// @Index
// public String permalink;
// @Nullable
// public String media;
// @Index
// public String websitePageSlug;
// public long favoritesTimestamp; // Favorites date, if not favorite: 0L
//
// public Anecdote(String text, String permalink) {
// this(MediaType.TEXT, text, permalink, null);
// }
//
// public Anecdote(@Nullable String type, String text, @Nullable String permalink, @Nullable String media) {
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// }
//
// @Generated(1799107445)
// @Internal
// /** This constructor was generated by ObjectBox and may change any time. */
// public Anecdote(long id, String type, String text, String permalink, String media, String websitePageSlug,
// long favoritesTimestamp) {
// this.id = id;
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// this.websitePageSlug = websitePageSlug;
// this.favoritesTimestamp = favoritesTimestamp;
// }
//
// @Generated(443678178)
// public Anecdote() {
// }
//
// /**
// * Return the text without html
// *
// * @return plain text text
// */
// public String getPlainTextContent() {
// return Jsoup.parse(text.replace("<br>", "#lb#")).text().replace("#lb#", System.getProperty("line.separator"));
// }
//
// /**
// * Get the share string of the
// * @param context app context
// * @return the shareable string description of this anecdote
// */
// public String getShareString(Context context){
// String copyString = getPlainTextContent();
//
// if(!TextUtils.isEmpty(permalink)){
// copyString += " " + permalink;
// }
//
// copyString += " " + context.getString(R.string.app_share_credits);
//
// return copyString;
// }
//
// /**
// * Return if the anecdote has been favorited by the user, in the current session (meaning it is not stored).
// */
// public boolean isFavorite(){
// return favoritesTimestamp != 0L;
// }
//
// @Override
// public Anecdote clone() throws CloneNotSupportedException {
// Object o = null;
// try {
// o = super.clone();
// } catch(CloneNotSupportedException cnse) {
// cnse.printStackTrace(System.err);
// }
// return (Anecdote) o;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Anecdote anecdote = (Anecdote) o;
//
// if (type != null ? !type.equals(anecdote.type) : anecdote.type != null) return false;
// if (text != null ? !text.equals(anecdote.text) : anecdote.text != null) return false;
// //noinspection SimplifiableIfStatement
// if (permalink != null ? !permalink.equals(anecdote.permalink) : anecdote.permalink != null) return false;
// return media != null ? media.equals(anecdote.media) : anecdote.media == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = type != null ? type.hashCode() : 0;
// result = 31 * result + (text != null ? text.hashCode() : 0);
// result = 31 * result + (permalink != null ? permalink.hashCode() : 0);
// result = 31 * result + (media != null ? media.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Anecdote text='" + text + "'\', permalink='" + permalink + '\'';
// }
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/model/MediaType.java
// public class MediaType {
//
// public static final String URL = "url";
// public static final String TEXT = "text";
// public static final String IMAGE = "image";
// public static final String VIDEO = "video";
//
// }
| import android.support.annotation.Nullable;
import android.support.v4.util.Pair;
import android.text.TextUtils;
import org.jsoup.nodes.Element;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import io.gresse.hugo.anecdote.anecdote.model.Anecdote;
import io.gresse.hugo.anecdote.anecdote.model.MediaType; | package io.gresse.hugo.anecdote.api.model;
/**
* Represent the text parsing option for a {@link WebsitePage}
*
* Created by Hugo Gresse on 08/06/16.
*/
public class Content {
@Nullable
public Item url;
public List<ContentItem> items;
public Content() {
items = new ArrayList<>();
}
public Anecdote getAnecdote(Element element, Element tempElement){
String urlString = url != null ? url.getData(element, tempElement) : null;
String text = getText(element, tempElement);
Pair<String, String> media = getMedia(element, tempElement);
if(media == null){
return new Anecdote(text, urlString);
}
return new Anecdote(media.first, text, urlString, media.second);
}
protected String getText(Element element, Element tempElement){
String text = null;
for (ContentItem contentItem : items){ | // Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/model/Anecdote.java
// @Entity
// public class Anecdote implements Cloneable {
//
// @Id
// public long id;
// @Index
// @Nullable
// public String type;
// public String text;
// @Nullable
// @Index
// public String permalink;
// @Nullable
// public String media;
// @Index
// public String websitePageSlug;
// public long favoritesTimestamp; // Favorites date, if not favorite: 0L
//
// public Anecdote(String text, String permalink) {
// this(MediaType.TEXT, text, permalink, null);
// }
//
// public Anecdote(@Nullable String type, String text, @Nullable String permalink, @Nullable String media) {
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// }
//
// @Generated(1799107445)
// @Internal
// /** This constructor was generated by ObjectBox and may change any time. */
// public Anecdote(long id, String type, String text, String permalink, String media, String websitePageSlug,
// long favoritesTimestamp) {
// this.id = id;
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// this.websitePageSlug = websitePageSlug;
// this.favoritesTimestamp = favoritesTimestamp;
// }
//
// @Generated(443678178)
// public Anecdote() {
// }
//
// /**
// * Return the text without html
// *
// * @return plain text text
// */
// public String getPlainTextContent() {
// return Jsoup.parse(text.replace("<br>", "#lb#")).text().replace("#lb#", System.getProperty("line.separator"));
// }
//
// /**
// * Get the share string of the
// * @param context app context
// * @return the shareable string description of this anecdote
// */
// public String getShareString(Context context){
// String copyString = getPlainTextContent();
//
// if(!TextUtils.isEmpty(permalink)){
// copyString += " " + permalink;
// }
//
// copyString += " " + context.getString(R.string.app_share_credits);
//
// return copyString;
// }
//
// /**
// * Return if the anecdote has been favorited by the user, in the current session (meaning it is not stored).
// */
// public boolean isFavorite(){
// return favoritesTimestamp != 0L;
// }
//
// @Override
// public Anecdote clone() throws CloneNotSupportedException {
// Object o = null;
// try {
// o = super.clone();
// } catch(CloneNotSupportedException cnse) {
// cnse.printStackTrace(System.err);
// }
// return (Anecdote) o;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Anecdote anecdote = (Anecdote) o;
//
// if (type != null ? !type.equals(anecdote.type) : anecdote.type != null) return false;
// if (text != null ? !text.equals(anecdote.text) : anecdote.text != null) return false;
// //noinspection SimplifiableIfStatement
// if (permalink != null ? !permalink.equals(anecdote.permalink) : anecdote.permalink != null) return false;
// return media != null ? media.equals(anecdote.media) : anecdote.media == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = type != null ? type.hashCode() : 0;
// result = 31 * result + (text != null ? text.hashCode() : 0);
// result = 31 * result + (permalink != null ? permalink.hashCode() : 0);
// result = 31 * result + (media != null ? media.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Anecdote text='" + text + "'\', permalink='" + permalink + '\'';
// }
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/model/MediaType.java
// public class MediaType {
//
// public static final String URL = "url";
// public static final String TEXT = "text";
// public static final String IMAGE = "image";
// public static final String VIDEO = "video";
//
// }
// Path: app/src/main/java/io/gresse/hugo/anecdote/api/model/Content.java
import android.support.annotation.Nullable;
import android.support.v4.util.Pair;
import android.text.TextUtils;
import org.jsoup.nodes.Element;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import io.gresse.hugo.anecdote.anecdote.model.Anecdote;
import io.gresse.hugo.anecdote.anecdote.model.MediaType;
package io.gresse.hugo.anecdote.api.model;
/**
* Represent the text parsing option for a {@link WebsitePage}
*
* Created by Hugo Gresse on 08/06/16.
*/
public class Content {
@Nullable
public Item url;
public List<ContentItem> items;
public Content() {
items = new ArrayList<>();
}
public Anecdote getAnecdote(Element element, Element tempElement){
String urlString = url != null ? url.getData(element, tempElement) : null;
String text = getText(element, tempElement);
Pair<String, String> media = getMedia(element, tempElement);
if(media == null){
return new Anecdote(text, urlString);
}
return new Anecdote(media.first, text, urlString, media.second);
}
protected String getText(Element element, Element tempElement){
String text = null;
for (ContentItem contentItem : items){ | if(! contentItem.type.equals(MediaType.TEXT)){ |
HugoGresse/Anecdote | app/src/main/java/io/gresse/hugo/anecdote/anecdote/ToolbarSpinnerAdapter.java | // Path: app/src/main/java/io/gresse/hugo/anecdote/api/model/Website.java
// public class Website {
//
// public static final String SOURCE_LOCAL = "local";
// public static final String SOURCE_REMOTE = "remote";
// public static final String SOURCE_CALCULATED = "calc";
//
// public int version;
// public String slug;
// public String name;
// public int color;
// public int like;
// public String source;
// public String userAgent;
//
// public List<WebsitePage> pages;
//
// public Website() {
// this(null, SOURCE_LOCAL);
// }
//
// public Website(String name, String source) {
// this.pages = new ArrayList<>();
// this.source = source;
// this.name = name;
// }
//
// /**
// * Validate this object by preventing any crash when using it
// */
// public void validateData() {
// if (TextUtils.isEmpty(name)) {
// name = Long.toHexString(Double.doubleToLongBits(Math.random()));
// }
//
// for(WebsitePage websitePage : pages){
// websitePage.validate();
// }
//
// if (TextUtils.isEmpty(slug)) {
// if (source.equals(SOURCE_REMOTE)) {
// slug = "api-" + name;
// } else if (source.equals(SOURCE_CALCULATED)) {
// slug = "calc-" + name;
// } else {
// slug = "local-" + name;
// }
// }
// }
//
// /**
// * Check if the version missmatch between the two object
// *
// * @param website the new website
// * @return true if up to date, false otherweise
// */
// public boolean isUpToDate(Website website) {
// return website.version <= version;
// }
//
// /**
// * Check if the user can edit this website manually or not
// *
// * @return true if editable
// */
// public boolean isEditable() {
// return source.equals(SOURCE_LOCAL);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Website website = (Website) o;
//
// if (!slug.equals(website.slug)) return false;
// return source.equals(website.source);
//
// }
//
// @Override
// public int hashCode() {
// int result = slug.hashCode();
// result = 31 * result + source.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "Website{" +
// "version=" + version +
// ", slug='" + slug + '\'' +
// ", name='" + name + '\'' +
// ", color=" + color +
// ", like=" + like +
// ", source='" + source + '\'' +
// ", userAgent='" + userAgent + '\'' +
// ", pages=" + pages +
// '}';
// }
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/api/model/WebsitePage.java
// public class WebsitePage {
//
// public String name;
// public String slug;
// public String url;
// public String selector;
// public String urlSuffix;
// public boolean isFirstPageZero;
// public boolean isSinglePage;
// public Content content;
// /**
// * If a pagination is not null, so the first page to get if the root website (like http://9gag.com) and the
// * other page url are getted from the last page launch using this field.
// */
// @Nullable
// public Pagination pagination;
//
// /**
// * Get the page url from the given page number.
// *
// * @param pageNumber the page to get the url from
// * @param paginationMap the paginationMap is any, to try to get the url from
// * @return the url that represent the page
// */
// public String getPageUrl(int pageNumber, @Nullable Map<Integer, String> paginationMap) {
// if (pagination == null) {
// return url +
// ((isFirstPageZero) ? pageNumber : pageNumber + 1) +
// ((urlSuffix == null)? "" : urlSuffix);
// } else if (pageNumber != 0 && paginationMap != null && paginationMap.containsKey(pageNumber)) {
// return paginationMap.get(pageNumber);
// } else {
// return url;
// }
// }
//
// /**
// * Validate inner data to prevent usage when using it
// */
// public void validate() {
// if(TextUtils.isEmpty(slug)){
// slug = "local-" + name;
// }
// if(content == null){
// content = new Content();
// }
// }
// }
| import android.content.Context;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
import io.gresse.hugo.anecdote.R;
import io.gresse.hugo.anecdote.api.model.Website;
import io.gresse.hugo.anecdote.api.model.WebsitePage; | package io.gresse.hugo.anecdote.anecdote;
/**
* Adapter for the toolbar spinner
* <p/>
* Created by Hugo Gresse on 31/05/16.
*/
public class ToolbarSpinnerAdapter extends BaseAdapter {
private final Context mContext; | // Path: app/src/main/java/io/gresse/hugo/anecdote/api/model/Website.java
// public class Website {
//
// public static final String SOURCE_LOCAL = "local";
// public static final String SOURCE_REMOTE = "remote";
// public static final String SOURCE_CALCULATED = "calc";
//
// public int version;
// public String slug;
// public String name;
// public int color;
// public int like;
// public String source;
// public String userAgent;
//
// public List<WebsitePage> pages;
//
// public Website() {
// this(null, SOURCE_LOCAL);
// }
//
// public Website(String name, String source) {
// this.pages = new ArrayList<>();
// this.source = source;
// this.name = name;
// }
//
// /**
// * Validate this object by preventing any crash when using it
// */
// public void validateData() {
// if (TextUtils.isEmpty(name)) {
// name = Long.toHexString(Double.doubleToLongBits(Math.random()));
// }
//
// for(WebsitePage websitePage : pages){
// websitePage.validate();
// }
//
// if (TextUtils.isEmpty(slug)) {
// if (source.equals(SOURCE_REMOTE)) {
// slug = "api-" + name;
// } else if (source.equals(SOURCE_CALCULATED)) {
// slug = "calc-" + name;
// } else {
// slug = "local-" + name;
// }
// }
// }
//
// /**
// * Check if the version missmatch between the two object
// *
// * @param website the new website
// * @return true if up to date, false otherweise
// */
// public boolean isUpToDate(Website website) {
// return website.version <= version;
// }
//
// /**
// * Check if the user can edit this website manually or not
// *
// * @return true if editable
// */
// public boolean isEditable() {
// return source.equals(SOURCE_LOCAL);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Website website = (Website) o;
//
// if (!slug.equals(website.slug)) return false;
// return source.equals(website.source);
//
// }
//
// @Override
// public int hashCode() {
// int result = slug.hashCode();
// result = 31 * result + source.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "Website{" +
// "version=" + version +
// ", slug='" + slug + '\'' +
// ", name='" + name + '\'' +
// ", color=" + color +
// ", like=" + like +
// ", source='" + source + '\'' +
// ", userAgent='" + userAgent + '\'' +
// ", pages=" + pages +
// '}';
// }
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/api/model/WebsitePage.java
// public class WebsitePage {
//
// public String name;
// public String slug;
// public String url;
// public String selector;
// public String urlSuffix;
// public boolean isFirstPageZero;
// public boolean isSinglePage;
// public Content content;
// /**
// * If a pagination is not null, so the first page to get if the root website (like http://9gag.com) and the
// * other page url are getted from the last page launch using this field.
// */
// @Nullable
// public Pagination pagination;
//
// /**
// * Get the page url from the given page number.
// *
// * @param pageNumber the page to get the url from
// * @param paginationMap the paginationMap is any, to try to get the url from
// * @return the url that represent the page
// */
// public String getPageUrl(int pageNumber, @Nullable Map<Integer, String> paginationMap) {
// if (pagination == null) {
// return url +
// ((isFirstPageZero) ? pageNumber : pageNumber + 1) +
// ((urlSuffix == null)? "" : urlSuffix);
// } else if (pageNumber != 0 && paginationMap != null && paginationMap.containsKey(pageNumber)) {
// return paginationMap.get(pageNumber);
// } else {
// return url;
// }
// }
//
// /**
// * Validate inner data to prevent usage when using it
// */
// public void validate() {
// if(TextUtils.isEmpty(slug)){
// slug = "local-" + name;
// }
// if(content == null){
// content = new Content();
// }
// }
// }
// Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/ToolbarSpinnerAdapter.java
import android.content.Context;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
import io.gresse.hugo.anecdote.R;
import io.gresse.hugo.anecdote.api.model.Website;
import io.gresse.hugo.anecdote.api.model.WebsitePage;
package io.gresse.hugo.anecdote.anecdote;
/**
* Adapter for the toolbar spinner
* <p/>
* Created by Hugo Gresse on 31/05/16.
*/
public class ToolbarSpinnerAdapter extends BaseAdapter {
private final Context mContext; | private Website mWebsite; |
HugoGresse/Anecdote | app/src/main/java/io/gresse/hugo/anecdote/anecdote/ToolbarSpinnerAdapter.java | // Path: app/src/main/java/io/gresse/hugo/anecdote/api/model/Website.java
// public class Website {
//
// public static final String SOURCE_LOCAL = "local";
// public static final String SOURCE_REMOTE = "remote";
// public static final String SOURCE_CALCULATED = "calc";
//
// public int version;
// public String slug;
// public String name;
// public int color;
// public int like;
// public String source;
// public String userAgent;
//
// public List<WebsitePage> pages;
//
// public Website() {
// this(null, SOURCE_LOCAL);
// }
//
// public Website(String name, String source) {
// this.pages = new ArrayList<>();
// this.source = source;
// this.name = name;
// }
//
// /**
// * Validate this object by preventing any crash when using it
// */
// public void validateData() {
// if (TextUtils.isEmpty(name)) {
// name = Long.toHexString(Double.doubleToLongBits(Math.random()));
// }
//
// for(WebsitePage websitePage : pages){
// websitePage.validate();
// }
//
// if (TextUtils.isEmpty(slug)) {
// if (source.equals(SOURCE_REMOTE)) {
// slug = "api-" + name;
// } else if (source.equals(SOURCE_CALCULATED)) {
// slug = "calc-" + name;
// } else {
// slug = "local-" + name;
// }
// }
// }
//
// /**
// * Check if the version missmatch between the two object
// *
// * @param website the new website
// * @return true if up to date, false otherweise
// */
// public boolean isUpToDate(Website website) {
// return website.version <= version;
// }
//
// /**
// * Check if the user can edit this website manually or not
// *
// * @return true if editable
// */
// public boolean isEditable() {
// return source.equals(SOURCE_LOCAL);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Website website = (Website) o;
//
// if (!slug.equals(website.slug)) return false;
// return source.equals(website.source);
//
// }
//
// @Override
// public int hashCode() {
// int result = slug.hashCode();
// result = 31 * result + source.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "Website{" +
// "version=" + version +
// ", slug='" + slug + '\'' +
// ", name='" + name + '\'' +
// ", color=" + color +
// ", like=" + like +
// ", source='" + source + '\'' +
// ", userAgent='" + userAgent + '\'' +
// ", pages=" + pages +
// '}';
// }
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/api/model/WebsitePage.java
// public class WebsitePage {
//
// public String name;
// public String slug;
// public String url;
// public String selector;
// public String urlSuffix;
// public boolean isFirstPageZero;
// public boolean isSinglePage;
// public Content content;
// /**
// * If a pagination is not null, so the first page to get if the root website (like http://9gag.com) and the
// * other page url are getted from the last page launch using this field.
// */
// @Nullable
// public Pagination pagination;
//
// /**
// * Get the page url from the given page number.
// *
// * @param pageNumber the page to get the url from
// * @param paginationMap the paginationMap is any, to try to get the url from
// * @return the url that represent the page
// */
// public String getPageUrl(int pageNumber, @Nullable Map<Integer, String> paginationMap) {
// if (pagination == null) {
// return url +
// ((isFirstPageZero) ? pageNumber : pageNumber + 1) +
// ((urlSuffix == null)? "" : urlSuffix);
// } else if (pageNumber != 0 && paginationMap != null && paginationMap.containsKey(pageNumber)) {
// return paginationMap.get(pageNumber);
// } else {
// return url;
// }
// }
//
// /**
// * Validate inner data to prevent usage when using it
// */
// public void validate() {
// if(TextUtils.isEmpty(slug)){
// slug = "local-" + name;
// }
// if(content == null){
// content = new Content();
// }
// }
// }
| import android.content.Context;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
import io.gresse.hugo.anecdote.R;
import io.gresse.hugo.anecdote.api.model.Website;
import io.gresse.hugo.anecdote.api.model.WebsitePage; | @Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
String item = (String) getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.toolbar_spinner_dropdown_item, parent, false);
}
((TextView) convertView.findViewById(R.id.title)).setText(item);
return convertView;
}
/**
* Populate the spinner with the given website. It will browse it add add the websitep ages name.
*
* @param website the website to get pages from
* @param websitePageSlugSelected the slug of the selected item, if any
* @return the selected item index
*/
public int populate(Website website, @Nullable String websitePageSlugSelected) {
mItems.clear();
mWebsite = website;
mTitle = website.name;
int selected = 0;
int i = 0; | // Path: app/src/main/java/io/gresse/hugo/anecdote/api/model/Website.java
// public class Website {
//
// public static final String SOURCE_LOCAL = "local";
// public static final String SOURCE_REMOTE = "remote";
// public static final String SOURCE_CALCULATED = "calc";
//
// public int version;
// public String slug;
// public String name;
// public int color;
// public int like;
// public String source;
// public String userAgent;
//
// public List<WebsitePage> pages;
//
// public Website() {
// this(null, SOURCE_LOCAL);
// }
//
// public Website(String name, String source) {
// this.pages = new ArrayList<>();
// this.source = source;
// this.name = name;
// }
//
// /**
// * Validate this object by preventing any crash when using it
// */
// public void validateData() {
// if (TextUtils.isEmpty(name)) {
// name = Long.toHexString(Double.doubleToLongBits(Math.random()));
// }
//
// for(WebsitePage websitePage : pages){
// websitePage.validate();
// }
//
// if (TextUtils.isEmpty(slug)) {
// if (source.equals(SOURCE_REMOTE)) {
// slug = "api-" + name;
// } else if (source.equals(SOURCE_CALCULATED)) {
// slug = "calc-" + name;
// } else {
// slug = "local-" + name;
// }
// }
// }
//
// /**
// * Check if the version missmatch between the two object
// *
// * @param website the new website
// * @return true if up to date, false otherweise
// */
// public boolean isUpToDate(Website website) {
// return website.version <= version;
// }
//
// /**
// * Check if the user can edit this website manually or not
// *
// * @return true if editable
// */
// public boolean isEditable() {
// return source.equals(SOURCE_LOCAL);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Website website = (Website) o;
//
// if (!slug.equals(website.slug)) return false;
// return source.equals(website.source);
//
// }
//
// @Override
// public int hashCode() {
// int result = slug.hashCode();
// result = 31 * result + source.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "Website{" +
// "version=" + version +
// ", slug='" + slug + '\'' +
// ", name='" + name + '\'' +
// ", color=" + color +
// ", like=" + like +
// ", source='" + source + '\'' +
// ", userAgent='" + userAgent + '\'' +
// ", pages=" + pages +
// '}';
// }
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/api/model/WebsitePage.java
// public class WebsitePage {
//
// public String name;
// public String slug;
// public String url;
// public String selector;
// public String urlSuffix;
// public boolean isFirstPageZero;
// public boolean isSinglePage;
// public Content content;
// /**
// * If a pagination is not null, so the first page to get if the root website (like http://9gag.com) and the
// * other page url are getted from the last page launch using this field.
// */
// @Nullable
// public Pagination pagination;
//
// /**
// * Get the page url from the given page number.
// *
// * @param pageNumber the page to get the url from
// * @param paginationMap the paginationMap is any, to try to get the url from
// * @return the url that represent the page
// */
// public String getPageUrl(int pageNumber, @Nullable Map<Integer, String> paginationMap) {
// if (pagination == null) {
// return url +
// ((isFirstPageZero) ? pageNumber : pageNumber + 1) +
// ((urlSuffix == null)? "" : urlSuffix);
// } else if (pageNumber != 0 && paginationMap != null && paginationMap.containsKey(pageNumber)) {
// return paginationMap.get(pageNumber);
// } else {
// return url;
// }
// }
//
// /**
// * Validate inner data to prevent usage when using it
// */
// public void validate() {
// if(TextUtils.isEmpty(slug)){
// slug = "local-" + name;
// }
// if(content == null){
// content = new Content();
// }
// }
// }
// Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/ToolbarSpinnerAdapter.java
import android.content.Context;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
import io.gresse.hugo.anecdote.R;
import io.gresse.hugo.anecdote.api.model.Website;
import io.gresse.hugo.anecdote.api.model.WebsitePage;
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
String item = (String) getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.toolbar_spinner_dropdown_item, parent, false);
}
((TextView) convertView.findViewById(R.id.title)).setText(item);
return convertView;
}
/**
* Populate the spinner with the given website. It will browse it add add the websitep ages name.
*
* @param website the website to get pages from
* @param websitePageSlugSelected the slug of the selected item, if any
* @return the selected item index
*/
public int populate(Website website, @Nullable String websitePageSlugSelected) {
mItems.clear();
mWebsite = website;
mTitle = website.name;
int selected = 0;
int i = 0; | for (WebsitePage websitePage : website.pages) { |
HugoGresse/Anecdote | app/src/main/java/io/gresse/hugo/anecdote/api/chooser/WebsiteChooserAdapter.java | // Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/WebsiteViewHolderListener.java
// public interface WebsiteViewHolderListener {
// void onClick(Object object);
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/api/model/Website.java
// public class Website {
//
// public static final String SOURCE_LOCAL = "local";
// public static final String SOURCE_REMOTE = "remote";
// public static final String SOURCE_CALCULATED = "calc";
//
// public int version;
// public String slug;
// public String name;
// public int color;
// public int like;
// public String source;
// public String userAgent;
//
// public List<WebsitePage> pages;
//
// public Website() {
// this(null, SOURCE_LOCAL);
// }
//
// public Website(String name, String source) {
// this.pages = new ArrayList<>();
// this.source = source;
// this.name = name;
// }
//
// /**
// * Validate this object by preventing any crash when using it
// */
// public void validateData() {
// if (TextUtils.isEmpty(name)) {
// name = Long.toHexString(Double.doubleToLongBits(Math.random()));
// }
//
// for(WebsitePage websitePage : pages){
// websitePage.validate();
// }
//
// if (TextUtils.isEmpty(slug)) {
// if (source.equals(SOURCE_REMOTE)) {
// slug = "api-" + name;
// } else if (source.equals(SOURCE_CALCULATED)) {
// slug = "calc-" + name;
// } else {
// slug = "local-" + name;
// }
// }
// }
//
// /**
// * Check if the version missmatch between the two object
// *
// * @param website the new website
// * @return true if up to date, false otherweise
// */
// public boolean isUpToDate(Website website) {
// return website.version <= version;
// }
//
// /**
// * Check if the user can edit this website manually or not
// *
// * @return true if editable
// */
// public boolean isEditable() {
// return source.equals(SOURCE_LOCAL);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Website website = (Website) o;
//
// if (!slug.equals(website.slug)) return false;
// return source.equals(website.source);
//
// }
//
// @Override
// public int hashCode() {
// int result = slug.hashCode();
// result = 31 * result + source.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "Website{" +
// "version=" + version +
// ", slug='" + slug + '\'' +
// ", name='" + name + '\'' +
// ", color=" + color +
// ", like=" + like +
// ", source='" + source + '\'' +
// ", userAgent='" + userAgent + '\'' +
// ", pages=" + pages +
// '}';
// }
// }
| import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.gresse.hugo.anecdote.R;
import io.gresse.hugo.anecdote.anecdote.WebsiteViewHolderListener;
import io.gresse.hugo.anecdote.api.model.Website; | package io.gresse.hugo.anecdote.api.chooser;
/**
* Display a list of website
* <p/>
* Created by Hugo Gresse on 03/03/16.
*/
public class WebsiteChooserAdapter extends RecyclerView.Adapter<WebsiteChooserAdapter.BaseWebsiteViewHolder> {
@SuppressWarnings("unused")
public static final String TAG = WebsiteChooserAdapter.class.getSimpleName();
public static final int VIEW_TYPE_WEBSITE = 0;
public static final int VIEW_TYPE_CUSTOM = 1;
public static final int VIEW_TYPE_LOAD = 2;
/**
* Null list = no data, empty list = data loaded but nothing to display
*/
@Nullable | // Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/WebsiteViewHolderListener.java
// public interface WebsiteViewHolderListener {
// void onClick(Object object);
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/api/model/Website.java
// public class Website {
//
// public static final String SOURCE_LOCAL = "local";
// public static final String SOURCE_REMOTE = "remote";
// public static final String SOURCE_CALCULATED = "calc";
//
// public int version;
// public String slug;
// public String name;
// public int color;
// public int like;
// public String source;
// public String userAgent;
//
// public List<WebsitePage> pages;
//
// public Website() {
// this(null, SOURCE_LOCAL);
// }
//
// public Website(String name, String source) {
// this.pages = new ArrayList<>();
// this.source = source;
// this.name = name;
// }
//
// /**
// * Validate this object by preventing any crash when using it
// */
// public void validateData() {
// if (TextUtils.isEmpty(name)) {
// name = Long.toHexString(Double.doubleToLongBits(Math.random()));
// }
//
// for(WebsitePage websitePage : pages){
// websitePage.validate();
// }
//
// if (TextUtils.isEmpty(slug)) {
// if (source.equals(SOURCE_REMOTE)) {
// slug = "api-" + name;
// } else if (source.equals(SOURCE_CALCULATED)) {
// slug = "calc-" + name;
// } else {
// slug = "local-" + name;
// }
// }
// }
//
// /**
// * Check if the version missmatch between the two object
// *
// * @param website the new website
// * @return true if up to date, false otherweise
// */
// public boolean isUpToDate(Website website) {
// return website.version <= version;
// }
//
// /**
// * Check if the user can edit this website manually or not
// *
// * @return true if editable
// */
// public boolean isEditable() {
// return source.equals(SOURCE_LOCAL);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Website website = (Website) o;
//
// if (!slug.equals(website.slug)) return false;
// return source.equals(website.source);
//
// }
//
// @Override
// public int hashCode() {
// int result = slug.hashCode();
// result = 31 * result + source.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "Website{" +
// "version=" + version +
// ", slug='" + slug + '\'' +
// ", name='" + name + '\'' +
// ", color=" + color +
// ", like=" + like +
// ", source='" + source + '\'' +
// ", userAgent='" + userAgent + '\'' +
// ", pages=" + pages +
// '}';
// }
// }
// Path: app/src/main/java/io/gresse/hugo/anecdote/api/chooser/WebsiteChooserAdapter.java
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.gresse.hugo.anecdote.R;
import io.gresse.hugo.anecdote.anecdote.WebsiteViewHolderListener;
import io.gresse.hugo.anecdote.api.model.Website;
package io.gresse.hugo.anecdote.api.chooser;
/**
* Display a list of website
* <p/>
* Created by Hugo Gresse on 03/03/16.
*/
public class WebsiteChooserAdapter extends RecyclerView.Adapter<WebsiteChooserAdapter.BaseWebsiteViewHolder> {
@SuppressWarnings("unused")
public static final String TAG = WebsiteChooserAdapter.class.getSimpleName();
public static final int VIEW_TYPE_WEBSITE = 0;
public static final int VIEW_TYPE_CUSTOM = 1;
public static final int VIEW_TYPE_LOAD = 2;
/**
* Null list = no data, empty list = data loaded but nothing to display
*/
@Nullable | private List<Website> mWebsites; |
HugoGresse/Anecdote | app/src/main/java/io/gresse/hugo/anecdote/api/chooser/WebsiteChooserAdapter.java | // Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/WebsiteViewHolderListener.java
// public interface WebsiteViewHolderListener {
// void onClick(Object object);
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/api/model/Website.java
// public class Website {
//
// public static final String SOURCE_LOCAL = "local";
// public static final String SOURCE_REMOTE = "remote";
// public static final String SOURCE_CALCULATED = "calc";
//
// public int version;
// public String slug;
// public String name;
// public int color;
// public int like;
// public String source;
// public String userAgent;
//
// public List<WebsitePage> pages;
//
// public Website() {
// this(null, SOURCE_LOCAL);
// }
//
// public Website(String name, String source) {
// this.pages = new ArrayList<>();
// this.source = source;
// this.name = name;
// }
//
// /**
// * Validate this object by preventing any crash when using it
// */
// public void validateData() {
// if (TextUtils.isEmpty(name)) {
// name = Long.toHexString(Double.doubleToLongBits(Math.random()));
// }
//
// for(WebsitePage websitePage : pages){
// websitePage.validate();
// }
//
// if (TextUtils.isEmpty(slug)) {
// if (source.equals(SOURCE_REMOTE)) {
// slug = "api-" + name;
// } else if (source.equals(SOURCE_CALCULATED)) {
// slug = "calc-" + name;
// } else {
// slug = "local-" + name;
// }
// }
// }
//
// /**
// * Check if the version missmatch between the two object
// *
// * @param website the new website
// * @return true if up to date, false otherweise
// */
// public boolean isUpToDate(Website website) {
// return website.version <= version;
// }
//
// /**
// * Check if the user can edit this website manually or not
// *
// * @return true if editable
// */
// public boolean isEditable() {
// return source.equals(SOURCE_LOCAL);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Website website = (Website) o;
//
// if (!slug.equals(website.slug)) return false;
// return source.equals(website.source);
//
// }
//
// @Override
// public int hashCode() {
// int result = slug.hashCode();
// result = 31 * result + source.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "Website{" +
// "version=" + version +
// ", slug='" + slug + '\'' +
// ", name='" + name + '\'' +
// ", color=" + color +
// ", like=" + like +
// ", source='" + source + '\'' +
// ", userAgent='" + userAgent + '\'' +
// ", pages=" + pages +
// '}';
// }
// }
| import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.gresse.hugo.anecdote.R;
import io.gresse.hugo.anecdote.anecdote.WebsiteViewHolderListener;
import io.gresse.hugo.anecdote.api.model.Website; | package io.gresse.hugo.anecdote.api.chooser;
/**
* Display a list of website
* <p/>
* Created by Hugo Gresse on 03/03/16.
*/
public class WebsiteChooserAdapter extends RecyclerView.Adapter<WebsiteChooserAdapter.BaseWebsiteViewHolder> {
@SuppressWarnings("unused")
public static final String TAG = WebsiteChooserAdapter.class.getSimpleName();
public static final int VIEW_TYPE_WEBSITE = 0;
public static final int VIEW_TYPE_CUSTOM = 1;
public static final int VIEW_TYPE_LOAD = 2;
/**
* Null list = no data, empty list = data loaded but nothing to display
*/
@Nullable
private List<Website> mWebsites;
@Nullable | // Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/WebsiteViewHolderListener.java
// public interface WebsiteViewHolderListener {
// void onClick(Object object);
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/api/model/Website.java
// public class Website {
//
// public static final String SOURCE_LOCAL = "local";
// public static final String SOURCE_REMOTE = "remote";
// public static final String SOURCE_CALCULATED = "calc";
//
// public int version;
// public String slug;
// public String name;
// public int color;
// public int like;
// public String source;
// public String userAgent;
//
// public List<WebsitePage> pages;
//
// public Website() {
// this(null, SOURCE_LOCAL);
// }
//
// public Website(String name, String source) {
// this.pages = new ArrayList<>();
// this.source = source;
// this.name = name;
// }
//
// /**
// * Validate this object by preventing any crash when using it
// */
// public void validateData() {
// if (TextUtils.isEmpty(name)) {
// name = Long.toHexString(Double.doubleToLongBits(Math.random()));
// }
//
// for(WebsitePage websitePage : pages){
// websitePage.validate();
// }
//
// if (TextUtils.isEmpty(slug)) {
// if (source.equals(SOURCE_REMOTE)) {
// slug = "api-" + name;
// } else if (source.equals(SOURCE_CALCULATED)) {
// slug = "calc-" + name;
// } else {
// slug = "local-" + name;
// }
// }
// }
//
// /**
// * Check if the version missmatch between the two object
// *
// * @param website the new website
// * @return true if up to date, false otherweise
// */
// public boolean isUpToDate(Website website) {
// return website.version <= version;
// }
//
// /**
// * Check if the user can edit this website manually or not
// *
// * @return true if editable
// */
// public boolean isEditable() {
// return source.equals(SOURCE_LOCAL);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Website website = (Website) o;
//
// if (!slug.equals(website.slug)) return false;
// return source.equals(website.source);
//
// }
//
// @Override
// public int hashCode() {
// int result = slug.hashCode();
// result = 31 * result + source.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "Website{" +
// "version=" + version +
// ", slug='" + slug + '\'' +
// ", name='" + name + '\'' +
// ", color=" + color +
// ", like=" + like +
// ", source='" + source + '\'' +
// ", userAgent='" + userAgent + '\'' +
// ", pages=" + pages +
// '}';
// }
// }
// Path: app/src/main/java/io/gresse/hugo/anecdote/api/chooser/WebsiteChooserAdapter.java
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.gresse.hugo.anecdote.R;
import io.gresse.hugo.anecdote.anecdote.WebsiteViewHolderListener;
import io.gresse.hugo.anecdote.api.model.Website;
package io.gresse.hugo.anecdote.api.chooser;
/**
* Display a list of website
* <p/>
* Created by Hugo Gresse on 03/03/16.
*/
public class WebsiteChooserAdapter extends RecyclerView.Adapter<WebsiteChooserAdapter.BaseWebsiteViewHolder> {
@SuppressWarnings("unused")
public static final String TAG = WebsiteChooserAdapter.class.getSimpleName();
public static final int VIEW_TYPE_WEBSITE = 0;
public static final int VIEW_TYPE_CUSTOM = 1;
public static final int VIEW_TYPE_LOAD = 2;
/**
* Null list = no data, empty list = data loaded but nothing to display
*/
@Nullable
private List<Website> mWebsites;
@Nullable | private WebsiteViewHolderListener mViewHolderListener; |
HugoGresse/Anecdote | app/src/main/java/io/gresse/hugo/anecdote/util/Utils.java | // Path: app/src/main/java/io/gresse/hugo/anecdote/api/model/Website.java
// public class Website {
//
// public static final String SOURCE_LOCAL = "local";
// public static final String SOURCE_REMOTE = "remote";
// public static final String SOURCE_CALCULATED = "calc";
//
// public int version;
// public String slug;
// public String name;
// public int color;
// public int like;
// public String source;
// public String userAgent;
//
// public List<WebsitePage> pages;
//
// public Website() {
// this(null, SOURCE_LOCAL);
// }
//
// public Website(String name, String source) {
// this.pages = new ArrayList<>();
// this.source = source;
// this.name = name;
// }
//
// /**
// * Validate this object by preventing any crash when using it
// */
// public void validateData() {
// if (TextUtils.isEmpty(name)) {
// name = Long.toHexString(Double.doubleToLongBits(Math.random()));
// }
//
// for(WebsitePage websitePage : pages){
// websitePage.validate();
// }
//
// if (TextUtils.isEmpty(slug)) {
// if (source.equals(SOURCE_REMOTE)) {
// slug = "api-" + name;
// } else if (source.equals(SOURCE_CALCULATED)) {
// slug = "calc-" + name;
// } else {
// slug = "local-" + name;
// }
// }
// }
//
// /**
// * Check if the version missmatch between the two object
// *
// * @param website the new website
// * @return true if up to date, false otherweise
// */
// public boolean isUpToDate(Website website) {
// return website.version <= version;
// }
//
// /**
// * Check if the user can edit this website manually or not
// *
// * @return true if editable
// */
// public boolean isEditable() {
// return source.equals(SOURCE_LOCAL);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Website website = (Website) o;
//
// if (!slug.equals(website.slug)) return false;
// return source.equals(website.source);
//
// }
//
// @Override
// public int hashCode() {
// int result = slug.hashCode();
// result = 31 * result + source.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "Website{" +
// "version=" + version +
// ", slug='" + slug + '\'' +
// ", name='" + name + '\'' +
// ", color=" + color +
// ", like=" + like +
// ", source='" + source + '\'' +
// ", userAgent='" + userAgent + '\'' +
// ", pages=" + pages +
// '}';
// }
// }
| import android.app.Application;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.text.TextUtils;
import io.gresse.hugo.anecdote.api.model.Website; | package io.gresse.hugo.anecdote.util;
/**
* Generals utils
* <p/>
* Created by Hugo Gresse on 13/02/16.
*/
public class Utils {
/**
* Return the user agent sent on all request. It's not default Android user agent as we don't really want that
* websites see the app trafic (for now at least).
* <p/>
* Be only replace the device by the correct one.
*
* @return the user agent
*/
public static String getUserAgent() {
return "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1 " + Build.MODEL +
") AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.95 Mobile Safari/537.36";
}
/**
* Return the user agent sent on all request. It will choose between our local custom user agent or given
* useragent for this website.
*
* @return the user agent
*/ | // Path: app/src/main/java/io/gresse/hugo/anecdote/api/model/Website.java
// public class Website {
//
// public static final String SOURCE_LOCAL = "local";
// public static final String SOURCE_REMOTE = "remote";
// public static final String SOURCE_CALCULATED = "calc";
//
// public int version;
// public String slug;
// public String name;
// public int color;
// public int like;
// public String source;
// public String userAgent;
//
// public List<WebsitePage> pages;
//
// public Website() {
// this(null, SOURCE_LOCAL);
// }
//
// public Website(String name, String source) {
// this.pages = new ArrayList<>();
// this.source = source;
// this.name = name;
// }
//
// /**
// * Validate this object by preventing any crash when using it
// */
// public void validateData() {
// if (TextUtils.isEmpty(name)) {
// name = Long.toHexString(Double.doubleToLongBits(Math.random()));
// }
//
// for(WebsitePage websitePage : pages){
// websitePage.validate();
// }
//
// if (TextUtils.isEmpty(slug)) {
// if (source.equals(SOURCE_REMOTE)) {
// slug = "api-" + name;
// } else if (source.equals(SOURCE_CALCULATED)) {
// slug = "calc-" + name;
// } else {
// slug = "local-" + name;
// }
// }
// }
//
// /**
// * Check if the version missmatch between the two object
// *
// * @param website the new website
// * @return true if up to date, false otherweise
// */
// public boolean isUpToDate(Website website) {
// return website.version <= version;
// }
//
// /**
// * Check if the user can edit this website manually or not
// *
// * @return true if editable
// */
// public boolean isEditable() {
// return source.equals(SOURCE_LOCAL);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Website website = (Website) o;
//
// if (!slug.equals(website.slug)) return false;
// return source.equals(website.source);
//
// }
//
// @Override
// public int hashCode() {
// int result = slug.hashCode();
// result = 31 * result + source.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "Website{" +
// "version=" + version +
// ", slug='" + slug + '\'' +
// ", name='" + name + '\'' +
// ", color=" + color +
// ", like=" + like +
// ", source='" + source + '\'' +
// ", userAgent='" + userAgent + '\'' +
// ", pages=" + pages +
// '}';
// }
// }
// Path: app/src/main/java/io/gresse/hugo/anecdote/util/Utils.java
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.text.TextUtils;
import io.gresse.hugo.anecdote.api.model.Website;
package io.gresse.hugo.anecdote.util;
/**
* Generals utils
* <p/>
* Created by Hugo Gresse on 13/02/16.
*/
public class Utils {
/**
* Return the user agent sent on all request. It's not default Android user agent as we don't really want that
* websites see the app trafic (for now at least).
* <p/>
* Be only replace the device by the correct one.
*
* @return the user agent
*/
public static String getUserAgent() {
return "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1 " + Build.MODEL +
") AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.95 Mobile Safari/537.36";
}
/**
* Return the user agent sent on all request. It will choose between our local custom user agent or given
* useragent for this website.
*
* @return the user agent
*/ | public static String getUserAgent(Website website) { |
HugoGresse/Anecdote | app/src/main/java/io/gresse/hugo/anecdote/tracking/EventTracker.java | // Path: app/src/main/java/io/gresse/hugo/anecdote/Configuration.java
// public class Configuration {
//
// public static final boolean DEBUG = BuildConfig.DEBUG;
// public static final String API_VERSION = "2";
// public static final String API_URL = "https://anecdote-api.firebaseio.com/v" + API_VERSION + "/websites.json";
// public static final String DOWNLOAD_FOLDER = "Anecdote";
// public static final int IMAGE_SAVE_TOAST_DURATION = 5000;
// public static final String DONATION_LINK = "https://paypal.me/HugoGresse/5";
//
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/social/CopyAnecdoteEvent.java
// public class CopyAnecdoteEvent extends SocialEvent {
//
// public static final String TYPE_ANECDOTE = "Anecdote";
// public static final String TYPE_MEDIA = "Media";
//
// public final String type;
// public final String shareString;
//
// public CopyAnecdoteEvent(String websiteName, Anecdote anecdote, String type, String shareString) {
// super(websiteName, anecdote);
// this.type = type;
// this.shareString = shareString;
// }
// }
| import android.app.Activity;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import io.gresse.hugo.anecdote.Configuration;
import io.gresse.hugo.anecdote.anecdote.social.CopyAnecdoteEvent; | package io.gresse.hugo.anecdote.tracking;
/**
* Main entry point for tracking application activity. Sub flavors are responsable to implement
* {@link EventSenderInterface} with a class named "EventSender" and send the proper information to each services they
* manage.
* <p/>
* Created by Hugo Gresse on 25/04/16.
*/
public class EventTracker {
public static final String CONTENT_TYPE_ANECDOTE = "Anecdote";
public static final String CONTENT_TYPE_APP = "App";
public static final String TRACKING_WEBSITE_NAME = "Website name";
private static EventSenderInterface sEvent;
public EventTracker(Context context) {
if (!isEventEnable()) return;
sEvent = new EventSender(context);
}
/**
* Return true if event reporting is enable, checking the BuildConfig
*
* @return true if enable, false otherweise
*/
public static boolean isEventEnable() { | // Path: app/src/main/java/io/gresse/hugo/anecdote/Configuration.java
// public class Configuration {
//
// public static final boolean DEBUG = BuildConfig.DEBUG;
// public static final String API_VERSION = "2";
// public static final String API_URL = "https://anecdote-api.firebaseio.com/v" + API_VERSION + "/websites.json";
// public static final String DOWNLOAD_FOLDER = "Anecdote";
// public static final int IMAGE_SAVE_TOAST_DURATION = 5000;
// public static final String DONATION_LINK = "https://paypal.me/HugoGresse/5";
//
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/social/CopyAnecdoteEvent.java
// public class CopyAnecdoteEvent extends SocialEvent {
//
// public static final String TYPE_ANECDOTE = "Anecdote";
// public static final String TYPE_MEDIA = "Media";
//
// public final String type;
// public final String shareString;
//
// public CopyAnecdoteEvent(String websiteName, Anecdote anecdote, String type, String shareString) {
// super(websiteName, anecdote);
// this.type = type;
// this.shareString = shareString;
// }
// }
// Path: app/src/main/java/io/gresse/hugo/anecdote/tracking/EventTracker.java
import android.app.Activity;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import io.gresse.hugo.anecdote.Configuration;
import io.gresse.hugo.anecdote.anecdote.social.CopyAnecdoteEvent;
package io.gresse.hugo.anecdote.tracking;
/**
* Main entry point for tracking application activity. Sub flavors are responsable to implement
* {@link EventSenderInterface} with a class named "EventSender" and send the proper information to each services they
* manage.
* <p/>
* Created by Hugo Gresse on 25/04/16.
*/
public class EventTracker {
public static final String CONTENT_TYPE_ANECDOTE = "Anecdote";
public static final String CONTENT_TYPE_APP = "App";
public static final String TRACKING_WEBSITE_NAME = "Website name";
private static EventSenderInterface sEvent;
public EventTracker(Context context) {
if (!isEventEnable()) return;
sEvent = new EventSender(context);
}
/**
* Return true if event reporting is enable, checking the BuildConfig
*
* @return true if enable, false otherweise
*/
public static boolean isEventEnable() { | return !Configuration.DEBUG; |
HugoGresse/Anecdote | app/src/main/java/io/gresse/hugo/anecdote/tracking/EventTracker.java | // Path: app/src/main/java/io/gresse/hugo/anecdote/Configuration.java
// public class Configuration {
//
// public static final boolean DEBUG = BuildConfig.DEBUG;
// public static final String API_VERSION = "2";
// public static final String API_URL = "https://anecdote-api.firebaseio.com/v" + API_VERSION + "/websites.json";
// public static final String DOWNLOAD_FOLDER = "Anecdote";
// public static final int IMAGE_SAVE_TOAST_DURATION = 5000;
// public static final String DONATION_LINK = "https://paypal.me/HugoGresse/5";
//
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/social/CopyAnecdoteEvent.java
// public class CopyAnecdoteEvent extends SocialEvent {
//
// public static final String TYPE_ANECDOTE = "Anecdote";
// public static final String TYPE_MEDIA = "Media";
//
// public final String type;
// public final String shareString;
//
// public CopyAnecdoteEvent(String websiteName, Anecdote anecdote, String type, String shareString) {
// super(websiteName, anecdote);
// this.type = type;
// this.shareString = shareString;
// }
// }
| import android.app.Activity;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import io.gresse.hugo.anecdote.Configuration;
import io.gresse.hugo.anecdote.anecdote.social.CopyAnecdoteEvent; | */
public static void trackWebsiteDefault(String websiteName) {
if (!isEventEnable()) return;
sEvent.sendEvent("Website delete", "Website set default", websiteName);
}
/**
* Track when all websites are restored for new ones
*/
public static void trackWebsitesRestored() {
if (!isEventEnable()) return;
sEvent.sendEvent("Website restored");
}
/**
* Track when a custom website is added
*/
public static void trackCustomWebsiteAdded() {
if (!isEventEnable()) return;
sEvent.sendEvent("Websites custom added");
}
/**
* Track the copy action on an anecdote
*
* @param event the copy event
*/ | // Path: app/src/main/java/io/gresse/hugo/anecdote/Configuration.java
// public class Configuration {
//
// public static final boolean DEBUG = BuildConfig.DEBUG;
// public static final String API_VERSION = "2";
// public static final String API_URL = "https://anecdote-api.firebaseio.com/v" + API_VERSION + "/websites.json";
// public static final String DOWNLOAD_FOLDER = "Anecdote";
// public static final int IMAGE_SAVE_TOAST_DURATION = 5000;
// public static final String DONATION_LINK = "https://paypal.me/HugoGresse/5";
//
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/social/CopyAnecdoteEvent.java
// public class CopyAnecdoteEvent extends SocialEvent {
//
// public static final String TYPE_ANECDOTE = "Anecdote";
// public static final String TYPE_MEDIA = "Media";
//
// public final String type;
// public final String shareString;
//
// public CopyAnecdoteEvent(String websiteName, Anecdote anecdote, String type, String shareString) {
// super(websiteName, anecdote);
// this.type = type;
// this.shareString = shareString;
// }
// }
// Path: app/src/main/java/io/gresse/hugo/anecdote/tracking/EventTracker.java
import android.app.Activity;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import io.gresse.hugo.anecdote.Configuration;
import io.gresse.hugo.anecdote.anecdote.social.CopyAnecdoteEvent;
*/
public static void trackWebsiteDefault(String websiteName) {
if (!isEventEnable()) return;
sEvent.sendEvent("Website delete", "Website set default", websiteName);
}
/**
* Track when all websites are restored for new ones
*/
public static void trackWebsitesRestored() {
if (!isEventEnable()) return;
sEvent.sendEvent("Website restored");
}
/**
* Track when a custom website is added
*/
public static void trackCustomWebsiteAdded() {
if (!isEventEnable()) return;
sEvent.sendEvent("Websites custom added");
}
/**
* Track the copy action on an anecdote
*
* @param event the copy event
*/ | public static void trackAnecdoteCopy(CopyAnecdoteEvent event) { |
HugoGresse/Anecdote | app/src/main/java/io/gresse/hugo/anecdote/anecdote/social/ShareAnecdoteEvent.java | // Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/model/Anecdote.java
// @Entity
// public class Anecdote implements Cloneable {
//
// @Id
// public long id;
// @Index
// @Nullable
// public String type;
// public String text;
// @Nullable
// @Index
// public String permalink;
// @Nullable
// public String media;
// @Index
// public String websitePageSlug;
// public long favoritesTimestamp; // Favorites date, if not favorite: 0L
//
// public Anecdote(String text, String permalink) {
// this(MediaType.TEXT, text, permalink, null);
// }
//
// public Anecdote(@Nullable String type, String text, @Nullable String permalink, @Nullable String media) {
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// }
//
// @Generated(1799107445)
// @Internal
// /** This constructor was generated by ObjectBox and may change any time. */
// public Anecdote(long id, String type, String text, String permalink, String media, String websitePageSlug,
// long favoritesTimestamp) {
// this.id = id;
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// this.websitePageSlug = websitePageSlug;
// this.favoritesTimestamp = favoritesTimestamp;
// }
//
// @Generated(443678178)
// public Anecdote() {
// }
//
// /**
// * Return the text without html
// *
// * @return plain text text
// */
// public String getPlainTextContent() {
// return Jsoup.parse(text.replace("<br>", "#lb#")).text().replace("#lb#", System.getProperty("line.separator"));
// }
//
// /**
// * Get the share string of the
// * @param context app context
// * @return the shareable string description of this anecdote
// */
// public String getShareString(Context context){
// String copyString = getPlainTextContent();
//
// if(!TextUtils.isEmpty(permalink)){
// copyString += " " + permalink;
// }
//
// copyString += " " + context.getString(R.string.app_share_credits);
//
// return copyString;
// }
//
// /**
// * Return if the anecdote has been favorited by the user, in the current session (meaning it is not stored).
// */
// public boolean isFavorite(){
// return favoritesTimestamp != 0L;
// }
//
// @Override
// public Anecdote clone() throws CloneNotSupportedException {
// Object o = null;
// try {
// o = super.clone();
// } catch(CloneNotSupportedException cnse) {
// cnse.printStackTrace(System.err);
// }
// return (Anecdote) o;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Anecdote anecdote = (Anecdote) o;
//
// if (type != null ? !type.equals(anecdote.type) : anecdote.type != null) return false;
// if (text != null ? !text.equals(anecdote.text) : anecdote.text != null) return false;
// //noinspection SimplifiableIfStatement
// if (permalink != null ? !permalink.equals(anecdote.permalink) : anecdote.permalink != null) return false;
// return media != null ? media.equals(anecdote.media) : anecdote.media == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = type != null ? type.hashCode() : 0;
// result = 31 * result + (text != null ? text.hashCode() : 0);
// result = 31 * result + (permalink != null ? permalink.hashCode() : 0);
// result = 31 * result + (media != null ? media.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Anecdote text='" + text + "'\', permalink='" + permalink + '\'';
// }
// }
| import io.gresse.hugo.anecdote.anecdote.model.Anecdote; | package io.gresse.hugo.anecdote.anecdote.social;
/**
* Launched to share an anecdote
*
* Created by Hugo Gresse on 20/07/16.
*/
public class ShareAnecdoteEvent extends SocialEvent {
public String shareString;
| // Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/model/Anecdote.java
// @Entity
// public class Anecdote implements Cloneable {
//
// @Id
// public long id;
// @Index
// @Nullable
// public String type;
// public String text;
// @Nullable
// @Index
// public String permalink;
// @Nullable
// public String media;
// @Index
// public String websitePageSlug;
// public long favoritesTimestamp; // Favorites date, if not favorite: 0L
//
// public Anecdote(String text, String permalink) {
// this(MediaType.TEXT, text, permalink, null);
// }
//
// public Anecdote(@Nullable String type, String text, @Nullable String permalink, @Nullable String media) {
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// }
//
// @Generated(1799107445)
// @Internal
// /** This constructor was generated by ObjectBox and may change any time. */
// public Anecdote(long id, String type, String text, String permalink, String media, String websitePageSlug,
// long favoritesTimestamp) {
// this.id = id;
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// this.websitePageSlug = websitePageSlug;
// this.favoritesTimestamp = favoritesTimestamp;
// }
//
// @Generated(443678178)
// public Anecdote() {
// }
//
// /**
// * Return the text without html
// *
// * @return plain text text
// */
// public String getPlainTextContent() {
// return Jsoup.parse(text.replace("<br>", "#lb#")).text().replace("#lb#", System.getProperty("line.separator"));
// }
//
// /**
// * Get the share string of the
// * @param context app context
// * @return the shareable string description of this anecdote
// */
// public String getShareString(Context context){
// String copyString = getPlainTextContent();
//
// if(!TextUtils.isEmpty(permalink)){
// copyString += " " + permalink;
// }
//
// copyString += " " + context.getString(R.string.app_share_credits);
//
// return copyString;
// }
//
// /**
// * Return if the anecdote has been favorited by the user, in the current session (meaning it is not stored).
// */
// public boolean isFavorite(){
// return favoritesTimestamp != 0L;
// }
//
// @Override
// public Anecdote clone() throws CloneNotSupportedException {
// Object o = null;
// try {
// o = super.clone();
// } catch(CloneNotSupportedException cnse) {
// cnse.printStackTrace(System.err);
// }
// return (Anecdote) o;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Anecdote anecdote = (Anecdote) o;
//
// if (type != null ? !type.equals(anecdote.type) : anecdote.type != null) return false;
// if (text != null ? !text.equals(anecdote.text) : anecdote.text != null) return false;
// //noinspection SimplifiableIfStatement
// if (permalink != null ? !permalink.equals(anecdote.permalink) : anecdote.permalink != null) return false;
// return media != null ? media.equals(anecdote.media) : anecdote.media == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = type != null ? type.hashCode() : 0;
// result = 31 * result + (text != null ? text.hashCode() : 0);
// result = 31 * result + (permalink != null ? permalink.hashCode() : 0);
// result = 31 * result + (media != null ? media.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Anecdote text='" + text + "'\', permalink='" + permalink + '\'';
// }
// }
// Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/social/ShareAnecdoteEvent.java
import io.gresse.hugo.anecdote.anecdote.model.Anecdote;
package io.gresse.hugo.anecdote.anecdote.social;
/**
* Launched to share an anecdote
*
* Created by Hugo Gresse on 20/07/16.
*/
public class ShareAnecdoteEvent extends SocialEvent {
public String shareString;
| public ShareAnecdoteEvent(String websiteName, Anecdote anecdote, String shareString) { |
HugoGresse/Anecdote | app/src/main/java/io/gresse/hugo/anecdote/anecdote/list/AdapterListener.java | // Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/model/Anecdote.java
// @Entity
// public class Anecdote implements Cloneable {
//
// @Id
// public long id;
// @Index
// @Nullable
// public String type;
// public String text;
// @Nullable
// @Index
// public String permalink;
// @Nullable
// public String media;
// @Index
// public String websitePageSlug;
// public long favoritesTimestamp; // Favorites date, if not favorite: 0L
//
// public Anecdote(String text, String permalink) {
// this(MediaType.TEXT, text, permalink, null);
// }
//
// public Anecdote(@Nullable String type, String text, @Nullable String permalink, @Nullable String media) {
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// }
//
// @Generated(1799107445)
// @Internal
// /** This constructor was generated by ObjectBox and may change any time. */
// public Anecdote(long id, String type, String text, String permalink, String media, String websitePageSlug,
// long favoritesTimestamp) {
// this.id = id;
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// this.websitePageSlug = websitePageSlug;
// this.favoritesTimestamp = favoritesTimestamp;
// }
//
// @Generated(443678178)
// public Anecdote() {
// }
//
// /**
// * Return the text without html
// *
// * @return plain text text
// */
// public String getPlainTextContent() {
// return Jsoup.parse(text.replace("<br>", "#lb#")).text().replace("#lb#", System.getProperty("line.separator"));
// }
//
// /**
// * Get the share string of the
// * @param context app context
// * @return the shareable string description of this anecdote
// */
// public String getShareString(Context context){
// String copyString = getPlainTextContent();
//
// if(!TextUtils.isEmpty(permalink)){
// copyString += " " + permalink;
// }
//
// copyString += " " + context.getString(R.string.app_share_credits);
//
// return copyString;
// }
//
// /**
// * Return if the anecdote has been favorited by the user, in the current session (meaning it is not stored).
// */
// public boolean isFavorite(){
// return favoritesTimestamp != 0L;
// }
//
// @Override
// public Anecdote clone() throws CloneNotSupportedException {
// Object o = null;
// try {
// o = super.clone();
// } catch(CloneNotSupportedException cnse) {
// cnse.printStackTrace(System.err);
// }
// return (Anecdote) o;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Anecdote anecdote = (Anecdote) o;
//
// if (type != null ? !type.equals(anecdote.type) : anecdote.type != null) return false;
// if (text != null ? !text.equals(anecdote.text) : anecdote.text != null) return false;
// //noinspection SimplifiableIfStatement
// if (permalink != null ? !permalink.equals(anecdote.permalink) : anecdote.permalink != null) return false;
// return media != null ? media.equals(anecdote.media) : anecdote.media == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = type != null ? type.hashCode() : 0;
// result = 31 * result + (text != null ? text.hashCode() : 0);
// result = 31 * result + (permalink != null ? permalink.hashCode() : 0);
// result = 31 * result + (media != null ? media.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Anecdote text='" + text + "'\', permalink='" + permalink + '\'';
// }
// }
| import android.support.annotation.Nullable;
import android.view.View;
import io.gresse.hugo.anecdote.anecdote.model.Anecdote; | package io.gresse.hugo.anecdote.anecdote.list;
/**
* Listener for all {@link MixedContentAdapter}
* <p/>
* Created by Hugo Gresse on 17/02/16.
*/
public interface AdapterListener {
int ACTION_COPY = 1;
int ACTION_SHARE = 2;
int ACTION_OPEN_IN_BROWSER_PRELOAD = 3;
int ACTION_OPEN_IN_BROWSER = 4;
int ACTION_FULLSCREEN = 5;
int ACTION_FAVORIS = 6;
/**
* When a item received click, follow it with the correct information
*
* @param anecdote the anecdote which was clicked
* @param view the view clicked
* @param action the action to do, like {@link #ACTION_COPY}
*/ | // Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/model/Anecdote.java
// @Entity
// public class Anecdote implements Cloneable {
//
// @Id
// public long id;
// @Index
// @Nullable
// public String type;
// public String text;
// @Nullable
// @Index
// public String permalink;
// @Nullable
// public String media;
// @Index
// public String websitePageSlug;
// public long favoritesTimestamp; // Favorites date, if not favorite: 0L
//
// public Anecdote(String text, String permalink) {
// this(MediaType.TEXT, text, permalink, null);
// }
//
// public Anecdote(@Nullable String type, String text, @Nullable String permalink, @Nullable String media) {
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// }
//
// @Generated(1799107445)
// @Internal
// /** This constructor was generated by ObjectBox and may change any time. */
// public Anecdote(long id, String type, String text, String permalink, String media, String websitePageSlug,
// long favoritesTimestamp) {
// this.id = id;
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// this.websitePageSlug = websitePageSlug;
// this.favoritesTimestamp = favoritesTimestamp;
// }
//
// @Generated(443678178)
// public Anecdote() {
// }
//
// /**
// * Return the text without html
// *
// * @return plain text text
// */
// public String getPlainTextContent() {
// return Jsoup.parse(text.replace("<br>", "#lb#")).text().replace("#lb#", System.getProperty("line.separator"));
// }
//
// /**
// * Get the share string of the
// * @param context app context
// * @return the shareable string description of this anecdote
// */
// public String getShareString(Context context){
// String copyString = getPlainTextContent();
//
// if(!TextUtils.isEmpty(permalink)){
// copyString += " " + permalink;
// }
//
// copyString += " " + context.getString(R.string.app_share_credits);
//
// return copyString;
// }
//
// /**
// * Return if the anecdote has been favorited by the user, in the current session (meaning it is not stored).
// */
// public boolean isFavorite(){
// return favoritesTimestamp != 0L;
// }
//
// @Override
// public Anecdote clone() throws CloneNotSupportedException {
// Object o = null;
// try {
// o = super.clone();
// } catch(CloneNotSupportedException cnse) {
// cnse.printStackTrace(System.err);
// }
// return (Anecdote) o;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Anecdote anecdote = (Anecdote) o;
//
// if (type != null ? !type.equals(anecdote.type) : anecdote.type != null) return false;
// if (text != null ? !text.equals(anecdote.text) : anecdote.text != null) return false;
// //noinspection SimplifiableIfStatement
// if (permalink != null ? !permalink.equals(anecdote.permalink) : anecdote.permalink != null) return false;
// return media != null ? media.equals(anecdote.media) : anecdote.media == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = type != null ? type.hashCode() : 0;
// result = 31 * result + (text != null ? text.hashCode() : 0);
// result = 31 * result + (permalink != null ? permalink.hashCode() : 0);
// result = 31 * result + (media != null ? media.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Anecdote text='" + text + "'\', permalink='" + permalink + '\'';
// }
// }
// Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/list/AdapterListener.java
import android.support.annotation.Nullable;
import android.view.View;
import io.gresse.hugo.anecdote.anecdote.model.Anecdote;
package io.gresse.hugo.anecdote.anecdote.list;
/**
* Listener for all {@link MixedContentAdapter}
* <p/>
* Created by Hugo Gresse on 17/02/16.
*/
public interface AdapterListener {
int ACTION_COPY = 1;
int ACTION_SHARE = 2;
int ACTION_OPEN_IN_BROWSER_PRELOAD = 3;
int ACTION_OPEN_IN_BROWSER = 4;
int ACTION_FULLSCREEN = 5;
int ACTION_FAVORIS = 6;
/**
* When a item received click, follow it with the correct information
*
* @param anecdote the anecdote which was clicked
* @param view the view clicked
* @param action the action to do, like {@link #ACTION_COPY}
*/ | void onClick(Anecdote anecdote, @Nullable View view, int action); |
HugoGresse/Anecdote | app/src/main/java/io/gresse/hugo/anecdote/anecdote/social/SaveAndShareAnecdoteEvent.java | // Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/model/Anecdote.java
// @Entity
// public class Anecdote implements Cloneable {
//
// @Id
// public long id;
// @Index
// @Nullable
// public String type;
// public String text;
// @Nullable
// @Index
// public String permalink;
// @Nullable
// public String media;
// @Index
// public String websitePageSlug;
// public long favoritesTimestamp; // Favorites date, if not favorite: 0L
//
// public Anecdote(String text, String permalink) {
// this(MediaType.TEXT, text, permalink, null);
// }
//
// public Anecdote(@Nullable String type, String text, @Nullable String permalink, @Nullable String media) {
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// }
//
// @Generated(1799107445)
// @Internal
// /** This constructor was generated by ObjectBox and may change any time. */
// public Anecdote(long id, String type, String text, String permalink, String media, String websitePageSlug,
// long favoritesTimestamp) {
// this.id = id;
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// this.websitePageSlug = websitePageSlug;
// this.favoritesTimestamp = favoritesTimestamp;
// }
//
// @Generated(443678178)
// public Anecdote() {
// }
//
// /**
// * Return the text without html
// *
// * @return plain text text
// */
// public String getPlainTextContent() {
// return Jsoup.parse(text.replace("<br>", "#lb#")).text().replace("#lb#", System.getProperty("line.separator"));
// }
//
// /**
// * Get the share string of the
// * @param context app context
// * @return the shareable string description of this anecdote
// */
// public String getShareString(Context context){
// String copyString = getPlainTextContent();
//
// if(!TextUtils.isEmpty(permalink)){
// copyString += " " + permalink;
// }
//
// copyString += " " + context.getString(R.string.app_share_credits);
//
// return copyString;
// }
//
// /**
// * Return if the anecdote has been favorited by the user, in the current session (meaning it is not stored).
// */
// public boolean isFavorite(){
// return favoritesTimestamp != 0L;
// }
//
// @Override
// public Anecdote clone() throws CloneNotSupportedException {
// Object o = null;
// try {
// o = super.clone();
// } catch(CloneNotSupportedException cnse) {
// cnse.printStackTrace(System.err);
// }
// return (Anecdote) o;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Anecdote anecdote = (Anecdote) o;
//
// if (type != null ? !type.equals(anecdote.type) : anecdote.type != null) return false;
// if (text != null ? !text.equals(anecdote.text) : anecdote.text != null) return false;
// //noinspection SimplifiableIfStatement
// if (permalink != null ? !permalink.equals(anecdote.permalink) : anecdote.permalink != null) return false;
// return media != null ? media.equals(anecdote.media) : anecdote.media == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = type != null ? type.hashCode() : 0;
// result = 31 * result + (text != null ? text.hashCode() : 0);
// result = 31 * result + (permalink != null ? permalink.hashCode() : 0);
// result = 31 * result + (media != null ? media.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Anecdote text='" + text + "'\', permalink='" + permalink + '\'';
// }
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/view/CustomImageView.java
// public class CustomImageView extends android.support.v7.widget.AppCompatImageView {
// public CustomImageView(Context context) {
// super(context);
// }
//
// public CustomImageView(Context context, @Nullable AttributeSet attrs) {
// super(context, attrs);
// }
//
// public CustomImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// }
// @Nullable
// public File saveImage(){
//
// Drawable drawable = getDrawable();
// Bitmap bitmap = null;
//
// if(drawable instanceof BitmapDrawable){
// bitmap = ((BitmapDrawable) drawable).getBitmap();
// } else if (drawable instanceof GlideDrawable){
// bitmap = ((GlideBitmapDrawable)drawable.getCurrent()).getBitmap();
// }
//
// File output = new ImageSaver(getContext())
// .setExternal(true)
// .setDirectoryName(Configuration.DOWNLOAD_FOLDER)
// .setFileName(getContext().getString(R.string.app_name) + "-" + System.currentTimeMillis() + ".jpg")
// .save(bitmap);
//
// if(output != null){
// return output;
// }
// return null;
// }
// }
| import io.gresse.hugo.anecdote.anecdote.model.Anecdote;
import io.gresse.hugo.anecdote.view.CustomImageView; | package io.gresse.hugo.anecdote.anecdote.social;
/**
* Save a file and ask to share it
*
* Created by Hugo Gresse on 22/03/2017.
*/
public class SaveAndShareAnecdoteEvent extends SocialEvent {
final CustomImageView customImageView;
| // Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/model/Anecdote.java
// @Entity
// public class Anecdote implements Cloneable {
//
// @Id
// public long id;
// @Index
// @Nullable
// public String type;
// public String text;
// @Nullable
// @Index
// public String permalink;
// @Nullable
// public String media;
// @Index
// public String websitePageSlug;
// public long favoritesTimestamp; // Favorites date, if not favorite: 0L
//
// public Anecdote(String text, String permalink) {
// this(MediaType.TEXT, text, permalink, null);
// }
//
// public Anecdote(@Nullable String type, String text, @Nullable String permalink, @Nullable String media) {
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// }
//
// @Generated(1799107445)
// @Internal
// /** This constructor was generated by ObjectBox and may change any time. */
// public Anecdote(long id, String type, String text, String permalink, String media, String websitePageSlug,
// long favoritesTimestamp) {
// this.id = id;
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// this.websitePageSlug = websitePageSlug;
// this.favoritesTimestamp = favoritesTimestamp;
// }
//
// @Generated(443678178)
// public Anecdote() {
// }
//
// /**
// * Return the text without html
// *
// * @return plain text text
// */
// public String getPlainTextContent() {
// return Jsoup.parse(text.replace("<br>", "#lb#")).text().replace("#lb#", System.getProperty("line.separator"));
// }
//
// /**
// * Get the share string of the
// * @param context app context
// * @return the shareable string description of this anecdote
// */
// public String getShareString(Context context){
// String copyString = getPlainTextContent();
//
// if(!TextUtils.isEmpty(permalink)){
// copyString += " " + permalink;
// }
//
// copyString += " " + context.getString(R.string.app_share_credits);
//
// return copyString;
// }
//
// /**
// * Return if the anecdote has been favorited by the user, in the current session (meaning it is not stored).
// */
// public boolean isFavorite(){
// return favoritesTimestamp != 0L;
// }
//
// @Override
// public Anecdote clone() throws CloneNotSupportedException {
// Object o = null;
// try {
// o = super.clone();
// } catch(CloneNotSupportedException cnse) {
// cnse.printStackTrace(System.err);
// }
// return (Anecdote) o;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Anecdote anecdote = (Anecdote) o;
//
// if (type != null ? !type.equals(anecdote.type) : anecdote.type != null) return false;
// if (text != null ? !text.equals(anecdote.text) : anecdote.text != null) return false;
// //noinspection SimplifiableIfStatement
// if (permalink != null ? !permalink.equals(anecdote.permalink) : anecdote.permalink != null) return false;
// return media != null ? media.equals(anecdote.media) : anecdote.media == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = type != null ? type.hashCode() : 0;
// result = 31 * result + (text != null ? text.hashCode() : 0);
// result = 31 * result + (permalink != null ? permalink.hashCode() : 0);
// result = 31 * result + (media != null ? media.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Anecdote text='" + text + "'\', permalink='" + permalink + '\'';
// }
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/view/CustomImageView.java
// public class CustomImageView extends android.support.v7.widget.AppCompatImageView {
// public CustomImageView(Context context) {
// super(context);
// }
//
// public CustomImageView(Context context, @Nullable AttributeSet attrs) {
// super(context, attrs);
// }
//
// public CustomImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
// super(context, attrs, defStyleAttr);
// }
// @Nullable
// public File saveImage(){
//
// Drawable drawable = getDrawable();
// Bitmap bitmap = null;
//
// if(drawable instanceof BitmapDrawable){
// bitmap = ((BitmapDrawable) drawable).getBitmap();
// } else if (drawable instanceof GlideDrawable){
// bitmap = ((GlideBitmapDrawable)drawable.getCurrent()).getBitmap();
// }
//
// File output = new ImageSaver(getContext())
// .setExternal(true)
// .setDirectoryName(Configuration.DOWNLOAD_FOLDER)
// .setFileName(getContext().getString(R.string.app_name) + "-" + System.currentTimeMillis() + ".jpg")
// .save(bitmap);
//
// if(output != null){
// return output;
// }
// return null;
// }
// }
// Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/social/SaveAndShareAnecdoteEvent.java
import io.gresse.hugo.anecdote.anecdote.model.Anecdote;
import io.gresse.hugo.anecdote.view.CustomImageView;
package io.gresse.hugo.anecdote.anecdote.social;
/**
* Save a file and ask to share it
*
* Created by Hugo Gresse on 22/03/2017.
*/
public class SaveAndShareAnecdoteEvent extends SocialEvent {
final CustomImageView customImageView;
| public SaveAndShareAnecdoteEvent(String websiteName, Anecdote anecdote, CustomImageView customImageView) { |
HugoGresse/Anecdote | app/src/main/java/io/gresse/hugo/anecdote/anecdote/social/OpenAnecdoteEvent.java | // Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/model/Anecdote.java
// @Entity
// public class Anecdote implements Cloneable {
//
// @Id
// public long id;
// @Index
// @Nullable
// public String type;
// public String text;
// @Nullable
// @Index
// public String permalink;
// @Nullable
// public String media;
// @Index
// public String websitePageSlug;
// public long favoritesTimestamp; // Favorites date, if not favorite: 0L
//
// public Anecdote(String text, String permalink) {
// this(MediaType.TEXT, text, permalink, null);
// }
//
// public Anecdote(@Nullable String type, String text, @Nullable String permalink, @Nullable String media) {
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// }
//
// @Generated(1799107445)
// @Internal
// /** This constructor was generated by ObjectBox and may change any time. */
// public Anecdote(long id, String type, String text, String permalink, String media, String websitePageSlug,
// long favoritesTimestamp) {
// this.id = id;
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// this.websitePageSlug = websitePageSlug;
// this.favoritesTimestamp = favoritesTimestamp;
// }
//
// @Generated(443678178)
// public Anecdote() {
// }
//
// /**
// * Return the text without html
// *
// * @return plain text text
// */
// public String getPlainTextContent() {
// return Jsoup.parse(text.replace("<br>", "#lb#")).text().replace("#lb#", System.getProperty("line.separator"));
// }
//
// /**
// * Get the share string of the
// * @param context app context
// * @return the shareable string description of this anecdote
// */
// public String getShareString(Context context){
// String copyString = getPlainTextContent();
//
// if(!TextUtils.isEmpty(permalink)){
// copyString += " " + permalink;
// }
//
// copyString += " " + context.getString(R.string.app_share_credits);
//
// return copyString;
// }
//
// /**
// * Return if the anecdote has been favorited by the user, in the current session (meaning it is not stored).
// */
// public boolean isFavorite(){
// return favoritesTimestamp != 0L;
// }
//
// @Override
// public Anecdote clone() throws CloneNotSupportedException {
// Object o = null;
// try {
// o = super.clone();
// } catch(CloneNotSupportedException cnse) {
// cnse.printStackTrace(System.err);
// }
// return (Anecdote) o;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Anecdote anecdote = (Anecdote) o;
//
// if (type != null ? !type.equals(anecdote.type) : anecdote.type != null) return false;
// if (text != null ? !text.equals(anecdote.text) : anecdote.text != null) return false;
// //noinspection SimplifiableIfStatement
// if (permalink != null ? !permalink.equals(anecdote.permalink) : anecdote.permalink != null) return false;
// return media != null ? media.equals(anecdote.media) : anecdote.media == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = type != null ? type.hashCode() : 0;
// result = 31 * result + (text != null ? text.hashCode() : 0);
// result = 31 * result + (permalink != null ? permalink.hashCode() : 0);
// result = 31 * result + (media != null ? media.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Anecdote text='" + text + "'\', permalink='" + permalink + '\'';
// }
// }
| import io.gresse.hugo.anecdote.anecdote.model.Anecdote; | package io.gresse.hugo.anecdote.anecdote.social;
/**
* Launched to open the web page of the anecdote
* <p/>
* Created by Hugo Gresse on 20/07/16.
*/
public class OpenAnecdoteEvent extends SocialEvent {
public final boolean preloadOnly;
| // Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/model/Anecdote.java
// @Entity
// public class Anecdote implements Cloneable {
//
// @Id
// public long id;
// @Index
// @Nullable
// public String type;
// public String text;
// @Nullable
// @Index
// public String permalink;
// @Nullable
// public String media;
// @Index
// public String websitePageSlug;
// public long favoritesTimestamp; // Favorites date, if not favorite: 0L
//
// public Anecdote(String text, String permalink) {
// this(MediaType.TEXT, text, permalink, null);
// }
//
// public Anecdote(@Nullable String type, String text, @Nullable String permalink, @Nullable String media) {
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// }
//
// @Generated(1799107445)
// @Internal
// /** This constructor was generated by ObjectBox and may change any time. */
// public Anecdote(long id, String type, String text, String permalink, String media, String websitePageSlug,
// long favoritesTimestamp) {
// this.id = id;
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// this.websitePageSlug = websitePageSlug;
// this.favoritesTimestamp = favoritesTimestamp;
// }
//
// @Generated(443678178)
// public Anecdote() {
// }
//
// /**
// * Return the text without html
// *
// * @return plain text text
// */
// public String getPlainTextContent() {
// return Jsoup.parse(text.replace("<br>", "#lb#")).text().replace("#lb#", System.getProperty("line.separator"));
// }
//
// /**
// * Get the share string of the
// * @param context app context
// * @return the shareable string description of this anecdote
// */
// public String getShareString(Context context){
// String copyString = getPlainTextContent();
//
// if(!TextUtils.isEmpty(permalink)){
// copyString += " " + permalink;
// }
//
// copyString += " " + context.getString(R.string.app_share_credits);
//
// return copyString;
// }
//
// /**
// * Return if the anecdote has been favorited by the user, in the current session (meaning it is not stored).
// */
// public boolean isFavorite(){
// return favoritesTimestamp != 0L;
// }
//
// @Override
// public Anecdote clone() throws CloneNotSupportedException {
// Object o = null;
// try {
// o = super.clone();
// } catch(CloneNotSupportedException cnse) {
// cnse.printStackTrace(System.err);
// }
// return (Anecdote) o;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Anecdote anecdote = (Anecdote) o;
//
// if (type != null ? !type.equals(anecdote.type) : anecdote.type != null) return false;
// if (text != null ? !text.equals(anecdote.text) : anecdote.text != null) return false;
// //noinspection SimplifiableIfStatement
// if (permalink != null ? !permalink.equals(anecdote.permalink) : anecdote.permalink != null) return false;
// return media != null ? media.equals(anecdote.media) : anecdote.media == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = type != null ? type.hashCode() : 0;
// result = 31 * result + (text != null ? text.hashCode() : 0);
// result = 31 * result + (permalink != null ? permalink.hashCode() : 0);
// result = 31 * result + (media != null ? media.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Anecdote text='" + text + "'\', permalink='" + permalink + '\'';
// }
// }
// Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/social/OpenAnecdoteEvent.java
import io.gresse.hugo.anecdote.anecdote.model.Anecdote;
package io.gresse.hugo.anecdote.anecdote.social;
/**
* Launched to open the web page of the anecdote
* <p/>
* Created by Hugo Gresse on 20/07/16.
*/
public class OpenAnecdoteEvent extends SocialEvent {
public final boolean preloadOnly;
| public OpenAnecdoteEvent(String websiteName, Anecdote anecdote, boolean preloadOnly) { |
HugoGresse/Anecdote | app/src/main/java/io/gresse/hugo/anecdote/anecdote/fullscreen/FullscreenEvent.java | // Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/model/Anecdote.java
// @Entity
// public class Anecdote implements Cloneable {
//
// @Id
// public long id;
// @Index
// @Nullable
// public String type;
// public String text;
// @Nullable
// @Index
// public String permalink;
// @Nullable
// public String media;
// @Index
// public String websitePageSlug;
// public long favoritesTimestamp; // Favorites date, if not favorite: 0L
//
// public Anecdote(String text, String permalink) {
// this(MediaType.TEXT, text, permalink, null);
// }
//
// public Anecdote(@Nullable String type, String text, @Nullable String permalink, @Nullable String media) {
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// }
//
// @Generated(1799107445)
// @Internal
// /** This constructor was generated by ObjectBox and may change any time. */
// public Anecdote(long id, String type, String text, String permalink, String media, String websitePageSlug,
// long favoritesTimestamp) {
// this.id = id;
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// this.websitePageSlug = websitePageSlug;
// this.favoritesTimestamp = favoritesTimestamp;
// }
//
// @Generated(443678178)
// public Anecdote() {
// }
//
// /**
// * Return the text without html
// *
// * @return plain text text
// */
// public String getPlainTextContent() {
// return Jsoup.parse(text.replace("<br>", "#lb#")).text().replace("#lb#", System.getProperty("line.separator"));
// }
//
// /**
// * Get the share string of the
// * @param context app context
// * @return the shareable string description of this anecdote
// */
// public String getShareString(Context context){
// String copyString = getPlainTextContent();
//
// if(!TextUtils.isEmpty(permalink)){
// copyString += " " + permalink;
// }
//
// copyString += " " + context.getString(R.string.app_share_credits);
//
// return copyString;
// }
//
// /**
// * Return if the anecdote has been favorited by the user, in the current session (meaning it is not stored).
// */
// public boolean isFavorite(){
// return favoritesTimestamp != 0L;
// }
//
// @Override
// public Anecdote clone() throws CloneNotSupportedException {
// Object o = null;
// try {
// o = super.clone();
// } catch(CloneNotSupportedException cnse) {
// cnse.printStackTrace(System.err);
// }
// return (Anecdote) o;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Anecdote anecdote = (Anecdote) o;
//
// if (type != null ? !type.equals(anecdote.type) : anecdote.type != null) return false;
// if (text != null ? !text.equals(anecdote.text) : anecdote.text != null) return false;
// //noinspection SimplifiableIfStatement
// if (permalink != null ? !permalink.equals(anecdote.permalink) : anecdote.permalink != null) return false;
// return media != null ? media.equals(anecdote.media) : anecdote.media == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = type != null ? type.hashCode() : 0;
// result = 31 * result + (text != null ? text.hashCode() : 0);
// result = 31 * result + (permalink != null ? permalink.hashCode() : 0);
// result = 31 * result + (media != null ? media.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Anecdote text='" + text + "'\', permalink='" + permalink + '\'';
// }
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/event/Event.java
// public interface Event {
// }
| import android.support.v4.app.Fragment;
import android.view.View;
import io.gresse.hugo.anecdote.anecdote.model.Anecdote;
import io.gresse.hugo.anecdote.event.Event; | package io.gresse.hugo.anecdote.anecdote.fullscreen;
/**
* A click on an anecdote rich text request to open the text in fullscreen
* <p/>
* Created by Hugo Gresse on 21/04/16.
*/
public class FullscreenEvent implements Event {
public static final int TYPE_IMAGE = 0;
public static final int TYPE_VIDEO = 1;
public int type;
public String websiteName;
public Fragment currentFragment;
public View transitionView;
public String transitionName; | // Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/model/Anecdote.java
// @Entity
// public class Anecdote implements Cloneable {
//
// @Id
// public long id;
// @Index
// @Nullable
// public String type;
// public String text;
// @Nullable
// @Index
// public String permalink;
// @Nullable
// public String media;
// @Index
// public String websitePageSlug;
// public long favoritesTimestamp; // Favorites date, if not favorite: 0L
//
// public Anecdote(String text, String permalink) {
// this(MediaType.TEXT, text, permalink, null);
// }
//
// public Anecdote(@Nullable String type, String text, @Nullable String permalink, @Nullable String media) {
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// }
//
// @Generated(1799107445)
// @Internal
// /** This constructor was generated by ObjectBox and may change any time. */
// public Anecdote(long id, String type, String text, String permalink, String media, String websitePageSlug,
// long favoritesTimestamp) {
// this.id = id;
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// this.websitePageSlug = websitePageSlug;
// this.favoritesTimestamp = favoritesTimestamp;
// }
//
// @Generated(443678178)
// public Anecdote() {
// }
//
// /**
// * Return the text without html
// *
// * @return plain text text
// */
// public String getPlainTextContent() {
// return Jsoup.parse(text.replace("<br>", "#lb#")).text().replace("#lb#", System.getProperty("line.separator"));
// }
//
// /**
// * Get the share string of the
// * @param context app context
// * @return the shareable string description of this anecdote
// */
// public String getShareString(Context context){
// String copyString = getPlainTextContent();
//
// if(!TextUtils.isEmpty(permalink)){
// copyString += " " + permalink;
// }
//
// copyString += " " + context.getString(R.string.app_share_credits);
//
// return copyString;
// }
//
// /**
// * Return if the anecdote has been favorited by the user, in the current session (meaning it is not stored).
// */
// public boolean isFavorite(){
// return favoritesTimestamp != 0L;
// }
//
// @Override
// public Anecdote clone() throws CloneNotSupportedException {
// Object o = null;
// try {
// o = super.clone();
// } catch(CloneNotSupportedException cnse) {
// cnse.printStackTrace(System.err);
// }
// return (Anecdote) o;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Anecdote anecdote = (Anecdote) o;
//
// if (type != null ? !type.equals(anecdote.type) : anecdote.type != null) return false;
// if (text != null ? !text.equals(anecdote.text) : anecdote.text != null) return false;
// //noinspection SimplifiableIfStatement
// if (permalink != null ? !permalink.equals(anecdote.permalink) : anecdote.permalink != null) return false;
// return media != null ? media.equals(anecdote.media) : anecdote.media == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = type != null ? type.hashCode() : 0;
// result = 31 * result + (text != null ? text.hashCode() : 0);
// result = 31 * result + (permalink != null ? permalink.hashCode() : 0);
// result = 31 * result + (media != null ? media.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Anecdote text='" + text + "'\', permalink='" + permalink + '\'';
// }
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/event/Event.java
// public interface Event {
// }
// Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/fullscreen/FullscreenEvent.java
import android.support.v4.app.Fragment;
import android.view.View;
import io.gresse.hugo.anecdote.anecdote.model.Anecdote;
import io.gresse.hugo.anecdote.event.Event;
package io.gresse.hugo.anecdote.anecdote.fullscreen;
/**
* A click on an anecdote rich text request to open the text in fullscreen
* <p/>
* Created by Hugo Gresse on 21/04/16.
*/
public class FullscreenEvent implements Event {
public static final int TYPE_IMAGE = 0;
public static final int TYPE_VIDEO = 1;
public int type;
public String websiteName;
public Fragment currentFragment;
public View transitionView;
public String transitionName; | public Anecdote anecdote; |
HugoGresse/Anecdote | app/src/main/java/io/gresse/hugo/anecdote/view/CustomImageView.java | // Path: app/src/main/java/io/gresse/hugo/anecdote/Configuration.java
// public class Configuration {
//
// public static final boolean DEBUG = BuildConfig.DEBUG;
// public static final String API_VERSION = "2";
// public static final String API_URL = "https://anecdote-api.firebaseio.com/v" + API_VERSION + "/websites.json";
// public static final String DOWNLOAD_FOLDER = "Anecdote";
// public static final int IMAGE_SAVE_TOAST_DURATION = 5000;
// public static final String DONATION_LINK = "https://paypal.me/HugoGresse/5";
//
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/util/ImageSaver.java
// public class ImageSaver {
//
// public static final String TAG = ImageSaver.class.getSimpleName();
// private String mDirectoryName = "images";
// private String mFileName = "image.png";
// private Context mContext;
// private boolean mExternal;
//
// public ImageSaver(Context context) {
// this.mContext = context;
// }
//
// public ImageSaver setFileName(String fileName) {
// this.mFileName = fileName;
// return this;
// }
//
// public ImageSaver setExternal(boolean external) {
// this.mExternal = external;
// return this;
// }
//
// public ImageSaver setDirectoryName(String directoryName) {
// this.mDirectoryName = directoryName;
// return this;
// }
//
// @Nullable
// public File save(Bitmap bitmapImage) {
// FileOutputStream fileOutputStream = null;
// File file = null;
// try {
// file = createFile();
// if(!file.createNewFile()){
// Log.w(TAG, "Fail to create image file to " + file.getAbsolutePath());
// return null;
// }
// fileOutputStream = new FileOutputStream(file);
// Log.d(TAG, "Saving image to " + file.getAbsolutePath());
// bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
//
// if(mExternal){
// ContentValues values = new ContentValues();
// values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
// values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
// mContext.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
// }
// } catch (Exception e) {
// Log.w(TAG, "Fail to save image " + ((file != null) ? file.getAbsolutePath() : ""));
// e.printStackTrace();
// } finally {
// mContext = null;
// try {
// if (fileOutputStream != null) {
// fileOutputStream.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// return file;
// }
//
// @NonNull
// private File createFile() {
// File directory;
// if (mExternal) {
// directory = new File(
// Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
// mDirectoryName);
// if(!directory.exists()) {
// if(!directory.mkdirs()){
// Log.w(TAG, "Unable to make Anecdote picture folder " + directory.getAbsolutePath());
// }
// }
// } else {
// directory = mContext.getDir(mDirectoryName, Context.MODE_PRIVATE);
// }
//
// return new File(directory, mFileName);
// }
//
// public Bitmap load() {
// FileInputStream inputStream = null;
// try {
// inputStream = new FileInputStream(createFile());
// return BitmapFactory.decodeStream(inputStream);
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// try {
// if (inputStream != null) {
// inputStream.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// return null;
// }
// }
| import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import java.io.File;
import io.gresse.hugo.anecdote.Configuration;
import io.gresse.hugo.anecdote.R;
import io.gresse.hugo.anecdote.util.ImageSaver; | package io.gresse.hugo.anecdote.view;
/**
* Custom imageview that add some functionalities to it
* Created by Hugo Gresse on 18/03/2017.
*/
public class CustomImageView extends android.support.v7.widget.AppCompatImageView {
public CustomImageView(Context context) {
super(context);
}
public CustomImageView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public CustomImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Nullable
public File saveImage(){
Drawable drawable = getDrawable();
Bitmap bitmap = null;
if(drawable instanceof BitmapDrawable){
bitmap = ((BitmapDrawable) drawable).getBitmap();
} else if (drawable instanceof GlideDrawable){
bitmap = ((GlideBitmapDrawable)drawable.getCurrent()).getBitmap();
}
| // Path: app/src/main/java/io/gresse/hugo/anecdote/Configuration.java
// public class Configuration {
//
// public static final boolean DEBUG = BuildConfig.DEBUG;
// public static final String API_VERSION = "2";
// public static final String API_URL = "https://anecdote-api.firebaseio.com/v" + API_VERSION + "/websites.json";
// public static final String DOWNLOAD_FOLDER = "Anecdote";
// public static final int IMAGE_SAVE_TOAST_DURATION = 5000;
// public static final String DONATION_LINK = "https://paypal.me/HugoGresse/5";
//
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/util/ImageSaver.java
// public class ImageSaver {
//
// public static final String TAG = ImageSaver.class.getSimpleName();
// private String mDirectoryName = "images";
// private String mFileName = "image.png";
// private Context mContext;
// private boolean mExternal;
//
// public ImageSaver(Context context) {
// this.mContext = context;
// }
//
// public ImageSaver setFileName(String fileName) {
// this.mFileName = fileName;
// return this;
// }
//
// public ImageSaver setExternal(boolean external) {
// this.mExternal = external;
// return this;
// }
//
// public ImageSaver setDirectoryName(String directoryName) {
// this.mDirectoryName = directoryName;
// return this;
// }
//
// @Nullable
// public File save(Bitmap bitmapImage) {
// FileOutputStream fileOutputStream = null;
// File file = null;
// try {
// file = createFile();
// if(!file.createNewFile()){
// Log.w(TAG, "Fail to create image file to " + file.getAbsolutePath());
// return null;
// }
// fileOutputStream = new FileOutputStream(file);
// Log.d(TAG, "Saving image to " + file.getAbsolutePath());
// bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
//
// if(mExternal){
// ContentValues values = new ContentValues();
// values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
// values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
// mContext.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
// }
// } catch (Exception e) {
// Log.w(TAG, "Fail to save image " + ((file != null) ? file.getAbsolutePath() : ""));
// e.printStackTrace();
// } finally {
// mContext = null;
// try {
// if (fileOutputStream != null) {
// fileOutputStream.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// return file;
// }
//
// @NonNull
// private File createFile() {
// File directory;
// if (mExternal) {
// directory = new File(
// Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
// mDirectoryName);
// if(!directory.exists()) {
// if(!directory.mkdirs()){
// Log.w(TAG, "Unable to make Anecdote picture folder " + directory.getAbsolutePath());
// }
// }
// } else {
// directory = mContext.getDir(mDirectoryName, Context.MODE_PRIVATE);
// }
//
// return new File(directory, mFileName);
// }
//
// public Bitmap load() {
// FileInputStream inputStream = null;
// try {
// inputStream = new FileInputStream(createFile());
// return BitmapFactory.decodeStream(inputStream);
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// try {
// if (inputStream != null) {
// inputStream.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// return null;
// }
// }
// Path: app/src/main/java/io/gresse/hugo/anecdote/view/CustomImageView.java
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import java.io.File;
import io.gresse.hugo.anecdote.Configuration;
import io.gresse.hugo.anecdote.R;
import io.gresse.hugo.anecdote.util.ImageSaver;
package io.gresse.hugo.anecdote.view;
/**
* Custom imageview that add some functionalities to it
* Created by Hugo Gresse on 18/03/2017.
*/
public class CustomImageView extends android.support.v7.widget.AppCompatImageView {
public CustomImageView(Context context) {
super(context);
}
public CustomImageView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public CustomImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Nullable
public File saveImage(){
Drawable drawable = getDrawable();
Bitmap bitmap = null;
if(drawable instanceof BitmapDrawable){
bitmap = ((BitmapDrawable) drawable).getBitmap();
} else if (drawable instanceof GlideDrawable){
bitmap = ((GlideBitmapDrawable)drawable.getCurrent()).getBitmap();
}
| File output = new ImageSaver(getContext()) |
HugoGresse/Anecdote | app/src/main/java/io/gresse/hugo/anecdote/view/CustomImageView.java | // Path: app/src/main/java/io/gresse/hugo/anecdote/Configuration.java
// public class Configuration {
//
// public static final boolean DEBUG = BuildConfig.DEBUG;
// public static final String API_VERSION = "2";
// public static final String API_URL = "https://anecdote-api.firebaseio.com/v" + API_VERSION + "/websites.json";
// public static final String DOWNLOAD_FOLDER = "Anecdote";
// public static final int IMAGE_SAVE_TOAST_DURATION = 5000;
// public static final String DONATION_LINK = "https://paypal.me/HugoGresse/5";
//
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/util/ImageSaver.java
// public class ImageSaver {
//
// public static final String TAG = ImageSaver.class.getSimpleName();
// private String mDirectoryName = "images";
// private String mFileName = "image.png";
// private Context mContext;
// private boolean mExternal;
//
// public ImageSaver(Context context) {
// this.mContext = context;
// }
//
// public ImageSaver setFileName(String fileName) {
// this.mFileName = fileName;
// return this;
// }
//
// public ImageSaver setExternal(boolean external) {
// this.mExternal = external;
// return this;
// }
//
// public ImageSaver setDirectoryName(String directoryName) {
// this.mDirectoryName = directoryName;
// return this;
// }
//
// @Nullable
// public File save(Bitmap bitmapImage) {
// FileOutputStream fileOutputStream = null;
// File file = null;
// try {
// file = createFile();
// if(!file.createNewFile()){
// Log.w(TAG, "Fail to create image file to " + file.getAbsolutePath());
// return null;
// }
// fileOutputStream = new FileOutputStream(file);
// Log.d(TAG, "Saving image to " + file.getAbsolutePath());
// bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
//
// if(mExternal){
// ContentValues values = new ContentValues();
// values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
// values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
// mContext.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
// }
// } catch (Exception e) {
// Log.w(TAG, "Fail to save image " + ((file != null) ? file.getAbsolutePath() : ""));
// e.printStackTrace();
// } finally {
// mContext = null;
// try {
// if (fileOutputStream != null) {
// fileOutputStream.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// return file;
// }
//
// @NonNull
// private File createFile() {
// File directory;
// if (mExternal) {
// directory = new File(
// Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
// mDirectoryName);
// if(!directory.exists()) {
// if(!directory.mkdirs()){
// Log.w(TAG, "Unable to make Anecdote picture folder " + directory.getAbsolutePath());
// }
// }
// } else {
// directory = mContext.getDir(mDirectoryName, Context.MODE_PRIVATE);
// }
//
// return new File(directory, mFileName);
// }
//
// public Bitmap load() {
// FileInputStream inputStream = null;
// try {
// inputStream = new FileInputStream(createFile());
// return BitmapFactory.decodeStream(inputStream);
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// try {
// if (inputStream != null) {
// inputStream.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// return null;
// }
// }
| import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import java.io.File;
import io.gresse.hugo.anecdote.Configuration;
import io.gresse.hugo.anecdote.R;
import io.gresse.hugo.anecdote.util.ImageSaver; | package io.gresse.hugo.anecdote.view;
/**
* Custom imageview that add some functionalities to it
* Created by Hugo Gresse on 18/03/2017.
*/
public class CustomImageView extends android.support.v7.widget.AppCompatImageView {
public CustomImageView(Context context) {
super(context);
}
public CustomImageView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public CustomImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Nullable
public File saveImage(){
Drawable drawable = getDrawable();
Bitmap bitmap = null;
if(drawable instanceof BitmapDrawable){
bitmap = ((BitmapDrawable) drawable).getBitmap();
} else if (drawable instanceof GlideDrawable){
bitmap = ((GlideBitmapDrawable)drawable.getCurrent()).getBitmap();
}
File output = new ImageSaver(getContext())
.setExternal(true) | // Path: app/src/main/java/io/gresse/hugo/anecdote/Configuration.java
// public class Configuration {
//
// public static final boolean DEBUG = BuildConfig.DEBUG;
// public static final String API_VERSION = "2";
// public static final String API_URL = "https://anecdote-api.firebaseio.com/v" + API_VERSION + "/websites.json";
// public static final String DOWNLOAD_FOLDER = "Anecdote";
// public static final int IMAGE_SAVE_TOAST_DURATION = 5000;
// public static final String DONATION_LINK = "https://paypal.me/HugoGresse/5";
//
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/util/ImageSaver.java
// public class ImageSaver {
//
// public static final String TAG = ImageSaver.class.getSimpleName();
// private String mDirectoryName = "images";
// private String mFileName = "image.png";
// private Context mContext;
// private boolean mExternal;
//
// public ImageSaver(Context context) {
// this.mContext = context;
// }
//
// public ImageSaver setFileName(String fileName) {
// this.mFileName = fileName;
// return this;
// }
//
// public ImageSaver setExternal(boolean external) {
// this.mExternal = external;
// return this;
// }
//
// public ImageSaver setDirectoryName(String directoryName) {
// this.mDirectoryName = directoryName;
// return this;
// }
//
// @Nullable
// public File save(Bitmap bitmapImage) {
// FileOutputStream fileOutputStream = null;
// File file = null;
// try {
// file = createFile();
// if(!file.createNewFile()){
// Log.w(TAG, "Fail to create image file to " + file.getAbsolutePath());
// return null;
// }
// fileOutputStream = new FileOutputStream(file);
// Log.d(TAG, "Saving image to " + file.getAbsolutePath());
// bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
//
// if(mExternal){
// ContentValues values = new ContentValues();
// values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
// values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
// mContext.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
// }
// } catch (Exception e) {
// Log.w(TAG, "Fail to save image " + ((file != null) ? file.getAbsolutePath() : ""));
// e.printStackTrace();
// } finally {
// mContext = null;
// try {
// if (fileOutputStream != null) {
// fileOutputStream.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// return file;
// }
//
// @NonNull
// private File createFile() {
// File directory;
// if (mExternal) {
// directory = new File(
// Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
// mDirectoryName);
// if(!directory.exists()) {
// if(!directory.mkdirs()){
// Log.w(TAG, "Unable to make Anecdote picture folder " + directory.getAbsolutePath());
// }
// }
// } else {
// directory = mContext.getDir(mDirectoryName, Context.MODE_PRIVATE);
// }
//
// return new File(directory, mFileName);
// }
//
// public Bitmap load() {
// FileInputStream inputStream = null;
// try {
// inputStream = new FileInputStream(createFile());
// return BitmapFactory.decodeStream(inputStream);
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// try {
// if (inputStream != null) {
// inputStream.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// return null;
// }
// }
// Path: app/src/main/java/io/gresse/hugo/anecdote/view/CustomImageView.java
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import java.io.File;
import io.gresse.hugo.anecdote.Configuration;
import io.gresse.hugo.anecdote.R;
import io.gresse.hugo.anecdote.util.ImageSaver;
package io.gresse.hugo.anecdote.view;
/**
* Custom imageview that add some functionalities to it
* Created by Hugo Gresse on 18/03/2017.
*/
public class CustomImageView extends android.support.v7.widget.AppCompatImageView {
public CustomImageView(Context context) {
super(context);
}
public CustomImageView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public CustomImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Nullable
public File saveImage(){
Drawable drawable = getDrawable();
Bitmap bitmap = null;
if(drawable instanceof BitmapDrawable){
bitmap = ((BitmapDrawable) drawable).getBitmap();
} else if (drawable instanceof GlideDrawable){
bitmap = ((GlideBitmapDrawable)drawable.getCurrent()).getBitmap();
}
File output = new ImageSaver(getContext())
.setExternal(true) | .setDirectoryName(Configuration.DOWNLOAD_FOLDER) |
HugoGresse/Anecdote | app/src/main/java/io/gresse/hugo/anecdote/event/ChangeTitleEvent.java | // Path: app/src/main/java/io/gresse/hugo/anecdote/util/TitledFragment.java
// public abstract class TitledFragment extends Fragment {
//
// /**
// * Return the fragment title that could be use in a Toolbar for example.
// */
// public abstract String getTitle();
//
// }
| import android.support.annotation.Nullable;
import io.gresse.hugo.anecdote.util.TitledFragment; | package io.gresse.hugo.anecdote.event;
/**
* Requested when we need ot change the Toolbar title
* <p/>
* Created by Hugo Gresse on 14/02/16.
*/
public class ChangeTitleEvent implements Event {
public String title;
@Nullable
public String additionalTitle;
public boolean spinnerEnable;
public ChangeTitleEvent(String title) {
this.title = title;
this.spinnerEnable = false;
}
| // Path: app/src/main/java/io/gresse/hugo/anecdote/util/TitledFragment.java
// public abstract class TitledFragment extends Fragment {
//
// /**
// * Return the fragment title that could be use in a Toolbar for example.
// */
// public abstract String getTitle();
//
// }
// Path: app/src/main/java/io/gresse/hugo/anecdote/event/ChangeTitleEvent.java
import android.support.annotation.Nullable;
import io.gresse.hugo.anecdote.util.TitledFragment;
package io.gresse.hugo.anecdote.event;
/**
* Requested when we need ot change the Toolbar title
* <p/>
* Created by Hugo Gresse on 14/02/16.
*/
public class ChangeTitleEvent implements Event {
public String title;
@Nullable
public String additionalTitle;
public boolean spinnerEnable;
public ChangeTitleEvent(String title) {
this.title = title;
this.spinnerEnable = false;
}
| public ChangeTitleEvent(TitledFragment fragment, String additionalSlug, boolean spinnerEnable) { |
HugoGresse/Anecdote | app/src/main/java/io/gresse/hugo/anecdote/anecdote/list/MixedBaseViewHolder.java | // Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/model/Anecdote.java
// @Entity
// public class Anecdote implements Cloneable {
//
// @Id
// public long id;
// @Index
// @Nullable
// public String type;
// public String text;
// @Nullable
// @Index
// public String permalink;
// @Nullable
// public String media;
// @Index
// public String websitePageSlug;
// public long favoritesTimestamp; // Favorites date, if not favorite: 0L
//
// public Anecdote(String text, String permalink) {
// this(MediaType.TEXT, text, permalink, null);
// }
//
// public Anecdote(@Nullable String type, String text, @Nullable String permalink, @Nullable String media) {
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// }
//
// @Generated(1799107445)
// @Internal
// /** This constructor was generated by ObjectBox and may change any time. */
// public Anecdote(long id, String type, String text, String permalink, String media, String websitePageSlug,
// long favoritesTimestamp) {
// this.id = id;
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// this.websitePageSlug = websitePageSlug;
// this.favoritesTimestamp = favoritesTimestamp;
// }
//
// @Generated(443678178)
// public Anecdote() {
// }
//
// /**
// * Return the text without html
// *
// * @return plain text text
// */
// public String getPlainTextContent() {
// return Jsoup.parse(text.replace("<br>", "#lb#")).text().replace("#lb#", System.getProperty("line.separator"));
// }
//
// /**
// * Get the share string of the
// * @param context app context
// * @return the shareable string description of this anecdote
// */
// public String getShareString(Context context){
// String copyString = getPlainTextContent();
//
// if(!TextUtils.isEmpty(permalink)){
// copyString += " " + permalink;
// }
//
// copyString += " " + context.getString(R.string.app_share_credits);
//
// return copyString;
// }
//
// /**
// * Return if the anecdote has been favorited by the user, in the current session (meaning it is not stored).
// */
// public boolean isFavorite(){
// return favoritesTimestamp != 0L;
// }
//
// @Override
// public Anecdote clone() throws CloneNotSupportedException {
// Object o = null;
// try {
// o = super.clone();
// } catch(CloneNotSupportedException cnse) {
// cnse.printStackTrace(System.err);
// }
// return (Anecdote) o;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Anecdote anecdote = (Anecdote) o;
//
// if (type != null ? !type.equals(anecdote.type) : anecdote.type != null) return false;
// if (text != null ? !text.equals(anecdote.text) : anecdote.text != null) return false;
// //noinspection SimplifiableIfStatement
// if (permalink != null ? !permalink.equals(anecdote.permalink) : anecdote.permalink != null) return false;
// return media != null ? media.equals(anecdote.media) : anecdote.media == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = type != null ? type.hashCode() : 0;
// result = 31 * result + (text != null ? text.hashCode() : 0);
// result = 31 * result + (permalink != null ? permalink.hashCode() : 0);
// result = 31 * result + (media != null ? media.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Anecdote text='" + text + "'\', permalink='" + permalink + '\'';
// }
// }
| import android.graphics.Color;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.gresse.hugo.anecdote.R;
import io.gresse.hugo.anecdote.anecdote.model.Anecdote; | package io.gresse.hugo.anecdote.anecdote.list;
/***************************
* ViewHolder
***************************/
public class MixedBaseViewHolder
extends AnecdoteAdapter.BaseAnecdoteViewHolder
implements View.OnClickListener {
protected final AdapterListener mAdapterListener;
protected final MixedContentAdapter mAdapter;
private final int mTextSize;
private final boolean mRowStriping;
private final int mRowBackground;
private final int mRowStripingBackground;
private View mItemView;
protected String mWebsiteName = ""; | // Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/model/Anecdote.java
// @Entity
// public class Anecdote implements Cloneable {
//
// @Id
// public long id;
// @Index
// @Nullable
// public String type;
// public String text;
// @Nullable
// @Index
// public String permalink;
// @Nullable
// public String media;
// @Index
// public String websitePageSlug;
// public long favoritesTimestamp; // Favorites date, if not favorite: 0L
//
// public Anecdote(String text, String permalink) {
// this(MediaType.TEXT, text, permalink, null);
// }
//
// public Anecdote(@Nullable String type, String text, @Nullable String permalink, @Nullable String media) {
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// }
//
// @Generated(1799107445)
// @Internal
// /** This constructor was generated by ObjectBox and may change any time. */
// public Anecdote(long id, String type, String text, String permalink, String media, String websitePageSlug,
// long favoritesTimestamp) {
// this.id = id;
// this.type = type;
// this.text = text;
// this.permalink = permalink;
// this.media = media;
// this.websitePageSlug = websitePageSlug;
// this.favoritesTimestamp = favoritesTimestamp;
// }
//
// @Generated(443678178)
// public Anecdote() {
// }
//
// /**
// * Return the text without html
// *
// * @return plain text text
// */
// public String getPlainTextContent() {
// return Jsoup.parse(text.replace("<br>", "#lb#")).text().replace("#lb#", System.getProperty("line.separator"));
// }
//
// /**
// * Get the share string of the
// * @param context app context
// * @return the shareable string description of this anecdote
// */
// public String getShareString(Context context){
// String copyString = getPlainTextContent();
//
// if(!TextUtils.isEmpty(permalink)){
// copyString += " " + permalink;
// }
//
// copyString += " " + context.getString(R.string.app_share_credits);
//
// return copyString;
// }
//
// /**
// * Return if the anecdote has been favorited by the user, in the current session (meaning it is not stored).
// */
// public boolean isFavorite(){
// return favoritesTimestamp != 0L;
// }
//
// @Override
// public Anecdote clone() throws CloneNotSupportedException {
// Object o = null;
// try {
// o = super.clone();
// } catch(CloneNotSupportedException cnse) {
// cnse.printStackTrace(System.err);
// }
// return (Anecdote) o;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Anecdote anecdote = (Anecdote) o;
//
// if (type != null ? !type.equals(anecdote.type) : anecdote.type != null) return false;
// if (text != null ? !text.equals(anecdote.text) : anecdote.text != null) return false;
// //noinspection SimplifiableIfStatement
// if (permalink != null ? !permalink.equals(anecdote.permalink) : anecdote.permalink != null) return false;
// return media != null ? media.equals(anecdote.media) : anecdote.media == null;
//
// }
//
// @Override
// public int hashCode() {
// int result = type != null ? type.hashCode() : 0;
// result = 31 * result + (text != null ? text.hashCode() : 0);
// result = 31 * result + (permalink != null ? permalink.hashCode() : 0);
// result = 31 * result + (media != null ? media.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Anecdote text='" + text + "'\', permalink='" + permalink + '\'';
// }
// }
// Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/list/MixedBaseViewHolder.java
import android.graphics.Color;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.gresse.hugo.anecdote.R;
import io.gresse.hugo.anecdote.anecdote.model.Anecdote;
package io.gresse.hugo.anecdote.anecdote.list;
/***************************
* ViewHolder
***************************/
public class MixedBaseViewHolder
extends AnecdoteAdapter.BaseAnecdoteViewHolder
implements View.OnClickListener {
protected final AdapterListener mAdapterListener;
protected final MixedContentAdapter mAdapter;
private final int mTextSize;
private final boolean mRowStriping;
private final int mRowBackground;
private final int mRowStripingBackground;
private View mItemView;
protected String mWebsiteName = ""; | protected Anecdote mCurrentAnecdote; |
HugoGresse/Anecdote | app/src/main/java/io/gresse/hugo/anecdote/api/event/OnRemoteWebsiteResponseEvent.java | // Path: app/src/main/java/io/gresse/hugo/anecdote/api/model/Website.java
// public class Website {
//
// public static final String SOURCE_LOCAL = "local";
// public static final String SOURCE_REMOTE = "remote";
// public static final String SOURCE_CALCULATED = "calc";
//
// public int version;
// public String slug;
// public String name;
// public int color;
// public int like;
// public String source;
// public String userAgent;
//
// public List<WebsitePage> pages;
//
// public Website() {
// this(null, SOURCE_LOCAL);
// }
//
// public Website(String name, String source) {
// this.pages = new ArrayList<>();
// this.source = source;
// this.name = name;
// }
//
// /**
// * Validate this object by preventing any crash when using it
// */
// public void validateData() {
// if (TextUtils.isEmpty(name)) {
// name = Long.toHexString(Double.doubleToLongBits(Math.random()));
// }
//
// for(WebsitePage websitePage : pages){
// websitePage.validate();
// }
//
// if (TextUtils.isEmpty(slug)) {
// if (source.equals(SOURCE_REMOTE)) {
// slug = "api-" + name;
// } else if (source.equals(SOURCE_CALCULATED)) {
// slug = "calc-" + name;
// } else {
// slug = "local-" + name;
// }
// }
// }
//
// /**
// * Check if the version missmatch between the two object
// *
// * @param website the new website
// * @return true if up to date, false otherweise
// */
// public boolean isUpToDate(Website website) {
// return website.version <= version;
// }
//
// /**
// * Check if the user can edit this website manually or not
// *
// * @return true if editable
// */
// public boolean isEditable() {
// return source.equals(SOURCE_LOCAL);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Website website = (Website) o;
//
// if (!slug.equals(website.slug)) return false;
// return source.equals(website.source);
//
// }
//
// @Override
// public int hashCode() {
// int result = slug.hashCode();
// result = 31 * result + source.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "Website{" +
// "version=" + version +
// ", slug='" + slug + '\'' +
// ", name='" + name + '\'' +
// ", color=" + color +
// ", like=" + like +
// ", source='" + source + '\'' +
// ", userAgent='" + userAgent + '\'' +
// ", pages=" + pages +
// '}';
// }
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/event/Event.java
// public interface Event {
// }
| import java.util.List;
import io.gresse.hugo.anecdote.api.model.Website;
import io.gresse.hugo.anecdote.event.Event; | package io.gresse.hugo.anecdote.api.event;
/**
* When remote websites has been downloaded. This should be fired after {@link LoadRemoteWebsiteEvent}.
* <p/>
* Created by Hugo Gresse on 26/04/16.
*/
public class OnRemoteWebsiteResponseEvent implements Event {
public boolean isSuccessful; | // Path: app/src/main/java/io/gresse/hugo/anecdote/api/model/Website.java
// public class Website {
//
// public static final String SOURCE_LOCAL = "local";
// public static final String SOURCE_REMOTE = "remote";
// public static final String SOURCE_CALCULATED = "calc";
//
// public int version;
// public String slug;
// public String name;
// public int color;
// public int like;
// public String source;
// public String userAgent;
//
// public List<WebsitePage> pages;
//
// public Website() {
// this(null, SOURCE_LOCAL);
// }
//
// public Website(String name, String source) {
// this.pages = new ArrayList<>();
// this.source = source;
// this.name = name;
// }
//
// /**
// * Validate this object by preventing any crash when using it
// */
// public void validateData() {
// if (TextUtils.isEmpty(name)) {
// name = Long.toHexString(Double.doubleToLongBits(Math.random()));
// }
//
// for(WebsitePage websitePage : pages){
// websitePage.validate();
// }
//
// if (TextUtils.isEmpty(slug)) {
// if (source.equals(SOURCE_REMOTE)) {
// slug = "api-" + name;
// } else if (source.equals(SOURCE_CALCULATED)) {
// slug = "calc-" + name;
// } else {
// slug = "local-" + name;
// }
// }
// }
//
// /**
// * Check if the version missmatch between the two object
// *
// * @param website the new website
// * @return true if up to date, false otherweise
// */
// public boolean isUpToDate(Website website) {
// return website.version <= version;
// }
//
// /**
// * Check if the user can edit this website manually or not
// *
// * @return true if editable
// */
// public boolean isEditable() {
// return source.equals(SOURCE_LOCAL);
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// Website website = (Website) o;
//
// if (!slug.equals(website.slug)) return false;
// return source.equals(website.source);
//
// }
//
// @Override
// public int hashCode() {
// int result = slug.hashCode();
// result = 31 * result + source.hashCode();
// return result;
// }
//
// @Override
// public String toString() {
// return "Website{" +
// "version=" + version +
// ", slug='" + slug + '\'' +
// ", name='" + name + '\'' +
// ", color=" + color +
// ", like=" + like +
// ", source='" + source + '\'' +
// ", userAgent='" + userAgent + '\'' +
// ", pages=" + pages +
// '}';
// }
// }
//
// Path: app/src/main/java/io/gresse/hugo/anecdote/event/Event.java
// public interface Event {
// }
// Path: app/src/main/java/io/gresse/hugo/anecdote/api/event/OnRemoteWebsiteResponseEvent.java
import java.util.List;
import io.gresse.hugo.anecdote.api.model.Website;
import io.gresse.hugo.anecdote.event.Event;
package io.gresse.hugo.anecdote.api.event;
/**
* When remote websites has been downloaded. This should be fired after {@link LoadRemoteWebsiteEvent}.
* <p/>
* Created by Hugo Gresse on 26/04/16.
*/
public class OnRemoteWebsiteResponseEvent implements Event {
public boolean isSuccessful; | public List<Website> websiteList; |
HugoGresse/Anecdote | app/src/main/java/io/gresse/hugo/anecdote/view/ImageTransitionSet.java | // Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/fullscreen/FullscreenEnterTransitionEndEvent.java
// public class FullscreenEnterTransitionEndEvent implements Event {
// }
| import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.transition.ChangeBounds;
import android.transition.ChangeImageTransform;
import android.transition.ChangeTransform;
import android.transition.Transition;
import android.transition.TransitionSet;
import android.util.AttributeSet;
import org.greenrobot.eventbus.EventBus;
import io.gresse.hugo.anecdote.anecdote.fullscreen.FullscreenEnterTransitionEndEvent; | package io.gresse.hugo.anecdote.view;
/**
* Transition that performs almost exactly like {@link android.transition.AutoTransition}, but has an
* added {@link ChangeImageTransform} to support properly scaling up images.
*
* Source: https://github.com/bherbst/FragmentTransitionSample/blob/master/app/src/main/java/com/example/fragmenttransitions/DetailsTransition.java
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
public class ImageTransitionSet extends TransitionSet implements Transition.TransitionListener {
public ImageTransitionSet() {
init();
}
/**
* This constructor allows us to use this transition in XML
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ImageTransitionSet(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void init() {
setOrdering(ORDERING_TOGETHER);
addTransition(new ChangeBounds()).
addTransition(new ChangeTransform()).
addTransition(new ChangeImageTransform());
super.addListener(this);
}
/***************************
* Implements Transition.TransitionListener
***************************/
@Override
public void onTransitionStart(Transition transition) {
// Nothing special here
}
@Override
public void onTransitionEnd(Transition transition) { | // Path: app/src/main/java/io/gresse/hugo/anecdote/anecdote/fullscreen/FullscreenEnterTransitionEndEvent.java
// public class FullscreenEnterTransitionEndEvent implements Event {
// }
// Path: app/src/main/java/io/gresse/hugo/anecdote/view/ImageTransitionSet.java
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.transition.ChangeBounds;
import android.transition.ChangeImageTransform;
import android.transition.ChangeTransform;
import android.transition.Transition;
import android.transition.TransitionSet;
import android.util.AttributeSet;
import org.greenrobot.eventbus.EventBus;
import io.gresse.hugo.anecdote.anecdote.fullscreen.FullscreenEnterTransitionEndEvent;
package io.gresse.hugo.anecdote.view;
/**
* Transition that performs almost exactly like {@link android.transition.AutoTransition}, but has an
* added {@link ChangeImageTransform} to support properly scaling up images.
*
* Source: https://github.com/bherbst/FragmentTransitionSample/blob/master/app/src/main/java/com/example/fragmenttransitions/DetailsTransition.java
*/
@TargetApi(Build.VERSION_CODES.KITKAT)
public class ImageTransitionSet extends TransitionSet implements Transition.TransitionListener {
public ImageTransitionSet() {
init();
}
/**
* This constructor allows us to use this transition in XML
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ImageTransitionSet(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void init() {
setOrdering(ORDERING_TOGETHER);
addTransition(new ChangeBounds()).
addTransition(new ChangeTransform()).
addTransition(new ChangeImageTransform());
super.addListener(this);
}
/***************************
* Implements Transition.TransitionListener
***************************/
@Override
public void onTransitionStart(Transition transition) {
// Nothing special here
}
@Override
public void onTransitionEnd(Transition transition) { | EventBus.getDefault().post(new FullscreenEnterTransitionEndEvent()); |
salk31/RedQueryBuilder | redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/expression/SuggestEditorWidget.java | // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/engine/Session.java
// public class Session {
//
// private static IdentifierEscaper identifierEscaper = new IdentifierEscaper() {
// @Override
// public String quote(String id) {
// return "\"" + id + "\"";
// }
// };
//
// public void setIdentifierEscaper(IdentifierEscaper p) {
// identifierEscaper = p;
// }
//
// /**
// * Add double quotes around an identifier if required.
// *
// * @param s the identifier
// * @return the quoted identifier
// */
// public static String quoteIdentifier(String s) {
// return identifierEscaper.quote(s);
// }
//
// // XXX need commandBuilder and select?
// private CommandBuilder commandBuilder;
//
// private Select select;
//
// private Configuration config;
//
// private final ValueRegistry valueRegistry = new ValueRegistry();
//
// private final Database database;
//
// private final HandlerManager msgbus;
//
//
// // XXX 00 remove one of these constructors
// public Session(Configuration config2) {
// this(config2.getDatabase());
// this.config = config2;
// }
//
// @Deprecated
// public Session(Database database2) {
// database = database2;
// msgbus = new HandlerManager(this);
// }
//
// public Configuration getConfig() {
// return config;
// }
//
// public CommandBuilder getCommandBuilder() {
// return commandBuilder;
// }
//
// public void setCommandBuilder(CommandBuilder p) {
// commandBuilder = p;
// }
//
// public Database getDatabase() {
// return database;
// }
//
//
// public HandlerManager getMsgBus() {
// return msgbus;
// }
//
//
//
// public void setSelect(Select p) {
// select = p;
// }
//
// public Column resolveColumn(String alias, String columnName) {
// return select.resolveColumn(alias, columnName);
// }
//
// public ObjectArray<TableFilter> getFilters() {
// return select.getFilters();
// }
//
// public TableFilter getTableFilter(Table t) {
// for (TableFilter tf : select.getFilters()) {
// if (tf.getTable().equals(t)) {
// return tf;
// }
// }
// return null;
// }
//
// public TableFilter createTableFilter(Table t) {
// TableFilter tf = new TableFilter(this, t, TableFilter.newAlias(), select);
// select.addTableFilter(tf, true); // XXX really is true?
// return tf;
// }
//
// public TableFilter getOrCreateTableFilter(Table t) {
// TableFilter tf = getTableFilter(t);
// if (tf == null) {
// tf = createTableFilter(t);
// }
// return tf;
// }
//
// //public Table getTable(String alias) {
// // return select.getTable(alias);
// //}
//
// public Table getRootTable() {
// // XXX maybe if no table then grab default?
// // or should select always have one table?
// // or ui shouldn't offer condition button till table?
// return select.getFilters().get(0).getTable();
// }
//
// public ValueRegistry getValueRegistry() {
// return valueRegistry;
// }
// }
| import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.SuggestBox.DefaultSuggestionDisplay;
import com.google.gwt.user.client.ui.SuggestOracle;
import com.redspr.redquerybuilder.core.client.engine.Session;
import com.redspr.redquerybuilder.core.shared.meta.Column;
import com.redspr.redquerybuilder.core.shared.meta.SuggestRequest; |
@Override
public void onSuccess(Response result) {
callback.onSuggestionsReady(request, result);
}
});
}
@Override
public void requestSuggestions(final Request request,
final Callback callback) {
SuggestRequest sr = create(request);
session.getConfig().fireSuggest(sr, new AsyncCallback<Response>() {
@Override
public void onFailure(Throwable caught) {
// XXX
}
@Override
public void onSuccess(Response result) {
callback.onSuggestionsReady(request, result);
}
});
}
}
private final String tableName;
private final String columnName;
private final String columnType; | // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/engine/Session.java
// public class Session {
//
// private static IdentifierEscaper identifierEscaper = new IdentifierEscaper() {
// @Override
// public String quote(String id) {
// return "\"" + id + "\"";
// }
// };
//
// public void setIdentifierEscaper(IdentifierEscaper p) {
// identifierEscaper = p;
// }
//
// /**
// * Add double quotes around an identifier if required.
// *
// * @param s the identifier
// * @return the quoted identifier
// */
// public static String quoteIdentifier(String s) {
// return identifierEscaper.quote(s);
// }
//
// // XXX need commandBuilder and select?
// private CommandBuilder commandBuilder;
//
// private Select select;
//
// private Configuration config;
//
// private final ValueRegistry valueRegistry = new ValueRegistry();
//
// private final Database database;
//
// private final HandlerManager msgbus;
//
//
// // XXX 00 remove one of these constructors
// public Session(Configuration config2) {
// this(config2.getDatabase());
// this.config = config2;
// }
//
// @Deprecated
// public Session(Database database2) {
// database = database2;
// msgbus = new HandlerManager(this);
// }
//
// public Configuration getConfig() {
// return config;
// }
//
// public CommandBuilder getCommandBuilder() {
// return commandBuilder;
// }
//
// public void setCommandBuilder(CommandBuilder p) {
// commandBuilder = p;
// }
//
// public Database getDatabase() {
// return database;
// }
//
//
// public HandlerManager getMsgBus() {
// return msgbus;
// }
//
//
//
// public void setSelect(Select p) {
// select = p;
// }
//
// public Column resolveColumn(String alias, String columnName) {
// return select.resolveColumn(alias, columnName);
// }
//
// public ObjectArray<TableFilter> getFilters() {
// return select.getFilters();
// }
//
// public TableFilter getTableFilter(Table t) {
// for (TableFilter tf : select.getFilters()) {
// if (tf.getTable().equals(t)) {
// return tf;
// }
// }
// return null;
// }
//
// public TableFilter createTableFilter(Table t) {
// TableFilter tf = new TableFilter(this, t, TableFilter.newAlias(), select);
// select.addTableFilter(tf, true); // XXX really is true?
// return tf;
// }
//
// public TableFilter getOrCreateTableFilter(Table t) {
// TableFilter tf = getTableFilter(t);
// if (tf == null) {
// tf = createTableFilter(t);
// }
// return tf;
// }
//
// //public Table getTable(String alias) {
// // return select.getTable(alias);
// //}
//
// public Table getRootTable() {
// // XXX maybe if no table then grab default?
// // or should select always have one table?
// // or ui shouldn't offer condition button till table?
// return select.getFilters().get(0).getTable();
// }
//
// public ValueRegistry getValueRegistry() {
// return valueRegistry;
// }
// }
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/expression/SuggestEditorWidget.java
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.SuggestBox.DefaultSuggestionDisplay;
import com.google.gwt.user.client.ui.SuggestOracle;
import com.redspr.redquerybuilder.core.client.engine.Session;
import com.redspr.redquerybuilder.core.shared.meta.Column;
import com.redspr.redquerybuilder.core.shared.meta.SuggestRequest;
@Override
public void onSuccess(Response result) {
callback.onSuggestionsReady(request, result);
}
});
}
@Override
public void requestSuggestions(final Request request,
final Callback callback) {
SuggestRequest sr = create(request);
session.getConfig().fireSuggest(sr, new AsyncCallback<Response>() {
@Override
public void onFailure(Throwable caught) {
// XXX
}
@Override
public void onSuccess(Response result) {
callback.onSuggestionsReady(request, result);
}
});
}
}
private final String tableName;
private final String columnName;
private final String columnType; | private final Session session; |
salk31/RedQueryBuilder | redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/Configuration.java | // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/shared/meta/EnumerateRequest.java
// public class EnumerateRequest {
// private String tableName;
//
// private String columnName;
//
// private String columnType;
//
// public String getTableName() {
// return tableName;
// }
//
// public void setTableName(String p) {
// this.tableName = p;
// }
//
// public String getColumnName() {
// return columnName;
// }
//
// public void setColumnName(String p) {
// this.columnName = p;
// }
//
// public String getColumnTypeName() {
// return columnType;
// }
//
// public void setColumnTypeName(String p) {
// this.columnType = p;
// }
//
// }
| import java.util.List;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.SuggestOracle.Response;
import com.redspr.redquerybuilder.core.client.table.TableFilter;
import com.redspr.redquerybuilder.core.client.util.ObjectArray;
import com.redspr.redquerybuilder.core.shared.meta.Database;
import com.redspr.redquerybuilder.core.shared.meta.EnumerateRequest;
import com.redspr.redquerybuilder.core.shared.meta.SuggestRequest; | package com.redspr.redquerybuilder.core.client;
/**
* Extend this class to integrate with RedQueryBuilder.
*/
public class Configuration {
private Database database = new Database();
private final From from = new From();
| // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/shared/meta/EnumerateRequest.java
// public class EnumerateRequest {
// private String tableName;
//
// private String columnName;
//
// private String columnType;
//
// public String getTableName() {
// return tableName;
// }
//
// public void setTableName(String p) {
// this.tableName = p;
// }
//
// public String getColumnName() {
// return columnName;
// }
//
// public void setColumnName(String p) {
// this.columnName = p;
// }
//
// public String getColumnTypeName() {
// return columnType;
// }
//
// public void setColumnTypeName(String p) {
// this.columnType = p;
// }
//
// }
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/Configuration.java
import java.util.List;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.SuggestOracle.Response;
import com.redspr.redquerybuilder.core.client.table.TableFilter;
import com.redspr.redquerybuilder.core.client.util.ObjectArray;
import com.redspr.redquerybuilder.core.shared.meta.Database;
import com.redspr.redquerybuilder.core.shared.meta.EnumerateRequest;
import com.redspr.redquerybuilder.core.shared.meta.SuggestRequest;
package com.redspr.redquerybuilder.core.client;
/**
* Extend this class to integrate with RedQueryBuilder.
*/
public class Configuration {
private Database database = new Database();
private final From from = new From();
| public void fireEnumerate(EnumerateRequest request, AsyncCallback<Response> callback) { |
salk31/RedQueryBuilder | redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/command/Message.java | // Path: redquerybuilder-core/src/main/java/java/sql/SQLException.java
// public class SQLException extends Exception {
// public SQLException(String m) {
// super(m);
// }
//
// public SQLException(String m, Throwable t) {
// super(m, t);
// }
//
//
// public int getErrorCode() {
// return 0;
// }
// }
| import java.sql.SQLException; | /*
* Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License,
* Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*
* Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888
* Support for the operator "&&" as an alias for SPATIAL_INTERSECTS
*/
package com.redspr.redquerybuilder.core.client.command;
public final class Message {
private Message() {
}
| // Path: redquerybuilder-core/src/main/java/java/sql/SQLException.java
// public class SQLException extends Exception {
// public SQLException(String m) {
// super(m);
// }
//
// public SQLException(String m, Throwable t) {
// super(m, t);
// }
//
//
// public int getErrorCode() {
// return 0;
// }
// }
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/command/Message.java
import java.sql.SQLException;
/*
* Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License,
* Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*
* Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888
* Support for the operator "&&" as an alias for SPATIAL_INTERSECTS
*/
package com.redspr.redquerybuilder.core.client.command;
public final class Message {
private Message() {
}
| public static SQLException addSQL(Exception e, String sql) { |
salk31/RedQueryBuilder | redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/expression/Wildcard.java | // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/engine/Session.java
// public class Session {
//
// private static IdentifierEscaper identifierEscaper = new IdentifierEscaper() {
// @Override
// public String quote(String id) {
// return "\"" + id + "\"";
// }
// };
//
// public void setIdentifierEscaper(IdentifierEscaper p) {
// identifierEscaper = p;
// }
//
// /**
// * Add double quotes around an identifier if required.
// *
// * @param s the identifier
// * @return the quoted identifier
// */
// public static String quoteIdentifier(String s) {
// return identifierEscaper.quote(s);
// }
//
// // XXX need commandBuilder and select?
// private CommandBuilder commandBuilder;
//
// private Select select;
//
// private Configuration config;
//
// private final ValueRegistry valueRegistry = new ValueRegistry();
//
// private final Database database;
//
// private final HandlerManager msgbus;
//
//
// // XXX 00 remove one of these constructors
// public Session(Configuration config2) {
// this(config2.getDatabase());
// this.config = config2;
// }
//
// @Deprecated
// public Session(Database database2) {
// database = database2;
// msgbus = new HandlerManager(this);
// }
//
// public Configuration getConfig() {
// return config;
// }
//
// public CommandBuilder getCommandBuilder() {
// return commandBuilder;
// }
//
// public void setCommandBuilder(CommandBuilder p) {
// commandBuilder = p;
// }
//
// public Database getDatabase() {
// return database;
// }
//
//
// public HandlerManager getMsgBus() {
// return msgbus;
// }
//
//
//
// public void setSelect(Select p) {
// select = p;
// }
//
// public Column resolveColumn(String alias, String columnName) {
// return select.resolveColumn(alias, columnName);
// }
//
// public ObjectArray<TableFilter> getFilters() {
// return select.getFilters();
// }
//
// public TableFilter getTableFilter(Table t) {
// for (TableFilter tf : select.getFilters()) {
// if (tf.getTable().equals(t)) {
// return tf;
// }
// }
// return null;
// }
//
// public TableFilter createTableFilter(Table t) {
// TableFilter tf = new TableFilter(this, t, TableFilter.newAlias(), select);
// select.addTableFilter(tf, true); // XXX really is true?
// return tf;
// }
//
// public TableFilter getOrCreateTableFilter(Table t) {
// TableFilter tf = getTableFilter(t);
// if (tf == null) {
// tf = createTableFilter(t);
// }
// return tf;
// }
//
// //public Table getTable(String alias) {
// // return select.getTable(alias);
// //}
//
// public Table getRootTable() {
// // XXX maybe if no table then grab default?
// // or should select always have one table?
// // or ui shouldn't offer condition button till table?
// return select.getFilters().get(0).getTable();
// }
//
// public ValueRegistry getValueRegistry() {
// return valueRegistry;
// }
// }
| import java.util.List;
import com.redspr.redquerybuilder.core.client.engine.Session; | package com.redspr.redquerybuilder.core.client.expression;
public class Wildcard extends Expression {
private final String table;
| // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/engine/Session.java
// public class Session {
//
// private static IdentifierEscaper identifierEscaper = new IdentifierEscaper() {
// @Override
// public String quote(String id) {
// return "\"" + id + "\"";
// }
// };
//
// public void setIdentifierEscaper(IdentifierEscaper p) {
// identifierEscaper = p;
// }
//
// /**
// * Add double quotes around an identifier if required.
// *
// * @param s the identifier
// * @return the quoted identifier
// */
// public static String quoteIdentifier(String s) {
// return identifierEscaper.quote(s);
// }
//
// // XXX need commandBuilder and select?
// private CommandBuilder commandBuilder;
//
// private Select select;
//
// private Configuration config;
//
// private final ValueRegistry valueRegistry = new ValueRegistry();
//
// private final Database database;
//
// private final HandlerManager msgbus;
//
//
// // XXX 00 remove one of these constructors
// public Session(Configuration config2) {
// this(config2.getDatabase());
// this.config = config2;
// }
//
// @Deprecated
// public Session(Database database2) {
// database = database2;
// msgbus = new HandlerManager(this);
// }
//
// public Configuration getConfig() {
// return config;
// }
//
// public CommandBuilder getCommandBuilder() {
// return commandBuilder;
// }
//
// public void setCommandBuilder(CommandBuilder p) {
// commandBuilder = p;
// }
//
// public Database getDatabase() {
// return database;
// }
//
//
// public HandlerManager getMsgBus() {
// return msgbus;
// }
//
//
//
// public void setSelect(Select p) {
// select = p;
// }
//
// public Column resolveColumn(String alias, String columnName) {
// return select.resolveColumn(alias, columnName);
// }
//
// public ObjectArray<TableFilter> getFilters() {
// return select.getFilters();
// }
//
// public TableFilter getTableFilter(Table t) {
// for (TableFilter tf : select.getFilters()) {
// if (tf.getTable().equals(t)) {
// return tf;
// }
// }
// return null;
// }
//
// public TableFilter createTableFilter(Table t) {
// TableFilter tf = new TableFilter(this, t, TableFilter.newAlias(), select);
// select.addTableFilter(tf, true); // XXX really is true?
// return tf;
// }
//
// public TableFilter getOrCreateTableFilter(Table t) {
// TableFilter tf = getTableFilter(t);
// if (tf == null) {
// tf = createTableFilter(t);
// }
// return tf;
// }
//
// //public Table getTable(String alias) {
// // return select.getTable(alias);
// //}
//
// public Table getRootTable() {
// // XXX maybe if no table then grab default?
// // or should select always have one table?
// // or ui shouldn't offer condition button till table?
// return select.getFilters().get(0).getTable();
// }
//
// public ValueRegistry getValueRegistry() {
// return valueRegistry;
// }
// }
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/expression/Wildcard.java
import java.util.List;
import com.redspr.redquerybuilder.core.client.engine.Session;
package com.redspr.redquerybuilder.core.client.expression;
public class Wildcard extends Expression {
private final String table;
| public Wildcard(Session session, String schema, String table) { |
salk31/RedQueryBuilder | redquerybuilder-js/src/main/java/com/redspr/redquerybuilder/js/client/JsConfiguration.java | // Path: redquerybuilder-js/src/main/java/com/redspr/redquerybuilder/js/client/conf/JsFrom.java
// public class JsFrom extends JavaScriptObject {
// protected JsFrom() {
// }
//
// public final native boolean isVisible() /*-{ return this.visible; }-*/;
// }
| import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayMixed;
import com.redspr.redquerybuilder.core.client.table.TableFilter;
import com.redspr.redquerybuilder.core.client.util.ObjectArray;
import com.redspr.redquerybuilder.js.client.conf.JsFrom; | this.defaultSuggest(arg, function response(s) {
jsCallback.@com.redspr.redquerybuilder.js.client.JsCallback::response(Lcom/google/gwt/core/client/JavaScriptObject;)(s);
});
}
}-*/;
public final native void fireSuggest(String tableName, String columnName, String columnTypeName, String query,
int limit, JsCallback jsCallback) /*-{
var arg = {tableName: tableName,
columnName: columnName,
columnTypeName : columnTypeName,
query: query,
limit:limit};
this.suggest(arg, function response(s) {
jsCallback.@com.redspr.redquerybuilder.js.client.JsCallback::response(Lcom/google/gwt/core/client/JavaScriptObject;)(s);
});
}-*/;
public final native void fireEnumerate(String tableName, String columnName, String columnTypeName,
JsCallback jsCallback) /*-{
if (this.enumerate) {
var arg = {tableName: tableName,
columnName: columnName,
columnTypeName : columnTypeName};
this.enumerate(arg, function response(s) {
jsCallback.@com.redspr.redquerybuilder.js.client.JsCallback::response(Lcom/google/gwt/core/client/JavaScriptObject;)(s);
});
}
}-*/;
| // Path: redquerybuilder-js/src/main/java/com/redspr/redquerybuilder/js/client/conf/JsFrom.java
// public class JsFrom extends JavaScriptObject {
// protected JsFrom() {
// }
//
// public final native boolean isVisible() /*-{ return this.visible; }-*/;
// }
// Path: redquerybuilder-js/src/main/java/com/redspr/redquerybuilder/js/client/JsConfiguration.java
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayMixed;
import com.redspr.redquerybuilder.core.client.table.TableFilter;
import com.redspr.redquerybuilder.core.client.util.ObjectArray;
import com.redspr.redquerybuilder.js.client.conf.JsFrom;
this.defaultSuggest(arg, function response(s) {
jsCallback.@com.redspr.redquerybuilder.js.client.JsCallback::response(Lcom/google/gwt/core/client/JavaScriptObject;)(s);
});
}
}-*/;
public final native void fireSuggest(String tableName, String columnName, String columnTypeName, String query,
int limit, JsCallback jsCallback) /*-{
var arg = {tableName: tableName,
columnName: columnName,
columnTypeName : columnTypeName,
query: query,
limit:limit};
this.suggest(arg, function response(s) {
jsCallback.@com.redspr.redquerybuilder.js.client.JsCallback::response(Lcom/google/gwt/core/client/JavaScriptObject;)(s);
});
}-*/;
public final native void fireEnumerate(String tableName, String columnName, String columnTypeName,
JsCallback jsCallback) /*-{
if (this.enumerate) {
var arg = {tableName: tableName,
columnName: columnName,
columnTypeName : columnTypeName};
this.enumerate(arg, function response(s) {
jsCallback.@com.redspr.redquerybuilder.js.client.JsCallback::response(Lcom/google/gwt/core/client/JavaScriptObject;)(s);
});
}
}-*/;
| public final native JsFrom getFrom() /*-{ |
salk31/RedQueryBuilder | redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/expression/ConditionAndOr.java | // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/engine/Session.java
// public class Session {
//
// private static IdentifierEscaper identifierEscaper = new IdentifierEscaper() {
// @Override
// public String quote(String id) {
// return "\"" + id + "\"";
// }
// };
//
// public void setIdentifierEscaper(IdentifierEscaper p) {
// identifierEscaper = p;
// }
//
// /**
// * Add double quotes around an identifier if required.
// *
// * @param s the identifier
// * @return the quoted identifier
// */
// public static String quoteIdentifier(String s) {
// return identifierEscaper.quote(s);
// }
//
// // XXX need commandBuilder and select?
// private CommandBuilder commandBuilder;
//
// private Select select;
//
// private Configuration config;
//
// private final ValueRegistry valueRegistry = new ValueRegistry();
//
// private final Database database;
//
// private final HandlerManager msgbus;
//
//
// // XXX 00 remove one of these constructors
// public Session(Configuration config2) {
// this(config2.getDatabase());
// this.config = config2;
// }
//
// @Deprecated
// public Session(Database database2) {
// database = database2;
// msgbus = new HandlerManager(this);
// }
//
// public Configuration getConfig() {
// return config;
// }
//
// public CommandBuilder getCommandBuilder() {
// return commandBuilder;
// }
//
// public void setCommandBuilder(CommandBuilder p) {
// commandBuilder = p;
// }
//
// public Database getDatabase() {
// return database;
// }
//
//
// public HandlerManager getMsgBus() {
// return msgbus;
// }
//
//
//
// public void setSelect(Select p) {
// select = p;
// }
//
// public Column resolveColumn(String alias, String columnName) {
// return select.resolveColumn(alias, columnName);
// }
//
// public ObjectArray<TableFilter> getFilters() {
// return select.getFilters();
// }
//
// public TableFilter getTableFilter(Table t) {
// for (TableFilter tf : select.getFilters()) {
// if (tf.getTable().equals(t)) {
// return tf;
// }
// }
// return null;
// }
//
// public TableFilter createTableFilter(Table t) {
// TableFilter tf = new TableFilter(this, t, TableFilter.newAlias(), select);
// select.addTableFilter(tf, true); // XXX really is true?
// return tf;
// }
//
// public TableFilter getOrCreateTableFilter(Table t) {
// TableFilter tf = getTableFilter(t);
// if (tf == null) {
// tf = createTableFilter(t);
// }
// return tf;
// }
//
// //public Table getTable(String alias) {
// // return select.getTable(alias);
// //}
//
// public Table getRootTable() {
// // XXX maybe if no table then grab default?
// // or should select always have one table?
// // or ui shouldn't offer condition button till table?
// return select.getFilters().get(0).getTable();
// }
//
// public ValueRegistry getValueRegistry() {
// return valueRegistry;
// }
// }
| import java.util.List;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;
import com.redspr.redquerybuilder.core.client.BaseSqlWidget;
import com.redspr.redquerybuilder.core.client.Visitor;
import com.redspr.redquerybuilder.core.client.engine.Session;
import com.redspr.redquerybuilder.core.client.util.XWidget; | package com.redspr.redquerybuilder.core.client.expression;
/**
* An 'and' or 'or' condition as in WHERE ID=1 AND NAME=?
*/
public class ConditionAndOr extends Condition {
interface MyUiBinder extends UiBinder<Widget, ConditionAndOr> {
}
private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);
@UiField
XWidget<Expression> left;
@UiField
XWidget<Expression> right;
@UiField
ListBox op;
/**
* The AND condition type as in ID=1 AND NAME='Hello'.
*/
public static final int AND = 0;
/**
* The OR condition type as in ID=1 OR NAME='Hello'.
*/
public static final int OR = 1;
private int andOrType;
| // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/engine/Session.java
// public class Session {
//
// private static IdentifierEscaper identifierEscaper = new IdentifierEscaper() {
// @Override
// public String quote(String id) {
// return "\"" + id + "\"";
// }
// };
//
// public void setIdentifierEscaper(IdentifierEscaper p) {
// identifierEscaper = p;
// }
//
// /**
// * Add double quotes around an identifier if required.
// *
// * @param s the identifier
// * @return the quoted identifier
// */
// public static String quoteIdentifier(String s) {
// return identifierEscaper.quote(s);
// }
//
// // XXX need commandBuilder and select?
// private CommandBuilder commandBuilder;
//
// private Select select;
//
// private Configuration config;
//
// private final ValueRegistry valueRegistry = new ValueRegistry();
//
// private final Database database;
//
// private final HandlerManager msgbus;
//
//
// // XXX 00 remove one of these constructors
// public Session(Configuration config2) {
// this(config2.getDatabase());
// this.config = config2;
// }
//
// @Deprecated
// public Session(Database database2) {
// database = database2;
// msgbus = new HandlerManager(this);
// }
//
// public Configuration getConfig() {
// return config;
// }
//
// public CommandBuilder getCommandBuilder() {
// return commandBuilder;
// }
//
// public void setCommandBuilder(CommandBuilder p) {
// commandBuilder = p;
// }
//
// public Database getDatabase() {
// return database;
// }
//
//
// public HandlerManager getMsgBus() {
// return msgbus;
// }
//
//
//
// public void setSelect(Select p) {
// select = p;
// }
//
// public Column resolveColumn(String alias, String columnName) {
// return select.resolveColumn(alias, columnName);
// }
//
// public ObjectArray<TableFilter> getFilters() {
// return select.getFilters();
// }
//
// public TableFilter getTableFilter(Table t) {
// for (TableFilter tf : select.getFilters()) {
// if (tf.getTable().equals(t)) {
// return tf;
// }
// }
// return null;
// }
//
// public TableFilter createTableFilter(Table t) {
// TableFilter tf = new TableFilter(this, t, TableFilter.newAlias(), select);
// select.addTableFilter(tf, true); // XXX really is true?
// return tf;
// }
//
// public TableFilter getOrCreateTableFilter(Table t) {
// TableFilter tf = getTableFilter(t);
// if (tf == null) {
// tf = createTableFilter(t);
// }
// return tf;
// }
//
// //public Table getTable(String alias) {
// // return select.getTable(alias);
// //}
//
// public Table getRootTable() {
// // XXX maybe if no table then grab default?
// // or should select always have one table?
// // or ui shouldn't offer condition button till table?
// return select.getFilters().get(0).getTable();
// }
//
// public ValueRegistry getValueRegistry() {
// return valueRegistry;
// }
// }
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/expression/ConditionAndOr.java
import java.util.List;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;
import com.redspr.redquerybuilder.core.client.BaseSqlWidget;
import com.redspr.redquerybuilder.core.client.Visitor;
import com.redspr.redquerybuilder.core.client.engine.Session;
import com.redspr.redquerybuilder.core.client.util.XWidget;
package com.redspr.redquerybuilder.core.client.expression;
/**
* An 'and' or 'or' condition as in WHERE ID=1 AND NAME=?
*/
public class ConditionAndOr extends Condition {
interface MyUiBinder extends UiBinder<Widget, ConditionAndOr> {
}
private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);
@UiField
XWidget<Expression> left;
@UiField
XWidget<Expression> right;
@UiField
ListBox op;
/**
* The AND condition type as in ID=1 AND NAME='Hello'.
*/
public static final int AND = 0;
/**
* The OR condition type as in ID=1 OR NAME='Hello'.
*/
public static final int OR = 1;
private int andOrType;
| public ConditionAndOr(Session session, int andOrType2, Expression left2, Expression right2) { |
salk31/RedQueryBuilder | redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/command/dml/SelectUnion.java | // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/engine/Session.java
// public class Session {
//
// private static IdentifierEscaper identifierEscaper = new IdentifierEscaper() {
// @Override
// public String quote(String id) {
// return "\"" + id + "\"";
// }
// };
//
// public void setIdentifierEscaper(IdentifierEscaper p) {
// identifierEscaper = p;
// }
//
// /**
// * Add double quotes around an identifier if required.
// *
// * @param s the identifier
// * @return the quoted identifier
// */
// public static String quoteIdentifier(String s) {
// return identifierEscaper.quote(s);
// }
//
// // XXX need commandBuilder and select?
// private CommandBuilder commandBuilder;
//
// private Select select;
//
// private Configuration config;
//
// private final ValueRegistry valueRegistry = new ValueRegistry();
//
// private final Database database;
//
// private final HandlerManager msgbus;
//
//
// // XXX 00 remove one of these constructors
// public Session(Configuration config2) {
// this(config2.getDatabase());
// this.config = config2;
// }
//
// @Deprecated
// public Session(Database database2) {
// database = database2;
// msgbus = new HandlerManager(this);
// }
//
// public Configuration getConfig() {
// return config;
// }
//
// public CommandBuilder getCommandBuilder() {
// return commandBuilder;
// }
//
// public void setCommandBuilder(CommandBuilder p) {
// commandBuilder = p;
// }
//
// public Database getDatabase() {
// return database;
// }
//
//
// public HandlerManager getMsgBus() {
// return msgbus;
// }
//
//
//
// public void setSelect(Select p) {
// select = p;
// }
//
// public Column resolveColumn(String alias, String columnName) {
// return select.resolveColumn(alias, columnName);
// }
//
// public ObjectArray<TableFilter> getFilters() {
// return select.getFilters();
// }
//
// public TableFilter getTableFilter(Table t) {
// for (TableFilter tf : select.getFilters()) {
// if (tf.getTable().equals(t)) {
// return tf;
// }
// }
// return null;
// }
//
// public TableFilter createTableFilter(Table t) {
// TableFilter tf = new TableFilter(this, t, TableFilter.newAlias(), select);
// select.addTableFilter(tf, true); // XXX really is true?
// return tf;
// }
//
// public TableFilter getOrCreateTableFilter(Table t) {
// TableFilter tf = getTableFilter(t);
// if (tf == null) {
// tf = createTableFilter(t);
// }
// return tf;
// }
//
// //public Table getTable(String alias) {
// // return select.getTable(alias);
// //}
//
// public Table getRootTable() {
// // XXX maybe if no table then grab default?
// // or should select always have one table?
// // or ui shouldn't offer condition button till table?
// return select.getFilters().get(0).getTable();
// }
//
// public ValueRegistry getValueRegistry() {
// return valueRegistry;
// }
// }
//
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/expression/Expression.java
// public class Expression extends BaseSqlWidget {
//
// public Expression(Session session) {
// super(session);
// // initWidget(new Label("E" + getClass().getName()));
// }
//
// public String getSQL(List<Object> args) {
// return "blah";
// }
//
// }
| import com.redspr.redquerybuilder.core.client.engine.Session;
import com.redspr.redquerybuilder.core.client.expression.Expression;
import com.redspr.redquerybuilder.core.client.util.ObjectArray; | /*
* Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License,
* Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*
* Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888
* Support for the operator "&&" as an alias for SPATIAL_INTERSECTS
*/
package com.redspr.redquerybuilder.core.client.command.dml;
/**
* Represents a union SELECT statement.
*/
public class SelectUnion extends Query {
/**
* The type of a UNION statement.
*/
public static final int UNION = 0;
/**
* The type of a UNION ALL statement.
*/
public static final int UNION_ALL = 1;
/**
* The type of an EXCEPT statement.
*/
public static final int EXCEPT = 2;
/**
* The type of an INTERSECT statement.
*/
public static final int INTERSECT = 3;
private int unionType;
private final Query left;
private Query right; | // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/engine/Session.java
// public class Session {
//
// private static IdentifierEscaper identifierEscaper = new IdentifierEscaper() {
// @Override
// public String quote(String id) {
// return "\"" + id + "\"";
// }
// };
//
// public void setIdentifierEscaper(IdentifierEscaper p) {
// identifierEscaper = p;
// }
//
// /**
// * Add double quotes around an identifier if required.
// *
// * @param s the identifier
// * @return the quoted identifier
// */
// public static String quoteIdentifier(String s) {
// return identifierEscaper.quote(s);
// }
//
// // XXX need commandBuilder and select?
// private CommandBuilder commandBuilder;
//
// private Select select;
//
// private Configuration config;
//
// private final ValueRegistry valueRegistry = new ValueRegistry();
//
// private final Database database;
//
// private final HandlerManager msgbus;
//
//
// // XXX 00 remove one of these constructors
// public Session(Configuration config2) {
// this(config2.getDatabase());
// this.config = config2;
// }
//
// @Deprecated
// public Session(Database database2) {
// database = database2;
// msgbus = new HandlerManager(this);
// }
//
// public Configuration getConfig() {
// return config;
// }
//
// public CommandBuilder getCommandBuilder() {
// return commandBuilder;
// }
//
// public void setCommandBuilder(CommandBuilder p) {
// commandBuilder = p;
// }
//
// public Database getDatabase() {
// return database;
// }
//
//
// public HandlerManager getMsgBus() {
// return msgbus;
// }
//
//
//
// public void setSelect(Select p) {
// select = p;
// }
//
// public Column resolveColumn(String alias, String columnName) {
// return select.resolveColumn(alias, columnName);
// }
//
// public ObjectArray<TableFilter> getFilters() {
// return select.getFilters();
// }
//
// public TableFilter getTableFilter(Table t) {
// for (TableFilter tf : select.getFilters()) {
// if (tf.getTable().equals(t)) {
// return tf;
// }
// }
// return null;
// }
//
// public TableFilter createTableFilter(Table t) {
// TableFilter tf = new TableFilter(this, t, TableFilter.newAlias(), select);
// select.addTableFilter(tf, true); // XXX really is true?
// return tf;
// }
//
// public TableFilter getOrCreateTableFilter(Table t) {
// TableFilter tf = getTableFilter(t);
// if (tf == null) {
// tf = createTableFilter(t);
// }
// return tf;
// }
//
// //public Table getTable(String alias) {
// // return select.getTable(alias);
// //}
//
// public Table getRootTable() {
// // XXX maybe if no table then grab default?
// // or should select always have one table?
// // or ui shouldn't offer condition button till table?
// return select.getFilters().get(0).getTable();
// }
//
// public ValueRegistry getValueRegistry() {
// return valueRegistry;
// }
// }
//
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/expression/Expression.java
// public class Expression extends BaseSqlWidget {
//
// public Expression(Session session) {
// super(session);
// // initWidget(new Label("E" + getClass().getName()));
// }
//
// public String getSQL(List<Object> args) {
// return "blah";
// }
//
// }
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/command/dml/SelectUnion.java
import com.redspr.redquerybuilder.core.client.engine.Session;
import com.redspr.redquerybuilder.core.client.expression.Expression;
import com.redspr.redquerybuilder.core.client.util.ObjectArray;
/*
* Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License,
* Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*
* Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888
* Support for the operator "&&" as an alias for SPATIAL_INTERSECTS
*/
package com.redspr.redquerybuilder.core.client.command.dml;
/**
* Represents a union SELECT statement.
*/
public class SelectUnion extends Query {
/**
* The type of a UNION statement.
*/
public static final int UNION = 0;
/**
* The type of a UNION ALL statement.
*/
public static final int UNION_ALL = 1;
/**
* The type of an EXCEPT statement.
*/
public static final int EXCEPT = 2;
/**
* The type of an INTERSECT statement.
*/
public static final int INTERSECT = 3;
private int unionType;
private final Query left;
private Query right; | private ObjectArray<Expression> expressions; |
salk31/RedQueryBuilder | redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/command/dml/SelectUnion.java | // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/engine/Session.java
// public class Session {
//
// private static IdentifierEscaper identifierEscaper = new IdentifierEscaper() {
// @Override
// public String quote(String id) {
// return "\"" + id + "\"";
// }
// };
//
// public void setIdentifierEscaper(IdentifierEscaper p) {
// identifierEscaper = p;
// }
//
// /**
// * Add double quotes around an identifier if required.
// *
// * @param s the identifier
// * @return the quoted identifier
// */
// public static String quoteIdentifier(String s) {
// return identifierEscaper.quote(s);
// }
//
// // XXX need commandBuilder and select?
// private CommandBuilder commandBuilder;
//
// private Select select;
//
// private Configuration config;
//
// private final ValueRegistry valueRegistry = new ValueRegistry();
//
// private final Database database;
//
// private final HandlerManager msgbus;
//
//
// // XXX 00 remove one of these constructors
// public Session(Configuration config2) {
// this(config2.getDatabase());
// this.config = config2;
// }
//
// @Deprecated
// public Session(Database database2) {
// database = database2;
// msgbus = new HandlerManager(this);
// }
//
// public Configuration getConfig() {
// return config;
// }
//
// public CommandBuilder getCommandBuilder() {
// return commandBuilder;
// }
//
// public void setCommandBuilder(CommandBuilder p) {
// commandBuilder = p;
// }
//
// public Database getDatabase() {
// return database;
// }
//
//
// public HandlerManager getMsgBus() {
// return msgbus;
// }
//
//
//
// public void setSelect(Select p) {
// select = p;
// }
//
// public Column resolveColumn(String alias, String columnName) {
// return select.resolveColumn(alias, columnName);
// }
//
// public ObjectArray<TableFilter> getFilters() {
// return select.getFilters();
// }
//
// public TableFilter getTableFilter(Table t) {
// for (TableFilter tf : select.getFilters()) {
// if (tf.getTable().equals(t)) {
// return tf;
// }
// }
// return null;
// }
//
// public TableFilter createTableFilter(Table t) {
// TableFilter tf = new TableFilter(this, t, TableFilter.newAlias(), select);
// select.addTableFilter(tf, true); // XXX really is true?
// return tf;
// }
//
// public TableFilter getOrCreateTableFilter(Table t) {
// TableFilter tf = getTableFilter(t);
// if (tf == null) {
// tf = createTableFilter(t);
// }
// return tf;
// }
//
// //public Table getTable(String alias) {
// // return select.getTable(alias);
// //}
//
// public Table getRootTable() {
// // XXX maybe if no table then grab default?
// // or should select always have one table?
// // or ui shouldn't offer condition button till table?
// return select.getFilters().get(0).getTable();
// }
//
// public ValueRegistry getValueRegistry() {
// return valueRegistry;
// }
// }
//
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/expression/Expression.java
// public class Expression extends BaseSqlWidget {
//
// public Expression(Session session) {
// super(session);
// // initWidget(new Label("E" + getClass().getName()));
// }
//
// public String getSQL(List<Object> args) {
// return "blah";
// }
//
// }
| import com.redspr.redquerybuilder.core.client.engine.Session;
import com.redspr.redquerybuilder.core.client.expression.Expression;
import com.redspr.redquerybuilder.core.client.util.ObjectArray; | /*
* Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License,
* Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*
* Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888
* Support for the operator "&&" as an alias for SPATIAL_INTERSECTS
*/
package com.redspr.redquerybuilder.core.client.command.dml;
/**
* Represents a union SELECT statement.
*/
public class SelectUnion extends Query {
/**
* The type of a UNION statement.
*/
public static final int UNION = 0;
/**
* The type of a UNION ALL statement.
*/
public static final int UNION_ALL = 1;
/**
* The type of an EXCEPT statement.
*/
public static final int EXCEPT = 2;
/**
* The type of an INTERSECT statement.
*/
public static final int INTERSECT = 3;
private int unionType;
private final Query left;
private Query right;
private ObjectArray<Expression> expressions;
// private ObjectArray<SelectOrderBy> orderList;
// SortOrder sort;
private boolean distinct;
private boolean isPrepared, checkInit;
private boolean isForUpdate;
| // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/engine/Session.java
// public class Session {
//
// private static IdentifierEscaper identifierEscaper = new IdentifierEscaper() {
// @Override
// public String quote(String id) {
// return "\"" + id + "\"";
// }
// };
//
// public void setIdentifierEscaper(IdentifierEscaper p) {
// identifierEscaper = p;
// }
//
// /**
// * Add double quotes around an identifier if required.
// *
// * @param s the identifier
// * @return the quoted identifier
// */
// public static String quoteIdentifier(String s) {
// return identifierEscaper.quote(s);
// }
//
// // XXX need commandBuilder and select?
// private CommandBuilder commandBuilder;
//
// private Select select;
//
// private Configuration config;
//
// private final ValueRegistry valueRegistry = new ValueRegistry();
//
// private final Database database;
//
// private final HandlerManager msgbus;
//
//
// // XXX 00 remove one of these constructors
// public Session(Configuration config2) {
// this(config2.getDatabase());
// this.config = config2;
// }
//
// @Deprecated
// public Session(Database database2) {
// database = database2;
// msgbus = new HandlerManager(this);
// }
//
// public Configuration getConfig() {
// return config;
// }
//
// public CommandBuilder getCommandBuilder() {
// return commandBuilder;
// }
//
// public void setCommandBuilder(CommandBuilder p) {
// commandBuilder = p;
// }
//
// public Database getDatabase() {
// return database;
// }
//
//
// public HandlerManager getMsgBus() {
// return msgbus;
// }
//
//
//
// public void setSelect(Select p) {
// select = p;
// }
//
// public Column resolveColumn(String alias, String columnName) {
// return select.resolveColumn(alias, columnName);
// }
//
// public ObjectArray<TableFilter> getFilters() {
// return select.getFilters();
// }
//
// public TableFilter getTableFilter(Table t) {
// for (TableFilter tf : select.getFilters()) {
// if (tf.getTable().equals(t)) {
// return tf;
// }
// }
// return null;
// }
//
// public TableFilter createTableFilter(Table t) {
// TableFilter tf = new TableFilter(this, t, TableFilter.newAlias(), select);
// select.addTableFilter(tf, true); // XXX really is true?
// return tf;
// }
//
// public TableFilter getOrCreateTableFilter(Table t) {
// TableFilter tf = getTableFilter(t);
// if (tf == null) {
// tf = createTableFilter(t);
// }
// return tf;
// }
//
// //public Table getTable(String alias) {
// // return select.getTable(alias);
// //}
//
// public Table getRootTable() {
// // XXX maybe if no table then grab default?
// // or should select always have one table?
// // or ui shouldn't offer condition button till table?
// return select.getFilters().get(0).getTable();
// }
//
// public ValueRegistry getValueRegistry() {
// return valueRegistry;
// }
// }
//
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/expression/Expression.java
// public class Expression extends BaseSqlWidget {
//
// public Expression(Session session) {
// super(session);
// // initWidget(new Label("E" + getClass().getName()));
// }
//
// public String getSQL(List<Object> args) {
// return "blah";
// }
//
// }
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/command/dml/SelectUnion.java
import com.redspr.redquerybuilder.core.client.engine.Session;
import com.redspr.redquerybuilder.core.client.expression.Expression;
import com.redspr.redquerybuilder.core.client.util.ObjectArray;
/*
* Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License,
* Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*
* Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888
* Support for the operator "&&" as an alias for SPATIAL_INTERSECTS
*/
package com.redspr.redquerybuilder.core.client.command.dml;
/**
* Represents a union SELECT statement.
*/
public class SelectUnion extends Query {
/**
* The type of a UNION statement.
*/
public static final int UNION = 0;
/**
* The type of a UNION ALL statement.
*/
public static final int UNION_ALL = 1;
/**
* The type of an EXCEPT statement.
*/
public static final int EXCEPT = 2;
/**
* The type of an INTERSECT statement.
*/
public static final int INTERSECT = 3;
private int unionType;
private final Query left;
private Query right;
private ObjectArray<Expression> expressions;
// private ObjectArray<SelectOrderBy> orderList;
// SortOrder sort;
private boolean distinct;
private boolean isPrepared, checkInit;
private boolean isForUpdate;
| public SelectUnion(Session session, Query query) { |
salk31/RedQueryBuilder | redquerybuilder-core/src/test/java/com/redspr/redquerybuilder/core/client/CapturingConfiguration.java | // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/Configuration.java
// public class Configuration {
// private Database database = new Database();
//
// private final From from = new From();
//
// public void fireEnumerate(EnumerateRequest request, AsyncCallback<Response> callback) {
// }
//
// // XXX not called by CommandBuilder. GWT users meant to use RedQueryBuilder?
// public void fireOnSqlChange(String sql, List<Object> args) {
// }
//
// public void fireOnTableChange(ObjectArray<TableFilter> filters) {
// }
//
// public void fireDefaultSuggest(SuggestRequest request, AsyncCallback<Response> callback) {
// }
//
// public void fireSuggest(SuggestRequest request, AsyncCallback<Response> callback) {
// }
//
// public Database getDatabase() {
// return database;
// }
//
// public void setDatabase(Database p) {
// this.database = p;
// }
//
// public From getFrom() {
// return from;
// }
// }
//
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/shared/meta/EnumerateRequest.java
// public class EnumerateRequest {
// private String tableName;
//
// private String columnName;
//
// private String columnType;
//
// public String getTableName() {
// return tableName;
// }
//
// public void setTableName(String p) {
// this.tableName = p;
// }
//
// public String getColumnName() {
// return columnName;
// }
//
// public void setColumnName(String p) {
// this.columnName = p;
// }
//
// public String getColumnTypeName() {
// return columnType;
// }
//
// public void setColumnTypeName(String p) {
// this.columnType = p;
// }
//
// }
| import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.SuggestOracle.Response;
import com.redspr.redquerybuilder.core.client.Configuration;
import com.redspr.redquerybuilder.core.shared.meta.EnumerateRequest; | package com.redspr.redquerybuilder.core.client;
public class CapturingConfiguration extends Configuration {
private AsyncCallback<Response> enumerateCallback;
public AsyncCallback<Response> getEnumerateCallback() {
return enumerateCallback;
}
@Override | // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/Configuration.java
// public class Configuration {
// private Database database = new Database();
//
// private final From from = new From();
//
// public void fireEnumerate(EnumerateRequest request, AsyncCallback<Response> callback) {
// }
//
// // XXX not called by CommandBuilder. GWT users meant to use RedQueryBuilder?
// public void fireOnSqlChange(String sql, List<Object> args) {
// }
//
// public void fireOnTableChange(ObjectArray<TableFilter> filters) {
// }
//
// public void fireDefaultSuggest(SuggestRequest request, AsyncCallback<Response> callback) {
// }
//
// public void fireSuggest(SuggestRequest request, AsyncCallback<Response> callback) {
// }
//
// public Database getDatabase() {
// return database;
// }
//
// public void setDatabase(Database p) {
// this.database = p;
// }
//
// public From getFrom() {
// return from;
// }
// }
//
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/shared/meta/EnumerateRequest.java
// public class EnumerateRequest {
// private String tableName;
//
// private String columnName;
//
// private String columnType;
//
// public String getTableName() {
// return tableName;
// }
//
// public void setTableName(String p) {
// this.tableName = p;
// }
//
// public String getColumnName() {
// return columnName;
// }
//
// public void setColumnName(String p) {
// this.columnName = p;
// }
//
// public String getColumnTypeName() {
// return columnType;
// }
//
// public void setColumnTypeName(String p) {
// this.columnType = p;
// }
//
// }
// Path: redquerybuilder-core/src/test/java/com/redspr/redquerybuilder/core/client/CapturingConfiguration.java
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.SuggestOracle.Response;
import com.redspr.redquerybuilder.core.client.Configuration;
import com.redspr.redquerybuilder.core.shared.meta.EnumerateRequest;
package com.redspr.redquerybuilder.core.client;
public class CapturingConfiguration extends Configuration {
private AsyncCallback<Response> enumerateCallback;
public AsyncCallback<Response> getEnumerateCallback() {
return enumerateCallback;
}
@Override | public void fireEnumerate(EnumerateRequest request, AsyncCallback<Response> callback) { |
salk31/RedQueryBuilder | redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/shared/meta/DbObjectBase.java | // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/engine/Session.java
// public class Session {
//
// private static IdentifierEscaper identifierEscaper = new IdentifierEscaper() {
// @Override
// public String quote(String id) {
// return "\"" + id + "\"";
// }
// };
//
// public void setIdentifierEscaper(IdentifierEscaper p) {
// identifierEscaper = p;
// }
//
// /**
// * Add double quotes around an identifier if required.
// *
// * @param s the identifier
// * @return the quoted identifier
// */
// public static String quoteIdentifier(String s) {
// return identifierEscaper.quote(s);
// }
//
// // XXX need commandBuilder and select?
// private CommandBuilder commandBuilder;
//
// private Select select;
//
// private Configuration config;
//
// private final ValueRegistry valueRegistry = new ValueRegistry();
//
// private final Database database;
//
// private final HandlerManager msgbus;
//
//
// // XXX 00 remove one of these constructors
// public Session(Configuration config2) {
// this(config2.getDatabase());
// this.config = config2;
// }
//
// @Deprecated
// public Session(Database database2) {
// database = database2;
// msgbus = new HandlerManager(this);
// }
//
// public Configuration getConfig() {
// return config;
// }
//
// public CommandBuilder getCommandBuilder() {
// return commandBuilder;
// }
//
// public void setCommandBuilder(CommandBuilder p) {
// commandBuilder = p;
// }
//
// public Database getDatabase() {
// return database;
// }
//
//
// public HandlerManager getMsgBus() {
// return msgbus;
// }
//
//
//
// public void setSelect(Select p) {
// select = p;
// }
//
// public Column resolveColumn(String alias, String columnName) {
// return select.resolveColumn(alias, columnName);
// }
//
// public ObjectArray<TableFilter> getFilters() {
// return select.getFilters();
// }
//
// public TableFilter getTableFilter(Table t) {
// for (TableFilter tf : select.getFilters()) {
// if (tf.getTable().equals(t)) {
// return tf;
// }
// }
// return null;
// }
//
// public TableFilter createTableFilter(Table t) {
// TableFilter tf = new TableFilter(this, t, TableFilter.newAlias(), select);
// select.addTableFilter(tf, true); // XXX really is true?
// return tf;
// }
//
// public TableFilter getOrCreateTableFilter(Table t) {
// TableFilter tf = getTableFilter(t);
// if (tf == null) {
// tf = createTableFilter(t);
// }
// return tf;
// }
//
// //public Table getTable(String alias) {
// // return select.getTable(alias);
// //}
//
// public Table getRootTable() {
// // XXX maybe if no table then grab default?
// // or should select always have one table?
// // or ui shouldn't offer condition button till table?
// return select.getFilters().get(0).getTable();
// }
//
// public ValueRegistry getValueRegistry() {
// return valueRegistry;
// }
// }
| import com.redspr.redquerybuilder.core.client.engine.Session; | package com.redspr.redquerybuilder.core.shared.meta;
/**
* The base class for all database objects.
*/
public abstract class DbObjectBase implements DbObject, HasLabel {
private String objectName;
private String label;
protected void setObjectName(String name) {
objectName = name;
}
public void setLabel(String p) {
this.label = p;
}
@Override
public String getSQL() { | // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/engine/Session.java
// public class Session {
//
// private static IdentifierEscaper identifierEscaper = new IdentifierEscaper() {
// @Override
// public String quote(String id) {
// return "\"" + id + "\"";
// }
// };
//
// public void setIdentifierEscaper(IdentifierEscaper p) {
// identifierEscaper = p;
// }
//
// /**
// * Add double quotes around an identifier if required.
// *
// * @param s the identifier
// * @return the quoted identifier
// */
// public static String quoteIdentifier(String s) {
// return identifierEscaper.quote(s);
// }
//
// // XXX need commandBuilder and select?
// private CommandBuilder commandBuilder;
//
// private Select select;
//
// private Configuration config;
//
// private final ValueRegistry valueRegistry = new ValueRegistry();
//
// private final Database database;
//
// private final HandlerManager msgbus;
//
//
// // XXX 00 remove one of these constructors
// public Session(Configuration config2) {
// this(config2.getDatabase());
// this.config = config2;
// }
//
// @Deprecated
// public Session(Database database2) {
// database = database2;
// msgbus = new HandlerManager(this);
// }
//
// public Configuration getConfig() {
// return config;
// }
//
// public CommandBuilder getCommandBuilder() {
// return commandBuilder;
// }
//
// public void setCommandBuilder(CommandBuilder p) {
// commandBuilder = p;
// }
//
// public Database getDatabase() {
// return database;
// }
//
//
// public HandlerManager getMsgBus() {
// return msgbus;
// }
//
//
//
// public void setSelect(Select p) {
// select = p;
// }
//
// public Column resolveColumn(String alias, String columnName) {
// return select.resolveColumn(alias, columnName);
// }
//
// public ObjectArray<TableFilter> getFilters() {
// return select.getFilters();
// }
//
// public TableFilter getTableFilter(Table t) {
// for (TableFilter tf : select.getFilters()) {
// if (tf.getTable().equals(t)) {
// return tf;
// }
// }
// return null;
// }
//
// public TableFilter createTableFilter(Table t) {
// TableFilter tf = new TableFilter(this, t, TableFilter.newAlias(), select);
// select.addTableFilter(tf, true); // XXX really is true?
// return tf;
// }
//
// public TableFilter getOrCreateTableFilter(Table t) {
// TableFilter tf = getTableFilter(t);
// if (tf == null) {
// tf = createTableFilter(t);
// }
// return tf;
// }
//
// //public Table getTable(String alias) {
// // return select.getTable(alias);
// //}
//
// public Table getRootTable() {
// // XXX maybe if no table then grab default?
// // or should select always have one table?
// // or ui shouldn't offer condition button till table?
// return select.getFilters().get(0).getTable();
// }
//
// public ValueRegistry getValueRegistry() {
// return valueRegistry;
// }
// }
// Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/shared/meta/DbObjectBase.java
import com.redspr.redquerybuilder.core.client.engine.Session;
package com.redspr.redquerybuilder.core.shared.meta;
/**
* The base class for all database objects.
*/
public abstract class DbObjectBase implements DbObject, HasLabel {
private String objectName;
private String label;
protected void setObjectName(String name) {
objectName = name;
}
public void setLabel(String p) {
this.label = p;
}
@Override
public String getSQL() { | return Session.quoteIdentifier(objectName); |
salk31/RedQueryBuilder | redquerybuilder-js/src/main/java/com/redspr/redquerybuilder/js/client/JsVisitor.java | // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/VisitorContext.java
// @JsType
// public interface VisitorContext<T> {
// interface NodeType {
// String PARAMETER = "PARAMETER";
// String COLUMN = "COLUMN";
// String COMPARISON = "COMPARISON";
// String LOGIC = "LOGIC"; // XXX not sure about this
// String SELECT = "SELECT";
// };
//
// String getNodeType(); // TODO __ enum and JS?
// String getNodeName();
//
// HasMessages asHasMessages();
//
// HasValue<T> asHasValue();
// }
| import com.google.gwt.core.client.js.JsExport;
import com.redspr.redquerybuilder.core.client.BaseSqlWidget;
import com.redspr.redquerybuilder.core.client.Visitor;
import com.redspr.redquerybuilder.core.client.VisitorContext; | package com.redspr.redquerybuilder.js.client;
// XXX move into core as DefaultVisitor?
//@JsNamespace("$wnd.rqb")
@com.google.gwt.core.client.js.JsType
public class JsVisitor implements Visitor {
@JsExport("$wnd.rqb.Visitor")
public JsVisitor() {
}
@Override
public void handle(BaseSqlWidget w) {
}
@Override | // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/client/VisitorContext.java
// @JsType
// public interface VisitorContext<T> {
// interface NodeType {
// String PARAMETER = "PARAMETER";
// String COLUMN = "COLUMN";
// String COMPARISON = "COMPARISON";
// String LOGIC = "LOGIC"; // XXX not sure about this
// String SELECT = "SELECT";
// };
//
// String getNodeType(); // TODO __ enum and JS?
// String getNodeName();
//
// HasMessages asHasMessages();
//
// HasValue<T> asHasValue();
// }
// Path: redquerybuilder-js/src/main/java/com/redspr/redquerybuilder/js/client/JsVisitor.java
import com.google.gwt.core.client.js.JsExport;
import com.redspr.redquerybuilder.core.client.BaseSqlWidget;
import com.redspr.redquerybuilder.core.client.Visitor;
import com.redspr.redquerybuilder.core.client.VisitorContext;
package com.redspr.redquerybuilder.js.client;
// XXX move into core as DefaultVisitor?
//@JsNamespace("$wnd.rqb")
@com.google.gwt.core.client.js.JsType
public class JsVisitor implements Visitor {
@JsExport("$wnd.rqb.Visitor")
public JsVisitor() {
}
@Override
public void handle(BaseSqlWidget w) {
}
@Override | public void visit(VisitorContext<?> context) { |
salk31/RedQueryBuilder | redquerybuilder-core/src/test/java/com/redspr/redquerybuilder/core/client/expression/GwtTestTextEditor.java | // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/shared/meta/Editor.java
// public class Editor implements HasStyleName, Serializable, IsSerializable {
// public static class TextEditor extends Editor {
// @Override
// public Object getDefault() {
// return "";
// }
// }
//
// public static class DateEditor extends Editor {
// public static final String FORMAT = "format";
// }
//
// public static class BooleanEditor extends Editor {
// @Override
// public Object getDefault() {
// return Boolean.FALSE;
// }
// }
//
// public static class SelectEditor extends Editor {
//
// }
//
// public static class NumberEditor extends Editor {
// }
//
//
// // XXX - rubbish, only used by JSON?
// private static final Map<String, Editor> editorByName = new HashMap<String, Editor>();
//
// private static Editor valueOf2(String name) {
// if ("STRING".equals(name) || "TEXT".equals(name)) {
// return new TextEditor();
// } else if ("DATE".equals(name)) {
// return new DateEditor();
// } else if ("SUGGEST".equals(name)) {
// return new SuggestEditor();
// } else if ("SELECT".equals(name)) {
// return new SelectEditor();
// } else if ("NUMBER".equals(name)) {
// return new NumberEditor();
// } else {
// throw new RuntimeException("No editor for " + name);
// }
// }
//
// public static Editor valueOf(String name) {
// Editor e = editorByName.get(name);
// if (e == null) {
// e = valueOf2(name);
// editorByName.put(name, e);
// }
// return e;
// }
//
// // XXX map mush
// private final Map<String, Object> attributes = new HashMap<String, Object>();
//
// private String styleName;
//
// public Object getDefault() {
// return null;
// }
//
// public void setAttribute(String name, Object value) {
// attributes.put(name, value);
// }
//
// public Object getAttribute(String name) {
// return attributes.get(name);
// }
//
// public String getStyleName() {
// return styleName;
// }
//
// @Override
// public void setStyleName(String p) {
// this.styleName = p;
// }
// }
| import com.redspr.redquerybuilder.core.shared.meta.Editor; | package com.redspr.redquerybuilder.core.client.expression;
public class GwtTestTextEditor extends AbstractEditorTest<String> {
@Override | // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/shared/meta/Editor.java
// public class Editor implements HasStyleName, Serializable, IsSerializable {
// public static class TextEditor extends Editor {
// @Override
// public Object getDefault() {
// return "";
// }
// }
//
// public static class DateEditor extends Editor {
// public static final String FORMAT = "format";
// }
//
// public static class BooleanEditor extends Editor {
// @Override
// public Object getDefault() {
// return Boolean.FALSE;
// }
// }
//
// public static class SelectEditor extends Editor {
//
// }
//
// public static class NumberEditor extends Editor {
// }
//
//
// // XXX - rubbish, only used by JSON?
// private static final Map<String, Editor> editorByName = new HashMap<String, Editor>();
//
// private static Editor valueOf2(String name) {
// if ("STRING".equals(name) || "TEXT".equals(name)) {
// return new TextEditor();
// } else if ("DATE".equals(name)) {
// return new DateEditor();
// } else if ("SUGGEST".equals(name)) {
// return new SuggestEditor();
// } else if ("SELECT".equals(name)) {
// return new SelectEditor();
// } else if ("NUMBER".equals(name)) {
// return new NumberEditor();
// } else {
// throw new RuntimeException("No editor for " + name);
// }
// }
//
// public static Editor valueOf(String name) {
// Editor e = editorByName.get(name);
// if (e == null) {
// e = valueOf2(name);
// editorByName.put(name, e);
// }
// return e;
// }
//
// // XXX map mush
// private final Map<String, Object> attributes = new HashMap<String, Object>();
//
// private String styleName;
//
// public Object getDefault() {
// return null;
// }
//
// public void setAttribute(String name, Object value) {
// attributes.put(name, value);
// }
//
// public Object getAttribute(String name) {
// return attributes.get(name);
// }
//
// public String getStyleName() {
// return styleName;
// }
//
// @Override
// public void setStyleName(String p) {
// this.styleName = p;
// }
// }
// Path: redquerybuilder-core/src/test/java/com/redspr/redquerybuilder/core/client/expression/GwtTestTextEditor.java
import com.redspr.redquerybuilder.core.shared.meta.Editor;
package com.redspr.redquerybuilder.core.client.expression;
public class GwtTestTextEditor extends AbstractEditorTest<String> {
@Override | protected Editor getEditor() { |
salk31/RedQueryBuilder | redquerybuilder-jdbcsample/src/main/java/com/redspr/redquerybuilder/sample/MetaServlet.java | // Path: redquerybuilder-core/src/main/java/java/sql/SQLException.java
// public class SQLException extends Exception {
// public SQLException(String m) {
// super(m);
// }
//
// public SQLException(String m, Throwable t) {
// super(m, t);
// }
//
//
// public int getErrorCode() {
// return 0;
// }
// }
| import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject; | int keySeq = rs2.getInt("KEY_SEQ");
if (keySeq == 1) {
fk = new ForeignKey();
String name = rs2.getString("FK_NAME");
fk.name = name;
fksx.add(fk);
String key = "fk." + name;
fk.label = getLocal(key);
fk.reverseLabel = getLocal(key + ".reverse");
fk.fkTableName = rs2.getString("FKTABLE_NAME");
}
fk.fkColumnNames.add(rs2
.getString("FKCOLUMN_NAME"));
fk.pkColumnNames.add(rs2
.getString("PKCOLUMN_NAME"));
}
for (ForeignKey foo2 : fksx) {
fks.put(foo2.toJson());
}
}
}
}
res.setContentType("application/json");
root.write(res.getWriter()); | // Path: redquerybuilder-core/src/main/java/java/sql/SQLException.java
// public class SQLException extends Exception {
// public SQLException(String m) {
// super(m);
// }
//
// public SQLException(String m, Throwable t) {
// super(m, t);
// }
//
//
// public int getErrorCode() {
// return 0;
// }
// }
// Path: redquerybuilder-jdbcsample/src/main/java/com/redspr/redquerybuilder/sample/MetaServlet.java
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
int keySeq = rs2.getInt("KEY_SEQ");
if (keySeq == 1) {
fk = new ForeignKey();
String name = rs2.getString("FK_NAME");
fk.name = name;
fksx.add(fk);
String key = "fk." + name;
fk.label = getLocal(key);
fk.reverseLabel = getLocal(key + ".reverse");
fk.fkTableName = rs2.getString("FKTABLE_NAME");
}
fk.fkColumnNames.add(rs2
.getString("FKCOLUMN_NAME"));
fk.pkColumnNames.add(rs2
.getString("PKCOLUMN_NAME"));
}
for (ForeignKey foo2 : fksx) {
fks.put(foo2.toJson());
}
}
}
}
res.setContentType("application/json");
root.write(res.getWriter()); | } catch (SQLException ex) { |
salk31/RedQueryBuilder | redquerybuilder-core/src/test/java/com/redspr/redquerybuilder/core/client/expression/GwtTestNumberEditor.java | // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/shared/meta/Editor.java
// public class Editor implements HasStyleName, Serializable, IsSerializable {
// public static class TextEditor extends Editor {
// @Override
// public Object getDefault() {
// return "";
// }
// }
//
// public static class DateEditor extends Editor {
// public static final String FORMAT = "format";
// }
//
// public static class BooleanEditor extends Editor {
// @Override
// public Object getDefault() {
// return Boolean.FALSE;
// }
// }
//
// public static class SelectEditor extends Editor {
//
// }
//
// public static class NumberEditor extends Editor {
// }
//
//
// // XXX - rubbish, only used by JSON?
// private static final Map<String, Editor> editorByName = new HashMap<String, Editor>();
//
// private static Editor valueOf2(String name) {
// if ("STRING".equals(name) || "TEXT".equals(name)) {
// return new TextEditor();
// } else if ("DATE".equals(name)) {
// return new DateEditor();
// } else if ("SUGGEST".equals(name)) {
// return new SuggestEditor();
// } else if ("SELECT".equals(name)) {
// return new SelectEditor();
// } else if ("NUMBER".equals(name)) {
// return new NumberEditor();
// } else {
// throw new RuntimeException("No editor for " + name);
// }
// }
//
// public static Editor valueOf(String name) {
// Editor e = editorByName.get(name);
// if (e == null) {
// e = valueOf2(name);
// editorByName.put(name, e);
// }
// return e;
// }
//
// // XXX map mush
// private final Map<String, Object> attributes = new HashMap<String, Object>();
//
// private String styleName;
//
// public Object getDefault() {
// return null;
// }
//
// public void setAttribute(String name, Object value) {
// attributes.put(name, value);
// }
//
// public Object getAttribute(String name) {
// return attributes.get(name);
// }
//
// public String getStyleName() {
// return styleName;
// }
//
// @Override
// public void setStyleName(String p) {
// this.styleName = p;
// }
// }
| import com.redspr.redquerybuilder.core.shared.meta.Editor; | package com.redspr.redquerybuilder.core.client.expression;
public class GwtTestNumberEditor extends AbstractEditorTest<Double> {
@Override | // Path: redquerybuilder-core/src/main/java/com/redspr/redquerybuilder/core/shared/meta/Editor.java
// public class Editor implements HasStyleName, Serializable, IsSerializable {
// public static class TextEditor extends Editor {
// @Override
// public Object getDefault() {
// return "";
// }
// }
//
// public static class DateEditor extends Editor {
// public static final String FORMAT = "format";
// }
//
// public static class BooleanEditor extends Editor {
// @Override
// public Object getDefault() {
// return Boolean.FALSE;
// }
// }
//
// public static class SelectEditor extends Editor {
//
// }
//
// public static class NumberEditor extends Editor {
// }
//
//
// // XXX - rubbish, only used by JSON?
// private static final Map<String, Editor> editorByName = new HashMap<String, Editor>();
//
// private static Editor valueOf2(String name) {
// if ("STRING".equals(name) || "TEXT".equals(name)) {
// return new TextEditor();
// } else if ("DATE".equals(name)) {
// return new DateEditor();
// } else if ("SUGGEST".equals(name)) {
// return new SuggestEditor();
// } else if ("SELECT".equals(name)) {
// return new SelectEditor();
// } else if ("NUMBER".equals(name)) {
// return new NumberEditor();
// } else {
// throw new RuntimeException("No editor for " + name);
// }
// }
//
// public static Editor valueOf(String name) {
// Editor e = editorByName.get(name);
// if (e == null) {
// e = valueOf2(name);
// editorByName.put(name, e);
// }
// return e;
// }
//
// // XXX map mush
// private final Map<String, Object> attributes = new HashMap<String, Object>();
//
// private String styleName;
//
// public Object getDefault() {
// return null;
// }
//
// public void setAttribute(String name, Object value) {
// attributes.put(name, value);
// }
//
// public Object getAttribute(String name) {
// return attributes.get(name);
// }
//
// public String getStyleName() {
// return styleName;
// }
//
// @Override
// public void setStyleName(String p) {
// this.styleName = p;
// }
// }
// Path: redquerybuilder-core/src/test/java/com/redspr/redquerybuilder/core/client/expression/GwtTestNumberEditor.java
import com.redspr.redquerybuilder.core.shared.meta.Editor;
package com.redspr.redquerybuilder.core.client.expression;
public class GwtTestNumberEditor extends AbstractEditorTest<Double> {
@Override | protected Editor getEditor() { |
JetBrains/teamcity-vmware-plugin | cloud-vmware-server/src/test/java/jetbrains/buildServer/clouds/vmware/connector/VmwareApiConnectorTest.java | // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/connector/beans/ResourcePoolBean.java
// public class ResourcePoolBean implements VmwareManagedEntity, Comparable<ResourcePoolBean> {
// private final String myName;
// private final ManagedObjectReference myMOR;
// private final String myPath;
// private final ManagedObjectReference myParentRef;
// private final String myDatacenterId;
//
//
// @Used("Tests")
// public ResourcePoolBean(final ResourcePool rp){
// this(rp.getMOR(), rp.getName(), null, rp.getParent().getMOR(), "dc");
// }
//
// public ResourcePoolBean(@NotNull final ManagedObjectReference mor,
// @NotNull final String name,
// @NotNull final String path,
// @Nullable final ManagedObjectReference parentRef,
// @Nullable final String datacenterId) {
// myName = name;
// myMOR = mor;
// myPath = path;
// myParentRef = parentRef;
// myDatacenterId = datacenterId;
// }
//
// @NotNull
// @Override
// public String getId() {
// return myMOR.getVal();
// }
//
// @NotNull
// public String getName() {
// return myName;
// }
//
// @NotNull
// @Override
// public String getPath() {
// return myPath;
// }
//
// @Nullable
// @Override
// public String getDatacenterId() {
// return myDatacenterId;
// }
//
// @NotNull
// @Override
// public ManagedObjectReference getMOR() {
// return myMOR;
// }
//
// @Nullable
// @Override
// public ManagedObjectReference getParentMOR() {
// return myParentRef;
// }
//
// @Override
// public int compareTo(@NotNull final ResourcePoolBean o) {
// if (myPath == null && o.myPath == null){
// return StringUtil.compare(StringUtil.toLowerCase(myName), StringUtil.toLowerCase(o.myName));
// }
// return StringUtil.compare(StringUtil.toLowerCase(myPath), StringUtil.toLowerCase(o.myPath));
// }
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/errors/VmwareCheckedCloudException.java
// public class VmwareCheckedCloudException extends CheckedCloudException {
//
// public VmwareCheckedCloudException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// public VmwareCheckedCloudException(final String message) {
// super(message);
// }
//
// public VmwareCheckedCloudException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
| import com.intellij.openapi.util.Pair;
import com.vmware.vim25.*;
import com.vmware.vim25.mo.Datacenter;
import com.vmware.vim25.mo.Folder;
import com.vmware.vim25.mo.ManagedEntity;
import com.vmware.vim25.mo.ResourcePool;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import jetbrains.buildServer.BaseTestCase;
import jetbrains.buildServer.clouds.vmware.connector.beans.ResourcePoolBean;
import jetbrains.buildServer.clouds.vmware.errors.VmwareCheckedCloudException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test; | }
public void allow_same_respool_names() throws Exception{
final VMWareApiConnector connector = new VMWareApiConnectorImpl(new URL("http://localhost:9999"), "username", "pwd", null, null, null, null){
private final Map<String, ManagedEntity> myEntitiesMap = new HashMap<>();
private final Datacenter myDc = new Datacenter(null, null){
@Override
public ManagedObjectReference getMOR() {
ManagedObjectReference mor = new ManagedObjectReference();
mor.setType("Datacenter");
mor.setVal("datacenter-2");
return mor;
}
};
{
myEntitiesMap.put("datacenter-2", myDc);
final Folder folder = createEntity(Folder.class, null, "group-v1", "MyFolder");
myEntitiesMap.put("group-v1", folder);
final ResourcePool respool2 = createEntity(ResourcePool.class, folder, "resgroup-2", "MyRespool");
myEntitiesMap.put("resgroup-2", respool2);
final ResourcePool respool3 = createEntity(ResourcePool.class, folder, "resgroup-3", "MyRespool");
myEntitiesMap.put("resgroup-3", respool3);
}
@Override | // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/connector/beans/ResourcePoolBean.java
// public class ResourcePoolBean implements VmwareManagedEntity, Comparable<ResourcePoolBean> {
// private final String myName;
// private final ManagedObjectReference myMOR;
// private final String myPath;
// private final ManagedObjectReference myParentRef;
// private final String myDatacenterId;
//
//
// @Used("Tests")
// public ResourcePoolBean(final ResourcePool rp){
// this(rp.getMOR(), rp.getName(), null, rp.getParent().getMOR(), "dc");
// }
//
// public ResourcePoolBean(@NotNull final ManagedObjectReference mor,
// @NotNull final String name,
// @NotNull final String path,
// @Nullable final ManagedObjectReference parentRef,
// @Nullable final String datacenterId) {
// myName = name;
// myMOR = mor;
// myPath = path;
// myParentRef = parentRef;
// myDatacenterId = datacenterId;
// }
//
// @NotNull
// @Override
// public String getId() {
// return myMOR.getVal();
// }
//
// @NotNull
// public String getName() {
// return myName;
// }
//
// @NotNull
// @Override
// public String getPath() {
// return myPath;
// }
//
// @Nullable
// @Override
// public String getDatacenterId() {
// return myDatacenterId;
// }
//
// @NotNull
// @Override
// public ManagedObjectReference getMOR() {
// return myMOR;
// }
//
// @Nullable
// @Override
// public ManagedObjectReference getParentMOR() {
// return myParentRef;
// }
//
// @Override
// public int compareTo(@NotNull final ResourcePoolBean o) {
// if (myPath == null && o.myPath == null){
// return StringUtil.compare(StringUtil.toLowerCase(myName), StringUtil.toLowerCase(o.myName));
// }
// return StringUtil.compare(StringUtil.toLowerCase(myPath), StringUtil.toLowerCase(o.myPath));
// }
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/errors/VmwareCheckedCloudException.java
// public class VmwareCheckedCloudException extends CheckedCloudException {
//
// public VmwareCheckedCloudException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// public VmwareCheckedCloudException(final String message) {
// super(message);
// }
//
// public VmwareCheckedCloudException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
// Path: cloud-vmware-server/src/test/java/jetbrains/buildServer/clouds/vmware/connector/VmwareApiConnectorTest.java
import com.intellij.openapi.util.Pair;
import com.vmware.vim25.*;
import com.vmware.vim25.mo.Datacenter;
import com.vmware.vim25.mo.Folder;
import com.vmware.vim25.mo.ManagedEntity;
import com.vmware.vim25.mo.ResourcePool;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import jetbrains.buildServer.BaseTestCase;
import jetbrains.buildServer.clouds.vmware.connector.beans.ResourcePoolBean;
import jetbrains.buildServer.clouds.vmware.errors.VmwareCheckedCloudException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
}
public void allow_same_respool_names() throws Exception{
final VMWareApiConnector connector = new VMWareApiConnectorImpl(new URL("http://localhost:9999"), "username", "pwd", null, null, null, null){
private final Map<String, ManagedEntity> myEntitiesMap = new HashMap<>();
private final Datacenter myDc = new Datacenter(null, null){
@Override
public ManagedObjectReference getMOR() {
ManagedObjectReference mor = new ManagedObjectReference();
mor.setType("Datacenter");
mor.setVal("datacenter-2");
return mor;
}
};
{
myEntitiesMap.put("datacenter-2", myDc);
final Folder folder = createEntity(Folder.class, null, "group-v1", "MyFolder");
myEntitiesMap.put("group-v1", folder);
final ResourcePool respool2 = createEntity(ResourcePool.class, folder, "resgroup-2", "MyRespool");
myEntitiesMap.put("resgroup-2", respool2);
final ResourcePool respool3 = createEntity(ResourcePool.class, folder, "resgroup-3", "MyRespool");
myEntitiesMap.put("resgroup-3", respool3);
}
@Override | protected <T extends ManagedEntity> Collection<T> findAllEntitiesOld(final Class<T> instanceType) throws VmwareCheckedCloudException { |
JetBrains/teamcity-vmware-plugin | cloud-vmware-server/src/test/java/jetbrains/buildServer/clouds/vmware/connector/VmwareApiConnectorTest.java | // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/connector/beans/ResourcePoolBean.java
// public class ResourcePoolBean implements VmwareManagedEntity, Comparable<ResourcePoolBean> {
// private final String myName;
// private final ManagedObjectReference myMOR;
// private final String myPath;
// private final ManagedObjectReference myParentRef;
// private final String myDatacenterId;
//
//
// @Used("Tests")
// public ResourcePoolBean(final ResourcePool rp){
// this(rp.getMOR(), rp.getName(), null, rp.getParent().getMOR(), "dc");
// }
//
// public ResourcePoolBean(@NotNull final ManagedObjectReference mor,
// @NotNull final String name,
// @NotNull final String path,
// @Nullable final ManagedObjectReference parentRef,
// @Nullable final String datacenterId) {
// myName = name;
// myMOR = mor;
// myPath = path;
// myParentRef = parentRef;
// myDatacenterId = datacenterId;
// }
//
// @NotNull
// @Override
// public String getId() {
// return myMOR.getVal();
// }
//
// @NotNull
// public String getName() {
// return myName;
// }
//
// @NotNull
// @Override
// public String getPath() {
// return myPath;
// }
//
// @Nullable
// @Override
// public String getDatacenterId() {
// return myDatacenterId;
// }
//
// @NotNull
// @Override
// public ManagedObjectReference getMOR() {
// return myMOR;
// }
//
// @Nullable
// @Override
// public ManagedObjectReference getParentMOR() {
// return myParentRef;
// }
//
// @Override
// public int compareTo(@NotNull final ResourcePoolBean o) {
// if (myPath == null && o.myPath == null){
// return StringUtil.compare(StringUtil.toLowerCase(myName), StringUtil.toLowerCase(o.myName));
// }
// return StringUtil.compare(StringUtil.toLowerCase(myPath), StringUtil.toLowerCase(o.myPath));
// }
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/errors/VmwareCheckedCloudException.java
// public class VmwareCheckedCloudException extends CheckedCloudException {
//
// public VmwareCheckedCloudException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// public VmwareCheckedCloudException(final String message) {
// super(message);
// }
//
// public VmwareCheckedCloudException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
| import com.intellij.openapi.util.Pair;
import com.vmware.vim25.*;
import com.vmware.vim25.mo.Datacenter;
import com.vmware.vim25.mo.Folder;
import com.vmware.vim25.mo.ManagedEntity;
import com.vmware.vim25.mo.ResourcePool;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import jetbrains.buildServer.BaseTestCase;
import jetbrains.buildServer.clouds.vmware.connector.beans.ResourcePoolBean;
import jetbrains.buildServer.clouds.vmware.errors.VmwareCheckedCloudException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test; | }
return null;
}
@Override
protected <T extends ManagedEntity> T createExactManagedEntity(final ManagedObjectReference mor) {
return (T)myEntitiesMap.get(mor.getVal());
}
@Override
protected <T extends ManagedEntity> T searchManagedEntity(@NotNull final String idName,
@NotNull final Class<T> instanceType,
@Nullable final Datacenter dc) {
return (T)myEntitiesMap.get(idName);
}
@Override
protected ObjectContent[] getObjectContents(final Datacenter dc, final String[][] typeinfo) throws RemoteException {
assert dc == myDc;
final ObjectContent[] retval = new ObjectContent[2];
//"ResourcePool", "name", "parent"
ManagedObjectReference parentMOR = new ManagedObjectReference();
parentMOR.setType("Folder");
parentMOR.setVal("group-v1");
retval[0] = createObjectContent("ResourcePool", "resgroup-2", Pair.create("name", "MyRespool"), Pair.create("parent", parentMOR));
retval[1] = createObjectContent("ResourcePool", "resgroup-3", Pair.create("name", "MyRespool"), Pair.create("parent", parentMOR));
return retval;
}
};
| // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/connector/beans/ResourcePoolBean.java
// public class ResourcePoolBean implements VmwareManagedEntity, Comparable<ResourcePoolBean> {
// private final String myName;
// private final ManagedObjectReference myMOR;
// private final String myPath;
// private final ManagedObjectReference myParentRef;
// private final String myDatacenterId;
//
//
// @Used("Tests")
// public ResourcePoolBean(final ResourcePool rp){
// this(rp.getMOR(), rp.getName(), null, rp.getParent().getMOR(), "dc");
// }
//
// public ResourcePoolBean(@NotNull final ManagedObjectReference mor,
// @NotNull final String name,
// @NotNull final String path,
// @Nullable final ManagedObjectReference parentRef,
// @Nullable final String datacenterId) {
// myName = name;
// myMOR = mor;
// myPath = path;
// myParentRef = parentRef;
// myDatacenterId = datacenterId;
// }
//
// @NotNull
// @Override
// public String getId() {
// return myMOR.getVal();
// }
//
// @NotNull
// public String getName() {
// return myName;
// }
//
// @NotNull
// @Override
// public String getPath() {
// return myPath;
// }
//
// @Nullable
// @Override
// public String getDatacenterId() {
// return myDatacenterId;
// }
//
// @NotNull
// @Override
// public ManagedObjectReference getMOR() {
// return myMOR;
// }
//
// @Nullable
// @Override
// public ManagedObjectReference getParentMOR() {
// return myParentRef;
// }
//
// @Override
// public int compareTo(@NotNull final ResourcePoolBean o) {
// if (myPath == null && o.myPath == null){
// return StringUtil.compare(StringUtil.toLowerCase(myName), StringUtil.toLowerCase(o.myName));
// }
// return StringUtil.compare(StringUtil.toLowerCase(myPath), StringUtil.toLowerCase(o.myPath));
// }
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/errors/VmwareCheckedCloudException.java
// public class VmwareCheckedCloudException extends CheckedCloudException {
//
// public VmwareCheckedCloudException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// public VmwareCheckedCloudException(final String message) {
// super(message);
// }
//
// public VmwareCheckedCloudException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
// Path: cloud-vmware-server/src/test/java/jetbrains/buildServer/clouds/vmware/connector/VmwareApiConnectorTest.java
import com.intellij.openapi.util.Pair;
import com.vmware.vim25.*;
import com.vmware.vim25.mo.Datacenter;
import com.vmware.vim25.mo.Folder;
import com.vmware.vim25.mo.ManagedEntity;
import com.vmware.vim25.mo.ResourcePool;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import jetbrains.buildServer.BaseTestCase;
import jetbrains.buildServer.clouds.vmware.connector.beans.ResourcePoolBean;
import jetbrains.buildServer.clouds.vmware.errors.VmwareCheckedCloudException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jmock.Mockery;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
}
return null;
}
@Override
protected <T extends ManagedEntity> T createExactManagedEntity(final ManagedObjectReference mor) {
return (T)myEntitiesMap.get(mor.getVal());
}
@Override
protected <T extends ManagedEntity> T searchManagedEntity(@NotNull final String idName,
@NotNull final Class<T> instanceType,
@Nullable final Datacenter dc) {
return (T)myEntitiesMap.get(idName);
}
@Override
protected ObjectContent[] getObjectContents(final Datacenter dc, final String[][] typeinfo) throws RemoteException {
assert dc == myDc;
final ObjectContent[] retval = new ObjectContent[2];
//"ResourcePool", "name", "parent"
ManagedObjectReference parentMOR = new ManagedObjectReference();
parentMOR.setType("Folder");
parentMOR.setVal("group-v1");
retval[0] = createObjectContent("ResourcePool", "resgroup-2", Pair.create("name", "MyRespool"), Pair.create("parent", parentMOR));
retval[1] = createObjectContent("ResourcePool", "resgroup-3", Pair.create("name", "MyRespool"), Pair.create("parent", parentMOR));
return retval;
}
};
| final List<ResourcePoolBean> pools = connector.getResourcePools(); |
JetBrains/teamcity-vmware-plugin | cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/connector/VmwareTaskWrapper.java | // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/connector/AsyncCloudTask.java
// public interface AsyncCloudTask {
//
// /**
// * Consecutive execution of this method will makes no effect. Only first call of this method starts the executing.
// * All next calls just return the result
// * @return result
// */
// CloudTaskResult executeOrGetResult();
//
// @NotNull
// String getName();
//
// long getStartTime();
//
// boolean isDone();
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/connector/CloudTaskResult.java
// public class CloudTaskResult {
// private final boolean myHasErrors;
// private final String myDescription;
// private final Throwable myThrowable;
//
//
//
// public CloudTaskResult() {
// this(false, null, null);
// }
//
// public CloudTaskResult(@Nullable final String description) {
// this(false, description, null);
// }
//
// public CloudTaskResult(final boolean hasErrors, @Nullable final String description, @Nullable final Throwable throwable) {
// myHasErrors = hasErrors;
// myDescription = description;
// myThrowable = throwable;
// }
//
// public boolean isHasErrors() {
// return myHasErrors;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public Throwable getThrowable() {
// return myThrowable;
// }
// }
| import com.vmware.vim25.LocalizedMethodFault;
import com.vmware.vim25.TaskInfo;
import com.vmware.vim25.TaskInfoState;
import com.vmware.vim25.mo.Task;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
import jetbrains.buildServer.clouds.base.connector.AsyncCloudTask;
import jetbrains.buildServer.clouds.base.connector.CloudTaskResult;
import jetbrains.buildServer.log.LogUtil;
import jetbrains.buildServer.util.impl.Lazy;
import org.jetbrains.annotations.NotNull; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.clouds.vmware.connector;
/**
* @author Sergey.Pak
* Date: 7/29/2014
* Time: 6:22 PM
*/
public class VmwareTaskWrapper implements AsyncCloudTask {
private final Callable<Task> myVmwareTask;
private final String myTaskName;
private volatile long myStartTime; | // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/connector/AsyncCloudTask.java
// public interface AsyncCloudTask {
//
// /**
// * Consecutive execution of this method will makes no effect. Only first call of this method starts the executing.
// * All next calls just return the result
// * @return result
// */
// CloudTaskResult executeOrGetResult();
//
// @NotNull
// String getName();
//
// long getStartTime();
//
// boolean isDone();
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/connector/CloudTaskResult.java
// public class CloudTaskResult {
// private final boolean myHasErrors;
// private final String myDescription;
// private final Throwable myThrowable;
//
//
//
// public CloudTaskResult() {
// this(false, null, null);
// }
//
// public CloudTaskResult(@Nullable final String description) {
// this(false, description, null);
// }
//
// public CloudTaskResult(final boolean hasErrors, @Nullable final String description, @Nullable final Throwable throwable) {
// myHasErrors = hasErrors;
// myDescription = description;
// myThrowable = throwable;
// }
//
// public boolean isHasErrors() {
// return myHasErrors;
// }
//
// public String getDescription() {
// return myDescription;
// }
//
// public Throwable getThrowable() {
// return myThrowable;
// }
// }
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/connector/VmwareTaskWrapper.java
import com.vmware.vim25.LocalizedMethodFault;
import com.vmware.vim25.TaskInfo;
import com.vmware.vim25.TaskInfoState;
import com.vmware.vim25.mo.Task;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
import jetbrains.buildServer.clouds.base.connector.AsyncCloudTask;
import jetbrains.buildServer.clouds.base.connector.CloudTaskResult;
import jetbrains.buildServer.log.LogUtil;
import jetbrains.buildServer.util.impl.Lazy;
import org.jetbrains.annotations.NotNull;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.clouds.vmware.connector;
/**
* @author Sergey.Pak
* Date: 7/29/2014
* Time: 6:22 PM
*/
public class VmwareTaskWrapper implements AsyncCloudTask {
private final Callable<Task> myVmwareTask;
private final String myTaskName;
private volatile long myStartTime; | private final Lazy<CloudTaskResult> myResultLazy; |
JetBrains/teamcity-vmware-plugin | cloud-vmware-server/src/test/java/jetbrains/buildServer/clouds/vmware/stubs/FakeVirtualMachine.java | // Path: cloud-vmware-server/src/test/java/jetbrains/buildServer/clouds/vmware/stubs/FakeModel.java
// public static final ThreadFactory FAKE_MODEL_THREAD_FACTORY = r -> {
// Thread th = new Thread(r);
// th.setDaemon(true);
// return th;
// };
| import com.vmware.vim25.*;
import com.vmware.vim25.mo.*;
import java.rmi.RemoteException;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import jetbrains.buildServer.serverSide.TeamCityProperties;
import org.jetbrains.annotations.NotNull;
import static jetbrains.buildServer.clouds.vmware.stubs.FakeModel.FAKE_MODEL_THREAD_FACTORY; | newVm.setParentFolder(folder.getName());
final VirtualMachineConfigInfo oldConfig = newVm.myConfigInfoRef.get();
newVm.myConfigInfoRef.set(null);
newVm.myCustomizationSpec = spec.getCustomization();
final CountDownLatch latch = new CountDownLatch(1);
new Thread(){
@Override
public void run() {
try {sleep(100);} catch (InterruptedException e) {}
latch.countDown();
newVm.myConfigInfoRef.set(oldConfig);
if (spec.isPowerOn()){
if (!newVm.myIsStarted.compareAndSet(false, true)){
//throw new RemoteException("Already started");
}
}
}
}.start();
return longTask(latch);
}
@Override
public Task powerOffVM_Task() throws RemoteException {
FakeModel.instance().publishEvent(getName(), "powerOffVM_Task");
if (!myIsStarted.get()){
throw new RemoteException("Already stopped");
}
final TaskInfo taskInfo = new TaskInfo();
| // Path: cloud-vmware-server/src/test/java/jetbrains/buildServer/clouds/vmware/stubs/FakeModel.java
// public static final ThreadFactory FAKE_MODEL_THREAD_FACTORY = r -> {
// Thread th = new Thread(r);
// th.setDaemon(true);
// return th;
// };
// Path: cloud-vmware-server/src/test/java/jetbrains/buildServer/clouds/vmware/stubs/FakeVirtualMachine.java
import com.vmware.vim25.*;
import com.vmware.vim25.mo.*;
import java.rmi.RemoteException;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import jetbrains.buildServer.serverSide.TeamCityProperties;
import org.jetbrains.annotations.NotNull;
import static jetbrains.buildServer.clouds.vmware.stubs.FakeModel.FAKE_MODEL_THREAD_FACTORY;
newVm.setParentFolder(folder.getName());
final VirtualMachineConfigInfo oldConfig = newVm.myConfigInfoRef.get();
newVm.myConfigInfoRef.set(null);
newVm.myCustomizationSpec = spec.getCustomization();
final CountDownLatch latch = new CountDownLatch(1);
new Thread(){
@Override
public void run() {
try {sleep(100);} catch (InterruptedException e) {}
latch.countDown();
newVm.myConfigInfoRef.set(oldConfig);
if (spec.isPowerOn()){
if (!newVm.myIsStarted.compareAndSet(false, true)){
//throw new RemoteException("Already started");
}
}
}
}.start();
return longTask(latch);
}
@Override
public Task powerOffVM_Task() throws RemoteException {
FakeModel.instance().publishEvent(getName(), "powerOffVM_Task");
if (!myIsStarted.get()){
throw new RemoteException("Already stopped");
}
final TaskInfo taskInfo = new TaskInfo();
| final Thread thread = FAKE_MODEL_THREAD_FACTORY.newThread(() -> { |
JetBrains/teamcity-vmware-plugin | cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/connector/VmwareInstance.java | // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/connector/AbstractInstance.java
// public abstract class AbstractInstance {
// @NotNull
// public abstract String getName();
//
// public abstract boolean isInitialized();
//
// public abstract Date getStartDate();
//
// public abstract String getIpAddress();
//
// public abstract InstanceStatus getInstanceStatus();
//
// @Nullable
// public abstract String getProperty(String name);
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/VmwareSourceState.java
// public class VmwareSourceState {
//
// @Nullable
// private final String mySnapshotName;
//
// @Nullable
// private final String mySourceVmId;
//
// private VmwareSourceState(@Nullable final String snapshotName, @Nullable final String sourceVmId){
// mySnapshotName = snapshotName;
// mySourceVmId = sourceVmId;
// }
//
// public static VmwareSourceState from(@Nullable final String snapshot, @Nullable final String sourceVmId){
// return new VmwareSourceState(snapshot, sourceVmId);
// }
//
// @Nullable
// public String getDiffMessage(final VmwareSourceState vmState) {
// if (!Objects.equals(vmState.mySnapshotName, this.mySnapshotName)) {
// return String.format("Snapshot is outdated. VM: '%s' vs Actual: '%s'", mySnapshotName, vmState.mySnapshotName);
// } else if (!Objects.equals(vmState.mySourceVmId, this.mySourceVmId) && mySourceVmId != null && vmState.mySourceVmId != null) {
// return String.format("Source VM id is outdated. VM: '%s' vs Actual: '%s'", mySourceVmId, vmState.mySourceVmId);
// }
// return null;
// }
//
// @Nullable
// public String getSnapshotName() {
// return mySnapshotName;
// }
//
// @Nullable
// public String getSourceVmId() {
// return mySourceVmId;
// }
//
// @Override
// public boolean equals(final Object obj) {
// if (!(obj instanceof VmwareSourceState))
// return false;
// final VmwareSourceState state = (VmwareSourceState)obj;
//
// if (!Objects.equals(state.mySnapshotName, this.mySnapshotName))
// return false;
//
// if (!Objects.equals(state.mySourceVmId, this.mySourceVmId) && mySourceVmId != null && state.mySourceVmId != null)
// return false;
//
// return true;
// }
//
// @Override
// public String toString() {
// return "VmwareSourceState{" +
// "mySnapshotName='" + mySnapshotName + '\'' +
// ", mySourceVmId='" + mySourceVmId + '\'' +
// '}';
// }
// }
| import com.intellij.openapi.diagnostic.Logger;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.OptionValue;
import com.vmware.vim25.VirtualMachinePowerState;
import com.vmware.vim25.mo.VirtualMachine;
import java.util.*;
import jetbrains.buildServer.Used;
import jetbrains.buildServer.clouds.InstanceStatus;
import jetbrains.buildServer.clouds.base.connector.AbstractInstance;
import jetbrains.buildServer.clouds.vmware.VmwareSourceState;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | }
return myBootTime == null ? null : myBootTime.getTime();
}
@Nullable
public String getIpAddress() {
return myIpAddress;
}
@Override
public InstanceStatus getInstanceStatus() {
if (myPowerState == VirtualMachinePowerState.poweredOff) {
return InstanceStatus.STOPPED;
}
if (myPowerState == VirtualMachinePowerState.poweredOn) {
return InstanceStatus.RUNNING;
}
return InstanceStatus.UNKNOWN;
}
public boolean isReadonly() {
return myIsTemplate;
}
@NotNull
public String getChangeVersion() {
return myChangeVersion;
}
@Nullable | // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/connector/AbstractInstance.java
// public abstract class AbstractInstance {
// @NotNull
// public abstract String getName();
//
// public abstract boolean isInitialized();
//
// public abstract Date getStartDate();
//
// public abstract String getIpAddress();
//
// public abstract InstanceStatus getInstanceStatus();
//
// @Nullable
// public abstract String getProperty(String name);
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/VmwareSourceState.java
// public class VmwareSourceState {
//
// @Nullable
// private final String mySnapshotName;
//
// @Nullable
// private final String mySourceVmId;
//
// private VmwareSourceState(@Nullable final String snapshotName, @Nullable final String sourceVmId){
// mySnapshotName = snapshotName;
// mySourceVmId = sourceVmId;
// }
//
// public static VmwareSourceState from(@Nullable final String snapshot, @Nullable final String sourceVmId){
// return new VmwareSourceState(snapshot, sourceVmId);
// }
//
// @Nullable
// public String getDiffMessage(final VmwareSourceState vmState) {
// if (!Objects.equals(vmState.mySnapshotName, this.mySnapshotName)) {
// return String.format("Snapshot is outdated. VM: '%s' vs Actual: '%s'", mySnapshotName, vmState.mySnapshotName);
// } else if (!Objects.equals(vmState.mySourceVmId, this.mySourceVmId) && mySourceVmId != null && vmState.mySourceVmId != null) {
// return String.format("Source VM id is outdated. VM: '%s' vs Actual: '%s'", mySourceVmId, vmState.mySourceVmId);
// }
// return null;
// }
//
// @Nullable
// public String getSnapshotName() {
// return mySnapshotName;
// }
//
// @Nullable
// public String getSourceVmId() {
// return mySourceVmId;
// }
//
// @Override
// public boolean equals(final Object obj) {
// if (!(obj instanceof VmwareSourceState))
// return false;
// final VmwareSourceState state = (VmwareSourceState)obj;
//
// if (!Objects.equals(state.mySnapshotName, this.mySnapshotName))
// return false;
//
// if (!Objects.equals(state.mySourceVmId, this.mySourceVmId) && mySourceVmId != null && state.mySourceVmId != null)
// return false;
//
// return true;
// }
//
// @Override
// public String toString() {
// return "VmwareSourceState{" +
// "mySnapshotName='" + mySnapshotName + '\'' +
// ", mySourceVmId='" + mySourceVmId + '\'' +
// '}';
// }
// }
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/connector/VmwareInstance.java
import com.intellij.openapi.diagnostic.Logger;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.OptionValue;
import com.vmware.vim25.VirtualMachinePowerState;
import com.vmware.vim25.mo.VirtualMachine;
import java.util.*;
import jetbrains.buildServer.Used;
import jetbrains.buildServer.clouds.InstanceStatus;
import jetbrains.buildServer.clouds.base.connector.AbstractInstance;
import jetbrains.buildServer.clouds.vmware.VmwareSourceState;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
}
return myBootTime == null ? null : myBootTime.getTime();
}
@Nullable
public String getIpAddress() {
return myIpAddress;
}
@Override
public InstanceStatus getInstanceStatus() {
if (myPowerState == VirtualMachinePowerState.poweredOff) {
return InstanceStatus.STOPPED;
}
if (myPowerState == VirtualMachinePowerState.poweredOn) {
return InstanceStatus.RUNNING;
}
return InstanceStatus.UNKNOWN;
}
public boolean isReadonly() {
return myIsTemplate;
}
@NotNull
public String getChangeVersion() {
return myChangeVersion;
}
@Nullable | public VmwareSourceState getVmSourceState(){ |
JetBrains/teamcity-vmware-plugin | cloud-vmware-server/src/test/java/jetbrains/buildServer/clouds/base/stubs/DummyCloudImage.java | // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/AbstractCloudImage.java
// public abstract class AbstractCloudImage<T extends AbstractCloudInstance, G extends CloudImageDetails> implements CloudImage, UpdatableCloudErrorProvider {
// protected final UpdatableCloudErrorProvider myErrorProvider = new CloudErrorMap(SimpleErrorMessages.getInstance());
// private final Map<String, T> myInstances = new ConcurrentHashMap<String, T>();
// private final String myName;
// private final String myId;
//
// protected AbstractCloudImage(String name, String id) {
// myName = name;
// myId = id;
// }
//
// @NotNull
// public String getId() {
// return myId;
// }
//
// @NotNull
// public String getName() {
// return myName;
// }
//
// public void updateErrors(TypedCloudErrorInfo... errors) {
// myErrorProvider.updateErrors(errors);
// }
//
// @Nullable
// public CloudErrorInfo getErrorInfo() {
// return myErrorProvider.getErrorInfo();
// }
//
// @NotNull
// public Collection<T> getInstances() {
// return Collections.unmodifiableCollection(myInstances.values());
// }
//
// @Nullable
// public T findInstanceById(@NotNull final String instanceId) {
// return myInstances.get(instanceId);
// }
//
// public void removeInstance(@NotNull final String instanceId){
// myInstances.remove(instanceId);
// }
//
// public void addInstance(@NotNull final T instance){
// myInstances.put(instance.getInstanceId(), instance);
// }
//
// public boolean canStartNewInstance(){
// return canStartNewInstanceWithDetails().isPositive();
// }
//
// @NotNull
// public abstract CanStartNewInstanceResult canStartNewInstanceWithDetails();
//
// public abstract void terminateInstance(@NotNull final T instance);
//
// public abstract void restartInstance(@NotNull final T instance);
//
// public abstract T startNewInstance(@NotNull final CloudInstanceUserData tag);
//
// public abstract G getImageDetails();
//
// protected abstract T createInstanceFromReal(final AbstractInstance realInstance);
//
// public void detectNewInstances(final Map<String,? extends AbstractInstance> realInstances){
// for (String instanceName : realInstances.keySet()) {
// if (myInstances.get(instanceName) == null) {
// final AbstractInstance realInstance = realInstances.get(instanceName);
// final T newInstance = createInstanceFromReal(realInstance);
// newInstance.setStatus(realInstance.getInstanceStatus());
// addInstance(newInstance);
// }
// }
//
// }
//
// protected Set<String> getInstanceIds(){
// return Collections.unmodifiableSet(myInstances.keySet());
// }
//
// public String toString() {
// return getClass().getSimpleName() +"{" +"myName='" + getId() + '\'' +'}';
// }
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/connector/AbstractInstance.java
// public abstract class AbstractInstance {
// @NotNull
// public abstract String getName();
//
// public abstract boolean isInitialized();
//
// public abstract Date getStartDate();
//
// public abstract String getIpAddress();
//
// public abstract InstanceStatus getInstanceStatus();
//
// @Nullable
// public abstract String getProperty(String name);
// }
| import jetbrains.buildServer.clouds.CanStartNewInstanceResult;
import jetbrains.buildServer.clouds.CloudInstanceUserData;
import jetbrains.buildServer.clouds.base.AbstractCloudImage;
import jetbrains.buildServer.clouds.base.connector.AbstractInstance;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.clouds.base.stubs;
/**
* Created by Sergey.Pak on 3/4/2016.
*/
public class DummyCloudImage extends AbstractCloudImage<DummyCloudInstance, DummyImageDetails> {
public DummyCloudImage(final String name) {
super(name, name);
}
@NotNull
@Override
public CanStartNewInstanceResult canStartNewInstanceWithDetails() {
throw new UnsupportedOperationException("DummyCloudImage.canStartNewInstanceWithDetails");
}
@Override
public void terminateInstance(@NotNull final DummyCloudInstance instance) {
throw new UnsupportedOperationException("DummyCloudImage.terminateInstance");
//
}
@Override
public void restartInstance(@NotNull final DummyCloudInstance instance) {
throw new UnsupportedOperationException("DummyCloudImage.restartInstance");
//
}
@Override
public DummyCloudInstance startNewInstance(@NotNull final CloudInstanceUserData tag) {
throw new UnsupportedOperationException("DummyCloudImage.startNewInstance");
//return null;
}
@Override
public DummyImageDetails getImageDetails() {
throw new UnsupportedOperationException("DummyCloudImage.getImageDetails");
//return null;
}
@Override | // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/AbstractCloudImage.java
// public abstract class AbstractCloudImage<T extends AbstractCloudInstance, G extends CloudImageDetails> implements CloudImage, UpdatableCloudErrorProvider {
// protected final UpdatableCloudErrorProvider myErrorProvider = new CloudErrorMap(SimpleErrorMessages.getInstance());
// private final Map<String, T> myInstances = new ConcurrentHashMap<String, T>();
// private final String myName;
// private final String myId;
//
// protected AbstractCloudImage(String name, String id) {
// myName = name;
// myId = id;
// }
//
// @NotNull
// public String getId() {
// return myId;
// }
//
// @NotNull
// public String getName() {
// return myName;
// }
//
// public void updateErrors(TypedCloudErrorInfo... errors) {
// myErrorProvider.updateErrors(errors);
// }
//
// @Nullable
// public CloudErrorInfo getErrorInfo() {
// return myErrorProvider.getErrorInfo();
// }
//
// @NotNull
// public Collection<T> getInstances() {
// return Collections.unmodifiableCollection(myInstances.values());
// }
//
// @Nullable
// public T findInstanceById(@NotNull final String instanceId) {
// return myInstances.get(instanceId);
// }
//
// public void removeInstance(@NotNull final String instanceId){
// myInstances.remove(instanceId);
// }
//
// public void addInstance(@NotNull final T instance){
// myInstances.put(instance.getInstanceId(), instance);
// }
//
// public boolean canStartNewInstance(){
// return canStartNewInstanceWithDetails().isPositive();
// }
//
// @NotNull
// public abstract CanStartNewInstanceResult canStartNewInstanceWithDetails();
//
// public abstract void terminateInstance(@NotNull final T instance);
//
// public abstract void restartInstance(@NotNull final T instance);
//
// public abstract T startNewInstance(@NotNull final CloudInstanceUserData tag);
//
// public abstract G getImageDetails();
//
// protected abstract T createInstanceFromReal(final AbstractInstance realInstance);
//
// public void detectNewInstances(final Map<String,? extends AbstractInstance> realInstances){
// for (String instanceName : realInstances.keySet()) {
// if (myInstances.get(instanceName) == null) {
// final AbstractInstance realInstance = realInstances.get(instanceName);
// final T newInstance = createInstanceFromReal(realInstance);
// newInstance.setStatus(realInstance.getInstanceStatus());
// addInstance(newInstance);
// }
// }
//
// }
//
// protected Set<String> getInstanceIds(){
// return Collections.unmodifiableSet(myInstances.keySet());
// }
//
// public String toString() {
// return getClass().getSimpleName() +"{" +"myName='" + getId() + '\'' +'}';
// }
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/connector/AbstractInstance.java
// public abstract class AbstractInstance {
// @NotNull
// public abstract String getName();
//
// public abstract boolean isInitialized();
//
// public abstract Date getStartDate();
//
// public abstract String getIpAddress();
//
// public abstract InstanceStatus getInstanceStatus();
//
// @Nullable
// public abstract String getProperty(String name);
// }
// Path: cloud-vmware-server/src/test/java/jetbrains/buildServer/clouds/base/stubs/DummyCloudImage.java
import jetbrains.buildServer.clouds.CanStartNewInstanceResult;
import jetbrains.buildServer.clouds.CloudInstanceUserData;
import jetbrains.buildServer.clouds.base.AbstractCloudImage;
import jetbrains.buildServer.clouds.base.connector.AbstractInstance;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.clouds.base.stubs;
/**
* Created by Sergey.Pak on 3/4/2016.
*/
public class DummyCloudImage extends AbstractCloudImage<DummyCloudInstance, DummyImageDetails> {
public DummyCloudImage(final String name) {
super(name, name);
}
@NotNull
@Override
public CanStartNewInstanceResult canStartNewInstanceWithDetails() {
throw new UnsupportedOperationException("DummyCloudImage.canStartNewInstanceWithDetails");
}
@Override
public void terminateInstance(@NotNull final DummyCloudInstance instance) {
throw new UnsupportedOperationException("DummyCloudImage.terminateInstance");
//
}
@Override
public void restartInstance(@NotNull final DummyCloudInstance instance) {
throw new UnsupportedOperationException("DummyCloudImage.restartInstance");
//
}
@Override
public DummyCloudInstance startNewInstance(@NotNull final CloudInstanceUserData tag) {
throw new UnsupportedOperationException("DummyCloudImage.startNewInstance");
//return null;
}
@Override
public DummyImageDetails getImageDetails() {
throw new UnsupportedOperationException("DummyCloudImage.getImageDetails");
//return null;
}
@Override | protected DummyCloudInstance createInstanceFromReal(final AbstractInstance realInstance) { |
JetBrains/teamcity-vmware-plugin | cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/AbstractCloudClientFactory.java | // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/beans/CloudImageDetails.java
// public interface CloudImageDetails {
//
// CloneBehaviour getBehaviour();
//
// int getMaxInstances();
//
// String getSourceId();
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/errors/TypedCloudErrorInfo.java
// public class TypedCloudErrorInfo{
// @NotNull private final String myType;
// @NotNull private final String myMessage;
// @NotNull private final String myDetails;
// @Nullable private final Throwable myThrowable;
//
// public static TypedCloudErrorInfo fromException(@NotNull Throwable th){
// return new TypedCloudErrorInfo(th.getMessage(), th.getMessage(), th.toString(), th);
// }
//
// public TypedCloudErrorInfo(@NotNull final String message) {
// this(message, message, null, null);
// }
//
// public TypedCloudErrorInfo(@NotNull final String type, @NotNull final String message) {
// this(type, message, null, null);
// }
//
// public TypedCloudErrorInfo(@NotNull final String type, @NotNull final String message, @Nullable final String details) {
// this(type, message, details, null);
// }
//
// public TypedCloudErrorInfo(@Nullable final String type,
// @Nullable final String message,
// @Nullable final String details,
// @Nullable final Throwable throwable) {
// myType = String.valueOf(type);
// myMessage = String.valueOf(message);
// myDetails = String.valueOf(details);
// myThrowable = throwable;
// }
//
// @NotNull
// public String getType() {
// return myType;
// }
//
// @NotNull
// public String getMessage() {
// return myMessage;
// }
//
// @NotNull
// public String getDetails() {
// return myDetails;
// }
//
// @Nullable
// public Throwable getThrowable() {
// return myThrowable;
// }
//
//
// }
| import java.util.Collection;
import jetbrains.buildServer.clouds.*;
import jetbrains.buildServer.clouds.base.beans.CloudImageDetails;
import jetbrains.buildServer.clouds.base.errors.TypedCloudErrorInfo;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.clouds.base;
/**
* @author Sergey.Pak
* Date: 7/22/2014
* Time: 1:51 PM
*/
public abstract class AbstractCloudClientFactory <D extends CloudImageDetails,C extends AbstractCloudClient>
implements CloudClientFactory {
public AbstractCloudClientFactory(@NotNull final CloudRegistrar cloudRegistrar) {
cloudRegistrar.registerCloudFactory(this);
}
@NotNull
public C createNewClient(@NotNull final CloudState state, @NotNull final CloudClientParameters params) {
try { | // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/beans/CloudImageDetails.java
// public interface CloudImageDetails {
//
// CloneBehaviour getBehaviour();
//
// int getMaxInstances();
//
// String getSourceId();
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/errors/TypedCloudErrorInfo.java
// public class TypedCloudErrorInfo{
// @NotNull private final String myType;
// @NotNull private final String myMessage;
// @NotNull private final String myDetails;
// @Nullable private final Throwable myThrowable;
//
// public static TypedCloudErrorInfo fromException(@NotNull Throwable th){
// return new TypedCloudErrorInfo(th.getMessage(), th.getMessage(), th.toString(), th);
// }
//
// public TypedCloudErrorInfo(@NotNull final String message) {
// this(message, message, null, null);
// }
//
// public TypedCloudErrorInfo(@NotNull final String type, @NotNull final String message) {
// this(type, message, null, null);
// }
//
// public TypedCloudErrorInfo(@NotNull final String type, @NotNull final String message, @Nullable final String details) {
// this(type, message, details, null);
// }
//
// public TypedCloudErrorInfo(@Nullable final String type,
// @Nullable final String message,
// @Nullable final String details,
// @Nullable final Throwable throwable) {
// myType = String.valueOf(type);
// myMessage = String.valueOf(message);
// myDetails = String.valueOf(details);
// myThrowable = throwable;
// }
//
// @NotNull
// public String getType() {
// return myType;
// }
//
// @NotNull
// public String getMessage() {
// return myMessage;
// }
//
// @NotNull
// public String getDetails() {
// return myDetails;
// }
//
// @Nullable
// public Throwable getThrowable() {
// return myThrowable;
// }
//
//
// }
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/AbstractCloudClientFactory.java
import java.util.Collection;
import jetbrains.buildServer.clouds.*;
import jetbrains.buildServer.clouds.base.beans.CloudImageDetails;
import jetbrains.buildServer.clouds.base.errors.TypedCloudErrorInfo;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.clouds.base;
/**
* @author Sergey.Pak
* Date: 7/22/2014
* Time: 1:51 PM
*/
public abstract class AbstractCloudClientFactory <D extends CloudImageDetails,C extends AbstractCloudClient>
implements CloudClientFactory {
public AbstractCloudClientFactory(@NotNull final CloudRegistrar cloudRegistrar) {
cloudRegistrar.registerCloudFactory(this);
}
@NotNull
public C createNewClient(@NotNull final CloudState state, @NotNull final CloudClientParameters params) {
try { | final TypedCloudErrorInfo[] profileErrors = checkClientParams(params); |
JetBrains/teamcity-vmware-plugin | cloud-vmware-server/src/test/java/jetbrains/buildServer/clouds/base/stubs/DummyApiConnector.java | // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/connector/AbstractInstance.java
// public abstract class AbstractInstance {
// @NotNull
// public abstract String getName();
//
// public abstract boolean isInitialized();
//
// public abstract Date getStartDate();
//
// public abstract String getIpAddress();
//
// public abstract InstanceStatus getInstanceStatus();
//
// @Nullable
// public abstract String getProperty(String name);
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/connector/CloudApiConnector.java
// public interface CloudApiConnector<T extends AbstractCloudImage, G extends AbstractCloudInstance> {
//
// void test() throws CheckedCloudException;
//
// /**
// * A special key of the cloud connector. Used to determine whether this cloud connector can be used in several cloud profiles.
// * <br/>
// *
// * It is supposed to represent the same username and server url/region/instance
// * @return see above.
// */
// @NotNull
// String getKey();
//
// @NotNull
// <R extends AbstractInstance> Map<String, R> fetchInstances(@NotNull final T image) throws CheckedCloudException;
//
// @NotNull
// <R extends AbstractInstance> Map<T, Map<String, R>> fetchInstances(@NotNull final Collection<T> images) throws CheckedCloudException;
//
// @NotNull
// @Deprecated
// TypedCloudErrorInfo[] checkImage(@NotNull final T image);
//
// @NotNull
// Map<T, TypedCloudErrorInfo[]> checkImages(@NotNull final Collection<T> images);
//
// @NotNull
// TypedCloudErrorInfo[] checkInstance(@NotNull final G instance);
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/errors/CheckedCloudException.java
// public class CheckedCloudException extends Exception {
//
// public CheckedCloudException(final Throwable cause) {
// super(cause);
// }
//
// public CheckedCloudException(final String message) {
// super(message);
// }
//
// public CheckedCloudException(final String message, final Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/errors/TypedCloudErrorInfo.java
// public class TypedCloudErrorInfo{
// @NotNull private final String myType;
// @NotNull private final String myMessage;
// @NotNull private final String myDetails;
// @Nullable private final Throwable myThrowable;
//
// public static TypedCloudErrorInfo fromException(@NotNull Throwable th){
// return new TypedCloudErrorInfo(th.getMessage(), th.getMessage(), th.toString(), th);
// }
//
// public TypedCloudErrorInfo(@NotNull final String message) {
// this(message, message, null, null);
// }
//
// public TypedCloudErrorInfo(@NotNull final String type, @NotNull final String message) {
// this(type, message, null, null);
// }
//
// public TypedCloudErrorInfo(@NotNull final String type, @NotNull final String message, @Nullable final String details) {
// this(type, message, details, null);
// }
//
// public TypedCloudErrorInfo(@Nullable final String type,
// @Nullable final String message,
// @Nullable final String details,
// @Nullable final Throwable throwable) {
// myType = String.valueOf(type);
// myMessage = String.valueOf(message);
// myDetails = String.valueOf(details);
// myThrowable = throwable;
// }
//
// @NotNull
// public String getType() {
// return myType;
// }
//
// @NotNull
// public String getMessage() {
// return myMessage;
// }
//
// @NotNull
// public String getDetails() {
// return myDetails;
// }
//
// @Nullable
// public Throwable getThrowable() {
// return myThrowable;
// }
//
//
// }
| import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import jetbrains.buildServer.clouds.base.connector.AbstractInstance;
import jetbrains.buildServer.clouds.base.connector.CloudApiConnector;
import jetbrains.buildServer.clouds.base.errors.CheckedCloudException;
import jetbrains.buildServer.clouds.base.errors.TypedCloudErrorInfo;
import org.jetbrains.annotations.NotNull; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.clouds.base.stubs;
/**
* Created by Sergey.Pak on 3/4/2016.
*/
public class DummyApiConnector implements CloudApiConnector<DummyCloudImage, DummyCloudInstance> {
private final Map<String, DummyRealInstance> myRealInstanceMap;
private final Map<String, CountDownLatch> myLatchMap;
public DummyApiConnector(final Map<String, DummyRealInstance> realInstanceMap){
myRealInstanceMap = realInstanceMap;
myLatchMap = new HashMap<>();
}
@Override | // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/connector/AbstractInstance.java
// public abstract class AbstractInstance {
// @NotNull
// public abstract String getName();
//
// public abstract boolean isInitialized();
//
// public abstract Date getStartDate();
//
// public abstract String getIpAddress();
//
// public abstract InstanceStatus getInstanceStatus();
//
// @Nullable
// public abstract String getProperty(String name);
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/connector/CloudApiConnector.java
// public interface CloudApiConnector<T extends AbstractCloudImage, G extends AbstractCloudInstance> {
//
// void test() throws CheckedCloudException;
//
// /**
// * A special key of the cloud connector. Used to determine whether this cloud connector can be used in several cloud profiles.
// * <br/>
// *
// * It is supposed to represent the same username and server url/region/instance
// * @return see above.
// */
// @NotNull
// String getKey();
//
// @NotNull
// <R extends AbstractInstance> Map<String, R> fetchInstances(@NotNull final T image) throws CheckedCloudException;
//
// @NotNull
// <R extends AbstractInstance> Map<T, Map<String, R>> fetchInstances(@NotNull final Collection<T> images) throws CheckedCloudException;
//
// @NotNull
// @Deprecated
// TypedCloudErrorInfo[] checkImage(@NotNull final T image);
//
// @NotNull
// Map<T, TypedCloudErrorInfo[]> checkImages(@NotNull final Collection<T> images);
//
// @NotNull
// TypedCloudErrorInfo[] checkInstance(@NotNull final G instance);
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/errors/CheckedCloudException.java
// public class CheckedCloudException extends Exception {
//
// public CheckedCloudException(final Throwable cause) {
// super(cause);
// }
//
// public CheckedCloudException(final String message) {
// super(message);
// }
//
// public CheckedCloudException(final String message, final Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/errors/TypedCloudErrorInfo.java
// public class TypedCloudErrorInfo{
// @NotNull private final String myType;
// @NotNull private final String myMessage;
// @NotNull private final String myDetails;
// @Nullable private final Throwable myThrowable;
//
// public static TypedCloudErrorInfo fromException(@NotNull Throwable th){
// return new TypedCloudErrorInfo(th.getMessage(), th.getMessage(), th.toString(), th);
// }
//
// public TypedCloudErrorInfo(@NotNull final String message) {
// this(message, message, null, null);
// }
//
// public TypedCloudErrorInfo(@NotNull final String type, @NotNull final String message) {
// this(type, message, null, null);
// }
//
// public TypedCloudErrorInfo(@NotNull final String type, @NotNull final String message, @Nullable final String details) {
// this(type, message, details, null);
// }
//
// public TypedCloudErrorInfo(@Nullable final String type,
// @Nullable final String message,
// @Nullable final String details,
// @Nullable final Throwable throwable) {
// myType = String.valueOf(type);
// myMessage = String.valueOf(message);
// myDetails = String.valueOf(details);
// myThrowable = throwable;
// }
//
// @NotNull
// public String getType() {
// return myType;
// }
//
// @NotNull
// public String getMessage() {
// return myMessage;
// }
//
// @NotNull
// public String getDetails() {
// return myDetails;
// }
//
// @Nullable
// public Throwable getThrowable() {
// return myThrowable;
// }
//
//
// }
// Path: cloud-vmware-server/src/test/java/jetbrains/buildServer/clouds/base/stubs/DummyApiConnector.java
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import jetbrains.buildServer.clouds.base.connector.AbstractInstance;
import jetbrains.buildServer.clouds.base.connector.CloudApiConnector;
import jetbrains.buildServer.clouds.base.errors.CheckedCloudException;
import jetbrains.buildServer.clouds.base.errors.TypedCloudErrorInfo;
import org.jetbrains.annotations.NotNull;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.clouds.base.stubs;
/**
* Created by Sergey.Pak on 3/4/2016.
*/
public class DummyApiConnector implements CloudApiConnector<DummyCloudImage, DummyCloudInstance> {
private final Map<String, DummyRealInstance> myRealInstanceMap;
private final Map<String, CountDownLatch> myLatchMap;
public DummyApiConnector(final Map<String, DummyRealInstance> realInstanceMap){
myRealInstanceMap = realInstanceMap;
myLatchMap = new HashMap<>();
}
@Override | public void test() throws CheckedCloudException { |
JetBrains/teamcity-vmware-plugin | cloud-vmware-server/src/test/java/jetbrains/buildServer/clouds/base/stubs/DummyApiConnector.java | // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/connector/AbstractInstance.java
// public abstract class AbstractInstance {
// @NotNull
// public abstract String getName();
//
// public abstract boolean isInitialized();
//
// public abstract Date getStartDate();
//
// public abstract String getIpAddress();
//
// public abstract InstanceStatus getInstanceStatus();
//
// @Nullable
// public abstract String getProperty(String name);
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/connector/CloudApiConnector.java
// public interface CloudApiConnector<T extends AbstractCloudImage, G extends AbstractCloudInstance> {
//
// void test() throws CheckedCloudException;
//
// /**
// * A special key of the cloud connector. Used to determine whether this cloud connector can be used in several cloud profiles.
// * <br/>
// *
// * It is supposed to represent the same username and server url/region/instance
// * @return see above.
// */
// @NotNull
// String getKey();
//
// @NotNull
// <R extends AbstractInstance> Map<String, R> fetchInstances(@NotNull final T image) throws CheckedCloudException;
//
// @NotNull
// <R extends AbstractInstance> Map<T, Map<String, R>> fetchInstances(@NotNull final Collection<T> images) throws CheckedCloudException;
//
// @NotNull
// @Deprecated
// TypedCloudErrorInfo[] checkImage(@NotNull final T image);
//
// @NotNull
// Map<T, TypedCloudErrorInfo[]> checkImages(@NotNull final Collection<T> images);
//
// @NotNull
// TypedCloudErrorInfo[] checkInstance(@NotNull final G instance);
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/errors/CheckedCloudException.java
// public class CheckedCloudException extends Exception {
//
// public CheckedCloudException(final Throwable cause) {
// super(cause);
// }
//
// public CheckedCloudException(final String message) {
// super(message);
// }
//
// public CheckedCloudException(final String message, final Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/errors/TypedCloudErrorInfo.java
// public class TypedCloudErrorInfo{
// @NotNull private final String myType;
// @NotNull private final String myMessage;
// @NotNull private final String myDetails;
// @Nullable private final Throwable myThrowable;
//
// public static TypedCloudErrorInfo fromException(@NotNull Throwable th){
// return new TypedCloudErrorInfo(th.getMessage(), th.getMessage(), th.toString(), th);
// }
//
// public TypedCloudErrorInfo(@NotNull final String message) {
// this(message, message, null, null);
// }
//
// public TypedCloudErrorInfo(@NotNull final String type, @NotNull final String message) {
// this(type, message, null, null);
// }
//
// public TypedCloudErrorInfo(@NotNull final String type, @NotNull final String message, @Nullable final String details) {
// this(type, message, details, null);
// }
//
// public TypedCloudErrorInfo(@Nullable final String type,
// @Nullable final String message,
// @Nullable final String details,
// @Nullable final Throwable throwable) {
// myType = String.valueOf(type);
// myMessage = String.valueOf(message);
// myDetails = String.valueOf(details);
// myThrowable = throwable;
// }
//
// @NotNull
// public String getType() {
// return myType;
// }
//
// @NotNull
// public String getMessage() {
// return myMessage;
// }
//
// @NotNull
// public String getDetails() {
// return myDetails;
// }
//
// @Nullable
// public Throwable getThrowable() {
// return myThrowable;
// }
//
//
// }
| import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import jetbrains.buildServer.clouds.base.connector.AbstractInstance;
import jetbrains.buildServer.clouds.base.connector.CloudApiConnector;
import jetbrains.buildServer.clouds.base.errors.CheckedCloudException;
import jetbrains.buildServer.clouds.base.errors.TypedCloudErrorInfo;
import org.jetbrains.annotations.NotNull; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.clouds.base.stubs;
/**
* Created by Sergey.Pak on 3/4/2016.
*/
public class DummyApiConnector implements CloudApiConnector<DummyCloudImage, DummyCloudInstance> {
private final Map<String, DummyRealInstance> myRealInstanceMap;
private final Map<String, CountDownLatch> myLatchMap;
public DummyApiConnector(final Map<String, DummyRealInstance> realInstanceMap){
myRealInstanceMap = realInstanceMap;
myLatchMap = new HashMap<>();
}
@Override
public void test() throws CheckedCloudException {
checkLatch("test");
}
/**
* A special key of the cloud connector. Used to determine whether this cloud connector can be used in several cloud profiles.
* <br/>
* <p>
* It is supposed to represent the same username and server url/region/instance
*
* @return see above.
*/
@NotNull
@Override
public String getKey() {
return "dummy_connector";
}
@NotNull
@Override | // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/connector/AbstractInstance.java
// public abstract class AbstractInstance {
// @NotNull
// public abstract String getName();
//
// public abstract boolean isInitialized();
//
// public abstract Date getStartDate();
//
// public abstract String getIpAddress();
//
// public abstract InstanceStatus getInstanceStatus();
//
// @Nullable
// public abstract String getProperty(String name);
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/connector/CloudApiConnector.java
// public interface CloudApiConnector<T extends AbstractCloudImage, G extends AbstractCloudInstance> {
//
// void test() throws CheckedCloudException;
//
// /**
// * A special key of the cloud connector. Used to determine whether this cloud connector can be used in several cloud profiles.
// * <br/>
// *
// * It is supposed to represent the same username and server url/region/instance
// * @return see above.
// */
// @NotNull
// String getKey();
//
// @NotNull
// <R extends AbstractInstance> Map<String, R> fetchInstances(@NotNull final T image) throws CheckedCloudException;
//
// @NotNull
// <R extends AbstractInstance> Map<T, Map<String, R>> fetchInstances(@NotNull final Collection<T> images) throws CheckedCloudException;
//
// @NotNull
// @Deprecated
// TypedCloudErrorInfo[] checkImage(@NotNull final T image);
//
// @NotNull
// Map<T, TypedCloudErrorInfo[]> checkImages(@NotNull final Collection<T> images);
//
// @NotNull
// TypedCloudErrorInfo[] checkInstance(@NotNull final G instance);
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/errors/CheckedCloudException.java
// public class CheckedCloudException extends Exception {
//
// public CheckedCloudException(final Throwable cause) {
// super(cause);
// }
//
// public CheckedCloudException(final String message) {
// super(message);
// }
//
// public CheckedCloudException(final String message, final Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/errors/TypedCloudErrorInfo.java
// public class TypedCloudErrorInfo{
// @NotNull private final String myType;
// @NotNull private final String myMessage;
// @NotNull private final String myDetails;
// @Nullable private final Throwable myThrowable;
//
// public static TypedCloudErrorInfo fromException(@NotNull Throwable th){
// return new TypedCloudErrorInfo(th.getMessage(), th.getMessage(), th.toString(), th);
// }
//
// public TypedCloudErrorInfo(@NotNull final String message) {
// this(message, message, null, null);
// }
//
// public TypedCloudErrorInfo(@NotNull final String type, @NotNull final String message) {
// this(type, message, null, null);
// }
//
// public TypedCloudErrorInfo(@NotNull final String type, @NotNull final String message, @Nullable final String details) {
// this(type, message, details, null);
// }
//
// public TypedCloudErrorInfo(@Nullable final String type,
// @Nullable final String message,
// @Nullable final String details,
// @Nullable final Throwable throwable) {
// myType = String.valueOf(type);
// myMessage = String.valueOf(message);
// myDetails = String.valueOf(details);
// myThrowable = throwable;
// }
//
// @NotNull
// public String getType() {
// return myType;
// }
//
// @NotNull
// public String getMessage() {
// return myMessage;
// }
//
// @NotNull
// public String getDetails() {
// return myDetails;
// }
//
// @Nullable
// public Throwable getThrowable() {
// return myThrowable;
// }
//
//
// }
// Path: cloud-vmware-server/src/test/java/jetbrains/buildServer/clouds/base/stubs/DummyApiConnector.java
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import jetbrains.buildServer.clouds.base.connector.AbstractInstance;
import jetbrains.buildServer.clouds.base.connector.CloudApiConnector;
import jetbrains.buildServer.clouds.base.errors.CheckedCloudException;
import jetbrains.buildServer.clouds.base.errors.TypedCloudErrorInfo;
import org.jetbrains.annotations.NotNull;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.clouds.base.stubs;
/**
* Created by Sergey.Pak on 3/4/2016.
*/
public class DummyApiConnector implements CloudApiConnector<DummyCloudImage, DummyCloudInstance> {
private final Map<String, DummyRealInstance> myRealInstanceMap;
private final Map<String, CountDownLatch> myLatchMap;
public DummyApiConnector(final Map<String, DummyRealInstance> realInstanceMap){
myRealInstanceMap = realInstanceMap;
myLatchMap = new HashMap<>();
}
@Override
public void test() throws CheckedCloudException {
checkLatch("test");
}
/**
* A special key of the cloud connector. Used to determine whether this cloud connector can be used in several cloud profiles.
* <br/>
* <p>
* It is supposed to represent the same username and server url/region/instance
*
* @return see above.
*/
@NotNull
@Override
public String getKey() {
return "dummy_connector";
}
@NotNull
@Override | public <R extends AbstractInstance> Map<DummyCloudImage, Map<String, R>> fetchInstances(@NotNull final Collection<DummyCloudImage> images) throws CheckedCloudException { |
JetBrains/teamcity-vmware-plugin | cloud-vmware-server/src/test/java/jetbrains/buildServer/clouds/base/stubs/DummyApiConnector.java | // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/connector/AbstractInstance.java
// public abstract class AbstractInstance {
// @NotNull
// public abstract String getName();
//
// public abstract boolean isInitialized();
//
// public abstract Date getStartDate();
//
// public abstract String getIpAddress();
//
// public abstract InstanceStatus getInstanceStatus();
//
// @Nullable
// public abstract String getProperty(String name);
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/connector/CloudApiConnector.java
// public interface CloudApiConnector<T extends AbstractCloudImage, G extends AbstractCloudInstance> {
//
// void test() throws CheckedCloudException;
//
// /**
// * A special key of the cloud connector. Used to determine whether this cloud connector can be used in several cloud profiles.
// * <br/>
// *
// * It is supposed to represent the same username and server url/region/instance
// * @return see above.
// */
// @NotNull
// String getKey();
//
// @NotNull
// <R extends AbstractInstance> Map<String, R> fetchInstances(@NotNull final T image) throws CheckedCloudException;
//
// @NotNull
// <R extends AbstractInstance> Map<T, Map<String, R>> fetchInstances(@NotNull final Collection<T> images) throws CheckedCloudException;
//
// @NotNull
// @Deprecated
// TypedCloudErrorInfo[] checkImage(@NotNull final T image);
//
// @NotNull
// Map<T, TypedCloudErrorInfo[]> checkImages(@NotNull final Collection<T> images);
//
// @NotNull
// TypedCloudErrorInfo[] checkInstance(@NotNull final G instance);
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/errors/CheckedCloudException.java
// public class CheckedCloudException extends Exception {
//
// public CheckedCloudException(final Throwable cause) {
// super(cause);
// }
//
// public CheckedCloudException(final String message) {
// super(message);
// }
//
// public CheckedCloudException(final String message, final Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/errors/TypedCloudErrorInfo.java
// public class TypedCloudErrorInfo{
// @NotNull private final String myType;
// @NotNull private final String myMessage;
// @NotNull private final String myDetails;
// @Nullable private final Throwable myThrowable;
//
// public static TypedCloudErrorInfo fromException(@NotNull Throwable th){
// return new TypedCloudErrorInfo(th.getMessage(), th.getMessage(), th.toString(), th);
// }
//
// public TypedCloudErrorInfo(@NotNull final String message) {
// this(message, message, null, null);
// }
//
// public TypedCloudErrorInfo(@NotNull final String type, @NotNull final String message) {
// this(type, message, null, null);
// }
//
// public TypedCloudErrorInfo(@NotNull final String type, @NotNull final String message, @Nullable final String details) {
// this(type, message, details, null);
// }
//
// public TypedCloudErrorInfo(@Nullable final String type,
// @Nullable final String message,
// @Nullable final String details,
// @Nullable final Throwable throwable) {
// myType = String.valueOf(type);
// myMessage = String.valueOf(message);
// myDetails = String.valueOf(details);
// myThrowable = throwable;
// }
//
// @NotNull
// public String getType() {
// return myType;
// }
//
// @NotNull
// public String getMessage() {
// return myMessage;
// }
//
// @NotNull
// public String getDetails() {
// return myDetails;
// }
//
// @Nullable
// public Throwable getThrowable() {
// return myThrowable;
// }
//
//
// }
| import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import jetbrains.buildServer.clouds.base.connector.AbstractInstance;
import jetbrains.buildServer.clouds.base.connector.CloudApiConnector;
import jetbrains.buildServer.clouds.base.errors.CheckedCloudException;
import jetbrains.buildServer.clouds.base.errors.TypedCloudErrorInfo;
import org.jetbrains.annotations.NotNull; | * @return see above.
*/
@NotNull
@Override
public String getKey() {
return "dummy_connector";
}
@NotNull
@Override
public <R extends AbstractInstance> Map<DummyCloudImage, Map<String, R>> fetchInstances(@NotNull final Collection<DummyCloudImage> images) throws CheckedCloudException {
Map<DummyCloudImage, Map<String, R>> result = new HashMap<>();
for (DummyCloudImage image: images) {
if (fetchInstances(image).size() > 0)
result.put(image, fetchInstances(image));
}
return result;
}
@NotNull
@Override
public <R extends AbstractInstance> Map<String, R> fetchInstances(@NotNull final DummyCloudImage image) throws CheckedCloudException {
checkLatch("listImageInstances");
return myRealInstanceMap.entrySet().stream()
.filter(e->e.getValue().getDummyImageName().equals(image.getId()))
.collect(Collectors.toMap(e->e.getKey(), e->(R)e.getValue()));
}
@NotNull
@Override | // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/connector/AbstractInstance.java
// public abstract class AbstractInstance {
// @NotNull
// public abstract String getName();
//
// public abstract boolean isInitialized();
//
// public abstract Date getStartDate();
//
// public abstract String getIpAddress();
//
// public abstract InstanceStatus getInstanceStatus();
//
// @Nullable
// public abstract String getProperty(String name);
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/connector/CloudApiConnector.java
// public interface CloudApiConnector<T extends AbstractCloudImage, G extends AbstractCloudInstance> {
//
// void test() throws CheckedCloudException;
//
// /**
// * A special key of the cloud connector. Used to determine whether this cloud connector can be used in several cloud profiles.
// * <br/>
// *
// * It is supposed to represent the same username and server url/region/instance
// * @return see above.
// */
// @NotNull
// String getKey();
//
// @NotNull
// <R extends AbstractInstance> Map<String, R> fetchInstances(@NotNull final T image) throws CheckedCloudException;
//
// @NotNull
// <R extends AbstractInstance> Map<T, Map<String, R>> fetchInstances(@NotNull final Collection<T> images) throws CheckedCloudException;
//
// @NotNull
// @Deprecated
// TypedCloudErrorInfo[] checkImage(@NotNull final T image);
//
// @NotNull
// Map<T, TypedCloudErrorInfo[]> checkImages(@NotNull final Collection<T> images);
//
// @NotNull
// TypedCloudErrorInfo[] checkInstance(@NotNull final G instance);
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/errors/CheckedCloudException.java
// public class CheckedCloudException extends Exception {
//
// public CheckedCloudException(final Throwable cause) {
// super(cause);
// }
//
// public CheckedCloudException(final String message) {
// super(message);
// }
//
// public CheckedCloudException(final String message, final Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/errors/TypedCloudErrorInfo.java
// public class TypedCloudErrorInfo{
// @NotNull private final String myType;
// @NotNull private final String myMessage;
// @NotNull private final String myDetails;
// @Nullable private final Throwable myThrowable;
//
// public static TypedCloudErrorInfo fromException(@NotNull Throwable th){
// return new TypedCloudErrorInfo(th.getMessage(), th.getMessage(), th.toString(), th);
// }
//
// public TypedCloudErrorInfo(@NotNull final String message) {
// this(message, message, null, null);
// }
//
// public TypedCloudErrorInfo(@NotNull final String type, @NotNull final String message) {
// this(type, message, null, null);
// }
//
// public TypedCloudErrorInfo(@NotNull final String type, @NotNull final String message, @Nullable final String details) {
// this(type, message, details, null);
// }
//
// public TypedCloudErrorInfo(@Nullable final String type,
// @Nullable final String message,
// @Nullable final String details,
// @Nullable final Throwable throwable) {
// myType = String.valueOf(type);
// myMessage = String.valueOf(message);
// myDetails = String.valueOf(details);
// myThrowable = throwable;
// }
//
// @NotNull
// public String getType() {
// return myType;
// }
//
// @NotNull
// public String getMessage() {
// return myMessage;
// }
//
// @NotNull
// public String getDetails() {
// return myDetails;
// }
//
// @Nullable
// public Throwable getThrowable() {
// return myThrowable;
// }
//
//
// }
// Path: cloud-vmware-server/src/test/java/jetbrains/buildServer/clouds/base/stubs/DummyApiConnector.java
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import jetbrains.buildServer.clouds.base.connector.AbstractInstance;
import jetbrains.buildServer.clouds.base.connector.CloudApiConnector;
import jetbrains.buildServer.clouds.base.errors.CheckedCloudException;
import jetbrains.buildServer.clouds.base.errors.TypedCloudErrorInfo;
import org.jetbrains.annotations.NotNull;
* @return see above.
*/
@NotNull
@Override
public String getKey() {
return "dummy_connector";
}
@NotNull
@Override
public <R extends AbstractInstance> Map<DummyCloudImage, Map<String, R>> fetchInstances(@NotNull final Collection<DummyCloudImage> images) throws CheckedCloudException {
Map<DummyCloudImage, Map<String, R>> result = new HashMap<>();
for (DummyCloudImage image: images) {
if (fetchInstances(image).size() > 0)
result.put(image, fetchInstances(image));
}
return result;
}
@NotNull
@Override
public <R extends AbstractInstance> Map<String, R> fetchInstances(@NotNull final DummyCloudImage image) throws CheckedCloudException {
checkLatch("listImageInstances");
return myRealInstanceMap.entrySet().stream()
.filter(e->e.getValue().getDummyImageName().equals(image.getId()))
.collect(Collectors.toMap(e->e.getKey(), e->(R)e.getValue()));
}
@NotNull
@Override | public TypedCloudErrorInfo[] checkImage(@NotNull final DummyCloudImage image) { |
JetBrains/teamcity-vmware-plugin | cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/VmwarePropertiesProcessor.java | // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/web/VMWareWebConstants.java
// public class VMWareWebConstants {
//
// public static final String SERVER_URL="vmware_server_url";
// public static final String USERNAME="vmware_username";
// public static final String PASSWORD="vmware_password";
// public static final String PROFILE_INSTANCE_LIMIT="vmware_profile_instance_limit";
//
// public static final String SECURE_PASSWORD = "secure:"+PASSWORD;
//
//
// public String getServerUrl() {
// return SERVER_URL;
// }
//
// public String getUsername() {
// return USERNAME;
// }
//
// public String getPassword() {
// return PASSWORD;
// }
//
// public String getProfileInstanceLimit() {
// return PROFILE_INSTANCE_LIMIT;
// }
// }
| import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import java.util.*;
import java.util.stream.StreamSupport;
import jetbrains.buildServer.clouds.CloudConstants;
import jetbrains.buildServer.clouds.CloudImageParameters;
import jetbrains.buildServer.clouds.server.CloudManagerBase;
import jetbrains.buildServer.clouds.vmware.web.VMWareWebConstants;
import jetbrains.buildServer.serverSide.InvalidProperty;
import jetbrains.buildServer.serverSide.PropertiesProcessor;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.clouds.vmware;
/**
* Created by Sergey.Pak on 1/29/2016.
*/
public class VmwarePropertiesProcessor implements PropertiesProcessor {
@NotNull private final CloudManagerBase myCloudManager;
public VmwarePropertiesProcessor(@NotNull final CloudManagerBase cloudManager){
myCloudManager = cloudManager;
}
@NotNull
public Collection<InvalidProperty> process(final Map<String, String> properties) {
List<InvalidProperty> list = new ArrayList<InvalidProperty>();
// Remove helper properties used in ConfigurationHelperController and GetSnapshotsListController
try {
properties.remove("helperFieldValue");
properties.remove("helperFieldId");
properties.remove("image");
properties.remove("force_trust_manager");
} catch (UnsupportedOperationException ignored) {
// In case of unmodifiable map passed
}
| // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/web/VMWareWebConstants.java
// public class VMWareWebConstants {
//
// public static final String SERVER_URL="vmware_server_url";
// public static final String USERNAME="vmware_username";
// public static final String PASSWORD="vmware_password";
// public static final String PROFILE_INSTANCE_LIMIT="vmware_profile_instance_limit";
//
// public static final String SECURE_PASSWORD = "secure:"+PASSWORD;
//
//
// public String getServerUrl() {
// return SERVER_URL;
// }
//
// public String getUsername() {
// return USERNAME;
// }
//
// public String getPassword() {
// return PASSWORD;
// }
//
// public String getProfileInstanceLimit() {
// return PROFILE_INSTANCE_LIMIT;
// }
// }
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/VmwarePropertiesProcessor.java
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import java.util.*;
import java.util.stream.StreamSupport;
import jetbrains.buildServer.clouds.CloudConstants;
import jetbrains.buildServer.clouds.CloudImageParameters;
import jetbrains.buildServer.clouds.server.CloudManagerBase;
import jetbrains.buildServer.clouds.vmware.web.VMWareWebConstants;
import jetbrains.buildServer.serverSide.InvalidProperty;
import jetbrains.buildServer.serverSide.PropertiesProcessor;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.clouds.vmware;
/**
* Created by Sergey.Pak on 1/29/2016.
*/
public class VmwarePropertiesProcessor implements PropertiesProcessor {
@NotNull private final CloudManagerBase myCloudManager;
public VmwarePropertiesProcessor(@NotNull final CloudManagerBase cloudManager){
myCloudManager = cloudManager;
}
@NotNull
public Collection<InvalidProperty> process(final Map<String, String> properties) {
List<InvalidProperty> list = new ArrayList<InvalidProperty>();
// Remove helper properties used in ConfigurationHelperController and GetSnapshotsListController
try {
properties.remove("helperFieldValue");
properties.remove("helperFieldId");
properties.remove("image");
properties.remove("force_trust_manager");
} catch (UnsupportedOperationException ignored) {
// In case of unmodifiable map passed
}
| notEmpty(properties, VMWareWebConstants.SECURE_PASSWORD, list); |
JetBrains/teamcity-vmware-plugin | cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/VmwareCloudImageDetails.java | // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/beans/CloudImageDetails.java
// public interface CloudImageDetails {
//
// CloneBehaviour getBehaviour();
//
// int getMaxInstances();
//
// String getSourceId();
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/types/CloneBehaviour.java
// public enum CloneBehaviour {
// START_STOP (false, true),
// FRESH_CLONE (true, false),
// ON_DEMAND_CLONE(false, false)
// ;
// private final boolean myDeleteAfterStop;
// private final boolean myUseOriginal;
//
// CloneBehaviour(final boolean deleteAfterStop, final boolean useOriginal) {
// myDeleteAfterStop = deleteAfterStop;
// myUseOriginal = useOriginal;
// }
//
// public boolean isDeleteAfterStop() {
// return myDeleteAfterStop;
// }
//
// public boolean isUseOriginal() {
// return myUseOriginal;
// }
// }
| import jetbrains.buildServer.clouds.CloudImageParameters;
import jetbrains.buildServer.clouds.base.beans.CloudImageDetails;
import jetbrains.buildServer.clouds.base.types.CloneBehaviour;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.clouds.vmware;
/**
* @author Sergey.Pak
* Date: 10/16/2014
* Time: 5:37 PM
*/
public class VmwareCloudImageDetails implements CloudImageDetails {
@Nullable private final String myNickname;
@NotNull private final String mySourceVmName;
private final String myFolderId;
private final String myResourcePoolId;
@NotNull private final String mySnapshotName; | // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/beans/CloudImageDetails.java
// public interface CloudImageDetails {
//
// CloneBehaviour getBehaviour();
//
// int getMaxInstances();
//
// String getSourceId();
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/types/CloneBehaviour.java
// public enum CloneBehaviour {
// START_STOP (false, true),
// FRESH_CLONE (true, false),
// ON_DEMAND_CLONE(false, false)
// ;
// private final boolean myDeleteAfterStop;
// private final boolean myUseOriginal;
//
// CloneBehaviour(final boolean deleteAfterStop, final boolean useOriginal) {
// myDeleteAfterStop = deleteAfterStop;
// myUseOriginal = useOriginal;
// }
//
// public boolean isDeleteAfterStop() {
// return myDeleteAfterStop;
// }
//
// public boolean isUseOriginal() {
// return myUseOriginal;
// }
// }
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/VmwareCloudImageDetails.java
import jetbrains.buildServer.clouds.CloudImageParameters;
import jetbrains.buildServer.clouds.base.beans.CloudImageDetails;
import jetbrains.buildServer.clouds.base.types.CloneBehaviour;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.clouds.vmware;
/**
* @author Sergey.Pak
* Date: 10/16/2014
* Time: 5:37 PM
*/
public class VmwareCloudImageDetails implements CloudImageDetails {
@Nullable private final String myNickname;
@NotNull private final String mySourceVmName;
private final String myFolderId;
private final String myResourcePoolId;
@NotNull private final String mySnapshotName; | private final CloneBehaviour myCloneBehaviour; |
JetBrains/teamcity-vmware-plugin | cloud-vmware-server/src/test/java/jetbrains/buildServer/clouds/base/stubs/DummyImageDetails.java | // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/beans/CloudImageDetails.java
// public interface CloudImageDetails {
//
// CloneBehaviour getBehaviour();
//
// int getMaxInstances();
//
// String getSourceId();
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/types/CloneBehaviour.java
// public enum CloneBehaviour {
// START_STOP (false, true),
// FRESH_CLONE (true, false),
// ON_DEMAND_CLONE(false, false)
// ;
// private final boolean myDeleteAfterStop;
// private final boolean myUseOriginal;
//
// CloneBehaviour(final boolean deleteAfterStop, final boolean useOriginal) {
// myDeleteAfterStop = deleteAfterStop;
// myUseOriginal = useOriginal;
// }
//
// public boolean isDeleteAfterStop() {
// return myDeleteAfterStop;
// }
//
// public boolean isUseOriginal() {
// return myUseOriginal;
// }
// }
| import jetbrains.buildServer.clouds.base.beans.CloudImageDetails;
import jetbrains.buildServer.clouds.base.types.CloneBehaviour; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.clouds.base.stubs;
/**
* Created by Sergey.Pak on 3/4/2016.
*/
public class DummyImageDetails implements CloudImageDetails {
private final String myName;
public DummyImageDetails(final String name) {
myName = name;
}
@Override | // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/beans/CloudImageDetails.java
// public interface CloudImageDetails {
//
// CloneBehaviour getBehaviour();
//
// int getMaxInstances();
//
// String getSourceId();
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/base/types/CloneBehaviour.java
// public enum CloneBehaviour {
// START_STOP (false, true),
// FRESH_CLONE (true, false),
// ON_DEMAND_CLONE(false, false)
// ;
// private final boolean myDeleteAfterStop;
// private final boolean myUseOriginal;
//
// CloneBehaviour(final boolean deleteAfterStop, final boolean useOriginal) {
// myDeleteAfterStop = deleteAfterStop;
// myUseOriginal = useOriginal;
// }
//
// public boolean isDeleteAfterStop() {
// return myDeleteAfterStop;
// }
//
// public boolean isUseOriginal() {
// return myUseOriginal;
// }
// }
// Path: cloud-vmware-server/src/test/java/jetbrains/buildServer/clouds/base/stubs/DummyImageDetails.java
import jetbrains.buildServer.clouds.base.beans.CloudImageDetails;
import jetbrains.buildServer.clouds.base.types.CloneBehaviour;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.clouds.base.stubs;
/**
* Created by Sergey.Pak on 3/4/2016.
*/
public class DummyImageDetails implements CloudImageDetails {
private final String myName;
public DummyImageDetails(final String name) {
myName = name;
}
@Override | public CloneBehaviour getBehaviour() { |
JetBrains/teamcity-vmware-plugin | cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/connector/VmwareUtils.java | // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/connector/beans/FolderBean.java
// public class FolderBean implements VmwareManagedEntity, Comparable<FolderBean> {
// private final String myPath;
// private final String[] myChildType;
// private final String myName;
// private final ManagedObjectReference myMOR;
// private final ManagedObjectReference myParentRef;
// private final String myDatacenterId;
//
// @Used("Tests")
// public FolderBean(final Folder folder){
// this(folder.getMOR(), folder.getName(), null, folder.getChildType(), folder.getParent().getMOR(), "dc");
// }
//
// public FolderBean(@NotNull final ManagedObjectReference mor,
// @NotNull final String name,
// @NotNull final String path,
// @NotNull final String[] childType,
// @Nullable final ManagedObjectReference parentRef,
// @Nullable final String datacenterId) {
// myPath = path;
// myChildType = childType;
// myName = name;
// myMOR = mor;
// myParentRef = parentRef;
// myDatacenterId = datacenterId;
// }
//
// public String[] getChildType() {
// return myChildType;
// }
//
// @NotNull
// @Override
// public String getId() {
// return myMOR.getVal();
// }
//
// public String getName() {
// return myName;
// }
//
// @NotNull
// @Override
// public String getPath() {
// return myPath == null ? myName : myPath;
// }
//
// @Nullable
// @Override
// public String getDatacenterId() {
// return myDatacenterId;
// }
//
// @NotNull
// @Override
// public ManagedObjectReference getMOR() {
// return myMOR;
// }
//
// public ManagedObjectReference getParentMOR() {
// return myParentRef;
// }
//
// @Override
// public int compareTo(@NotNull final FolderBean o) {
// if (myPath == null && o.myPath == null) {
// return StringUtil.compare(StringUtil.toLowerCase(myName), StringUtil.toLowerCase(o.myName));
// }
// return StringUtil.compare(StringUtil.toLowerCase(myPath), StringUtil.toLowerCase(o.myPath));
// }
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/connector/beans/ResourcePoolBean.java
// public class ResourcePoolBean implements VmwareManagedEntity, Comparable<ResourcePoolBean> {
// private final String myName;
// private final ManagedObjectReference myMOR;
// private final String myPath;
// private final ManagedObjectReference myParentRef;
// private final String myDatacenterId;
//
//
// @Used("Tests")
// public ResourcePoolBean(final ResourcePool rp){
// this(rp.getMOR(), rp.getName(), null, rp.getParent().getMOR(), "dc");
// }
//
// public ResourcePoolBean(@NotNull final ManagedObjectReference mor,
// @NotNull final String name,
// @NotNull final String path,
// @Nullable final ManagedObjectReference parentRef,
// @Nullable final String datacenterId) {
// myName = name;
// myMOR = mor;
// myPath = path;
// myParentRef = parentRef;
// myDatacenterId = datacenterId;
// }
//
// @NotNull
// @Override
// public String getId() {
// return myMOR.getVal();
// }
//
// @NotNull
// public String getName() {
// return myName;
// }
//
// @NotNull
// @Override
// public String getPath() {
// return myPath;
// }
//
// @Nullable
// @Override
// public String getDatacenterId() {
// return myDatacenterId;
// }
//
// @NotNull
// @Override
// public ManagedObjectReference getMOR() {
// return myMOR;
// }
//
// @Nullable
// @Override
// public ManagedObjectReference getParentMOR() {
// return myParentRef;
// }
//
// @Override
// public int compareTo(@NotNull final ResourcePoolBean o) {
// if (myPath == null && o.myPath == null){
// return StringUtil.compare(StringUtil.toLowerCase(myName), StringUtil.toLowerCase(o.myName));
// }
// return StringUtil.compare(StringUtil.toLowerCase(myPath), StringUtil.toLowerCase(o.myPath));
// }
// }
| import com.vmware.vim25.mo.Datacenter;
import com.vmware.vim25.mo.Folder;
import com.vmware.vim25.mo.ManagedEntity;
import com.vmware.vim25.mo.ResourcePool;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import jetbrains.buildServer.clouds.vmware.connector.beans.FolderBean;
import jetbrains.buildServer.clouds.vmware.connector.beans.ResourcePoolBean;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | /*
* Copyright 2000-2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.clouds.vmware.connector;
/**
* @author Sergey.Pak
* Date: 2/6/2015
* Time: 5:37 PM
*/
public class VmwareUtils {
private static final String FOLDER_TYPE = Folder.class.getSimpleName();
private static final String RESPOOL_TYPE = ResourcePool.class.getSimpleName();
private static final String SPEC_FOLDER = "vm";
private static final String SPEC_RESPOOL = "Resources";
| // Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/connector/beans/FolderBean.java
// public class FolderBean implements VmwareManagedEntity, Comparable<FolderBean> {
// private final String myPath;
// private final String[] myChildType;
// private final String myName;
// private final ManagedObjectReference myMOR;
// private final ManagedObjectReference myParentRef;
// private final String myDatacenterId;
//
// @Used("Tests")
// public FolderBean(final Folder folder){
// this(folder.getMOR(), folder.getName(), null, folder.getChildType(), folder.getParent().getMOR(), "dc");
// }
//
// public FolderBean(@NotNull final ManagedObjectReference mor,
// @NotNull final String name,
// @NotNull final String path,
// @NotNull final String[] childType,
// @Nullable final ManagedObjectReference parentRef,
// @Nullable final String datacenterId) {
// myPath = path;
// myChildType = childType;
// myName = name;
// myMOR = mor;
// myParentRef = parentRef;
// myDatacenterId = datacenterId;
// }
//
// public String[] getChildType() {
// return myChildType;
// }
//
// @NotNull
// @Override
// public String getId() {
// return myMOR.getVal();
// }
//
// public String getName() {
// return myName;
// }
//
// @NotNull
// @Override
// public String getPath() {
// return myPath == null ? myName : myPath;
// }
//
// @Nullable
// @Override
// public String getDatacenterId() {
// return myDatacenterId;
// }
//
// @NotNull
// @Override
// public ManagedObjectReference getMOR() {
// return myMOR;
// }
//
// public ManagedObjectReference getParentMOR() {
// return myParentRef;
// }
//
// @Override
// public int compareTo(@NotNull final FolderBean o) {
// if (myPath == null && o.myPath == null) {
// return StringUtil.compare(StringUtil.toLowerCase(myName), StringUtil.toLowerCase(o.myName));
// }
// return StringUtil.compare(StringUtil.toLowerCase(myPath), StringUtil.toLowerCase(o.myPath));
// }
// }
//
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/connector/beans/ResourcePoolBean.java
// public class ResourcePoolBean implements VmwareManagedEntity, Comparable<ResourcePoolBean> {
// private final String myName;
// private final ManagedObjectReference myMOR;
// private final String myPath;
// private final ManagedObjectReference myParentRef;
// private final String myDatacenterId;
//
//
// @Used("Tests")
// public ResourcePoolBean(final ResourcePool rp){
// this(rp.getMOR(), rp.getName(), null, rp.getParent().getMOR(), "dc");
// }
//
// public ResourcePoolBean(@NotNull final ManagedObjectReference mor,
// @NotNull final String name,
// @NotNull final String path,
// @Nullable final ManagedObjectReference parentRef,
// @Nullable final String datacenterId) {
// myName = name;
// myMOR = mor;
// myPath = path;
// myParentRef = parentRef;
// myDatacenterId = datacenterId;
// }
//
// @NotNull
// @Override
// public String getId() {
// return myMOR.getVal();
// }
//
// @NotNull
// public String getName() {
// return myName;
// }
//
// @NotNull
// @Override
// public String getPath() {
// return myPath;
// }
//
// @Nullable
// @Override
// public String getDatacenterId() {
// return myDatacenterId;
// }
//
// @NotNull
// @Override
// public ManagedObjectReference getMOR() {
// return myMOR;
// }
//
// @Nullable
// @Override
// public ManagedObjectReference getParentMOR() {
// return myParentRef;
// }
//
// @Override
// public int compareTo(@NotNull final ResourcePoolBean o) {
// if (myPath == null && o.myPath == null){
// return StringUtil.compare(StringUtil.toLowerCase(myName), StringUtil.toLowerCase(o.myName));
// }
// return StringUtil.compare(StringUtil.toLowerCase(myPath), StringUtil.toLowerCase(o.myPath));
// }
// }
// Path: cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/connector/VmwareUtils.java
import com.vmware.vim25.mo.Datacenter;
import com.vmware.vim25.mo.Folder;
import com.vmware.vim25.mo.ManagedEntity;
import com.vmware.vim25.mo.ResourcePool;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import jetbrains.buildServer.clouds.vmware.connector.beans.FolderBean;
import jetbrains.buildServer.clouds.vmware.connector.beans.ResourcePoolBean;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/*
* Copyright 2000-2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.clouds.vmware.connector;
/**
* @author Sergey.Pak
* Date: 2/6/2015
* Time: 5:37 PM
*/
public class VmwareUtils {
private static final String FOLDER_TYPE = Folder.class.getSimpleName();
private static final String RESPOOL_TYPE = ResourcePool.class.getSimpleName();
private static final String SPEC_FOLDER = "vm";
private static final String SPEC_RESPOOL = "Resources";
| static boolean isSpecial(@NotNull final ResourcePoolBean pool){ |
mulesoft/mule-cookbook | rest-server/src/main/java/com/cookbook/tutorial/MuleAuthorizeResource.java | // Path: soap-server/src/main/java/com/cookbook/tutorial/service/Constants.java
// public class Constants {
// public static final String DEFAULT_TOKEN = "ASD9807123#123POI";
// }
| import com.cookbook.tutorial.service.Constants;
import org.mule.module.http.internal.ParameterMap;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.HashMap;
import java.util.Map; | package com.cookbook.tutorial;
@Path("/oauth")
public class MuleAuthorizeResource {
@GET
@Path("/authorize")
@Produces(MediaType.APPLICATION_JSON)
public Response authorize(@QueryParam("client_id") String accountId, @QueryParam("redirect_uri") String redirectTo) {
if (CLIENT_ID.equals(accountId)) {
return Response.status(302).location(
UriBuilder.fromUri(redirectTo).queryParam("code", new String[] { CODE }).build()).build();
} else {
return Response.status(400).entity(
UriBuilder.fromUri(redirectTo).queryParam("error", new String[] { "invalid_client" }).build()).build();
}
}
@POST
@Path("/accessToken")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response token(InputStream params) {
try {
ObjectInputStream objectReader = new ObjectInputStream(params);
ParameterMap parameterMap = (ParameterMap)objectReader.readObject();
if (parameterMap.get("code").equals(CODE) &&
parameterMap.get("client_id").equals(CLIENT_ID) &&
parameterMap.get("client_secret").equals(CLIENT_SECRET)
) {
Map<String, Object> map = new HashMap<>(); | // Path: soap-server/src/main/java/com/cookbook/tutorial/service/Constants.java
// public class Constants {
// public static final String DEFAULT_TOKEN = "ASD9807123#123POI";
// }
// Path: rest-server/src/main/java/com/cookbook/tutorial/MuleAuthorizeResource.java
import com.cookbook.tutorial.service.Constants;
import org.mule.module.http.internal.ParameterMap;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.HashMap;
import java.util.Map;
package com.cookbook.tutorial;
@Path("/oauth")
public class MuleAuthorizeResource {
@GET
@Path("/authorize")
@Produces(MediaType.APPLICATION_JSON)
public Response authorize(@QueryParam("client_id") String accountId, @QueryParam("redirect_uri") String redirectTo) {
if (CLIENT_ID.equals(accountId)) {
return Response.status(302).location(
UriBuilder.fromUri(redirectTo).queryParam("code", new String[] { CODE }).build()).build();
} else {
return Response.status(400).entity(
UriBuilder.fromUri(redirectTo).queryParam("error", new String[] { "invalid_client" }).build()).build();
}
}
@POST
@Path("/accessToken")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response token(InputStream params) {
try {
ObjectInputStream objectReader = new ObjectInputStream(params);
ParameterMap parameterMap = (ParameterMap)objectReader.readObject();
if (parameterMap.get("code").equals(CODE) &&
parameterMap.get("client_id").equals(CLIENT_ID) &&
parameterMap.get("client_secret").equals(CLIENT_SECRET)
) {
Map<String, Object> map = new HashMap<>(); | map.put("access_token", Constants.DEFAULT_TOKEN); |
mulesoft/mule-cookbook | soap-server/src/main/java/com/cookbook/tutorial/service/MuleCookBookServiceImpl.java | // Path: soap-server/src/main/java/com/cookbook/tutorial/internal/service/ObjectFactorySingleton.java
// public class ObjectFactorySingleton {
//
// private static ObjectFactory factory;
//
// public static ObjectFactory getInstance() {
// if (factory == null)
// factory = new ObjectFactory();
// return factory;
// }
// }
| import com.cookbook.tutorial.internal.service.ObjectFactorySingleton;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.soap.SOAPBinding;
import java.util.*;
import java.util.logging.Logger; | package com.cookbook.tutorial.service;
/**
* Created by Mulesoft.
*/
@javax.jws.WebService(
serviceName = "IMuleCookBookServiceService",
portName = "IMuleCookBookServicePort",
targetNamespace = "http://service.tutorial.cookbook.com/",
wsdlLocation = "wsdl/IMuleCookBookService.wsdl")
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
public class MuleCookBookServiceImpl implements IMuleCookBookService {
private static final Logger logger = Logger.getLogger(MuleCookBookServiceImpl.class.getName());
private Integer currentIndex = 0;
private Integer exceptionRatio = 10;
private IDAOCookBookService serviceDAL;
public MuleCookBookServiceImpl(){
serviceDAL = DAOCookBookServiceFactory.getInstance();
}
@Override
public CreateResponse create(@WebParam(partName = "parameters", name = "create", targetNamespace = "http://service.tutorial.cookbook.com/") Create parameters,
@WebParam(partName = "token", name = "token", targetNamespace = "http://service.tutorial.cookbook.com/", header = true) String token)
throws InvalidTokenException, SessionExpiredException, InvalidEntityException {
verifyToken(token);
checkExpiredSessionCondition(); | // Path: soap-server/src/main/java/com/cookbook/tutorial/internal/service/ObjectFactorySingleton.java
// public class ObjectFactorySingleton {
//
// private static ObjectFactory factory;
//
// public static ObjectFactory getInstance() {
// if (factory == null)
// factory = new ObjectFactory();
// return factory;
// }
// }
// Path: soap-server/src/main/java/com/cookbook/tutorial/service/MuleCookBookServiceImpl.java
import com.cookbook.tutorial.internal.service.ObjectFactorySingleton;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.soap.SOAPBinding;
import java.util.*;
import java.util.logging.Logger;
package com.cookbook.tutorial.service;
/**
* Created by Mulesoft.
*/
@javax.jws.WebService(
serviceName = "IMuleCookBookServiceService",
portName = "IMuleCookBookServicePort",
targetNamespace = "http://service.tutorial.cookbook.com/",
wsdlLocation = "wsdl/IMuleCookBookService.wsdl")
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
public class MuleCookBookServiceImpl implements IMuleCookBookService {
private static final Logger logger = Logger.getLogger(MuleCookBookServiceImpl.class.getName());
private Integer currentIndex = 0;
private Integer exceptionRatio = 10;
private IDAOCookBookService serviceDAL;
public MuleCookBookServiceImpl(){
serviceDAL = DAOCookBookServiceFactory.getInstance();
}
@Override
public CreateResponse create(@WebParam(partName = "parameters", name = "create", targetNamespace = "http://service.tutorial.cookbook.com/") Create parameters,
@WebParam(partName = "token", name = "token", targetNamespace = "http://service.tutorial.cookbook.com/", header = true) String token)
throws InvalidTokenException, SessionExpiredException, InvalidEntityException {
verifyToken(token);
checkExpiredSessionCondition(); | CreateResponse response = ObjectFactorySingleton.getInstance().createCreateResponse(); |
mulesoft/mule-cookbook | soap-server/src/test/java/com/cookbook/tutorial/service/DsqlParserTest.java | // Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/Constants.java
// public class Constants {
// public static final String INGREDIENT = "INGREDIENT";
// public static final String RECIPE = "RECIPE";
// public static final String ALL = "ALL";
// }
| import com.cookbook.tutorial.internal.dsql.*;
import com.cookbook.tutorial.internal.dsql.Constants;
import org.junit.Before;
import org.junit.Test;
import org.parboiled.Parboiled;
import org.parboiled.parserunners.ReportingParseRunner;
import org.parboiled.support.ParseTreeUtils;
import org.parboiled.support.ParsingResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.Assert.*; | ParsingResult<?> result = new ReportingParseRunner(parser.Statement()).run(input);
assertFalse("Foo is not a valid Entity Type", result.hasErrors());
}
@Test
public void validInvalidFieldExpression(){
String input = "GET foo FROM INGREDIENT";
ParsingResult<?> result = new ReportingParseRunner(parser.Statement()).run(input);
assertTrue("foo is not a valid field", result.hasErrors());
}
@Test
public void validWhereExpression(){
String input = "GET name FROM INGREDIENT MATCHING id==1";
ParsingResult<?> result = new ReportingParseRunner(parser.Statement()).run(input);
assertFalse("Fail to process query", result.hasErrors());
}
@Test
public void validWhereExpressionContains(){
String input = "GET ALL FROM RECIPE MATCHING id contains 1";
ParsingResult<?> result = new ReportingParseRunner(parser.Statement()).run(input);
assertFalse("Fail to process query", result.hasErrors());
}
@Test
public void getBasicQuery(){
String input = "GET ALL FROM INGREDIENT";
ParsingResult<?> result = new ReportingParseRunner(parser.Statement()).run(input);
Dsql dsql = Dsql.newInstance(input); | // Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/Constants.java
// public class Constants {
// public static final String INGREDIENT = "INGREDIENT";
// public static final String RECIPE = "RECIPE";
// public static final String ALL = "ALL";
// }
// Path: soap-server/src/test/java/com/cookbook/tutorial/service/DsqlParserTest.java
import com.cookbook.tutorial.internal.dsql.*;
import com.cookbook.tutorial.internal.dsql.Constants;
import org.junit.Before;
import org.junit.Test;
import org.parboiled.Parboiled;
import org.parboiled.parserunners.ReportingParseRunner;
import org.parboiled.support.ParseTreeUtils;
import org.parboiled.support.ParsingResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.Assert.*;
ParsingResult<?> result = new ReportingParseRunner(parser.Statement()).run(input);
assertFalse("Foo is not a valid Entity Type", result.hasErrors());
}
@Test
public void validInvalidFieldExpression(){
String input = "GET foo FROM INGREDIENT";
ParsingResult<?> result = new ReportingParseRunner(parser.Statement()).run(input);
assertTrue("foo is not a valid field", result.hasErrors());
}
@Test
public void validWhereExpression(){
String input = "GET name FROM INGREDIENT MATCHING id==1";
ParsingResult<?> result = new ReportingParseRunner(parser.Statement()).run(input);
assertFalse("Fail to process query", result.hasErrors());
}
@Test
public void validWhereExpressionContains(){
String input = "GET ALL FROM RECIPE MATCHING id contains 1";
ParsingResult<?> result = new ReportingParseRunner(parser.Statement()).run(input);
assertFalse("Fail to process query", result.hasErrors());
}
@Test
public void getBasicQuery(){
String input = "GET ALL FROM INGREDIENT";
ParsingResult<?> result = new ReportingParseRunner(parser.Statement()).run(input);
Dsql dsql = Dsql.newInstance(input); | assertEquals(Constants.INGREDIENT,dsql.getEntity()); |
mulesoft/mule-cookbook | rest-server/src/main/java/com/cookbook/tutorial/AuthorizeResource.java | // Path: soap-server/src/main/java/com/cookbook/tutorial/service/Constants.java
// public class Constants {
// public static final String DEFAULT_TOKEN = "ASD9807123#123POI";
// }
//
// Path: webservice/src/main/java/com/cookbook/tutorial/service/InvalidEntityException.java
// @WebFault(name = "InvalidEntity", faultBean = "com.cookbook.tutorial.service.FaultBean")
// @XmlAccessorType(XmlAccessType.FIELD)
// @XmlRootElement
// public class InvalidEntityException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Field containing the CookBook entity that caused the exception
// */
// private FaultBean faultBean;
//
// public InvalidEntityException(){
//
// }
//
// public InvalidEntityException(String message, FaultBean faultBean, Throwable cause) {
// super(message, cause);
// this.faultBean = faultBean;
// }
//
// public InvalidEntityException(String message, FaultBean faultBean) {
// super(message);
// this.faultBean = faultBean;
// }
//
// public FaultBean getFaultBean() {
// return faultBean;
// }
//
// public void setFaultBean(FaultBean faultBean) {
// this.faultBean = faultBean;
// }
// }
//
// Path: webservice/src/main/java/com/cookbook/tutorial/service/NoSuchEntityException.java
// @WebFault(name = "NoSuchEntity", faultBean = "com.cookbook.tutorial.service.FaultBean")
// @XmlAccessorType(XmlAccessType.FIELD)
// @XmlRootElement
// public class NoSuchEntityException extends RuntimeException {
// private static final long serialVersionUID = 1L;
//
// /**
// * Field containing the CookBook entity that caused the exception
// */
// private FaultBean faultBean;
//
// public NoSuchEntityException(){
//
// }
//
// public NoSuchEntityException(String message, FaultBean faultBean, Throwable cause) {
// super(message, cause);
// this.faultBean = faultBean;
// }
//
// public NoSuchEntityException(String message, FaultBean faultBean) {
// super(message);
// this.faultBean = faultBean;
// }
//
// public FaultBean getFaultBean() {
// return faultBean;
// }
//
// public void setFaultBean(FaultBean faultBean) {
// this.faultBean = faultBean;
// }
// }
| import com.cookbook.tutorial.service.Constants;
import com.cookbook.tutorial.service.InvalidEntityException;
import com.cookbook.tutorial.service.NoSuchEntityException;
import com.cookbook.tutorial.service.Recipe;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.net.URI;
import java.util.HashMap;
import java.util.Map; | package com.cookbook.tutorial;
@Path("/oauth")
public class AuthorizeResource {
@GET
@Path("/authorize")
@Produces(MediaType.APPLICATION_JSON)
public Response authorize(@QueryParam("client_id") String accountId, @QueryParam("redirect_uri") String redirectTo) {
if (CLIENT_ID.equals(accountId)) {
return Response.status(302).location(
UriBuilder.fromUri(redirectTo).queryParam("code", new String[] { CODE }).build()).build();
} else {
return Response.status(400).entity(
UriBuilder.fromUri(redirectTo).queryParam("error", new String[] { "invalid_client" }).build()).build();
}
}
@POST
@Path("/accessToken")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response token(MultivaluedMap<String, String> params) {
try {
if (params.get("code").get(0).equals(CODE) &&
params.get("client_id").get(0).equals(CLIENT_ID) &&
params.get("client_secret").get(0).equals(CLIENT_SECRET)
) {
Map<String, Object> map = new HashMap<>(); | // Path: soap-server/src/main/java/com/cookbook/tutorial/service/Constants.java
// public class Constants {
// public static final String DEFAULT_TOKEN = "ASD9807123#123POI";
// }
//
// Path: webservice/src/main/java/com/cookbook/tutorial/service/InvalidEntityException.java
// @WebFault(name = "InvalidEntity", faultBean = "com.cookbook.tutorial.service.FaultBean")
// @XmlAccessorType(XmlAccessType.FIELD)
// @XmlRootElement
// public class InvalidEntityException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// /**
// * Field containing the CookBook entity that caused the exception
// */
// private FaultBean faultBean;
//
// public InvalidEntityException(){
//
// }
//
// public InvalidEntityException(String message, FaultBean faultBean, Throwable cause) {
// super(message, cause);
// this.faultBean = faultBean;
// }
//
// public InvalidEntityException(String message, FaultBean faultBean) {
// super(message);
// this.faultBean = faultBean;
// }
//
// public FaultBean getFaultBean() {
// return faultBean;
// }
//
// public void setFaultBean(FaultBean faultBean) {
// this.faultBean = faultBean;
// }
// }
//
// Path: webservice/src/main/java/com/cookbook/tutorial/service/NoSuchEntityException.java
// @WebFault(name = "NoSuchEntity", faultBean = "com.cookbook.tutorial.service.FaultBean")
// @XmlAccessorType(XmlAccessType.FIELD)
// @XmlRootElement
// public class NoSuchEntityException extends RuntimeException {
// private static final long serialVersionUID = 1L;
//
// /**
// * Field containing the CookBook entity that caused the exception
// */
// private FaultBean faultBean;
//
// public NoSuchEntityException(){
//
// }
//
// public NoSuchEntityException(String message, FaultBean faultBean, Throwable cause) {
// super(message, cause);
// this.faultBean = faultBean;
// }
//
// public NoSuchEntityException(String message, FaultBean faultBean) {
// super(message);
// this.faultBean = faultBean;
// }
//
// public FaultBean getFaultBean() {
// return faultBean;
// }
//
// public void setFaultBean(FaultBean faultBean) {
// this.faultBean = faultBean;
// }
// }
// Path: rest-server/src/main/java/com/cookbook/tutorial/AuthorizeResource.java
import com.cookbook.tutorial.service.Constants;
import com.cookbook.tutorial.service.InvalidEntityException;
import com.cookbook.tutorial.service.NoSuchEntityException;
import com.cookbook.tutorial.service.Recipe;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
package com.cookbook.tutorial;
@Path("/oauth")
public class AuthorizeResource {
@GET
@Path("/authorize")
@Produces(MediaType.APPLICATION_JSON)
public Response authorize(@QueryParam("client_id") String accountId, @QueryParam("redirect_uri") String redirectTo) {
if (CLIENT_ID.equals(accountId)) {
return Response.status(302).location(
UriBuilder.fromUri(redirectTo).queryParam("code", new String[] { CODE }).build()).build();
} else {
return Response.status(400).entity(
UriBuilder.fromUri(redirectTo).queryParam("error", new String[] { "invalid_client" }).build()).build();
}
}
@POST
@Path("/accessToken")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Response token(MultivaluedMap<String, String> params) {
try {
if (params.get("code").get(0).equals(CODE) &&
params.get("client_id").get(0).equals(CLIENT_ID) &&
params.get("client_secret").get(0).equals(CLIENT_SECRET)
) {
Map<String, Object> map = new HashMap<>(); | map.put("access_token", Constants.DEFAULT_TOKEN); |
mulesoft/mule-cookbook | soap-server/src/main/java/com/cookbook/tutorial/internal/service/CookBookDefaultBackEndImp.java | // Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/Constants.java
// public class Constants {
// public static final String INGREDIENT = "INGREDIENT";
// public static final String RECIPE = "RECIPE";
// public static final String ALL = "ALL";
// }
//
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/CookBookQuery.java
// public interface CookBookQuery {
// boolean getAllFields();
// List<String> getFields();
// String getEntity();
// List<String> getCriteria();
// }
//
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/Dsql.java
// public class Dsql implements CookBookQuery{
// private final Pattern queryPattern = Pattern.compile("GET (.*) FROM ([\\w]*)( MATCHING (.*))?");
//
// private final Matcher matcher;
//
// public static Dsql newInstance(String query){
// return new Dsql(query);
// }
//
// private Dsql(String query){
// matcher=queryPattern.matcher(query);
// if(!matcher.matches()){
// throw new RuntimeException("Don't know how to process:"+query);
// }
// }
//
// @Override
// public boolean getAllFields() {
// return matcher.group(1).equals(Constants.ALL);
// }
//
// @Override
// public List<String> getFields() {
// return Arrays.asList(matcher.group(1).split(","));
// }
//
// @Override
// public String getEntity() {
// return matcher.group(2);
// }
//
// @Override
// public List<String> getCriteria() {
// if(matcher.groupCount()==4 && matcher.group(4)!=null) {
// return Arrays.asList(matcher.group(4).split(","));
// }
// return Collections.EMPTY_LIST;
// }
// }
//
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/DsqlParser.java
// @BuildParseTree
// public class DsqlParser extends BaseParser<Object>{
//
// public Rule Statement(){
// return Sequence(
// String("GET"),
// Ch(' '),
// Fields(),
// Ch(' '),
// String("FROM"),
// Ch(' '),
// Entities(),
// Clause(),
// EOI
// );
// }
//
// public Rule Fields() {
// return FirstOf(
// String("ALL"), OneOrMore(
// Sequence(
// Field(), ZeroOrMore(Ch(','), Field()))
// )
// );
// }
//
// public Rule Entities(){
// return FirstOf(String(Constants.INGREDIENT),String(Constants.RECIPE));
// }
//
// public Rule Clause(){
// return Optional(
// Sequence(
// Ch(' '),
// String("MATCHING"),
// Ch(' '),
// Sequence(
// Comparison(),ZeroOrMore(Ch(','),Comparison())
// )
// )
// );
// }
//
// public Rule Field(){
// return FirstOf(
// String("id"),
// String("created"),
// String("lastModified"),
// String("name"),
// String("quantity"),
// String("unit"),
// String("prepTime"),
// String("cookTime"),
// String("ingredients")
// );
// }
//
//
// public Rule Comparison(){
// return FirstOf(
// Sequence(AlphaNumeric(), Spacing(), Operator(),Spacing(), Field()), Sequence(Field(),Spacing(), Operator(),Spacing(), AlphaNumeric()));
// }
//
// public Rule Operator(){
// return FirstOf(
// String("=="),
// String("<>"),
// String(">"),
// String("<"),
// String(">="),
// String("<="),
// String("contains")
// );
// }
//
// public Rule AlphaNumeric(){
// return OneOrMore(FirstOf(CharRange('a','z'),CharRange('0','9'))
// );
// }
//
// public Rule Spacing(){
// return ZeroOrMore(Ch(' '));
// }
//
// }
| import com.cookbook.tutorial.internal.dsql.Constants;
import com.cookbook.tutorial.internal.dsql.CookBookQuery;
import com.cookbook.tutorial.internal.dsql.Dsql;
import com.cookbook.tutorial.internal.dsql.DsqlParser;
import com.cookbook.tutorial.service.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.cxf.common.util.CollectionUtils;
import org.parboiled.Parboiled;
import org.parboiled.common.FileUtils;
import org.parboiled.parserunners.ReportingParseRunner;
import org.parboiled.support.ParsingResult;
import javax.jws.WebParam;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import java.lang.reflect.Type;
import java.util.*; |
@Override
public List<CookBookEntity> updateList(@WebParam(name = "entities", targetNamespace = "") List<CookBookEntity> entities)
throws NoSuchEntityException, InvalidEntityException {
for (CookBookEntity entity : entities) {
update(entity);
}
return entities;
}
@Override
public void deleteList(@WebParam(name = "entityIds", targetNamespace = "") List<Integer> entityIds) throws NoSuchEntityException {
for (Integer id : entityIds) {
delete(id);
}
}
@Override
public List<CookBookEntity> addList(@WebParam(name = "entities", targetNamespace = "") List<CookBookEntity> entities)
throws InvalidEntityException {
for (CookBookEntity entity : entities) {
create(entity);
}
return entities;
}
@Override
public List<CookBookEntity> searchWithQuery(@WebParam(name = "query", targetNamespace = "") String query, @WebParam(name = "page", targetNamespace = "") Integer page,
@WebParam(name = "pageSize", targetNamespace = "") Integer pageSize) throws InvalidRequestException {
| // Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/Constants.java
// public class Constants {
// public static final String INGREDIENT = "INGREDIENT";
// public static final String RECIPE = "RECIPE";
// public static final String ALL = "ALL";
// }
//
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/CookBookQuery.java
// public interface CookBookQuery {
// boolean getAllFields();
// List<String> getFields();
// String getEntity();
// List<String> getCriteria();
// }
//
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/Dsql.java
// public class Dsql implements CookBookQuery{
// private final Pattern queryPattern = Pattern.compile("GET (.*) FROM ([\\w]*)( MATCHING (.*))?");
//
// private final Matcher matcher;
//
// public static Dsql newInstance(String query){
// return new Dsql(query);
// }
//
// private Dsql(String query){
// matcher=queryPattern.matcher(query);
// if(!matcher.matches()){
// throw new RuntimeException("Don't know how to process:"+query);
// }
// }
//
// @Override
// public boolean getAllFields() {
// return matcher.group(1).equals(Constants.ALL);
// }
//
// @Override
// public List<String> getFields() {
// return Arrays.asList(matcher.group(1).split(","));
// }
//
// @Override
// public String getEntity() {
// return matcher.group(2);
// }
//
// @Override
// public List<String> getCriteria() {
// if(matcher.groupCount()==4 && matcher.group(4)!=null) {
// return Arrays.asList(matcher.group(4).split(","));
// }
// return Collections.EMPTY_LIST;
// }
// }
//
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/DsqlParser.java
// @BuildParseTree
// public class DsqlParser extends BaseParser<Object>{
//
// public Rule Statement(){
// return Sequence(
// String("GET"),
// Ch(' '),
// Fields(),
// Ch(' '),
// String("FROM"),
// Ch(' '),
// Entities(),
// Clause(),
// EOI
// );
// }
//
// public Rule Fields() {
// return FirstOf(
// String("ALL"), OneOrMore(
// Sequence(
// Field(), ZeroOrMore(Ch(','), Field()))
// )
// );
// }
//
// public Rule Entities(){
// return FirstOf(String(Constants.INGREDIENT),String(Constants.RECIPE));
// }
//
// public Rule Clause(){
// return Optional(
// Sequence(
// Ch(' '),
// String("MATCHING"),
// Ch(' '),
// Sequence(
// Comparison(),ZeroOrMore(Ch(','),Comparison())
// )
// )
// );
// }
//
// public Rule Field(){
// return FirstOf(
// String("id"),
// String("created"),
// String("lastModified"),
// String("name"),
// String("quantity"),
// String("unit"),
// String("prepTime"),
// String("cookTime"),
// String("ingredients")
// );
// }
//
//
// public Rule Comparison(){
// return FirstOf(
// Sequence(AlphaNumeric(), Spacing(), Operator(),Spacing(), Field()), Sequence(Field(),Spacing(), Operator(),Spacing(), AlphaNumeric()));
// }
//
// public Rule Operator(){
// return FirstOf(
// String("=="),
// String("<>"),
// String(">"),
// String("<"),
// String(">="),
// String("<="),
// String("contains")
// );
// }
//
// public Rule AlphaNumeric(){
// return OneOrMore(FirstOf(CharRange('a','z'),CharRange('0','9'))
// );
// }
//
// public Rule Spacing(){
// return ZeroOrMore(Ch(' '));
// }
//
// }
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/service/CookBookDefaultBackEndImp.java
import com.cookbook.tutorial.internal.dsql.Constants;
import com.cookbook.tutorial.internal.dsql.CookBookQuery;
import com.cookbook.tutorial.internal.dsql.Dsql;
import com.cookbook.tutorial.internal.dsql.DsqlParser;
import com.cookbook.tutorial.service.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.cxf.common.util.CollectionUtils;
import org.parboiled.Parboiled;
import org.parboiled.common.FileUtils;
import org.parboiled.parserunners.ReportingParseRunner;
import org.parboiled.support.ParsingResult;
import javax.jws.WebParam;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import java.lang.reflect.Type;
import java.util.*;
@Override
public List<CookBookEntity> updateList(@WebParam(name = "entities", targetNamespace = "") List<CookBookEntity> entities)
throws NoSuchEntityException, InvalidEntityException {
for (CookBookEntity entity : entities) {
update(entity);
}
return entities;
}
@Override
public void deleteList(@WebParam(name = "entityIds", targetNamespace = "") List<Integer> entityIds) throws NoSuchEntityException {
for (Integer id : entityIds) {
delete(id);
}
}
@Override
public List<CookBookEntity> addList(@WebParam(name = "entities", targetNamespace = "") List<CookBookEntity> entities)
throws InvalidEntityException {
for (CookBookEntity entity : entities) {
create(entity);
}
return entities;
}
@Override
public List<CookBookEntity> searchWithQuery(@WebParam(name = "query", targetNamespace = "") String query, @WebParam(name = "page", targetNamespace = "") Integer page,
@WebParam(name = "pageSize", targetNamespace = "") Integer pageSize) throws InvalidRequestException {
| DsqlParser parser = Parboiled.createParser(DsqlParser.class); |
mulesoft/mule-cookbook | soap-server/src/main/java/com/cookbook/tutorial/internal/service/CookBookDefaultBackEndImp.java | // Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/Constants.java
// public class Constants {
// public static final String INGREDIENT = "INGREDIENT";
// public static final String RECIPE = "RECIPE";
// public static final String ALL = "ALL";
// }
//
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/CookBookQuery.java
// public interface CookBookQuery {
// boolean getAllFields();
// List<String> getFields();
// String getEntity();
// List<String> getCriteria();
// }
//
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/Dsql.java
// public class Dsql implements CookBookQuery{
// private final Pattern queryPattern = Pattern.compile("GET (.*) FROM ([\\w]*)( MATCHING (.*))?");
//
// private final Matcher matcher;
//
// public static Dsql newInstance(String query){
// return new Dsql(query);
// }
//
// private Dsql(String query){
// matcher=queryPattern.matcher(query);
// if(!matcher.matches()){
// throw new RuntimeException("Don't know how to process:"+query);
// }
// }
//
// @Override
// public boolean getAllFields() {
// return matcher.group(1).equals(Constants.ALL);
// }
//
// @Override
// public List<String> getFields() {
// return Arrays.asList(matcher.group(1).split(","));
// }
//
// @Override
// public String getEntity() {
// return matcher.group(2);
// }
//
// @Override
// public List<String> getCriteria() {
// if(matcher.groupCount()==4 && matcher.group(4)!=null) {
// return Arrays.asList(matcher.group(4).split(","));
// }
// return Collections.EMPTY_LIST;
// }
// }
//
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/DsqlParser.java
// @BuildParseTree
// public class DsqlParser extends BaseParser<Object>{
//
// public Rule Statement(){
// return Sequence(
// String("GET"),
// Ch(' '),
// Fields(),
// Ch(' '),
// String("FROM"),
// Ch(' '),
// Entities(),
// Clause(),
// EOI
// );
// }
//
// public Rule Fields() {
// return FirstOf(
// String("ALL"), OneOrMore(
// Sequence(
// Field(), ZeroOrMore(Ch(','), Field()))
// )
// );
// }
//
// public Rule Entities(){
// return FirstOf(String(Constants.INGREDIENT),String(Constants.RECIPE));
// }
//
// public Rule Clause(){
// return Optional(
// Sequence(
// Ch(' '),
// String("MATCHING"),
// Ch(' '),
// Sequence(
// Comparison(),ZeroOrMore(Ch(','),Comparison())
// )
// )
// );
// }
//
// public Rule Field(){
// return FirstOf(
// String("id"),
// String("created"),
// String("lastModified"),
// String("name"),
// String("quantity"),
// String("unit"),
// String("prepTime"),
// String("cookTime"),
// String("ingredients")
// );
// }
//
//
// public Rule Comparison(){
// return FirstOf(
// Sequence(AlphaNumeric(), Spacing(), Operator(),Spacing(), Field()), Sequence(Field(),Spacing(), Operator(),Spacing(), AlphaNumeric()));
// }
//
// public Rule Operator(){
// return FirstOf(
// String("=="),
// String("<>"),
// String(">"),
// String("<"),
// String(">="),
// String("<="),
// String("contains")
// );
// }
//
// public Rule AlphaNumeric(){
// return OneOrMore(FirstOf(CharRange('a','z'),CharRange('0','9'))
// );
// }
//
// public Rule Spacing(){
// return ZeroOrMore(Ch(' '));
// }
//
// }
| import com.cookbook.tutorial.internal.dsql.Constants;
import com.cookbook.tutorial.internal.dsql.CookBookQuery;
import com.cookbook.tutorial.internal.dsql.Dsql;
import com.cookbook.tutorial.internal.dsql.DsqlParser;
import com.cookbook.tutorial.service.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.cxf.common.util.CollectionUtils;
import org.parboiled.Parboiled;
import org.parboiled.common.FileUtils;
import org.parboiled.parserunners.ReportingParseRunner;
import org.parboiled.support.ParsingResult;
import javax.jws.WebParam;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import java.lang.reflect.Type;
import java.util.*; | }
return entities;
}
@Override
public void deleteList(@WebParam(name = "entityIds", targetNamespace = "") List<Integer> entityIds) throws NoSuchEntityException {
for (Integer id : entityIds) {
delete(id);
}
}
@Override
public List<CookBookEntity> addList(@WebParam(name = "entities", targetNamespace = "") List<CookBookEntity> entities)
throws InvalidEntityException {
for (CookBookEntity entity : entities) {
create(entity);
}
return entities;
}
@Override
public List<CookBookEntity> searchWithQuery(@WebParam(name = "query", targetNamespace = "") String query, @WebParam(name = "page", targetNamespace = "") Integer page,
@WebParam(name = "pageSize", targetNamespace = "") Integer pageSize) throws InvalidRequestException {
DsqlParser parser = Parboiled.createParser(DsqlParser.class);
ParsingResult<?> result = new ReportingParseRunner(parser.Statement()).run(query);
if (result.hasErrors()) {
throw new InvalidRequestException(result.parseErrors.get(0).getErrorMessage());
}
List<CookBookEntity> searchResult = new ArrayList<>(); | // Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/Constants.java
// public class Constants {
// public static final String INGREDIENT = "INGREDIENT";
// public static final String RECIPE = "RECIPE";
// public static final String ALL = "ALL";
// }
//
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/CookBookQuery.java
// public interface CookBookQuery {
// boolean getAllFields();
// List<String> getFields();
// String getEntity();
// List<String> getCriteria();
// }
//
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/Dsql.java
// public class Dsql implements CookBookQuery{
// private final Pattern queryPattern = Pattern.compile("GET (.*) FROM ([\\w]*)( MATCHING (.*))?");
//
// private final Matcher matcher;
//
// public static Dsql newInstance(String query){
// return new Dsql(query);
// }
//
// private Dsql(String query){
// matcher=queryPattern.matcher(query);
// if(!matcher.matches()){
// throw new RuntimeException("Don't know how to process:"+query);
// }
// }
//
// @Override
// public boolean getAllFields() {
// return matcher.group(1).equals(Constants.ALL);
// }
//
// @Override
// public List<String> getFields() {
// return Arrays.asList(matcher.group(1).split(","));
// }
//
// @Override
// public String getEntity() {
// return matcher.group(2);
// }
//
// @Override
// public List<String> getCriteria() {
// if(matcher.groupCount()==4 && matcher.group(4)!=null) {
// return Arrays.asList(matcher.group(4).split(","));
// }
// return Collections.EMPTY_LIST;
// }
// }
//
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/DsqlParser.java
// @BuildParseTree
// public class DsqlParser extends BaseParser<Object>{
//
// public Rule Statement(){
// return Sequence(
// String("GET"),
// Ch(' '),
// Fields(),
// Ch(' '),
// String("FROM"),
// Ch(' '),
// Entities(),
// Clause(),
// EOI
// );
// }
//
// public Rule Fields() {
// return FirstOf(
// String("ALL"), OneOrMore(
// Sequence(
// Field(), ZeroOrMore(Ch(','), Field()))
// )
// );
// }
//
// public Rule Entities(){
// return FirstOf(String(Constants.INGREDIENT),String(Constants.RECIPE));
// }
//
// public Rule Clause(){
// return Optional(
// Sequence(
// Ch(' '),
// String("MATCHING"),
// Ch(' '),
// Sequence(
// Comparison(),ZeroOrMore(Ch(','),Comparison())
// )
// )
// );
// }
//
// public Rule Field(){
// return FirstOf(
// String("id"),
// String("created"),
// String("lastModified"),
// String("name"),
// String("quantity"),
// String("unit"),
// String("prepTime"),
// String("cookTime"),
// String("ingredients")
// );
// }
//
//
// public Rule Comparison(){
// return FirstOf(
// Sequence(AlphaNumeric(), Spacing(), Operator(),Spacing(), Field()), Sequence(Field(),Spacing(), Operator(),Spacing(), AlphaNumeric()));
// }
//
// public Rule Operator(){
// return FirstOf(
// String("=="),
// String("<>"),
// String(">"),
// String("<"),
// String(">="),
// String("<="),
// String("contains")
// );
// }
//
// public Rule AlphaNumeric(){
// return OneOrMore(FirstOf(CharRange('a','z'),CharRange('0','9'))
// );
// }
//
// public Rule Spacing(){
// return ZeroOrMore(Ch(' '));
// }
//
// }
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/service/CookBookDefaultBackEndImp.java
import com.cookbook.tutorial.internal.dsql.Constants;
import com.cookbook.tutorial.internal.dsql.CookBookQuery;
import com.cookbook.tutorial.internal.dsql.Dsql;
import com.cookbook.tutorial.internal.dsql.DsqlParser;
import com.cookbook.tutorial.service.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.cxf.common.util.CollectionUtils;
import org.parboiled.Parboiled;
import org.parboiled.common.FileUtils;
import org.parboiled.parserunners.ReportingParseRunner;
import org.parboiled.support.ParsingResult;
import javax.jws.WebParam;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import java.lang.reflect.Type;
import java.util.*;
}
return entities;
}
@Override
public void deleteList(@WebParam(name = "entityIds", targetNamespace = "") List<Integer> entityIds) throws NoSuchEntityException {
for (Integer id : entityIds) {
delete(id);
}
}
@Override
public List<CookBookEntity> addList(@WebParam(name = "entities", targetNamespace = "") List<CookBookEntity> entities)
throws InvalidEntityException {
for (CookBookEntity entity : entities) {
create(entity);
}
return entities;
}
@Override
public List<CookBookEntity> searchWithQuery(@WebParam(name = "query", targetNamespace = "") String query, @WebParam(name = "page", targetNamespace = "") Integer page,
@WebParam(name = "pageSize", targetNamespace = "") Integer pageSize) throws InvalidRequestException {
DsqlParser parser = Parboiled.createParser(DsqlParser.class);
ParsingResult<?> result = new ReportingParseRunner(parser.Statement()).run(query);
if (result.hasErrors()) {
throw new InvalidRequestException(result.parseErrors.get(0).getErrorMessage());
}
List<CookBookEntity> searchResult = new ArrayList<>(); | CookBookQuery cookBookQuery = Dsql.newInstance(query); |
mulesoft/mule-cookbook | soap-server/src/main/java/com/cookbook/tutorial/internal/service/CookBookDefaultBackEndImp.java | // Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/Constants.java
// public class Constants {
// public static final String INGREDIENT = "INGREDIENT";
// public static final String RECIPE = "RECIPE";
// public static final String ALL = "ALL";
// }
//
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/CookBookQuery.java
// public interface CookBookQuery {
// boolean getAllFields();
// List<String> getFields();
// String getEntity();
// List<String> getCriteria();
// }
//
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/Dsql.java
// public class Dsql implements CookBookQuery{
// private final Pattern queryPattern = Pattern.compile("GET (.*) FROM ([\\w]*)( MATCHING (.*))?");
//
// private final Matcher matcher;
//
// public static Dsql newInstance(String query){
// return new Dsql(query);
// }
//
// private Dsql(String query){
// matcher=queryPattern.matcher(query);
// if(!matcher.matches()){
// throw new RuntimeException("Don't know how to process:"+query);
// }
// }
//
// @Override
// public boolean getAllFields() {
// return matcher.group(1).equals(Constants.ALL);
// }
//
// @Override
// public List<String> getFields() {
// return Arrays.asList(matcher.group(1).split(","));
// }
//
// @Override
// public String getEntity() {
// return matcher.group(2);
// }
//
// @Override
// public List<String> getCriteria() {
// if(matcher.groupCount()==4 && matcher.group(4)!=null) {
// return Arrays.asList(matcher.group(4).split(","));
// }
// return Collections.EMPTY_LIST;
// }
// }
//
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/DsqlParser.java
// @BuildParseTree
// public class DsqlParser extends BaseParser<Object>{
//
// public Rule Statement(){
// return Sequence(
// String("GET"),
// Ch(' '),
// Fields(),
// Ch(' '),
// String("FROM"),
// Ch(' '),
// Entities(),
// Clause(),
// EOI
// );
// }
//
// public Rule Fields() {
// return FirstOf(
// String("ALL"), OneOrMore(
// Sequence(
// Field(), ZeroOrMore(Ch(','), Field()))
// )
// );
// }
//
// public Rule Entities(){
// return FirstOf(String(Constants.INGREDIENT),String(Constants.RECIPE));
// }
//
// public Rule Clause(){
// return Optional(
// Sequence(
// Ch(' '),
// String("MATCHING"),
// Ch(' '),
// Sequence(
// Comparison(),ZeroOrMore(Ch(','),Comparison())
// )
// )
// );
// }
//
// public Rule Field(){
// return FirstOf(
// String("id"),
// String("created"),
// String("lastModified"),
// String("name"),
// String("quantity"),
// String("unit"),
// String("prepTime"),
// String("cookTime"),
// String("ingredients")
// );
// }
//
//
// public Rule Comparison(){
// return FirstOf(
// Sequence(AlphaNumeric(), Spacing(), Operator(),Spacing(), Field()), Sequence(Field(),Spacing(), Operator(),Spacing(), AlphaNumeric()));
// }
//
// public Rule Operator(){
// return FirstOf(
// String("=="),
// String("<>"),
// String(">"),
// String("<"),
// String(">="),
// String("<="),
// String("contains")
// );
// }
//
// public Rule AlphaNumeric(){
// return OneOrMore(FirstOf(CharRange('a','z'),CharRange('0','9'))
// );
// }
//
// public Rule Spacing(){
// return ZeroOrMore(Ch(' '));
// }
//
// }
| import com.cookbook.tutorial.internal.dsql.Constants;
import com.cookbook.tutorial.internal.dsql.CookBookQuery;
import com.cookbook.tutorial.internal.dsql.Dsql;
import com.cookbook.tutorial.internal.dsql.DsqlParser;
import com.cookbook.tutorial.service.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.cxf.common.util.CollectionUtils;
import org.parboiled.Parboiled;
import org.parboiled.common.FileUtils;
import org.parboiled.parserunners.ReportingParseRunner;
import org.parboiled.support.ParsingResult;
import javax.jws.WebParam;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import java.lang.reflect.Type;
import java.util.*; | }
return entities;
}
@Override
public void deleteList(@WebParam(name = "entityIds", targetNamespace = "") List<Integer> entityIds) throws NoSuchEntityException {
for (Integer id : entityIds) {
delete(id);
}
}
@Override
public List<CookBookEntity> addList(@WebParam(name = "entities", targetNamespace = "") List<CookBookEntity> entities)
throws InvalidEntityException {
for (CookBookEntity entity : entities) {
create(entity);
}
return entities;
}
@Override
public List<CookBookEntity> searchWithQuery(@WebParam(name = "query", targetNamespace = "") String query, @WebParam(name = "page", targetNamespace = "") Integer page,
@WebParam(name = "pageSize", targetNamespace = "") Integer pageSize) throws InvalidRequestException {
DsqlParser parser = Parboiled.createParser(DsqlParser.class);
ParsingResult<?> result = new ReportingParseRunner(parser.Statement()).run(query);
if (result.hasErrors()) {
throw new InvalidRequestException(result.parseErrors.get(0).getErrorMessage());
}
List<CookBookEntity> searchResult = new ArrayList<>(); | // Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/Constants.java
// public class Constants {
// public static final String INGREDIENT = "INGREDIENT";
// public static final String RECIPE = "RECIPE";
// public static final String ALL = "ALL";
// }
//
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/CookBookQuery.java
// public interface CookBookQuery {
// boolean getAllFields();
// List<String> getFields();
// String getEntity();
// List<String> getCriteria();
// }
//
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/Dsql.java
// public class Dsql implements CookBookQuery{
// private final Pattern queryPattern = Pattern.compile("GET (.*) FROM ([\\w]*)( MATCHING (.*))?");
//
// private final Matcher matcher;
//
// public static Dsql newInstance(String query){
// return new Dsql(query);
// }
//
// private Dsql(String query){
// matcher=queryPattern.matcher(query);
// if(!matcher.matches()){
// throw new RuntimeException("Don't know how to process:"+query);
// }
// }
//
// @Override
// public boolean getAllFields() {
// return matcher.group(1).equals(Constants.ALL);
// }
//
// @Override
// public List<String> getFields() {
// return Arrays.asList(matcher.group(1).split(","));
// }
//
// @Override
// public String getEntity() {
// return matcher.group(2);
// }
//
// @Override
// public List<String> getCriteria() {
// if(matcher.groupCount()==4 && matcher.group(4)!=null) {
// return Arrays.asList(matcher.group(4).split(","));
// }
// return Collections.EMPTY_LIST;
// }
// }
//
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/DsqlParser.java
// @BuildParseTree
// public class DsqlParser extends BaseParser<Object>{
//
// public Rule Statement(){
// return Sequence(
// String("GET"),
// Ch(' '),
// Fields(),
// Ch(' '),
// String("FROM"),
// Ch(' '),
// Entities(),
// Clause(),
// EOI
// );
// }
//
// public Rule Fields() {
// return FirstOf(
// String("ALL"), OneOrMore(
// Sequence(
// Field(), ZeroOrMore(Ch(','), Field()))
// )
// );
// }
//
// public Rule Entities(){
// return FirstOf(String(Constants.INGREDIENT),String(Constants.RECIPE));
// }
//
// public Rule Clause(){
// return Optional(
// Sequence(
// Ch(' '),
// String("MATCHING"),
// Ch(' '),
// Sequence(
// Comparison(),ZeroOrMore(Ch(','),Comparison())
// )
// )
// );
// }
//
// public Rule Field(){
// return FirstOf(
// String("id"),
// String("created"),
// String("lastModified"),
// String("name"),
// String("quantity"),
// String("unit"),
// String("prepTime"),
// String("cookTime"),
// String("ingredients")
// );
// }
//
//
// public Rule Comparison(){
// return FirstOf(
// Sequence(AlphaNumeric(), Spacing(), Operator(),Spacing(), Field()), Sequence(Field(),Spacing(), Operator(),Spacing(), AlphaNumeric()));
// }
//
// public Rule Operator(){
// return FirstOf(
// String("=="),
// String("<>"),
// String(">"),
// String("<"),
// String(">="),
// String("<="),
// String("contains")
// );
// }
//
// public Rule AlphaNumeric(){
// return OneOrMore(FirstOf(CharRange('a','z'),CharRange('0','9'))
// );
// }
//
// public Rule Spacing(){
// return ZeroOrMore(Ch(' '));
// }
//
// }
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/service/CookBookDefaultBackEndImp.java
import com.cookbook.tutorial.internal.dsql.Constants;
import com.cookbook.tutorial.internal.dsql.CookBookQuery;
import com.cookbook.tutorial.internal.dsql.Dsql;
import com.cookbook.tutorial.internal.dsql.DsqlParser;
import com.cookbook.tutorial.service.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.cxf.common.util.CollectionUtils;
import org.parboiled.Parboiled;
import org.parboiled.common.FileUtils;
import org.parboiled.parserunners.ReportingParseRunner;
import org.parboiled.support.ParsingResult;
import javax.jws.WebParam;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import java.lang.reflect.Type;
import java.util.*;
}
return entities;
}
@Override
public void deleteList(@WebParam(name = "entityIds", targetNamespace = "") List<Integer> entityIds) throws NoSuchEntityException {
for (Integer id : entityIds) {
delete(id);
}
}
@Override
public List<CookBookEntity> addList(@WebParam(name = "entities", targetNamespace = "") List<CookBookEntity> entities)
throws InvalidEntityException {
for (CookBookEntity entity : entities) {
create(entity);
}
return entities;
}
@Override
public List<CookBookEntity> searchWithQuery(@WebParam(name = "query", targetNamespace = "") String query, @WebParam(name = "page", targetNamespace = "") Integer page,
@WebParam(name = "pageSize", targetNamespace = "") Integer pageSize) throws InvalidRequestException {
DsqlParser parser = Parboiled.createParser(DsqlParser.class);
ParsingResult<?> result = new ReportingParseRunner(parser.Statement()).run(query);
if (result.hasErrors()) {
throw new InvalidRequestException(result.parseErrors.get(0).getErrorMessage());
}
List<CookBookEntity> searchResult = new ArrayList<>(); | CookBookQuery cookBookQuery = Dsql.newInstance(query); |
mulesoft/mule-cookbook | soap-server/src/main/java/com/cookbook/tutorial/internal/service/CookBookDefaultBackEndImp.java | // Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/Constants.java
// public class Constants {
// public static final String INGREDIENT = "INGREDIENT";
// public static final String RECIPE = "RECIPE";
// public static final String ALL = "ALL";
// }
//
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/CookBookQuery.java
// public interface CookBookQuery {
// boolean getAllFields();
// List<String> getFields();
// String getEntity();
// List<String> getCriteria();
// }
//
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/Dsql.java
// public class Dsql implements CookBookQuery{
// private final Pattern queryPattern = Pattern.compile("GET (.*) FROM ([\\w]*)( MATCHING (.*))?");
//
// private final Matcher matcher;
//
// public static Dsql newInstance(String query){
// return new Dsql(query);
// }
//
// private Dsql(String query){
// matcher=queryPattern.matcher(query);
// if(!matcher.matches()){
// throw new RuntimeException("Don't know how to process:"+query);
// }
// }
//
// @Override
// public boolean getAllFields() {
// return matcher.group(1).equals(Constants.ALL);
// }
//
// @Override
// public List<String> getFields() {
// return Arrays.asList(matcher.group(1).split(","));
// }
//
// @Override
// public String getEntity() {
// return matcher.group(2);
// }
//
// @Override
// public List<String> getCriteria() {
// if(matcher.groupCount()==4 && matcher.group(4)!=null) {
// return Arrays.asList(matcher.group(4).split(","));
// }
// return Collections.EMPTY_LIST;
// }
// }
//
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/DsqlParser.java
// @BuildParseTree
// public class DsqlParser extends BaseParser<Object>{
//
// public Rule Statement(){
// return Sequence(
// String("GET"),
// Ch(' '),
// Fields(),
// Ch(' '),
// String("FROM"),
// Ch(' '),
// Entities(),
// Clause(),
// EOI
// );
// }
//
// public Rule Fields() {
// return FirstOf(
// String("ALL"), OneOrMore(
// Sequence(
// Field(), ZeroOrMore(Ch(','), Field()))
// )
// );
// }
//
// public Rule Entities(){
// return FirstOf(String(Constants.INGREDIENT),String(Constants.RECIPE));
// }
//
// public Rule Clause(){
// return Optional(
// Sequence(
// Ch(' '),
// String("MATCHING"),
// Ch(' '),
// Sequence(
// Comparison(),ZeroOrMore(Ch(','),Comparison())
// )
// )
// );
// }
//
// public Rule Field(){
// return FirstOf(
// String("id"),
// String("created"),
// String("lastModified"),
// String("name"),
// String("quantity"),
// String("unit"),
// String("prepTime"),
// String("cookTime"),
// String("ingredients")
// );
// }
//
//
// public Rule Comparison(){
// return FirstOf(
// Sequence(AlphaNumeric(), Spacing(), Operator(),Spacing(), Field()), Sequence(Field(),Spacing(), Operator(),Spacing(), AlphaNumeric()));
// }
//
// public Rule Operator(){
// return FirstOf(
// String("=="),
// String("<>"),
// String(">"),
// String("<"),
// String(">="),
// String("<="),
// String("contains")
// );
// }
//
// public Rule AlphaNumeric(){
// return OneOrMore(FirstOf(CharRange('a','z'),CharRange('0','9'))
// );
// }
//
// public Rule Spacing(){
// return ZeroOrMore(Ch(' '));
// }
//
// }
| import com.cookbook.tutorial.internal.dsql.Constants;
import com.cookbook.tutorial.internal.dsql.CookBookQuery;
import com.cookbook.tutorial.internal.dsql.Dsql;
import com.cookbook.tutorial.internal.dsql.DsqlParser;
import com.cookbook.tutorial.service.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.cxf.common.util.CollectionUtils;
import org.parboiled.Parboiled;
import org.parboiled.common.FileUtils;
import org.parboiled.parserunners.ReportingParseRunner;
import org.parboiled.support.ParsingResult;
import javax.jws.WebParam;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import java.lang.reflect.Type;
import java.util.*; |
@Override
public List<CookBookEntity> addList(@WebParam(name = "entities", targetNamespace = "") List<CookBookEntity> entities)
throws InvalidEntityException {
for (CookBookEntity entity : entities) {
create(entity);
}
return entities;
}
@Override
public List<CookBookEntity> searchWithQuery(@WebParam(name = "query", targetNamespace = "") String query, @WebParam(name = "page", targetNamespace = "") Integer page,
@WebParam(name = "pageSize", targetNamespace = "") Integer pageSize) throws InvalidRequestException {
DsqlParser parser = Parboiled.createParser(DsqlParser.class);
ParsingResult<?> result = new ReportingParseRunner(parser.Statement()).run(query);
if (result.hasErrors()) {
throw new InvalidRequestException(result.parseErrors.get(0).getErrorMessage());
}
List<CookBookEntity> searchResult = new ArrayList<>();
CookBookQuery cookBookQuery = Dsql.newInstance(query);
if(pageSize==null){
throw new InvalidRequestException("Need to specify a page size");
}
Integer currentCount = 0;
Integer skipCount = 0;
Integer addedCount = 0;
if(page!=null){
skipCount=page*pageSize;
} | // Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/Constants.java
// public class Constants {
// public static final String INGREDIENT = "INGREDIENT";
// public static final String RECIPE = "RECIPE";
// public static final String ALL = "ALL";
// }
//
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/CookBookQuery.java
// public interface CookBookQuery {
// boolean getAllFields();
// List<String> getFields();
// String getEntity();
// List<String> getCriteria();
// }
//
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/Dsql.java
// public class Dsql implements CookBookQuery{
// private final Pattern queryPattern = Pattern.compile("GET (.*) FROM ([\\w]*)( MATCHING (.*))?");
//
// private final Matcher matcher;
//
// public static Dsql newInstance(String query){
// return new Dsql(query);
// }
//
// private Dsql(String query){
// matcher=queryPattern.matcher(query);
// if(!matcher.matches()){
// throw new RuntimeException("Don't know how to process:"+query);
// }
// }
//
// @Override
// public boolean getAllFields() {
// return matcher.group(1).equals(Constants.ALL);
// }
//
// @Override
// public List<String> getFields() {
// return Arrays.asList(matcher.group(1).split(","));
// }
//
// @Override
// public String getEntity() {
// return matcher.group(2);
// }
//
// @Override
// public List<String> getCriteria() {
// if(matcher.groupCount()==4 && matcher.group(4)!=null) {
// return Arrays.asList(matcher.group(4).split(","));
// }
// return Collections.EMPTY_LIST;
// }
// }
//
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/dsql/DsqlParser.java
// @BuildParseTree
// public class DsqlParser extends BaseParser<Object>{
//
// public Rule Statement(){
// return Sequence(
// String("GET"),
// Ch(' '),
// Fields(),
// Ch(' '),
// String("FROM"),
// Ch(' '),
// Entities(),
// Clause(),
// EOI
// );
// }
//
// public Rule Fields() {
// return FirstOf(
// String("ALL"), OneOrMore(
// Sequence(
// Field(), ZeroOrMore(Ch(','), Field()))
// )
// );
// }
//
// public Rule Entities(){
// return FirstOf(String(Constants.INGREDIENT),String(Constants.RECIPE));
// }
//
// public Rule Clause(){
// return Optional(
// Sequence(
// Ch(' '),
// String("MATCHING"),
// Ch(' '),
// Sequence(
// Comparison(),ZeroOrMore(Ch(','),Comparison())
// )
// )
// );
// }
//
// public Rule Field(){
// return FirstOf(
// String("id"),
// String("created"),
// String("lastModified"),
// String("name"),
// String("quantity"),
// String("unit"),
// String("prepTime"),
// String("cookTime"),
// String("ingredients")
// );
// }
//
//
// public Rule Comparison(){
// return FirstOf(
// Sequence(AlphaNumeric(), Spacing(), Operator(),Spacing(), Field()), Sequence(Field(),Spacing(), Operator(),Spacing(), AlphaNumeric()));
// }
//
// public Rule Operator(){
// return FirstOf(
// String("=="),
// String("<>"),
// String(">"),
// String("<"),
// String(">="),
// String("<="),
// String("contains")
// );
// }
//
// public Rule AlphaNumeric(){
// return OneOrMore(FirstOf(CharRange('a','z'),CharRange('0','9'))
// );
// }
//
// public Rule Spacing(){
// return ZeroOrMore(Ch(' '));
// }
//
// }
// Path: soap-server/src/main/java/com/cookbook/tutorial/internal/service/CookBookDefaultBackEndImp.java
import com.cookbook.tutorial.internal.dsql.Constants;
import com.cookbook.tutorial.internal.dsql.CookBookQuery;
import com.cookbook.tutorial.internal.dsql.Dsql;
import com.cookbook.tutorial.internal.dsql.DsqlParser;
import com.cookbook.tutorial.service.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.cxf.common.util.CollectionUtils;
import org.parboiled.Parboiled;
import org.parboiled.common.FileUtils;
import org.parboiled.parserunners.ReportingParseRunner;
import org.parboiled.support.ParsingResult;
import javax.jws.WebParam;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import java.lang.reflect.Type;
import java.util.*;
@Override
public List<CookBookEntity> addList(@WebParam(name = "entities", targetNamespace = "") List<CookBookEntity> entities)
throws InvalidEntityException {
for (CookBookEntity entity : entities) {
create(entity);
}
return entities;
}
@Override
public List<CookBookEntity> searchWithQuery(@WebParam(name = "query", targetNamespace = "") String query, @WebParam(name = "page", targetNamespace = "") Integer page,
@WebParam(name = "pageSize", targetNamespace = "") Integer pageSize) throws InvalidRequestException {
DsqlParser parser = Parboiled.createParser(DsqlParser.class);
ParsingResult<?> result = new ReportingParseRunner(parser.Statement()).run(query);
if (result.hasErrors()) {
throw new InvalidRequestException(result.parseErrors.get(0).getErrorMessage());
}
List<CookBookEntity> searchResult = new ArrayList<>();
CookBookQuery cookBookQuery = Dsql.newInstance(query);
if(pageSize==null){
throw new InvalidRequestException("Need to specify a page size");
}
Integer currentCount = 0;
Integer skipCount = 0;
Integer addedCount = 0;
if(page!=null){
skipCount=page*pageSize;
} | if (cookBookQuery.getEntity().equals(Constants.INGREDIENT)) { |
mulesoft/mule-cookbook | rest-server/src/main/java/com/cookbook/tutorial/IngredientResource.java | // Path: soap-server/src/main/java/com/cookbook/tutorial/service/DAOCookBookServiceFactory.java
// public class DAOCookBookServiceFactory {
//
// private static IDAOCookBookService instance;
//
// public static IDAOCookBookService getInstance(){
// if(instance==null){
// instance = new CookBookDefaultBackEndImp();
// }
// return instance;
// }
// }
| import com.cookbook.tutorial.service.DAOCookBookServiceFactory;
import com.cookbook.tutorial.service.*;
import org.parboiled.common.StringUtils;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; | package com.cookbook.tutorial;
@Path("/ingredient")
public class IngredientResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response get(@QueryParam("access_token") String token,@QueryParam("query") String query, @QueryParam("page") Integer page, @QueryParam("pageSize") Integer pageSize) {
if(!Constants.DEFAULT_TOKEN.equals(token)){
return Response.status(401).entity(new ErrorResponse("invalid_client","Invalid Token")).build();
}
try {
if(StringUtils.isEmpty(query)){
query="GET ALL FROM INGREDIENT";
}
if(page==null){
page = 0;
}
if(pageSize==null){
pageSize = 0;
} | // Path: soap-server/src/main/java/com/cookbook/tutorial/service/DAOCookBookServiceFactory.java
// public class DAOCookBookServiceFactory {
//
// private static IDAOCookBookService instance;
//
// public static IDAOCookBookService getInstance(){
// if(instance==null){
// instance = new CookBookDefaultBackEndImp();
// }
// return instance;
// }
// }
// Path: rest-server/src/main/java/com/cookbook/tutorial/IngredientResource.java
import com.cookbook.tutorial.service.DAOCookBookServiceFactory;
import com.cookbook.tutorial.service.*;
import org.parboiled.common.StringUtils;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
package com.cookbook.tutorial;
@Path("/ingredient")
public class IngredientResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response get(@QueryParam("access_token") String token,@QueryParam("query") String query, @QueryParam("page") Integer page, @QueryParam("pageSize") Integer pageSize) {
if(!Constants.DEFAULT_TOKEN.equals(token)){
return Response.status(401).entity(new ErrorResponse("invalid_client","Invalid Token")).build();
}
try {
if(StringUtils.isEmpty(query)){
query="GET ALL FROM INGREDIENT";
}
if(page==null){
page = 0;
}
if(pageSize==null){
pageSize = 0;
} | return Response.status(200).entity(DAOCookBookServiceFactory.getInstance().searchWithQuery(query,page,pageSize)).build(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.