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
Hevelian/hevelian-olastic
olastic-core/src/main/java/com/hevelian/olastic/core/elastic/parsers/ESMultiResponseParser.java
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/edm/ElasticEdmEntitySet.java // public class ElasticEdmEntitySet extends EdmEntitySetImpl { // // private ElasticCsdlEntitySet csdlEntitySet; // private ElasticEdmProvider provider; // // /** // * Initialize fields. // * // * @param provider // * the EDM provider // * @param container // * the EDM entity container // * @param entitySet // * the EDM entity set // */ // public ElasticEdmEntitySet(ElasticEdmProvider provider, EdmEntityContainer container, // ElasticCsdlEntitySet entitySet) { // super(provider, container, entitySet); // this.provider = provider; // this.csdlEntitySet = entitySet; // } // // /** // * Get's index name in Elasticsearch. // * // * @return index name // */ // public String getESIndex() { // return csdlEntitySet.getESIndex(); // } // // /** // * Get's type name in Elasticsearch. // * // * @return type name // */ // public String getESType() { // return csdlEntitySet.getESType(); // } // // @Override // public ElasticEdmEntityType getEntityType() { // EdmEntityType entityType = provider.getEntityType(new FullQualifiedName( // csdlEntitySet.getTypeFQN().getNamespace(), csdlEntitySet.getESType())); // return entityType != null ? (ElasticEdmEntityType) entityType // : (ElasticEdmEntityType) provider.getEntityType(csdlEntitySet.getTypeFQN()); // } // // /** // * Sets index to entity set. // * // * @param esIntex // * ES index // */ // public void setESIndex(String esIntex) { // csdlEntitySet.setESIndex(esIntex); // } // // /** // * Sets type to entity set. // * // * @param esType // * ES type // */ // public void setESType(String esType) { // csdlEntitySet.setESType(esType); // } // // /** // * Override because of if child entity type has name which starts with as // * parent entity type name, then wrong entity set is returning. // */ // @Override // public EdmBindingTarget getRelatedBindingTarget(final String path) { // if (path == null) { // return null; // } // EdmBindingTarget bindingTarget = null; // boolean found = false; // for (Iterator<EdmNavigationPropertyBinding> itor = getNavigationPropertyBindings() // .iterator(); itor.hasNext() && !found;) { // EdmNavigationPropertyBinding binding = itor.next(); // checkBinding(binding); // // Replace 'startsWith' to 'equals' // if (path.equals(binding.getPath())) { // Target target = new Target(binding.getTarget(), getEntityContainer()); // EdmEntityContainer entityContainer = getEntityContainer( // target.getEntityContainer()); // try { // bindingTarget = entityContainer.getEntitySet(target.getTargetName()); // if (bindingTarget == null) { // throw new EdmException("Cannot find EntitySet " + target.getTargetName()); // } // } catch (EdmException e) { // bindingTarget = entityContainer.getSingleton(target.getTargetName()); // if (bindingTarget == null) { // throw new EdmException("Cannot find Singleton " + target.getTargetName(), // e); // } // } finally { // found = bindingTarget != null; // } // } // } // return bindingTarget; // } // // private void checkBinding(EdmNavigationPropertyBinding binding) { // if (binding.getPath() == null || binding.getTarget() == null) { // throw new EdmException( // "Path or Target in navigation property binding must not be null!"); // } // } // // private EdmEntityContainer getEntityContainer(FullQualifiedName containerName) { // EdmEntityContainer entityContainer = edm.getEntityContainer(containerName); // if (entityContainer == null) { // throw new EdmException("Cannot find entity container with name: " + containerName); // } // return entityContainer; // } // // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/processors/data/InstanceData.java // @AllArgsConstructor // @Getter // public class InstanceData<T, V> { // // private final T type; // private final V value; // // }
import com.hevelian.olastic.core.edm.ElasticEdmEntitySet; import com.hevelian.olastic.core.processors.data.InstanceData; import org.apache.olingo.server.api.ODataApplicationException; import org.elasticsearch.action.search.MultiSearchResponse; import java.util.List;
package com.hevelian.olastic.core.elastic.parsers; /** * Interface to provide behavior for Elasticsearch response parsers. * * @author Taras Kohut * * @param <T> * instance data type class * @param <V> * instance data value class */ public interface ESMultiResponseParser<T, V> { /** * Parses Elasticsearch {@link MultiSearchResponse} and returns * {@link InstanceData} with type and value. * * @param response * multi response from Elasticsearch * @param responseEntitySets * entitySet list of the data returned from Elasticsearch * @param returnEntitySet * entitySet that should be returned to the client * @return instance data with type and value * @throws ODataApplicationException * if any error occurred during parsing response */ InstanceData<T, V> parse(MultiSearchResponse response,
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/edm/ElasticEdmEntitySet.java // public class ElasticEdmEntitySet extends EdmEntitySetImpl { // // private ElasticCsdlEntitySet csdlEntitySet; // private ElasticEdmProvider provider; // // /** // * Initialize fields. // * // * @param provider // * the EDM provider // * @param container // * the EDM entity container // * @param entitySet // * the EDM entity set // */ // public ElasticEdmEntitySet(ElasticEdmProvider provider, EdmEntityContainer container, // ElasticCsdlEntitySet entitySet) { // super(provider, container, entitySet); // this.provider = provider; // this.csdlEntitySet = entitySet; // } // // /** // * Get's index name in Elasticsearch. // * // * @return index name // */ // public String getESIndex() { // return csdlEntitySet.getESIndex(); // } // // /** // * Get's type name in Elasticsearch. // * // * @return type name // */ // public String getESType() { // return csdlEntitySet.getESType(); // } // // @Override // public ElasticEdmEntityType getEntityType() { // EdmEntityType entityType = provider.getEntityType(new FullQualifiedName( // csdlEntitySet.getTypeFQN().getNamespace(), csdlEntitySet.getESType())); // return entityType != null ? (ElasticEdmEntityType) entityType // : (ElasticEdmEntityType) provider.getEntityType(csdlEntitySet.getTypeFQN()); // } // // /** // * Sets index to entity set. // * // * @param esIntex // * ES index // */ // public void setESIndex(String esIntex) { // csdlEntitySet.setESIndex(esIntex); // } // // /** // * Sets type to entity set. // * // * @param esType // * ES type // */ // public void setESType(String esType) { // csdlEntitySet.setESType(esType); // } // // /** // * Override because of if child entity type has name which starts with as // * parent entity type name, then wrong entity set is returning. // */ // @Override // public EdmBindingTarget getRelatedBindingTarget(final String path) { // if (path == null) { // return null; // } // EdmBindingTarget bindingTarget = null; // boolean found = false; // for (Iterator<EdmNavigationPropertyBinding> itor = getNavigationPropertyBindings() // .iterator(); itor.hasNext() && !found;) { // EdmNavigationPropertyBinding binding = itor.next(); // checkBinding(binding); // // Replace 'startsWith' to 'equals' // if (path.equals(binding.getPath())) { // Target target = new Target(binding.getTarget(), getEntityContainer()); // EdmEntityContainer entityContainer = getEntityContainer( // target.getEntityContainer()); // try { // bindingTarget = entityContainer.getEntitySet(target.getTargetName()); // if (bindingTarget == null) { // throw new EdmException("Cannot find EntitySet " + target.getTargetName()); // } // } catch (EdmException e) { // bindingTarget = entityContainer.getSingleton(target.getTargetName()); // if (bindingTarget == null) { // throw new EdmException("Cannot find Singleton " + target.getTargetName(), // e); // } // } finally { // found = bindingTarget != null; // } // } // } // return bindingTarget; // } // // private void checkBinding(EdmNavigationPropertyBinding binding) { // if (binding.getPath() == null || binding.getTarget() == null) { // throw new EdmException( // "Path or Target in navigation property binding must not be null!"); // } // } // // private EdmEntityContainer getEntityContainer(FullQualifiedName containerName) { // EdmEntityContainer entityContainer = edm.getEntityContainer(containerName); // if (entityContainer == null) { // throw new EdmException("Cannot find entity container with name: " + containerName); // } // return entityContainer; // } // // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/processors/data/InstanceData.java // @AllArgsConstructor // @Getter // public class InstanceData<T, V> { // // private final T type; // private final V value; // // } // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/parsers/ESMultiResponseParser.java import com.hevelian.olastic.core.edm.ElasticEdmEntitySet; import com.hevelian.olastic.core.processors.data.InstanceData; import org.apache.olingo.server.api.ODataApplicationException; import org.elasticsearch.action.search.MultiSearchResponse; import java.util.List; package com.hevelian.olastic.core.elastic.parsers; /** * Interface to provide behavior for Elasticsearch response parsers. * * @author Taras Kohut * * @param <T> * instance data type class * @param <V> * instance data value class */ public interface ESMultiResponseParser<T, V> { /** * Parses Elasticsearch {@link MultiSearchResponse} and returns * {@link InstanceData} with type and value. * * @param response * multi response from Elasticsearch * @param responseEntitySets * entitySet list of the data returned from Elasticsearch * @param returnEntitySet * entitySet that should be returned to the client * @return instance data with type and value * @throws ODataApplicationException * if any error occurred during parsing response */ InstanceData<T, V> parse(MultiSearchResponse response,
List<ElasticEdmEntitySet> responseEntitySets, ElasticEdmEntitySet returnEntitySet)
Hevelian/hevelian-olastic
olastic-core/src/main/java/com/hevelian/olastic/core/elastic/queries/SearchQuery.java
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/pagination/Pagination.java // public class Pagination { // /** Default skip value. */ // public static final int SKIP_DEFAULT = 0; // /** Default top value. */ // public static final int TOP_DEFAULT = 25; // private int top; // private int skip; // private List<Sort> orderBy; // // /** // * Initializes pagination with all the data. // * // * @param top // * top count // * @param skip // * skip count // * @param orderBy // * order by field // */ // public Pagination(int top, int skip, List<Sort> orderBy) { // this.top = top; // this.skip = skip; // this.orderBy = orderBy; // } // // public int getTop() { // return top; // } // // public void setTop(int top) { // this.top = top; // } // // public int getSkip() { // return skip; // } // // public void setSkip(int skip) { // this.skip = skip; // } // // public List<Sort> getOrderBy() { // return orderBy; // } // // public void setOrderBy(List<Sort> orderBy) { // this.orderBy = orderBy; // } // }
import java.util.Set; import org.elasticsearch.index.query.QueryBuilder; import com.hevelian.olastic.core.elastic.pagination.Pagination; import lombok.Getter; import lombok.NonNull;
package com.hevelian.olastic.core.elastic.queries; /** * Search query with fields. * * @author rdidyk */ @Getter public class SearchQuery extends Query { @NonNull private final Set<String> fields; /** * Constructor to initialize parameters. * * @param index * index name * @param types * types name * @param queryBuilder * main query builder * @param fields * fields to search * @param pagination * pagination */ public SearchQuery(String index, String[] types, QueryBuilder queryBuilder, Set<String> fields,
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/pagination/Pagination.java // public class Pagination { // /** Default skip value. */ // public static final int SKIP_DEFAULT = 0; // /** Default top value. */ // public static final int TOP_DEFAULT = 25; // private int top; // private int skip; // private List<Sort> orderBy; // // /** // * Initializes pagination with all the data. // * // * @param top // * top count // * @param skip // * skip count // * @param orderBy // * order by field // */ // public Pagination(int top, int skip, List<Sort> orderBy) { // this.top = top; // this.skip = skip; // this.orderBy = orderBy; // } // // public int getTop() { // return top; // } // // public void setTop(int top) { // this.top = top; // } // // public int getSkip() { // return skip; // } // // public void setSkip(int skip) { // this.skip = skip; // } // // public List<Sort> getOrderBy() { // return orderBy; // } // // public void setOrderBy(List<Sort> orderBy) { // this.orderBy = orderBy; // } // } // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/queries/SearchQuery.java import java.util.Set; import org.elasticsearch.index.query.QueryBuilder; import com.hevelian.olastic.core.elastic.pagination.Pagination; import lombok.Getter; import lombok.NonNull; package com.hevelian.olastic.core.elastic.queries; /** * Search query with fields. * * @author rdidyk */ @Getter public class SearchQuery extends Query { @NonNull private final Set<String> fields; /** * Constructor to initialize parameters. * * @param index * index name * @param types * types name * @param queryBuilder * main query builder * @param fields * fields to search * @param pagination * pagination */ public SearchQuery(String index, String[] types, QueryBuilder queryBuilder, Set<String> fields,
Pagination pagination) {
Hevelian/hevelian-olastic
olastic-core/src/test/java/com/hevelian/olastic/core/stub/TestProvider.java
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/edm/annotations/AnnotationProvider.java // public class AnnotationProvider { // /** Analyzed term name. */ // public static final String ANALYZED_TERM_NAME = "Analyzed"; // // private HashMap<String, TermAnnotation> annotations = new HashMap<>(); // // // declaring terms and annotations // private CsdlAnnotation analyzedAnnotation = new CsdlAnnotation().setTerm("OData.Analyzed") // .setExpression(new CsdlConstantExpression( // CsdlConstantExpression.ConstantExpressionType.Bool, "true")); // // private CsdlTerm analyzedTerm = new CsdlTerm().setAppliesTo(Arrays.asList("Property")) // .setName(ANALYZED_TERM_NAME).setType(EdmPrimitiveTypeKind.String.getFullQualifiedName() // .getFullQualifiedNameAsString()); // // /** // * Default constructor. Sets default annotation. // */ // public AnnotationProvider() { // annotations.put(ANALYZED_TERM_NAME, new TermAnnotation(analyzedTerm, analyzedAnnotation)); // } // // /** // * Gets annotation by term name. // * // * @param termName // * term name // * @return found annotation, otherwise null // */ // public CsdlAnnotation getAnnotation(String termName) { // TermAnnotation temAnnotation = annotations.get(termName); // if (temAnnotation != null) { // return annotations.get(termName).annotation; // } else { // return null; // } // } // // /** // * Gets term by term name. // * // * @param termName // * term name // * @return found term, otherwise null // */ // public CsdlTerm getTerm(String termName) { // TermAnnotation temAnnotation = annotations.get(termName); // if (temAnnotation != null) { // return annotations.get(termName).term; // } else { // return null; // } // } // // public List<CsdlTerm> getTerms() { // return annotations.entrySet().stream().map(entry -> entry.getValue().term) // .collect(Collectors.toList()); // } // // /** // * Class represents container for term and annotation. // */ // private class TermAnnotation { // private CsdlAnnotation annotation; // private CsdlTerm term; // // TermAnnotation(CsdlTerm term, CsdlAnnotation annotation) { // this.term = term; // this.annotation = annotation; // } // } // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/mappings/MappingMetaDataProvider.java // public interface MappingMetaDataProvider { // /** // * Return all the mappings for all the types inside a single index. // * // * @param index // * name of the index. // * @return Type/Mapping map. // */ // ImmutableOpenMap<String, MappingMetaData> getAllMappings(String index); // // /** // * Get mapping for a single type. The {@link #getAllMappings(String)} should // * be used if the mappings for all the types are required. // * // * @param index // * name of the index. // * @param type // * name of the type within the index. // * @return mapping metadata for a single type. // */ // MappingMetaData getMappingForType(String index, String type); // // /** // * Get all mappings for fields with the requested name within a single // * instance. // * // * @param index // * name of the index. // * @param field // * name of the field. // * @return type/field mapping map. // */ // ImmutableOpenMap<String, FieldMappingMetaData> getMappingsForField(String index, String field); // // /** // * Get mapping for a single field within a single type. // * // * @param index // * name of the index. // * @param type // * name of the type. // * @param field // * name of the field. // * @return mapping metadata for a single field. // */ // FieldMappingMetaData getMappingForField(String index, String type, String field); // }
import com.hevelian.olastic.core.api.edm.annotations.AnnotationProvider; import com.hevelian.olastic.core.api.edm.provider.*; import com.hevelian.olastic.core.elastic.mappings.MappingMetaDataProvider; import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind; import org.apache.olingo.commons.api.edm.FullQualifiedName; import org.apache.olingo.commons.api.edm.provider.*; import org.apache.olingo.commons.api.ex.ODataException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List;
package com.hevelian.olastic.core.stub; /** * Initializes stub provider for testing purposes. */ public class TestProvider extends ElasticCsdlEdmProvider { private static List<CsdlAnnotation> analyzedAnnotations = Arrays
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/edm/annotations/AnnotationProvider.java // public class AnnotationProvider { // /** Analyzed term name. */ // public static final String ANALYZED_TERM_NAME = "Analyzed"; // // private HashMap<String, TermAnnotation> annotations = new HashMap<>(); // // // declaring terms and annotations // private CsdlAnnotation analyzedAnnotation = new CsdlAnnotation().setTerm("OData.Analyzed") // .setExpression(new CsdlConstantExpression( // CsdlConstantExpression.ConstantExpressionType.Bool, "true")); // // private CsdlTerm analyzedTerm = new CsdlTerm().setAppliesTo(Arrays.asList("Property")) // .setName(ANALYZED_TERM_NAME).setType(EdmPrimitiveTypeKind.String.getFullQualifiedName() // .getFullQualifiedNameAsString()); // // /** // * Default constructor. Sets default annotation. // */ // public AnnotationProvider() { // annotations.put(ANALYZED_TERM_NAME, new TermAnnotation(analyzedTerm, analyzedAnnotation)); // } // // /** // * Gets annotation by term name. // * // * @param termName // * term name // * @return found annotation, otherwise null // */ // public CsdlAnnotation getAnnotation(String termName) { // TermAnnotation temAnnotation = annotations.get(termName); // if (temAnnotation != null) { // return annotations.get(termName).annotation; // } else { // return null; // } // } // // /** // * Gets term by term name. // * // * @param termName // * term name // * @return found term, otherwise null // */ // public CsdlTerm getTerm(String termName) { // TermAnnotation temAnnotation = annotations.get(termName); // if (temAnnotation != null) { // return annotations.get(termName).term; // } else { // return null; // } // } // // public List<CsdlTerm> getTerms() { // return annotations.entrySet().stream().map(entry -> entry.getValue().term) // .collect(Collectors.toList()); // } // // /** // * Class represents container for term and annotation. // */ // private class TermAnnotation { // private CsdlAnnotation annotation; // private CsdlTerm term; // // TermAnnotation(CsdlTerm term, CsdlAnnotation annotation) { // this.term = term; // this.annotation = annotation; // } // } // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/mappings/MappingMetaDataProvider.java // public interface MappingMetaDataProvider { // /** // * Return all the mappings for all the types inside a single index. // * // * @param index // * name of the index. // * @return Type/Mapping map. // */ // ImmutableOpenMap<String, MappingMetaData> getAllMappings(String index); // // /** // * Get mapping for a single type. The {@link #getAllMappings(String)} should // * be used if the mappings for all the types are required. // * // * @param index // * name of the index. // * @param type // * name of the type within the index. // * @return mapping metadata for a single type. // */ // MappingMetaData getMappingForType(String index, String type); // // /** // * Get all mappings for fields with the requested name within a single // * instance. // * // * @param index // * name of the index. // * @param field // * name of the field. // * @return type/field mapping map. // */ // ImmutableOpenMap<String, FieldMappingMetaData> getMappingsForField(String index, String field); // // /** // * Get mapping for a single field within a single type. // * // * @param index // * name of the index. // * @param type // * name of the type. // * @param field // * name of the field. // * @return mapping metadata for a single field. // */ // FieldMappingMetaData getMappingForField(String index, String type, String field); // } // Path: olastic-core/src/test/java/com/hevelian/olastic/core/stub/TestProvider.java import com.hevelian.olastic.core.api.edm.annotations.AnnotationProvider; import com.hevelian.olastic.core.api.edm.provider.*; import com.hevelian.olastic.core.elastic.mappings.MappingMetaDataProvider; import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind; import org.apache.olingo.commons.api.edm.FullQualifiedName; import org.apache.olingo.commons.api.edm.provider.*; import org.apache.olingo.commons.api.ex.ODataException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; package com.hevelian.olastic.core.stub; /** * Initializes stub provider for testing purposes. */ public class TestProvider extends ElasticCsdlEdmProvider { private static List<CsdlAnnotation> analyzedAnnotations = Arrays
.asList(new AnnotationProvider().getAnnotation(AnnotationProvider.ANALYZED_TERM_NAME));
Hevelian/hevelian-olastic
olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/MethodsTest.java
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static EdmAnnotation getAnalyzedAnnotation() { // EdmAnnotation annotation = mock(EdmAnnotation.class); // EdmTerm term = mock(EdmTerm.class); // EdmExpression expression = mock(EdmExpression.class); // EdmConstantExpression constantExpression = mock(EdmConstantExpression.class); // doReturn(Boolean.parseBoolean( // new AnnotationProvider().getAnnotation(AnnotationProvider.ANALYZED_TERM_NAME) // .getExpression().asConstant().getValue())).when(constantExpression) // .asPrimitive(); // doReturn(constantExpression).when(expression).asConstant(); // doReturn(AnnotationProvider.ANALYZED_TERM_NAME).when(term).getName(); // doReturn(term).when(annotation).getTerm(); // doReturn(expression).when(annotation).getExpression(); // return annotation; // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/ElasticConstants.java // public final class ElasticConstants { // // /** Field data type property. */ // public static final String FIELD_DATATYPE_PROPERTY = "type"; // /** Properties property name. */ // public static final String PROPERTIES_PROPERTY = "properties"; // /** Parent property name. */ // public static final String PARENT_PROPERTY = "_parent"; // /** ID field name. */ // public static final String ID_FIELD_NAME = "_id"; // /** Suffix for keyword (not-analyzed) field. */ // public static final String KEYWORD_SUFFIX = "keyword"; // /** Field suffix delimiter. */ // public static final String SUFFIX_DELIMITER = "."; // /** Nested path separator. */ // public static final String NESTED_PATH_SEPARATOR = "."; // /** Wildcard character. */ // public static final String WILDCARD_CHAR = "*"; // /** // * The _all field is a special catch-all field which concatenates the values // * of all of the other fields into one big string. // */ // public static final String ALL_FIELD = "_all"; // // private ElasticConstants() { // } // }
import static com.hevelian.olastic.core.TestUtils.getAnalyzedAnnotation; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.apache.olingo.commons.api.edm.EdmAnnotation; import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.core.edm.primitivetype.EdmString; import org.json.JSONObject; import org.junit.Test; import com.hevelian.olastic.core.elastic.ElasticConstants;
package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl; /** * Tests for Built-in odata Query Functions. * * @author Taras Kohut */ public class MethodsTest { private String field = "someField"; private String value = "'value'"; private EdmType edmString = new EdmString();
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static EdmAnnotation getAnalyzedAnnotation() { // EdmAnnotation annotation = mock(EdmAnnotation.class); // EdmTerm term = mock(EdmTerm.class); // EdmExpression expression = mock(EdmExpression.class); // EdmConstantExpression constantExpression = mock(EdmConstantExpression.class); // doReturn(Boolean.parseBoolean( // new AnnotationProvider().getAnnotation(AnnotationProvider.ANALYZED_TERM_NAME) // .getExpression().asConstant().getValue())).when(constantExpression) // .asPrimitive(); // doReturn(constantExpression).when(expression).asConstant(); // doReturn(AnnotationProvider.ANALYZED_TERM_NAME).when(term).getName(); // doReturn(term).when(annotation).getTerm(); // doReturn(expression).when(annotation).getExpression(); // return annotation; // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/ElasticConstants.java // public final class ElasticConstants { // // /** Field data type property. */ // public static final String FIELD_DATATYPE_PROPERTY = "type"; // /** Properties property name. */ // public static final String PROPERTIES_PROPERTY = "properties"; // /** Parent property name. */ // public static final String PARENT_PROPERTY = "_parent"; // /** ID field name. */ // public static final String ID_FIELD_NAME = "_id"; // /** Suffix for keyword (not-analyzed) field. */ // public static final String KEYWORD_SUFFIX = "keyword"; // /** Field suffix delimiter. */ // public static final String SUFFIX_DELIMITER = "."; // /** Nested path separator. */ // public static final String NESTED_PATH_SEPARATOR = "."; // /** Wildcard character. */ // public static final String WILDCARD_CHAR = "*"; // /** // * The _all field is a special catch-all field which concatenates the values // * of all of the other fields into one big string. // */ // public static final String ALL_FIELD = "_all"; // // private ElasticConstants() { // } // } // Path: olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/MethodsTest.java import static com.hevelian.olastic.core.TestUtils.getAnalyzedAnnotation; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.apache.olingo.commons.api.edm.EdmAnnotation; import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.core.edm.primitivetype.EdmString; import org.json.JSONObject; import org.junit.Test; import com.hevelian.olastic.core.elastic.ElasticConstants; package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl; /** * Tests for Built-in odata Query Functions. * * @author Taras Kohut */ public class MethodsTest { private String field = "someField"; private String value = "'value'"; private EdmType edmString = new EdmString();
private List<EdmAnnotation> annotations = Arrays.asList(getAnalyzedAnnotation());
Hevelian/hevelian-olastic
olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/MethodsTest.java
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static EdmAnnotation getAnalyzedAnnotation() { // EdmAnnotation annotation = mock(EdmAnnotation.class); // EdmTerm term = mock(EdmTerm.class); // EdmExpression expression = mock(EdmExpression.class); // EdmConstantExpression constantExpression = mock(EdmConstantExpression.class); // doReturn(Boolean.parseBoolean( // new AnnotationProvider().getAnnotation(AnnotationProvider.ANALYZED_TERM_NAME) // .getExpression().asConstant().getValue())).when(constantExpression) // .asPrimitive(); // doReturn(constantExpression).when(expression).asConstant(); // doReturn(AnnotationProvider.ANALYZED_TERM_NAME).when(term).getName(); // doReturn(term).when(annotation).getTerm(); // doReturn(expression).when(annotation).getExpression(); // return annotation; // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/ElasticConstants.java // public final class ElasticConstants { // // /** Field data type property. */ // public static final String FIELD_DATATYPE_PROPERTY = "type"; // /** Properties property name. */ // public static final String PROPERTIES_PROPERTY = "properties"; // /** Parent property name. */ // public static final String PARENT_PROPERTY = "_parent"; // /** ID field name. */ // public static final String ID_FIELD_NAME = "_id"; // /** Suffix for keyword (not-analyzed) field. */ // public static final String KEYWORD_SUFFIX = "keyword"; // /** Field suffix delimiter. */ // public static final String SUFFIX_DELIMITER = "."; // /** Nested path separator. */ // public static final String NESTED_PATH_SEPARATOR = "."; // /** Wildcard character. */ // public static final String WILDCARD_CHAR = "*"; // /** // * The _all field is a special catch-all field which concatenates the values // * of all of the other fields into one big string. // */ // public static final String ALL_FIELD = "_all"; // // private ElasticConstants() { // } // }
import static com.hevelian.olastic.core.TestUtils.getAnalyzedAnnotation; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.apache.olingo.commons.api.edm.EdmAnnotation; import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.core.edm.primitivetype.EdmString; import org.json.JSONObject; import org.junit.Test; import com.hevelian.olastic.core.elastic.ElasticConstants;
package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl; /** * Tests for Built-in odata Query Functions. * * @author Taras Kohut */ public class MethodsTest { private String field = "someField"; private String value = "'value'"; private EdmType edmString = new EdmString(); private List<EdmAnnotation> annotations = Arrays.asList(getAnalyzedAnnotation()); @Test public void contains_PrimitiveAndLiteral_QueryIsCorrect() throws Exception { PrimitiveMember left = new PrimitiveMember(field, annotations); LiteralMember right = new LiteralMember(value, edmString); ExpressionResult result = left.contains(right); JSONObject queryObj = new JSONObject(result.getQueryBuilder().toString()); JSONObject rootObj = queryObj.getJSONObject("wildcard"); String fieldName = field + ".keyword"; JSONObject valueObject = rootObj.getJSONObject(fieldName); String actualValue = (String) valueObject.get("wildcard");
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static EdmAnnotation getAnalyzedAnnotation() { // EdmAnnotation annotation = mock(EdmAnnotation.class); // EdmTerm term = mock(EdmTerm.class); // EdmExpression expression = mock(EdmExpression.class); // EdmConstantExpression constantExpression = mock(EdmConstantExpression.class); // doReturn(Boolean.parseBoolean( // new AnnotationProvider().getAnnotation(AnnotationProvider.ANALYZED_TERM_NAME) // .getExpression().asConstant().getValue())).when(constantExpression) // .asPrimitive(); // doReturn(constantExpression).when(expression).asConstant(); // doReturn(AnnotationProvider.ANALYZED_TERM_NAME).when(term).getName(); // doReturn(term).when(annotation).getTerm(); // doReturn(expression).when(annotation).getExpression(); // return annotation; // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/ElasticConstants.java // public final class ElasticConstants { // // /** Field data type property. */ // public static final String FIELD_DATATYPE_PROPERTY = "type"; // /** Properties property name. */ // public static final String PROPERTIES_PROPERTY = "properties"; // /** Parent property name. */ // public static final String PARENT_PROPERTY = "_parent"; // /** ID field name. */ // public static final String ID_FIELD_NAME = "_id"; // /** Suffix for keyword (not-analyzed) field. */ // public static final String KEYWORD_SUFFIX = "keyword"; // /** Field suffix delimiter. */ // public static final String SUFFIX_DELIMITER = "."; // /** Nested path separator. */ // public static final String NESTED_PATH_SEPARATOR = "."; // /** Wildcard character. */ // public static final String WILDCARD_CHAR = "*"; // /** // * The _all field is a special catch-all field which concatenates the values // * of all of the other fields into one big string. // */ // public static final String ALL_FIELD = "_all"; // // private ElasticConstants() { // } // } // Path: olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/MethodsTest.java import static com.hevelian.olastic.core.TestUtils.getAnalyzedAnnotation; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.apache.olingo.commons.api.edm.EdmAnnotation; import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.core.edm.primitivetype.EdmString; import org.json.JSONObject; import org.junit.Test; import com.hevelian.olastic.core.elastic.ElasticConstants; package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl; /** * Tests for Built-in odata Query Functions. * * @author Taras Kohut */ public class MethodsTest { private String field = "someField"; private String value = "'value'"; private EdmType edmString = new EdmString(); private List<EdmAnnotation> annotations = Arrays.asList(getAnalyzedAnnotation()); @Test public void contains_PrimitiveAndLiteral_QueryIsCorrect() throws Exception { PrimitiveMember left = new PrimitiveMember(field, annotations); LiteralMember right = new LiteralMember(value, edmString); ExpressionResult result = left.contains(right); JSONObject queryObj = new JSONObject(result.getQueryBuilder().toString()); JSONObject rootObj = queryObj.getJSONObject("wildcard"); String fieldName = field + ".keyword"; JSONObject valueObject = rootObj.getJSONObject(fieldName); String actualValue = (String) valueObject.get("wildcard");
assertEquals(ElasticConstants.WILDCARD_CHAR + value.substring(1, value.length() - 1)
Hevelian/hevelian-olastic
olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/PrimitiveMemberTest.java
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterEqualsQuery(String query, String field, String value) { // checkFilterEqualsQueryInternal(query, field, value, false); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterNotEqualsQuery(String query, String field, String value) { // checkFilterEqualsQueryInternal(query, field, value, true); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterRangeQuery(String query, String operator, String field, // Object expValue) throws ODataApplicationException { // String rootKey = "range"; // boolean includeLower = !operator.equals("gt"); // boolean includeUpper = !operator.equals("lt"); // String valueKey = operator.startsWith("g") ? "from" : "to"; // JSONObject queryObj = new JSONObject(query); // JSONObject rootObj = queryObj.getJSONObject(rootKey); // JSONObject valueObject = rootObj.getJSONObject(field); // String actualValue = (String) valueObject.get(valueKey); // assertEquals(expValue, actualValue); // assertEquals(valueObject.get("include_lower"), includeLower); // assertEquals(valueObject.get("include_upper"), includeUpper); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static EdmAnnotation getAnalyzedAnnotation() { // EdmAnnotation annotation = mock(EdmAnnotation.class); // EdmTerm term = mock(EdmTerm.class); // EdmExpression expression = mock(EdmExpression.class); // EdmConstantExpression constantExpression = mock(EdmConstantExpression.class); // doReturn(Boolean.parseBoolean( // new AnnotationProvider().getAnnotation(AnnotationProvider.ANALYZED_TERM_NAME) // .getExpression().asConstant().getValue())).when(constantExpression) // .asPrimitive(); // doReturn(constantExpression).when(expression).asConstant(); // doReturn(AnnotationProvider.ANALYZED_TERM_NAME).when(term).getName(); // doReturn(term).when(annotation).getTerm(); // doReturn(expression).when(annotation).getExpression(); // return annotation; // }
import static com.hevelian.olastic.core.TestUtils.checkFilterEqualsQuery; import static com.hevelian.olastic.core.TestUtils.checkFilterNotEqualsQuery; import static com.hevelian.olastic.core.TestUtils.checkFilterRangeQuery; import static com.hevelian.olastic.core.TestUtils.getAnalyzedAnnotation; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.apache.olingo.commons.api.edm.EdmAnnotation; import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.core.edm.primitivetype.EdmInt32; import org.apache.olingo.commons.core.edm.primitivetype.EdmString; import org.apache.olingo.server.api.ODataApplicationException; import org.junit.Test;
package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl; /** * Tests for {@link PrimitiveMember} class. * * @author Taras Kohut */ public class PrimitiveMemberTest { private String field = "someField"; private String value = "'value'"; private String intValue = "10"; private EdmType edmString = new EdmString(); private EdmType edmInt = new EdmInt32();
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterEqualsQuery(String query, String field, String value) { // checkFilterEqualsQueryInternal(query, field, value, false); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterNotEqualsQuery(String query, String field, String value) { // checkFilterEqualsQueryInternal(query, field, value, true); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterRangeQuery(String query, String operator, String field, // Object expValue) throws ODataApplicationException { // String rootKey = "range"; // boolean includeLower = !operator.equals("gt"); // boolean includeUpper = !operator.equals("lt"); // String valueKey = operator.startsWith("g") ? "from" : "to"; // JSONObject queryObj = new JSONObject(query); // JSONObject rootObj = queryObj.getJSONObject(rootKey); // JSONObject valueObject = rootObj.getJSONObject(field); // String actualValue = (String) valueObject.get(valueKey); // assertEquals(expValue, actualValue); // assertEquals(valueObject.get("include_lower"), includeLower); // assertEquals(valueObject.get("include_upper"), includeUpper); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static EdmAnnotation getAnalyzedAnnotation() { // EdmAnnotation annotation = mock(EdmAnnotation.class); // EdmTerm term = mock(EdmTerm.class); // EdmExpression expression = mock(EdmExpression.class); // EdmConstantExpression constantExpression = mock(EdmConstantExpression.class); // doReturn(Boolean.parseBoolean( // new AnnotationProvider().getAnnotation(AnnotationProvider.ANALYZED_TERM_NAME) // .getExpression().asConstant().getValue())).when(constantExpression) // .asPrimitive(); // doReturn(constantExpression).when(expression).asConstant(); // doReturn(AnnotationProvider.ANALYZED_TERM_NAME).when(term).getName(); // doReturn(term).when(annotation).getTerm(); // doReturn(expression).when(annotation).getExpression(); // return annotation; // } // Path: olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/PrimitiveMemberTest.java import static com.hevelian.olastic.core.TestUtils.checkFilterEqualsQuery; import static com.hevelian.olastic.core.TestUtils.checkFilterNotEqualsQuery; import static com.hevelian.olastic.core.TestUtils.checkFilterRangeQuery; import static com.hevelian.olastic.core.TestUtils.getAnalyzedAnnotation; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.apache.olingo.commons.api.edm.EdmAnnotation; import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.core.edm.primitivetype.EdmInt32; import org.apache.olingo.commons.core.edm.primitivetype.EdmString; import org.apache.olingo.server.api.ODataApplicationException; import org.junit.Test; package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl; /** * Tests for {@link PrimitiveMember} class. * * @author Taras Kohut */ public class PrimitiveMemberTest { private String field = "someField"; private String value = "'value'"; private String intValue = "10"; private EdmType edmString = new EdmString(); private EdmType edmInt = new EdmInt32();
private List<EdmAnnotation> annotations = Arrays.asList(getAnalyzedAnnotation());
Hevelian/hevelian-olastic
olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/PrimitiveMemberTest.java
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterEqualsQuery(String query, String field, String value) { // checkFilterEqualsQueryInternal(query, field, value, false); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterNotEqualsQuery(String query, String field, String value) { // checkFilterEqualsQueryInternal(query, field, value, true); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterRangeQuery(String query, String operator, String field, // Object expValue) throws ODataApplicationException { // String rootKey = "range"; // boolean includeLower = !operator.equals("gt"); // boolean includeUpper = !operator.equals("lt"); // String valueKey = operator.startsWith("g") ? "from" : "to"; // JSONObject queryObj = new JSONObject(query); // JSONObject rootObj = queryObj.getJSONObject(rootKey); // JSONObject valueObject = rootObj.getJSONObject(field); // String actualValue = (String) valueObject.get(valueKey); // assertEquals(expValue, actualValue); // assertEquals(valueObject.get("include_lower"), includeLower); // assertEquals(valueObject.get("include_upper"), includeUpper); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static EdmAnnotation getAnalyzedAnnotation() { // EdmAnnotation annotation = mock(EdmAnnotation.class); // EdmTerm term = mock(EdmTerm.class); // EdmExpression expression = mock(EdmExpression.class); // EdmConstantExpression constantExpression = mock(EdmConstantExpression.class); // doReturn(Boolean.parseBoolean( // new AnnotationProvider().getAnnotation(AnnotationProvider.ANALYZED_TERM_NAME) // .getExpression().asConstant().getValue())).when(constantExpression) // .asPrimitive(); // doReturn(constantExpression).when(expression).asConstant(); // doReturn(AnnotationProvider.ANALYZED_TERM_NAME).when(term).getName(); // doReturn(term).when(annotation).getTerm(); // doReturn(expression).when(annotation).getExpression(); // return annotation; // }
import static com.hevelian.olastic.core.TestUtils.checkFilterEqualsQuery; import static com.hevelian.olastic.core.TestUtils.checkFilterNotEqualsQuery; import static com.hevelian.olastic.core.TestUtils.checkFilterRangeQuery; import static com.hevelian.olastic.core.TestUtils.getAnalyzedAnnotation; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.apache.olingo.commons.api.edm.EdmAnnotation; import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.core.edm.primitivetype.EdmInt32; import org.apache.olingo.commons.core.edm.primitivetype.EdmString; import org.apache.olingo.server.api.ODataApplicationException; import org.junit.Test;
package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl; /** * Tests for {@link PrimitiveMember} class. * * @author Taras Kohut */ public class PrimitiveMemberTest { private String field = "someField"; private String value = "'value'"; private String intValue = "10"; private EdmType edmString = new EdmString(); private EdmType edmInt = new EdmInt32(); private List<EdmAnnotation> annotations = Arrays.asList(getAnalyzedAnnotation()); @Test public void eq_PrimitiveAndLiteral_CorrectESQuery() throws Exception { PrimitiveMember left = new PrimitiveMember(field, annotations); LiteralMember right = new LiteralMember(value, edmString); ExpressionResult result = left.eq(right);
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterEqualsQuery(String query, String field, String value) { // checkFilterEqualsQueryInternal(query, field, value, false); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterNotEqualsQuery(String query, String field, String value) { // checkFilterEqualsQueryInternal(query, field, value, true); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterRangeQuery(String query, String operator, String field, // Object expValue) throws ODataApplicationException { // String rootKey = "range"; // boolean includeLower = !operator.equals("gt"); // boolean includeUpper = !operator.equals("lt"); // String valueKey = operator.startsWith("g") ? "from" : "to"; // JSONObject queryObj = new JSONObject(query); // JSONObject rootObj = queryObj.getJSONObject(rootKey); // JSONObject valueObject = rootObj.getJSONObject(field); // String actualValue = (String) valueObject.get(valueKey); // assertEquals(expValue, actualValue); // assertEquals(valueObject.get("include_lower"), includeLower); // assertEquals(valueObject.get("include_upper"), includeUpper); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static EdmAnnotation getAnalyzedAnnotation() { // EdmAnnotation annotation = mock(EdmAnnotation.class); // EdmTerm term = mock(EdmTerm.class); // EdmExpression expression = mock(EdmExpression.class); // EdmConstantExpression constantExpression = mock(EdmConstantExpression.class); // doReturn(Boolean.parseBoolean( // new AnnotationProvider().getAnnotation(AnnotationProvider.ANALYZED_TERM_NAME) // .getExpression().asConstant().getValue())).when(constantExpression) // .asPrimitive(); // doReturn(constantExpression).when(expression).asConstant(); // doReturn(AnnotationProvider.ANALYZED_TERM_NAME).when(term).getName(); // doReturn(term).when(annotation).getTerm(); // doReturn(expression).when(annotation).getExpression(); // return annotation; // } // Path: olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/PrimitiveMemberTest.java import static com.hevelian.olastic.core.TestUtils.checkFilterEqualsQuery; import static com.hevelian.olastic.core.TestUtils.checkFilterNotEqualsQuery; import static com.hevelian.olastic.core.TestUtils.checkFilterRangeQuery; import static com.hevelian.olastic.core.TestUtils.getAnalyzedAnnotation; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.apache.olingo.commons.api.edm.EdmAnnotation; import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.core.edm.primitivetype.EdmInt32; import org.apache.olingo.commons.core.edm.primitivetype.EdmString; import org.apache.olingo.server.api.ODataApplicationException; import org.junit.Test; package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl; /** * Tests for {@link PrimitiveMember} class. * * @author Taras Kohut */ public class PrimitiveMemberTest { private String field = "someField"; private String value = "'value'"; private String intValue = "10"; private EdmType edmString = new EdmString(); private EdmType edmInt = new EdmInt32(); private List<EdmAnnotation> annotations = Arrays.asList(getAnalyzedAnnotation()); @Test public void eq_PrimitiveAndLiteral_CorrectESQuery() throws Exception { PrimitiveMember left = new PrimitiveMember(field, annotations); LiteralMember right = new LiteralMember(value, edmString); ExpressionResult result = left.eq(right);
checkFilterEqualsQuery(result.getQueryBuilder().toString(), field, value);
Hevelian/hevelian-olastic
olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/PrimitiveMemberTest.java
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterEqualsQuery(String query, String field, String value) { // checkFilterEqualsQueryInternal(query, field, value, false); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterNotEqualsQuery(String query, String field, String value) { // checkFilterEqualsQueryInternal(query, field, value, true); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterRangeQuery(String query, String operator, String field, // Object expValue) throws ODataApplicationException { // String rootKey = "range"; // boolean includeLower = !operator.equals("gt"); // boolean includeUpper = !operator.equals("lt"); // String valueKey = operator.startsWith("g") ? "from" : "to"; // JSONObject queryObj = new JSONObject(query); // JSONObject rootObj = queryObj.getJSONObject(rootKey); // JSONObject valueObject = rootObj.getJSONObject(field); // String actualValue = (String) valueObject.get(valueKey); // assertEquals(expValue, actualValue); // assertEquals(valueObject.get("include_lower"), includeLower); // assertEquals(valueObject.get("include_upper"), includeUpper); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static EdmAnnotation getAnalyzedAnnotation() { // EdmAnnotation annotation = mock(EdmAnnotation.class); // EdmTerm term = mock(EdmTerm.class); // EdmExpression expression = mock(EdmExpression.class); // EdmConstantExpression constantExpression = mock(EdmConstantExpression.class); // doReturn(Boolean.parseBoolean( // new AnnotationProvider().getAnnotation(AnnotationProvider.ANALYZED_TERM_NAME) // .getExpression().asConstant().getValue())).when(constantExpression) // .asPrimitive(); // doReturn(constantExpression).when(expression).asConstant(); // doReturn(AnnotationProvider.ANALYZED_TERM_NAME).when(term).getName(); // doReturn(term).when(annotation).getTerm(); // doReturn(expression).when(annotation).getExpression(); // return annotation; // }
import static com.hevelian.olastic.core.TestUtils.checkFilterEqualsQuery; import static com.hevelian.olastic.core.TestUtils.checkFilterNotEqualsQuery; import static com.hevelian.olastic.core.TestUtils.checkFilterRangeQuery; import static com.hevelian.olastic.core.TestUtils.getAnalyzedAnnotation; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.apache.olingo.commons.api.edm.EdmAnnotation; import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.core.edm.primitivetype.EdmInt32; import org.apache.olingo.commons.core.edm.primitivetype.EdmString; import org.apache.olingo.server.api.ODataApplicationException; import org.junit.Test;
package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl; /** * Tests for {@link PrimitiveMember} class. * * @author Taras Kohut */ public class PrimitiveMemberTest { private String field = "someField"; private String value = "'value'"; private String intValue = "10"; private EdmType edmString = new EdmString(); private EdmType edmInt = new EdmInt32(); private List<EdmAnnotation> annotations = Arrays.asList(getAnalyzedAnnotation()); @Test public void eq_PrimitiveAndLiteral_CorrectESQuery() throws Exception { PrimitiveMember left = new PrimitiveMember(field, annotations); LiteralMember right = new LiteralMember(value, edmString); ExpressionResult result = left.eq(right); checkFilterEqualsQuery(result.getQueryBuilder().toString(), field, value); } @Test public void ne_PrimitiveAndLiteral_CorrectESQuery() throws Exception { PrimitiveMember left = new PrimitiveMember(field, annotations); LiteralMember right = new LiteralMember(value, edmString); ExpressionResult result = left.ne(right);
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterEqualsQuery(String query, String field, String value) { // checkFilterEqualsQueryInternal(query, field, value, false); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterNotEqualsQuery(String query, String field, String value) { // checkFilterEqualsQueryInternal(query, field, value, true); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterRangeQuery(String query, String operator, String field, // Object expValue) throws ODataApplicationException { // String rootKey = "range"; // boolean includeLower = !operator.equals("gt"); // boolean includeUpper = !operator.equals("lt"); // String valueKey = operator.startsWith("g") ? "from" : "to"; // JSONObject queryObj = new JSONObject(query); // JSONObject rootObj = queryObj.getJSONObject(rootKey); // JSONObject valueObject = rootObj.getJSONObject(field); // String actualValue = (String) valueObject.get(valueKey); // assertEquals(expValue, actualValue); // assertEquals(valueObject.get("include_lower"), includeLower); // assertEquals(valueObject.get("include_upper"), includeUpper); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static EdmAnnotation getAnalyzedAnnotation() { // EdmAnnotation annotation = mock(EdmAnnotation.class); // EdmTerm term = mock(EdmTerm.class); // EdmExpression expression = mock(EdmExpression.class); // EdmConstantExpression constantExpression = mock(EdmConstantExpression.class); // doReturn(Boolean.parseBoolean( // new AnnotationProvider().getAnnotation(AnnotationProvider.ANALYZED_TERM_NAME) // .getExpression().asConstant().getValue())).when(constantExpression) // .asPrimitive(); // doReturn(constantExpression).when(expression).asConstant(); // doReturn(AnnotationProvider.ANALYZED_TERM_NAME).when(term).getName(); // doReturn(term).when(annotation).getTerm(); // doReturn(expression).when(annotation).getExpression(); // return annotation; // } // Path: olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/PrimitiveMemberTest.java import static com.hevelian.olastic.core.TestUtils.checkFilterEqualsQuery; import static com.hevelian.olastic.core.TestUtils.checkFilterNotEqualsQuery; import static com.hevelian.olastic.core.TestUtils.checkFilterRangeQuery; import static com.hevelian.olastic.core.TestUtils.getAnalyzedAnnotation; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.apache.olingo.commons.api.edm.EdmAnnotation; import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.core.edm.primitivetype.EdmInt32; import org.apache.olingo.commons.core.edm.primitivetype.EdmString; import org.apache.olingo.server.api.ODataApplicationException; import org.junit.Test; package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl; /** * Tests for {@link PrimitiveMember} class. * * @author Taras Kohut */ public class PrimitiveMemberTest { private String field = "someField"; private String value = "'value'"; private String intValue = "10"; private EdmType edmString = new EdmString(); private EdmType edmInt = new EdmInt32(); private List<EdmAnnotation> annotations = Arrays.asList(getAnalyzedAnnotation()); @Test public void eq_PrimitiveAndLiteral_CorrectESQuery() throws Exception { PrimitiveMember left = new PrimitiveMember(field, annotations); LiteralMember right = new LiteralMember(value, edmString); ExpressionResult result = left.eq(right); checkFilterEqualsQuery(result.getQueryBuilder().toString(), field, value); } @Test public void ne_PrimitiveAndLiteral_CorrectESQuery() throws Exception { PrimitiveMember left = new PrimitiveMember(field, annotations); LiteralMember right = new LiteralMember(value, edmString); ExpressionResult result = left.ne(right);
checkFilterNotEqualsQuery(result.getQueryBuilder().toString(), field, value);
Hevelian/hevelian-olastic
olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/PrimitiveMemberTest.java
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterEqualsQuery(String query, String field, String value) { // checkFilterEqualsQueryInternal(query, field, value, false); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterNotEqualsQuery(String query, String field, String value) { // checkFilterEqualsQueryInternal(query, field, value, true); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterRangeQuery(String query, String operator, String field, // Object expValue) throws ODataApplicationException { // String rootKey = "range"; // boolean includeLower = !operator.equals("gt"); // boolean includeUpper = !operator.equals("lt"); // String valueKey = operator.startsWith("g") ? "from" : "to"; // JSONObject queryObj = new JSONObject(query); // JSONObject rootObj = queryObj.getJSONObject(rootKey); // JSONObject valueObject = rootObj.getJSONObject(field); // String actualValue = (String) valueObject.get(valueKey); // assertEquals(expValue, actualValue); // assertEquals(valueObject.get("include_lower"), includeLower); // assertEquals(valueObject.get("include_upper"), includeUpper); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static EdmAnnotation getAnalyzedAnnotation() { // EdmAnnotation annotation = mock(EdmAnnotation.class); // EdmTerm term = mock(EdmTerm.class); // EdmExpression expression = mock(EdmExpression.class); // EdmConstantExpression constantExpression = mock(EdmConstantExpression.class); // doReturn(Boolean.parseBoolean( // new AnnotationProvider().getAnnotation(AnnotationProvider.ANALYZED_TERM_NAME) // .getExpression().asConstant().getValue())).when(constantExpression) // .asPrimitive(); // doReturn(constantExpression).when(expression).asConstant(); // doReturn(AnnotationProvider.ANALYZED_TERM_NAME).when(term).getName(); // doReturn(term).when(annotation).getTerm(); // doReturn(expression).when(annotation).getExpression(); // return annotation; // }
import static com.hevelian.olastic.core.TestUtils.checkFilterEqualsQuery; import static com.hevelian.olastic.core.TestUtils.checkFilterNotEqualsQuery; import static com.hevelian.olastic.core.TestUtils.checkFilterRangeQuery; import static com.hevelian.olastic.core.TestUtils.getAnalyzedAnnotation; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.apache.olingo.commons.api.edm.EdmAnnotation; import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.core.edm.primitivetype.EdmInt32; import org.apache.olingo.commons.core.edm.primitivetype.EdmString; import org.apache.olingo.server.api.ODataApplicationException; import org.junit.Test;
package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl; /** * Tests for {@link PrimitiveMember} class. * * @author Taras Kohut */ public class PrimitiveMemberTest { private String field = "someField"; private String value = "'value'"; private String intValue = "10"; private EdmType edmString = new EdmString(); private EdmType edmInt = new EdmInt32(); private List<EdmAnnotation> annotations = Arrays.asList(getAnalyzedAnnotation()); @Test public void eq_PrimitiveAndLiteral_CorrectESQuery() throws Exception { PrimitiveMember left = new PrimitiveMember(field, annotations); LiteralMember right = new LiteralMember(value, edmString); ExpressionResult result = left.eq(right); checkFilterEqualsQuery(result.getQueryBuilder().toString(), field, value); } @Test public void ne_PrimitiveAndLiteral_CorrectESQuery() throws Exception { PrimitiveMember left = new PrimitiveMember(field, annotations); LiteralMember right = new LiteralMember(value, edmString); ExpressionResult result = left.ne(right); checkFilterNotEqualsQuery(result.getQueryBuilder().toString(), field, value); } @Test public void ge_PrimitiveAndLiteral_CorrectESQuery() throws Exception { PrimitiveMember left = new PrimitiveMember(field, annotations); LiteralMember right = new LiteralMember(intValue, edmInt); ExpressionResult result = left.ge(right);
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterEqualsQuery(String query, String field, String value) { // checkFilterEqualsQueryInternal(query, field, value, false); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterNotEqualsQuery(String query, String field, String value) { // checkFilterEqualsQueryInternal(query, field, value, true); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterRangeQuery(String query, String operator, String field, // Object expValue) throws ODataApplicationException { // String rootKey = "range"; // boolean includeLower = !operator.equals("gt"); // boolean includeUpper = !operator.equals("lt"); // String valueKey = operator.startsWith("g") ? "from" : "to"; // JSONObject queryObj = new JSONObject(query); // JSONObject rootObj = queryObj.getJSONObject(rootKey); // JSONObject valueObject = rootObj.getJSONObject(field); // String actualValue = (String) valueObject.get(valueKey); // assertEquals(expValue, actualValue); // assertEquals(valueObject.get("include_lower"), includeLower); // assertEquals(valueObject.get("include_upper"), includeUpper); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static EdmAnnotation getAnalyzedAnnotation() { // EdmAnnotation annotation = mock(EdmAnnotation.class); // EdmTerm term = mock(EdmTerm.class); // EdmExpression expression = mock(EdmExpression.class); // EdmConstantExpression constantExpression = mock(EdmConstantExpression.class); // doReturn(Boolean.parseBoolean( // new AnnotationProvider().getAnnotation(AnnotationProvider.ANALYZED_TERM_NAME) // .getExpression().asConstant().getValue())).when(constantExpression) // .asPrimitive(); // doReturn(constantExpression).when(expression).asConstant(); // doReturn(AnnotationProvider.ANALYZED_TERM_NAME).when(term).getName(); // doReturn(term).when(annotation).getTerm(); // doReturn(expression).when(annotation).getExpression(); // return annotation; // } // Path: olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/PrimitiveMemberTest.java import static com.hevelian.olastic.core.TestUtils.checkFilterEqualsQuery; import static com.hevelian.olastic.core.TestUtils.checkFilterNotEqualsQuery; import static com.hevelian.olastic.core.TestUtils.checkFilterRangeQuery; import static com.hevelian.olastic.core.TestUtils.getAnalyzedAnnotation; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.apache.olingo.commons.api.edm.EdmAnnotation; import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.core.edm.primitivetype.EdmInt32; import org.apache.olingo.commons.core.edm.primitivetype.EdmString; import org.apache.olingo.server.api.ODataApplicationException; import org.junit.Test; package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl; /** * Tests for {@link PrimitiveMember} class. * * @author Taras Kohut */ public class PrimitiveMemberTest { private String field = "someField"; private String value = "'value'"; private String intValue = "10"; private EdmType edmString = new EdmString(); private EdmType edmInt = new EdmInt32(); private List<EdmAnnotation> annotations = Arrays.asList(getAnalyzedAnnotation()); @Test public void eq_PrimitiveAndLiteral_CorrectESQuery() throws Exception { PrimitiveMember left = new PrimitiveMember(field, annotations); LiteralMember right = new LiteralMember(value, edmString); ExpressionResult result = left.eq(right); checkFilterEqualsQuery(result.getQueryBuilder().toString(), field, value); } @Test public void ne_PrimitiveAndLiteral_CorrectESQuery() throws Exception { PrimitiveMember left = new PrimitiveMember(field, annotations); LiteralMember right = new LiteralMember(value, edmString); ExpressionResult result = left.ne(right); checkFilterNotEqualsQuery(result.getQueryBuilder().toString(), field, value); } @Test public void ge_PrimitiveAndLiteral_CorrectESQuery() throws Exception { PrimitiveMember left = new PrimitiveMember(field, annotations); LiteralMember right = new LiteralMember(intValue, edmInt); ExpressionResult result = left.ge(right);
checkFilterRangeQuery(result.getQueryBuilder().toString(), "ge", field, intValue);
Hevelian/hevelian-olastic
olastic-core/src/main/java/com/hevelian/olastic/core/elastic/utils/ElasticUtils.java
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/edm/annotations/AnnotationProvider.java // public class AnnotationProvider { // /** Analyzed term name. */ // public static final String ANALYZED_TERM_NAME = "Analyzed"; // // private HashMap<String, TermAnnotation> annotations = new HashMap<>(); // // // declaring terms and annotations // private CsdlAnnotation analyzedAnnotation = new CsdlAnnotation().setTerm("OData.Analyzed") // .setExpression(new CsdlConstantExpression( // CsdlConstantExpression.ConstantExpressionType.Bool, "true")); // // private CsdlTerm analyzedTerm = new CsdlTerm().setAppliesTo(Arrays.asList("Property")) // .setName(ANALYZED_TERM_NAME).setType(EdmPrimitiveTypeKind.String.getFullQualifiedName() // .getFullQualifiedNameAsString()); // // /** // * Default constructor. Sets default annotation. // */ // public AnnotationProvider() { // annotations.put(ANALYZED_TERM_NAME, new TermAnnotation(analyzedTerm, analyzedAnnotation)); // } // // /** // * Gets annotation by term name. // * // * @param termName // * term name // * @return found annotation, otherwise null // */ // public CsdlAnnotation getAnnotation(String termName) { // TermAnnotation temAnnotation = annotations.get(termName); // if (temAnnotation != null) { // return annotations.get(termName).annotation; // } else { // return null; // } // } // // /** // * Gets term by term name. // * // * @param termName // * term name // * @return found term, otherwise null // */ // public CsdlTerm getTerm(String termName) { // TermAnnotation temAnnotation = annotations.get(termName); // if (temAnnotation != null) { // return annotations.get(termName).term; // } else { // return null; // } // } // // public List<CsdlTerm> getTerms() { // return annotations.entrySet().stream().map(entry -> entry.getValue().term) // .collect(Collectors.toList()); // } // // /** // * Class represents container for term and annotation. // */ // private class TermAnnotation { // private CsdlAnnotation annotation; // private CsdlTerm term; // // TermAnnotation(CsdlTerm term, CsdlAnnotation annotation) { // this.term = term; // this.annotation = annotation; // } // } // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/ElasticConstants.java // public final class ElasticConstants { // // /** Field data type property. */ // public static final String FIELD_DATATYPE_PROPERTY = "type"; // /** Properties property name. */ // public static final String PROPERTIES_PROPERTY = "properties"; // /** Parent property name. */ // public static final String PARENT_PROPERTY = "_parent"; // /** ID field name. */ // public static final String ID_FIELD_NAME = "_id"; // /** Suffix for keyword (not-analyzed) field. */ // public static final String KEYWORD_SUFFIX = "keyword"; // /** Field suffix delimiter. */ // public static final String SUFFIX_DELIMITER = "."; // /** Nested path separator. */ // public static final String NESTED_PATH_SEPARATOR = "."; // /** Wildcard character. */ // public static final String WILDCARD_CHAR = "*"; // /** // * The _all field is a special catch-all field which concatenates the values // * of all of the other fields into one big string. // */ // public static final String ALL_FIELD = "_all"; // // private ElasticConstants() { // } // }
import com.hevelian.olastic.core.api.edm.annotations.AnnotationProvider; import com.hevelian.olastic.core.elastic.ElasticConstants; import org.apache.olingo.commons.api.edm.EdmAnnotation; import java.util.List; import java.util.Optional;
package com.hevelian.olastic.core.elastic.utils; /** * Elasticsearch utils. */ public final class ElasticUtils { private ElasticUtils() { } /** * Returns keyword field name if needed. Keyword field is non analyzed * field. * * @param name * field name * @param annotations * field edm type * @return property's keyword field name */ public static String addKeywordIfNeeded(String name, List<EdmAnnotation> annotations) { boolean isAnalyzed = false; Optional<EdmAnnotation> analyzedAnnotation = annotations.stream() .filter(annotation -> annotation.getTerm().getName()
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/edm/annotations/AnnotationProvider.java // public class AnnotationProvider { // /** Analyzed term name. */ // public static final String ANALYZED_TERM_NAME = "Analyzed"; // // private HashMap<String, TermAnnotation> annotations = new HashMap<>(); // // // declaring terms and annotations // private CsdlAnnotation analyzedAnnotation = new CsdlAnnotation().setTerm("OData.Analyzed") // .setExpression(new CsdlConstantExpression( // CsdlConstantExpression.ConstantExpressionType.Bool, "true")); // // private CsdlTerm analyzedTerm = new CsdlTerm().setAppliesTo(Arrays.asList("Property")) // .setName(ANALYZED_TERM_NAME).setType(EdmPrimitiveTypeKind.String.getFullQualifiedName() // .getFullQualifiedNameAsString()); // // /** // * Default constructor. Sets default annotation. // */ // public AnnotationProvider() { // annotations.put(ANALYZED_TERM_NAME, new TermAnnotation(analyzedTerm, analyzedAnnotation)); // } // // /** // * Gets annotation by term name. // * // * @param termName // * term name // * @return found annotation, otherwise null // */ // public CsdlAnnotation getAnnotation(String termName) { // TermAnnotation temAnnotation = annotations.get(termName); // if (temAnnotation != null) { // return annotations.get(termName).annotation; // } else { // return null; // } // } // // /** // * Gets term by term name. // * // * @param termName // * term name // * @return found term, otherwise null // */ // public CsdlTerm getTerm(String termName) { // TermAnnotation temAnnotation = annotations.get(termName); // if (temAnnotation != null) { // return annotations.get(termName).term; // } else { // return null; // } // } // // public List<CsdlTerm> getTerms() { // return annotations.entrySet().stream().map(entry -> entry.getValue().term) // .collect(Collectors.toList()); // } // // /** // * Class represents container for term and annotation. // */ // private class TermAnnotation { // private CsdlAnnotation annotation; // private CsdlTerm term; // // TermAnnotation(CsdlTerm term, CsdlAnnotation annotation) { // this.term = term; // this.annotation = annotation; // } // } // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/ElasticConstants.java // public final class ElasticConstants { // // /** Field data type property. */ // public static final String FIELD_DATATYPE_PROPERTY = "type"; // /** Properties property name. */ // public static final String PROPERTIES_PROPERTY = "properties"; // /** Parent property name. */ // public static final String PARENT_PROPERTY = "_parent"; // /** ID field name. */ // public static final String ID_FIELD_NAME = "_id"; // /** Suffix for keyword (not-analyzed) field. */ // public static final String KEYWORD_SUFFIX = "keyword"; // /** Field suffix delimiter. */ // public static final String SUFFIX_DELIMITER = "."; // /** Nested path separator. */ // public static final String NESTED_PATH_SEPARATOR = "."; // /** Wildcard character. */ // public static final String WILDCARD_CHAR = "*"; // /** // * The _all field is a special catch-all field which concatenates the values // * of all of the other fields into one big string. // */ // public static final String ALL_FIELD = "_all"; // // private ElasticConstants() { // } // } // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/utils/ElasticUtils.java import com.hevelian.olastic.core.api.edm.annotations.AnnotationProvider; import com.hevelian.olastic.core.elastic.ElasticConstants; import org.apache.olingo.commons.api.edm.EdmAnnotation; import java.util.List; import java.util.Optional; package com.hevelian.olastic.core.elastic.utils; /** * Elasticsearch utils. */ public final class ElasticUtils { private ElasticUtils() { } /** * Returns keyword field name if needed. Keyword field is non analyzed * field. * * @param name * field name * @param annotations * field edm type * @return property's keyword field name */ public static String addKeywordIfNeeded(String name, List<EdmAnnotation> annotations) { boolean isAnalyzed = false; Optional<EdmAnnotation> analyzedAnnotation = annotations.stream() .filter(annotation -> annotation.getTerm().getName()
.equals(AnnotationProvider.ANALYZED_TERM_NAME))
Hevelian/hevelian-olastic
olastic-core/src/main/java/com/hevelian/olastic/core/elastic/utils/ElasticUtils.java
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/edm/annotations/AnnotationProvider.java // public class AnnotationProvider { // /** Analyzed term name. */ // public static final String ANALYZED_TERM_NAME = "Analyzed"; // // private HashMap<String, TermAnnotation> annotations = new HashMap<>(); // // // declaring terms and annotations // private CsdlAnnotation analyzedAnnotation = new CsdlAnnotation().setTerm("OData.Analyzed") // .setExpression(new CsdlConstantExpression( // CsdlConstantExpression.ConstantExpressionType.Bool, "true")); // // private CsdlTerm analyzedTerm = new CsdlTerm().setAppliesTo(Arrays.asList("Property")) // .setName(ANALYZED_TERM_NAME).setType(EdmPrimitiveTypeKind.String.getFullQualifiedName() // .getFullQualifiedNameAsString()); // // /** // * Default constructor. Sets default annotation. // */ // public AnnotationProvider() { // annotations.put(ANALYZED_TERM_NAME, new TermAnnotation(analyzedTerm, analyzedAnnotation)); // } // // /** // * Gets annotation by term name. // * // * @param termName // * term name // * @return found annotation, otherwise null // */ // public CsdlAnnotation getAnnotation(String termName) { // TermAnnotation temAnnotation = annotations.get(termName); // if (temAnnotation != null) { // return annotations.get(termName).annotation; // } else { // return null; // } // } // // /** // * Gets term by term name. // * // * @param termName // * term name // * @return found term, otherwise null // */ // public CsdlTerm getTerm(String termName) { // TermAnnotation temAnnotation = annotations.get(termName); // if (temAnnotation != null) { // return annotations.get(termName).term; // } else { // return null; // } // } // // public List<CsdlTerm> getTerms() { // return annotations.entrySet().stream().map(entry -> entry.getValue().term) // .collect(Collectors.toList()); // } // // /** // * Class represents container for term and annotation. // */ // private class TermAnnotation { // private CsdlAnnotation annotation; // private CsdlTerm term; // // TermAnnotation(CsdlTerm term, CsdlAnnotation annotation) { // this.term = term; // this.annotation = annotation; // } // } // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/ElasticConstants.java // public final class ElasticConstants { // // /** Field data type property. */ // public static final String FIELD_DATATYPE_PROPERTY = "type"; // /** Properties property name. */ // public static final String PROPERTIES_PROPERTY = "properties"; // /** Parent property name. */ // public static final String PARENT_PROPERTY = "_parent"; // /** ID field name. */ // public static final String ID_FIELD_NAME = "_id"; // /** Suffix for keyword (not-analyzed) field. */ // public static final String KEYWORD_SUFFIX = "keyword"; // /** Field suffix delimiter. */ // public static final String SUFFIX_DELIMITER = "."; // /** Nested path separator. */ // public static final String NESTED_PATH_SEPARATOR = "."; // /** Wildcard character. */ // public static final String WILDCARD_CHAR = "*"; // /** // * The _all field is a special catch-all field which concatenates the values // * of all of the other fields into one big string. // */ // public static final String ALL_FIELD = "_all"; // // private ElasticConstants() { // } // }
import com.hevelian.olastic.core.api.edm.annotations.AnnotationProvider; import com.hevelian.olastic.core.elastic.ElasticConstants; import org.apache.olingo.commons.api.edm.EdmAnnotation; import java.util.List; import java.util.Optional;
package com.hevelian.olastic.core.elastic.utils; /** * Elasticsearch utils. */ public final class ElasticUtils { private ElasticUtils() { } /** * Returns keyword field name if needed. Keyword field is non analyzed * field. * * @param name * field name * @param annotations * field edm type * @return property's keyword field name */ public static String addKeywordIfNeeded(String name, List<EdmAnnotation> annotations) { boolean isAnalyzed = false; Optional<EdmAnnotation> analyzedAnnotation = annotations.stream() .filter(annotation -> annotation.getTerm().getName() .equals(AnnotationProvider.ANALYZED_TERM_NAME)) .findFirst(); if (analyzedAnnotation.isPresent()) { isAnalyzed = (Boolean) (analyzedAnnotation.get().getExpression().asConstant() .asPrimitive()); } return isAnalyzed ? addKeyword(name) : name; } /** * Returns keyword field name. Keyword field is non analyzed field. * * @param fieldName * name of the field * @return property's keyword field name */ public static String addKeyword(String fieldName) {
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/edm/annotations/AnnotationProvider.java // public class AnnotationProvider { // /** Analyzed term name. */ // public static final String ANALYZED_TERM_NAME = "Analyzed"; // // private HashMap<String, TermAnnotation> annotations = new HashMap<>(); // // // declaring terms and annotations // private CsdlAnnotation analyzedAnnotation = new CsdlAnnotation().setTerm("OData.Analyzed") // .setExpression(new CsdlConstantExpression( // CsdlConstantExpression.ConstantExpressionType.Bool, "true")); // // private CsdlTerm analyzedTerm = new CsdlTerm().setAppliesTo(Arrays.asList("Property")) // .setName(ANALYZED_TERM_NAME).setType(EdmPrimitiveTypeKind.String.getFullQualifiedName() // .getFullQualifiedNameAsString()); // // /** // * Default constructor. Sets default annotation. // */ // public AnnotationProvider() { // annotations.put(ANALYZED_TERM_NAME, new TermAnnotation(analyzedTerm, analyzedAnnotation)); // } // // /** // * Gets annotation by term name. // * // * @param termName // * term name // * @return found annotation, otherwise null // */ // public CsdlAnnotation getAnnotation(String termName) { // TermAnnotation temAnnotation = annotations.get(termName); // if (temAnnotation != null) { // return annotations.get(termName).annotation; // } else { // return null; // } // } // // /** // * Gets term by term name. // * // * @param termName // * term name // * @return found term, otherwise null // */ // public CsdlTerm getTerm(String termName) { // TermAnnotation temAnnotation = annotations.get(termName); // if (temAnnotation != null) { // return annotations.get(termName).term; // } else { // return null; // } // } // // public List<CsdlTerm> getTerms() { // return annotations.entrySet().stream().map(entry -> entry.getValue().term) // .collect(Collectors.toList()); // } // // /** // * Class represents container for term and annotation. // */ // private class TermAnnotation { // private CsdlAnnotation annotation; // private CsdlTerm term; // // TermAnnotation(CsdlTerm term, CsdlAnnotation annotation) { // this.term = term; // this.annotation = annotation; // } // } // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/ElasticConstants.java // public final class ElasticConstants { // // /** Field data type property. */ // public static final String FIELD_DATATYPE_PROPERTY = "type"; // /** Properties property name. */ // public static final String PROPERTIES_PROPERTY = "properties"; // /** Parent property name. */ // public static final String PARENT_PROPERTY = "_parent"; // /** ID field name. */ // public static final String ID_FIELD_NAME = "_id"; // /** Suffix for keyword (not-analyzed) field. */ // public static final String KEYWORD_SUFFIX = "keyword"; // /** Field suffix delimiter. */ // public static final String SUFFIX_DELIMITER = "."; // /** Nested path separator. */ // public static final String NESTED_PATH_SEPARATOR = "."; // /** Wildcard character. */ // public static final String WILDCARD_CHAR = "*"; // /** // * The _all field is a special catch-all field which concatenates the values // * of all of the other fields into one big string. // */ // public static final String ALL_FIELD = "_all"; // // private ElasticConstants() { // } // } // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/utils/ElasticUtils.java import com.hevelian.olastic.core.api.edm.annotations.AnnotationProvider; import com.hevelian.olastic.core.elastic.ElasticConstants; import org.apache.olingo.commons.api.edm.EdmAnnotation; import java.util.List; import java.util.Optional; package com.hevelian.olastic.core.elastic.utils; /** * Elasticsearch utils. */ public final class ElasticUtils { private ElasticUtils() { } /** * Returns keyword field name if needed. Keyword field is non analyzed * field. * * @param name * field name * @param annotations * field edm type * @return property's keyword field name */ public static String addKeywordIfNeeded(String name, List<EdmAnnotation> annotations) { boolean isAnalyzed = false; Optional<EdmAnnotation> analyzedAnnotation = annotations.stream() .filter(annotation -> annotation.getTerm().getName() .equals(AnnotationProvider.ANALYZED_TERM_NAME)) .findFirst(); if (analyzedAnnotation.isPresent()) { isAnalyzed = (Boolean) (analyzedAnnotation.get().getExpression().asConstant() .asPrimitive()); } return isAnalyzed ? addKeyword(name) : name; } /** * Returns keyword field name. Keyword field is non analyzed field. * * @param fieldName * name of the field * @return property's keyword field name */ public static String addKeyword(String fieldName) {
return fieldName + ElasticConstants.SUFFIX_DELIMITER + ElasticConstants.KEYWORD_SUFFIX;
Hevelian/hevelian-olastic
olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/ParentPrimitiveMemberTest.java
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterParentEqualsQuery(String query, String parent, String field, // String value) { // checkFilterParentEqualsQueryInternal(query, parent, field, value, false); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterParentNotEqualsQuery(String query, String parent, String field, // String value) { // checkFilterParentEqualsQueryInternal(query, parent, field, value, true); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static EdmAnnotation getAnalyzedAnnotation() { // EdmAnnotation annotation = mock(EdmAnnotation.class); // EdmTerm term = mock(EdmTerm.class); // EdmExpression expression = mock(EdmExpression.class); // EdmConstantExpression constantExpression = mock(EdmConstantExpression.class); // doReturn(Boolean.parseBoolean( // new AnnotationProvider().getAnnotation(AnnotationProvider.ANALYZED_TERM_NAME) // .getExpression().asConstant().getValue())).when(constantExpression) // .asPrimitive(); // doReturn(constantExpression).when(expression).asConstant(); // doReturn(AnnotationProvider.ANALYZED_TERM_NAME).when(term).getName(); // doReturn(term).when(annotation).getTerm(); // doReturn(expression).when(annotation).getExpression(); // return annotation; // }
import static com.hevelian.olastic.core.TestUtils.checkFilterParentEqualsQuery; import static com.hevelian.olastic.core.TestUtils.checkFilterParentNotEqualsQuery; import static com.hevelian.olastic.core.TestUtils.getAnalyzedAnnotation; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.apache.olingo.commons.api.edm.EdmAnnotation; import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.core.edm.primitivetype.EdmInt32; import org.apache.olingo.commons.core.edm.primitivetype.EdmString; import org.apache.olingo.server.api.ODataApplicationException; import org.json.JSONObject; import org.junit.Test;
package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl; /** * Tests for {@link ParentPrimitiveMember} class. * * @author Taras Kohut */ public class ParentPrimitiveMemberTest { private String field = "someField"; private String value = "'value'"; private String intValue = "10";
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterParentEqualsQuery(String query, String parent, String field, // String value) { // checkFilterParentEqualsQueryInternal(query, parent, field, value, false); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterParentNotEqualsQuery(String query, String parent, String field, // String value) { // checkFilterParentEqualsQueryInternal(query, parent, field, value, true); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static EdmAnnotation getAnalyzedAnnotation() { // EdmAnnotation annotation = mock(EdmAnnotation.class); // EdmTerm term = mock(EdmTerm.class); // EdmExpression expression = mock(EdmExpression.class); // EdmConstantExpression constantExpression = mock(EdmConstantExpression.class); // doReturn(Boolean.parseBoolean( // new AnnotationProvider().getAnnotation(AnnotationProvider.ANALYZED_TERM_NAME) // .getExpression().asConstant().getValue())).when(constantExpression) // .asPrimitive(); // doReturn(constantExpression).when(expression).asConstant(); // doReturn(AnnotationProvider.ANALYZED_TERM_NAME).when(term).getName(); // doReturn(term).when(annotation).getTerm(); // doReturn(expression).when(annotation).getExpression(); // return annotation; // } // Path: olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/ParentPrimitiveMemberTest.java import static com.hevelian.olastic.core.TestUtils.checkFilterParentEqualsQuery; import static com.hevelian.olastic.core.TestUtils.checkFilterParentNotEqualsQuery; import static com.hevelian.olastic.core.TestUtils.getAnalyzedAnnotation; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.apache.olingo.commons.api.edm.EdmAnnotation; import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.core.edm.primitivetype.EdmInt32; import org.apache.olingo.commons.core.edm.primitivetype.EdmString; import org.apache.olingo.server.api.ODataApplicationException; import org.json.JSONObject; import org.junit.Test; package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl; /** * Tests for {@link ParentPrimitiveMember} class. * * @author Taras Kohut */ public class ParentPrimitiveMemberTest { private String field = "someField"; private String value = "'value'"; private String intValue = "10";
private List<EdmAnnotation> annotations = Arrays.asList(getAnalyzedAnnotation());
Hevelian/hevelian-olastic
olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/ParentPrimitiveMemberTest.java
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterParentEqualsQuery(String query, String parent, String field, // String value) { // checkFilterParentEqualsQueryInternal(query, parent, field, value, false); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterParentNotEqualsQuery(String query, String parent, String field, // String value) { // checkFilterParentEqualsQueryInternal(query, parent, field, value, true); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static EdmAnnotation getAnalyzedAnnotation() { // EdmAnnotation annotation = mock(EdmAnnotation.class); // EdmTerm term = mock(EdmTerm.class); // EdmExpression expression = mock(EdmExpression.class); // EdmConstantExpression constantExpression = mock(EdmConstantExpression.class); // doReturn(Boolean.parseBoolean( // new AnnotationProvider().getAnnotation(AnnotationProvider.ANALYZED_TERM_NAME) // .getExpression().asConstant().getValue())).when(constantExpression) // .asPrimitive(); // doReturn(constantExpression).when(expression).asConstant(); // doReturn(AnnotationProvider.ANALYZED_TERM_NAME).when(term).getName(); // doReturn(term).when(annotation).getTerm(); // doReturn(expression).when(annotation).getExpression(); // return annotation; // }
import static com.hevelian.olastic.core.TestUtils.checkFilterParentEqualsQuery; import static com.hevelian.olastic.core.TestUtils.checkFilterParentNotEqualsQuery; import static com.hevelian.olastic.core.TestUtils.getAnalyzedAnnotation; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.apache.olingo.commons.api.edm.EdmAnnotation; import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.core.edm.primitivetype.EdmInt32; import org.apache.olingo.commons.core.edm.primitivetype.EdmString; import org.apache.olingo.server.api.ODataApplicationException; import org.json.JSONObject; import org.junit.Test;
package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl; /** * Tests for {@link ParentPrimitiveMember} class. * * @author Taras Kohut */ public class ParentPrimitiveMemberTest { private String field = "someField"; private String value = "'value'"; private String intValue = "10"; private List<EdmAnnotation> annotations = Arrays.asList(getAnalyzedAnnotation()); private EdmType edmString = new EdmString(); private EdmType edmInt = new EdmInt32(); private List<String> parentTypes = Arrays.asList("parentType"); private PrimitiveMember primitiveMember = new PrimitiveMember(field, annotations); @Test public void eq_ParentAndLiteral_CorrectESQuery() throws Exception { ParentPrimitiveMember left = new ParentPrimitiveMember(parentTypes, primitiveMember); LiteralMember right = new LiteralMember(value, edmString); ExpressionResult result = left.eq(right);
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterParentEqualsQuery(String query, String parent, String field, // String value) { // checkFilterParentEqualsQueryInternal(query, parent, field, value, false); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterParentNotEqualsQuery(String query, String parent, String field, // String value) { // checkFilterParentEqualsQueryInternal(query, parent, field, value, true); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static EdmAnnotation getAnalyzedAnnotation() { // EdmAnnotation annotation = mock(EdmAnnotation.class); // EdmTerm term = mock(EdmTerm.class); // EdmExpression expression = mock(EdmExpression.class); // EdmConstantExpression constantExpression = mock(EdmConstantExpression.class); // doReturn(Boolean.parseBoolean( // new AnnotationProvider().getAnnotation(AnnotationProvider.ANALYZED_TERM_NAME) // .getExpression().asConstant().getValue())).when(constantExpression) // .asPrimitive(); // doReturn(constantExpression).when(expression).asConstant(); // doReturn(AnnotationProvider.ANALYZED_TERM_NAME).when(term).getName(); // doReturn(term).when(annotation).getTerm(); // doReturn(expression).when(annotation).getExpression(); // return annotation; // } // Path: olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/ParentPrimitiveMemberTest.java import static com.hevelian.olastic.core.TestUtils.checkFilterParentEqualsQuery; import static com.hevelian.olastic.core.TestUtils.checkFilterParentNotEqualsQuery; import static com.hevelian.olastic.core.TestUtils.getAnalyzedAnnotation; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.apache.olingo.commons.api.edm.EdmAnnotation; import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.core.edm.primitivetype.EdmInt32; import org.apache.olingo.commons.core.edm.primitivetype.EdmString; import org.apache.olingo.server.api.ODataApplicationException; import org.json.JSONObject; import org.junit.Test; package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl; /** * Tests for {@link ParentPrimitiveMember} class. * * @author Taras Kohut */ public class ParentPrimitiveMemberTest { private String field = "someField"; private String value = "'value'"; private String intValue = "10"; private List<EdmAnnotation> annotations = Arrays.asList(getAnalyzedAnnotation()); private EdmType edmString = new EdmString(); private EdmType edmInt = new EdmInt32(); private List<String> parentTypes = Arrays.asList("parentType"); private PrimitiveMember primitiveMember = new PrimitiveMember(field, annotations); @Test public void eq_ParentAndLiteral_CorrectESQuery() throws Exception { ParentPrimitiveMember left = new ParentPrimitiveMember(parentTypes, primitiveMember); LiteralMember right = new LiteralMember(value, edmString); ExpressionResult result = left.eq(right);
checkFilterParentEqualsQuery(result.getQueryBuilder().toString(), parentTypes.get(0), field,
Hevelian/hevelian-olastic
olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/ParentPrimitiveMemberTest.java
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterParentEqualsQuery(String query, String parent, String field, // String value) { // checkFilterParentEqualsQueryInternal(query, parent, field, value, false); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterParentNotEqualsQuery(String query, String parent, String field, // String value) { // checkFilterParentEqualsQueryInternal(query, parent, field, value, true); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static EdmAnnotation getAnalyzedAnnotation() { // EdmAnnotation annotation = mock(EdmAnnotation.class); // EdmTerm term = mock(EdmTerm.class); // EdmExpression expression = mock(EdmExpression.class); // EdmConstantExpression constantExpression = mock(EdmConstantExpression.class); // doReturn(Boolean.parseBoolean( // new AnnotationProvider().getAnnotation(AnnotationProvider.ANALYZED_TERM_NAME) // .getExpression().asConstant().getValue())).when(constantExpression) // .asPrimitive(); // doReturn(constantExpression).when(expression).asConstant(); // doReturn(AnnotationProvider.ANALYZED_TERM_NAME).when(term).getName(); // doReturn(term).when(annotation).getTerm(); // doReturn(expression).when(annotation).getExpression(); // return annotation; // }
import static com.hevelian.olastic.core.TestUtils.checkFilterParentEqualsQuery; import static com.hevelian.olastic.core.TestUtils.checkFilterParentNotEqualsQuery; import static com.hevelian.olastic.core.TestUtils.getAnalyzedAnnotation; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.apache.olingo.commons.api.edm.EdmAnnotation; import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.core.edm.primitivetype.EdmInt32; import org.apache.olingo.commons.core.edm.primitivetype.EdmString; import org.apache.olingo.server.api.ODataApplicationException; import org.json.JSONObject; import org.junit.Test;
List<String> severalTypes = Arrays.asList("Author", "Book", "Character"); ParentPrimitiveMember left = new ParentPrimitiveMember(severalTypes, primitiveMember); LiteralMember right = new LiteralMember(value, edmString); ExpressionResult result = left.eq(right); JSONObject firstChild = new JSONObject(result.getQueryBuilder().toString()) .getJSONObject("has_parent"); String firstActualType = (String) firstChild.get("parent_type"); assertEquals(severalTypes.get(0), firstActualType); JSONObject secondChild = firstChild.getJSONObject("query").getJSONObject("has_parent"); String secondActualType = (String) secondChild.get("parent_type"); assertEquals(severalTypes.get(1), secondActualType); JSONObject thirdChild = secondChild.getJSONObject("query").getJSONObject("has_parent"); String thirdActualType = (String) thirdChild.get("parent_type"); assertEquals(severalTypes.get(2), thirdActualType); JSONObject rootObj = thirdChild.getJSONObject("query").getJSONObject("term"); String fieldName = field + ".keyword"; JSONObject valueObject = rootObj.getJSONObject(fieldName); String actualValue = (String) valueObject.get("value"); assertEquals(value.substring(1, value.length() - 1), actualValue); } @Test public void ne_ParentAndLiteral_CorrectESQuery() throws Exception { ParentPrimitiveMember left = new ParentPrimitiveMember(parentTypes, primitiveMember); LiteralMember right = new LiteralMember(value, edmString); ExpressionResult result = left.ne(right);
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterParentEqualsQuery(String query, String parent, String field, // String value) { // checkFilterParentEqualsQueryInternal(query, parent, field, value, false); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static void checkFilterParentNotEqualsQuery(String query, String parent, String field, // String value) { // checkFilterParentEqualsQueryInternal(query, parent, field, value, true); // } // // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java // public static EdmAnnotation getAnalyzedAnnotation() { // EdmAnnotation annotation = mock(EdmAnnotation.class); // EdmTerm term = mock(EdmTerm.class); // EdmExpression expression = mock(EdmExpression.class); // EdmConstantExpression constantExpression = mock(EdmConstantExpression.class); // doReturn(Boolean.parseBoolean( // new AnnotationProvider().getAnnotation(AnnotationProvider.ANALYZED_TERM_NAME) // .getExpression().asConstant().getValue())).when(constantExpression) // .asPrimitive(); // doReturn(constantExpression).when(expression).asConstant(); // doReturn(AnnotationProvider.ANALYZED_TERM_NAME).when(term).getName(); // doReturn(term).when(annotation).getTerm(); // doReturn(expression).when(annotation).getExpression(); // return annotation; // } // Path: olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/ParentPrimitiveMemberTest.java import static com.hevelian.olastic.core.TestUtils.checkFilterParentEqualsQuery; import static com.hevelian.olastic.core.TestUtils.checkFilterParentNotEqualsQuery; import static com.hevelian.olastic.core.TestUtils.getAnalyzedAnnotation; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.List; import org.apache.olingo.commons.api.edm.EdmAnnotation; import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.core.edm.primitivetype.EdmInt32; import org.apache.olingo.commons.core.edm.primitivetype.EdmString; import org.apache.olingo.server.api.ODataApplicationException; import org.json.JSONObject; import org.junit.Test; List<String> severalTypes = Arrays.asList("Author", "Book", "Character"); ParentPrimitiveMember left = new ParentPrimitiveMember(severalTypes, primitiveMember); LiteralMember right = new LiteralMember(value, edmString); ExpressionResult result = left.eq(right); JSONObject firstChild = new JSONObject(result.getQueryBuilder().toString()) .getJSONObject("has_parent"); String firstActualType = (String) firstChild.get("parent_type"); assertEquals(severalTypes.get(0), firstActualType); JSONObject secondChild = firstChild.getJSONObject("query").getJSONObject("has_parent"); String secondActualType = (String) secondChild.get("parent_type"); assertEquals(severalTypes.get(1), secondActualType); JSONObject thirdChild = secondChild.getJSONObject("query").getJSONObject("has_parent"); String thirdActualType = (String) thirdChild.get("parent_type"); assertEquals(severalTypes.get(2), thirdActualType); JSONObject rootObj = thirdChild.getJSONObject("query").getJSONObject("term"); String fieldName = field + ".keyword"; JSONObject valueObject = rootObj.getJSONObject(fieldName); String actualValue = (String) valueObject.get("value"); assertEquals(value.substring(1, value.length() - 1), actualValue); } @Test public void ne_ParentAndLiteral_CorrectESQuery() throws Exception { ParentPrimitiveMember left = new ParentPrimitiveMember(parentTypes, primitiveMember); LiteralMember right = new LiteralMember(value, edmString); ExpressionResult result = left.ne(right);
checkFilterParentNotEqualsQuery(result.getQueryBuilder().toString(), parentTypes.get(0),
Hevelian/hevelian-olastic
olastic-core/src/main/java/com/hevelian/olastic/core/elastic/queries/Query.java
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/pagination/Pagination.java // public class Pagination { // /** Default skip value. */ // public static final int SKIP_DEFAULT = 0; // /** Default top value. */ // public static final int TOP_DEFAULT = 25; // private int top; // private int skip; // private List<Sort> orderBy; // // /** // * Initializes pagination with all the data. // * // * @param top // * top count // * @param skip // * skip count // * @param orderBy // * order by field // */ // public Pagination(int top, int skip, List<Sort> orderBy) { // this.top = top; // this.skip = skip; // this.orderBy = orderBy; // } // // public int getTop() { // return top; // } // // public void setTop(int top) { // this.top = top; // } // // public int getSkip() { // return skip; // } // // public void setSkip(int skip) { // this.skip = skip; // } // // public List<Sort> getOrderBy() { // return orderBy; // } // // public void setOrderBy(List<Sort> orderBy) { // this.orderBy = orderBy; // } // }
import org.elasticsearch.index.query.QueryBuilder; import com.hevelian.olastic.core.elastic.pagination.Pagination; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NonNull; import lombok.Setter;
package com.hevelian.olastic.core.elastic.queries; /** * Query with base parameters for all queries to create request. * * @author rdidyk */ @AllArgsConstructor @Getter @Setter public class Query { @NonNull private String index; @NonNull private String[] types; @NonNull private QueryBuilder queryBuilder;
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/pagination/Pagination.java // public class Pagination { // /** Default skip value. */ // public static final int SKIP_DEFAULT = 0; // /** Default top value. */ // public static final int TOP_DEFAULT = 25; // private int top; // private int skip; // private List<Sort> orderBy; // // /** // * Initializes pagination with all the data. // * // * @param top // * top count // * @param skip // * skip count // * @param orderBy // * order by field // */ // public Pagination(int top, int skip, List<Sort> orderBy) { // this.top = top; // this.skip = skip; // this.orderBy = orderBy; // } // // public int getTop() { // return top; // } // // public void setTop(int top) { // this.top = top; // } // // public int getSkip() { // return skip; // } // // public void setSkip(int skip) { // this.skip = skip; // } // // public List<Sort> getOrderBy() { // return orderBy; // } // // public void setOrderBy(List<Sort> orderBy) { // this.orderBy = orderBy; // } // } // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/queries/Query.java import org.elasticsearch.index.query.QueryBuilder; import com.hevelian.olastic.core.elastic.pagination.Pagination; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NonNull; import lombok.Setter; package com.hevelian.olastic.core.elastic.queries; /** * Query with base parameters for all queries to create request. * * @author rdidyk */ @AllArgsConstructor @Getter @Setter public class Query { @NonNull private String index; @NonNull private String[] types; @NonNull private QueryBuilder queryBuilder;
private Pagination pagination;
Hevelian/hevelian-olastic
olastic-web/src/main/java/com/hevelian/olastic/listeners/AppContextListener.java
// Path: olastic-web/src/main/java/com/hevelian/olastic/config/ESConfig.java // public interface ESConfig { // // /** // * Return's attribute name to specify it in context. // * // * @return attribute name // */ // static String getName() { // return "ElasticsearchConfiguration"; // } // // /** // * Return's {@link Client} instance. // * // * @return client // */ // Client getClient(); // // /** // * Close {@link Client}. // */ // void close(); // // /** // * Return's indices from client. // * // * @return indices set // */ // Set<String> getIndices(); // // } // // Path: olastic-web/src/main/java/com/hevelian/olastic/config/ESConfigImpl.java // public class ESConfigImpl implements ESConfig { // /** Elasticsearch client. */ // protected final Client client; // // /** // * Creates a new Elasticsearch client configuration with predefined // * properties. // * // * @param host // * host name // * @param port // * port number // * @param cluster // * cluster name // * @throws UnknownHostException // * if no IP address for the host could be found // */ // public ESConfigImpl(String host, int port, String cluster) throws UnknownHostException { // Settings settings = Settings.builder().put("cluster.name", cluster).build(); // this.client = initClient(settings, // new InetSocketTransportAddress(InetAddress.getByName(host), port)); // initESClient(); // } // // /** // * Initialize's Elasticsearch {@link Client}. // * // * @param settings // * the settings passed to transport client // * @param address // * transport address that will be used to connect to // * @return client instance // */ // protected Client initClient(Settings settings, TransportAddress address) { // PreBuiltTransportClient preBuildClient = new PreBuiltTransportClient(settings); // preBuildClient.addTransportAddress(address); // return preBuildClient; // } // // /** // * Initializes {@link ESClient} instance to execute all queries in // * application. // */ // protected void initESClient() { // ESClient.init(client); // } // // @Override // public void close() { // client.close(); // } // // @Override // public Client getClient() { // return client; // } // // @Override // public Set<String> getIndices() { // try { // return client.admin().indices().stats(new IndicesStatsRequest()).actionGet() // .getIndices().keySet(); // } catch (NoNodeAvailableException e) { // throw new ODataRuntimeException("Elasticsearch has no node available.", e); // } // } // // }
import java.net.UnknownHostException; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import com.hevelian.olastic.config.ESConfig; import com.hevelian.olastic.config.ESConfigImpl; import lombok.extern.log4j.Log4j2;
package com.hevelian.olastic.listeners; /** * Application context listener to get Elasticsearch properties from context and * initialize {@link ESConfig}. * * @author rdidyk */ @Log4j2 public class AppContextListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { ServletContext ctx = sce.getServletContext(); String host = ctx.getInitParameter("elastic.host"); String port = ctx.getInitParameter("elastic.port"); String cluster = ctx.getInitParameter("elastic.cluster"); try {
// Path: olastic-web/src/main/java/com/hevelian/olastic/config/ESConfig.java // public interface ESConfig { // // /** // * Return's attribute name to specify it in context. // * // * @return attribute name // */ // static String getName() { // return "ElasticsearchConfiguration"; // } // // /** // * Return's {@link Client} instance. // * // * @return client // */ // Client getClient(); // // /** // * Close {@link Client}. // */ // void close(); // // /** // * Return's indices from client. // * // * @return indices set // */ // Set<String> getIndices(); // // } // // Path: olastic-web/src/main/java/com/hevelian/olastic/config/ESConfigImpl.java // public class ESConfigImpl implements ESConfig { // /** Elasticsearch client. */ // protected final Client client; // // /** // * Creates a new Elasticsearch client configuration with predefined // * properties. // * // * @param host // * host name // * @param port // * port number // * @param cluster // * cluster name // * @throws UnknownHostException // * if no IP address for the host could be found // */ // public ESConfigImpl(String host, int port, String cluster) throws UnknownHostException { // Settings settings = Settings.builder().put("cluster.name", cluster).build(); // this.client = initClient(settings, // new InetSocketTransportAddress(InetAddress.getByName(host), port)); // initESClient(); // } // // /** // * Initialize's Elasticsearch {@link Client}. // * // * @param settings // * the settings passed to transport client // * @param address // * transport address that will be used to connect to // * @return client instance // */ // protected Client initClient(Settings settings, TransportAddress address) { // PreBuiltTransportClient preBuildClient = new PreBuiltTransportClient(settings); // preBuildClient.addTransportAddress(address); // return preBuildClient; // } // // /** // * Initializes {@link ESClient} instance to execute all queries in // * application. // */ // protected void initESClient() { // ESClient.init(client); // } // // @Override // public void close() { // client.close(); // } // // @Override // public Client getClient() { // return client; // } // // @Override // public Set<String> getIndices() { // try { // return client.admin().indices().stats(new IndicesStatsRequest()).actionGet() // .getIndices().keySet(); // } catch (NoNodeAvailableException e) { // throw new ODataRuntimeException("Elasticsearch has no node available.", e); // } // } // // } // Path: olastic-web/src/main/java/com/hevelian/olastic/listeners/AppContextListener.java import java.net.UnknownHostException; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import com.hevelian.olastic.config.ESConfig; import com.hevelian.olastic.config.ESConfigImpl; import lombok.extern.log4j.Log4j2; package com.hevelian.olastic.listeners; /** * Application context listener to get Elasticsearch properties from context and * initialize {@link ESConfig}. * * @author rdidyk */ @Log4j2 public class AppContextListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { ServletContext ctx = sce.getServletContext(); String host = ctx.getInitParameter("elastic.host"); String port = ctx.getInitParameter("elastic.port"); String cluster = ctx.getInitParameter("elastic.cluster"); try {
ESConfig config = new ESConfigImpl(host, Integer.valueOf(port), cluster);
Hevelian/hevelian-olastic
olastic-web/src/main/java/com/hevelian/olastic/listeners/AppContextListener.java
// Path: olastic-web/src/main/java/com/hevelian/olastic/config/ESConfig.java // public interface ESConfig { // // /** // * Return's attribute name to specify it in context. // * // * @return attribute name // */ // static String getName() { // return "ElasticsearchConfiguration"; // } // // /** // * Return's {@link Client} instance. // * // * @return client // */ // Client getClient(); // // /** // * Close {@link Client}. // */ // void close(); // // /** // * Return's indices from client. // * // * @return indices set // */ // Set<String> getIndices(); // // } // // Path: olastic-web/src/main/java/com/hevelian/olastic/config/ESConfigImpl.java // public class ESConfigImpl implements ESConfig { // /** Elasticsearch client. */ // protected final Client client; // // /** // * Creates a new Elasticsearch client configuration with predefined // * properties. // * // * @param host // * host name // * @param port // * port number // * @param cluster // * cluster name // * @throws UnknownHostException // * if no IP address for the host could be found // */ // public ESConfigImpl(String host, int port, String cluster) throws UnknownHostException { // Settings settings = Settings.builder().put("cluster.name", cluster).build(); // this.client = initClient(settings, // new InetSocketTransportAddress(InetAddress.getByName(host), port)); // initESClient(); // } // // /** // * Initialize's Elasticsearch {@link Client}. // * // * @param settings // * the settings passed to transport client // * @param address // * transport address that will be used to connect to // * @return client instance // */ // protected Client initClient(Settings settings, TransportAddress address) { // PreBuiltTransportClient preBuildClient = new PreBuiltTransportClient(settings); // preBuildClient.addTransportAddress(address); // return preBuildClient; // } // // /** // * Initializes {@link ESClient} instance to execute all queries in // * application. // */ // protected void initESClient() { // ESClient.init(client); // } // // @Override // public void close() { // client.close(); // } // // @Override // public Client getClient() { // return client; // } // // @Override // public Set<String> getIndices() { // try { // return client.admin().indices().stats(new IndicesStatsRequest()).actionGet() // .getIndices().keySet(); // } catch (NoNodeAvailableException e) { // throw new ODataRuntimeException("Elasticsearch has no node available.", e); // } // } // // }
import java.net.UnknownHostException; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import com.hevelian.olastic.config.ESConfig; import com.hevelian.olastic.config.ESConfigImpl; import lombok.extern.log4j.Log4j2;
package com.hevelian.olastic.listeners; /** * Application context listener to get Elasticsearch properties from context and * initialize {@link ESConfig}. * * @author rdidyk */ @Log4j2 public class AppContextListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { ServletContext ctx = sce.getServletContext(); String host = ctx.getInitParameter("elastic.host"); String port = ctx.getInitParameter("elastic.port"); String cluster = ctx.getInitParameter("elastic.cluster"); try {
// Path: olastic-web/src/main/java/com/hevelian/olastic/config/ESConfig.java // public interface ESConfig { // // /** // * Return's attribute name to specify it in context. // * // * @return attribute name // */ // static String getName() { // return "ElasticsearchConfiguration"; // } // // /** // * Return's {@link Client} instance. // * // * @return client // */ // Client getClient(); // // /** // * Close {@link Client}. // */ // void close(); // // /** // * Return's indices from client. // * // * @return indices set // */ // Set<String> getIndices(); // // } // // Path: olastic-web/src/main/java/com/hevelian/olastic/config/ESConfigImpl.java // public class ESConfigImpl implements ESConfig { // /** Elasticsearch client. */ // protected final Client client; // // /** // * Creates a new Elasticsearch client configuration with predefined // * properties. // * // * @param host // * host name // * @param port // * port number // * @param cluster // * cluster name // * @throws UnknownHostException // * if no IP address for the host could be found // */ // public ESConfigImpl(String host, int port, String cluster) throws UnknownHostException { // Settings settings = Settings.builder().put("cluster.name", cluster).build(); // this.client = initClient(settings, // new InetSocketTransportAddress(InetAddress.getByName(host), port)); // initESClient(); // } // // /** // * Initialize's Elasticsearch {@link Client}. // * // * @param settings // * the settings passed to transport client // * @param address // * transport address that will be used to connect to // * @return client instance // */ // protected Client initClient(Settings settings, TransportAddress address) { // PreBuiltTransportClient preBuildClient = new PreBuiltTransportClient(settings); // preBuildClient.addTransportAddress(address); // return preBuildClient; // } // // /** // * Initializes {@link ESClient} instance to execute all queries in // * application. // */ // protected void initESClient() { // ESClient.init(client); // } // // @Override // public void close() { // client.close(); // } // // @Override // public Client getClient() { // return client; // } // // @Override // public Set<String> getIndices() { // try { // return client.admin().indices().stats(new IndicesStatsRequest()).actionGet() // .getIndices().keySet(); // } catch (NoNodeAvailableException e) { // throw new ODataRuntimeException("Elasticsearch has no node available.", e); // } // } // // } // Path: olastic-web/src/main/java/com/hevelian/olastic/listeners/AppContextListener.java import java.net.UnknownHostException; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import com.hevelian.olastic.config.ESConfig; import com.hevelian.olastic.config.ESConfigImpl; import lombok.extern.log4j.Log4j2; package com.hevelian.olastic.listeners; /** * Application context listener to get Elasticsearch properties from context and * initialize {@link ESConfig}. * * @author rdidyk */ @Log4j2 public class AppContextListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { ServletContext ctx = sce.getServletContext(); String host = ctx.getInitParameter("elastic.host"); String port = ctx.getInitParameter("elastic.port"); String cluster = ctx.getInitParameter("elastic.cluster"); try {
ESConfig config = new ESConfigImpl(host, Integer.valueOf(port), cluster);
Hevelian/hevelian-olastic
olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/BaseMember.java
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/ElasticConstants.java // public static final String WILDCARD_CHAR = "*"; // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/utils/ElasticUtils.java // public static String addKeywordIfNeeded(String name, List<EdmAnnotation> annotations) { // boolean isAnalyzed = false; // Optional<EdmAnnotation> analyzedAnnotation = annotations.stream() // .filter(annotation -> annotation.getTerm().getName() // .equals(AnnotationProvider.ANALYZED_TERM_NAME)) // .findFirst(); // if (analyzedAnnotation.isPresent()) { // isAnalyzed = (Boolean) (analyzedAnnotation.get().getExpression().asConstant() // .asPrimitive()); // } // return isAnalyzed ? addKeyword(name) : name; // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/utils/ProcessorUtils.java // public static <T> T throwNotImplemented(String msg) throws ODataApplicationException { // throw new ODataApplicationException(msg, HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), // Locale.ROOT); // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java // public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression { // // }
import static com.hevelian.olastic.core.elastic.ElasticConstants.WILDCARD_CHAR; import static com.hevelian.olastic.core.elastic.utils.ElasticUtils.addKeywordIfNeeded; import static com.hevelian.olastic.core.utils.ProcessorUtils.throwNotImplemented; import static org.elasticsearch.index.query.QueryBuilders.prefixQuery; import static org.elasticsearch.index.query.QueryBuilders.wildcardQuery; import org.apache.olingo.server.api.ODataApplicationException; import org.elasticsearch.index.query.QueryBuilder; import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember;
package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl; /** * Base common class for any expression member. * * @author Taras Kohut */ public abstract class BaseMember implements ExpressionMember { @Override public ExpressionMember any() throws ODataApplicationException {
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/ElasticConstants.java // public static final String WILDCARD_CHAR = "*"; // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/utils/ElasticUtils.java // public static String addKeywordIfNeeded(String name, List<EdmAnnotation> annotations) { // boolean isAnalyzed = false; // Optional<EdmAnnotation> analyzedAnnotation = annotations.stream() // .filter(annotation -> annotation.getTerm().getName() // .equals(AnnotationProvider.ANALYZED_TERM_NAME)) // .findFirst(); // if (analyzedAnnotation.isPresent()) { // isAnalyzed = (Boolean) (analyzedAnnotation.get().getExpression().asConstant() // .asPrimitive()); // } // return isAnalyzed ? addKeyword(name) : name; // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/utils/ProcessorUtils.java // public static <T> T throwNotImplemented(String msg) throws ODataApplicationException { // throw new ODataApplicationException(msg, HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), // Locale.ROOT); // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java // public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression { // // } // Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/BaseMember.java import static com.hevelian.olastic.core.elastic.ElasticConstants.WILDCARD_CHAR; import static com.hevelian.olastic.core.elastic.utils.ElasticUtils.addKeywordIfNeeded; import static com.hevelian.olastic.core.utils.ProcessorUtils.throwNotImplemented; import static org.elasticsearch.index.query.QueryBuilders.prefixQuery; import static org.elasticsearch.index.query.QueryBuilders.wildcardQuery; import org.apache.olingo.server.api.ODataApplicationException; import org.elasticsearch.index.query.QueryBuilder; import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember; package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl; /** * Base common class for any expression member. * * @author Taras Kohut */ public abstract class BaseMember implements ExpressionMember { @Override public ExpressionMember any() throws ODataApplicationException {
return throwNotImplemented();
Hevelian/hevelian-olastic
olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/BaseMember.java
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/ElasticConstants.java // public static final String WILDCARD_CHAR = "*"; // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/utils/ElasticUtils.java // public static String addKeywordIfNeeded(String name, List<EdmAnnotation> annotations) { // boolean isAnalyzed = false; // Optional<EdmAnnotation> analyzedAnnotation = annotations.stream() // .filter(annotation -> annotation.getTerm().getName() // .equals(AnnotationProvider.ANALYZED_TERM_NAME)) // .findFirst(); // if (analyzedAnnotation.isPresent()) { // isAnalyzed = (Boolean) (analyzedAnnotation.get().getExpression().asConstant() // .asPrimitive()); // } // return isAnalyzed ? addKeyword(name) : name; // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/utils/ProcessorUtils.java // public static <T> T throwNotImplemented(String msg) throws ODataApplicationException { // throw new ODataApplicationException(msg, HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), // Locale.ROOT); // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java // public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression { // // }
import static com.hevelian.olastic.core.elastic.ElasticConstants.WILDCARD_CHAR; import static com.hevelian.olastic.core.elastic.utils.ElasticUtils.addKeywordIfNeeded; import static com.hevelian.olastic.core.utils.ProcessorUtils.throwNotImplemented; import static org.elasticsearch.index.query.QueryBuilders.prefixQuery; import static org.elasticsearch.index.query.QueryBuilders.wildcardQuery; import org.apache.olingo.server.api.ODataApplicationException; import org.elasticsearch.index.query.QueryBuilder; import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember;
return throwNotImplemented(); } @Override public ExpressionMember startsWith(ExpressionMember expressionMember) throws ODataApplicationException { return throwNotImplemented(); } @Override public ExpressionMember endsWith(ExpressionMember expressionMember) throws ODataApplicationException { return throwNotImplemented(); } @Override public ExpressionMember date() throws ODataApplicationException { return throwNotImplemented(); } /** * Builds contains query based on {@link AnnotatedMember} and value. * * @param member * annotated member with field and annotations * @param value * contains value * @return query builder instance */ protected QueryBuilder buildContainsQuery(AnnotatedMember member, Object value) {
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/ElasticConstants.java // public static final String WILDCARD_CHAR = "*"; // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/utils/ElasticUtils.java // public static String addKeywordIfNeeded(String name, List<EdmAnnotation> annotations) { // boolean isAnalyzed = false; // Optional<EdmAnnotation> analyzedAnnotation = annotations.stream() // .filter(annotation -> annotation.getTerm().getName() // .equals(AnnotationProvider.ANALYZED_TERM_NAME)) // .findFirst(); // if (analyzedAnnotation.isPresent()) { // isAnalyzed = (Boolean) (analyzedAnnotation.get().getExpression().asConstant() // .asPrimitive()); // } // return isAnalyzed ? addKeyword(name) : name; // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/utils/ProcessorUtils.java // public static <T> T throwNotImplemented(String msg) throws ODataApplicationException { // throw new ODataApplicationException(msg, HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), // Locale.ROOT); // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java // public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression { // // } // Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/BaseMember.java import static com.hevelian.olastic.core.elastic.ElasticConstants.WILDCARD_CHAR; import static com.hevelian.olastic.core.elastic.utils.ElasticUtils.addKeywordIfNeeded; import static com.hevelian.olastic.core.utils.ProcessorUtils.throwNotImplemented; import static org.elasticsearch.index.query.QueryBuilders.prefixQuery; import static org.elasticsearch.index.query.QueryBuilders.wildcardQuery; import org.apache.olingo.server.api.ODataApplicationException; import org.elasticsearch.index.query.QueryBuilder; import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember; return throwNotImplemented(); } @Override public ExpressionMember startsWith(ExpressionMember expressionMember) throws ODataApplicationException { return throwNotImplemented(); } @Override public ExpressionMember endsWith(ExpressionMember expressionMember) throws ODataApplicationException { return throwNotImplemented(); } @Override public ExpressionMember date() throws ODataApplicationException { return throwNotImplemented(); } /** * Builds contains query based on {@link AnnotatedMember} and value. * * @param member * annotated member with field and annotations * @param value * contains value * @return query builder instance */ protected QueryBuilder buildContainsQuery(AnnotatedMember member, Object value) {
return wildcardQuery(addKeywordIfNeeded(member.getField(), member.getAnnotations()),
Hevelian/hevelian-olastic
olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/BaseMember.java
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/ElasticConstants.java // public static final String WILDCARD_CHAR = "*"; // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/utils/ElasticUtils.java // public static String addKeywordIfNeeded(String name, List<EdmAnnotation> annotations) { // boolean isAnalyzed = false; // Optional<EdmAnnotation> analyzedAnnotation = annotations.stream() // .filter(annotation -> annotation.getTerm().getName() // .equals(AnnotationProvider.ANALYZED_TERM_NAME)) // .findFirst(); // if (analyzedAnnotation.isPresent()) { // isAnalyzed = (Boolean) (analyzedAnnotation.get().getExpression().asConstant() // .asPrimitive()); // } // return isAnalyzed ? addKeyword(name) : name; // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/utils/ProcessorUtils.java // public static <T> T throwNotImplemented(String msg) throws ODataApplicationException { // throw new ODataApplicationException(msg, HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), // Locale.ROOT); // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java // public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression { // // }
import static com.hevelian.olastic.core.elastic.ElasticConstants.WILDCARD_CHAR; import static com.hevelian.olastic.core.elastic.utils.ElasticUtils.addKeywordIfNeeded; import static com.hevelian.olastic.core.utils.ProcessorUtils.throwNotImplemented; import static org.elasticsearch.index.query.QueryBuilders.prefixQuery; import static org.elasticsearch.index.query.QueryBuilders.wildcardQuery; import org.apache.olingo.server.api.ODataApplicationException; import org.elasticsearch.index.query.QueryBuilder; import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember;
} @Override public ExpressionMember startsWith(ExpressionMember expressionMember) throws ODataApplicationException { return throwNotImplemented(); } @Override public ExpressionMember endsWith(ExpressionMember expressionMember) throws ODataApplicationException { return throwNotImplemented(); } @Override public ExpressionMember date() throws ODataApplicationException { return throwNotImplemented(); } /** * Builds contains query based on {@link AnnotatedMember} and value. * * @param member * annotated member with field and annotations * @param value * contains value * @return query builder instance */ protected QueryBuilder buildContainsQuery(AnnotatedMember member, Object value) { return wildcardQuery(addKeywordIfNeeded(member.getField(), member.getAnnotations()),
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/ElasticConstants.java // public static final String WILDCARD_CHAR = "*"; // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/utils/ElasticUtils.java // public static String addKeywordIfNeeded(String name, List<EdmAnnotation> annotations) { // boolean isAnalyzed = false; // Optional<EdmAnnotation> analyzedAnnotation = annotations.stream() // .filter(annotation -> annotation.getTerm().getName() // .equals(AnnotationProvider.ANALYZED_TERM_NAME)) // .findFirst(); // if (analyzedAnnotation.isPresent()) { // isAnalyzed = (Boolean) (analyzedAnnotation.get().getExpression().asConstant() // .asPrimitive()); // } // return isAnalyzed ? addKeyword(name) : name; // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/utils/ProcessorUtils.java // public static <T> T throwNotImplemented(String msg) throws ODataApplicationException { // throw new ODataApplicationException(msg, HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), // Locale.ROOT); // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java // public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression { // // } // Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/BaseMember.java import static com.hevelian.olastic.core.elastic.ElasticConstants.WILDCARD_CHAR; import static com.hevelian.olastic.core.elastic.utils.ElasticUtils.addKeywordIfNeeded; import static com.hevelian.olastic.core.utils.ProcessorUtils.throwNotImplemented; import static org.elasticsearch.index.query.QueryBuilders.prefixQuery; import static org.elasticsearch.index.query.QueryBuilders.wildcardQuery; import org.apache.olingo.server.api.ODataApplicationException; import org.elasticsearch.index.query.QueryBuilder; import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember; } @Override public ExpressionMember startsWith(ExpressionMember expressionMember) throws ODataApplicationException { return throwNotImplemented(); } @Override public ExpressionMember endsWith(ExpressionMember expressionMember) throws ODataApplicationException { return throwNotImplemented(); } @Override public ExpressionMember date() throws ODataApplicationException { return throwNotImplemented(); } /** * Builds contains query based on {@link AnnotatedMember} and value. * * @param member * annotated member with field and annotations * @param value * contains value * @return query builder instance */ protected QueryBuilder buildContainsQuery(AnnotatedMember member, Object value) { return wildcardQuery(addKeywordIfNeeded(member.getField(), member.getAnnotations()),
WILDCARD_CHAR + value + WILDCARD_CHAR);
Hevelian/hevelian-olastic
olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/edm/annotations/AnnotationProvider.java // public class AnnotationProvider { // /** Analyzed term name. */ // public static final String ANALYZED_TERM_NAME = "Analyzed"; // // private HashMap<String, TermAnnotation> annotations = new HashMap<>(); // // // declaring terms and annotations // private CsdlAnnotation analyzedAnnotation = new CsdlAnnotation().setTerm("OData.Analyzed") // .setExpression(new CsdlConstantExpression( // CsdlConstantExpression.ConstantExpressionType.Bool, "true")); // // private CsdlTerm analyzedTerm = new CsdlTerm().setAppliesTo(Arrays.asList("Property")) // .setName(ANALYZED_TERM_NAME).setType(EdmPrimitiveTypeKind.String.getFullQualifiedName() // .getFullQualifiedNameAsString()); // // /** // * Default constructor. Sets default annotation. // */ // public AnnotationProvider() { // annotations.put(ANALYZED_TERM_NAME, new TermAnnotation(analyzedTerm, analyzedAnnotation)); // } // // /** // * Gets annotation by term name. // * // * @param termName // * term name // * @return found annotation, otherwise null // */ // public CsdlAnnotation getAnnotation(String termName) { // TermAnnotation temAnnotation = annotations.get(termName); // if (temAnnotation != null) { // return annotations.get(termName).annotation; // } else { // return null; // } // } // // /** // * Gets term by term name. // * // * @param termName // * term name // * @return found term, otherwise null // */ // public CsdlTerm getTerm(String termName) { // TermAnnotation temAnnotation = annotations.get(termName); // if (temAnnotation != null) { // return annotations.get(termName).term; // } else { // return null; // } // } // // public List<CsdlTerm> getTerms() { // return annotations.entrySet().stream().map(entry -> entry.getValue().term) // .collect(Collectors.toList()); // } // // /** // * Class represents container for term and annotation. // */ // private class TermAnnotation { // private CsdlAnnotation annotation; // private CsdlTerm term; // // TermAnnotation(CsdlTerm term, CsdlAnnotation annotation) { // this.term = term; // this.annotation = annotation; // } // } // }
import com.hevelian.olastic.core.api.edm.annotations.AnnotationProvider; import org.apache.olingo.commons.api.edm.EdmAnnotation; import org.apache.olingo.commons.api.edm.EdmTerm; import org.apache.olingo.commons.api.edm.annotation.EdmConstantExpression; import org.apache.olingo.commons.api.edm.annotation.EdmExpression; import org.apache.olingo.server.api.ODataApplicationException; import org.json.JSONArray; import org.json.JSONObject; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock;
* Expected value enclosed in '' */ public static void checkFilterGrandParentEqualsQuery(String query, String field, String value, String parent, String grandParent, String queryKey, String valueKey) { JSONObject childObj = new JSONObject(query).getJSONObject("has_parent"); String childType = (String) childObj.get("parent_type"); assertEquals(parent, childType); JSONObject subChildObj = childObj.getJSONObject("query").getJSONObject("has_parent"); String subChildType = (String) subChildObj.get("parent_type"); assertEquals(grandParent, subChildType); JSONObject rootObj; rootObj = subChildObj.getJSONObject("query").getJSONObject(queryKey); String fieldName = field + ".keyword"; JSONObject valueObject = rootObj.getJSONObject(fieldName); String actualValue = (String) valueObject.get(valueKey); assertEquals(value.substring(1, value.length() - 1), actualValue); } /** * Mocks analyzed annotation. * * @return mocked analyzed annotation */ public static EdmAnnotation getAnalyzedAnnotation() { EdmAnnotation annotation = mock(EdmAnnotation.class); EdmTerm term = mock(EdmTerm.class); EdmExpression expression = mock(EdmExpression.class); EdmConstantExpression constantExpression = mock(EdmConstantExpression.class); doReturn(Boolean.parseBoolean(
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/edm/annotations/AnnotationProvider.java // public class AnnotationProvider { // /** Analyzed term name. */ // public static final String ANALYZED_TERM_NAME = "Analyzed"; // // private HashMap<String, TermAnnotation> annotations = new HashMap<>(); // // // declaring terms and annotations // private CsdlAnnotation analyzedAnnotation = new CsdlAnnotation().setTerm("OData.Analyzed") // .setExpression(new CsdlConstantExpression( // CsdlConstantExpression.ConstantExpressionType.Bool, "true")); // // private CsdlTerm analyzedTerm = new CsdlTerm().setAppliesTo(Arrays.asList("Property")) // .setName(ANALYZED_TERM_NAME).setType(EdmPrimitiveTypeKind.String.getFullQualifiedName() // .getFullQualifiedNameAsString()); // // /** // * Default constructor. Sets default annotation. // */ // public AnnotationProvider() { // annotations.put(ANALYZED_TERM_NAME, new TermAnnotation(analyzedTerm, analyzedAnnotation)); // } // // /** // * Gets annotation by term name. // * // * @param termName // * term name // * @return found annotation, otherwise null // */ // public CsdlAnnotation getAnnotation(String termName) { // TermAnnotation temAnnotation = annotations.get(termName); // if (temAnnotation != null) { // return annotations.get(termName).annotation; // } else { // return null; // } // } // // /** // * Gets term by term name. // * // * @param termName // * term name // * @return found term, otherwise null // */ // public CsdlTerm getTerm(String termName) { // TermAnnotation temAnnotation = annotations.get(termName); // if (temAnnotation != null) { // return annotations.get(termName).term; // } else { // return null; // } // } // // public List<CsdlTerm> getTerms() { // return annotations.entrySet().stream().map(entry -> entry.getValue().term) // .collect(Collectors.toList()); // } // // /** // * Class represents container for term and annotation. // */ // private class TermAnnotation { // private CsdlAnnotation annotation; // private CsdlTerm term; // // TermAnnotation(CsdlTerm term, CsdlAnnotation annotation) { // this.term = term; // this.annotation = annotation; // } // } // } // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java import com.hevelian.olastic.core.api.edm.annotations.AnnotationProvider; import org.apache.olingo.commons.api.edm.EdmAnnotation; import org.apache.olingo.commons.api.edm.EdmTerm; import org.apache.olingo.commons.api.edm.annotation.EdmConstantExpression; import org.apache.olingo.commons.api.edm.annotation.EdmExpression; import org.apache.olingo.server.api.ODataApplicationException; import org.json.JSONArray; import org.json.JSONObject; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; * Expected value enclosed in '' */ public static void checkFilterGrandParentEqualsQuery(String query, String field, String value, String parent, String grandParent, String queryKey, String valueKey) { JSONObject childObj = new JSONObject(query).getJSONObject("has_parent"); String childType = (String) childObj.get("parent_type"); assertEquals(parent, childType); JSONObject subChildObj = childObj.getJSONObject("query").getJSONObject("has_parent"); String subChildType = (String) subChildObj.get("parent_type"); assertEquals(grandParent, subChildType); JSONObject rootObj; rootObj = subChildObj.getJSONObject("query").getJSONObject(queryKey); String fieldName = field + ".keyword"; JSONObject valueObject = rootObj.getJSONObject(fieldName); String actualValue = (String) valueObject.get(valueKey); assertEquals(value.substring(1, value.length() - 1), actualValue); } /** * Mocks analyzed annotation. * * @return mocked analyzed annotation */ public static EdmAnnotation getAnalyzedAnnotation() { EdmAnnotation annotation = mock(EdmAnnotation.class); EdmTerm term = mock(EdmTerm.class); EdmExpression expression = mock(EdmExpression.class); EdmConstantExpression constantExpression = mock(EdmConstantExpression.class); doReturn(Boolean.parseBoolean(
new AnnotationProvider().getAnnotation(AnnotationProvider.ANALYZED_TERM_NAME)
Hevelian/hevelian-olastic
olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/LiteralMember.java
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java // public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression { // // }
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember; import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.core.edm.primitivetype.EdmString; import org.apache.olingo.server.api.ODataApplicationException; import org.apache.olingo.server.core.uri.parser.UriTokenizer; import org.apache.olingo.server.core.uri.parser.UriTokenizer.TokenKind; import java.util.ArrayList; import java.util.List;
} this.edmType = edmType; this.value = value; } /** * Checks the edm type of the string value, and creates concrete type from * this value. * * @return converted value */ public Object getValue() { UriTokenizer tokenizer = new UriTokenizer(value); if (tokenizer.next(UriTokenizer.TokenKind.StringValue) && edmType instanceof EdmString) { return value.substring(1, value.length() - 1).replaceAll("''", SINGLE_QUOTE); } else if (tokenizer.next(TokenKind.jsonArrayOrObject) && edmType == null) { String arrayAsString = value.substring(1, value.length() - 1); List<String> values = new ArrayList<>(); for (String string : arrayAsString.split(",")) { values.add(string.replace("\"", "")); } return values; } else if (tokenizer.next(TokenKind.NULL)) { return null; } else { return value; } } @Override
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java // public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression { // // } // Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/LiteralMember.java import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember; import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.core.edm.primitivetype.EdmString; import org.apache.olingo.server.api.ODataApplicationException; import org.apache.olingo.server.core.uri.parser.UriTokenizer; import org.apache.olingo.server.core.uri.parser.UriTokenizer.TokenKind; import java.util.ArrayList; import java.util.List; } this.edmType = edmType; this.value = value; } /** * Checks the edm type of the string value, and creates concrete type from * this value. * * @return converted value */ public Object getValue() { UriTokenizer tokenizer = new UriTokenizer(value); if (tokenizer.next(UriTokenizer.TokenKind.StringValue) && edmType instanceof EdmString) { return value.substring(1, value.length() - 1).replaceAll("''", SINGLE_QUOTE); } else if (tokenizer.next(TokenKind.jsonArrayOrObject) && edmType == null) { String arrayAsString = value.substring(1, value.length() - 1); List<String> values = new ArrayList<>(); for (String string : arrayAsString.split(",")) { values.add(string.replace("\"", "")); } return values; } else if (tokenizer.next(TokenKind.NULL)) { return null; } else { return value; } } @Override
public ExpressionMember eq(ExpressionMember expressionMember) throws ODataApplicationException {
Hevelian/hevelian-olastic
olastic-core/src/main/java/com/hevelian/olastic/core/processors/ESProcessor.java
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/ElasticOData.java // public final class ElasticOData extends ODataImpl { // // private ElasticOData() { // } // // /** // * Creates new instance of {@link ElasticOData} instance. // * // * @return new OData instance // */ // public static ElasticOData newInstance() { // return new ElasticOData(); // } // // @Override // public ElasticServiceMetadata createServiceMetadata(CsdlEdmProvider edmProvider, // List<EdmxReference> references) { // return createServiceMetadata(edmProvider, references, null); // } // // @Override // public ElasticServiceMetadata createServiceMetadata(CsdlEdmProvider edmProvider, // List<EdmxReference> references, ServiceMetadataETagSupport serviceMetadataETagSupport) { // return new ElasticServiceMetadata(castToType(edmProvider, ElasticCsdlEdmProvider.class), // references, serviceMetadataETagSupport); // } // // @Override // public ODataSerializer createSerializer(ContentType contentType) throws SerializerException { // ODataSerializer serializer = null; // if (contentType.isCompatible(ContentType.APPLICATION_JSON)) { // String metadata = contentType.getParameter(ContentType.PARAMETER_ODATA_METADATA); // if (metadata == null // || ContentType.VALUE_ODATA_METADATA_MINIMAL.equalsIgnoreCase(metadata) // || ContentType.VALUE_ODATA_METADATA_NONE.equalsIgnoreCase(metadata) // || ContentType.VALUE_ODATA_METADATA_FULL.equalsIgnoreCase(metadata)) { // serializer = new ElasticODataJsonSerializer(contentType); // } // } else if (contentType.isCompatible(ContentType.APPLICATION_XML) // || contentType.isCompatible(ContentType.APPLICATION_ATOM_XML)) { // serializer = new ElasticODataXmlSerializer(); // } // if (serializer == null) { // throw new SerializerException( // "Unsupported format: " + contentType.toContentTypeString(), // SerializerException.MessageKeys.UNSUPPORTED_FORMAT, // contentType.toContentTypeString()); // } // return serializer; // } // // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/ElasticServiceMetadata.java // public class ElasticServiceMetadata implements ServiceMetadata { // // private ElasticEdmProvider edm; // private final List<EdmxReference> references; // private final ServiceMetadataETagSupport serviceMetadataETagSupport; // // /** // * Initialize fields. // * // * @param edmProvider // * the EDM provider // * @param references // * the EDMX references // * @param serviceMetadataETagSupport // * service metadata support // */ // public ElasticServiceMetadata(ElasticCsdlEdmProvider edmProvider, // List<EdmxReference> references, ServiceMetadataETagSupport serviceMetadataETagSupport) { // this.edm = new ElasticEdmProvider(edmProvider); // this.references = references; // this.serviceMetadataETagSupport = serviceMetadataETagSupport; // } // // @Override // public ElasticEdmProvider getEdm() { // return edm; // } // // @Override // public ODataServiceVersion getDataServiceVersion() { // return ODataServiceVersion.V40; // } // // @Override // public List<EdmxReference> getReferences() { // return Collections.unmodifiableList(references); // } // // @Override // public ServiceMetadataETagSupport getServiceMetadataETagSupport() { // return serviceMetadataETagSupport; // } // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/utils/MetaDataUtils.java // public static <T> T castToType(Object object, Class<T> clazz) { // if (clazz.isInstance(object)) { // return clazz.cast(object); // } // throw new ODataRuntimeException( // String.format("Invalid %s instance. Only %s class is supported.", // object.getClass().getSimpleName(), clazz.getName())); // }
import com.hevelian.olastic.core.ElasticOData; import com.hevelian.olastic.core.ElasticServiceMetadata; import org.apache.olingo.server.api.OData; import org.apache.olingo.server.api.ServiceMetadata; import org.apache.olingo.server.api.processor.Processor; import static com.hevelian.olastic.core.utils.MetaDataUtils.castToType;
package com.hevelian.olastic.core.processors; /** * Base interface for all Elastic processor types. */ public interface ESProcessor extends Processor { @Override default void init(OData odata, ServiceMetadata serviceMetadata) {
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/ElasticOData.java // public final class ElasticOData extends ODataImpl { // // private ElasticOData() { // } // // /** // * Creates new instance of {@link ElasticOData} instance. // * // * @return new OData instance // */ // public static ElasticOData newInstance() { // return new ElasticOData(); // } // // @Override // public ElasticServiceMetadata createServiceMetadata(CsdlEdmProvider edmProvider, // List<EdmxReference> references) { // return createServiceMetadata(edmProvider, references, null); // } // // @Override // public ElasticServiceMetadata createServiceMetadata(CsdlEdmProvider edmProvider, // List<EdmxReference> references, ServiceMetadataETagSupport serviceMetadataETagSupport) { // return new ElasticServiceMetadata(castToType(edmProvider, ElasticCsdlEdmProvider.class), // references, serviceMetadataETagSupport); // } // // @Override // public ODataSerializer createSerializer(ContentType contentType) throws SerializerException { // ODataSerializer serializer = null; // if (contentType.isCompatible(ContentType.APPLICATION_JSON)) { // String metadata = contentType.getParameter(ContentType.PARAMETER_ODATA_METADATA); // if (metadata == null // || ContentType.VALUE_ODATA_METADATA_MINIMAL.equalsIgnoreCase(metadata) // || ContentType.VALUE_ODATA_METADATA_NONE.equalsIgnoreCase(metadata) // || ContentType.VALUE_ODATA_METADATA_FULL.equalsIgnoreCase(metadata)) { // serializer = new ElasticODataJsonSerializer(contentType); // } // } else if (contentType.isCompatible(ContentType.APPLICATION_XML) // || contentType.isCompatible(ContentType.APPLICATION_ATOM_XML)) { // serializer = new ElasticODataXmlSerializer(); // } // if (serializer == null) { // throw new SerializerException( // "Unsupported format: " + contentType.toContentTypeString(), // SerializerException.MessageKeys.UNSUPPORTED_FORMAT, // contentType.toContentTypeString()); // } // return serializer; // } // // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/ElasticServiceMetadata.java // public class ElasticServiceMetadata implements ServiceMetadata { // // private ElasticEdmProvider edm; // private final List<EdmxReference> references; // private final ServiceMetadataETagSupport serviceMetadataETagSupport; // // /** // * Initialize fields. // * // * @param edmProvider // * the EDM provider // * @param references // * the EDMX references // * @param serviceMetadataETagSupport // * service metadata support // */ // public ElasticServiceMetadata(ElasticCsdlEdmProvider edmProvider, // List<EdmxReference> references, ServiceMetadataETagSupport serviceMetadataETagSupport) { // this.edm = new ElasticEdmProvider(edmProvider); // this.references = references; // this.serviceMetadataETagSupport = serviceMetadataETagSupport; // } // // @Override // public ElasticEdmProvider getEdm() { // return edm; // } // // @Override // public ODataServiceVersion getDataServiceVersion() { // return ODataServiceVersion.V40; // } // // @Override // public List<EdmxReference> getReferences() { // return Collections.unmodifiableList(references); // } // // @Override // public ServiceMetadataETagSupport getServiceMetadataETagSupport() { // return serviceMetadataETagSupport; // } // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/utils/MetaDataUtils.java // public static <T> T castToType(Object object, Class<T> clazz) { // if (clazz.isInstance(object)) { // return clazz.cast(object); // } // throw new ODataRuntimeException( // String.format("Invalid %s instance. Only %s class is supported.", // object.getClass().getSimpleName(), clazz.getName())); // } // Path: olastic-core/src/main/java/com/hevelian/olastic/core/processors/ESProcessor.java import com.hevelian.olastic.core.ElasticOData; import com.hevelian.olastic.core.ElasticServiceMetadata; import org.apache.olingo.server.api.OData; import org.apache.olingo.server.api.ServiceMetadata; import org.apache.olingo.server.api.processor.Processor; import static com.hevelian.olastic.core.utils.MetaDataUtils.castToType; package com.hevelian.olastic.core.processors; /** * Base interface for all Elastic processor types. */ public interface ESProcessor extends Processor { @Override default void init(OData odata, ServiceMetadata serviceMetadata) {
init(castToType(odata, ElasticOData.class),
Hevelian/hevelian-olastic
olastic-core/src/main/java/com/hevelian/olastic/core/processors/ESProcessor.java
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/ElasticOData.java // public final class ElasticOData extends ODataImpl { // // private ElasticOData() { // } // // /** // * Creates new instance of {@link ElasticOData} instance. // * // * @return new OData instance // */ // public static ElasticOData newInstance() { // return new ElasticOData(); // } // // @Override // public ElasticServiceMetadata createServiceMetadata(CsdlEdmProvider edmProvider, // List<EdmxReference> references) { // return createServiceMetadata(edmProvider, references, null); // } // // @Override // public ElasticServiceMetadata createServiceMetadata(CsdlEdmProvider edmProvider, // List<EdmxReference> references, ServiceMetadataETagSupport serviceMetadataETagSupport) { // return new ElasticServiceMetadata(castToType(edmProvider, ElasticCsdlEdmProvider.class), // references, serviceMetadataETagSupport); // } // // @Override // public ODataSerializer createSerializer(ContentType contentType) throws SerializerException { // ODataSerializer serializer = null; // if (contentType.isCompatible(ContentType.APPLICATION_JSON)) { // String metadata = contentType.getParameter(ContentType.PARAMETER_ODATA_METADATA); // if (metadata == null // || ContentType.VALUE_ODATA_METADATA_MINIMAL.equalsIgnoreCase(metadata) // || ContentType.VALUE_ODATA_METADATA_NONE.equalsIgnoreCase(metadata) // || ContentType.VALUE_ODATA_METADATA_FULL.equalsIgnoreCase(metadata)) { // serializer = new ElasticODataJsonSerializer(contentType); // } // } else if (contentType.isCompatible(ContentType.APPLICATION_XML) // || contentType.isCompatible(ContentType.APPLICATION_ATOM_XML)) { // serializer = new ElasticODataXmlSerializer(); // } // if (serializer == null) { // throw new SerializerException( // "Unsupported format: " + contentType.toContentTypeString(), // SerializerException.MessageKeys.UNSUPPORTED_FORMAT, // contentType.toContentTypeString()); // } // return serializer; // } // // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/ElasticServiceMetadata.java // public class ElasticServiceMetadata implements ServiceMetadata { // // private ElasticEdmProvider edm; // private final List<EdmxReference> references; // private final ServiceMetadataETagSupport serviceMetadataETagSupport; // // /** // * Initialize fields. // * // * @param edmProvider // * the EDM provider // * @param references // * the EDMX references // * @param serviceMetadataETagSupport // * service metadata support // */ // public ElasticServiceMetadata(ElasticCsdlEdmProvider edmProvider, // List<EdmxReference> references, ServiceMetadataETagSupport serviceMetadataETagSupport) { // this.edm = new ElasticEdmProvider(edmProvider); // this.references = references; // this.serviceMetadataETagSupport = serviceMetadataETagSupport; // } // // @Override // public ElasticEdmProvider getEdm() { // return edm; // } // // @Override // public ODataServiceVersion getDataServiceVersion() { // return ODataServiceVersion.V40; // } // // @Override // public List<EdmxReference> getReferences() { // return Collections.unmodifiableList(references); // } // // @Override // public ServiceMetadataETagSupport getServiceMetadataETagSupport() { // return serviceMetadataETagSupport; // } // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/utils/MetaDataUtils.java // public static <T> T castToType(Object object, Class<T> clazz) { // if (clazz.isInstance(object)) { // return clazz.cast(object); // } // throw new ODataRuntimeException( // String.format("Invalid %s instance. Only %s class is supported.", // object.getClass().getSimpleName(), clazz.getName())); // }
import com.hevelian.olastic.core.ElasticOData; import com.hevelian.olastic.core.ElasticServiceMetadata; import org.apache.olingo.server.api.OData; import org.apache.olingo.server.api.ServiceMetadata; import org.apache.olingo.server.api.processor.Processor; import static com.hevelian.olastic.core.utils.MetaDataUtils.castToType;
package com.hevelian.olastic.core.processors; /** * Base interface for all Elastic processor types. */ public interface ESProcessor extends Processor { @Override default void init(OData odata, ServiceMetadata serviceMetadata) {
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/ElasticOData.java // public final class ElasticOData extends ODataImpl { // // private ElasticOData() { // } // // /** // * Creates new instance of {@link ElasticOData} instance. // * // * @return new OData instance // */ // public static ElasticOData newInstance() { // return new ElasticOData(); // } // // @Override // public ElasticServiceMetadata createServiceMetadata(CsdlEdmProvider edmProvider, // List<EdmxReference> references) { // return createServiceMetadata(edmProvider, references, null); // } // // @Override // public ElasticServiceMetadata createServiceMetadata(CsdlEdmProvider edmProvider, // List<EdmxReference> references, ServiceMetadataETagSupport serviceMetadataETagSupport) { // return new ElasticServiceMetadata(castToType(edmProvider, ElasticCsdlEdmProvider.class), // references, serviceMetadataETagSupport); // } // // @Override // public ODataSerializer createSerializer(ContentType contentType) throws SerializerException { // ODataSerializer serializer = null; // if (contentType.isCompatible(ContentType.APPLICATION_JSON)) { // String metadata = contentType.getParameter(ContentType.PARAMETER_ODATA_METADATA); // if (metadata == null // || ContentType.VALUE_ODATA_METADATA_MINIMAL.equalsIgnoreCase(metadata) // || ContentType.VALUE_ODATA_METADATA_NONE.equalsIgnoreCase(metadata) // || ContentType.VALUE_ODATA_METADATA_FULL.equalsIgnoreCase(metadata)) { // serializer = new ElasticODataJsonSerializer(contentType); // } // } else if (contentType.isCompatible(ContentType.APPLICATION_XML) // || contentType.isCompatible(ContentType.APPLICATION_ATOM_XML)) { // serializer = new ElasticODataXmlSerializer(); // } // if (serializer == null) { // throw new SerializerException( // "Unsupported format: " + contentType.toContentTypeString(), // SerializerException.MessageKeys.UNSUPPORTED_FORMAT, // contentType.toContentTypeString()); // } // return serializer; // } // // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/ElasticServiceMetadata.java // public class ElasticServiceMetadata implements ServiceMetadata { // // private ElasticEdmProvider edm; // private final List<EdmxReference> references; // private final ServiceMetadataETagSupport serviceMetadataETagSupport; // // /** // * Initialize fields. // * // * @param edmProvider // * the EDM provider // * @param references // * the EDMX references // * @param serviceMetadataETagSupport // * service metadata support // */ // public ElasticServiceMetadata(ElasticCsdlEdmProvider edmProvider, // List<EdmxReference> references, ServiceMetadataETagSupport serviceMetadataETagSupport) { // this.edm = new ElasticEdmProvider(edmProvider); // this.references = references; // this.serviceMetadataETagSupport = serviceMetadataETagSupport; // } // // @Override // public ElasticEdmProvider getEdm() { // return edm; // } // // @Override // public ODataServiceVersion getDataServiceVersion() { // return ODataServiceVersion.V40; // } // // @Override // public List<EdmxReference> getReferences() { // return Collections.unmodifiableList(references); // } // // @Override // public ServiceMetadataETagSupport getServiceMetadataETagSupport() { // return serviceMetadataETagSupport; // } // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/utils/MetaDataUtils.java // public static <T> T castToType(Object object, Class<T> clazz) { // if (clazz.isInstance(object)) { // return clazz.cast(object); // } // throw new ODataRuntimeException( // String.format("Invalid %s instance. Only %s class is supported.", // object.getClass().getSimpleName(), clazz.getName())); // } // Path: olastic-core/src/main/java/com/hevelian/olastic/core/processors/ESProcessor.java import com.hevelian.olastic.core.ElasticOData; import com.hevelian.olastic.core.ElasticServiceMetadata; import org.apache.olingo.server.api.OData; import org.apache.olingo.server.api.ServiceMetadata; import org.apache.olingo.server.api.processor.Processor; import static com.hevelian.olastic.core.utils.MetaDataUtils.castToType; package com.hevelian.olastic.core.processors; /** * Base interface for all Elastic processor types. */ public interface ESProcessor extends Processor { @Override default void init(OData odata, ServiceMetadata serviceMetadata) {
init(castToType(odata, ElasticOData.class),
Hevelian/hevelian-olastic
olastic-core/src/main/java/com/hevelian/olastic/core/processors/ESProcessor.java
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/ElasticOData.java // public final class ElasticOData extends ODataImpl { // // private ElasticOData() { // } // // /** // * Creates new instance of {@link ElasticOData} instance. // * // * @return new OData instance // */ // public static ElasticOData newInstance() { // return new ElasticOData(); // } // // @Override // public ElasticServiceMetadata createServiceMetadata(CsdlEdmProvider edmProvider, // List<EdmxReference> references) { // return createServiceMetadata(edmProvider, references, null); // } // // @Override // public ElasticServiceMetadata createServiceMetadata(CsdlEdmProvider edmProvider, // List<EdmxReference> references, ServiceMetadataETagSupport serviceMetadataETagSupport) { // return new ElasticServiceMetadata(castToType(edmProvider, ElasticCsdlEdmProvider.class), // references, serviceMetadataETagSupport); // } // // @Override // public ODataSerializer createSerializer(ContentType contentType) throws SerializerException { // ODataSerializer serializer = null; // if (contentType.isCompatible(ContentType.APPLICATION_JSON)) { // String metadata = contentType.getParameter(ContentType.PARAMETER_ODATA_METADATA); // if (metadata == null // || ContentType.VALUE_ODATA_METADATA_MINIMAL.equalsIgnoreCase(metadata) // || ContentType.VALUE_ODATA_METADATA_NONE.equalsIgnoreCase(metadata) // || ContentType.VALUE_ODATA_METADATA_FULL.equalsIgnoreCase(metadata)) { // serializer = new ElasticODataJsonSerializer(contentType); // } // } else if (contentType.isCompatible(ContentType.APPLICATION_XML) // || contentType.isCompatible(ContentType.APPLICATION_ATOM_XML)) { // serializer = new ElasticODataXmlSerializer(); // } // if (serializer == null) { // throw new SerializerException( // "Unsupported format: " + contentType.toContentTypeString(), // SerializerException.MessageKeys.UNSUPPORTED_FORMAT, // contentType.toContentTypeString()); // } // return serializer; // } // // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/ElasticServiceMetadata.java // public class ElasticServiceMetadata implements ServiceMetadata { // // private ElasticEdmProvider edm; // private final List<EdmxReference> references; // private final ServiceMetadataETagSupport serviceMetadataETagSupport; // // /** // * Initialize fields. // * // * @param edmProvider // * the EDM provider // * @param references // * the EDMX references // * @param serviceMetadataETagSupport // * service metadata support // */ // public ElasticServiceMetadata(ElasticCsdlEdmProvider edmProvider, // List<EdmxReference> references, ServiceMetadataETagSupport serviceMetadataETagSupport) { // this.edm = new ElasticEdmProvider(edmProvider); // this.references = references; // this.serviceMetadataETagSupport = serviceMetadataETagSupport; // } // // @Override // public ElasticEdmProvider getEdm() { // return edm; // } // // @Override // public ODataServiceVersion getDataServiceVersion() { // return ODataServiceVersion.V40; // } // // @Override // public List<EdmxReference> getReferences() { // return Collections.unmodifiableList(references); // } // // @Override // public ServiceMetadataETagSupport getServiceMetadataETagSupport() { // return serviceMetadataETagSupport; // } // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/utils/MetaDataUtils.java // public static <T> T castToType(Object object, Class<T> clazz) { // if (clazz.isInstance(object)) { // return clazz.cast(object); // } // throw new ODataRuntimeException( // String.format("Invalid %s instance. Only %s class is supported.", // object.getClass().getSimpleName(), clazz.getName())); // }
import com.hevelian.olastic.core.ElasticOData; import com.hevelian.olastic.core.ElasticServiceMetadata; import org.apache.olingo.server.api.OData; import org.apache.olingo.server.api.ServiceMetadata; import org.apache.olingo.server.api.processor.Processor; import static com.hevelian.olastic.core.utils.MetaDataUtils.castToType;
package com.hevelian.olastic.core.processors; /** * Base interface for all Elastic processor types. */ public interface ESProcessor extends Processor { @Override default void init(OData odata, ServiceMetadata serviceMetadata) { init(castToType(odata, ElasticOData.class),
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/ElasticOData.java // public final class ElasticOData extends ODataImpl { // // private ElasticOData() { // } // // /** // * Creates new instance of {@link ElasticOData} instance. // * // * @return new OData instance // */ // public static ElasticOData newInstance() { // return new ElasticOData(); // } // // @Override // public ElasticServiceMetadata createServiceMetadata(CsdlEdmProvider edmProvider, // List<EdmxReference> references) { // return createServiceMetadata(edmProvider, references, null); // } // // @Override // public ElasticServiceMetadata createServiceMetadata(CsdlEdmProvider edmProvider, // List<EdmxReference> references, ServiceMetadataETagSupport serviceMetadataETagSupport) { // return new ElasticServiceMetadata(castToType(edmProvider, ElasticCsdlEdmProvider.class), // references, serviceMetadataETagSupport); // } // // @Override // public ODataSerializer createSerializer(ContentType contentType) throws SerializerException { // ODataSerializer serializer = null; // if (contentType.isCompatible(ContentType.APPLICATION_JSON)) { // String metadata = contentType.getParameter(ContentType.PARAMETER_ODATA_METADATA); // if (metadata == null // || ContentType.VALUE_ODATA_METADATA_MINIMAL.equalsIgnoreCase(metadata) // || ContentType.VALUE_ODATA_METADATA_NONE.equalsIgnoreCase(metadata) // || ContentType.VALUE_ODATA_METADATA_FULL.equalsIgnoreCase(metadata)) { // serializer = new ElasticODataJsonSerializer(contentType); // } // } else if (contentType.isCompatible(ContentType.APPLICATION_XML) // || contentType.isCompatible(ContentType.APPLICATION_ATOM_XML)) { // serializer = new ElasticODataXmlSerializer(); // } // if (serializer == null) { // throw new SerializerException( // "Unsupported format: " + contentType.toContentTypeString(), // SerializerException.MessageKeys.UNSUPPORTED_FORMAT, // contentType.toContentTypeString()); // } // return serializer; // } // // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/ElasticServiceMetadata.java // public class ElasticServiceMetadata implements ServiceMetadata { // // private ElasticEdmProvider edm; // private final List<EdmxReference> references; // private final ServiceMetadataETagSupport serviceMetadataETagSupport; // // /** // * Initialize fields. // * // * @param edmProvider // * the EDM provider // * @param references // * the EDMX references // * @param serviceMetadataETagSupport // * service metadata support // */ // public ElasticServiceMetadata(ElasticCsdlEdmProvider edmProvider, // List<EdmxReference> references, ServiceMetadataETagSupport serviceMetadataETagSupport) { // this.edm = new ElasticEdmProvider(edmProvider); // this.references = references; // this.serviceMetadataETagSupport = serviceMetadataETagSupport; // } // // @Override // public ElasticEdmProvider getEdm() { // return edm; // } // // @Override // public ODataServiceVersion getDataServiceVersion() { // return ODataServiceVersion.V40; // } // // @Override // public List<EdmxReference> getReferences() { // return Collections.unmodifiableList(references); // } // // @Override // public ServiceMetadataETagSupport getServiceMetadataETagSupport() { // return serviceMetadataETagSupport; // } // } // // Path: olastic-core/src/main/java/com/hevelian/olastic/core/utils/MetaDataUtils.java // public static <T> T castToType(Object object, Class<T> clazz) { // if (clazz.isInstance(object)) { // return clazz.cast(object); // } // throw new ODataRuntimeException( // String.format("Invalid %s instance. Only %s class is supported.", // object.getClass().getSimpleName(), clazz.getName())); // } // Path: olastic-core/src/main/java/com/hevelian/olastic/core/processors/ESProcessor.java import com.hevelian.olastic.core.ElasticOData; import com.hevelian.olastic.core.ElasticServiceMetadata; import org.apache.olingo.server.api.OData; import org.apache.olingo.server.api.ServiceMetadata; import org.apache.olingo.server.api.processor.Processor; import static com.hevelian.olastic.core.utils.MetaDataUtils.castToType; package com.hevelian.olastic.core.processors; /** * Base interface for all Elastic processor types. */ public interface ESProcessor extends Processor { @Override default void init(OData odata, ServiceMetadata serviceMetadata) { init(castToType(odata, ElasticOData.class),
castToType(serviceMetadata, ElasticServiceMetadata.class));
Hevelian/hevelian-olastic
olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/ExpressionResult.java
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java // public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression { // // }
import static org.elasticsearch.index.query.QueryBuilders.boolQuery; import org.apache.olingo.server.api.ODataApplicationException; import org.elasticsearch.index.query.QueryBuilder; import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember; import lombok.AllArgsConstructor; import lombok.Getter;
package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl; /** * Represents the result of expression. * * @author Taras Kohut */ @AllArgsConstructor @Getter public class ExpressionResult extends BaseMember { private final QueryBuilder queryBuilder; @Override
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java // public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression { // // } // Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/ExpressionResult.java import static org.elasticsearch.index.query.QueryBuilders.boolQuery; import org.apache.olingo.server.api.ODataApplicationException; import org.elasticsearch.index.query.QueryBuilder; import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember; import lombok.AllArgsConstructor; import lombok.Getter; package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl; /** * Represents the result of expression. * * @author Taras Kohut */ @AllArgsConstructor @Getter public class ExpressionResult extends BaseMember { private final QueryBuilder queryBuilder; @Override
public ExpressionResult and(ExpressionMember expressionMember)
Hevelian/hevelian-olastic
olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/ParentPrimitiveMember.java
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java // public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression { // // }
import java.util.List; import org.apache.olingo.server.api.ODataApplicationException; import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember;
package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl; /** * Wraps the data needed for building parent query. * * @author Taras Kohut */ public class ParentPrimitiveMember extends ParentMember { private PrimitiveMember primitiveMember; /** * Initialize fields. * * @param parentTypes * list of parent type names * @param primitiveMember * primitive member instance */ public ParentPrimitiveMember(List<String> parentTypes, PrimitiveMember primitiveMember) { super(parentTypes); this.primitiveMember = primitiveMember; } @Override
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java // public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression { // // } // Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/ParentPrimitiveMember.java import java.util.List; import org.apache.olingo.server.api.ODataApplicationException; import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember; package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl; /** * Wraps the data needed for building parent query. * * @author Taras Kohut */ public class ParentPrimitiveMember extends ParentMember { private PrimitiveMember primitiveMember; /** * Initialize fields. * * @param parentTypes * list of parent type names * @param primitiveMember * primitive member instance */ public ParentPrimitiveMember(List<String> parentTypes, PrimitiveMember primitiveMember) { super(parentTypes); this.primitiveMember = primitiveMember; } @Override
public ExpressionResult eq(ExpressionMember expressionMember) throws ODataApplicationException {
Hevelian/hevelian-olastic
olastic-core/src/main/java/com/hevelian/olastic/core/elastic/mappings/DefaultElasticToCsdlMapper.java
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/utils/MetaDataUtils.java // public final class MetaDataUtils { // // /** Name space separator. */ // public static final String NAMESPACE_SEPARATOR = "."; // /** Target path separator. */ // public static final String TARGET_SEPARATOR = "/"; // // private MetaDataUtils() { // } // // /** // * Casts object to specified class. // * // * @param object // * object to cast // * @param clazz // * class to cast // * @param <T> // * class type // * @return casted instance, or exception will be thrown in case object is // * not instance of specified class // */ // public static <T> T castToType(Object object, Class<T> clazz) { // if (clazz.isInstance(object)) { // return clazz.cast(object); // } // throw new ODataRuntimeException( // String.format("Invalid %s instance. Only %s class is supported.", // object.getClass().getSimpleName(), clazz.getName())); // } // // }
import org.apache.olingo.commons.api.edm.FullQualifiedName; import com.hevelian.olastic.core.utils.MetaDataUtils;
package com.hevelian.olastic.core.elastic.mappings; /** * Default implementation of {@link ElasticToCsdlMapper} interface. * * @author rdidyk */ public class DefaultElasticToCsdlMapper implements ElasticToCsdlMapper { /** Default schema name space. */ public static final String DEFAULT_NAMESPACE = "Olastic.OData"; private final String namespace; /** * Default constructor. */ public DefaultElasticToCsdlMapper() { this(DEFAULT_NAMESPACE); } /** * Constructor to initialize namespace. * * @param namespace * namespace */ public DefaultElasticToCsdlMapper(String namespace) { this.namespace = namespace; } @Override public String esFieldToCsdlProperty(String index, String type, String field) { return field; } @Override public boolean esFieldIsCollection(String index, String type, String field) { return false; } @Override public FullQualifiedName esTypeToEntityType(String index, String type) { return new FullQualifiedName(esIndexToCsdlNamespace(index), type); } @Override public String esIndexToCsdlNamespace(String index) {
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/utils/MetaDataUtils.java // public final class MetaDataUtils { // // /** Name space separator. */ // public static final String NAMESPACE_SEPARATOR = "."; // /** Target path separator. */ // public static final String TARGET_SEPARATOR = "/"; // // private MetaDataUtils() { // } // // /** // * Casts object to specified class. // * // * @param object // * object to cast // * @param clazz // * class to cast // * @param <T> // * class type // * @return casted instance, or exception will be thrown in case object is // * not instance of specified class // */ // public static <T> T castToType(Object object, Class<T> clazz) { // if (clazz.isInstance(object)) { // return clazz.cast(object); // } // throw new ODataRuntimeException( // String.format("Invalid %s instance. Only %s class is supported.", // object.getClass().getSimpleName(), clazz.getName())); // } // // } // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/mappings/DefaultElasticToCsdlMapper.java import org.apache.olingo.commons.api.edm.FullQualifiedName; import com.hevelian.olastic.core.utils.MetaDataUtils; package com.hevelian.olastic.core.elastic.mappings; /** * Default implementation of {@link ElasticToCsdlMapper} interface. * * @author rdidyk */ public class DefaultElasticToCsdlMapper implements ElasticToCsdlMapper { /** Default schema name space. */ public static final String DEFAULT_NAMESPACE = "Olastic.OData"; private final String namespace; /** * Default constructor. */ public DefaultElasticToCsdlMapper() { this(DEFAULT_NAMESPACE); } /** * Constructor to initialize namespace. * * @param namespace * namespace */ public DefaultElasticToCsdlMapper(String namespace) { this.namespace = namespace; } @Override public String esFieldToCsdlProperty(String index, String type, String field) { return field; } @Override public boolean esFieldIsCollection(String index, String type, String field) { return false; } @Override public FullQualifiedName esTypeToEntityType(String index, String type) { return new FullQualifiedName(esIndexToCsdlNamespace(index), type); } @Override public String esIndexToCsdlNamespace(String index) {
return namespace + MetaDataUtils.NAMESPACE_SEPARATOR + index;
spatialsimulator/XitoSBML
src/main/java/jp/ac/keio/bio/fun/xitosbml/image/ImageTable.java
// Path: src/main/java/jp/ac/keio/bio/fun/xitosbml/gui/AddingColumn.java // @SuppressWarnings("serial") // public class AddingColumn extends ButtonColumn { // // /** The table. */ // JTable table; // // /** The edit button. */ // JButton editButton; // // /** The render button. */ // JButton renderButton; // // // /** // * Instantiates a new adding column. // * // * @param table the JTable object // * @param columnIndex the column index // */ // public AddingColumn(JTable table, int columnIndex){ // super(table,columnIndex); // this.table = table; // renderButton = new JButton("+"); // editButton = new JButton("+"); // editButton.setName("getimage"); // setButtons(renderButton, editButton); // } // } // // Path: src/main/java/jp/ac/keio/bio/fun/xitosbml/gui/ArrowColumn.java // @SuppressWarnings({ "serial" }) // public class ArrowColumn extends ButtonColumn{ // // /** The table. */ // JTable table; // // /** The edit button. */ // BasicArrowButton editButton; // // /** The render button. */ // BasicArrowButton renderButton; // // /** // * Instantiates a new arrow column. // * // * @param table the JTable object // * @param columnIndex the column index // * @param direction the direction of the arrow // */ // public ArrowColumn(JTable table, int columnIndex, int direction){ // super(table, columnIndex); // renderButton = new BasicArrowButton(direction); // editButton = new BasicArrowButton(direction); // editButton.setText("arrow"); // setButtons(renderButton, editButton); // } // }
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Frame; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.HashMap; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.plaf.basic.BasicArrowButton; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; import ij.ImagePlus; import ij.gui.MessageDialog; import ij.io.FileInfo; import jp.ac.keio.bio.fun.xitosbml.gui.AddingColumn; import jp.ac.keio.bio.fun.xitosbml.gui.ArrowColumn;
package jp.ac.keio.bio.fun.xitosbml.image; /** * The class ImageTable, which inherits JTable and implements mousePressed() * method for adding images to the spatial model. * This class is used in {@link jp.ac.keio.bio.fun.xitosbml.image.ImageExplorer}. * Date Created: Dec 7, 2015 * * @author Kaito Ii &lt;ii@fun.bio.keio.ac.jp&gt; * @author Akira Funahashi &lt;funa@bio.keio.ac.jp&gt; */ @SuppressWarnings("serial") public class ImageTable extends JTable implements MouseListener{ /** The table model. */ private DefaultTableModel tableModel; /** The default domain type. */ private final String[] defaultDomtype = {"Nucleus","Mitochondria","Golgi","Cytosol"}; /** The column title. */ private final String[] columnNames = {"Domain Type","Image","Add","Up","Down"}; /** The column index of domain type. */ private final int colDomType = 0; /** The column index of image name. */ private final int colImgName = 1; /** The column index of add image. */ private final int colAddImage = 2; /** The column index of up button. */ private final int colUpButton = 3; /** The column index of down button. */ private final int colDownButton = 4; /** The hashmap of domain file. HashMap&lt;String, ImagePlus&gt; */ private HashMap<String,ImagePlus> hashDomFile = new HashMap<String, ImagePlus>(); /** The file information of composite image. */ private FileInfo compoInfo; /** * Instantiates a new image table. */ public ImageTable() { super(); Object[][] data = new Object[defaultDomtype.length][columnNames.length]; for (int i = 0; i < defaultDomtype.length; i++) { data[i][0] = defaultDomtype[i]; } // table tableModel = new MyTableModel(data, columnNames); setModel(tableModel); setBackground(new Color(169,169,169)); getTableHeader().setReorderingAllowed(false); // mouse addMouseListener(this); setCellSelectionEnabled(true);
// Path: src/main/java/jp/ac/keio/bio/fun/xitosbml/gui/AddingColumn.java // @SuppressWarnings("serial") // public class AddingColumn extends ButtonColumn { // // /** The table. */ // JTable table; // // /** The edit button. */ // JButton editButton; // // /** The render button. */ // JButton renderButton; // // // /** // * Instantiates a new adding column. // * // * @param table the JTable object // * @param columnIndex the column index // */ // public AddingColumn(JTable table, int columnIndex){ // super(table,columnIndex); // this.table = table; // renderButton = new JButton("+"); // editButton = new JButton("+"); // editButton.setName("getimage"); // setButtons(renderButton, editButton); // } // } // // Path: src/main/java/jp/ac/keio/bio/fun/xitosbml/gui/ArrowColumn.java // @SuppressWarnings({ "serial" }) // public class ArrowColumn extends ButtonColumn{ // // /** The table. */ // JTable table; // // /** The edit button. */ // BasicArrowButton editButton; // // /** The render button. */ // BasicArrowButton renderButton; // // /** // * Instantiates a new arrow column. // * // * @param table the JTable object // * @param columnIndex the column index // * @param direction the direction of the arrow // */ // public ArrowColumn(JTable table, int columnIndex, int direction){ // super(table, columnIndex); // renderButton = new BasicArrowButton(direction); // editButton = new BasicArrowButton(direction); // editButton.setText("arrow"); // setButtons(renderButton, editButton); // } // } // Path: src/main/java/jp/ac/keio/bio/fun/xitosbml/image/ImageTable.java import java.awt.BorderLayout; import java.awt.Color; import java.awt.Frame; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.HashMap; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.plaf.basic.BasicArrowButton; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; import ij.ImagePlus; import ij.gui.MessageDialog; import ij.io.FileInfo; import jp.ac.keio.bio.fun.xitosbml.gui.AddingColumn; import jp.ac.keio.bio.fun.xitosbml.gui.ArrowColumn; package jp.ac.keio.bio.fun.xitosbml.image; /** * The class ImageTable, which inherits JTable and implements mousePressed() * method for adding images to the spatial model. * This class is used in {@link jp.ac.keio.bio.fun.xitosbml.image.ImageExplorer}. * Date Created: Dec 7, 2015 * * @author Kaito Ii &lt;ii@fun.bio.keio.ac.jp&gt; * @author Akira Funahashi &lt;funa@bio.keio.ac.jp&gt; */ @SuppressWarnings("serial") public class ImageTable extends JTable implements MouseListener{ /** The table model. */ private DefaultTableModel tableModel; /** The default domain type. */ private final String[] defaultDomtype = {"Nucleus","Mitochondria","Golgi","Cytosol"}; /** The column title. */ private final String[] columnNames = {"Domain Type","Image","Add","Up","Down"}; /** The column index of domain type. */ private final int colDomType = 0; /** The column index of image name. */ private final int colImgName = 1; /** The column index of add image. */ private final int colAddImage = 2; /** The column index of up button. */ private final int colUpButton = 3; /** The column index of down button. */ private final int colDownButton = 4; /** The hashmap of domain file. HashMap&lt;String, ImagePlus&gt; */ private HashMap<String,ImagePlus> hashDomFile = new HashMap<String, ImagePlus>(); /** The file information of composite image. */ private FileInfo compoInfo; /** * Instantiates a new image table. */ public ImageTable() { super(); Object[][] data = new Object[defaultDomtype.length][columnNames.length]; for (int i = 0; i < defaultDomtype.length; i++) { data[i][0] = defaultDomtype[i]; } // table tableModel = new MyTableModel(data, columnNames); setModel(tableModel); setBackground(new Color(169,169,169)); getTableHeader().setReorderingAllowed(false); // mouse addMouseListener(this); setCellSelectionEnabled(true);
new ArrowColumn(this, colUpButton, BasicArrowButton.NORTH);
spatialsimulator/XitoSBML
src/main/java/jp/ac/keio/bio/fun/xitosbml/image/ImageTable.java
// Path: src/main/java/jp/ac/keio/bio/fun/xitosbml/gui/AddingColumn.java // @SuppressWarnings("serial") // public class AddingColumn extends ButtonColumn { // // /** The table. */ // JTable table; // // /** The edit button. */ // JButton editButton; // // /** The render button. */ // JButton renderButton; // // // /** // * Instantiates a new adding column. // * // * @param table the JTable object // * @param columnIndex the column index // */ // public AddingColumn(JTable table, int columnIndex){ // super(table,columnIndex); // this.table = table; // renderButton = new JButton("+"); // editButton = new JButton("+"); // editButton.setName("getimage"); // setButtons(renderButton, editButton); // } // } // // Path: src/main/java/jp/ac/keio/bio/fun/xitosbml/gui/ArrowColumn.java // @SuppressWarnings({ "serial" }) // public class ArrowColumn extends ButtonColumn{ // // /** The table. */ // JTable table; // // /** The edit button. */ // BasicArrowButton editButton; // // /** The render button. */ // BasicArrowButton renderButton; // // /** // * Instantiates a new arrow column. // * // * @param table the JTable object // * @param columnIndex the column index // * @param direction the direction of the arrow // */ // public ArrowColumn(JTable table, int columnIndex, int direction){ // super(table, columnIndex); // renderButton = new BasicArrowButton(direction); // editButton = new BasicArrowButton(direction); // editButton.setText("arrow"); // setButtons(renderButton, editButton); // } // }
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Frame; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.HashMap; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.plaf.basic.BasicArrowButton; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; import ij.ImagePlus; import ij.gui.MessageDialog; import ij.io.FileInfo; import jp.ac.keio.bio.fun.xitosbml.gui.AddingColumn; import jp.ac.keio.bio.fun.xitosbml.gui.ArrowColumn;
package jp.ac.keio.bio.fun.xitosbml.image; /** * The class ImageTable, which inherits JTable and implements mousePressed() * method for adding images to the spatial model. * This class is used in {@link jp.ac.keio.bio.fun.xitosbml.image.ImageExplorer}. * Date Created: Dec 7, 2015 * * @author Kaito Ii &lt;ii@fun.bio.keio.ac.jp&gt; * @author Akira Funahashi &lt;funa@bio.keio.ac.jp&gt; */ @SuppressWarnings("serial") public class ImageTable extends JTable implements MouseListener{ /** The table model. */ private DefaultTableModel tableModel; /** The default domain type. */ private final String[] defaultDomtype = {"Nucleus","Mitochondria","Golgi","Cytosol"}; /** The column title. */ private final String[] columnNames = {"Domain Type","Image","Add","Up","Down"}; /** The column index of domain type. */ private final int colDomType = 0; /** The column index of image name. */ private final int colImgName = 1; /** The column index of add image. */ private final int colAddImage = 2; /** The column index of up button. */ private final int colUpButton = 3; /** The column index of down button. */ private final int colDownButton = 4; /** The hashmap of domain file. HashMap&lt;String, ImagePlus&gt; */ private HashMap<String,ImagePlus> hashDomFile = new HashMap<String, ImagePlus>(); /** The file information of composite image. */ private FileInfo compoInfo; /** * Instantiates a new image table. */ public ImageTable() { super(); Object[][] data = new Object[defaultDomtype.length][columnNames.length]; for (int i = 0; i < defaultDomtype.length; i++) { data[i][0] = defaultDomtype[i]; } // table tableModel = new MyTableModel(data, columnNames); setModel(tableModel); setBackground(new Color(169,169,169)); getTableHeader().setReorderingAllowed(false); // mouse addMouseListener(this); setCellSelectionEnabled(true); new ArrowColumn(this, colUpButton, BasicArrowButton.NORTH); new ArrowColumn(this, colDownButton, BasicArrowButton.SOUTH);
// Path: src/main/java/jp/ac/keio/bio/fun/xitosbml/gui/AddingColumn.java // @SuppressWarnings("serial") // public class AddingColumn extends ButtonColumn { // // /** The table. */ // JTable table; // // /** The edit button. */ // JButton editButton; // // /** The render button. */ // JButton renderButton; // // // /** // * Instantiates a new adding column. // * // * @param table the JTable object // * @param columnIndex the column index // */ // public AddingColumn(JTable table, int columnIndex){ // super(table,columnIndex); // this.table = table; // renderButton = new JButton("+"); // editButton = new JButton("+"); // editButton.setName("getimage"); // setButtons(renderButton, editButton); // } // } // // Path: src/main/java/jp/ac/keio/bio/fun/xitosbml/gui/ArrowColumn.java // @SuppressWarnings({ "serial" }) // public class ArrowColumn extends ButtonColumn{ // // /** The table. */ // JTable table; // // /** The edit button. */ // BasicArrowButton editButton; // // /** The render button. */ // BasicArrowButton renderButton; // // /** // * Instantiates a new arrow column. // * // * @param table the JTable object // * @param columnIndex the column index // * @param direction the direction of the arrow // */ // public ArrowColumn(JTable table, int columnIndex, int direction){ // super(table, columnIndex); // renderButton = new BasicArrowButton(direction); // editButton = new BasicArrowButton(direction); // editButton.setText("arrow"); // setButtons(renderButton, editButton); // } // } // Path: src/main/java/jp/ac/keio/bio/fun/xitosbml/image/ImageTable.java import java.awt.BorderLayout; import java.awt.Color; import java.awt.Frame; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.HashMap; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.plaf.basic.BasicArrowButton; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; import ij.ImagePlus; import ij.gui.MessageDialog; import ij.io.FileInfo; import jp.ac.keio.bio.fun.xitosbml.gui.AddingColumn; import jp.ac.keio.bio.fun.xitosbml.gui.ArrowColumn; package jp.ac.keio.bio.fun.xitosbml.image; /** * The class ImageTable, which inherits JTable and implements mousePressed() * method for adding images to the spatial model. * This class is used in {@link jp.ac.keio.bio.fun.xitosbml.image.ImageExplorer}. * Date Created: Dec 7, 2015 * * @author Kaito Ii &lt;ii@fun.bio.keio.ac.jp&gt; * @author Akira Funahashi &lt;funa@bio.keio.ac.jp&gt; */ @SuppressWarnings("serial") public class ImageTable extends JTable implements MouseListener{ /** The table model. */ private DefaultTableModel tableModel; /** The default domain type. */ private final String[] defaultDomtype = {"Nucleus","Mitochondria","Golgi","Cytosol"}; /** The column title. */ private final String[] columnNames = {"Domain Type","Image","Add","Up","Down"}; /** The column index of domain type. */ private final int colDomType = 0; /** The column index of image name. */ private final int colImgName = 1; /** The column index of add image. */ private final int colAddImage = 2; /** The column index of up button. */ private final int colUpButton = 3; /** The column index of down button. */ private final int colDownButton = 4; /** The hashmap of domain file. HashMap&lt;String, ImagePlus&gt; */ private HashMap<String,ImagePlus> hashDomFile = new HashMap<String, ImagePlus>(); /** The file information of composite image. */ private FileInfo compoInfo; /** * Instantiates a new image table. */ public ImageTable() { super(); Object[][] data = new Object[defaultDomtype.length][columnNames.length]; for (int i = 0; i < defaultDomtype.length; i++) { data[i][0] = defaultDomtype[i]; } // table tableModel = new MyTableModel(data, columnNames); setModel(tableModel); setBackground(new Color(169,169,169)); getTableHeader().setReorderingAllowed(false); // mouse addMouseListener(this); setCellSelectionEnabled(true); new ArrowColumn(this, colUpButton, BasicArrowButton.NORTH); new ArrowColumn(this, colDownButton, BasicArrowButton.SOUTH);
new AddingColumn(this, colAddImage);
spatialsimulator/XitoSBML
src/main/java/jp/ac/keio/bio/fun/xitosbml/Spatial_Model_Validator.java
// Path: src/main/java/jp/ac/keio/bio/fun/xitosbml/xitosbml/MainModelValidator.java // public class MainModelValidator extends MainSBaseSpatial { // // /** // * Overrides ij.plugin.PlugIn#run(java.lang.String). // * A file dialog for validating the model will be displayed. // * Users will select a model (SBML file) through the graphical user interface, // * and then XitoSBML will will check whether the SBML document has correct // * level, version and extension. Checking missing boundary conditions for // * Species is also done by this method. // * Moreover, if XitoSBML is connected to an internet, // * then it will send the model to the online SBML validator, which will run // * a semantic validation, and show the validation result. // * // * @param arg name of the method defined in plugins.config // */ // @Override // public void run(String arg) { // try{ // document = getDocument(); // } catch (NullPointerException e){ // e.getStackTrace(); // return; // } catch (XMLStreamException | IOException e) { // e.printStackTrace(); // } // // checkSBMLDocument(document); // ModelValidator validator = new ModelValidator(document); // validator.validate(); // } // }
import jp.ac.keio.bio.fun.xitosbml.xitosbml.MainModelValidator;
package jp.ac.keio.bio.fun.xitosbml; /** * The class Spatial_Model_Validator. * * This class calls "run Model Validation" from ImageJ (XitoSBML). * This class is an implementation of XitoSBML as an ImageJ plugin. * The run(String) method will call jp.ac.keio.bio.fun.xitosbml.xitosbml.MainModelValidator#run(java.lang.String). * Once registered in src/main/resources/plugins.config, the run() method can be called from the ImageJ menu. * Date Created: Oct 1, 2015 * * @author Kaito Ii &lt;ii@fun.bio.keio.ac.jp&gt; * @author Akira Funahashi &lt;funa@bio.keio.ac.jp&gt; */ public class Spatial_Model_Validator extends Spatial_SBML { /** * Launch XitoSBML as ImageJ plugin. * See {@link jp.ac.keio.bio.fun.xitosbml.xitosbml.MainModelValidator#run(java.lang.String)} for implementation. * @param arg name of the method defined in plugins.config */ @Override public void run(String arg) {
// Path: src/main/java/jp/ac/keio/bio/fun/xitosbml/xitosbml/MainModelValidator.java // public class MainModelValidator extends MainSBaseSpatial { // // /** // * Overrides ij.plugin.PlugIn#run(java.lang.String). // * A file dialog for validating the model will be displayed. // * Users will select a model (SBML file) through the graphical user interface, // * and then XitoSBML will will check whether the SBML document has correct // * level, version and extension. Checking missing boundary conditions for // * Species is also done by this method. // * Moreover, if XitoSBML is connected to an internet, // * then it will send the model to the online SBML validator, which will run // * a semantic validation, and show the validation result. // * // * @param arg name of the method defined in plugins.config // */ // @Override // public void run(String arg) { // try{ // document = getDocument(); // } catch (NullPointerException e){ // e.getStackTrace(); // return; // } catch (XMLStreamException | IOException e) { // e.printStackTrace(); // } // // checkSBMLDocument(document); // ModelValidator validator = new ModelValidator(document); // validator.validate(); // } // } // Path: src/main/java/jp/ac/keio/bio/fun/xitosbml/Spatial_Model_Validator.java import jp.ac.keio.bio.fun.xitosbml.xitosbml.MainModelValidator; package jp.ac.keio.bio.fun.xitosbml; /** * The class Spatial_Model_Validator. * * This class calls "run Model Validation" from ImageJ (XitoSBML). * This class is an implementation of XitoSBML as an ImageJ plugin. * The run(String) method will call jp.ac.keio.bio.fun.xitosbml.xitosbml.MainModelValidator#run(java.lang.String). * Once registered in src/main/resources/plugins.config, the run() method can be called from the ImageJ menu. * Date Created: Oct 1, 2015 * * @author Kaito Ii &lt;ii@fun.bio.keio.ac.jp&gt; * @author Akira Funahashi &lt;funa@bio.keio.ac.jp&gt; */ public class Spatial_Model_Validator extends Spatial_SBML { /** * Launch XitoSBML as ImageJ plugin. * See {@link jp.ac.keio.bio.fun.xitosbml.xitosbml.MainModelValidator#run(java.lang.String)} for implementation. * @param arg name of the method defined in plugins.config */ @Override public void run(String arg) {
new MainModelValidator().run(arg);
spatialsimulator/XitoSBML
src/main/java/jp/ac/keio/bio/fun/xitosbml/Spatial_Model_Edit.java
// Path: src/main/java/jp/ac/keio/bio/fun/xitosbml/xitosbml/MainModelEdit.java // public class MainModelEdit extends MainSBaseSpatial { // // /** // * Overrides ij.plugin.PlugIn#run(java.lang.String). // * A dialog for editing the model will be displayed. // * Users can add, modify following SBML elements and save the model through the dialog. // * <ul> // * <li>Species</li> // * <li>Parameter</li> // * <li>Advection coefficient</li> // * <li>Diffusion coefficient</li> // * <li>Boundary condition</li> // * <li>Reaction</li> // * </ul> // * // * Once the model is saved as SBML, XitoSBML will visualize the model in 3D space, // * and execute a syntax validation for both SBML core and spatial extension by using // * SBML online validator. // * With this plugin, users can create a reaction-diffusion model in spatial SBML format. // * @param arg name of the method defined in plugins.config // */ // @Override // public void run(String arg) { // try { // document = getDocument(); // } catch (NullPointerException e){ // e.getStackTrace(); // return; // } catch (Exception e) { // IJ.error("Error: File is not an SBML Model"); // return; // } // // checkSBMLDocument(document); // // addSBases(); // ModelSaver saver = new ModelSaver(document); // saver.save(); // showDomainStructure(); // GeometryDatas gData = new GeometryDatas(model); // visualize(gData.getSpImgList()); // // print(); // // ModelValidator validator = new ModelValidator(document); // validator.validate(); // } // }
import jp.ac.keio.bio.fun.xitosbml.xitosbml.MainModelEdit;
package jp.ac.keio.bio.fun.xitosbml; /** * The class Spatial_Model_Edit. * * This class calls "run Model Editor" from ImageJ (XitoSBML). * This class is an implementation of XitoSBML as an ImageJ plugin. * The run(String) method will call jp.ac.keio.bio.fun.xitosbml.xitosbml.MainModelEdit#run(java.lang.String). * Once registered in src/main/resources/plugins.config, the run() method can be called from the ImageJ menu. * Date Created: Jun 17, 2015 * * @author Kaito Ii &lt;ii@fun.bio.keio.ac.jp&gt; * @author Akira Funahashi &lt;funa@bio.keio.ac.jp&gt; */ public class Spatial_Model_Edit extends Spatial_SBML { /** * Launch XitoSBML as ImageJ plugin. * See {@link jp.ac.keio.bio.fun.xitosbml.xitosbml.MainModelEdit#run(java.lang.String)} for implementation. * @param arg name of the method defined in plugins.config */ @Override public void run(String arg) {
// Path: src/main/java/jp/ac/keio/bio/fun/xitosbml/xitosbml/MainModelEdit.java // public class MainModelEdit extends MainSBaseSpatial { // // /** // * Overrides ij.plugin.PlugIn#run(java.lang.String). // * A dialog for editing the model will be displayed. // * Users can add, modify following SBML elements and save the model through the dialog. // * <ul> // * <li>Species</li> // * <li>Parameter</li> // * <li>Advection coefficient</li> // * <li>Diffusion coefficient</li> // * <li>Boundary condition</li> // * <li>Reaction</li> // * </ul> // * // * Once the model is saved as SBML, XitoSBML will visualize the model in 3D space, // * and execute a syntax validation for both SBML core and spatial extension by using // * SBML online validator. // * With this plugin, users can create a reaction-diffusion model in spatial SBML format. // * @param arg name of the method defined in plugins.config // */ // @Override // public void run(String arg) { // try { // document = getDocument(); // } catch (NullPointerException e){ // e.getStackTrace(); // return; // } catch (Exception e) { // IJ.error("Error: File is not an SBML Model"); // return; // } // // checkSBMLDocument(document); // // addSBases(); // ModelSaver saver = new ModelSaver(document); // saver.save(); // showDomainStructure(); // GeometryDatas gData = new GeometryDatas(model); // visualize(gData.getSpImgList()); // // print(); // // ModelValidator validator = new ModelValidator(document); // validator.validate(); // } // } // Path: src/main/java/jp/ac/keio/bio/fun/xitosbml/Spatial_Model_Edit.java import jp.ac.keio.bio.fun.xitosbml.xitosbml.MainModelEdit; package jp.ac.keio.bio.fun.xitosbml; /** * The class Spatial_Model_Edit. * * This class calls "run Model Editor" from ImageJ (XitoSBML). * This class is an implementation of XitoSBML as an ImageJ plugin. * The run(String) method will call jp.ac.keio.bio.fun.xitosbml.xitosbml.MainModelEdit#run(java.lang.String). * Once registered in src/main/resources/plugins.config, the run() method can be called from the ImageJ menu. * Date Created: Jun 17, 2015 * * @author Kaito Ii &lt;ii@fun.bio.keio.ac.jp&gt; * @author Akira Funahashi &lt;funa@bio.keio.ac.jp&gt; */ public class Spatial_Model_Edit extends Spatial_SBML { /** * Launch XitoSBML as ImageJ plugin. * See {@link jp.ac.keio.bio.fun.xitosbml.xitosbml.MainModelEdit#run(java.lang.String)} for implementation. * @param arg name of the method defined in plugins.config */ @Override public void run(String arg) {
new MainModelEdit().run(arg);
spatialsimulator/XitoSBML
src/main/java/jp/ac/keio/bio/fun/xitosbml/Spatial_Img_SBML.java
// Path: src/main/java/jp/ac/keio/bio/fun/xitosbml/xitosbml/MainImgSpatial.java // public class MainImgSpatial extends MainSpatial { // // /** // * Overrides ij.plugin.PlugIn#run(java.lang.String). // * A dialog for specifying the correspondence between the image and the region in the cell will be displayed. // * The specified image is read and the following process is performed. // * <ol> // * <li>Interpolate an image if it is a Z-stack image (3D image)</li> // * <li>Fill holes (blank pixels) in the image by morphology operation if exists</li> // * <li>Export generated image to spatial SBML</li> // * </ol> // * // * @param arg name of the method defined in plugins.config // */ // @Override // public void run(String arg) { // // gui(); // // if close button is pressed, then exit this plugin // if (imgexp.getDomFile() == null) { // return; // } // computeImg(); // SpatialSBMLExporter sbmlexp = new SpatialSBMLExporter(spImg); // model = sbmlexp.getModel(); // sbmlexp.createGeometryElements(); // //visualize(spImg); // // //add species and parameter here // int reply = JOptionPane.showConfirmDialog(null, "Do you want to add Parameters or Species to the model?", "Adding Parameters and species", JOptionPane.YES_NO_CANCEL_OPTION); // if(reply == JOptionPane.YES_OPTION) // addSBases(); // // sbmlexp.addCoordParameter(); // document = sbmlexp.getDocument(); // ModelSaver saver = new ModelSaver(document); // saver.save(); // spImg.saveAsImage(saver.getPath(), saver.getName()); // showDomainStructure(); // // // print(); // ModelValidator validator = new ModelValidator(document); // validator.validate(); // } // }
import ij.IJ; import ij.ImageJ; import jp.ac.keio.bio.fun.xitosbml.xitosbml.MainImgSpatial;
package jp.ac.keio.bio.fun.xitosbml; /** * The class Spatial_Img_SBML. * * This class calls "run Spatial Image SBML plugin" from ImageJ (XitoSBML). * This class is an implementation of XitoSBML as an ImageJ plugin. * The run(String) method will call jp.ac.keio.bio.fun.xitosbml.xitosbml.MainImgSpatial#run(java.lang.String). * Once registered in src/main/resources/plugins.config, the run() method can be called from the ImageJ menu. * Date Created: Jun 17, 2015 * * @author Kaito Ii &lt;ii@fun.bio.keio.ac.jp&gt; * @author Akira Funahashi &lt;funa@bio.keio.ac.jp&gt; */ public class Spatial_Img_SBML extends Spatial_SBML { /** * Launch XitoSBML as ImageJ plugin. * See {@link jp.ac.keio.bio.fun.xitosbml.xitosbml.MainImgSpatial#run(java.lang.String)} for implementation. * @param arg name of the method defined in plugins.config */ public void run(String arg) { if (arg.equals("about")) { showAbout(); return; } else {
// Path: src/main/java/jp/ac/keio/bio/fun/xitosbml/xitosbml/MainImgSpatial.java // public class MainImgSpatial extends MainSpatial { // // /** // * Overrides ij.plugin.PlugIn#run(java.lang.String). // * A dialog for specifying the correspondence between the image and the region in the cell will be displayed. // * The specified image is read and the following process is performed. // * <ol> // * <li>Interpolate an image if it is a Z-stack image (3D image)</li> // * <li>Fill holes (blank pixels) in the image by morphology operation if exists</li> // * <li>Export generated image to spatial SBML</li> // * </ol> // * // * @param arg name of the method defined in plugins.config // */ // @Override // public void run(String arg) { // // gui(); // // if close button is pressed, then exit this plugin // if (imgexp.getDomFile() == null) { // return; // } // computeImg(); // SpatialSBMLExporter sbmlexp = new SpatialSBMLExporter(spImg); // model = sbmlexp.getModel(); // sbmlexp.createGeometryElements(); // //visualize(spImg); // // //add species and parameter here // int reply = JOptionPane.showConfirmDialog(null, "Do you want to add Parameters or Species to the model?", "Adding Parameters and species", JOptionPane.YES_NO_CANCEL_OPTION); // if(reply == JOptionPane.YES_OPTION) // addSBases(); // // sbmlexp.addCoordParameter(); // document = sbmlexp.getDocument(); // ModelSaver saver = new ModelSaver(document); // saver.save(); // spImg.saveAsImage(saver.getPath(), saver.getName()); // showDomainStructure(); // // // print(); // ModelValidator validator = new ModelValidator(document); // validator.validate(); // } // } // Path: src/main/java/jp/ac/keio/bio/fun/xitosbml/Spatial_Img_SBML.java import ij.IJ; import ij.ImageJ; import jp.ac.keio.bio.fun.xitosbml.xitosbml.MainImgSpatial; package jp.ac.keio.bio.fun.xitosbml; /** * The class Spatial_Img_SBML. * * This class calls "run Spatial Image SBML plugin" from ImageJ (XitoSBML). * This class is an implementation of XitoSBML as an ImageJ plugin. * The run(String) method will call jp.ac.keio.bio.fun.xitosbml.xitosbml.MainImgSpatial#run(java.lang.String). * Once registered in src/main/resources/plugins.config, the run() method can be called from the ImageJ menu. * Date Created: Jun 17, 2015 * * @author Kaito Ii &lt;ii@fun.bio.keio.ac.jp&gt; * @author Akira Funahashi &lt;funa@bio.keio.ac.jp&gt; */ public class Spatial_Img_SBML extends Spatial_SBML { /** * Launch XitoSBML as ImageJ plugin. * See {@link jp.ac.keio.bio.fun.xitosbml.xitosbml.MainImgSpatial#run(java.lang.String)} for implementation. * @param arg name of the method defined in plugins.config */ public void run(String arg) { if (arg.equals("about")) { showAbout(); return; } else {
new MainImgSpatial().run(arg);
spatialsimulator/XitoSBML
src/main/java/jp/ac/keio/bio/fun/xitosbml/Spatial_Parametric_SBML.java
// Path: src/main/java/jp/ac/keio/bio/fun/xitosbml/xitosbml/MainParametricSpatial.java // public class MainParametricSpatial extends MainSpatial{ // // /** // * Overrides ij.plugin.PlugIn#run(java.lang.String). // * A dialog for specifying the correspondence between the image and the region in the cell will be displayed. // * The specified image is read and the following process is performed. // * // * 1. Interpolate an image if it is a Z-stack image (3D image) // * 2. Fill holes (blank pixels) in the image by morphology operation if exists // * 3. Export generated image to spatial parametric SBML // * // * @param arg name of the method defined in plugins.config // */ // @Override // public void run(String arg) { // /* // Frame[] f = ImageJ.getFrames(); // // Frame frame = null; // for(int i = 0 ; i < f.length ; i++){ // if(f[i].getTitle().equals("ImageJ 3D Viewer")) frame = f[i]; // } // if(frame == null){ // IJ.error("3D Viewer not opened"); // return; // } // ImageWindow3D win = (ImageWindow3D) frame; // univ = (Image3DUniverse) win.getUniverse(); // */ // // gui(); // computeImg(); // SpatialSBMLExporter sbmlexp = new SpatialSBMLExporter(spImg); // visualize(spImg); // viewer.findPoints(); // sbmlexp.createParametric(viewer.gethashVertices(), viewer.gethashBound()); // // // int reply = JOptionPane.showConfirmDialog(null, "Do you want to add Parameters or Species to the model?", "Adding Parameters and species", JOptionPane.YES_NO_CANCEL_OPTION); // if(reply == JOptionPane.YES_OPTION) // addSBases(); // // sbmlexp.addCoordParameter(); // document = sbmlexp.getDocument(); // ModelSaver saver = new ModelSaver(document); // saver.save(); // } // }
import jp.ac.keio.bio.fun.xitosbml.xitosbml.MainParametricSpatial;
package jp.ac.keio.bio.fun.xitosbml; /** * The class Spatial_Parametric_SBML. * * This class calls "Images to Spatial Parametric SBML converter" from ImageJ (XitoSBML). * This class is an implementation of XitoSBML as an ImageJ plugin. * The run(String) method will call jp.ac.keio.bio.fun.xitosbml.xitosbml.MainParametricSpatial#run(java.lang.String). * Once registered in src/main/resources/plugins.config, the run() method can be called from the ImageJ menu. * Date Created: Oct 1, 2015 * * @author Kaito Ii &lt;ii@fun.bio.keio.ac.jp&gt; * @author Akira Funahashi &lt;funa@bio.keio.ac.jp&gt; */ public class Spatial_Parametric_SBML extends Spatial_SBML{ /** * Launch XitoSBML as ImageJ plugin. * See {@link jp.ac.keio.bio.fun.xitosbml.xitosbml.MainParametricSpatial#run(java.lang.String)} for implementation. * @param arg name of the method defined in plugins.config */ @Override public void run(String arg) {
// Path: src/main/java/jp/ac/keio/bio/fun/xitosbml/xitosbml/MainParametricSpatial.java // public class MainParametricSpatial extends MainSpatial{ // // /** // * Overrides ij.plugin.PlugIn#run(java.lang.String). // * A dialog for specifying the correspondence between the image and the region in the cell will be displayed. // * The specified image is read and the following process is performed. // * // * 1. Interpolate an image if it is a Z-stack image (3D image) // * 2. Fill holes (blank pixels) in the image by morphology operation if exists // * 3. Export generated image to spatial parametric SBML // * // * @param arg name of the method defined in plugins.config // */ // @Override // public void run(String arg) { // /* // Frame[] f = ImageJ.getFrames(); // // Frame frame = null; // for(int i = 0 ; i < f.length ; i++){ // if(f[i].getTitle().equals("ImageJ 3D Viewer")) frame = f[i]; // } // if(frame == null){ // IJ.error("3D Viewer not opened"); // return; // } // ImageWindow3D win = (ImageWindow3D) frame; // univ = (Image3DUniverse) win.getUniverse(); // */ // // gui(); // computeImg(); // SpatialSBMLExporter sbmlexp = new SpatialSBMLExporter(spImg); // visualize(spImg); // viewer.findPoints(); // sbmlexp.createParametric(viewer.gethashVertices(), viewer.gethashBound()); // // // int reply = JOptionPane.showConfirmDialog(null, "Do you want to add Parameters or Species to the model?", "Adding Parameters and species", JOptionPane.YES_NO_CANCEL_OPTION); // if(reply == JOptionPane.YES_OPTION) // addSBases(); // // sbmlexp.addCoordParameter(); // document = sbmlexp.getDocument(); // ModelSaver saver = new ModelSaver(document); // saver.save(); // } // } // Path: src/main/java/jp/ac/keio/bio/fun/xitosbml/Spatial_Parametric_SBML.java import jp.ac.keio.bio.fun.xitosbml.xitosbml.MainParametricSpatial; package jp.ac.keio.bio.fun.xitosbml; /** * The class Spatial_Parametric_SBML. * * This class calls "Images to Spatial Parametric SBML converter" from ImageJ (XitoSBML). * This class is an implementation of XitoSBML as an ImageJ plugin. * The run(String) method will call jp.ac.keio.bio.fun.xitosbml.xitosbml.MainParametricSpatial#run(java.lang.String). * Once registered in src/main/resources/plugins.config, the run() method can be called from the ImageJ menu. * Date Created: Oct 1, 2015 * * @author Kaito Ii &lt;ii@fun.bio.keio.ac.jp&gt; * @author Akira Funahashi &lt;funa@bio.keio.ac.jp&gt; */ public class Spatial_Parametric_SBML extends Spatial_SBML{ /** * Launch XitoSBML as ImageJ plugin. * See {@link jp.ac.keio.bio.fun.xitosbml.xitosbml.MainParametricSpatial#run(java.lang.String)} for implementation. * @param arg name of the method defined in plugins.config */ @Override public void run(String arg) {
new MainParametricSpatial().run(arg);
apache/incubator-myriad
myriad-scheduler/src/main/java/org/apache/myriad/health/MesosDriverHealthCheck.java
// Path: myriad-scheduler/src/main/java/org/apache/myriad/scheduler/MyriadDriverManager.java // public class MyriadDriverManager { // private static final Logger LOGGER = LoggerFactory.getLogger(MyriadDriverManager.class); // private final Lock driverLock; // private MyriadDriver driver; // private Status driverStatus; // // @Inject // public MyriadDriverManager(MyriadDriver driver) { // this.driver = driver; // this.driverLock = new ReentrantLock(); // this.driverStatus = Protos.Status.DRIVER_NOT_STARTED; // } // // public Status startDriver() { // this.driverLock.lock(); // try { // Preconditions.checkState(this.isStartable()); // LOGGER.info("Starting driver..."); // this.driverStatus = driver.start(); // LOGGER.info("Driver started with status: {}", this.driverStatus); // } finally { // this.driverLock.unlock(); // } // return this.driverStatus; // } // // // /** // * Stop driver, executor, and tasks if false, otherwise just the driver. // * // * @return driver status // */ // public Status stopDriver(boolean failover) { // this.driverLock.lock(); // try { // if (isRunning()) { // if (failover) { // LOGGER.info("Stopping driver ..."); // } else { // LOGGER.info("Stopping driver and terminating tasks..."); // } // this.driverStatus = this.driver.stop(failover); // LOGGER.info("Stopped driver with status: {}", this.driverStatus); // } // } finally { // this.driverLock.unlock(); // } // return driverStatus; // } // // /** // * Aborting driver without stopping tasks. // * // * @return driver status // */ // public Status abortDriver() { // this.driverLock.lock(); // try { // if (isRunning()) { // LOGGER.info("Aborting driver..."); // this.driverStatus = this.driver.abort(); // LOGGER.info("Aborted driver with status: {}", this.driverStatus); // } // } finally { // this.driverLock.unlock(); // } // return driverStatus; // } // // public Status kill(final TaskID taskId) { // LOGGER.info("Killing task {}", taskId); // this.driverLock.lock(); // try { // if (isRunning()) { // this.driverStatus = driver.kill(taskId); // LOGGER.info("Task {} killed with status: {}", taskId, this.driverStatus); // } else { // LOGGER.warn("Cannot kill task, driver is not running"); // } // } finally { // this.driverLock.unlock(); // } // // return driverStatus; // } // // public Status getDriverStatus() { // return this.driverStatus; // } // // private boolean isStartable() { // return this.driver != null && this.driverStatus == Status.DRIVER_NOT_STARTED; // } // // private boolean isRunning() { // return this.driver != null && this.driverStatus == Status.DRIVER_RUNNING; // } // }
import com.codahale.metrics.health.HealthCheck; import javax.inject.Inject; import org.apache.mesos.Protos.Status; import org.apache.myriad.scheduler.MyriadDriverManager;
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.apache.myriad.health; /** * Health Check that Mesos Master is running */ public class MesosDriverHealthCheck extends HealthCheck { public static final String NAME = "mesos-driver";
// Path: myriad-scheduler/src/main/java/org/apache/myriad/scheduler/MyriadDriverManager.java // public class MyriadDriverManager { // private static final Logger LOGGER = LoggerFactory.getLogger(MyriadDriverManager.class); // private final Lock driverLock; // private MyriadDriver driver; // private Status driverStatus; // // @Inject // public MyriadDriverManager(MyriadDriver driver) { // this.driver = driver; // this.driverLock = new ReentrantLock(); // this.driverStatus = Protos.Status.DRIVER_NOT_STARTED; // } // // public Status startDriver() { // this.driverLock.lock(); // try { // Preconditions.checkState(this.isStartable()); // LOGGER.info("Starting driver..."); // this.driverStatus = driver.start(); // LOGGER.info("Driver started with status: {}", this.driverStatus); // } finally { // this.driverLock.unlock(); // } // return this.driverStatus; // } // // // /** // * Stop driver, executor, and tasks if false, otherwise just the driver. // * // * @return driver status // */ // public Status stopDriver(boolean failover) { // this.driverLock.lock(); // try { // if (isRunning()) { // if (failover) { // LOGGER.info("Stopping driver ..."); // } else { // LOGGER.info("Stopping driver and terminating tasks..."); // } // this.driverStatus = this.driver.stop(failover); // LOGGER.info("Stopped driver with status: {}", this.driverStatus); // } // } finally { // this.driverLock.unlock(); // } // return driverStatus; // } // // /** // * Aborting driver without stopping tasks. // * // * @return driver status // */ // public Status abortDriver() { // this.driverLock.lock(); // try { // if (isRunning()) { // LOGGER.info("Aborting driver..."); // this.driverStatus = this.driver.abort(); // LOGGER.info("Aborted driver with status: {}", this.driverStatus); // } // } finally { // this.driverLock.unlock(); // } // return driverStatus; // } // // public Status kill(final TaskID taskId) { // LOGGER.info("Killing task {}", taskId); // this.driverLock.lock(); // try { // if (isRunning()) { // this.driverStatus = driver.kill(taskId); // LOGGER.info("Task {} killed with status: {}", taskId, this.driverStatus); // } else { // LOGGER.warn("Cannot kill task, driver is not running"); // } // } finally { // this.driverLock.unlock(); // } // // return driverStatus; // } // // public Status getDriverStatus() { // return this.driverStatus; // } // // private boolean isStartable() { // return this.driver != null && this.driverStatus == Status.DRIVER_NOT_STARTED; // } // // private boolean isRunning() { // return this.driver != null && this.driverStatus == Status.DRIVER_RUNNING; // } // } // Path: myriad-scheduler/src/main/java/org/apache/myriad/health/MesosDriverHealthCheck.java import com.codahale.metrics.health.HealthCheck; import javax.inject.Inject; import org.apache.mesos.Protos.Status; import org.apache.myriad.scheduler.MyriadDriverManager; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.apache.myriad.health; /** * Health Check that Mesos Master is running */ public class MesosDriverHealthCheck extends HealthCheck { public static final String NAME = "mesos-driver";
private MyriadDriverManager driverManager;
apache/incubator-myriad
myriad-scheduler/src/main/java/org/apache/myriad/policy/LeastAMNodesFirstPolicy.java
// Path: myriad-scheduler/src/main/java/org/apache/myriad/scheduler/yarn/interceptor/InterceptorRegistry.java // public interface InterceptorRegistry { // // public void register(YarnSchedulerInterceptor interceptor); // // }
import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.inject.Inject; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.AbstractYarnScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeRemovedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeUpdateSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.SchedulerEvent; import org.apache.mesos.Protos; import org.apache.myriad.scheduler.yarn.interceptor.BaseInterceptor; import org.apache.myriad.scheduler.yarn.interceptor.InterceptorRegistry; import org.apache.myriad.state.SchedulerState; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.apache.myriad.policy; /** * A scale down policy that maintains returns a list of nodes running least number of AMs. */ public class LeastAMNodesFirstPolicy extends BaseInterceptor implements NodeScaleDownPolicy { private static final Logger LOGGER = LoggerFactory.getLogger(LeastAMNodesFirstPolicy.class); private final AbstractYarnScheduler yarnScheduler; private final SchedulerState schedulerState; //TODO(Santosh): Should figure out the right values for the hashmap properties. // currently it's tuned for 200 nodes and 50 RM RPC threads (Yarn's default). private static final int INITIAL_NODE_SIZE = 200; private static final int EXPECTED_CONCURRENT_ACCCESS_COUNT = 50; private static final float LOAD_FACTOR_DEFAULT = 0.75f; private Map<String, SchedulerNode> schedulerNodes = new ConcurrentHashMap<>(INITIAL_NODE_SIZE, LOAD_FACTOR_DEFAULT, EXPECTED_CONCURRENT_ACCCESS_COUNT); @Inject
// Path: myriad-scheduler/src/main/java/org/apache/myriad/scheduler/yarn/interceptor/InterceptorRegistry.java // public interface InterceptorRegistry { // // public void register(YarnSchedulerInterceptor interceptor); // // } // Path: myriad-scheduler/src/main/java/org/apache/myriad/policy/LeastAMNodesFirstPolicy.java import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.inject.Inject; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.AbstractYarnScheduler; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.SchedulerNode; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeRemovedSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeUpdateSchedulerEvent; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.SchedulerEvent; import org.apache.mesos.Protos; import org.apache.myriad.scheduler.yarn.interceptor.BaseInterceptor; import org.apache.myriad.scheduler.yarn.interceptor.InterceptorRegistry; import org.apache.myriad.state.SchedulerState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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.apache.myriad.policy; /** * A scale down policy that maintains returns a list of nodes running least number of AMs. */ public class LeastAMNodesFirstPolicy extends BaseInterceptor implements NodeScaleDownPolicy { private static final Logger LOGGER = LoggerFactory.getLogger(LeastAMNodesFirstPolicy.class); private final AbstractYarnScheduler yarnScheduler; private final SchedulerState schedulerState; //TODO(Santosh): Should figure out the right values for the hashmap properties. // currently it's tuned for 200 nodes and 50 RM RPC threads (Yarn's default). private static final int INITIAL_NODE_SIZE = 200; private static final int EXPECTED_CONCURRENT_ACCCESS_COUNT = 50; private static final float LOAD_FACTOR_DEFAULT = 0.75f; private Map<String, SchedulerNode> schedulerNodes = new ConcurrentHashMap<>(INITIAL_NODE_SIZE, LOAD_FACTOR_DEFAULT, EXPECTED_CONCURRENT_ACCCESS_COUNT); @Inject
public LeastAMNodesFirstPolicy(InterceptorRegistry registry, AbstractYarnScheduler yarnScheduler, SchedulerState schedulerState) {
LTTPP/Eemory
org.lttpp.eemory/src/org/lttpp/eemory/util/ObjectUtil.java
// Path: org.lttpp.eemory/src/org/lttpp/eemory/Messages.java // public class Messages extends NLS { // // private static final String BUNDLE_NAME = "messages"; //$NON-NLS-1$ // // public static String Plugin_Configs_Shell_Title; // public static String Plugin_Configs_QuickOrgnize_Shell_Title; // public static String Plugin_Configs_Title; // public static String Plugin_Configs_Message; // public static String Plugin_Configs_Organize; // public static String Plugin_Configs_Notebook; // public static String Plugin_Configs_Note; // public static String Plugin_Configs_Tags; // public static String Plugin_Configs_Notebook_Hint; // public static String Plugin_Configs_Note_Hint; // public static String Plugin_Configs_Tags_Hint; // public static String Plugin_Configs_Comments; // public static String Plugin_Configs_Refresh; // public static String Plugin_Configs_Authenticating; // public static String Plugin_Configs_FetchingNotebooks; // public static String Plugin_Configs_FetchingNotes; // public static String Plugin_Configs_FetchingTags; // public static String Plugin_Runtime_ClipFileToEvernote; // public static String Plugin_Runtime_ClipSelectionToEvernote; // public static String Plugin_Runtime_ClipScreenshotToEvernote_Hint; // public static String Plugin_Runtime_CreateNewNote; // public static String Plugin_Runtime_CreateNewNoteInNotebook; // public static String Plugin_Runtime_ClipToDefault; // public static String Plugin_Runtime_CreateNewNoteWithGivenName; // public static String Plugin_Runtime_CreateNewNoteWithGivenNameInNotebook; // public static String Plugin_Runtime_ClipToNotebook_Default; // public static String Plugin_OutOfDate; // public static String Plugin_Error_Occurred; // public static String Plugin_Error_OutOfDate; // public static String Plugin_Error_NoFile; // public static String Plugin_Error_NoText; // public static String Plugin_OAuth_Cancel; // public static String Plugin_OAuth_Copy; // // public static String Plugin_OAuth_TokenNotConfigured; // public static String Plugin_OAuth_Title; // public static String Plugin_OAuth_Configure; // public static String Plugin_OAuth_NotNow; // public static String Plugin_OAuth_Waiting; // public static String Plugin_OAuth_Confirm; // public static String Plugin_OAuth_AuthExpired_Message; // public static String Plugin_OAuth_AuthExpired_Title; // public static String Plugin_OAuth_AuthExpired_ReAuth; // public static String Plugin_OAuth_DoItManually; // public static String Plugin_OAuth_SWITCH_YXBJ; // public static String Plugin_OAuth_SWITCH_INTL; // // public static String DOM_Error0; // public static String DOM_Error1; // public static String DOM_Error2; // public static String DOM_Error3; // public static String DOM_Error4; // public static String DOM_Error5; // public static String DOM_Error6; // public static String DOM_Error7; // public static String DOM_Error8; // public static String DOM_Error9; // public static String Throwable_IllegalArgumentException_Message; // public static String Throwable_NotSerializable_Message; // // // For Debug // public static String Plugin_Debug_Default_Font_Style; // public static String Plugin_Debug_StyleRange_Font_Style; // public static String Plugin_Debug_FinalConcluded_Font_Style; // public static String Plugin_Debug_NewClipper; // public static String Plugin_Debug_IsFullScreenSupported; // public static String Plugin_Debug_CapturedScreenshot; // public static String Plugin_Debug_NoScreenCaptureProcessor; // // static { // // initialize resource bundle // NLS.initializeMessages(BUNDLE_NAME, Messages.class); // } // // private Messages() { // } // // }
import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.SerializationException; import org.apache.commons.lang3.SerializationUtils; import org.apache.commons.lang3.StringUtils; import org.lttpp.eemory.Messages;
@SuppressWarnings("unchecked") protected static <T> T cloneCloneNotSupportedObject(final T obj, final boolean deep) { if (obj instanceof String) { return obj; } else if (obj instanceof Byte) { return (T) new Byte((Byte) obj); } else if (obj instanceof Short) { return (T) new Short((Short) obj); } else if (obj instanceof Integer) { return (T) new Integer((Integer) obj); } else if (obj instanceof Long) { return (T) new Long((Long) obj); } else if (obj instanceof Float) { return (T) new Float((Float) obj); } else if (obj instanceof Double) { return (T) new Double((Double) obj); } else if (obj instanceof Boolean) { return (T) new Boolean((Boolean) obj); } else if (obj instanceof Character) { return (T) new Character((Character) obj); } return null; } /* * Assume object is serializable. */ public static String serialize(final Object object) { if (!(object instanceof Serializable)) {
// Path: org.lttpp.eemory/src/org/lttpp/eemory/Messages.java // public class Messages extends NLS { // // private static final String BUNDLE_NAME = "messages"; //$NON-NLS-1$ // // public static String Plugin_Configs_Shell_Title; // public static String Plugin_Configs_QuickOrgnize_Shell_Title; // public static String Plugin_Configs_Title; // public static String Plugin_Configs_Message; // public static String Plugin_Configs_Organize; // public static String Plugin_Configs_Notebook; // public static String Plugin_Configs_Note; // public static String Plugin_Configs_Tags; // public static String Plugin_Configs_Notebook_Hint; // public static String Plugin_Configs_Note_Hint; // public static String Plugin_Configs_Tags_Hint; // public static String Plugin_Configs_Comments; // public static String Plugin_Configs_Refresh; // public static String Plugin_Configs_Authenticating; // public static String Plugin_Configs_FetchingNotebooks; // public static String Plugin_Configs_FetchingNotes; // public static String Plugin_Configs_FetchingTags; // public static String Plugin_Runtime_ClipFileToEvernote; // public static String Plugin_Runtime_ClipSelectionToEvernote; // public static String Plugin_Runtime_ClipScreenshotToEvernote_Hint; // public static String Plugin_Runtime_CreateNewNote; // public static String Plugin_Runtime_CreateNewNoteInNotebook; // public static String Plugin_Runtime_ClipToDefault; // public static String Plugin_Runtime_CreateNewNoteWithGivenName; // public static String Plugin_Runtime_CreateNewNoteWithGivenNameInNotebook; // public static String Plugin_Runtime_ClipToNotebook_Default; // public static String Plugin_OutOfDate; // public static String Plugin_Error_Occurred; // public static String Plugin_Error_OutOfDate; // public static String Plugin_Error_NoFile; // public static String Plugin_Error_NoText; // public static String Plugin_OAuth_Cancel; // public static String Plugin_OAuth_Copy; // // public static String Plugin_OAuth_TokenNotConfigured; // public static String Plugin_OAuth_Title; // public static String Plugin_OAuth_Configure; // public static String Plugin_OAuth_NotNow; // public static String Plugin_OAuth_Waiting; // public static String Plugin_OAuth_Confirm; // public static String Plugin_OAuth_AuthExpired_Message; // public static String Plugin_OAuth_AuthExpired_Title; // public static String Plugin_OAuth_AuthExpired_ReAuth; // public static String Plugin_OAuth_DoItManually; // public static String Plugin_OAuth_SWITCH_YXBJ; // public static String Plugin_OAuth_SWITCH_INTL; // // public static String DOM_Error0; // public static String DOM_Error1; // public static String DOM_Error2; // public static String DOM_Error3; // public static String DOM_Error4; // public static String DOM_Error5; // public static String DOM_Error6; // public static String DOM_Error7; // public static String DOM_Error8; // public static String DOM_Error9; // public static String Throwable_IllegalArgumentException_Message; // public static String Throwable_NotSerializable_Message; // // // For Debug // public static String Plugin_Debug_Default_Font_Style; // public static String Plugin_Debug_StyleRange_Font_Style; // public static String Plugin_Debug_FinalConcluded_Font_Style; // public static String Plugin_Debug_NewClipper; // public static String Plugin_Debug_IsFullScreenSupported; // public static String Plugin_Debug_CapturedScreenshot; // public static String Plugin_Debug_NoScreenCaptureProcessor; // // static { // // initialize resource bundle // NLS.initializeMessages(BUNDLE_NAME, Messages.class); // } // // private Messages() { // } // // } // Path: org.lttpp.eemory/src/org/lttpp/eemory/util/ObjectUtil.java import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.SerializationException; import org.apache.commons.lang3.SerializationUtils; import org.apache.commons.lang3.StringUtils; import org.lttpp.eemory.Messages; @SuppressWarnings("unchecked") protected static <T> T cloneCloneNotSupportedObject(final T obj, final boolean deep) { if (obj instanceof String) { return obj; } else if (obj instanceof Byte) { return (T) new Byte((Byte) obj); } else if (obj instanceof Short) { return (T) new Short((Short) obj); } else if (obj instanceof Integer) { return (T) new Integer((Integer) obj); } else if (obj instanceof Long) { return (T) new Long((Long) obj); } else if (obj instanceof Float) { return (T) new Float((Float) obj); } else if (obj instanceof Double) { return (T) new Double((Double) obj); } else if (obj instanceof Boolean) { return (T) new Boolean((Boolean) obj); } else if (obj instanceof Character) { return (T) new Character((Character) obj); } return null; } /* * Assume object is serializable. */ public static String serialize(final Object object) { if (!(object instanceof Serializable)) {
throw new SerializationException(Messages.bind(Messages.Throwable_NotSerializable_Message, object));
LTTPP/Eemory
org.lttpp.eemory/src/org/lttpp/eemory/client/NoteOps.java
// Path: org.lttpp.eemory/src/org/lttpp/eemory/client/metadata/ENObjectType.java // public enum ENObjectType { // // NORMAL { // @Override // public String toString() { // return Constants.ENOBJECT_TYPE_NORMAL; // } // }, // LINKED { // @Override // public String toString() { // return Constants.ENOBJECT_TYPE_LINKED; // } // }, // BUSINESS { // @Override // public String toString() { // return Constants.ENOBJECT_TYPE_BUSINESS; // } // }; // // public static ENObjectType forName(final String name) throws IllegalArgumentException { // ENObjectType[] values = ENObjectType.values(); // for (ENObjectType value : values) { // if (value.toString().equalsIgnoreCase(name)) { // return value; // } // } // LogUtil.debug(Messages.bind(Messages.Throwable_IllegalArgumentException_Message, name)); // throw new IllegalArgumentException(Messages.bind(Messages.Throwable_IllegalArgumentException_Message, name)); // } // // } // // Path: org.lttpp.eemory/src/org/lttpp/eemory/client/model/ENNote.java // public interface ENNote extends ENObject { // // public ENObject getNotebook(); // // public void setNotebook(ENObject notebook); // // public List<List<StyleText>> getContent(); // // public void setContent(List<List<StyleText>> content); // // public List<File> getAttachments(); // // public void setAttachments(List<File> files); // // public List<String> getTags(); // // public abstract void setTags(List<String> tags); // // public abstract String getComments(); // // public abstract void setComments(String comments); // // public abstract int getTabWidth(); // // public abstract void setTabWidth(int tabWidth); // // }
import org.lttpp.eemory.client.metadata.ENObjectType; import org.lttpp.eemory.client.model.ENNote; import com.evernote.clients.NoteStoreClient; import com.evernote.edam.error.EDAMNotFoundException; import com.evernote.edam.error.EDAMSystemException; import com.evernote.edam.error.EDAMUserException; import com.evernote.edam.type.LinkedNotebook; import com.evernote.thrift.TException;
package org.lttpp.eemory.client; public abstract class NoteOps { private final StoreClientFactory factory; public NoteOps(final StoreClientFactory factory) { this.factory = factory; }
// Path: org.lttpp.eemory/src/org/lttpp/eemory/client/metadata/ENObjectType.java // public enum ENObjectType { // // NORMAL { // @Override // public String toString() { // return Constants.ENOBJECT_TYPE_NORMAL; // } // }, // LINKED { // @Override // public String toString() { // return Constants.ENOBJECT_TYPE_LINKED; // } // }, // BUSINESS { // @Override // public String toString() { // return Constants.ENOBJECT_TYPE_BUSINESS; // } // }; // // public static ENObjectType forName(final String name) throws IllegalArgumentException { // ENObjectType[] values = ENObjectType.values(); // for (ENObjectType value : values) { // if (value.toString().equalsIgnoreCase(name)) { // return value; // } // } // LogUtil.debug(Messages.bind(Messages.Throwable_IllegalArgumentException_Message, name)); // throw new IllegalArgumentException(Messages.bind(Messages.Throwable_IllegalArgumentException_Message, name)); // } // // } // // Path: org.lttpp.eemory/src/org/lttpp/eemory/client/model/ENNote.java // public interface ENNote extends ENObject { // // public ENObject getNotebook(); // // public void setNotebook(ENObject notebook); // // public List<List<StyleText>> getContent(); // // public void setContent(List<List<StyleText>> content); // // public List<File> getAttachments(); // // public void setAttachments(List<File> files); // // public List<String> getTags(); // // public abstract void setTags(List<String> tags); // // public abstract String getComments(); // // public abstract void setComments(String comments); // // public abstract int getTabWidth(); // // public abstract void setTabWidth(int tabWidth); // // } // Path: org.lttpp.eemory/src/org/lttpp/eemory/client/NoteOps.java import org.lttpp.eemory.client.metadata.ENObjectType; import org.lttpp.eemory.client.model.ENNote; import com.evernote.clients.NoteStoreClient; import com.evernote.edam.error.EDAMNotFoundException; import com.evernote.edam.error.EDAMSystemException; import com.evernote.edam.error.EDAMUserException; import com.evernote.edam.type.LinkedNotebook; import com.evernote.thrift.TException; package org.lttpp.eemory.client; public abstract class NoteOps { private final StoreClientFactory factory; public NoteOps(final StoreClientFactory factory) { this.factory = factory; }
public abstract void updateOrCreate(ENNote args) throws Exception;
LTTPP/Eemory
org.lttpp.eemory/src/org/lttpp/eemory/client/NoteOps.java
// Path: org.lttpp.eemory/src/org/lttpp/eemory/client/metadata/ENObjectType.java // public enum ENObjectType { // // NORMAL { // @Override // public String toString() { // return Constants.ENOBJECT_TYPE_NORMAL; // } // }, // LINKED { // @Override // public String toString() { // return Constants.ENOBJECT_TYPE_LINKED; // } // }, // BUSINESS { // @Override // public String toString() { // return Constants.ENOBJECT_TYPE_BUSINESS; // } // }; // // public static ENObjectType forName(final String name) throws IllegalArgumentException { // ENObjectType[] values = ENObjectType.values(); // for (ENObjectType value : values) { // if (value.toString().equalsIgnoreCase(name)) { // return value; // } // } // LogUtil.debug(Messages.bind(Messages.Throwable_IllegalArgumentException_Message, name)); // throw new IllegalArgumentException(Messages.bind(Messages.Throwable_IllegalArgumentException_Message, name)); // } // // } // // Path: org.lttpp.eemory/src/org/lttpp/eemory/client/model/ENNote.java // public interface ENNote extends ENObject { // // public ENObject getNotebook(); // // public void setNotebook(ENObject notebook); // // public List<List<StyleText>> getContent(); // // public void setContent(List<List<StyleText>> content); // // public List<File> getAttachments(); // // public void setAttachments(List<File> files); // // public List<String> getTags(); // // public abstract void setTags(List<String> tags); // // public abstract String getComments(); // // public abstract void setComments(String comments); // // public abstract int getTabWidth(); // // public abstract void setTabWidth(int tabWidth); // // }
import org.lttpp.eemory.client.metadata.ENObjectType; import org.lttpp.eemory.client.model.ENNote; import com.evernote.clients.NoteStoreClient; import com.evernote.edam.error.EDAMNotFoundException; import com.evernote.edam.error.EDAMSystemException; import com.evernote.edam.error.EDAMUserException; import com.evernote.edam.type.LinkedNotebook; import com.evernote.thrift.TException;
package org.lttpp.eemory.client; public abstract class NoteOps { private final StoreClientFactory factory; public NoteOps(final StoreClientFactory factory) { this.factory = factory; } public abstract void updateOrCreate(ENNote args) throws Exception; protected NoteStoreClient getNoteStoreClient(final ENNote args) throws EDAMUserException, EDAMSystemException, TException, EDAMNotFoundException { NoteStoreClient client;
// Path: org.lttpp.eemory/src/org/lttpp/eemory/client/metadata/ENObjectType.java // public enum ENObjectType { // // NORMAL { // @Override // public String toString() { // return Constants.ENOBJECT_TYPE_NORMAL; // } // }, // LINKED { // @Override // public String toString() { // return Constants.ENOBJECT_TYPE_LINKED; // } // }, // BUSINESS { // @Override // public String toString() { // return Constants.ENOBJECT_TYPE_BUSINESS; // } // }; // // public static ENObjectType forName(final String name) throws IllegalArgumentException { // ENObjectType[] values = ENObjectType.values(); // for (ENObjectType value : values) { // if (value.toString().equalsIgnoreCase(name)) { // return value; // } // } // LogUtil.debug(Messages.bind(Messages.Throwable_IllegalArgumentException_Message, name)); // throw new IllegalArgumentException(Messages.bind(Messages.Throwable_IllegalArgumentException_Message, name)); // } // // } // // Path: org.lttpp.eemory/src/org/lttpp/eemory/client/model/ENNote.java // public interface ENNote extends ENObject { // // public ENObject getNotebook(); // // public void setNotebook(ENObject notebook); // // public List<List<StyleText>> getContent(); // // public void setContent(List<List<StyleText>> content); // // public List<File> getAttachments(); // // public void setAttachments(List<File> files); // // public List<String> getTags(); // // public abstract void setTags(List<String> tags); // // public abstract String getComments(); // // public abstract void setComments(String comments); // // public abstract int getTabWidth(); // // public abstract void setTabWidth(int tabWidth); // // } // Path: org.lttpp.eemory/src/org/lttpp/eemory/client/NoteOps.java import org.lttpp.eemory.client.metadata.ENObjectType; import org.lttpp.eemory.client.model.ENNote; import com.evernote.clients.NoteStoreClient; import com.evernote.edam.error.EDAMNotFoundException; import com.evernote.edam.error.EDAMSystemException; import com.evernote.edam.error.EDAMUserException; import com.evernote.edam.type.LinkedNotebook; import com.evernote.thrift.TException; package org.lttpp.eemory.client; public abstract class NoteOps { private final StoreClientFactory factory; public NoteOps(final StoreClientFactory factory) { this.factory = factory; } public abstract void updateOrCreate(ENNote args) throws Exception; protected NoteStoreClient getNoteStoreClient(final ENNote args) throws EDAMUserException, EDAMSystemException, TException, EDAMNotFoundException { NoteStoreClient client;
if (args.getNotebook().getType() == ENObjectType.LINKED) {
LTTPP/Eemory
org.lttpp.eemory/src/org/lttpp/eemory/ui/SyncQuickOrganizeDialog.java
// Path: org.lttpp.eemory/src/org/lttpp/eemory/util/LogUtil.java // public class LogUtil { // // private static final ILog log = EemoryPlugin.getDefault().getLog(); // // public static void debug(final String message) { // String debug = System.getProperty(Constants.PLUGIN_DEBUG_MODE); // if (BooleanUtils.toBoolean(debug)) { // logInfo(message); // } // } // // public static void logInfo(final Throwable exception) { // log.log(info(exception)); // } // // public static void logWarning(final Throwable exception) { // log.log(warning(exception)); // } // // public static void logWarning(final String message, final Throwable exception) { // log.log(warning(message, exception)); // } // // public static void logCancel(final Throwable exception) { // log.log(cancel(exception)); // } // // public static void logError(final Throwable exception) { // log.log(error(exception)); // } // // public static void logInfo(final String message) { // log.log(info(message)); // } // // public static void logWarning(final String message) { // log.log(warning(message)); // } // // public static void logCancel(final String message) { // log.log(cancel(message)); // } // // public static void logError(final String message) { // log.log(error(message)); // } // // public static IStatus info(final Throwable exception) { // return new Status(Status.INFO, EemoryPlugin.PLUGIN_ID, ExceptionUtils.getRootCauseMessage(exception), exception); // } // // public static IStatus warning(final Throwable exception) { // return new Status(Status.WARNING, EemoryPlugin.PLUGIN_ID, ExceptionUtils.getRootCauseMessage(exception), exception); // } // // public static IStatus warning(final String message, final Throwable exception) { // return new Status(Status.WARNING, EemoryPlugin.PLUGIN_ID, message, exception); // } // // public static IStatus cancel(final Throwable exception) { // return new Status(Status.CANCEL, EemoryPlugin.PLUGIN_ID, ExceptionUtils.getRootCauseMessage(exception), exception); // } // // public static IStatus error(final Throwable exception) { // return new Status(Status.ERROR, EemoryPlugin.PLUGIN_ID, ExceptionUtils.getRootCauseMessage(exception), exception); // } // // public static IStatus info(final String message) { // return new Status(Status.INFO, EemoryPlugin.PLUGIN_ID, message); // } // // public static IStatus warning(final String message) { // return new Status(Status.WARNING, EemoryPlugin.PLUGIN_ID, message); // } // // public static IStatus cancel(final String message) { // return new Status(Status.CANCEL, EemoryPlugin.PLUGIN_ID, message); // } // public static IStatus error(final String message) { // return new Status(Status.ERROR, EemoryPlugin.PLUGIN_ID, message); // } // // public static IStatus ok() { // return Status.OK_STATUS; // } // // public static IStatus cancel() { // return Status.CANCEL_STATUS; // } // // }
import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.lttpp.eemory.util.LogUtil;
package org.lttpp.eemory.ui; public class SyncQuickOrganizeDialog { private final Shell shell; private int option = QuickOrganizeDialog.CANCEL; public SyncQuickOrganizeDialog(final Shell shell) { this.shell = shell; } public int show() { Display.getDefault().syncExec(new Runnable() { @Override public void run() { try { option = QuickOrganizeDialog.show(shell); } catch (Exception e) {
// Path: org.lttpp.eemory/src/org/lttpp/eemory/util/LogUtil.java // public class LogUtil { // // private static final ILog log = EemoryPlugin.getDefault().getLog(); // // public static void debug(final String message) { // String debug = System.getProperty(Constants.PLUGIN_DEBUG_MODE); // if (BooleanUtils.toBoolean(debug)) { // logInfo(message); // } // } // // public static void logInfo(final Throwable exception) { // log.log(info(exception)); // } // // public static void logWarning(final Throwable exception) { // log.log(warning(exception)); // } // // public static void logWarning(final String message, final Throwable exception) { // log.log(warning(message, exception)); // } // // public static void logCancel(final Throwable exception) { // log.log(cancel(exception)); // } // // public static void logError(final Throwable exception) { // log.log(error(exception)); // } // // public static void logInfo(final String message) { // log.log(info(message)); // } // // public static void logWarning(final String message) { // log.log(warning(message)); // } // // public static void logCancel(final String message) { // log.log(cancel(message)); // } // // public static void logError(final String message) { // log.log(error(message)); // } // // public static IStatus info(final Throwable exception) { // return new Status(Status.INFO, EemoryPlugin.PLUGIN_ID, ExceptionUtils.getRootCauseMessage(exception), exception); // } // // public static IStatus warning(final Throwable exception) { // return new Status(Status.WARNING, EemoryPlugin.PLUGIN_ID, ExceptionUtils.getRootCauseMessage(exception), exception); // } // // public static IStatus warning(final String message, final Throwable exception) { // return new Status(Status.WARNING, EemoryPlugin.PLUGIN_ID, message, exception); // } // // public static IStatus cancel(final Throwable exception) { // return new Status(Status.CANCEL, EemoryPlugin.PLUGIN_ID, ExceptionUtils.getRootCauseMessage(exception), exception); // } // // public static IStatus error(final Throwable exception) { // return new Status(Status.ERROR, EemoryPlugin.PLUGIN_ID, ExceptionUtils.getRootCauseMessage(exception), exception); // } // // public static IStatus info(final String message) { // return new Status(Status.INFO, EemoryPlugin.PLUGIN_ID, message); // } // // public static IStatus warning(final String message) { // return new Status(Status.WARNING, EemoryPlugin.PLUGIN_ID, message); // } // // public static IStatus cancel(final String message) { // return new Status(Status.CANCEL, EemoryPlugin.PLUGIN_ID, message); // } // public static IStatus error(final String message) { // return new Status(Status.ERROR, EemoryPlugin.PLUGIN_ID, message); // } // // public static IStatus ok() { // return Status.OK_STATUS; // } // // public static IStatus cancel() { // return Status.CANCEL_STATUS; // } // // } // Path: org.lttpp.eemory/src/org/lttpp/eemory/ui/SyncQuickOrganizeDialog.java import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.lttpp.eemory.util.LogUtil; package org.lttpp.eemory.ui; public class SyncQuickOrganizeDialog { private final Shell shell; private int option = QuickOrganizeDialog.CANCEL; public SyncQuickOrganizeDialog(final Shell shell) { this.shell = shell; } public int show() { Display.getDefault().syncExec(new Runnable() { @Override public void run() { try { option = QuickOrganizeDialog.show(shell); } catch (Exception e) {
LogUtil.logError(e);
LTTPP/Eemory
org.lttpp.eemory/src/org/lttpp/eemory/enml/StyleText.java
// Path: org.lttpp.eemory/src/org/lttpp/eemory/util/ColorUtil.java // public class ColorUtil { // // public final static java.awt.Color AWT_EVERNOTE_GREEN = new java.awt.Color(32, 192, 92); // public final static org.eclipse.swt.graphics.Color SWT_COLOR_DEFAULT = new org.eclipse.swt.graphics.Color(null, 0, 0, 0); // public final static int SWT_COLOR_GRAY = SWT.COLOR_GRAY; // // public static String toHexCode(final int r, final int g, final int b) { // return ConstantsUtil.POUND + toHexString(r) + toHexString(g) + toHexString(b); // } // // private static String toHexString(final int number) { // String hex = Integer.toHexString(number).toUpperCase(); // while (hex.length() < 2) { // hex = 0 + hex; // } // return hex; // } // // }
import org.apache.commons.lang3.StringUtils; import org.lttpp.eemory.util.ColorUtil;
package org.lttpp.eemory.enml; public class StyleText { private String text; private String face; private String colorHexCode; private String size; private FontStyle fontStyle; public StyleText(final String text) { this.text = text; face = StringUtils.EMPTY;
// Path: org.lttpp.eemory/src/org/lttpp/eemory/util/ColorUtil.java // public class ColorUtil { // // public final static java.awt.Color AWT_EVERNOTE_GREEN = new java.awt.Color(32, 192, 92); // public final static org.eclipse.swt.graphics.Color SWT_COLOR_DEFAULT = new org.eclipse.swt.graphics.Color(null, 0, 0, 0); // public final static int SWT_COLOR_GRAY = SWT.COLOR_GRAY; // // public static String toHexCode(final int r, final int g, final int b) { // return ConstantsUtil.POUND + toHexString(r) + toHexString(g) + toHexString(b); // } // // private static String toHexString(final int number) { // String hex = Integer.toHexString(number).toUpperCase(); // while (hex.length() < 2) { // hex = 0 + hex; // } // return hex; // } // // } // Path: org.lttpp.eemory/src/org/lttpp/eemory/enml/StyleText.java import org.apache.commons.lang3.StringUtils; import org.lttpp.eemory.util.ColorUtil; package org.lttpp.eemory.enml; public class StyleText { private String text; private String face; private String colorHexCode; private String size; private FontStyle fontStyle; public StyleText(final String text) { this.text = text; face = StringUtils.EMPTY;
colorHexCode = ColorUtil.toHexCode(0, 0, 0);
LTTPP/Eemory
org.lttpp.eemory/src/org/lttpp/eemory/client/impl/model/ENObjectImpl.java
// Path: org.lttpp.eemory/src/org/lttpp/eemory/client/metadata/ENObjectType.java // public enum ENObjectType { // // NORMAL { // @Override // public String toString() { // return Constants.ENOBJECT_TYPE_NORMAL; // } // }, // LINKED { // @Override // public String toString() { // return Constants.ENOBJECT_TYPE_LINKED; // } // }, // BUSINESS { // @Override // public String toString() { // return Constants.ENOBJECT_TYPE_BUSINESS; // } // }; // // public static ENObjectType forName(final String name) throws IllegalArgumentException { // ENObjectType[] values = ENObjectType.values(); // for (ENObjectType value : values) { // if (value.toString().equalsIgnoreCase(name)) { // return value; // } // } // LogUtil.debug(Messages.bind(Messages.Throwable_IllegalArgumentException_Message, name)); // throw new IllegalArgumentException(Messages.bind(Messages.Throwable_IllegalArgumentException_Message, name)); // } // // }
import org.apache.commons.lang3.StringUtils; import org.lttpp.eemory.client.metadata.ENObjectType; import org.lttpp.eemory.client.model.ENObject;
package org.lttpp.eemory.client.impl.model; public class ENObjectImpl implements ENObject { private String name; private String guid; private boolean reset = false; private boolean adopt = false;
// Path: org.lttpp.eemory/src/org/lttpp/eemory/client/metadata/ENObjectType.java // public enum ENObjectType { // // NORMAL { // @Override // public String toString() { // return Constants.ENOBJECT_TYPE_NORMAL; // } // }, // LINKED { // @Override // public String toString() { // return Constants.ENOBJECT_TYPE_LINKED; // } // }, // BUSINESS { // @Override // public String toString() { // return Constants.ENOBJECT_TYPE_BUSINESS; // } // }; // // public static ENObjectType forName(final String name) throws IllegalArgumentException { // ENObjectType[] values = ENObjectType.values(); // for (ENObjectType value : values) { // if (value.toString().equalsIgnoreCase(name)) { // return value; // } // } // LogUtil.debug(Messages.bind(Messages.Throwable_IllegalArgumentException_Message, name)); // throw new IllegalArgumentException(Messages.bind(Messages.Throwable_IllegalArgumentException_Message, name)); // } // // } // Path: org.lttpp.eemory/src/org/lttpp/eemory/client/impl/model/ENObjectImpl.java import org.apache.commons.lang3.StringUtils; import org.lttpp.eemory.client.metadata.ENObjectType; import org.lttpp.eemory.client.model.ENObject; package org.lttpp.eemory.client.impl.model; public class ENObjectImpl implements ENObject { private String name; private String guid; private boolean reset = false; private boolean adopt = false;
private ENObjectType type = ENObjectType.NORMAL;
LTTPP/Eemory
org.lttpp.eemory/src/org/lttpp/eemory/oauth/impl/BundledFileResource.java
// Path: org.lttpp.eemory/src/org/lttpp/eemory/util/ConstantsUtil.java // public class ConstantsUtil { // // public static final String COMMA = ","; // public static final String COLON = ":"; // public static final String SEMICOLON = ";"; // public static final String DOT = "."; // public static final String POUND = "#"; // public static final String STAR = "*"; // public static final String MD5 = "MD5"; // public static final String LEFT_PARENTHESIS = "("; // public static final String RIGHT_PARENTHESIS = ")"; // public static final String LEFT_BRACE = "{"; // public static final String RIGHT_BRACE = "}"; // public static final String LESS_THAN = "<"; // public static final String GREATER_THAN = ">"; // public static final String RIGHT_ANGLE_BRACKET = GREATER_THAN; // public static final String LEFT_ANGLE_BRACKET = LESS_THAN; // public static final String IMG_PNG = "png"; // public static final String PLUS = "+"; // public static final String MINUS = "-"; // public static final String EQUAL = "="; // public static final String EXCLAMATION = "!"; // public static final String DOUBLE_QUOTE = "\""; // public static final String SINGLE_QUOTE = "'"; // public static String SLASH = "/"; // public static String BACKSLASH = "\\"; // public static String QUESTION_MARK = "?"; // public static final String TAB = "\t"; // // }
import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.nio.channels.ReadableByteChannel; import org.eclipse.jetty.util.resource.Resource; import org.lttpp.eemory.util.ConstantsUtil;
stream.close(); } catch (IOException ignored) { } return true; } else { return false; } } @Override public InputStream getInputStream() { return stream = getLoadingClass().getResourceAsStream(name); } @Override public ReadableByteChannel getReadableByteChannel() { return null; } @Override public URI getAlias() { return null; } @Override public Resource addPath(final String path) throws MalformedURLException { if (path == null) { throw new MalformedURLException(); }
// Path: org.lttpp.eemory/src/org/lttpp/eemory/util/ConstantsUtil.java // public class ConstantsUtil { // // public static final String COMMA = ","; // public static final String COLON = ":"; // public static final String SEMICOLON = ";"; // public static final String DOT = "."; // public static final String POUND = "#"; // public static final String STAR = "*"; // public static final String MD5 = "MD5"; // public static final String LEFT_PARENTHESIS = "("; // public static final String RIGHT_PARENTHESIS = ")"; // public static final String LEFT_BRACE = "{"; // public static final String RIGHT_BRACE = "}"; // public static final String LESS_THAN = "<"; // public static final String GREATER_THAN = ">"; // public static final String RIGHT_ANGLE_BRACKET = GREATER_THAN; // public static final String LEFT_ANGLE_BRACKET = LESS_THAN; // public static final String IMG_PNG = "png"; // public static final String PLUS = "+"; // public static final String MINUS = "-"; // public static final String EQUAL = "="; // public static final String EXCLAMATION = "!"; // public static final String DOUBLE_QUOTE = "\""; // public static final String SINGLE_QUOTE = "'"; // public static String SLASH = "/"; // public static String BACKSLASH = "\\"; // public static String QUESTION_MARK = "?"; // public static final String TAB = "\t"; // // } // Path: org.lttpp.eemory/src/org/lttpp/eemory/oauth/impl/BundledFileResource.java import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.nio.channels.ReadableByteChannel; import org.eclipse.jetty.util.resource.Resource; import org.lttpp.eemory.util.ConstantsUtil; stream.close(); } catch (IOException ignored) { } return true; } else { return false; } } @Override public InputStream getInputStream() { return stream = getLoadingClass().getResourceAsStream(name); } @Override public ReadableByteChannel getReadableByteChannel() { return null; } @Override public URI getAlias() { return null; } @Override public Resource addPath(final String path) throws MalformedURLException { if (path == null) { throw new MalformedURLException(); }
if (ConstantsUtil.SLASH.equals(path)) {
LTTPP/Eemory
org.lttpp.eemory/src/org/lttpp/eemory/client/EeClipper.java
// Path: org.lttpp.eemory/src/org/lttpp/eemory/client/model/ENNote.java // public interface ENNote extends ENObject { // // public ENObject getNotebook(); // // public void setNotebook(ENObject notebook); // // public List<List<StyleText>> getContent(); // // public void setContent(List<List<StyleText>> content); // // public List<File> getAttachments(); // // public void setAttachments(List<File> files); // // public List<String> getTags(); // // public abstract void setTags(List<String> tags); // // public abstract String getComments(); // // public abstract void setComments(String comments); // // public abstract int getTabWidth(); // // public abstract void setTabWidth(int tabWidth); // // }
import java.util.List; import java.util.Map; import org.lttpp.eemory.client.model.ENNote; import org.lttpp.eemory.client.model.ENObject;
package org.lttpp.eemory.client; public abstract class EeClipper { private boolean valid = true;
// Path: org.lttpp.eemory/src/org/lttpp/eemory/client/model/ENNote.java // public interface ENNote extends ENObject { // // public ENObject getNotebook(); // // public void setNotebook(ENObject notebook); // // public List<List<StyleText>> getContent(); // // public void setContent(List<List<StyleText>> content); // // public List<File> getAttachments(); // // public void setAttachments(List<File> files); // // public List<String> getTags(); // // public abstract void setTags(List<String> tags); // // public abstract String getComments(); // // public abstract void setComments(String comments); // // public abstract int getTabWidth(); // // public abstract void setTabWidth(int tabWidth); // // } // Path: org.lttpp.eemory/src/org/lttpp/eemory/client/EeClipper.java import java.util.List; import java.util.Map; import org.lttpp.eemory.client.model.ENNote; import org.lttpp.eemory.client.model.ENObject; package org.lttpp.eemory.client; public abstract class EeClipper { private boolean valid = true;
public abstract void clipFile(ENNote args) throws Exception;
LTTPP/Eemory
org.lttpp.eemory/src/org/lttpp/eemory/client/model/ENNote.java
// Path: org.lttpp.eemory/src/org/lttpp/eemory/enml/StyleText.java // public class StyleText { // // private String text; // private String face; // private String colorHexCode; // private String size; // private FontStyle fontStyle; // // public StyleText(final String text) { // this.text = text; // face = StringUtils.EMPTY; // colorHexCode = ColorUtil.toHexCode(0, 0, 0); // fontStyle = FontStyle.NORMAL; // size = StringUtils.EMPTY; // } // // public StyleText(final String text, final String face, final String colorHexCode, final String size, final FontStyle fontStyle) { // this.text = text; // this.face = face; // this.colorHexCode = colorHexCode; // this.fontStyle = fontStyle; // this.size = size; // } // // public String getText() { // return text; // } // // public void setText(final String text) { // this.text = text; // } // // public String getColorHexCode() { // return colorHexCode; // } // // public void setColorHexCode(final String colorHexCode) { // this.colorHexCode = colorHexCode; // } // // public FontStyle getFontStyle() { // return fontStyle; // } // // public void setFontStyle(final FontStyle fontStyle) { // this.fontStyle = fontStyle; // } // // public String getFace() { // return face; // } // // public void setFace(final String face) { // this.face = face; // } // // public String getSize() { // return size; // } // // public void setSize(final String size) { // this.size = size; // } // // @Override // public String toString() { // return text; // } // // }
import java.io.File; import java.util.List; import org.lttpp.eemory.enml.StyleText;
package org.lttpp.eemory.client.model; public interface ENNote extends ENObject { public ENObject getNotebook(); public void setNotebook(ENObject notebook);
// Path: org.lttpp.eemory/src/org/lttpp/eemory/enml/StyleText.java // public class StyleText { // // private String text; // private String face; // private String colorHexCode; // private String size; // private FontStyle fontStyle; // // public StyleText(final String text) { // this.text = text; // face = StringUtils.EMPTY; // colorHexCode = ColorUtil.toHexCode(0, 0, 0); // fontStyle = FontStyle.NORMAL; // size = StringUtils.EMPTY; // } // // public StyleText(final String text, final String face, final String colorHexCode, final String size, final FontStyle fontStyle) { // this.text = text; // this.face = face; // this.colorHexCode = colorHexCode; // this.fontStyle = fontStyle; // this.size = size; // } // // public String getText() { // return text; // } // // public void setText(final String text) { // this.text = text; // } // // public String getColorHexCode() { // return colorHexCode; // } // // public void setColorHexCode(final String colorHexCode) { // this.colorHexCode = colorHexCode; // } // // public FontStyle getFontStyle() { // return fontStyle; // } // // public void setFontStyle(final FontStyle fontStyle) { // this.fontStyle = fontStyle; // } // // public String getFace() { // return face; // } // // public void setFace(final String face) { // this.face = face; // } // // public String getSize() { // return size; // } // // public void setSize(final String size) { // this.size = size; // } // // @Override // public String toString() { // return text; // } // // } // Path: org.lttpp.eemory/src/org/lttpp/eemory/client/model/ENNote.java import java.io.File; import java.util.List; import org.lttpp.eemory.enml.StyleText; package org.lttpp.eemory.client.model; public interface ENNote extends ENObject { public ENObject getNotebook(); public void setNotebook(ENObject notebook);
public List<List<StyleText>> getContent();
LTTPP/Eemory
org.lttpp.eemory/src/org/lttpp/eemory/oauth/impl/EclipseErrorLog.java
// Path: org.lttpp.eemory/src/org/lttpp/eemory/util/LogUtil.java // public class LogUtil { // // private static final ILog log = EemoryPlugin.getDefault().getLog(); // // public static void debug(final String message) { // String debug = System.getProperty(Constants.PLUGIN_DEBUG_MODE); // if (BooleanUtils.toBoolean(debug)) { // logInfo(message); // } // } // // public static void logInfo(final Throwable exception) { // log.log(info(exception)); // } // // public static void logWarning(final Throwable exception) { // log.log(warning(exception)); // } // // public static void logWarning(final String message, final Throwable exception) { // log.log(warning(message, exception)); // } // // public static void logCancel(final Throwable exception) { // log.log(cancel(exception)); // } // // public static void logError(final Throwable exception) { // log.log(error(exception)); // } // // public static void logInfo(final String message) { // log.log(info(message)); // } // // public static void logWarning(final String message) { // log.log(warning(message)); // } // // public static void logCancel(final String message) { // log.log(cancel(message)); // } // // public static void logError(final String message) { // log.log(error(message)); // } // // public static IStatus info(final Throwable exception) { // return new Status(Status.INFO, EemoryPlugin.PLUGIN_ID, ExceptionUtils.getRootCauseMessage(exception), exception); // } // // public static IStatus warning(final Throwable exception) { // return new Status(Status.WARNING, EemoryPlugin.PLUGIN_ID, ExceptionUtils.getRootCauseMessage(exception), exception); // } // // public static IStatus warning(final String message, final Throwable exception) { // return new Status(Status.WARNING, EemoryPlugin.PLUGIN_ID, message, exception); // } // // public static IStatus cancel(final Throwable exception) { // return new Status(Status.CANCEL, EemoryPlugin.PLUGIN_ID, ExceptionUtils.getRootCauseMessage(exception), exception); // } // // public static IStatus error(final Throwable exception) { // return new Status(Status.ERROR, EemoryPlugin.PLUGIN_ID, ExceptionUtils.getRootCauseMessage(exception), exception); // } // // public static IStatus info(final String message) { // return new Status(Status.INFO, EemoryPlugin.PLUGIN_ID, message); // } // // public static IStatus warning(final String message) { // return new Status(Status.WARNING, EemoryPlugin.PLUGIN_ID, message); // } // // public static IStatus cancel(final String message) { // return new Status(Status.CANCEL, EemoryPlugin.PLUGIN_ID, message); // } // public static IStatus error(final String message) { // return new Status(Status.ERROR, EemoryPlugin.PLUGIN_ID, message); // } // // public static IStatus ok() { // return Status.OK_STATUS; // } // // public static IStatus cancel() { // return Status.CANCEL_STATUS; // } // // }
import org.eclipse.jetty.util.log.AbstractLogger; import org.eclipse.jetty.util.log.Logger; import org.lttpp.eemory.util.LogUtil;
nop(); } @Override public void info(final Throwable thrown) { nop(); } @Override public void info(final String message, final Object... args) { nop(); } @Override public void info(final String message, final Throwable args) { nop(); } @Override public boolean isDebugEnabled() { return false; } @Override public void setDebugEnabled(final boolean debugEnabled) { nop(); } @Override public void warn(final Throwable thrown) {
// Path: org.lttpp.eemory/src/org/lttpp/eemory/util/LogUtil.java // public class LogUtil { // // private static final ILog log = EemoryPlugin.getDefault().getLog(); // // public static void debug(final String message) { // String debug = System.getProperty(Constants.PLUGIN_DEBUG_MODE); // if (BooleanUtils.toBoolean(debug)) { // logInfo(message); // } // } // // public static void logInfo(final Throwable exception) { // log.log(info(exception)); // } // // public static void logWarning(final Throwable exception) { // log.log(warning(exception)); // } // // public static void logWarning(final String message, final Throwable exception) { // log.log(warning(message, exception)); // } // // public static void logCancel(final Throwable exception) { // log.log(cancel(exception)); // } // // public static void logError(final Throwable exception) { // log.log(error(exception)); // } // // public static void logInfo(final String message) { // log.log(info(message)); // } // // public static void logWarning(final String message) { // log.log(warning(message)); // } // // public static void logCancel(final String message) { // log.log(cancel(message)); // } // // public static void logError(final String message) { // log.log(error(message)); // } // // public static IStatus info(final Throwable exception) { // return new Status(Status.INFO, EemoryPlugin.PLUGIN_ID, ExceptionUtils.getRootCauseMessage(exception), exception); // } // // public static IStatus warning(final Throwable exception) { // return new Status(Status.WARNING, EemoryPlugin.PLUGIN_ID, ExceptionUtils.getRootCauseMessage(exception), exception); // } // // public static IStatus warning(final String message, final Throwable exception) { // return new Status(Status.WARNING, EemoryPlugin.PLUGIN_ID, message, exception); // } // // public static IStatus cancel(final Throwable exception) { // return new Status(Status.CANCEL, EemoryPlugin.PLUGIN_ID, ExceptionUtils.getRootCauseMessage(exception), exception); // } // // public static IStatus error(final Throwable exception) { // return new Status(Status.ERROR, EemoryPlugin.PLUGIN_ID, ExceptionUtils.getRootCauseMessage(exception), exception); // } // // public static IStatus info(final String message) { // return new Status(Status.INFO, EemoryPlugin.PLUGIN_ID, message); // } // // public static IStatus warning(final String message) { // return new Status(Status.WARNING, EemoryPlugin.PLUGIN_ID, message); // } // // public static IStatus cancel(final String message) { // return new Status(Status.CANCEL, EemoryPlugin.PLUGIN_ID, message); // } // public static IStatus error(final String message) { // return new Status(Status.ERROR, EemoryPlugin.PLUGIN_ID, message); // } // // public static IStatus ok() { // return Status.OK_STATUS; // } // // public static IStatus cancel() { // return Status.CANCEL_STATUS; // } // // } // Path: org.lttpp.eemory/src/org/lttpp/eemory/oauth/impl/EclipseErrorLog.java import org.eclipse.jetty.util.log.AbstractLogger; import org.eclipse.jetty.util.log.Logger; import org.lttpp.eemory.util.LogUtil; nop(); } @Override public void info(final Throwable thrown) { nop(); } @Override public void info(final String message, final Object... args) { nop(); } @Override public void info(final String message, final Throwable args) { nop(); } @Override public boolean isDebugEnabled() { return false; } @Override public void setDebugEnabled(final boolean debugEnabled) { nop(); } @Override public void warn(final Throwable thrown) {
LogUtil.logWarning(thrown);
LTTPP/Eemory
org.lttpp.eemory/src/org/lttpp/eemory/Constants.java
// Path: org.lttpp.eemory/src/org/lttpp/eemory/util/ConstantsUtil.java // public class ConstantsUtil { // // public static final String COMMA = ","; // public static final String COLON = ":"; // public static final String SEMICOLON = ";"; // public static final String DOT = "."; // public static final String POUND = "#"; // public static final String STAR = "*"; // public static final String MD5 = "MD5"; // public static final String LEFT_PARENTHESIS = "("; // public static final String RIGHT_PARENTHESIS = ")"; // public static final String LEFT_BRACE = "{"; // public static final String RIGHT_BRACE = "}"; // public static final String LESS_THAN = "<"; // public static final String GREATER_THAN = ">"; // public static final String RIGHT_ANGLE_BRACKET = GREATER_THAN; // public static final String LEFT_ANGLE_BRACKET = LESS_THAN; // public static final String IMG_PNG = "png"; // public static final String PLUS = "+"; // public static final String MINUS = "-"; // public static final String EQUAL = "="; // public static final String EXCLAMATION = "!"; // public static final String DOUBLE_QUOTE = "\""; // public static final String SINGLE_QUOTE = "'"; // public static String SLASH = "/"; // public static String BACKSLASH = "\\"; // public static String QUESTION_MARK = "?"; // public static final String TAB = "\t"; // // }
import org.lttpp.eemory.util.ConstantsUtil;
public static final String OAUTH_VERIFIER = "oauth_verifier"; public static final String CALLBACK_HTML_META = "text/html;charset=utf-8"; public static final String OAUTH_EVERNOTE_TRADEMARK = "icons/evernote_32x32.png"; public static final String OAUTH_EVERNOTE_TRADEMARK_DISCONNECTED = "icons/evernote_32x32.png"; public static final String OAUTH_CALLBACK_HTML = "html/callback.html"; public static final String OAUTH_CALLBACK_ERR_HTML = "html/callback_err.html"; public static final String OAUTH_NOTTARGET_HTML = "html/images/default.html"; public static final String OAUTH_RESOURCE_BASE = "html/images"; public static final String OAUTH_DEFAULT_HTML = "default.html"; // Store type public static final String ENOBJECT_TYPE_NORMAL = "normal"; public static final String ENOBJECT_TYPE_LINKED = "linked"; public static final String ENOBJECT_TYPE_BUSINESS = "business"; // mime-util public static final String MimeDetector = "eu.medsea.mimeutil.detector.MagicMimeMimeDetector"; // Plug-in public static final String PLUGIN_DEBUG_MODE = "org.lttpp.eemory.debug"; public static final String PLUGIN_RUN_ON_SANDBOX = "com.evernote.sandbox"; // Button properties public static final String Plugin_OAuth_AuthExpired_ReAuth = "Plugin_OAuth_AuthExpired_ReAuth"; public static final String Plugin_OAuth_NotNow = "Plugin_OAuth_NotNow"; public static final String Plugin_OAuth_Copy = "Plugin_OAuth_Copy"; public static final String Plugin_OAuth_Cancel = "Plugin_OAuth_Cancel"; // Others public static final String FileNamePartSimpleDateFormat = "yyyy-MM-dd'T'HH-mm-ss-";
// Path: org.lttpp.eemory/src/org/lttpp/eemory/util/ConstantsUtil.java // public class ConstantsUtil { // // public static final String COMMA = ","; // public static final String COLON = ":"; // public static final String SEMICOLON = ";"; // public static final String DOT = "."; // public static final String POUND = "#"; // public static final String STAR = "*"; // public static final String MD5 = "MD5"; // public static final String LEFT_PARENTHESIS = "("; // public static final String RIGHT_PARENTHESIS = ")"; // public static final String LEFT_BRACE = "{"; // public static final String RIGHT_BRACE = "}"; // public static final String LESS_THAN = "<"; // public static final String GREATER_THAN = ">"; // public static final String RIGHT_ANGLE_BRACKET = GREATER_THAN; // public static final String LEFT_ANGLE_BRACKET = LESS_THAN; // public static final String IMG_PNG = "png"; // public static final String PLUS = "+"; // public static final String MINUS = "-"; // public static final String EQUAL = "="; // public static final String EXCLAMATION = "!"; // public static final String DOUBLE_QUOTE = "\""; // public static final String SINGLE_QUOTE = "'"; // public static String SLASH = "/"; // public static String BACKSLASH = "\\"; // public static String QUESTION_MARK = "?"; // public static final String TAB = "\t"; // // } // Path: org.lttpp.eemory/src/org/lttpp/eemory/Constants.java import org.lttpp.eemory.util.ConstantsUtil; public static final String OAUTH_VERIFIER = "oauth_verifier"; public static final String CALLBACK_HTML_META = "text/html;charset=utf-8"; public static final String OAUTH_EVERNOTE_TRADEMARK = "icons/evernote_32x32.png"; public static final String OAUTH_EVERNOTE_TRADEMARK_DISCONNECTED = "icons/evernote_32x32.png"; public static final String OAUTH_CALLBACK_HTML = "html/callback.html"; public static final String OAUTH_CALLBACK_ERR_HTML = "html/callback_err.html"; public static final String OAUTH_NOTTARGET_HTML = "html/images/default.html"; public static final String OAUTH_RESOURCE_BASE = "html/images"; public static final String OAUTH_DEFAULT_HTML = "default.html"; // Store type public static final String ENOBJECT_TYPE_NORMAL = "normal"; public static final String ENOBJECT_TYPE_LINKED = "linked"; public static final String ENOBJECT_TYPE_BUSINESS = "business"; // mime-util public static final String MimeDetector = "eu.medsea.mimeutil.detector.MagicMimeMimeDetector"; // Plug-in public static final String PLUGIN_DEBUG_MODE = "org.lttpp.eemory.debug"; public static final String PLUGIN_RUN_ON_SANDBOX = "com.evernote.sandbox"; // Button properties public static final String Plugin_OAuth_AuthExpired_ReAuth = "Plugin_OAuth_AuthExpired_ReAuth"; public static final String Plugin_OAuth_NotNow = "Plugin_OAuth_NotNow"; public static final String Plugin_OAuth_Copy = "Plugin_OAuth_Copy"; public static final String Plugin_OAuth_Cancel = "Plugin_OAuth_Cancel"; // Others public static final String FileNamePartSimpleDateFormat = "yyyy-MM-dd'T'HH-mm-ss-";
public static final String TAGS_SEPARATOR = ConstantsUtil.COMMA;
LTTPP/Eemory
org.lttpp.eemory/src/org/lttpp/eemory/ui/GeomPoint.java
// Path: org.lttpp.eemory/src/org/lttpp/eemory/util/ConstantsUtil.java // public class ConstantsUtil { // // public static final String COMMA = ","; // public static final String COLON = ":"; // public static final String SEMICOLON = ";"; // public static final String DOT = "."; // public static final String POUND = "#"; // public static final String STAR = "*"; // public static final String MD5 = "MD5"; // public static final String LEFT_PARENTHESIS = "("; // public static final String RIGHT_PARENTHESIS = ")"; // public static final String LEFT_BRACE = "{"; // public static final String RIGHT_BRACE = "}"; // public static final String LESS_THAN = "<"; // public static final String GREATER_THAN = ">"; // public static final String RIGHT_ANGLE_BRACKET = GREATER_THAN; // public static final String LEFT_ANGLE_BRACKET = LESS_THAN; // public static final String IMG_PNG = "png"; // public static final String PLUS = "+"; // public static final String MINUS = "-"; // public static final String EQUAL = "="; // public static final String EXCLAMATION = "!"; // public static final String DOUBLE_QUOTE = "\""; // public static final String SINGLE_QUOTE = "'"; // public static String SLASH = "/"; // public static String BACKSLASH = "\\"; // public static String QUESTION_MARK = "?"; // public static final String TAB = "\t"; // // }
import java.awt.Toolkit; import org.lttpp.eemory.util.ConstantsUtil;
return getX() * getX() + getY() * getY(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof GeomPoint)) { return false; } GeomPoint p = (GeomPoint) obj; if (x == p.x && y == p.y) { return true; } return false; } @Override public Object clone() { GeomPoint o = null; try { o = (GeomPoint) super.clone(); } catch (CloneNotSupportedException e) { } return o; } @Override public String toString() {
// Path: org.lttpp.eemory/src/org/lttpp/eemory/util/ConstantsUtil.java // public class ConstantsUtil { // // public static final String COMMA = ","; // public static final String COLON = ":"; // public static final String SEMICOLON = ";"; // public static final String DOT = "."; // public static final String POUND = "#"; // public static final String STAR = "*"; // public static final String MD5 = "MD5"; // public static final String LEFT_PARENTHESIS = "("; // public static final String RIGHT_PARENTHESIS = ")"; // public static final String LEFT_BRACE = "{"; // public static final String RIGHT_BRACE = "}"; // public static final String LESS_THAN = "<"; // public static final String GREATER_THAN = ">"; // public static final String RIGHT_ANGLE_BRACKET = GREATER_THAN; // public static final String LEFT_ANGLE_BRACKET = LESS_THAN; // public static final String IMG_PNG = "png"; // public static final String PLUS = "+"; // public static final String MINUS = "-"; // public static final String EQUAL = "="; // public static final String EXCLAMATION = "!"; // public static final String DOUBLE_QUOTE = "\""; // public static final String SINGLE_QUOTE = "'"; // public static String SLASH = "/"; // public static String BACKSLASH = "\\"; // public static String QUESTION_MARK = "?"; // public static final String TAB = "\t"; // // } // Path: org.lttpp.eemory/src/org/lttpp/eemory/ui/GeomPoint.java import java.awt.Toolkit; import org.lttpp.eemory.util.ConstantsUtil; return getX() * getX() + getY() * getY(); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof GeomPoint)) { return false; } GeomPoint p = (GeomPoint) obj; if (x == p.x && y == p.y) { return true; } return false; } @Override public Object clone() { GeomPoint o = null; try { o = (GeomPoint) super.clone(); } catch (CloneNotSupportedException e) { } return o; } @Override public String toString() {
return ConstantsUtil.LEFT_PARENTHESIS + getX() + ConstantsUtil.COMMA + getY() + ConstantsUtil.RIGHT_PARENTHESIS;
Duraiamuthan/VPN-Android
OpenVPN-Client/main/src/main/java/com/openvpn/Durai/core/NetworkSpace.java
// Path: OpenVPN-Client/main/build/generated/source/buildConfig/normal/debug/com/openvpn/Durai/BuildConfig.java // public final class BuildConfig { // public static final boolean DEBUG = Boolean.parseBoolean("true"); // public static final String APPLICATION_ID = "com.openvpn.Durai"; // public static final String BUILD_TYPE = "debug"; // public static final String FLAVOR = "normal"; // public static final int VERSION_CODE = 1; // public static final String VERSION_NAME = ""; // }
import android.os.Build; import android.text.TextUtils; import junit.framework.Assert; import org.jetbrains.annotations.NotNull; import java.math.BigInteger; import java.net.Inet6Address; import java.util.*; import com.openvpn.Durai.BuildConfig;
for (int i = 0; i < numBits; i++) { if (one) numAddress = numAddress.setBit(i); else numAddress = numAddress.clearBit(i); } return numAddress; } @Override public String toString() { //String in = included ? "+" : "-"; if (isV4) return String.format(Locale.US,"%s/%d", getIPv4Address(), networkMask); else return String.format(Locale.US, "%s/%d", getIPv6Address(), networkMask); } ipAddress(BigInteger baseAddress, int mask, boolean included, boolean isV4) { this.netAddress = baseAddress; this.networkMask = mask; this.included = included; this.isV4 = isV4; } public ipAddress[] split() { ipAddress firstHalf = new ipAddress(getFirstAddress(), networkMask + 1, included, isV4); ipAddress secondHalf = new ipAddress(firstHalf.getLastAddress().add(BigInteger.ONE), networkMask + 1, included, isV4);
// Path: OpenVPN-Client/main/build/generated/source/buildConfig/normal/debug/com/openvpn/Durai/BuildConfig.java // public final class BuildConfig { // public static final boolean DEBUG = Boolean.parseBoolean("true"); // public static final String APPLICATION_ID = "com.openvpn.Durai"; // public static final String BUILD_TYPE = "debug"; // public static final String FLAVOR = "normal"; // public static final int VERSION_CODE = 1; // public static final String VERSION_NAME = ""; // } // Path: OpenVPN-Client/main/src/main/java/com/openvpn/Durai/core/NetworkSpace.java import android.os.Build; import android.text.TextUtils; import junit.framework.Assert; import org.jetbrains.annotations.NotNull; import java.math.BigInteger; import java.net.Inet6Address; import java.util.*; import com.openvpn.Durai.BuildConfig; for (int i = 0; i < numBits; i++) { if (one) numAddress = numAddress.setBit(i); else numAddress = numAddress.clearBit(i); } return numAddress; } @Override public String toString() { //String in = included ? "+" : "-"; if (isV4) return String.format(Locale.US,"%s/%d", getIPv4Address(), networkMask); else return String.format(Locale.US, "%s/%d", getIPv6Address(), networkMask); } ipAddress(BigInteger baseAddress, int mask, boolean included, boolean isV4) { this.netAddress = baseAddress; this.networkMask = mask; this.included = included; this.isV4 = isV4; } public ipAddress[] split() { ipAddress firstHalf = new ipAddress(getFirstAddress(), networkMask + 1, included, isV4); ipAddress secondHalf = new ipAddress(firstHalf.getLastAddress().add(BigInteger.ONE), networkMask + 1, included, isV4);
if (BuildConfig.DEBUG) Assert.assertTrue(secondHalf.getLastAddress().equals(getLastAddress()));
Duraiamuthan/VPN-Android
OpenVPN-Client/main/src/main/java/com/openvpn/Durai/core/OpenVPNApplication.java
// Path: OpenVPN-Client/main/build/generated/source/buildConfig/normal/debug/com/openvpn/Durai/BuildConfig.java // public final class BuildConfig { // public static final boolean DEBUG = Boolean.parseBoolean("true"); // public static final String APPLICATION_ID = "com.openvpn.Durai"; // public static final String BUILD_TYPE = "debug"; // public static final String FLAVOR = "normal"; // public static final int VERSION_CODE = 1; // public static final String VERSION_NAME = ""; // }
import android.app.Application; import com.openvpn.Durai.BuildConfig;
package com.openvpn.Durai.core; public class OpenVPNApplication extends Application { @Override public void onCreate() { super.onCreate(); PRNGFixes.apply();
// Path: OpenVPN-Client/main/build/generated/source/buildConfig/normal/debug/com/openvpn/Durai/BuildConfig.java // public final class BuildConfig { // public static final boolean DEBUG = Boolean.parseBoolean("true"); // public static final String APPLICATION_ID = "com.openvpn.Durai"; // public static final String BUILD_TYPE = "debug"; // public static final String FLAVOR = "normal"; // public static final int VERSION_CODE = 1; // public static final String VERSION_NAME = ""; // } // Path: OpenVPN-Client/main/src/main/java/com/openvpn/Durai/core/OpenVPNApplication.java import android.app.Application; import com.openvpn.Durai.BuildConfig; package com.openvpn.Durai.core; public class OpenVPNApplication extends Application { @Override public void onCreate() { super.onCreate(); PRNGFixes.apply();
if (BuildConfig.DEBUG) {
Duraiamuthan/VPN-Android
OpenVPN-Client/main/src/main/java/com/openvpn/Durai/core/DeviceStateReceiver.java
// Path: OpenVPN-Client/main/src/main/java/com/openvpn/Durai/core/OpenVPNManagement.java // enum pauseReason { // noNetwork, // userPause, // screenOff // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.NetworkInfo.State; import android.preference.PreferenceManager; import java.util.LinkedList; import static com.openvpn.Durai.core.OpenVPNManagement.pauseReason;
} else if (networkInfo == null) { // Not connected, stop Durai, set last connected network to no network lastNetwork = -1; if (sendusr1) { network = connectState.DISCONNECTED; // Set screen state to be disconnected if disconnect pending if (screen == connectState.PENDINGDISCONNECT) screen = connectState.DISCONNECTED; mManagement.pause(getPauseReason()); } } if (!netstatestring.equals(lastStateMsg)) VpnStatus.logInfo(com.openvpn.Durai.R.string.netstatus, netstatestring); lastStateMsg = netstatestring; } public boolean isUserPaused() { return userpause == connectState.DISCONNECTED; } private boolean shouldBeConnected() { return (screen == connectState.SHOULDBECONNECTED && userpause == connectState.SHOULDBECONNECTED && network == connectState.SHOULDBECONNECTED); }
// Path: OpenVPN-Client/main/src/main/java/com/openvpn/Durai/core/OpenVPNManagement.java // enum pauseReason { // noNetwork, // userPause, // screenOff // } // Path: OpenVPN-Client/main/src/main/java/com/openvpn/Durai/core/DeviceStateReceiver.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.NetworkInfo.State; import android.preference.PreferenceManager; import java.util.LinkedList; import static com.openvpn.Durai.core.OpenVPNManagement.pauseReason; } else if (networkInfo == null) { // Not connected, stop Durai, set last connected network to no network lastNetwork = -1; if (sendusr1) { network = connectState.DISCONNECTED; // Set screen state to be disconnected if disconnect pending if (screen == connectState.PENDINGDISCONNECT) screen = connectState.DISCONNECTED; mManagement.pause(getPauseReason()); } } if (!netstatestring.equals(lastStateMsg)) VpnStatus.logInfo(com.openvpn.Durai.R.string.netstatus, netstatestring); lastStateMsg = netstatestring; } public boolean isUserPaused() { return userpause == connectState.DISCONNECTED; } private boolean shouldBeConnected() { return (screen == connectState.SHOULDBECONNECTED && userpause == connectState.SHOULDBECONNECTED && network == connectState.SHOULDBECONNECTED); }
private pauseReason getPauseReason() {
robzenn92/peersimTutorial
src/main/java/epto/EpTODissemination.java
// Path: src/main/java/epto/utils/Ball.java // public class Ball extends HashMap<UUID, Event> { // // } // // Path: src/main/java/epto/utils/Event.java // public class Event implements Comparable<Event>{ // // public UUID id; // // public LogicalClock timestamp; // // public int ttl; // // public long sourceId; // // public Event() { // id = UUID.randomUUID(); // } // // public int compareTo(Event o) { // int comparisionLC = timestamp.compareTo(o.timestamp); // return (comparisionLC != 0)? comparisionLC : (int)(sourceId - o.sourceId); // } // // @Override // public String toString() { // return "{timestamp=" + timestamp + ", ttl=" + ttl + ", sourceId=" + sourceId + "}"; // } // } // // Path: src/main/java/epto/utils/Message.java // public class Message { // // public final static int PREBROADCAST = 0; // public final static int BROADCAST = 1; // public final static int DELIVER = 2; // public final static int DISSEMINATION = 3; // public final static int ORDER = 4; // // private int type; // private Object content; // // private Node source; // // private Node destination; // // public Message(int type, Object content) { // this.type = type; // this.content = content; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public Object getContent() { // return content; // } // // public void setContent(Object content) { // this.content = content; // } // // // public Node getSource() { // // return source; // // } // // // // public void setSource(Node source) { // // this.source = source; // // } // // // // public Node getDestination() { // // return destination; // // } // // // // public void setDestination(Node destination) { // // this.destination = destination; // // } // } // // Path: src/main/java/epto/utils/Utils.java // public class Utils { // // public static final int DEFAULT_FANOUT = 5; // // public static final int DEFAULT_TTL = 2; // } // // Path: src/main/java/pss/IPeerSamplingService.java // public interface IPeerSamplingService { // // public Node selectNeighbor(); // // public List<Node> selectNeighbors(int k); // // public int degree(); // // public void myTurn(Node node, int pid); // // } // // Path: src/main/java/time/LogicalClock.java // public class LogicalClock implements Comparable<LogicalClock> { // // private long nodeId; // private int eventId; // // public LogicalClock(long nodeId) { // this.nodeId = nodeId; // this.eventId = 0; // } // // public LogicalClock(long nodeId, int eventId) { // this(nodeId); // this.eventId = eventId; // } // // public void increment() { // this.eventId++; // } // // public long getNodeId() { // return nodeId; // } // // public void setNodeId(long nodeId) { // this.nodeId = nodeId; // } // // public int getEventId() { // return eventId; // } // // public void setEventId(int eventId) { // this.eventId = eventId; // } // // public int compareTo(LogicalClock o) { // return (nodeId == o.nodeId)? eventId - o.eventId : (int) nodeId - (int) o.nodeId; // } // // @Override // public String toString() { // return "{nodeId=" + nodeId + ", eventId=" + eventId + "}"; // } // // @Override // public LogicalClock clone() throws CloneNotSupportedException { // return new LogicalClock(nodeId, eventId); // } // }
import epto.utils.Ball; import epto.utils.Event; import epto.utils.Message; import epto.utils.Utils; import peersim.cdsim.CDProtocol; import peersim.config.Configuration; import peersim.config.FastConfig; import peersim.core.Node; import peersim.edsim.EDProtocol; import peersim.transport.Transport; import pss.IPeerSamplingService; import time.LogicalClock; import java.util.List;
package epto; /** * The EpTO dissemination component * * The algorithm assumes the existence of a peer sampling service (PSS) responsible for keeping p’s view * up-to-date with a random stream of at least K deemed correct processes allowing a fanout of size K. * TTL (time to live) holds the number of rounds for which each event needs to be relayed during its dissemination. * The nextBall set collects the events to be sent in the next round by process p. * The dissemination component consists of three procedures executed atomically: the event broadcast primitive, * the event receive callback and the periodic relaying task. */ public class EpTODissemination implements CDProtocol, EDProtocol, EpTOBroadcaster { // ================================= // Configuration Parameters // ================================= /** * Config parameter name for the fanout K: number of deemed correct processes * @config */ private static final String PAR_FANOUT = "fanout"; /** * Config parameter name for the TTL (time to live). * It is a constant holding the number of rounds for which each event needs to be relayed during its dissemination. * @config */ private static final String PAR_TTL = "ttl"; // ================================= // Parameters // ================================= /** * The id of this protocol in the protocol array */ public static int PID = 0; /** * The number of deemed correct processes */ private final int K; /** * The number of rounds for which each event needs to be relayed during its dissemination */ private final int TTL; /** * The nextBall set collects the events to be sent in the next round by process p * It relies on an HashMap<UUID, Event> */
// Path: src/main/java/epto/utils/Ball.java // public class Ball extends HashMap<UUID, Event> { // // } // // Path: src/main/java/epto/utils/Event.java // public class Event implements Comparable<Event>{ // // public UUID id; // // public LogicalClock timestamp; // // public int ttl; // // public long sourceId; // // public Event() { // id = UUID.randomUUID(); // } // // public int compareTo(Event o) { // int comparisionLC = timestamp.compareTo(o.timestamp); // return (comparisionLC != 0)? comparisionLC : (int)(sourceId - o.sourceId); // } // // @Override // public String toString() { // return "{timestamp=" + timestamp + ", ttl=" + ttl + ", sourceId=" + sourceId + "}"; // } // } // // Path: src/main/java/epto/utils/Message.java // public class Message { // // public final static int PREBROADCAST = 0; // public final static int BROADCAST = 1; // public final static int DELIVER = 2; // public final static int DISSEMINATION = 3; // public final static int ORDER = 4; // // private int type; // private Object content; // // private Node source; // // private Node destination; // // public Message(int type, Object content) { // this.type = type; // this.content = content; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public Object getContent() { // return content; // } // // public void setContent(Object content) { // this.content = content; // } // // // public Node getSource() { // // return source; // // } // // // // public void setSource(Node source) { // // this.source = source; // // } // // // // public Node getDestination() { // // return destination; // // } // // // // public void setDestination(Node destination) { // // this.destination = destination; // // } // } // // Path: src/main/java/epto/utils/Utils.java // public class Utils { // // public static final int DEFAULT_FANOUT = 5; // // public static final int DEFAULT_TTL = 2; // } // // Path: src/main/java/pss/IPeerSamplingService.java // public interface IPeerSamplingService { // // public Node selectNeighbor(); // // public List<Node> selectNeighbors(int k); // // public int degree(); // // public void myTurn(Node node, int pid); // // } // // Path: src/main/java/time/LogicalClock.java // public class LogicalClock implements Comparable<LogicalClock> { // // private long nodeId; // private int eventId; // // public LogicalClock(long nodeId) { // this.nodeId = nodeId; // this.eventId = 0; // } // // public LogicalClock(long nodeId, int eventId) { // this(nodeId); // this.eventId = eventId; // } // // public void increment() { // this.eventId++; // } // // public long getNodeId() { // return nodeId; // } // // public void setNodeId(long nodeId) { // this.nodeId = nodeId; // } // // public int getEventId() { // return eventId; // } // // public void setEventId(int eventId) { // this.eventId = eventId; // } // // public int compareTo(LogicalClock o) { // return (nodeId == o.nodeId)? eventId - o.eventId : (int) nodeId - (int) o.nodeId; // } // // @Override // public String toString() { // return "{nodeId=" + nodeId + ", eventId=" + eventId + "}"; // } // // @Override // public LogicalClock clone() throws CloneNotSupportedException { // return new LogicalClock(nodeId, eventId); // } // } // Path: src/main/java/epto/EpTODissemination.java import epto.utils.Ball; import epto.utils.Event; import epto.utils.Message; import epto.utils.Utils; import peersim.cdsim.CDProtocol; import peersim.config.Configuration; import peersim.config.FastConfig; import peersim.core.Node; import peersim.edsim.EDProtocol; import peersim.transport.Transport; import pss.IPeerSamplingService; import time.LogicalClock; import java.util.List; package epto; /** * The EpTO dissemination component * * The algorithm assumes the existence of a peer sampling service (PSS) responsible for keeping p’s view * up-to-date with a random stream of at least K deemed correct processes allowing a fanout of size K. * TTL (time to live) holds the number of rounds for which each event needs to be relayed during its dissemination. * The nextBall set collects the events to be sent in the next round by process p. * The dissemination component consists of three procedures executed atomically: the event broadcast primitive, * the event receive callback and the periodic relaying task. */ public class EpTODissemination implements CDProtocol, EDProtocol, EpTOBroadcaster { // ================================= // Configuration Parameters // ================================= /** * Config parameter name for the fanout K: number of deemed correct processes * @config */ private static final String PAR_FANOUT = "fanout"; /** * Config parameter name for the TTL (time to live). * It is a constant holding the number of rounds for which each event needs to be relayed during its dissemination. * @config */ private static final String PAR_TTL = "ttl"; // ================================= // Parameters // ================================= /** * The id of this protocol in the protocol array */ public static int PID = 0; /** * The number of deemed correct processes */ private final int K; /** * The number of rounds for which each event needs to be relayed during its dissemination */ private final int TTL; /** * The nextBall set collects the events to be sent in the next round by process p * It relies on an HashMap<UUID, Event> */
private Ball nextBall = new Ball();
robzenn92/peersimTutorial
src/main/java/epto/EpTODissemination.java
// Path: src/main/java/epto/utils/Ball.java // public class Ball extends HashMap<UUID, Event> { // // } // // Path: src/main/java/epto/utils/Event.java // public class Event implements Comparable<Event>{ // // public UUID id; // // public LogicalClock timestamp; // // public int ttl; // // public long sourceId; // // public Event() { // id = UUID.randomUUID(); // } // // public int compareTo(Event o) { // int comparisionLC = timestamp.compareTo(o.timestamp); // return (comparisionLC != 0)? comparisionLC : (int)(sourceId - o.sourceId); // } // // @Override // public String toString() { // return "{timestamp=" + timestamp + ", ttl=" + ttl + ", sourceId=" + sourceId + "}"; // } // } // // Path: src/main/java/epto/utils/Message.java // public class Message { // // public final static int PREBROADCAST = 0; // public final static int BROADCAST = 1; // public final static int DELIVER = 2; // public final static int DISSEMINATION = 3; // public final static int ORDER = 4; // // private int type; // private Object content; // // private Node source; // // private Node destination; // // public Message(int type, Object content) { // this.type = type; // this.content = content; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public Object getContent() { // return content; // } // // public void setContent(Object content) { // this.content = content; // } // // // public Node getSource() { // // return source; // // } // // // // public void setSource(Node source) { // // this.source = source; // // } // // // // public Node getDestination() { // // return destination; // // } // // // // public void setDestination(Node destination) { // // this.destination = destination; // // } // } // // Path: src/main/java/epto/utils/Utils.java // public class Utils { // // public static final int DEFAULT_FANOUT = 5; // // public static final int DEFAULT_TTL = 2; // } // // Path: src/main/java/pss/IPeerSamplingService.java // public interface IPeerSamplingService { // // public Node selectNeighbor(); // // public List<Node> selectNeighbors(int k); // // public int degree(); // // public void myTurn(Node node, int pid); // // } // // Path: src/main/java/time/LogicalClock.java // public class LogicalClock implements Comparable<LogicalClock> { // // private long nodeId; // private int eventId; // // public LogicalClock(long nodeId) { // this.nodeId = nodeId; // this.eventId = 0; // } // // public LogicalClock(long nodeId, int eventId) { // this(nodeId); // this.eventId = eventId; // } // // public void increment() { // this.eventId++; // } // // public long getNodeId() { // return nodeId; // } // // public void setNodeId(long nodeId) { // this.nodeId = nodeId; // } // // public int getEventId() { // return eventId; // } // // public void setEventId(int eventId) { // this.eventId = eventId; // } // // public int compareTo(LogicalClock o) { // return (nodeId == o.nodeId)? eventId - o.eventId : (int) nodeId - (int) o.nodeId; // } // // @Override // public String toString() { // return "{nodeId=" + nodeId + ", eventId=" + eventId + "}"; // } // // @Override // public LogicalClock clone() throws CloneNotSupportedException { // return new LogicalClock(nodeId, eventId); // } // }
import epto.utils.Ball; import epto.utils.Event; import epto.utils.Message; import epto.utils.Utils; import peersim.cdsim.CDProtocol; import peersim.config.Configuration; import peersim.config.FastConfig; import peersim.core.Node; import peersim.edsim.EDProtocol; import peersim.transport.Transport; import pss.IPeerSamplingService; import time.LogicalClock; import java.util.List;
package epto; /** * The EpTO dissemination component * * The algorithm assumes the existence of a peer sampling service (PSS) responsible for keeping p’s view * up-to-date with a random stream of at least K deemed correct processes allowing a fanout of size K. * TTL (time to live) holds the number of rounds for which each event needs to be relayed during its dissemination. * The nextBall set collects the events to be sent in the next round by process p. * The dissemination component consists of three procedures executed atomically: the event broadcast primitive, * the event receive callback and the periodic relaying task. */ public class EpTODissemination implements CDProtocol, EDProtocol, EpTOBroadcaster { // ================================= // Configuration Parameters // ================================= /** * Config parameter name for the fanout K: number of deemed correct processes * @config */ private static final String PAR_FANOUT = "fanout"; /** * Config parameter name for the TTL (time to live). * It is a constant holding the number of rounds for which each event needs to be relayed during its dissemination. * @config */ private static final String PAR_TTL = "ttl"; // ================================= // Parameters // ================================= /** * The id of this protocol in the protocol array */ public static int PID = 0; /** * The number of deemed correct processes */ private final int K; /** * The number of rounds for which each event needs to be relayed during its dissemination */ private final int TTL; /** * The nextBall set collects the events to be sent in the next round by process p * It relies on an HashMap<UUID, Event> */ private Ball nextBall = new Ball(); /** * Last updated LogicalClock */
// Path: src/main/java/epto/utils/Ball.java // public class Ball extends HashMap<UUID, Event> { // // } // // Path: src/main/java/epto/utils/Event.java // public class Event implements Comparable<Event>{ // // public UUID id; // // public LogicalClock timestamp; // // public int ttl; // // public long sourceId; // // public Event() { // id = UUID.randomUUID(); // } // // public int compareTo(Event o) { // int comparisionLC = timestamp.compareTo(o.timestamp); // return (comparisionLC != 0)? comparisionLC : (int)(sourceId - o.sourceId); // } // // @Override // public String toString() { // return "{timestamp=" + timestamp + ", ttl=" + ttl + ", sourceId=" + sourceId + "}"; // } // } // // Path: src/main/java/epto/utils/Message.java // public class Message { // // public final static int PREBROADCAST = 0; // public final static int BROADCAST = 1; // public final static int DELIVER = 2; // public final static int DISSEMINATION = 3; // public final static int ORDER = 4; // // private int type; // private Object content; // // private Node source; // // private Node destination; // // public Message(int type, Object content) { // this.type = type; // this.content = content; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public Object getContent() { // return content; // } // // public void setContent(Object content) { // this.content = content; // } // // // public Node getSource() { // // return source; // // } // // // // public void setSource(Node source) { // // this.source = source; // // } // // // // public Node getDestination() { // // return destination; // // } // // // // public void setDestination(Node destination) { // // this.destination = destination; // // } // } // // Path: src/main/java/epto/utils/Utils.java // public class Utils { // // public static final int DEFAULT_FANOUT = 5; // // public static final int DEFAULT_TTL = 2; // } // // Path: src/main/java/pss/IPeerSamplingService.java // public interface IPeerSamplingService { // // public Node selectNeighbor(); // // public List<Node> selectNeighbors(int k); // // public int degree(); // // public void myTurn(Node node, int pid); // // } // // Path: src/main/java/time/LogicalClock.java // public class LogicalClock implements Comparable<LogicalClock> { // // private long nodeId; // private int eventId; // // public LogicalClock(long nodeId) { // this.nodeId = nodeId; // this.eventId = 0; // } // // public LogicalClock(long nodeId, int eventId) { // this(nodeId); // this.eventId = eventId; // } // // public void increment() { // this.eventId++; // } // // public long getNodeId() { // return nodeId; // } // // public void setNodeId(long nodeId) { // this.nodeId = nodeId; // } // // public int getEventId() { // return eventId; // } // // public void setEventId(int eventId) { // this.eventId = eventId; // } // // public int compareTo(LogicalClock o) { // return (nodeId == o.nodeId)? eventId - o.eventId : (int) nodeId - (int) o.nodeId; // } // // @Override // public String toString() { // return "{nodeId=" + nodeId + ", eventId=" + eventId + "}"; // } // // @Override // public LogicalClock clone() throws CloneNotSupportedException { // return new LogicalClock(nodeId, eventId); // } // } // Path: src/main/java/epto/EpTODissemination.java import epto.utils.Ball; import epto.utils.Event; import epto.utils.Message; import epto.utils.Utils; import peersim.cdsim.CDProtocol; import peersim.config.Configuration; import peersim.config.FastConfig; import peersim.core.Node; import peersim.edsim.EDProtocol; import peersim.transport.Transport; import pss.IPeerSamplingService; import time.LogicalClock; import java.util.List; package epto; /** * The EpTO dissemination component * * The algorithm assumes the existence of a peer sampling service (PSS) responsible for keeping p’s view * up-to-date with a random stream of at least K deemed correct processes allowing a fanout of size K. * TTL (time to live) holds the number of rounds for which each event needs to be relayed during its dissemination. * The nextBall set collects the events to be sent in the next round by process p. * The dissemination component consists of three procedures executed atomically: the event broadcast primitive, * the event receive callback and the periodic relaying task. */ public class EpTODissemination implements CDProtocol, EDProtocol, EpTOBroadcaster { // ================================= // Configuration Parameters // ================================= /** * Config parameter name for the fanout K: number of deemed correct processes * @config */ private static final String PAR_FANOUT = "fanout"; /** * Config parameter name for the TTL (time to live). * It is a constant holding the number of rounds for which each event needs to be relayed during its dissemination. * @config */ private static final String PAR_TTL = "ttl"; // ================================= // Parameters // ================================= /** * The id of this protocol in the protocol array */ public static int PID = 0; /** * The number of deemed correct processes */ private final int K; /** * The number of rounds for which each event needs to be relayed during its dissemination */ private final int TTL; /** * The nextBall set collects the events to be sent in the next round by process p * It relies on an HashMap<UUID, Event> */ private Ball nextBall = new Ball(); /** * Last updated LogicalClock */
private LogicalClock lastLogicalClock;
robzenn92/peersimTutorial
src/main/java/epto/EpTODissemination.java
// Path: src/main/java/epto/utils/Ball.java // public class Ball extends HashMap<UUID, Event> { // // } // // Path: src/main/java/epto/utils/Event.java // public class Event implements Comparable<Event>{ // // public UUID id; // // public LogicalClock timestamp; // // public int ttl; // // public long sourceId; // // public Event() { // id = UUID.randomUUID(); // } // // public int compareTo(Event o) { // int comparisionLC = timestamp.compareTo(o.timestamp); // return (comparisionLC != 0)? comparisionLC : (int)(sourceId - o.sourceId); // } // // @Override // public String toString() { // return "{timestamp=" + timestamp + ", ttl=" + ttl + ", sourceId=" + sourceId + "}"; // } // } // // Path: src/main/java/epto/utils/Message.java // public class Message { // // public final static int PREBROADCAST = 0; // public final static int BROADCAST = 1; // public final static int DELIVER = 2; // public final static int DISSEMINATION = 3; // public final static int ORDER = 4; // // private int type; // private Object content; // // private Node source; // // private Node destination; // // public Message(int type, Object content) { // this.type = type; // this.content = content; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public Object getContent() { // return content; // } // // public void setContent(Object content) { // this.content = content; // } // // // public Node getSource() { // // return source; // // } // // // // public void setSource(Node source) { // // this.source = source; // // } // // // // public Node getDestination() { // // return destination; // // } // // // // public void setDestination(Node destination) { // // this.destination = destination; // // } // } // // Path: src/main/java/epto/utils/Utils.java // public class Utils { // // public static final int DEFAULT_FANOUT = 5; // // public static final int DEFAULT_TTL = 2; // } // // Path: src/main/java/pss/IPeerSamplingService.java // public interface IPeerSamplingService { // // public Node selectNeighbor(); // // public List<Node> selectNeighbors(int k); // // public int degree(); // // public void myTurn(Node node, int pid); // // } // // Path: src/main/java/time/LogicalClock.java // public class LogicalClock implements Comparable<LogicalClock> { // // private long nodeId; // private int eventId; // // public LogicalClock(long nodeId) { // this.nodeId = nodeId; // this.eventId = 0; // } // // public LogicalClock(long nodeId, int eventId) { // this(nodeId); // this.eventId = eventId; // } // // public void increment() { // this.eventId++; // } // // public long getNodeId() { // return nodeId; // } // // public void setNodeId(long nodeId) { // this.nodeId = nodeId; // } // // public int getEventId() { // return eventId; // } // // public void setEventId(int eventId) { // this.eventId = eventId; // } // // public int compareTo(LogicalClock o) { // return (nodeId == o.nodeId)? eventId - o.eventId : (int) nodeId - (int) o.nodeId; // } // // @Override // public String toString() { // return "{nodeId=" + nodeId + ", eventId=" + eventId + "}"; // } // // @Override // public LogicalClock clone() throws CloneNotSupportedException { // return new LogicalClock(nodeId, eventId); // } // }
import epto.utils.Ball; import epto.utils.Event; import epto.utils.Message; import epto.utils.Utils; import peersim.cdsim.CDProtocol; import peersim.config.Configuration; import peersim.config.FastConfig; import peersim.core.Node; import peersim.edsim.EDProtocol; import peersim.transport.Transport; import pss.IPeerSamplingService; import time.LogicalClock; import java.util.List;
package epto; /** * The EpTO dissemination component * * The algorithm assumes the existence of a peer sampling service (PSS) responsible for keeping p’s view * up-to-date with a random stream of at least K deemed correct processes allowing a fanout of size K. * TTL (time to live) holds the number of rounds for which each event needs to be relayed during its dissemination. * The nextBall set collects the events to be sent in the next round by process p. * The dissemination component consists of three procedures executed atomically: the event broadcast primitive, * the event receive callback and the periodic relaying task. */ public class EpTODissemination implements CDProtocol, EDProtocol, EpTOBroadcaster { // ================================= // Configuration Parameters // ================================= /** * Config parameter name for the fanout K: number of deemed correct processes * @config */ private static final String PAR_FANOUT = "fanout"; /** * Config parameter name for the TTL (time to live). * It is a constant holding the number of rounds for which each event needs to be relayed during its dissemination. * @config */ private static final String PAR_TTL = "ttl"; // ================================= // Parameters // ================================= /** * The id of this protocol in the protocol array */ public static int PID = 0; /** * The number of deemed correct processes */ private final int K; /** * The number of rounds for which each event needs to be relayed during its dissemination */ private final int TTL; /** * The nextBall set collects the events to be sent in the next round by process p * It relies on an HashMap<UUID, Event> */ private Ball nextBall = new Ball(); /** * Last updated LogicalClock */ private LogicalClock lastLogicalClock; // ================================= // Constructor implementation // ================================= public EpTODissemination(String prefix) { PID = Configuration.lookupPid(prefix.replace("protocol.",""));
// Path: src/main/java/epto/utils/Ball.java // public class Ball extends HashMap<UUID, Event> { // // } // // Path: src/main/java/epto/utils/Event.java // public class Event implements Comparable<Event>{ // // public UUID id; // // public LogicalClock timestamp; // // public int ttl; // // public long sourceId; // // public Event() { // id = UUID.randomUUID(); // } // // public int compareTo(Event o) { // int comparisionLC = timestamp.compareTo(o.timestamp); // return (comparisionLC != 0)? comparisionLC : (int)(sourceId - o.sourceId); // } // // @Override // public String toString() { // return "{timestamp=" + timestamp + ", ttl=" + ttl + ", sourceId=" + sourceId + "}"; // } // } // // Path: src/main/java/epto/utils/Message.java // public class Message { // // public final static int PREBROADCAST = 0; // public final static int BROADCAST = 1; // public final static int DELIVER = 2; // public final static int DISSEMINATION = 3; // public final static int ORDER = 4; // // private int type; // private Object content; // // private Node source; // // private Node destination; // // public Message(int type, Object content) { // this.type = type; // this.content = content; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public Object getContent() { // return content; // } // // public void setContent(Object content) { // this.content = content; // } // // // public Node getSource() { // // return source; // // } // // // // public void setSource(Node source) { // // this.source = source; // // } // // // // public Node getDestination() { // // return destination; // // } // // // // public void setDestination(Node destination) { // // this.destination = destination; // // } // } // // Path: src/main/java/epto/utils/Utils.java // public class Utils { // // public static final int DEFAULT_FANOUT = 5; // // public static final int DEFAULT_TTL = 2; // } // // Path: src/main/java/pss/IPeerSamplingService.java // public interface IPeerSamplingService { // // public Node selectNeighbor(); // // public List<Node> selectNeighbors(int k); // // public int degree(); // // public void myTurn(Node node, int pid); // // } // // Path: src/main/java/time/LogicalClock.java // public class LogicalClock implements Comparable<LogicalClock> { // // private long nodeId; // private int eventId; // // public LogicalClock(long nodeId) { // this.nodeId = nodeId; // this.eventId = 0; // } // // public LogicalClock(long nodeId, int eventId) { // this(nodeId); // this.eventId = eventId; // } // // public void increment() { // this.eventId++; // } // // public long getNodeId() { // return nodeId; // } // // public void setNodeId(long nodeId) { // this.nodeId = nodeId; // } // // public int getEventId() { // return eventId; // } // // public void setEventId(int eventId) { // this.eventId = eventId; // } // // public int compareTo(LogicalClock o) { // return (nodeId == o.nodeId)? eventId - o.eventId : (int) nodeId - (int) o.nodeId; // } // // @Override // public String toString() { // return "{nodeId=" + nodeId + ", eventId=" + eventId + "}"; // } // // @Override // public LogicalClock clone() throws CloneNotSupportedException { // return new LogicalClock(nodeId, eventId); // } // } // Path: src/main/java/epto/EpTODissemination.java import epto.utils.Ball; import epto.utils.Event; import epto.utils.Message; import epto.utils.Utils; import peersim.cdsim.CDProtocol; import peersim.config.Configuration; import peersim.config.FastConfig; import peersim.core.Node; import peersim.edsim.EDProtocol; import peersim.transport.Transport; import pss.IPeerSamplingService; import time.LogicalClock; import java.util.List; package epto; /** * The EpTO dissemination component * * The algorithm assumes the existence of a peer sampling service (PSS) responsible for keeping p’s view * up-to-date with a random stream of at least K deemed correct processes allowing a fanout of size K. * TTL (time to live) holds the number of rounds for which each event needs to be relayed during its dissemination. * The nextBall set collects the events to be sent in the next round by process p. * The dissemination component consists of three procedures executed atomically: the event broadcast primitive, * the event receive callback and the periodic relaying task. */ public class EpTODissemination implements CDProtocol, EDProtocol, EpTOBroadcaster { // ================================= // Configuration Parameters // ================================= /** * Config parameter name for the fanout K: number of deemed correct processes * @config */ private static final String PAR_FANOUT = "fanout"; /** * Config parameter name for the TTL (time to live). * It is a constant holding the number of rounds for which each event needs to be relayed during its dissemination. * @config */ private static final String PAR_TTL = "ttl"; // ================================= // Parameters // ================================= /** * The id of this protocol in the protocol array */ public static int PID = 0; /** * The number of deemed correct processes */ private final int K; /** * The number of rounds for which each event needs to be relayed during its dissemination */ private final int TTL; /** * The nextBall set collects the events to be sent in the next round by process p * It relies on an HashMap<UUID, Event> */ private Ball nextBall = new Ball(); /** * Last updated LogicalClock */ private LogicalClock lastLogicalClock; // ================================= // Constructor implementation // ================================= public EpTODissemination(String prefix) { PID = Configuration.lookupPid(prefix.replace("protocol.",""));
K = Configuration.getInt(prefix + "." + PAR_FANOUT, Utils.DEFAULT_FANOUT);
robzenn92/peersimTutorial
src/main/java/epto/EpTODissemination.java
// Path: src/main/java/epto/utils/Ball.java // public class Ball extends HashMap<UUID, Event> { // // } // // Path: src/main/java/epto/utils/Event.java // public class Event implements Comparable<Event>{ // // public UUID id; // // public LogicalClock timestamp; // // public int ttl; // // public long sourceId; // // public Event() { // id = UUID.randomUUID(); // } // // public int compareTo(Event o) { // int comparisionLC = timestamp.compareTo(o.timestamp); // return (comparisionLC != 0)? comparisionLC : (int)(sourceId - o.sourceId); // } // // @Override // public String toString() { // return "{timestamp=" + timestamp + ", ttl=" + ttl + ", sourceId=" + sourceId + "}"; // } // } // // Path: src/main/java/epto/utils/Message.java // public class Message { // // public final static int PREBROADCAST = 0; // public final static int BROADCAST = 1; // public final static int DELIVER = 2; // public final static int DISSEMINATION = 3; // public final static int ORDER = 4; // // private int type; // private Object content; // // private Node source; // // private Node destination; // // public Message(int type, Object content) { // this.type = type; // this.content = content; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public Object getContent() { // return content; // } // // public void setContent(Object content) { // this.content = content; // } // // // public Node getSource() { // // return source; // // } // // // // public void setSource(Node source) { // // this.source = source; // // } // // // // public Node getDestination() { // // return destination; // // } // // // // public void setDestination(Node destination) { // // this.destination = destination; // // } // } // // Path: src/main/java/epto/utils/Utils.java // public class Utils { // // public static final int DEFAULT_FANOUT = 5; // // public static final int DEFAULT_TTL = 2; // } // // Path: src/main/java/pss/IPeerSamplingService.java // public interface IPeerSamplingService { // // public Node selectNeighbor(); // // public List<Node> selectNeighbors(int k); // // public int degree(); // // public void myTurn(Node node, int pid); // // } // // Path: src/main/java/time/LogicalClock.java // public class LogicalClock implements Comparable<LogicalClock> { // // private long nodeId; // private int eventId; // // public LogicalClock(long nodeId) { // this.nodeId = nodeId; // this.eventId = 0; // } // // public LogicalClock(long nodeId, int eventId) { // this(nodeId); // this.eventId = eventId; // } // // public void increment() { // this.eventId++; // } // // public long getNodeId() { // return nodeId; // } // // public void setNodeId(long nodeId) { // this.nodeId = nodeId; // } // // public int getEventId() { // return eventId; // } // // public void setEventId(int eventId) { // this.eventId = eventId; // } // // public int compareTo(LogicalClock o) { // return (nodeId == o.nodeId)? eventId - o.eventId : (int) nodeId - (int) o.nodeId; // } // // @Override // public String toString() { // return "{nodeId=" + nodeId + ", eventId=" + eventId + "}"; // } // // @Override // public LogicalClock clone() throws CloneNotSupportedException { // return new LogicalClock(nodeId, eventId); // } // }
import epto.utils.Ball; import epto.utils.Event; import epto.utils.Message; import epto.utils.Utils; import peersim.cdsim.CDProtocol; import peersim.config.Configuration; import peersim.config.FastConfig; import peersim.core.Node; import peersim.edsim.EDProtocol; import peersim.transport.Transport; import pss.IPeerSamplingService; import time.LogicalClock; import java.util.List;
// foreach event in nextBall do for (Event event : nextBall.values()) { // event.ttl event.ttl + 1 event.ttl++; } if (nextBall.size() != 0) { List<Node> peers = pss.selectNeighbors(K); // foreach q in peers do send BALL(nextBall) to q for (Node q : peers) { send(nextBall, node, q); } } // TODO: maybe this can be put within the above statement cause if nextBall is empty there is no need to order it // orderEvents(nextBall) // Message m = new Message(Message.ORDER, nextBall.clone()); // EDSimulator.add(10, m, node, EpTOOrdering.PID); EpTOOrdering EpTO_ordering = (EpTOOrdering) node.getProtocol(EpTOOrdering.PID); EpTO_ordering.orderEvents((Ball) nextBall.clone(), node); // nextBall = 0 nextBall.clear(); } } private void send(Ball nextBall, Node source, Node destination) { if (destination.isUp()) {
// Path: src/main/java/epto/utils/Ball.java // public class Ball extends HashMap<UUID, Event> { // // } // // Path: src/main/java/epto/utils/Event.java // public class Event implements Comparable<Event>{ // // public UUID id; // // public LogicalClock timestamp; // // public int ttl; // // public long sourceId; // // public Event() { // id = UUID.randomUUID(); // } // // public int compareTo(Event o) { // int comparisionLC = timestamp.compareTo(o.timestamp); // return (comparisionLC != 0)? comparisionLC : (int)(sourceId - o.sourceId); // } // // @Override // public String toString() { // return "{timestamp=" + timestamp + ", ttl=" + ttl + ", sourceId=" + sourceId + "}"; // } // } // // Path: src/main/java/epto/utils/Message.java // public class Message { // // public final static int PREBROADCAST = 0; // public final static int BROADCAST = 1; // public final static int DELIVER = 2; // public final static int DISSEMINATION = 3; // public final static int ORDER = 4; // // private int type; // private Object content; // // private Node source; // // private Node destination; // // public Message(int type, Object content) { // this.type = type; // this.content = content; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public Object getContent() { // return content; // } // // public void setContent(Object content) { // this.content = content; // } // // // public Node getSource() { // // return source; // // } // // // // public void setSource(Node source) { // // this.source = source; // // } // // // // public Node getDestination() { // // return destination; // // } // // // // public void setDestination(Node destination) { // // this.destination = destination; // // } // } // // Path: src/main/java/epto/utils/Utils.java // public class Utils { // // public static final int DEFAULT_FANOUT = 5; // // public static final int DEFAULT_TTL = 2; // } // // Path: src/main/java/pss/IPeerSamplingService.java // public interface IPeerSamplingService { // // public Node selectNeighbor(); // // public List<Node> selectNeighbors(int k); // // public int degree(); // // public void myTurn(Node node, int pid); // // } // // Path: src/main/java/time/LogicalClock.java // public class LogicalClock implements Comparable<LogicalClock> { // // private long nodeId; // private int eventId; // // public LogicalClock(long nodeId) { // this.nodeId = nodeId; // this.eventId = 0; // } // // public LogicalClock(long nodeId, int eventId) { // this(nodeId); // this.eventId = eventId; // } // // public void increment() { // this.eventId++; // } // // public long getNodeId() { // return nodeId; // } // // public void setNodeId(long nodeId) { // this.nodeId = nodeId; // } // // public int getEventId() { // return eventId; // } // // public void setEventId(int eventId) { // this.eventId = eventId; // } // // public int compareTo(LogicalClock o) { // return (nodeId == o.nodeId)? eventId - o.eventId : (int) nodeId - (int) o.nodeId; // } // // @Override // public String toString() { // return "{nodeId=" + nodeId + ", eventId=" + eventId + "}"; // } // // @Override // public LogicalClock clone() throws CloneNotSupportedException { // return new LogicalClock(nodeId, eventId); // } // } // Path: src/main/java/epto/EpTODissemination.java import epto.utils.Ball; import epto.utils.Event; import epto.utils.Message; import epto.utils.Utils; import peersim.cdsim.CDProtocol; import peersim.config.Configuration; import peersim.config.FastConfig; import peersim.core.Node; import peersim.edsim.EDProtocol; import peersim.transport.Transport; import pss.IPeerSamplingService; import time.LogicalClock; import java.util.List; // foreach event in nextBall do for (Event event : nextBall.values()) { // event.ttl event.ttl + 1 event.ttl++; } if (nextBall.size() != 0) { List<Node> peers = pss.selectNeighbors(K); // foreach q in peers do send BALL(nextBall) to q for (Node q : peers) { send(nextBall, node, q); } } // TODO: maybe this can be put within the above statement cause if nextBall is empty there is no need to order it // orderEvents(nextBall) // Message m = new Message(Message.ORDER, nextBall.clone()); // EDSimulator.add(10, m, node, EpTOOrdering.PID); EpTOOrdering EpTO_ordering = (EpTOOrdering) node.getProtocol(EpTOOrdering.PID); EpTO_ordering.orderEvents((Ball) nextBall.clone(), node); // nextBall = 0 nextBall.clear(); } } private void send(Ball nextBall, Node source, Node destination) { if (destination.isUp()) {
((Transport) source.getProtocol(FastConfig.getTransport(PID))).send(source, destination, new Message(Message.BROADCAST, nextBall.clone()), PID);
robzenn92/peersimTutorial
src/main/java/newscast/observers/PartialViewObserver.java
// Path: src/main/java/newscast/NewscastProtocol.java // public class NewscastProtocol extends PeerSamplingService implements Linkable { // // // // ================================= // // Parameters // // ================================= // // /** // * Config parameter name for the cache size // * @config // */ // private static final String PAR_CACHE = "cache"; // // /** // * Partial view size indicates how many neighbours are allowed to be in the peer's partial view. // */ // private int cache; // // /** // * Partial view containing the peer's neighbours. // * Its size is the same as the cache size. // */ // private PartialView view; // // // // ================================= // // Constructor implementation // // ================================= // // public NewscastProtocol(int cache) { // this.cache = cache; // this.view = new PartialView(cache); // } // // public NewscastProtocol(String n) { // super(n); // cache = Configuration.getInt(n + "." + PAR_CACHE, Utils.DEFAULT_CACHE_SIZE); // view = new PartialView(cache); // } // // // ================================= // // Newscast implementation // // ================================= // // public Node selectNeighbor() { // return view.getRandomPeer().getNode(); // } // // public ArrayList<Node> selectNeighbors(int k) { // // int degree = degree(); // int max = Math.max(k, degree); // ArrayList<Node> neighbors = new ArrayList<Node>(max); // // while (neighbors.size() != max) { // Node n = selectNeighbor(); // if (!neighbors.contains(n)) { // neighbors.add(n); // } // } // return neighbors; // } // // // ================================= // // Linkable implementation // // ================================= // // public int degree() { // return view.size(); // } // // public Node getNeighbor(int i) { // return view.getPeer(i).getNode(); // } // // public boolean addNeighbor(Node node) { // if ( view.contains(node)) return false; // return view.addPeer(node,false); // } // // public boolean contains(Node node) { // return view.contains(node); // } // // public void pack() { } // // public void onKill() { // view = null; // } // // public Object clone() { // return new NewscastProtocol(cache); // } // // public void setCache(int cache) { // this.cache = cache; // } // // public PartialView getView() { // return view; // } // // public void setView(PartialView view) { // this.view = view; // } // // public void myTurn(Node node, int pid) { // // // System.out.println("Node " + node.getID() + " is updating its view with Newscast at cycle " + CommonState.getTime()); // // // Get a random peer from the PartialView // Node neighbour = selectNeighbor(); // NewscastProtocol destination = (NewscastProtocol) neighbour.getProtocol(pid); // // // Merge everything // PartialView cloned = null; // try { // cloned = view.clone(); // } catch (CloneNotSupportedException e) { // e.printStackTrace(); // } // // view.merge(destination.getView(), node, neighbour); // // destination.getView().merge(cloned, neighbour.getNode(), node); // } // }
import peersim.config.Configuration; import peersim.core.Node; import peersim.core.Protocol; import peersim.graph.Graph; import peersim.reports.GraphObserver; import peersim.util.FileNameGenerator; import newscast.NewscastProtocol; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream;
System.out.println("Writing to file " + fname); PrintStream pstr = new PrintStream(fos); // dump topology: graphToFile(g, pstr); fos.close(); } catch (IOException e) { throw new RuntimeException(e); } return false; } /** * Utility method: prints out data to plot the topology using gnuplot a * gnuplot style. * * @param g current graph. * @param ps a {@link java.io.PrintStream} object to write to. */ private static void graphToFile(Graph g, PrintStream ps) { for (int i = 1; i < g.size(); i++) { Node current = (Node) g.getNode(i); Protocol p = current.getProtocol(protocolId);
// Path: src/main/java/newscast/NewscastProtocol.java // public class NewscastProtocol extends PeerSamplingService implements Linkable { // // // // ================================= // // Parameters // // ================================= // // /** // * Config parameter name for the cache size // * @config // */ // private static final String PAR_CACHE = "cache"; // // /** // * Partial view size indicates how many neighbours are allowed to be in the peer's partial view. // */ // private int cache; // // /** // * Partial view containing the peer's neighbours. // * Its size is the same as the cache size. // */ // private PartialView view; // // // // ================================= // // Constructor implementation // // ================================= // // public NewscastProtocol(int cache) { // this.cache = cache; // this.view = new PartialView(cache); // } // // public NewscastProtocol(String n) { // super(n); // cache = Configuration.getInt(n + "." + PAR_CACHE, Utils.DEFAULT_CACHE_SIZE); // view = new PartialView(cache); // } // // // ================================= // // Newscast implementation // // ================================= // // public Node selectNeighbor() { // return view.getRandomPeer().getNode(); // } // // public ArrayList<Node> selectNeighbors(int k) { // // int degree = degree(); // int max = Math.max(k, degree); // ArrayList<Node> neighbors = new ArrayList<Node>(max); // // while (neighbors.size() != max) { // Node n = selectNeighbor(); // if (!neighbors.contains(n)) { // neighbors.add(n); // } // } // return neighbors; // } // // // ================================= // // Linkable implementation // // ================================= // // public int degree() { // return view.size(); // } // // public Node getNeighbor(int i) { // return view.getPeer(i).getNode(); // } // // public boolean addNeighbor(Node node) { // if ( view.contains(node)) return false; // return view.addPeer(node,false); // } // // public boolean contains(Node node) { // return view.contains(node); // } // // public void pack() { } // // public void onKill() { // view = null; // } // // public Object clone() { // return new NewscastProtocol(cache); // } // // public void setCache(int cache) { // this.cache = cache; // } // // public PartialView getView() { // return view; // } // // public void setView(PartialView view) { // this.view = view; // } // // public void myTurn(Node node, int pid) { // // // System.out.println("Node " + node.getID() + " is updating its view with Newscast at cycle " + CommonState.getTime()); // // // Get a random peer from the PartialView // Node neighbour = selectNeighbor(); // NewscastProtocol destination = (NewscastProtocol) neighbour.getProtocol(pid); // // // Merge everything // PartialView cloned = null; // try { // cloned = view.clone(); // } catch (CloneNotSupportedException e) { // e.printStackTrace(); // } // // view.merge(destination.getView(), node, neighbour); // // destination.getView().merge(cloned, neighbour.getNode(), node); // } // } // Path: src/main/java/newscast/observers/PartialViewObserver.java import peersim.config.Configuration; import peersim.core.Node; import peersim.core.Protocol; import peersim.graph.Graph; import peersim.reports.GraphObserver; import peersim.util.FileNameGenerator; import newscast.NewscastProtocol; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; System.out.println("Writing to file " + fname); PrintStream pstr = new PrintStream(fos); // dump topology: graphToFile(g, pstr); fos.close(); } catch (IOException e) { throw new RuntimeException(e); } return false; } /** * Utility method: prints out data to plot the topology using gnuplot a * gnuplot style. * * @param g current graph. * @param ps a {@link java.io.PrintStream} object to write to. */ private static void graphToFile(Graph g, PrintStream ps) { for (int i = 1; i < g.size(); i++) { Node current = (Node) g.getNode(i); Protocol p = current.getProtocol(protocolId);
NewscastProtocol peer = (NewscastProtocol) p;
robzenn92/peersimTutorial
src/test/java/unit/TestNodeDescriptors.java
// Path: src/test/java/helpers/NodeHelper.java // public class NodeHelper { // // public static Node createNode(final int id) { // // return new Node() { // // public Protocol getProtocol(int i) { // return null; // } // // public int protocolSize() { // return 0; // } // // public void setIndex(int i) { // } // // public int getIndex() { // return 0; // } // // public long getID() { // return id; // } // // public int getFailState() { // return 0; // } // // public void setFailState(int i) { // // } // // public boolean isUp() { // return true; // } // // public Object clone() { // return null; // } // }; // } // } // // Path: src/main/java/newscast/utils/NodeDescriptor.java // public class NodeDescriptor implements Comparable { // // private Node node; // private int age; // // public NodeDescriptor(Node node) { // this.node = node; // this.age = CommonState.getIntTime(); // } // // public NodeDescriptor(Node node, int age) { // this.node = node; // this.age = age; // } // // public int compareTo(Object o) { // int age1 = ((NodeDescriptor) o).getAge(); // return (age < age1) ? 1 : ((age == age1) ? 0 : -1); // } // // public void updateAge() { // this.age++; // } // // public Node getNode() { // return node; // } // // public int getAge() { // return age; // } // // @Override // public String toString() { // return "ND: { node = " + node.getID() + ", age = " + age + " }"; // } // }
import helpers.NodeHelper; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; import peersim.config.Configuration; import peersim.config.ParsedProperties; import newscast.utils.NodeDescriptor; import java.io.IOException; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue;
package unit; public class TestNodeDescriptors { @BeforeSuite public void setUpConfiguration() throws IOException { Configuration.setConfig(new ParsedProperties("src/test/resources/tests.cfg")); } @Test public void testNewNodeDescriptorRandomAge() {
// Path: src/test/java/helpers/NodeHelper.java // public class NodeHelper { // // public static Node createNode(final int id) { // // return new Node() { // // public Protocol getProtocol(int i) { // return null; // } // // public int protocolSize() { // return 0; // } // // public void setIndex(int i) { // } // // public int getIndex() { // return 0; // } // // public long getID() { // return id; // } // // public int getFailState() { // return 0; // } // // public void setFailState(int i) { // // } // // public boolean isUp() { // return true; // } // // public Object clone() { // return null; // } // }; // } // } // // Path: src/main/java/newscast/utils/NodeDescriptor.java // public class NodeDescriptor implements Comparable { // // private Node node; // private int age; // // public NodeDescriptor(Node node) { // this.node = node; // this.age = CommonState.getIntTime(); // } // // public NodeDescriptor(Node node, int age) { // this.node = node; // this.age = age; // } // // public int compareTo(Object o) { // int age1 = ((NodeDescriptor) o).getAge(); // return (age < age1) ? 1 : ((age == age1) ? 0 : -1); // } // // public void updateAge() { // this.age++; // } // // public Node getNode() { // return node; // } // // public int getAge() { // return age; // } // // @Override // public String toString() { // return "ND: { node = " + node.getID() + ", age = " + age + " }"; // } // } // Path: src/test/java/unit/TestNodeDescriptors.java import helpers.NodeHelper; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; import peersim.config.Configuration; import peersim.config.ParsedProperties; import newscast.utils.NodeDescriptor; import java.io.IOException; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; package unit; public class TestNodeDescriptors { @BeforeSuite public void setUpConfiguration() throws IOException { Configuration.setConfig(new ParsedProperties("src/test/resources/tests.cfg")); } @Test public void testNewNodeDescriptorRandomAge() {
NodeDescriptor n = new NodeDescriptor(NodeHelper.createNode(1));
robzenn92/peersimTutorial
src/test/java/unit/TestNodeDescriptors.java
// Path: src/test/java/helpers/NodeHelper.java // public class NodeHelper { // // public static Node createNode(final int id) { // // return new Node() { // // public Protocol getProtocol(int i) { // return null; // } // // public int protocolSize() { // return 0; // } // // public void setIndex(int i) { // } // // public int getIndex() { // return 0; // } // // public long getID() { // return id; // } // // public int getFailState() { // return 0; // } // // public void setFailState(int i) { // // } // // public boolean isUp() { // return true; // } // // public Object clone() { // return null; // } // }; // } // } // // Path: src/main/java/newscast/utils/NodeDescriptor.java // public class NodeDescriptor implements Comparable { // // private Node node; // private int age; // // public NodeDescriptor(Node node) { // this.node = node; // this.age = CommonState.getIntTime(); // } // // public NodeDescriptor(Node node, int age) { // this.node = node; // this.age = age; // } // // public int compareTo(Object o) { // int age1 = ((NodeDescriptor) o).getAge(); // return (age < age1) ? 1 : ((age == age1) ? 0 : -1); // } // // public void updateAge() { // this.age++; // } // // public Node getNode() { // return node; // } // // public int getAge() { // return age; // } // // @Override // public String toString() { // return "ND: { node = " + node.getID() + ", age = " + age + " }"; // } // }
import helpers.NodeHelper; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; import peersim.config.Configuration; import peersim.config.ParsedProperties; import newscast.utils.NodeDescriptor; import java.io.IOException; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue;
package unit; public class TestNodeDescriptors { @BeforeSuite public void setUpConfiguration() throws IOException { Configuration.setConfig(new ParsedProperties("src/test/resources/tests.cfg")); } @Test public void testNewNodeDescriptorRandomAge() {
// Path: src/test/java/helpers/NodeHelper.java // public class NodeHelper { // // public static Node createNode(final int id) { // // return new Node() { // // public Protocol getProtocol(int i) { // return null; // } // // public int protocolSize() { // return 0; // } // // public void setIndex(int i) { // } // // public int getIndex() { // return 0; // } // // public long getID() { // return id; // } // // public int getFailState() { // return 0; // } // // public void setFailState(int i) { // // } // // public boolean isUp() { // return true; // } // // public Object clone() { // return null; // } // }; // } // } // // Path: src/main/java/newscast/utils/NodeDescriptor.java // public class NodeDescriptor implements Comparable { // // private Node node; // private int age; // // public NodeDescriptor(Node node) { // this.node = node; // this.age = CommonState.getIntTime(); // } // // public NodeDescriptor(Node node, int age) { // this.node = node; // this.age = age; // } // // public int compareTo(Object o) { // int age1 = ((NodeDescriptor) o).getAge(); // return (age < age1) ? 1 : ((age == age1) ? 0 : -1); // } // // public void updateAge() { // this.age++; // } // // public Node getNode() { // return node; // } // // public int getAge() { // return age; // } // // @Override // public String toString() { // return "ND: { node = " + node.getID() + ", age = " + age + " }"; // } // } // Path: src/test/java/unit/TestNodeDescriptors.java import helpers.NodeHelper; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Test; import peersim.config.Configuration; import peersim.config.ParsedProperties; import newscast.utils.NodeDescriptor; import java.io.IOException; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; package unit; public class TestNodeDescriptors { @BeforeSuite public void setUpConfiguration() throws IOException { Configuration.setConfig(new ParsedProperties("src/test/resources/tests.cfg")); } @Test public void testNewNodeDescriptorRandomAge() {
NodeDescriptor n = new NodeDescriptor(NodeHelper.createNode(1));
robzenn92/peersimTutorial
src/main/java/epto/EpTOApplication.java
// Path: src/main/java/epto/utils/Event.java // public class Event implements Comparable<Event>{ // // public UUID id; // // public LogicalClock timestamp; // // public int ttl; // // public long sourceId; // // public Event() { // id = UUID.randomUUID(); // } // // public int compareTo(Event o) { // int comparisionLC = timestamp.compareTo(o.timestamp); // return (comparisionLC != 0)? comparisionLC : (int)(sourceId - o.sourceId); // } // // @Override // public String toString() { // return "{timestamp=" + timestamp + ", ttl=" + ttl + ", sourceId=" + sourceId + "}"; // } // } // // Path: src/main/java/epto/utils/Message.java // public class Message { // // public final static int PREBROADCAST = 0; // public final static int BROADCAST = 1; // public final static int DELIVER = 2; // public final static int DISSEMINATION = 3; // public final static int ORDER = 4; // // private int type; // private Object content; // // private Node source; // // private Node destination; // // public Message(int type, Object content) { // this.type = type; // this.content = content; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public Object getContent() { // return content; // } // // public void setContent(Object content) { // this.content = content; // } // // // public Node getSource() { // // return source; // // } // // // // public void setSource(Node source) { // // this.source = source; // // } // // // // public Node getDestination() { // // return destination; // // } // // // // public void setDestination(Node destination) { // // this.destination = destination; // // } // }
import epto.utils.Event; import epto.utils.Message; import peersim.cdsim.CDProtocol; import peersim.config.Configuration; import peersim.core.CommonState; import peersim.core.Node; import peersim.edsim.EDProtocol; import java.util.ArrayList;
package epto; public class EpTOApplication implements CDProtocol, EDProtocol, EpTOBroadcaster, EpTODeliverer { // ================================= // Configuration Parameters // ================================= /** * Config parameter name for the probability to EpTOBroadcast an event * Its value must be between 0 and 1 * @config */ private static final String PAR_PROB = "prob"; // ================================= // Parameters // ================================= /** * The id of this protocol in the protocol array */ public static int PID = 0; /** * The probability to EpTOBroadcast an event */ private final double PROB;
// Path: src/main/java/epto/utils/Event.java // public class Event implements Comparable<Event>{ // // public UUID id; // // public LogicalClock timestamp; // // public int ttl; // // public long sourceId; // // public Event() { // id = UUID.randomUUID(); // } // // public int compareTo(Event o) { // int comparisionLC = timestamp.compareTo(o.timestamp); // return (comparisionLC != 0)? comparisionLC : (int)(sourceId - o.sourceId); // } // // @Override // public String toString() { // return "{timestamp=" + timestamp + ", ttl=" + ttl + ", sourceId=" + sourceId + "}"; // } // } // // Path: src/main/java/epto/utils/Message.java // public class Message { // // public final static int PREBROADCAST = 0; // public final static int BROADCAST = 1; // public final static int DELIVER = 2; // public final static int DISSEMINATION = 3; // public final static int ORDER = 4; // // private int type; // private Object content; // // private Node source; // // private Node destination; // // public Message(int type, Object content) { // this.type = type; // this.content = content; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public Object getContent() { // return content; // } // // public void setContent(Object content) { // this.content = content; // } // // // public Node getSource() { // // return source; // // } // // // // public void setSource(Node source) { // // this.source = source; // // } // // // // public Node getDestination() { // // return destination; // // } // // // // public void setDestination(Node destination) { // // this.destination = destination; // // } // } // Path: src/main/java/epto/EpTOApplication.java import epto.utils.Event; import epto.utils.Message; import peersim.cdsim.CDProtocol; import peersim.config.Configuration; import peersim.core.CommonState; import peersim.core.Node; import peersim.edsim.EDProtocol; import java.util.ArrayList; package epto; public class EpTOApplication implements CDProtocol, EDProtocol, EpTOBroadcaster, EpTODeliverer { // ================================= // Configuration Parameters // ================================= /** * Config parameter name for the probability to EpTOBroadcast an event * Its value must be between 0 and 1 * @config */ private static final String PAR_PROB = "prob"; // ================================= // Parameters // ================================= /** * The id of this protocol in the protocol array */ public static int PID = 0; /** * The probability to EpTOBroadcast an event */ private final double PROB;
private ArrayList<Event> delivered = new ArrayList<Event>();
robzenn92/peersimTutorial
src/main/java/epto/EpTOApplication.java
// Path: src/main/java/epto/utils/Event.java // public class Event implements Comparable<Event>{ // // public UUID id; // // public LogicalClock timestamp; // // public int ttl; // // public long sourceId; // // public Event() { // id = UUID.randomUUID(); // } // // public int compareTo(Event o) { // int comparisionLC = timestamp.compareTo(o.timestamp); // return (comparisionLC != 0)? comparisionLC : (int)(sourceId - o.sourceId); // } // // @Override // public String toString() { // return "{timestamp=" + timestamp + ", ttl=" + ttl + ", sourceId=" + sourceId + "}"; // } // } // // Path: src/main/java/epto/utils/Message.java // public class Message { // // public final static int PREBROADCAST = 0; // public final static int BROADCAST = 1; // public final static int DELIVER = 2; // public final static int DISSEMINATION = 3; // public final static int ORDER = 4; // // private int type; // private Object content; // // private Node source; // // private Node destination; // // public Message(int type, Object content) { // this.type = type; // this.content = content; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public Object getContent() { // return content; // } // // public void setContent(Object content) { // this.content = content; // } // // // public Node getSource() { // // return source; // // } // // // // public void setSource(Node source) { // // this.source = source; // // } // // // // public Node getDestination() { // // return destination; // // } // // // // public void setDestination(Node destination) { // // this.destination = destination; // // } // }
import epto.utils.Event; import epto.utils.Message; import peersim.cdsim.CDProtocol; import peersim.config.Configuration; import peersim.core.CommonState; import peersim.core.Node; import peersim.edsim.EDProtocol; import java.util.ArrayList;
EpTOBroadcast(new Event(), node); } } public void EpTOBroadcast(Event event, Node node) { // Message m = new Message(Message.PREBROADCAST, event); // EDSimulator.add(10, m, node, EpTODissemination.PID); EpTODissemination EpTO_dissemination = (EpTODissemination) node.getProtocol(EpTODissemination.PID); EpTO_dissemination.EpTOBroadcast(event, node); } public Object clone() { EpTOApplication epToApplication = null; try { epToApplication = (EpTOApplication) super.clone(); epToApplication.delivered = new ArrayList<Event>(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return epToApplication; } public void EpTODeliver(Event event, Node node) { delivered.add(event); System.out.println("Node " + node.getID() + " delivered : " + event); System.out.println("Node " + node.getID() + " delivered (till now) : " + delivered); } public void processEvent(Node node, int i, Object o) {
// Path: src/main/java/epto/utils/Event.java // public class Event implements Comparable<Event>{ // // public UUID id; // // public LogicalClock timestamp; // // public int ttl; // // public long sourceId; // // public Event() { // id = UUID.randomUUID(); // } // // public int compareTo(Event o) { // int comparisionLC = timestamp.compareTo(o.timestamp); // return (comparisionLC != 0)? comparisionLC : (int)(sourceId - o.sourceId); // } // // @Override // public String toString() { // return "{timestamp=" + timestamp + ", ttl=" + ttl + ", sourceId=" + sourceId + "}"; // } // } // // Path: src/main/java/epto/utils/Message.java // public class Message { // // public final static int PREBROADCAST = 0; // public final static int BROADCAST = 1; // public final static int DELIVER = 2; // public final static int DISSEMINATION = 3; // public final static int ORDER = 4; // // private int type; // private Object content; // // private Node source; // // private Node destination; // // public Message(int type, Object content) { // this.type = type; // this.content = content; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public Object getContent() { // return content; // } // // public void setContent(Object content) { // this.content = content; // } // // // public Node getSource() { // // return source; // // } // // // // public void setSource(Node source) { // // this.source = source; // // } // // // // public Node getDestination() { // // return destination; // // } // // // // public void setDestination(Node destination) { // // this.destination = destination; // // } // } // Path: src/main/java/epto/EpTOApplication.java import epto.utils.Event; import epto.utils.Message; import peersim.cdsim.CDProtocol; import peersim.config.Configuration; import peersim.core.CommonState; import peersim.core.Node; import peersim.edsim.EDProtocol; import java.util.ArrayList; EpTOBroadcast(new Event(), node); } } public void EpTOBroadcast(Event event, Node node) { // Message m = new Message(Message.PREBROADCAST, event); // EDSimulator.add(10, m, node, EpTODissemination.PID); EpTODissemination EpTO_dissemination = (EpTODissemination) node.getProtocol(EpTODissemination.PID); EpTO_dissemination.EpTOBroadcast(event, node); } public Object clone() { EpTOApplication epToApplication = null; try { epToApplication = (EpTOApplication) super.clone(); epToApplication.delivered = new ArrayList<Event>(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return epToApplication; } public void EpTODeliver(Event event, Node node) { delivered.add(event); System.out.println("Node " + node.getID() + " delivered : " + event); System.out.println("Node " + node.getID() + " delivered (till now) : " + delivered); } public void processEvent(Node node, int i, Object o) {
Message m = (Message) o;
robzenn92/peersimTutorial
src/main/java/epto/EpTOOrdering.java
// Path: src/main/java/epto/utils/Ball.java // public class Ball extends HashMap<UUID, Event> { // // } // // Path: src/main/java/epto/utils/Event.java // public class Event implements Comparable<Event>{ // // public UUID id; // // public LogicalClock timestamp; // // public int ttl; // // public long sourceId; // // public Event() { // id = UUID.randomUUID(); // } // // public int compareTo(Event o) { // int comparisionLC = timestamp.compareTo(o.timestamp); // return (comparisionLC != 0)? comparisionLC : (int)(sourceId - o.sourceId); // } // // @Override // public String toString() { // return "{timestamp=" + timestamp + ", ttl=" + ttl + ", sourceId=" + sourceId + "}"; // } // } // // Path: src/main/java/epto/utils/Message.java // public class Message { // // public final static int PREBROADCAST = 0; // public final static int BROADCAST = 1; // public final static int DELIVER = 2; // public final static int DISSEMINATION = 3; // public final static int ORDER = 4; // // private int type; // private Object content; // // private Node source; // // private Node destination; // // public Message(int type, Object content) { // this.type = type; // this.content = content; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public Object getContent() { // return content; // } // // public void setContent(Object content) { // this.content = content; // } // // // public Node getSource() { // // return source; // // } // // // // public void setSource(Node source) { // // this.source = source; // // } // // // // public Node getDestination() { // // return destination; // // } // // // // public void setDestination(Node destination) { // // this.destination = destination; // // } // } // // Path: src/main/java/epto/utils/Utils.java // public class Utils { // // public static final int DEFAULT_FANOUT = 5; // // public static final int DEFAULT_TTL = 2; // }
import epto.utils.Ball; import epto.utils.Event; import epto.utils.Message; import epto.utils.Utils; import peersim.config.Configuration; import peersim.core.Node; import peersim.edsim.EDProtocol; import peersim.edsim.EDSimulator; import java.util.*;
package epto; /** * The EpTO ordering component */ public class EpTOOrdering implements EDProtocol, EpTODeliverer { // ================================= // Configuration Parameters // ================================= /** * Config parameter name for the TTL (time to live). * It is a constant holding the number of rounds for which each event needs to be relayed during its dissemination. * @config */ private static final String PAR_TTL = "ttl"; // ================================= // Parameters // ================================= /** * The id of this protocol in the protocol array */ public static int PID = 0; /** * The number of rounds for which each event needs to be relayed during its dissemination */ private final int TTL; /** * A received map of (id, event) pairs with all known but not yet delivered events */
// Path: src/main/java/epto/utils/Ball.java // public class Ball extends HashMap<UUID, Event> { // // } // // Path: src/main/java/epto/utils/Event.java // public class Event implements Comparable<Event>{ // // public UUID id; // // public LogicalClock timestamp; // // public int ttl; // // public long sourceId; // // public Event() { // id = UUID.randomUUID(); // } // // public int compareTo(Event o) { // int comparisionLC = timestamp.compareTo(o.timestamp); // return (comparisionLC != 0)? comparisionLC : (int)(sourceId - o.sourceId); // } // // @Override // public String toString() { // return "{timestamp=" + timestamp + ", ttl=" + ttl + ", sourceId=" + sourceId + "}"; // } // } // // Path: src/main/java/epto/utils/Message.java // public class Message { // // public final static int PREBROADCAST = 0; // public final static int BROADCAST = 1; // public final static int DELIVER = 2; // public final static int DISSEMINATION = 3; // public final static int ORDER = 4; // // private int type; // private Object content; // // private Node source; // // private Node destination; // // public Message(int type, Object content) { // this.type = type; // this.content = content; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public Object getContent() { // return content; // } // // public void setContent(Object content) { // this.content = content; // } // // // public Node getSource() { // // return source; // // } // // // // public void setSource(Node source) { // // this.source = source; // // } // // // // public Node getDestination() { // // return destination; // // } // // // // public void setDestination(Node destination) { // // this.destination = destination; // // } // } // // Path: src/main/java/epto/utils/Utils.java // public class Utils { // // public static final int DEFAULT_FANOUT = 5; // // public static final int DEFAULT_TTL = 2; // } // Path: src/main/java/epto/EpTOOrdering.java import epto.utils.Ball; import epto.utils.Event; import epto.utils.Message; import epto.utils.Utils; import peersim.config.Configuration; import peersim.core.Node; import peersim.edsim.EDProtocol; import peersim.edsim.EDSimulator; import java.util.*; package epto; /** * The EpTO ordering component */ public class EpTOOrdering implements EDProtocol, EpTODeliverer { // ================================= // Configuration Parameters // ================================= /** * Config parameter name for the TTL (time to live). * It is a constant holding the number of rounds for which each event needs to be relayed during its dissemination. * @config */ private static final String PAR_TTL = "ttl"; // ================================= // Parameters // ================================= /** * The id of this protocol in the protocol array */ public static int PID = 0; /** * The number of rounds for which each event needs to be relayed during its dissemination */ private final int TTL; /** * A received map of (id, event) pairs with all known but not yet delivered events */
private HashMap<UUID, Event> received = new HashMap<UUID, Event>();
robzenn92/peersimTutorial
src/main/java/epto/EpTOOrdering.java
// Path: src/main/java/epto/utils/Ball.java // public class Ball extends HashMap<UUID, Event> { // // } // // Path: src/main/java/epto/utils/Event.java // public class Event implements Comparable<Event>{ // // public UUID id; // // public LogicalClock timestamp; // // public int ttl; // // public long sourceId; // // public Event() { // id = UUID.randomUUID(); // } // // public int compareTo(Event o) { // int comparisionLC = timestamp.compareTo(o.timestamp); // return (comparisionLC != 0)? comparisionLC : (int)(sourceId - o.sourceId); // } // // @Override // public String toString() { // return "{timestamp=" + timestamp + ", ttl=" + ttl + ", sourceId=" + sourceId + "}"; // } // } // // Path: src/main/java/epto/utils/Message.java // public class Message { // // public final static int PREBROADCAST = 0; // public final static int BROADCAST = 1; // public final static int DELIVER = 2; // public final static int DISSEMINATION = 3; // public final static int ORDER = 4; // // private int type; // private Object content; // // private Node source; // // private Node destination; // // public Message(int type, Object content) { // this.type = type; // this.content = content; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public Object getContent() { // return content; // } // // public void setContent(Object content) { // this.content = content; // } // // // public Node getSource() { // // return source; // // } // // // // public void setSource(Node source) { // // this.source = source; // // } // // // // public Node getDestination() { // // return destination; // // } // // // // public void setDestination(Node destination) { // // this.destination = destination; // // } // } // // Path: src/main/java/epto/utils/Utils.java // public class Utils { // // public static final int DEFAULT_FANOUT = 5; // // public static final int DEFAULT_TTL = 2; // }
import epto.utils.Ball; import epto.utils.Event; import epto.utils.Message; import epto.utils.Utils; import peersim.config.Configuration; import peersim.core.Node; import peersim.edsim.EDProtocol; import peersim.edsim.EDSimulator; import java.util.*;
package epto; /** * The EpTO ordering component */ public class EpTOOrdering implements EDProtocol, EpTODeliverer { // ================================= // Configuration Parameters // ================================= /** * Config parameter name for the TTL (time to live). * It is a constant holding the number of rounds for which each event needs to be relayed during its dissemination. * @config */ private static final String PAR_TTL = "ttl"; // ================================= // Parameters // ================================= /** * The id of this protocol in the protocol array */ public static int PID = 0; /** * The number of rounds for which each event needs to be relayed during its dissemination */ private final int TTL; /** * A received map of (id, event) pairs with all known but not yet delivered events */ private HashMap<UUID, Event> received = new HashMap<UUID, Event>(); /** * A delivered set with all the events already delivered to the application */ private HashSet<UUID> delivered = new HashSet<UUID>(); /** * The timestamp of the last event delivered */ private int lastDeliveredTimestamp = 0; // ================================= // Constructor implementation // ================================= public EpTOOrdering(String prefix) { PID = Configuration.lookupPid(prefix.replace("protocol.",""));
// Path: src/main/java/epto/utils/Ball.java // public class Ball extends HashMap<UUID, Event> { // // } // // Path: src/main/java/epto/utils/Event.java // public class Event implements Comparable<Event>{ // // public UUID id; // // public LogicalClock timestamp; // // public int ttl; // // public long sourceId; // // public Event() { // id = UUID.randomUUID(); // } // // public int compareTo(Event o) { // int comparisionLC = timestamp.compareTo(o.timestamp); // return (comparisionLC != 0)? comparisionLC : (int)(sourceId - o.sourceId); // } // // @Override // public String toString() { // return "{timestamp=" + timestamp + ", ttl=" + ttl + ", sourceId=" + sourceId + "}"; // } // } // // Path: src/main/java/epto/utils/Message.java // public class Message { // // public final static int PREBROADCAST = 0; // public final static int BROADCAST = 1; // public final static int DELIVER = 2; // public final static int DISSEMINATION = 3; // public final static int ORDER = 4; // // private int type; // private Object content; // // private Node source; // // private Node destination; // // public Message(int type, Object content) { // this.type = type; // this.content = content; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public Object getContent() { // return content; // } // // public void setContent(Object content) { // this.content = content; // } // // // public Node getSource() { // // return source; // // } // // // // public void setSource(Node source) { // // this.source = source; // // } // // // // public Node getDestination() { // // return destination; // // } // // // // public void setDestination(Node destination) { // // this.destination = destination; // // } // } // // Path: src/main/java/epto/utils/Utils.java // public class Utils { // // public static final int DEFAULT_FANOUT = 5; // // public static final int DEFAULT_TTL = 2; // } // Path: src/main/java/epto/EpTOOrdering.java import epto.utils.Ball; import epto.utils.Event; import epto.utils.Message; import epto.utils.Utils; import peersim.config.Configuration; import peersim.core.Node; import peersim.edsim.EDProtocol; import peersim.edsim.EDSimulator; import java.util.*; package epto; /** * The EpTO ordering component */ public class EpTOOrdering implements EDProtocol, EpTODeliverer { // ================================= // Configuration Parameters // ================================= /** * Config parameter name for the TTL (time to live). * It is a constant holding the number of rounds for which each event needs to be relayed during its dissemination. * @config */ private static final String PAR_TTL = "ttl"; // ================================= // Parameters // ================================= /** * The id of this protocol in the protocol array */ public static int PID = 0; /** * The number of rounds for which each event needs to be relayed during its dissemination */ private final int TTL; /** * A received map of (id, event) pairs with all known but not yet delivered events */ private HashMap<UUID, Event> received = new HashMap<UUID, Event>(); /** * A delivered set with all the events already delivered to the application */ private HashSet<UUID> delivered = new HashSet<UUID>(); /** * The timestamp of the last event delivered */ private int lastDeliveredTimestamp = 0; // ================================= // Constructor implementation // ================================= public EpTOOrdering(String prefix) { PID = Configuration.lookupPid(prefix.replace("protocol.",""));
TTL = Configuration.getInt(prefix + "." + PAR_TTL, Utils.DEFAULT_TTL);
robzenn92/peersimTutorial
src/main/java/epto/EpTOOrdering.java
// Path: src/main/java/epto/utils/Ball.java // public class Ball extends HashMap<UUID, Event> { // // } // // Path: src/main/java/epto/utils/Event.java // public class Event implements Comparable<Event>{ // // public UUID id; // // public LogicalClock timestamp; // // public int ttl; // // public long sourceId; // // public Event() { // id = UUID.randomUUID(); // } // // public int compareTo(Event o) { // int comparisionLC = timestamp.compareTo(o.timestamp); // return (comparisionLC != 0)? comparisionLC : (int)(sourceId - o.sourceId); // } // // @Override // public String toString() { // return "{timestamp=" + timestamp + ", ttl=" + ttl + ", sourceId=" + sourceId + "}"; // } // } // // Path: src/main/java/epto/utils/Message.java // public class Message { // // public final static int PREBROADCAST = 0; // public final static int BROADCAST = 1; // public final static int DELIVER = 2; // public final static int DISSEMINATION = 3; // public final static int ORDER = 4; // // private int type; // private Object content; // // private Node source; // // private Node destination; // // public Message(int type, Object content) { // this.type = type; // this.content = content; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public Object getContent() { // return content; // } // // public void setContent(Object content) { // this.content = content; // } // // // public Node getSource() { // // return source; // // } // // // // public void setSource(Node source) { // // this.source = source; // // } // // // // public Node getDestination() { // // return destination; // // } // // // // public void setDestination(Node destination) { // // this.destination = destination; // // } // } // // Path: src/main/java/epto/utils/Utils.java // public class Utils { // // public static final int DEFAULT_FANOUT = 5; // // public static final int DEFAULT_TTL = 2; // }
import epto.utils.Ball; import epto.utils.Event; import epto.utils.Message; import epto.utils.Utils; import peersim.config.Configuration; import peersim.core.Node; import peersim.edsim.EDProtocol; import peersim.edsim.EDSimulator; import java.util.*;
package epto; /** * The EpTO ordering component */ public class EpTOOrdering implements EDProtocol, EpTODeliverer { // ================================= // Configuration Parameters // ================================= /** * Config parameter name for the TTL (time to live). * It is a constant holding the number of rounds for which each event needs to be relayed during its dissemination. * @config */ private static final String PAR_TTL = "ttl"; // ================================= // Parameters // ================================= /** * The id of this protocol in the protocol array */ public static int PID = 0; /** * The number of rounds for which each event needs to be relayed during its dissemination */ private final int TTL; /** * A received map of (id, event) pairs with all known but not yet delivered events */ private HashMap<UUID, Event> received = new HashMap<UUID, Event>(); /** * A delivered set with all the events already delivered to the application */ private HashSet<UUID> delivered = new HashSet<UUID>(); /** * The timestamp of the last event delivered */ private int lastDeliveredTimestamp = 0; // ================================= // Constructor implementation // ================================= public EpTOOrdering(String prefix) { PID = Configuration.lookupPid(prefix.replace("protocol.","")); TTL = Configuration.getInt(prefix + "." + PAR_TTL, Utils.DEFAULT_TTL); received.clear(); delivered.clear(); } /** * Procedure orderEvents is called every round (line 27 of Al- gorithm 1) and its goal is to deliver events * to the application (Algorithm 2, line 30) via the deliver function. * * To do so, each process p maintains a received map of (id, event) pairs with all known but not yet delivered events * and a delivered set with all the events already delivered to the application. * * The main task of this procedure is to move events from the received set to the delivered set, * preserving the total order of the events. This is done in several steps as follows. * * We start by incrementing the ttl of all events previously received (lines 6–7) to indicate the start of a new round. * * @param ball - a ball EpTO sent by another peer */
// Path: src/main/java/epto/utils/Ball.java // public class Ball extends HashMap<UUID, Event> { // // } // // Path: src/main/java/epto/utils/Event.java // public class Event implements Comparable<Event>{ // // public UUID id; // // public LogicalClock timestamp; // // public int ttl; // // public long sourceId; // // public Event() { // id = UUID.randomUUID(); // } // // public int compareTo(Event o) { // int comparisionLC = timestamp.compareTo(o.timestamp); // return (comparisionLC != 0)? comparisionLC : (int)(sourceId - o.sourceId); // } // // @Override // public String toString() { // return "{timestamp=" + timestamp + ", ttl=" + ttl + ", sourceId=" + sourceId + "}"; // } // } // // Path: src/main/java/epto/utils/Message.java // public class Message { // // public final static int PREBROADCAST = 0; // public final static int BROADCAST = 1; // public final static int DELIVER = 2; // public final static int DISSEMINATION = 3; // public final static int ORDER = 4; // // private int type; // private Object content; // // private Node source; // // private Node destination; // // public Message(int type, Object content) { // this.type = type; // this.content = content; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public Object getContent() { // return content; // } // // public void setContent(Object content) { // this.content = content; // } // // // public Node getSource() { // // return source; // // } // // // // public void setSource(Node source) { // // this.source = source; // // } // // // // public Node getDestination() { // // return destination; // // } // // // // public void setDestination(Node destination) { // // this.destination = destination; // // } // } // // Path: src/main/java/epto/utils/Utils.java // public class Utils { // // public static final int DEFAULT_FANOUT = 5; // // public static final int DEFAULT_TTL = 2; // } // Path: src/main/java/epto/EpTOOrdering.java import epto.utils.Ball; import epto.utils.Event; import epto.utils.Message; import epto.utils.Utils; import peersim.config.Configuration; import peersim.core.Node; import peersim.edsim.EDProtocol; import peersim.edsim.EDSimulator; import java.util.*; package epto; /** * The EpTO ordering component */ public class EpTOOrdering implements EDProtocol, EpTODeliverer { // ================================= // Configuration Parameters // ================================= /** * Config parameter name for the TTL (time to live). * It is a constant holding the number of rounds for which each event needs to be relayed during its dissemination. * @config */ private static final String PAR_TTL = "ttl"; // ================================= // Parameters // ================================= /** * The id of this protocol in the protocol array */ public static int PID = 0; /** * The number of rounds for which each event needs to be relayed during its dissemination */ private final int TTL; /** * A received map of (id, event) pairs with all known but not yet delivered events */ private HashMap<UUID, Event> received = new HashMap<UUID, Event>(); /** * A delivered set with all the events already delivered to the application */ private HashSet<UUID> delivered = new HashSet<UUID>(); /** * The timestamp of the last event delivered */ private int lastDeliveredTimestamp = 0; // ================================= // Constructor implementation // ================================= public EpTOOrdering(String prefix) { PID = Configuration.lookupPid(prefix.replace("protocol.","")); TTL = Configuration.getInt(prefix + "." + PAR_TTL, Utils.DEFAULT_TTL); received.clear(); delivered.clear(); } /** * Procedure orderEvents is called every round (line 27 of Al- gorithm 1) and its goal is to deliver events * to the application (Algorithm 2, line 30) via the deliver function. * * To do so, each process p maintains a received map of (id, event) pairs with all known but not yet delivered events * and a delivered set with all the events already delivered to the application. * * The main task of this procedure is to move events from the received set to the delivered set, * preserving the total order of the events. This is done in several steps as follows. * * We start by incrementing the ttl of all events previously received (lines 6–7) to indicate the start of a new round. * * @param ball - a ball EpTO sent by another peer */
public void orderEvents(Ball ball, Node node) {
robzenn92/peersimTutorial
src/main/java/epto/EpTOOrdering.java
// Path: src/main/java/epto/utils/Ball.java // public class Ball extends HashMap<UUID, Event> { // // } // // Path: src/main/java/epto/utils/Event.java // public class Event implements Comparable<Event>{ // // public UUID id; // // public LogicalClock timestamp; // // public int ttl; // // public long sourceId; // // public Event() { // id = UUID.randomUUID(); // } // // public int compareTo(Event o) { // int comparisionLC = timestamp.compareTo(o.timestamp); // return (comparisionLC != 0)? comparisionLC : (int)(sourceId - o.sourceId); // } // // @Override // public String toString() { // return "{timestamp=" + timestamp + ", ttl=" + ttl + ", sourceId=" + sourceId + "}"; // } // } // // Path: src/main/java/epto/utils/Message.java // public class Message { // // public final static int PREBROADCAST = 0; // public final static int BROADCAST = 1; // public final static int DELIVER = 2; // public final static int DISSEMINATION = 3; // public final static int ORDER = 4; // // private int type; // private Object content; // // private Node source; // // private Node destination; // // public Message(int type, Object content) { // this.type = type; // this.content = content; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public Object getContent() { // return content; // } // // public void setContent(Object content) { // this.content = content; // } // // // public Node getSource() { // // return source; // // } // // // // public void setSource(Node source) { // // this.source = source; // // } // // // // public Node getDestination() { // // return destination; // // } // // // // public void setDestination(Node destination) { // // this.destination = destination; // // } // } // // Path: src/main/java/epto/utils/Utils.java // public class Utils { // // public static final int DEFAULT_FANOUT = 5; // // public static final int DEFAULT_TTL = 2; // }
import epto.utils.Ball; import epto.utils.Event; import epto.utils.Message; import epto.utils.Utils; import peersim.config.Configuration; import peersim.core.Node; import peersim.edsim.EDProtocol; import peersim.edsim.EDSimulator; import java.util.*;
private ArrayList<Event> sortEvents(HashMap<UUID, Event> events) { ArrayList<Event> sorted = new ArrayList<Event>(events.size()); sorted.addAll(events.values()); Collections.sort(sorted, new Comparator<Event>() { public int compare(Event o1, Event o2) { return o1.compareTo(o2); } }); return sorted; } public Object clone() { EpTOOrdering ordering = null; try { ordering = (EpTOOrdering) super.clone(); ordering.received = new HashMap<UUID, Event>(); ordering.delivered = new HashSet<UUID>(); ordering.lastDeliveredTimestamp = 0; } catch (CloneNotSupportedException e) { e.printStackTrace(); } return ordering; } // TODO: deliver event to the application public void EpTODeliver(Event event, Node node) {
// Path: src/main/java/epto/utils/Ball.java // public class Ball extends HashMap<UUID, Event> { // // } // // Path: src/main/java/epto/utils/Event.java // public class Event implements Comparable<Event>{ // // public UUID id; // // public LogicalClock timestamp; // // public int ttl; // // public long sourceId; // // public Event() { // id = UUID.randomUUID(); // } // // public int compareTo(Event o) { // int comparisionLC = timestamp.compareTo(o.timestamp); // return (comparisionLC != 0)? comparisionLC : (int)(sourceId - o.sourceId); // } // // @Override // public String toString() { // return "{timestamp=" + timestamp + ", ttl=" + ttl + ", sourceId=" + sourceId + "}"; // } // } // // Path: src/main/java/epto/utils/Message.java // public class Message { // // public final static int PREBROADCAST = 0; // public final static int BROADCAST = 1; // public final static int DELIVER = 2; // public final static int DISSEMINATION = 3; // public final static int ORDER = 4; // // private int type; // private Object content; // // private Node source; // // private Node destination; // // public Message(int type, Object content) { // this.type = type; // this.content = content; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public Object getContent() { // return content; // } // // public void setContent(Object content) { // this.content = content; // } // // // public Node getSource() { // // return source; // // } // // // // public void setSource(Node source) { // // this.source = source; // // } // // // // public Node getDestination() { // // return destination; // // } // // // // public void setDestination(Node destination) { // // this.destination = destination; // // } // } // // Path: src/main/java/epto/utils/Utils.java // public class Utils { // // public static final int DEFAULT_FANOUT = 5; // // public static final int DEFAULT_TTL = 2; // } // Path: src/main/java/epto/EpTOOrdering.java import epto.utils.Ball; import epto.utils.Event; import epto.utils.Message; import epto.utils.Utils; import peersim.config.Configuration; import peersim.core.Node; import peersim.edsim.EDProtocol; import peersim.edsim.EDSimulator; import java.util.*; private ArrayList<Event> sortEvents(HashMap<UUID, Event> events) { ArrayList<Event> sorted = new ArrayList<Event>(events.size()); sorted.addAll(events.values()); Collections.sort(sorted, new Comparator<Event>() { public int compare(Event o1, Event o2) { return o1.compareTo(o2); } }); return sorted; } public Object clone() { EpTOOrdering ordering = null; try { ordering = (EpTOOrdering) super.clone(); ordering.received = new HashMap<UUID, Event>(); ordering.delivered = new HashSet<UUID>(); ordering.lastDeliveredTimestamp = 0; } catch (CloneNotSupportedException e) { e.printStackTrace(); } return ordering; } // TODO: deliver event to the application public void EpTODeliver(Event event, Node node) {
Message m = new Message(Message.DELIVER, event);
robzenn92/peersimTutorial
src/main/java/epto/utils/Event.java
// Path: src/main/java/time/LogicalClock.java // public class LogicalClock implements Comparable<LogicalClock> { // // private long nodeId; // private int eventId; // // public LogicalClock(long nodeId) { // this.nodeId = nodeId; // this.eventId = 0; // } // // public LogicalClock(long nodeId, int eventId) { // this(nodeId); // this.eventId = eventId; // } // // public void increment() { // this.eventId++; // } // // public long getNodeId() { // return nodeId; // } // // public void setNodeId(long nodeId) { // this.nodeId = nodeId; // } // // public int getEventId() { // return eventId; // } // // public void setEventId(int eventId) { // this.eventId = eventId; // } // // public int compareTo(LogicalClock o) { // return (nodeId == o.nodeId)? eventId - o.eventId : (int) nodeId - (int) o.nodeId; // } // // @Override // public String toString() { // return "{nodeId=" + nodeId + ", eventId=" + eventId + "}"; // } // // @Override // public LogicalClock clone() throws CloneNotSupportedException { // return new LogicalClock(nodeId, eventId); // } // }
import peersim.core.CommonState; import time.LogicalClock; import java.util.UUID;
package epto.utils; public class Event implements Comparable<Event>{ public UUID id;
// Path: src/main/java/time/LogicalClock.java // public class LogicalClock implements Comparable<LogicalClock> { // // private long nodeId; // private int eventId; // // public LogicalClock(long nodeId) { // this.nodeId = nodeId; // this.eventId = 0; // } // // public LogicalClock(long nodeId, int eventId) { // this(nodeId); // this.eventId = eventId; // } // // public void increment() { // this.eventId++; // } // // public long getNodeId() { // return nodeId; // } // // public void setNodeId(long nodeId) { // this.nodeId = nodeId; // } // // public int getEventId() { // return eventId; // } // // public void setEventId(int eventId) { // this.eventId = eventId; // } // // public int compareTo(LogicalClock o) { // return (nodeId == o.nodeId)? eventId - o.eventId : (int) nodeId - (int) o.nodeId; // } // // @Override // public String toString() { // return "{nodeId=" + nodeId + ", eventId=" + eventId + "}"; // } // // @Override // public LogicalClock clone() throws CloneNotSupportedException { // return new LogicalClock(nodeId, eventId); // } // } // Path: src/main/java/epto/utils/Event.java import peersim.core.CommonState; import time.LogicalClock; import java.util.UUID; package epto.utils; public class Event implements Comparable<Event>{ public UUID id;
public LogicalClock timestamp;
malteseduck/sonar-xquery-plugin
src/main/java/org/sonar/plugins/xquery/parser/AbstractXQueryParser.java
// Path: src/main/java/org/sonar/plugins/xquery/parser/reporter/ProblemReporter.java // public class ProblemReporter { // // private boolean failOnError; // private boolean outputError; // // private List<Problem> problems; // // public ProblemReporter() { // this(false); // } // // public ProblemReporter(boolean failOnError) { // this.failOnError = failOnError; // this.outputError = true; // problems = new ArrayList<Problem>(); // } // // public List<Problem> getProblems() { // return problems; // } // // public boolean isFailOnError() { // return failOnError; // } // // public boolean isOutputError() { // return outputError; // } // // public void reportError(String id, String message, Token token) { // Problem problem = new Problem(id, message, token); // problems.add(problem); // if (failOnError) { // throw new RuntimeException(problem.getMessageString()); // } else if (outputError) { // System.err.println(problem.getId() + problem.getMessageString()); // } // } // // public void setFailOnError(boolean failOnError) { // this.failOnError = failOnError; // } // // public void setOutputError(boolean outputError) { // this.outputError = outputError; // } // }
import java.util.List; import org.antlr.runtime.*; import org.sonar.plugins.xquery.parser.reporter.ProblemReporter; import java.util.ArrayList;
/* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ /******************************************************************************* * Copyright (c) 2008, 2009 28msec Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Gabriel Petrovay (28msec) - initial API and implementation * * Modified * Chris Cieslinski *******************************************************************************/ package org.sonar.plugins.xquery.parser; public abstract class AbstractXQueryParser extends Parser implements XQueryLanguageConstants { private final LazyTokenStream stream; private ANTLRStringStream source; private ArrayList<AbstractXQueryLexer> lexerStack; private int language;
// Path: src/main/java/org/sonar/plugins/xquery/parser/reporter/ProblemReporter.java // public class ProblemReporter { // // private boolean failOnError; // private boolean outputError; // // private List<Problem> problems; // // public ProblemReporter() { // this(false); // } // // public ProblemReporter(boolean failOnError) { // this.failOnError = failOnError; // this.outputError = true; // problems = new ArrayList<Problem>(); // } // // public List<Problem> getProblems() { // return problems; // } // // public boolean isFailOnError() { // return failOnError; // } // // public boolean isOutputError() { // return outputError; // } // // public void reportError(String id, String message, Token token) { // Problem problem = new Problem(id, message, token); // problems.add(problem); // if (failOnError) { // throw new RuntimeException(problem.getMessageString()); // } else if (outputError) { // System.err.println(problem.getId() + problem.getMessageString()); // } // } // // public void setFailOnError(boolean failOnError) { // this.failOnError = failOnError; // } // // public void setOutputError(boolean outputError) { // this.outputError = outputError; // } // } // Path: src/main/java/org/sonar/plugins/xquery/parser/AbstractXQueryParser.java import java.util.List; import org.antlr.runtime.*; import org.sonar.plugins.xquery.parser.reporter.ProblemReporter; import java.util.ArrayList; /* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ /******************************************************************************* * Copyright (c) 2008, 2009 28msec Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Gabriel Petrovay (28msec) - initial API and implementation * * Modified * Chris Cieslinski *******************************************************************************/ package org.sonar.plugins.xquery.parser; public abstract class AbstractXQueryParser extends Parser implements XQueryLanguageConstants { private final LazyTokenStream stream; private ANTLRStringStream source; private ArrayList<AbstractXQueryLexer> lexerStack; private int language;
private ProblemReporter reporter;
malteseduck/sonar-xquery-plugin
src/main/java/org/sonar/plugins/xquery/language/XQueryCodeColorizerFormat.java
// Path: src/main/java/org/sonar/plugins/xquery/api/XQueryConstants.java // public interface XQueryConstants { // static String XQUERY_LANGUAGE_KEY = "xquery"; // static String FILE_EXTENSIONS_KEY = "sonar.xquery.fileExtensions"; // static String SOURCE_DIRECTORY_KEY = "sonar.xquery.sourceDirectory"; // static String XQTEST_REPORTS_DIRECTORY_KEY = "sonar.xqtest.reportsPath"; // // static String XQUERY_LANGUAGE_NAME = "XQuery"; // static String[] DEFAULT_FILE_EXTENSIONS = {"xqy", "xquery", "xq", "xqi", "xql", "xqm", "xqws"}; // static String DEFAULT_FILE_EXTENSIONS_STRING = "xqy, xquery, xq, xqi, xql, xqm, xqws"; // static String DEFAULT_SOURCE_DIRECTORY = "src/main/xquery"; // static String DEFAULT_XQTEST_DIRECTORY = "target/xqtest-reports"; // } // // Path: src/main/java/org/sonar/plugins/xquery/language/XQuery.java // static final String[] KEYWORDS_ARRAY = new String[]{"xquery", "where", "version", "variable", "union", // "typeswitch", "treat", "to", "then", "text", "stable", "sortby", "some", "self", "schema", "satisfies", // "returns", "return", "ref", "processing-instruction", "preceding-sibling", "preceding", "precedes", // "parent", "only", "of", "node", "namespace", "module", "let", "item", "intersect", "instance", "in", // "import", "if", "function", "for", "follows", "following-sibling", "following", "external", "except", // "every", "else", "element", "descending", "descendant-or-self", "descendant", "define", "default", // "declare", "comment", "child", "cast", "case", "before", "attribute", "assert", "ascending", "as", // "ancestor-or-self", "ancestor", "after"}; // // Path: src/main/java/org/sonar/plugins/xquery/language/XQuery.java // static final String[] TYPES_ARRAY = new String[]{"xs:yearMonthDuration", "xs:unsignedLong", "xs:time", // "xs:string", "xs:short", "xs:QName", "xs:Name", "xs:long", "xs:integer", "xs:int", "xs:gYearMonth", // "xs:gYear", "xs:gMonthDay", "xs:gDay", "xs:float", "xs:duration", "xs:double", "xs:decimal", // "xs:dayTimeDuration", "xs:dateTime", "xs:date", "xs:byte", "xs:boolean", "xs:anyURI", // "xf:yearMonthDuration"};
import org.sonar.api.web.CodeColorizerFormat; import org.sonar.colorizer.KeywordsTokenizer; import org.sonar.colorizer.RegexpTokenizer; import org.sonar.colorizer.StringTokenizer; import org.sonar.colorizer.Tokenizer; import org.sonar.plugins.xquery.api.XQueryConstants; import java.util.*; import static org.sonar.plugins.xquery.language.XQuery.KEYWORDS_ARRAY; import static org.sonar.plugins.xquery.language.XQuery.TYPES_ARRAY;
/* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.language; public class XQueryCodeColorizerFormat extends CodeColorizerFormat { private final List<Tokenizer> tokenizers = new ArrayList<Tokenizer>(); private static final Set<String> KEYWORDS = new HashSet<String>(); private static final Set<String> TYPES = new HashSet<String>(); static {
// Path: src/main/java/org/sonar/plugins/xquery/api/XQueryConstants.java // public interface XQueryConstants { // static String XQUERY_LANGUAGE_KEY = "xquery"; // static String FILE_EXTENSIONS_KEY = "sonar.xquery.fileExtensions"; // static String SOURCE_DIRECTORY_KEY = "sonar.xquery.sourceDirectory"; // static String XQTEST_REPORTS_DIRECTORY_KEY = "sonar.xqtest.reportsPath"; // // static String XQUERY_LANGUAGE_NAME = "XQuery"; // static String[] DEFAULT_FILE_EXTENSIONS = {"xqy", "xquery", "xq", "xqi", "xql", "xqm", "xqws"}; // static String DEFAULT_FILE_EXTENSIONS_STRING = "xqy, xquery, xq, xqi, xql, xqm, xqws"; // static String DEFAULT_SOURCE_DIRECTORY = "src/main/xquery"; // static String DEFAULT_XQTEST_DIRECTORY = "target/xqtest-reports"; // } // // Path: src/main/java/org/sonar/plugins/xquery/language/XQuery.java // static final String[] KEYWORDS_ARRAY = new String[]{"xquery", "where", "version", "variable", "union", // "typeswitch", "treat", "to", "then", "text", "stable", "sortby", "some", "self", "schema", "satisfies", // "returns", "return", "ref", "processing-instruction", "preceding-sibling", "preceding", "precedes", // "parent", "only", "of", "node", "namespace", "module", "let", "item", "intersect", "instance", "in", // "import", "if", "function", "for", "follows", "following-sibling", "following", "external", "except", // "every", "else", "element", "descending", "descendant-or-self", "descendant", "define", "default", // "declare", "comment", "child", "cast", "case", "before", "attribute", "assert", "ascending", "as", // "ancestor-or-self", "ancestor", "after"}; // // Path: src/main/java/org/sonar/plugins/xquery/language/XQuery.java // static final String[] TYPES_ARRAY = new String[]{"xs:yearMonthDuration", "xs:unsignedLong", "xs:time", // "xs:string", "xs:short", "xs:QName", "xs:Name", "xs:long", "xs:integer", "xs:int", "xs:gYearMonth", // "xs:gYear", "xs:gMonthDay", "xs:gDay", "xs:float", "xs:duration", "xs:double", "xs:decimal", // "xs:dayTimeDuration", "xs:dateTime", "xs:date", "xs:byte", "xs:boolean", "xs:anyURI", // "xf:yearMonthDuration"}; // Path: src/main/java/org/sonar/plugins/xquery/language/XQueryCodeColorizerFormat.java import org.sonar.api.web.CodeColorizerFormat; import org.sonar.colorizer.KeywordsTokenizer; import org.sonar.colorizer.RegexpTokenizer; import org.sonar.colorizer.StringTokenizer; import org.sonar.colorizer.Tokenizer; import org.sonar.plugins.xquery.api.XQueryConstants; import java.util.*; import static org.sonar.plugins.xquery.language.XQuery.KEYWORDS_ARRAY; import static org.sonar.plugins.xquery.language.XQuery.TYPES_ARRAY; /* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.language; public class XQueryCodeColorizerFormat extends CodeColorizerFormat { private final List<Tokenizer> tokenizers = new ArrayList<Tokenizer>(); private static final Set<String> KEYWORDS = new HashSet<String>(); private static final Set<String> TYPES = new HashSet<String>(); static {
Collections.addAll(KEYWORDS, KEYWORDS_ARRAY);
malteseduck/sonar-xquery-plugin
src/main/java/org/sonar/plugins/xquery/language/XQueryCodeColorizerFormat.java
// Path: src/main/java/org/sonar/plugins/xquery/api/XQueryConstants.java // public interface XQueryConstants { // static String XQUERY_LANGUAGE_KEY = "xquery"; // static String FILE_EXTENSIONS_KEY = "sonar.xquery.fileExtensions"; // static String SOURCE_DIRECTORY_KEY = "sonar.xquery.sourceDirectory"; // static String XQTEST_REPORTS_DIRECTORY_KEY = "sonar.xqtest.reportsPath"; // // static String XQUERY_LANGUAGE_NAME = "XQuery"; // static String[] DEFAULT_FILE_EXTENSIONS = {"xqy", "xquery", "xq", "xqi", "xql", "xqm", "xqws"}; // static String DEFAULT_FILE_EXTENSIONS_STRING = "xqy, xquery, xq, xqi, xql, xqm, xqws"; // static String DEFAULT_SOURCE_DIRECTORY = "src/main/xquery"; // static String DEFAULT_XQTEST_DIRECTORY = "target/xqtest-reports"; // } // // Path: src/main/java/org/sonar/plugins/xquery/language/XQuery.java // static final String[] KEYWORDS_ARRAY = new String[]{"xquery", "where", "version", "variable", "union", // "typeswitch", "treat", "to", "then", "text", "stable", "sortby", "some", "self", "schema", "satisfies", // "returns", "return", "ref", "processing-instruction", "preceding-sibling", "preceding", "precedes", // "parent", "only", "of", "node", "namespace", "module", "let", "item", "intersect", "instance", "in", // "import", "if", "function", "for", "follows", "following-sibling", "following", "external", "except", // "every", "else", "element", "descending", "descendant-or-self", "descendant", "define", "default", // "declare", "comment", "child", "cast", "case", "before", "attribute", "assert", "ascending", "as", // "ancestor-or-self", "ancestor", "after"}; // // Path: src/main/java/org/sonar/plugins/xquery/language/XQuery.java // static final String[] TYPES_ARRAY = new String[]{"xs:yearMonthDuration", "xs:unsignedLong", "xs:time", // "xs:string", "xs:short", "xs:QName", "xs:Name", "xs:long", "xs:integer", "xs:int", "xs:gYearMonth", // "xs:gYear", "xs:gMonthDay", "xs:gDay", "xs:float", "xs:duration", "xs:double", "xs:decimal", // "xs:dayTimeDuration", "xs:dateTime", "xs:date", "xs:byte", "xs:boolean", "xs:anyURI", // "xf:yearMonthDuration"};
import org.sonar.api.web.CodeColorizerFormat; import org.sonar.colorizer.KeywordsTokenizer; import org.sonar.colorizer.RegexpTokenizer; import org.sonar.colorizer.StringTokenizer; import org.sonar.colorizer.Tokenizer; import org.sonar.plugins.xquery.api.XQueryConstants; import java.util.*; import static org.sonar.plugins.xquery.language.XQuery.KEYWORDS_ARRAY; import static org.sonar.plugins.xquery.language.XQuery.TYPES_ARRAY;
/* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.language; public class XQueryCodeColorizerFormat extends CodeColorizerFormat { private final List<Tokenizer> tokenizers = new ArrayList<Tokenizer>(); private static final Set<String> KEYWORDS = new HashSet<String>(); private static final Set<String> TYPES = new HashSet<String>(); static { Collections.addAll(KEYWORDS, KEYWORDS_ARRAY);
// Path: src/main/java/org/sonar/plugins/xquery/api/XQueryConstants.java // public interface XQueryConstants { // static String XQUERY_LANGUAGE_KEY = "xquery"; // static String FILE_EXTENSIONS_KEY = "sonar.xquery.fileExtensions"; // static String SOURCE_DIRECTORY_KEY = "sonar.xquery.sourceDirectory"; // static String XQTEST_REPORTS_DIRECTORY_KEY = "sonar.xqtest.reportsPath"; // // static String XQUERY_LANGUAGE_NAME = "XQuery"; // static String[] DEFAULT_FILE_EXTENSIONS = {"xqy", "xquery", "xq", "xqi", "xql", "xqm", "xqws"}; // static String DEFAULT_FILE_EXTENSIONS_STRING = "xqy, xquery, xq, xqi, xql, xqm, xqws"; // static String DEFAULT_SOURCE_DIRECTORY = "src/main/xquery"; // static String DEFAULT_XQTEST_DIRECTORY = "target/xqtest-reports"; // } // // Path: src/main/java/org/sonar/plugins/xquery/language/XQuery.java // static final String[] KEYWORDS_ARRAY = new String[]{"xquery", "where", "version", "variable", "union", // "typeswitch", "treat", "to", "then", "text", "stable", "sortby", "some", "self", "schema", "satisfies", // "returns", "return", "ref", "processing-instruction", "preceding-sibling", "preceding", "precedes", // "parent", "only", "of", "node", "namespace", "module", "let", "item", "intersect", "instance", "in", // "import", "if", "function", "for", "follows", "following-sibling", "following", "external", "except", // "every", "else", "element", "descending", "descendant-or-self", "descendant", "define", "default", // "declare", "comment", "child", "cast", "case", "before", "attribute", "assert", "ascending", "as", // "ancestor-or-self", "ancestor", "after"}; // // Path: src/main/java/org/sonar/plugins/xquery/language/XQuery.java // static final String[] TYPES_ARRAY = new String[]{"xs:yearMonthDuration", "xs:unsignedLong", "xs:time", // "xs:string", "xs:short", "xs:QName", "xs:Name", "xs:long", "xs:integer", "xs:int", "xs:gYearMonth", // "xs:gYear", "xs:gMonthDay", "xs:gDay", "xs:float", "xs:duration", "xs:double", "xs:decimal", // "xs:dayTimeDuration", "xs:dateTime", "xs:date", "xs:byte", "xs:boolean", "xs:anyURI", // "xf:yearMonthDuration"}; // Path: src/main/java/org/sonar/plugins/xquery/language/XQueryCodeColorizerFormat.java import org.sonar.api.web.CodeColorizerFormat; import org.sonar.colorizer.KeywordsTokenizer; import org.sonar.colorizer.RegexpTokenizer; import org.sonar.colorizer.StringTokenizer; import org.sonar.colorizer.Tokenizer; import org.sonar.plugins.xquery.api.XQueryConstants; import java.util.*; import static org.sonar.plugins.xquery.language.XQuery.KEYWORDS_ARRAY; import static org.sonar.plugins.xquery.language.XQuery.TYPES_ARRAY; /* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.language; public class XQueryCodeColorizerFormat extends CodeColorizerFormat { private final List<Tokenizer> tokenizers = new ArrayList<Tokenizer>(); private static final Set<String> KEYWORDS = new HashSet<String>(); private static final Set<String> TYPES = new HashSet<String>(); static { Collections.addAll(KEYWORDS, KEYWORDS_ARRAY);
Collections.addAll(TYPES, TYPES_ARRAY);
malteseduck/sonar-xquery-plugin
src/main/java/org/sonar/plugins/xquery/language/XQueryCodeColorizerFormat.java
// Path: src/main/java/org/sonar/plugins/xquery/api/XQueryConstants.java // public interface XQueryConstants { // static String XQUERY_LANGUAGE_KEY = "xquery"; // static String FILE_EXTENSIONS_KEY = "sonar.xquery.fileExtensions"; // static String SOURCE_DIRECTORY_KEY = "sonar.xquery.sourceDirectory"; // static String XQTEST_REPORTS_DIRECTORY_KEY = "sonar.xqtest.reportsPath"; // // static String XQUERY_LANGUAGE_NAME = "XQuery"; // static String[] DEFAULT_FILE_EXTENSIONS = {"xqy", "xquery", "xq", "xqi", "xql", "xqm", "xqws"}; // static String DEFAULT_FILE_EXTENSIONS_STRING = "xqy, xquery, xq, xqi, xql, xqm, xqws"; // static String DEFAULT_SOURCE_DIRECTORY = "src/main/xquery"; // static String DEFAULT_XQTEST_DIRECTORY = "target/xqtest-reports"; // } // // Path: src/main/java/org/sonar/plugins/xquery/language/XQuery.java // static final String[] KEYWORDS_ARRAY = new String[]{"xquery", "where", "version", "variable", "union", // "typeswitch", "treat", "to", "then", "text", "stable", "sortby", "some", "self", "schema", "satisfies", // "returns", "return", "ref", "processing-instruction", "preceding-sibling", "preceding", "precedes", // "parent", "only", "of", "node", "namespace", "module", "let", "item", "intersect", "instance", "in", // "import", "if", "function", "for", "follows", "following-sibling", "following", "external", "except", // "every", "else", "element", "descending", "descendant-or-self", "descendant", "define", "default", // "declare", "comment", "child", "cast", "case", "before", "attribute", "assert", "ascending", "as", // "ancestor-or-self", "ancestor", "after"}; // // Path: src/main/java/org/sonar/plugins/xquery/language/XQuery.java // static final String[] TYPES_ARRAY = new String[]{"xs:yearMonthDuration", "xs:unsignedLong", "xs:time", // "xs:string", "xs:short", "xs:QName", "xs:Name", "xs:long", "xs:integer", "xs:int", "xs:gYearMonth", // "xs:gYear", "xs:gMonthDay", "xs:gDay", "xs:float", "xs:duration", "xs:double", "xs:decimal", // "xs:dayTimeDuration", "xs:dateTime", "xs:date", "xs:byte", "xs:boolean", "xs:anyURI", // "xf:yearMonthDuration"};
import org.sonar.api.web.CodeColorizerFormat; import org.sonar.colorizer.KeywordsTokenizer; import org.sonar.colorizer.RegexpTokenizer; import org.sonar.colorizer.StringTokenizer; import org.sonar.colorizer.Tokenizer; import org.sonar.plugins.xquery.api.XQueryConstants; import java.util.*; import static org.sonar.plugins.xquery.language.XQuery.KEYWORDS_ARRAY; import static org.sonar.plugins.xquery.language.XQuery.TYPES_ARRAY;
/* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.language; public class XQueryCodeColorizerFormat extends CodeColorizerFormat { private final List<Tokenizer> tokenizers = new ArrayList<Tokenizer>(); private static final Set<String> KEYWORDS = new HashSet<String>(); private static final Set<String> TYPES = new HashSet<String>(); static { Collections.addAll(KEYWORDS, KEYWORDS_ARRAY); Collections.addAll(TYPES, TYPES_ARRAY); } /* * Style Classes for colors: * a: annotations (tan bold) * k: keywords (blue bold) * c: global statics? (purple italic) * s: string (green bold) * j: javascript (grey) * cd: (grey) * cppd: (grey) * h: (blue) * p: (green) */ public XQueryCodeColorizerFormat() {
// Path: src/main/java/org/sonar/plugins/xquery/api/XQueryConstants.java // public interface XQueryConstants { // static String XQUERY_LANGUAGE_KEY = "xquery"; // static String FILE_EXTENSIONS_KEY = "sonar.xquery.fileExtensions"; // static String SOURCE_DIRECTORY_KEY = "sonar.xquery.sourceDirectory"; // static String XQTEST_REPORTS_DIRECTORY_KEY = "sonar.xqtest.reportsPath"; // // static String XQUERY_LANGUAGE_NAME = "XQuery"; // static String[] DEFAULT_FILE_EXTENSIONS = {"xqy", "xquery", "xq", "xqi", "xql", "xqm", "xqws"}; // static String DEFAULT_FILE_EXTENSIONS_STRING = "xqy, xquery, xq, xqi, xql, xqm, xqws"; // static String DEFAULT_SOURCE_DIRECTORY = "src/main/xquery"; // static String DEFAULT_XQTEST_DIRECTORY = "target/xqtest-reports"; // } // // Path: src/main/java/org/sonar/plugins/xquery/language/XQuery.java // static final String[] KEYWORDS_ARRAY = new String[]{"xquery", "where", "version", "variable", "union", // "typeswitch", "treat", "to", "then", "text", "stable", "sortby", "some", "self", "schema", "satisfies", // "returns", "return", "ref", "processing-instruction", "preceding-sibling", "preceding", "precedes", // "parent", "only", "of", "node", "namespace", "module", "let", "item", "intersect", "instance", "in", // "import", "if", "function", "for", "follows", "following-sibling", "following", "external", "except", // "every", "else", "element", "descending", "descendant-or-self", "descendant", "define", "default", // "declare", "comment", "child", "cast", "case", "before", "attribute", "assert", "ascending", "as", // "ancestor-or-self", "ancestor", "after"}; // // Path: src/main/java/org/sonar/plugins/xquery/language/XQuery.java // static final String[] TYPES_ARRAY = new String[]{"xs:yearMonthDuration", "xs:unsignedLong", "xs:time", // "xs:string", "xs:short", "xs:QName", "xs:Name", "xs:long", "xs:integer", "xs:int", "xs:gYearMonth", // "xs:gYear", "xs:gMonthDay", "xs:gDay", "xs:float", "xs:duration", "xs:double", "xs:decimal", // "xs:dayTimeDuration", "xs:dateTime", "xs:date", "xs:byte", "xs:boolean", "xs:anyURI", // "xf:yearMonthDuration"}; // Path: src/main/java/org/sonar/plugins/xquery/language/XQueryCodeColorizerFormat.java import org.sonar.api.web.CodeColorizerFormat; import org.sonar.colorizer.KeywordsTokenizer; import org.sonar.colorizer.RegexpTokenizer; import org.sonar.colorizer.StringTokenizer; import org.sonar.colorizer.Tokenizer; import org.sonar.plugins.xquery.api.XQueryConstants; import java.util.*; import static org.sonar.plugins.xquery.language.XQuery.KEYWORDS_ARRAY; import static org.sonar.plugins.xquery.language.XQuery.TYPES_ARRAY; /* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.language; public class XQueryCodeColorizerFormat extends CodeColorizerFormat { private final List<Tokenizer> tokenizers = new ArrayList<Tokenizer>(); private static final Set<String> KEYWORDS = new HashSet<String>(); private static final Set<String> TYPES = new HashSet<String>(); static { Collections.addAll(KEYWORDS, KEYWORDS_ARRAY); Collections.addAll(TYPES, TYPES_ARRAY); } /* * Style Classes for colors: * a: annotations (tan bold) * k: keywords (blue bold) * c: global statics? (purple italic) * s: string (green bold) * j: javascript (grey) * cd: (grey) * cppd: (grey) * h: (blue) * p: (green) */ public XQueryCodeColorizerFormat() {
super(XQueryConstants.XQUERY_LANGUAGE_KEY);
malteseduck/sonar-xquery-plugin
src/main/java/org/sonar/plugins/xquery/parser/DebugAbstractXQueryParser.java
// Path: src/main/java/org/sonar/plugins/xquery/parser/reporter/ProblemReporter.java // public class ProblemReporter { // // private boolean failOnError; // private boolean outputError; // // private List<Problem> problems; // // public ProblemReporter() { // this(false); // } // // public ProblemReporter(boolean failOnError) { // this.failOnError = failOnError; // this.outputError = true; // problems = new ArrayList<Problem>(); // } // // public List<Problem> getProblems() { // return problems; // } // // public boolean isFailOnError() { // return failOnError; // } // // public boolean isOutputError() { // return outputError; // } // // public void reportError(String id, String message, Token token) { // Problem problem = new Problem(id, message, token); // problems.add(problem); // if (failOnError) { // throw new RuntimeException(problem.getMessageString()); // } else if (outputError) { // System.err.println(problem.getId() + problem.getMessageString()); // } // } // // public void setFailOnError(boolean failOnError) { // this.failOnError = failOnError; // } // // public void setOutputError(boolean outputError) { // this.outputError = outputError; // } // }
import org.antlr.runtime.*; import org.antlr.runtime.debug.DebugEventListener; import org.antlr.runtime.debug.DebugParser; import org.sonar.plugins.xquery.parser.reporter.ProblemReporter; import java.util.ArrayList; import java.util.List;
/* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.parser; public abstract class DebugAbstractXQueryParser extends DebugParser implements XQueryLanguageConstants { private LazyTokenStream stream; private ANTLRStringStream source; private ArrayList<AbstractXQueryLexer> lexerStack; private int language;
// Path: src/main/java/org/sonar/plugins/xquery/parser/reporter/ProblemReporter.java // public class ProblemReporter { // // private boolean failOnError; // private boolean outputError; // // private List<Problem> problems; // // public ProblemReporter() { // this(false); // } // // public ProblemReporter(boolean failOnError) { // this.failOnError = failOnError; // this.outputError = true; // problems = new ArrayList<Problem>(); // } // // public List<Problem> getProblems() { // return problems; // } // // public boolean isFailOnError() { // return failOnError; // } // // public boolean isOutputError() { // return outputError; // } // // public void reportError(String id, String message, Token token) { // Problem problem = new Problem(id, message, token); // problems.add(problem); // if (failOnError) { // throw new RuntimeException(problem.getMessageString()); // } else if (outputError) { // System.err.println(problem.getId() + problem.getMessageString()); // } // } // // public void setFailOnError(boolean failOnError) { // this.failOnError = failOnError; // } // // public void setOutputError(boolean outputError) { // this.outputError = outputError; // } // } // Path: src/main/java/org/sonar/plugins/xquery/parser/DebugAbstractXQueryParser.java import org.antlr.runtime.*; import org.antlr.runtime.debug.DebugEventListener; import org.antlr.runtime.debug.DebugParser; import org.sonar.plugins.xquery.parser.reporter.ProblemReporter; import java.util.ArrayList; import java.util.List; /* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.parser; public abstract class DebugAbstractXQueryParser extends DebugParser implements XQueryLanguageConstants { private LazyTokenStream stream; private ANTLRStringStream source; private ArrayList<AbstractXQueryLexer> lexerStack; private int language;
private ProblemReporter reporter;
malteseduck/sonar-xquery-plugin
src/main/java/org/sonar/plugins/xquery/parser/AbstractXQueryLexer.java
// Path: src/main/java/org/sonar/plugins/xquery/parser/reporter/ProblemReporter.java // public class ProblemReporter { // // private boolean failOnError; // private boolean outputError; // // private List<Problem> problems; // // public ProblemReporter() { // this(false); // } // // public ProblemReporter(boolean failOnError) { // this.failOnError = failOnError; // this.outputError = true; // problems = new ArrayList<Problem>(); // } // // public List<Problem> getProblems() { // return problems; // } // // public boolean isFailOnError() { // return failOnError; // } // // public boolean isOutputError() { // return outputError; // } // // public void reportError(String id, String message, Token token) { // Problem problem = new Problem(id, message, token); // problems.add(problem); // if (failOnError) { // throw new RuntimeException(problem.getMessageString()); // } else if (outputError) { // System.err.println(problem.getId() + problem.getMessageString()); // } // } // // public void setFailOnError(boolean failOnError) { // this.failOnError = failOnError; // } // // public void setOutputError(boolean outputError) { // this.outputError = outputError; // } // }
import org.antlr.runtime.*; import org.sonar.plugins.xquery.parser.reporter.ProblemReporter; import java.util.List;
/* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ /******************************************************************************* * Copyright (c) 2008, 2009 28msec Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Gabriel Petrovay (28msec) - initial API and implementation * * Modified * Chris Cieslinski *******************************************************************************/ package org.sonar.plugins.xquery.parser; public abstract class AbstractXQueryLexer extends Lexer implements XQueryLanguageConstants { private boolean fIsWsExplicit = false; private int language;
// Path: src/main/java/org/sonar/plugins/xquery/parser/reporter/ProblemReporter.java // public class ProblemReporter { // // private boolean failOnError; // private boolean outputError; // // private List<Problem> problems; // // public ProblemReporter() { // this(false); // } // // public ProblemReporter(boolean failOnError) { // this.failOnError = failOnError; // this.outputError = true; // problems = new ArrayList<Problem>(); // } // // public List<Problem> getProblems() { // return problems; // } // // public boolean isFailOnError() { // return failOnError; // } // // public boolean isOutputError() { // return outputError; // } // // public void reportError(String id, String message, Token token) { // Problem problem = new Problem(id, message, token); // problems.add(problem); // if (failOnError) { // throw new RuntimeException(problem.getMessageString()); // } else if (outputError) { // System.err.println(problem.getId() + problem.getMessageString()); // } // } // // public void setFailOnError(boolean failOnError) { // this.failOnError = failOnError; // } // // public void setOutputError(boolean outputError) { // this.outputError = outputError; // } // } // Path: src/main/java/org/sonar/plugins/xquery/parser/AbstractXQueryLexer.java import org.antlr.runtime.*; import org.sonar.plugins.xquery.parser.reporter.ProblemReporter; import java.util.List; /* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ /******************************************************************************* * Copyright (c) 2008, 2009 28msec Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Gabriel Petrovay (28msec) - initial API and implementation * * Modified * Chris Cieslinski *******************************************************************************/ package org.sonar.plugins.xquery.parser; public abstract class AbstractXQueryLexer extends Lexer implements XQueryLanguageConstants { private boolean fIsWsExplicit = false; private int language;
private ProblemReporter reporter;
malteseduck/sonar-xquery-plugin
src/main/java/org/sonar/plugins/xquery/test/XQueryTestSensor.java
// Path: src/main/java/org/sonar/plugins/xquery/api/XQueryConstants.java // public interface XQueryConstants { // static String XQUERY_LANGUAGE_KEY = "xquery"; // static String FILE_EXTENSIONS_KEY = "sonar.xquery.fileExtensions"; // static String SOURCE_DIRECTORY_KEY = "sonar.xquery.sourceDirectory"; // static String XQTEST_REPORTS_DIRECTORY_KEY = "sonar.xqtest.reportsPath"; // // static String XQUERY_LANGUAGE_NAME = "XQuery"; // static String[] DEFAULT_FILE_EXTENSIONS = {"xqy", "xquery", "xq", "xqi", "xql", "xqm", "xqws"}; // static String DEFAULT_FILE_EXTENSIONS_STRING = "xqy, xquery, xq, xqi, xql, xqm, xqws"; // static String DEFAULT_SOURCE_DIRECTORY = "src/main/xquery"; // static String DEFAULT_XQTEST_DIRECTORY = "target/xqtest-reports"; // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.batch.Sensor; import org.sonar.api.batch.SensorContext; import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.config.Settings; import org.sonar.api.resources.Project; import org.sonar.plugins.xquery.api.XQueryConstants; import java.io.File;
/* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.test; public class XQueryTestSensor implements Sensor { private static final Logger LOGGER = LoggerFactory.getLogger(XQueryTestSensor.class); private final SurefireXQueryParser surefireXQueryParser; private final Settings settings; private final FileSystem fileSystem; public XQueryTestSensor(SurefireXQueryParser surefireXQueryParser, Settings settings, FileSystem fileSystem) { this.surefireXQueryParser = surefireXQueryParser; this.settings = settings; this.fileSystem = fileSystem; } @Override public boolean shouldExecuteOnProject(Project project) {
// Path: src/main/java/org/sonar/plugins/xquery/api/XQueryConstants.java // public interface XQueryConstants { // static String XQUERY_LANGUAGE_KEY = "xquery"; // static String FILE_EXTENSIONS_KEY = "sonar.xquery.fileExtensions"; // static String SOURCE_DIRECTORY_KEY = "sonar.xquery.sourceDirectory"; // static String XQTEST_REPORTS_DIRECTORY_KEY = "sonar.xqtest.reportsPath"; // // static String XQUERY_LANGUAGE_NAME = "XQuery"; // static String[] DEFAULT_FILE_EXTENSIONS = {"xqy", "xquery", "xq", "xqi", "xql", "xqm", "xqws"}; // static String DEFAULT_FILE_EXTENSIONS_STRING = "xqy, xquery, xq, xqi, xql, xqm, xqws"; // static String DEFAULT_SOURCE_DIRECTORY = "src/main/xquery"; // static String DEFAULT_XQTEST_DIRECTORY = "target/xqtest-reports"; // } // Path: src/main/java/org/sonar/plugins/xquery/test/XQueryTestSensor.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.batch.Sensor; import org.sonar.api.batch.SensorContext; import org.sonar.api.batch.fs.FileSystem; import org.sonar.api.config.Settings; import org.sonar.api.resources.Project; import org.sonar.plugins.xquery.api.XQueryConstants; import java.io.File; /* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.test; public class XQueryTestSensor implements Sensor { private static final Logger LOGGER = LoggerFactory.getLogger(XQueryTestSensor.class); private final SurefireXQueryParser surefireXQueryParser; private final Settings settings; private final FileSystem fileSystem; public XQueryTestSensor(SurefireXQueryParser surefireXQueryParser, Settings settings, FileSystem fileSystem) { this.surefireXQueryParser = surefireXQueryParser; this.settings = settings; this.fileSystem = fileSystem; } @Override public boolean shouldExecuteOnProject(Project project) {
return fileSystem.files(fileSystem.predicates().hasLanguage(XQueryConstants.XQUERY_LANGUAGE_KEY)).iterator().hasNext();
malteseduck/sonar-xquery-plugin
src/main/java/org/sonar/plugins/xquery/rules/XQueryProfile.java
// Path: src/main/java/org/sonar/plugins/xquery/api/XQueryConstants.java // public interface XQueryConstants { // static String XQUERY_LANGUAGE_KEY = "xquery"; // static String FILE_EXTENSIONS_KEY = "sonar.xquery.fileExtensions"; // static String SOURCE_DIRECTORY_KEY = "sonar.xquery.sourceDirectory"; // static String XQTEST_REPORTS_DIRECTORY_KEY = "sonar.xqtest.reportsPath"; // // static String XQUERY_LANGUAGE_NAME = "XQuery"; // static String[] DEFAULT_FILE_EXTENSIONS = {"xqy", "xquery", "xq", "xqi", "xql", "xqm", "xqws"}; // static String DEFAULT_FILE_EXTENSIONS_STRING = "xqy, xquery, xq, xqi, xql, xqm, xqws"; // static String DEFAULT_SOURCE_DIRECTORY = "src/main/xquery"; // static String DEFAULT_XQTEST_DIRECTORY = "target/xqtest-reports"; // }
import org.sonar.api.profiles.ProfileDefinition; import org.sonar.api.profiles.RulesProfile; import org.sonar.api.rules.AnnotationRuleParser; import org.sonar.api.rules.Rule; import org.sonar.api.utils.ValidationMessages; import org.sonar.plugins.xquery.api.XQueryConstants; import org.sonar.api.profiles.AnnotationProfileParser; import java.util.List;
/* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.rules; /** * Default XQuery profile. * * @since 1.0 */ public final class XQueryProfile extends ProfileDefinition { private final AnnotationProfileParser annotationProfileParser; public XQueryProfile(AnnotationProfileParser annotationProfileParser) { this.annotationProfileParser = annotationProfileParser; } @Override public RulesProfile createProfile(ValidationMessages messages) {
// Path: src/main/java/org/sonar/plugins/xquery/api/XQueryConstants.java // public interface XQueryConstants { // static String XQUERY_LANGUAGE_KEY = "xquery"; // static String FILE_EXTENSIONS_KEY = "sonar.xquery.fileExtensions"; // static String SOURCE_DIRECTORY_KEY = "sonar.xquery.sourceDirectory"; // static String XQTEST_REPORTS_DIRECTORY_KEY = "sonar.xqtest.reportsPath"; // // static String XQUERY_LANGUAGE_NAME = "XQuery"; // static String[] DEFAULT_FILE_EXTENSIONS = {"xqy", "xquery", "xq", "xqi", "xql", "xqm", "xqws"}; // static String DEFAULT_FILE_EXTENSIONS_STRING = "xqy, xquery, xq, xqi, xql, xqm, xqws"; // static String DEFAULT_SOURCE_DIRECTORY = "src/main/xquery"; // static String DEFAULT_XQTEST_DIRECTORY = "target/xqtest-reports"; // } // Path: src/main/java/org/sonar/plugins/xquery/rules/XQueryProfile.java import org.sonar.api.profiles.ProfileDefinition; import org.sonar.api.profiles.RulesProfile; import org.sonar.api.rules.AnnotationRuleParser; import org.sonar.api.rules.Rule; import org.sonar.api.utils.ValidationMessages; import org.sonar.plugins.xquery.api.XQueryConstants; import org.sonar.api.profiles.AnnotationProfileParser; import java.util.List; /* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.rules; /** * Default XQuery profile. * * @since 1.0 */ public final class XQueryProfile extends ProfileDefinition { private final AnnotationProfileParser annotationProfileParser; public XQueryProfile(AnnotationProfileParser annotationProfileParser) { this.annotationProfileParser = annotationProfileParser; } @Override public RulesProfile createProfile(ValidationMessages messages) {
return annotationProfileParser.parse(CheckClasses.REPOSITORY_KEY, "Default Profile", XQueryConstants.XQUERY_LANGUAGE_KEY, CheckClasses.getChecks(), messages);
malteseduck/sonar-xquery-plugin
src/main/java/org/sonar/plugins/xquery/checks/ParseErrorCheck.java
// Path: src/main/java/org/sonar/plugins/xquery/parser/reporter/Problem.java // public class Problem { // private String id; // private Token token; // // private String message; // // public Problem(String id, String message, Token token) { // this.id = id; // this.message = message; // this.token = token; // } // public int getCharPositionInLine() { // if (token != null) { // return token.getCharPositionInLine(); // } // return 0; // } // // public String getId() { // return id; // } // // public int getLine() { // if (token != null) { // return token.getLine(); // } // return 0; // } // // public String getMessage() { // return message; // } // // public String getMessageString() { // StringBuffer buffer = new StringBuffer(" - line "); // buffer.append(getLine()).append(":").append(getCharPositionInLine()).append(" - ").append(getMessage()); // return buffer.toString(); // } // // public Token getToken() { // return token; // } // // public void setId(String id) { // this.id = id; // } // // public void setMessage(String message) { // this.message = message; // } // // public void setToken(Token token) { // this.token = token; // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer("Problem ["); // buffer.append(getLine()).append(":").append(getCharPositionInLine()).append(" - ").append(getMessage()).append("]"); // return buffer.toString(); // } // } // // Path: src/main/java/org/sonar/plugins/xquery/parser/reporter/ProblemReporter.java // public class ProblemReporter { // // private boolean failOnError; // private boolean outputError; // // private List<Problem> problems; // // public ProblemReporter() { // this(false); // } // // public ProblemReporter(boolean failOnError) { // this.failOnError = failOnError; // this.outputError = true; // problems = new ArrayList<Problem>(); // } // // public List<Problem> getProblems() { // return problems; // } // // public boolean isFailOnError() { // return failOnError; // } // // public boolean isOutputError() { // return outputError; // } // // public void reportError(String id, String message, Token token) { // Problem problem = new Problem(id, message, token); // problems.add(problem); // if (failOnError) { // throw new RuntimeException(problem.getMessageString()); // } else if (outputError) { // System.err.println(problem.getId() + problem.getMessageString()); // } // } // // public void setFailOnError(boolean failOnError) { // this.failOnError = failOnError; // } // // public void setOutputError(boolean outputError) { // this.outputError = outputError; // } // } // // Path: src/main/java/org/sonar/plugins/xquery/rules/CheckClasses.java // public final class CheckClasses { // // public static final String REPOSITORY_KEY = "xquery"; // // private CheckClasses() { // } // // public static List<Class> getChecks() { // return ImmutableList.<Class>of( // DynamicFunctionCheck.class, // EffectiveBooleanCheck.class, // FunctionMappingCheck.class, // OperationsInPredicateCheck.class, // OrderByRangeCheck.class, // ParseErrorCheck.class, // StrongTypingInFLWORCheck.class, // StrongTypingInFunctionDeclarationCheck.class, // StrongTypingInModuleVariableCheck.class, // XPathDescendantStepsCheck.class, // XPathSubExpressionsInPredicateCheck.class, // XPathTextStepsCheck.class, // XQueryVersionCheck.class // ); // } // }
import org.apache.commons.lang.StringUtils; import org.sonar.api.rule.RuleKey; import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.xquery.parser.reporter.Problem; import org.sonar.plugins.xquery.parser.reporter.ProblemReporter; import org.sonar.plugins.xquery.rules.CheckClasses;
/* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.checks; @Rule( key = ParseErrorCheck.RULE_KEY, name = "Code Parsing Error", description = "This is to catch parsing errors on projects. " + "There may be a potential syntax error, or the parser just may not be able to process certain syntax.", priority = Priority.INFO ) public class ParseErrorCheck extends AbstractCheck { private static String[] MESSAGES = new String[] {"no viable alternative at character 'D'"}; public static final String RULE_KEY = "ParseError";
// Path: src/main/java/org/sonar/plugins/xquery/parser/reporter/Problem.java // public class Problem { // private String id; // private Token token; // // private String message; // // public Problem(String id, String message, Token token) { // this.id = id; // this.message = message; // this.token = token; // } // public int getCharPositionInLine() { // if (token != null) { // return token.getCharPositionInLine(); // } // return 0; // } // // public String getId() { // return id; // } // // public int getLine() { // if (token != null) { // return token.getLine(); // } // return 0; // } // // public String getMessage() { // return message; // } // // public String getMessageString() { // StringBuffer buffer = new StringBuffer(" - line "); // buffer.append(getLine()).append(":").append(getCharPositionInLine()).append(" - ").append(getMessage()); // return buffer.toString(); // } // // public Token getToken() { // return token; // } // // public void setId(String id) { // this.id = id; // } // // public void setMessage(String message) { // this.message = message; // } // // public void setToken(Token token) { // this.token = token; // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer("Problem ["); // buffer.append(getLine()).append(":").append(getCharPositionInLine()).append(" - ").append(getMessage()).append("]"); // return buffer.toString(); // } // } // // Path: src/main/java/org/sonar/plugins/xquery/parser/reporter/ProblemReporter.java // public class ProblemReporter { // // private boolean failOnError; // private boolean outputError; // // private List<Problem> problems; // // public ProblemReporter() { // this(false); // } // // public ProblemReporter(boolean failOnError) { // this.failOnError = failOnError; // this.outputError = true; // problems = new ArrayList<Problem>(); // } // // public List<Problem> getProblems() { // return problems; // } // // public boolean isFailOnError() { // return failOnError; // } // // public boolean isOutputError() { // return outputError; // } // // public void reportError(String id, String message, Token token) { // Problem problem = new Problem(id, message, token); // problems.add(problem); // if (failOnError) { // throw new RuntimeException(problem.getMessageString()); // } else if (outputError) { // System.err.println(problem.getId() + problem.getMessageString()); // } // } // // public void setFailOnError(boolean failOnError) { // this.failOnError = failOnError; // } // // public void setOutputError(boolean outputError) { // this.outputError = outputError; // } // } // // Path: src/main/java/org/sonar/plugins/xquery/rules/CheckClasses.java // public final class CheckClasses { // // public static final String REPOSITORY_KEY = "xquery"; // // private CheckClasses() { // } // // public static List<Class> getChecks() { // return ImmutableList.<Class>of( // DynamicFunctionCheck.class, // EffectiveBooleanCheck.class, // FunctionMappingCheck.class, // OperationsInPredicateCheck.class, // OrderByRangeCheck.class, // ParseErrorCheck.class, // StrongTypingInFLWORCheck.class, // StrongTypingInFunctionDeclarationCheck.class, // StrongTypingInModuleVariableCheck.class, // XPathDescendantStepsCheck.class, // XPathSubExpressionsInPredicateCheck.class, // XPathTextStepsCheck.class, // XQueryVersionCheck.class // ); // } // } // Path: src/main/java/org/sonar/plugins/xquery/checks/ParseErrorCheck.java import org.apache.commons.lang.StringUtils; import org.sonar.api.rule.RuleKey; import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.xquery.parser.reporter.Problem; import org.sonar.plugins.xquery.parser.reporter.ProblemReporter; import org.sonar.plugins.xquery.rules.CheckClasses; /* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.checks; @Rule( key = ParseErrorCheck.RULE_KEY, name = "Code Parsing Error", description = "This is to catch parsing errors on projects. " + "There may be a potential syntax error, or the parser just may not be able to process certain syntax.", priority = Priority.INFO ) public class ParseErrorCheck extends AbstractCheck { private static String[] MESSAGES = new String[] {"no viable alternative at character 'D'"}; public static final String RULE_KEY = "ParseError";
private static final RuleKey RULE = RuleKey.of(CheckClasses.REPOSITORY_KEY, RULE_KEY);
malteseduck/sonar-xquery-plugin
src/main/java/org/sonar/plugins/xquery/checks/ParseErrorCheck.java
// Path: src/main/java/org/sonar/plugins/xquery/parser/reporter/Problem.java // public class Problem { // private String id; // private Token token; // // private String message; // // public Problem(String id, String message, Token token) { // this.id = id; // this.message = message; // this.token = token; // } // public int getCharPositionInLine() { // if (token != null) { // return token.getCharPositionInLine(); // } // return 0; // } // // public String getId() { // return id; // } // // public int getLine() { // if (token != null) { // return token.getLine(); // } // return 0; // } // // public String getMessage() { // return message; // } // // public String getMessageString() { // StringBuffer buffer = new StringBuffer(" - line "); // buffer.append(getLine()).append(":").append(getCharPositionInLine()).append(" - ").append(getMessage()); // return buffer.toString(); // } // // public Token getToken() { // return token; // } // // public void setId(String id) { // this.id = id; // } // // public void setMessage(String message) { // this.message = message; // } // // public void setToken(Token token) { // this.token = token; // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer("Problem ["); // buffer.append(getLine()).append(":").append(getCharPositionInLine()).append(" - ").append(getMessage()).append("]"); // return buffer.toString(); // } // } // // Path: src/main/java/org/sonar/plugins/xquery/parser/reporter/ProblemReporter.java // public class ProblemReporter { // // private boolean failOnError; // private boolean outputError; // // private List<Problem> problems; // // public ProblemReporter() { // this(false); // } // // public ProblemReporter(boolean failOnError) { // this.failOnError = failOnError; // this.outputError = true; // problems = new ArrayList<Problem>(); // } // // public List<Problem> getProblems() { // return problems; // } // // public boolean isFailOnError() { // return failOnError; // } // // public boolean isOutputError() { // return outputError; // } // // public void reportError(String id, String message, Token token) { // Problem problem = new Problem(id, message, token); // problems.add(problem); // if (failOnError) { // throw new RuntimeException(problem.getMessageString()); // } else if (outputError) { // System.err.println(problem.getId() + problem.getMessageString()); // } // } // // public void setFailOnError(boolean failOnError) { // this.failOnError = failOnError; // } // // public void setOutputError(boolean outputError) { // this.outputError = outputError; // } // } // // Path: src/main/java/org/sonar/plugins/xquery/rules/CheckClasses.java // public final class CheckClasses { // // public static final String REPOSITORY_KEY = "xquery"; // // private CheckClasses() { // } // // public static List<Class> getChecks() { // return ImmutableList.<Class>of( // DynamicFunctionCheck.class, // EffectiveBooleanCheck.class, // FunctionMappingCheck.class, // OperationsInPredicateCheck.class, // OrderByRangeCheck.class, // ParseErrorCheck.class, // StrongTypingInFLWORCheck.class, // StrongTypingInFunctionDeclarationCheck.class, // StrongTypingInModuleVariableCheck.class, // XPathDescendantStepsCheck.class, // XPathSubExpressionsInPredicateCheck.class, // XPathTextStepsCheck.class, // XQueryVersionCheck.class // ); // } // }
import org.apache.commons.lang.StringUtils; import org.sonar.api.rule.RuleKey; import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.xquery.parser.reporter.Problem; import org.sonar.plugins.xquery.parser.reporter.ProblemReporter; import org.sonar.plugins.xquery.rules.CheckClasses;
/* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.checks; @Rule( key = ParseErrorCheck.RULE_KEY, name = "Code Parsing Error", description = "This is to catch parsing errors on projects. " + "There may be a potential syntax error, or the parser just may not be able to process certain syntax.", priority = Priority.INFO ) public class ParseErrorCheck extends AbstractCheck { private static String[] MESSAGES = new String[] {"no viable alternative at character 'D'"}; public static final String RULE_KEY = "ParseError"; private static final RuleKey RULE = RuleKey.of(CheckClasses.REPOSITORY_KEY, RULE_KEY); @Override
// Path: src/main/java/org/sonar/plugins/xquery/parser/reporter/Problem.java // public class Problem { // private String id; // private Token token; // // private String message; // // public Problem(String id, String message, Token token) { // this.id = id; // this.message = message; // this.token = token; // } // public int getCharPositionInLine() { // if (token != null) { // return token.getCharPositionInLine(); // } // return 0; // } // // public String getId() { // return id; // } // // public int getLine() { // if (token != null) { // return token.getLine(); // } // return 0; // } // // public String getMessage() { // return message; // } // // public String getMessageString() { // StringBuffer buffer = new StringBuffer(" - line "); // buffer.append(getLine()).append(":").append(getCharPositionInLine()).append(" - ").append(getMessage()); // return buffer.toString(); // } // // public Token getToken() { // return token; // } // // public void setId(String id) { // this.id = id; // } // // public void setMessage(String message) { // this.message = message; // } // // public void setToken(Token token) { // this.token = token; // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer("Problem ["); // buffer.append(getLine()).append(":").append(getCharPositionInLine()).append(" - ").append(getMessage()).append("]"); // return buffer.toString(); // } // } // // Path: src/main/java/org/sonar/plugins/xquery/parser/reporter/ProblemReporter.java // public class ProblemReporter { // // private boolean failOnError; // private boolean outputError; // // private List<Problem> problems; // // public ProblemReporter() { // this(false); // } // // public ProblemReporter(boolean failOnError) { // this.failOnError = failOnError; // this.outputError = true; // problems = new ArrayList<Problem>(); // } // // public List<Problem> getProblems() { // return problems; // } // // public boolean isFailOnError() { // return failOnError; // } // // public boolean isOutputError() { // return outputError; // } // // public void reportError(String id, String message, Token token) { // Problem problem = new Problem(id, message, token); // problems.add(problem); // if (failOnError) { // throw new RuntimeException(problem.getMessageString()); // } else if (outputError) { // System.err.println(problem.getId() + problem.getMessageString()); // } // } // // public void setFailOnError(boolean failOnError) { // this.failOnError = failOnError; // } // // public void setOutputError(boolean outputError) { // this.outputError = outputError; // } // } // // Path: src/main/java/org/sonar/plugins/xquery/rules/CheckClasses.java // public final class CheckClasses { // // public static final String REPOSITORY_KEY = "xquery"; // // private CheckClasses() { // } // // public static List<Class> getChecks() { // return ImmutableList.<Class>of( // DynamicFunctionCheck.class, // EffectiveBooleanCheck.class, // FunctionMappingCheck.class, // OperationsInPredicateCheck.class, // OrderByRangeCheck.class, // ParseErrorCheck.class, // StrongTypingInFLWORCheck.class, // StrongTypingInFunctionDeclarationCheck.class, // StrongTypingInModuleVariableCheck.class, // XPathDescendantStepsCheck.class, // XPathSubExpressionsInPredicateCheck.class, // XPathTextStepsCheck.class, // XQueryVersionCheck.class // ); // } // } // Path: src/main/java/org/sonar/plugins/xquery/checks/ParseErrorCheck.java import org.apache.commons.lang.StringUtils; import org.sonar.api.rule.RuleKey; import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.xquery.parser.reporter.Problem; import org.sonar.plugins.xquery.parser.reporter.ProblemReporter; import org.sonar.plugins.xquery.rules.CheckClasses; /* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.checks; @Rule( key = ParseErrorCheck.RULE_KEY, name = "Code Parsing Error", description = "This is to catch parsing errors on projects. " + "There may be a potential syntax error, or the parser just may not be able to process certain syntax.", priority = Priority.INFO ) public class ParseErrorCheck extends AbstractCheck { private static String[] MESSAGES = new String[] {"no viable alternative at character 'D'"}; public static final String RULE_KEY = "ParseError"; private static final RuleKey RULE = RuleKey.of(CheckClasses.REPOSITORY_KEY, RULE_KEY); @Override
public void checkReport(ProblemReporter reporter) {
malteseduck/sonar-xquery-plugin
src/main/java/org/sonar/plugins/xquery/checks/ParseErrorCheck.java
// Path: src/main/java/org/sonar/plugins/xquery/parser/reporter/Problem.java // public class Problem { // private String id; // private Token token; // // private String message; // // public Problem(String id, String message, Token token) { // this.id = id; // this.message = message; // this.token = token; // } // public int getCharPositionInLine() { // if (token != null) { // return token.getCharPositionInLine(); // } // return 0; // } // // public String getId() { // return id; // } // // public int getLine() { // if (token != null) { // return token.getLine(); // } // return 0; // } // // public String getMessage() { // return message; // } // // public String getMessageString() { // StringBuffer buffer = new StringBuffer(" - line "); // buffer.append(getLine()).append(":").append(getCharPositionInLine()).append(" - ").append(getMessage()); // return buffer.toString(); // } // // public Token getToken() { // return token; // } // // public void setId(String id) { // this.id = id; // } // // public void setMessage(String message) { // this.message = message; // } // // public void setToken(Token token) { // this.token = token; // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer("Problem ["); // buffer.append(getLine()).append(":").append(getCharPositionInLine()).append(" - ").append(getMessage()).append("]"); // return buffer.toString(); // } // } // // Path: src/main/java/org/sonar/plugins/xquery/parser/reporter/ProblemReporter.java // public class ProblemReporter { // // private boolean failOnError; // private boolean outputError; // // private List<Problem> problems; // // public ProblemReporter() { // this(false); // } // // public ProblemReporter(boolean failOnError) { // this.failOnError = failOnError; // this.outputError = true; // problems = new ArrayList<Problem>(); // } // // public List<Problem> getProblems() { // return problems; // } // // public boolean isFailOnError() { // return failOnError; // } // // public boolean isOutputError() { // return outputError; // } // // public void reportError(String id, String message, Token token) { // Problem problem = new Problem(id, message, token); // problems.add(problem); // if (failOnError) { // throw new RuntimeException(problem.getMessageString()); // } else if (outputError) { // System.err.println(problem.getId() + problem.getMessageString()); // } // } // // public void setFailOnError(boolean failOnError) { // this.failOnError = failOnError; // } // // public void setOutputError(boolean outputError) { // this.outputError = outputError; // } // } // // Path: src/main/java/org/sonar/plugins/xquery/rules/CheckClasses.java // public final class CheckClasses { // // public static final String REPOSITORY_KEY = "xquery"; // // private CheckClasses() { // } // // public static List<Class> getChecks() { // return ImmutableList.<Class>of( // DynamicFunctionCheck.class, // EffectiveBooleanCheck.class, // FunctionMappingCheck.class, // OperationsInPredicateCheck.class, // OrderByRangeCheck.class, // ParseErrorCheck.class, // StrongTypingInFLWORCheck.class, // StrongTypingInFunctionDeclarationCheck.class, // StrongTypingInModuleVariableCheck.class, // XPathDescendantStepsCheck.class, // XPathSubExpressionsInPredicateCheck.class, // XPathTextStepsCheck.class, // XQueryVersionCheck.class // ); // } // }
import org.apache.commons.lang.StringUtils; import org.sonar.api.rule.RuleKey; import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.xquery.parser.reporter.Problem; import org.sonar.plugins.xquery.parser.reporter.ProblemReporter; import org.sonar.plugins.xquery.rules.CheckClasses;
/* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.checks; @Rule( key = ParseErrorCheck.RULE_KEY, name = "Code Parsing Error", description = "This is to catch parsing errors on projects. " + "There may be a potential syntax error, or the parser just may not be able to process certain syntax.", priority = Priority.INFO ) public class ParseErrorCheck extends AbstractCheck { private static String[] MESSAGES = new String[] {"no viable alternative at character 'D'"}; public static final String RULE_KEY = "ParseError"; private static final RuleKey RULE = RuleKey.of(CheckClasses.REPOSITORY_KEY, RULE_KEY); @Override public void checkReport(ProblemReporter reporter) { boolean allowed = false;
// Path: src/main/java/org/sonar/plugins/xquery/parser/reporter/Problem.java // public class Problem { // private String id; // private Token token; // // private String message; // // public Problem(String id, String message, Token token) { // this.id = id; // this.message = message; // this.token = token; // } // public int getCharPositionInLine() { // if (token != null) { // return token.getCharPositionInLine(); // } // return 0; // } // // public String getId() { // return id; // } // // public int getLine() { // if (token != null) { // return token.getLine(); // } // return 0; // } // // public String getMessage() { // return message; // } // // public String getMessageString() { // StringBuffer buffer = new StringBuffer(" - line "); // buffer.append(getLine()).append(":").append(getCharPositionInLine()).append(" - ").append(getMessage()); // return buffer.toString(); // } // // public Token getToken() { // return token; // } // // public void setId(String id) { // this.id = id; // } // // public void setMessage(String message) { // this.message = message; // } // // public void setToken(Token token) { // this.token = token; // } // // @Override // public String toString() { // StringBuffer buffer = new StringBuffer("Problem ["); // buffer.append(getLine()).append(":").append(getCharPositionInLine()).append(" - ").append(getMessage()).append("]"); // return buffer.toString(); // } // } // // Path: src/main/java/org/sonar/plugins/xquery/parser/reporter/ProblemReporter.java // public class ProblemReporter { // // private boolean failOnError; // private boolean outputError; // // private List<Problem> problems; // // public ProblemReporter() { // this(false); // } // // public ProblemReporter(boolean failOnError) { // this.failOnError = failOnError; // this.outputError = true; // problems = new ArrayList<Problem>(); // } // // public List<Problem> getProblems() { // return problems; // } // // public boolean isFailOnError() { // return failOnError; // } // // public boolean isOutputError() { // return outputError; // } // // public void reportError(String id, String message, Token token) { // Problem problem = new Problem(id, message, token); // problems.add(problem); // if (failOnError) { // throw new RuntimeException(problem.getMessageString()); // } else if (outputError) { // System.err.println(problem.getId() + problem.getMessageString()); // } // } // // public void setFailOnError(boolean failOnError) { // this.failOnError = failOnError; // } // // public void setOutputError(boolean outputError) { // this.outputError = outputError; // } // } // // Path: src/main/java/org/sonar/plugins/xquery/rules/CheckClasses.java // public final class CheckClasses { // // public static final String REPOSITORY_KEY = "xquery"; // // private CheckClasses() { // } // // public static List<Class> getChecks() { // return ImmutableList.<Class>of( // DynamicFunctionCheck.class, // EffectiveBooleanCheck.class, // FunctionMappingCheck.class, // OperationsInPredicateCheck.class, // OrderByRangeCheck.class, // ParseErrorCheck.class, // StrongTypingInFLWORCheck.class, // StrongTypingInFunctionDeclarationCheck.class, // StrongTypingInModuleVariableCheck.class, // XPathDescendantStepsCheck.class, // XPathSubExpressionsInPredicateCheck.class, // XPathTextStepsCheck.class, // XQueryVersionCheck.class // ); // } // } // Path: src/main/java/org/sonar/plugins/xquery/checks/ParseErrorCheck.java import org.apache.commons.lang.StringUtils; import org.sonar.api.rule.RuleKey; import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.xquery.parser.reporter.Problem; import org.sonar.plugins.xquery.parser.reporter.ProblemReporter; import org.sonar.plugins.xquery.rules.CheckClasses; /* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.checks; @Rule( key = ParseErrorCheck.RULE_KEY, name = "Code Parsing Error", description = "This is to catch parsing errors on projects. " + "There may be a potential syntax error, or the parser just may not be able to process certain syntax.", priority = Priority.INFO ) public class ParseErrorCheck extends AbstractCheck { private static String[] MESSAGES = new String[] {"no viable alternative at character 'D'"}; public static final String RULE_KEY = "ParseError"; private static final RuleKey RULE = RuleKey.of(CheckClasses.REPOSITORY_KEY, RULE_KEY); @Override public void checkReport(ProblemReporter reporter) { boolean allowed = false;
for (Problem problem : reporter.getProblems()) {
malteseduck/sonar-xquery-plugin
src/main/java/org/sonar/plugins/xquery/test/SurefireXQueryParser.java
// Path: src/main/java/org/sonar/plugins/xquery/api/XQueryConstants.java // public interface XQueryConstants { // static String XQUERY_LANGUAGE_KEY = "xquery"; // static String FILE_EXTENSIONS_KEY = "sonar.xquery.fileExtensions"; // static String SOURCE_DIRECTORY_KEY = "sonar.xquery.sourceDirectory"; // static String XQTEST_REPORTS_DIRECTORY_KEY = "sonar.xqtest.reportsPath"; // // static String XQUERY_LANGUAGE_NAME = "XQuery"; // static String[] DEFAULT_FILE_EXTENSIONS = {"xqy", "xquery", "xq", "xqi", "xql", "xqm", "xqws"}; // static String DEFAULT_FILE_EXTENSIONS_STRING = "xqy, xquery, xq, xqi, xql, xqm, xqws"; // static String DEFAULT_SOURCE_DIRECTORY = "src/main/xquery"; // static String DEFAULT_XQTEST_DIRECTORY = "target/xqtest-reports"; // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.BatchExtension; import org.sonar.api.config.Settings; import org.sonar.api.resources.Resource; import org.sonar.plugins.surefire.api.AbstractSurefireParser; import org.sonar.plugins.xquery.api.XQueryConstants;
/* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.test; public class SurefireXQueryParser extends AbstractSurefireParser implements BatchExtension { private static final Logger LOGGER = LoggerFactory.getLogger(SurefireXQueryParser.class); private final Settings settings; public SurefireXQueryParser(Settings settings) { this.settings = settings; } @Override protected Resource getUnitTestResource(String classKey) {
// Path: src/main/java/org/sonar/plugins/xquery/api/XQueryConstants.java // public interface XQueryConstants { // static String XQUERY_LANGUAGE_KEY = "xquery"; // static String FILE_EXTENSIONS_KEY = "sonar.xquery.fileExtensions"; // static String SOURCE_DIRECTORY_KEY = "sonar.xquery.sourceDirectory"; // static String XQTEST_REPORTS_DIRECTORY_KEY = "sonar.xqtest.reportsPath"; // // static String XQUERY_LANGUAGE_NAME = "XQuery"; // static String[] DEFAULT_FILE_EXTENSIONS = {"xqy", "xquery", "xq", "xqi", "xql", "xqm", "xqws"}; // static String DEFAULT_FILE_EXTENSIONS_STRING = "xqy, xquery, xq, xqi, xql, xqm, xqws"; // static String DEFAULT_SOURCE_DIRECTORY = "src/main/xquery"; // static String DEFAULT_XQTEST_DIRECTORY = "target/xqtest-reports"; // } // Path: src/main/java/org/sonar/plugins/xquery/test/SurefireXQueryParser.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.BatchExtension; import org.sonar.api.config.Settings; import org.sonar.api.resources.Resource; import org.sonar.plugins.surefire.api.AbstractSurefireParser; import org.sonar.plugins.xquery.api.XQueryConstants; /* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.test; public class SurefireXQueryParser extends AbstractSurefireParser implements BatchExtension { private static final Logger LOGGER = LoggerFactory.getLogger(SurefireXQueryParser.class); private final Settings settings; public SurefireXQueryParser(Settings settings) { this.settings = settings; } @Override protected Resource getUnitTestResource(String classKey) {
return org.sonar.api.resources.File.create(settings.getString(XQueryConstants.SOURCE_DIRECTORY_KEY) + classKey);
malteseduck/sonar-xquery-plugin
src/test/java/org/sonar/plugins/xquery/parser/GenerateAST.java
// Path: src/main/java/org/antlr/runtime/debug/XQueryParseTreeBuilder.java // public class XQueryParseTreeBuilder extends ParseTreeBuilder { // // public XQueryParseTreeBuilder(String grammarName) { // super(grammarName); // } // // public ParseTree create(Object payload) { // return new XQueryParseTree(payload); // } // // public void consumeToken(Token token) { // if ( backtracking>0 ) return; // XQueryParseTree ruleNode = (XQueryParseTree)callStack.peek(); // XQueryParseTree elementNode = (XQueryParseTree) create(token); // elementNode.hiddenTokens = this.hiddenTokens; // this.hiddenTokens = new ArrayList<Object>(); // ruleNode.addChild(elementNode); // } // }
import org.antlr.runtime.ANTLRStringStream; import org.antlr.runtime.TokenStream; import org.antlr.runtime.debug.ParseTreeBuilder; import org.antlr.runtime.debug.XQueryParseTreeBuilder; import org.apache.commons.lang.StringUtils; import org.codehaus.plexus.util.FileUtils; import java.io.IOException;
/* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.parser; /** * Class that can be used to generate an AST for a specified string that can be * used to see how it would look. * * It can also generate the parse tree as well if the member is changed to * "true" and change the parser creation to use the builder. This can only be * done if the parser was generated with the "-debug" option * * For use in manual testing. */ public class GenerateAST { public static final boolean INCLUDE_AST = true; public static final boolean INCLUDE_PARSE_TREE = false; // public static final String PATH = "/Users/cieslinskice/Documents/Code/lds-edit/src/main/xquery/invoke/function-apply.xqy"; public static final String PATH = ""; public static String code(String... strings) { StringBuffer code = new StringBuffer(); for (String string : strings) { if (code.length() > 0) { code.append('\n'); } code.append(string); } return code.toString(); } public static void main(String[] args) throws IOException { XQueryTree tree = new XQueryTree();
// Path: src/main/java/org/antlr/runtime/debug/XQueryParseTreeBuilder.java // public class XQueryParseTreeBuilder extends ParseTreeBuilder { // // public XQueryParseTreeBuilder(String grammarName) { // super(grammarName); // } // // public ParseTree create(Object payload) { // return new XQueryParseTree(payload); // } // // public void consumeToken(Token token) { // if ( backtracking>0 ) return; // XQueryParseTree ruleNode = (XQueryParseTree)callStack.peek(); // XQueryParseTree elementNode = (XQueryParseTree) create(token); // elementNode.hiddenTokens = this.hiddenTokens; // this.hiddenTokens = new ArrayList<Object>(); // ruleNode.addChild(elementNode); // } // } // Path: src/test/java/org/sonar/plugins/xquery/parser/GenerateAST.java import org.antlr.runtime.ANTLRStringStream; import org.antlr.runtime.TokenStream; import org.antlr.runtime.debug.ParseTreeBuilder; import org.antlr.runtime.debug.XQueryParseTreeBuilder; import org.apache.commons.lang.StringUtils; import org.codehaus.plexus.util.FileUtils; import java.io.IOException; /* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.parser; /** * Class that can be used to generate an AST for a specified string that can be * used to see how it would look. * * It can also generate the parse tree as well if the member is changed to * "true" and change the parser creation to use the builder. This can only be * done if the parser was generated with the "-debug" option * * For use in manual testing. */ public class GenerateAST { public static final boolean INCLUDE_AST = true; public static final boolean INCLUDE_PARSE_TREE = false; // public static final String PATH = "/Users/cieslinskice/Documents/Code/lds-edit/src/main/xquery/invoke/function-apply.xqy"; public static final String PATH = ""; public static String code(String... strings) { StringBuffer code = new StringBuffer(); for (String string : strings) { if (code.length() > 0) { code.append('\n'); } code.append(string); } return code.toString(); } public static void main(String[] args) throws IOException { XQueryTree tree = new XQueryTree();
ParseTreeBuilder builder = new XQueryParseTreeBuilder("MainModule");
malteseduck/sonar-xquery-plugin
src/test/java/org/sonar/plugins/xquery/parser/TestParser.java
// Path: src/main/java/org/antlr/runtime/debug/XQueryParseTreeBuilder.java // public class XQueryParseTreeBuilder extends ParseTreeBuilder { // // public XQueryParseTreeBuilder(String grammarName) { // super(grammarName); // } // // public ParseTree create(Object payload) { // return new XQueryParseTree(payload); // } // // public void consumeToken(Token token) { // if ( backtracking>0 ) return; // XQueryParseTree ruleNode = (XQueryParseTree)callStack.peek(); // XQueryParseTree elementNode = (XQueryParseTree) create(token); // elementNode.hiddenTokens = this.hiddenTokens; // this.hiddenTokens = new ArrayList<Object>(); // ruleNode.addChild(elementNode); // } // }
import java.io.File; import java.io.IOException; import java.util.List; import org.antlr.runtime.ANTLRFileStream; import org.antlr.runtime.ANTLRStringStream; import org.antlr.runtime.TokenStream; import org.antlr.runtime.debug.ParseTreeBuilder; import org.antlr.runtime.debug.XQueryParseTreeBuilder; import org.apache.commons.lang.StringUtils; import org.codehaus.plexus.util.FileUtils;
/* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.parser; /** * Class that can be used to test many external files to see how the parser * handles different types of query files. A good "full" test is the XQuery Test * Suite at http://dev.w3.org/2006/xquery-test-suite/PublicPagesStagingArea/. * Download the latest test, extract it, then point the parser to the directory * with that contains the queries (and change the file filter to "xq" since that * is their file extension). * * For use in manual testing. */ public class TestParser { public static String CODE_ROOT = "/Users/cieslinskice/Documents/XQTS_1_0_3"; public static String CODE_FILTER = "**/*.xq"; public static void main(String[] args) throws IOException { XQueryTree tree = new XQueryTree();
// Path: src/main/java/org/antlr/runtime/debug/XQueryParseTreeBuilder.java // public class XQueryParseTreeBuilder extends ParseTreeBuilder { // // public XQueryParseTreeBuilder(String grammarName) { // super(grammarName); // } // // public ParseTree create(Object payload) { // return new XQueryParseTree(payload); // } // // public void consumeToken(Token token) { // if ( backtracking>0 ) return; // XQueryParseTree ruleNode = (XQueryParseTree)callStack.peek(); // XQueryParseTree elementNode = (XQueryParseTree) create(token); // elementNode.hiddenTokens = this.hiddenTokens; // this.hiddenTokens = new ArrayList<Object>(); // ruleNode.addChild(elementNode); // } // } // Path: src/test/java/org/sonar/plugins/xquery/parser/TestParser.java import java.io.File; import java.io.IOException; import java.util.List; import org.antlr.runtime.ANTLRFileStream; import org.antlr.runtime.ANTLRStringStream; import org.antlr.runtime.TokenStream; import org.antlr.runtime.debug.ParseTreeBuilder; import org.antlr.runtime.debug.XQueryParseTreeBuilder; import org.apache.commons.lang.StringUtils; import org.codehaus.plexus.util.FileUtils; /* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.parser; /** * Class that can be used to test many external files to see how the parser * handles different types of query files. A good "full" test is the XQuery Test * Suite at http://dev.w3.org/2006/xquery-test-suite/PublicPagesStagingArea/. * Download the latest test, extract it, then point the parser to the directory * with that contains the queries (and change the file filter to "xq" since that * is their file extension). * * For use in manual testing. */ public class TestParser { public static String CODE_ROOT = "/Users/cieslinskice/Documents/XQTS_1_0_3"; public static String CODE_FILTER = "**/*.xq"; public static void main(String[] args) throws IOException { XQueryTree tree = new XQueryTree();
ParseTreeBuilder builder = new XQueryParseTreeBuilder("MainModule");
malteseduck/sonar-xquery-plugin
src/main/java/org/sonar/plugins/xquery/language/XQuery.java
// Path: src/main/java/org/sonar/plugins/xquery/api/XQueryConstants.java // public interface XQueryConstants { // static String XQUERY_LANGUAGE_KEY = "xquery"; // static String FILE_EXTENSIONS_KEY = "sonar.xquery.fileExtensions"; // static String SOURCE_DIRECTORY_KEY = "sonar.xquery.sourceDirectory"; // static String XQTEST_REPORTS_DIRECTORY_KEY = "sonar.xqtest.reportsPath"; // // static String XQUERY_LANGUAGE_NAME = "XQuery"; // static String[] DEFAULT_FILE_EXTENSIONS = {"xqy", "xquery", "xq", "xqi", "xql", "xqm", "xqws"}; // static String DEFAULT_FILE_EXTENSIONS_STRING = "xqy, xquery, xq, xqi, xql, xqm, xqws"; // static String DEFAULT_SOURCE_DIRECTORY = "src/main/xquery"; // static String DEFAULT_XQTEST_DIRECTORY = "target/xqtest-reports"; // }
import org.sonar.api.resources.AbstractLanguage; import org.sonar.plugins.xquery.api.XQueryConstants;
/* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.language; /** * This class defines the XQuery language. * * @since 1.0 */ public class XQuery extends AbstractLanguage { static final String[] KEYWORDS_ARRAY = new String[]{"xquery", "where", "version", "variable", "union", "typeswitch", "treat", "to", "then", "text", "stable", "sortby", "some", "self", "schema", "satisfies", "returns", "return", "ref", "processing-instruction", "preceding-sibling", "preceding", "precedes", "parent", "only", "of", "node", "namespace", "module", "let", "item", "intersect", "instance", "in", "import", "if", "function", "for", "follows", "following-sibling", "following", "external", "except", "every", "else", "element", "descending", "descendant-or-self", "descendant", "define", "default", "declare", "comment", "child", "cast", "case", "before", "attribute", "assert", "ascending", "as", "ancestor-or-self", "ancestor", "after"}; static final String[] TYPES_ARRAY = new String[]{"xs:yearMonthDuration", "xs:unsignedLong", "xs:time", "xs:string", "xs:short", "xs:QName", "xs:Name", "xs:long", "xs:integer", "xs:int", "xs:gYearMonth", "xs:gYear", "xs:gMonthDay", "xs:gDay", "xs:float", "xs:duration", "xs:double", "xs:decimal", "xs:dayTimeDuration", "xs:dateTime", "xs:date", "xs:byte", "xs:boolean", "xs:anyURI", "xf:yearMonthDuration"}; /** * A XQuery instance. */ public static final XQuery INSTANCE = new XQuery(); /** * Default constructor. */ public XQuery() {
// Path: src/main/java/org/sonar/plugins/xquery/api/XQueryConstants.java // public interface XQueryConstants { // static String XQUERY_LANGUAGE_KEY = "xquery"; // static String FILE_EXTENSIONS_KEY = "sonar.xquery.fileExtensions"; // static String SOURCE_DIRECTORY_KEY = "sonar.xquery.sourceDirectory"; // static String XQTEST_REPORTS_DIRECTORY_KEY = "sonar.xqtest.reportsPath"; // // static String XQUERY_LANGUAGE_NAME = "XQuery"; // static String[] DEFAULT_FILE_EXTENSIONS = {"xqy", "xquery", "xq", "xqi", "xql", "xqm", "xqws"}; // static String DEFAULT_FILE_EXTENSIONS_STRING = "xqy, xquery, xq, xqi, xql, xqm, xqws"; // static String DEFAULT_SOURCE_DIRECTORY = "src/main/xquery"; // static String DEFAULT_XQTEST_DIRECTORY = "target/xqtest-reports"; // } // Path: src/main/java/org/sonar/plugins/xquery/language/XQuery.java import org.sonar.api.resources.AbstractLanguage; import org.sonar.plugins.xquery.api.XQueryConstants; /* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.language; /** * This class defines the XQuery language. * * @since 1.0 */ public class XQuery extends AbstractLanguage { static final String[] KEYWORDS_ARRAY = new String[]{"xquery", "where", "version", "variable", "union", "typeswitch", "treat", "to", "then", "text", "stable", "sortby", "some", "self", "schema", "satisfies", "returns", "return", "ref", "processing-instruction", "preceding-sibling", "preceding", "precedes", "parent", "only", "of", "node", "namespace", "module", "let", "item", "intersect", "instance", "in", "import", "if", "function", "for", "follows", "following-sibling", "following", "external", "except", "every", "else", "element", "descending", "descendant-or-self", "descendant", "define", "default", "declare", "comment", "child", "cast", "case", "before", "attribute", "assert", "ascending", "as", "ancestor-or-self", "ancestor", "after"}; static final String[] TYPES_ARRAY = new String[]{"xs:yearMonthDuration", "xs:unsignedLong", "xs:time", "xs:string", "xs:short", "xs:QName", "xs:Name", "xs:long", "xs:integer", "xs:int", "xs:gYearMonth", "xs:gYear", "xs:gMonthDay", "xs:gDay", "xs:float", "xs:duration", "xs:double", "xs:decimal", "xs:dayTimeDuration", "xs:dateTime", "xs:date", "xs:byte", "xs:boolean", "xs:anyURI", "xf:yearMonthDuration"}; /** * A XQuery instance. */ public static final XQuery INSTANCE = new XQuery(); /** * Default constructor. */ public XQuery() {
super(XQueryConstants.XQUERY_LANGUAGE_KEY, XQueryConstants.XQUERY_LANGUAGE_NAME);
malteseduck/sonar-xquery-plugin
src/main/java/org/sonar/plugins/xquery/checks/LogCheck.java
// Path: src/main/java/org/sonar/plugins/xquery/rules/CheckClasses.java // public final class CheckClasses { // // public static final String REPOSITORY_KEY = "xquery"; // // private CheckClasses() { // } // // public static List<Class> getChecks() { // return ImmutableList.<Class>of( // DynamicFunctionCheck.class, // EffectiveBooleanCheck.class, // FunctionMappingCheck.class, // OperationsInPredicateCheck.class, // OrderByRangeCheck.class, // ParseErrorCheck.class, // StrongTypingInFLWORCheck.class, // StrongTypingInFunctionDeclarationCheck.class, // StrongTypingInModuleVariableCheck.class, // XPathDescendantStepsCheck.class, // XPathSubExpressionsInPredicateCheck.class, // XPathTextStepsCheck.class, // XQueryVersionCheck.class // ); // } // }
import org.sonar.check.Rule; import org.sonar.plugins.xquery.rules.CheckClasses; import org.sonar.api.rule.RuleKey; import org.sonar.check.Priority;
/* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.checks; /** * Checks for usage of the xdmp:log function. * * @since 1.1 */ @Rule( key = LogCheck.RULE_KEY, name = "Log Function Usage (Marklogic)", description = "Favor using xdmp:trace() instead of xdmp:log().\n" + "Please note that this check is Marklogic specific.", priority = Priority.MINOR) public class LogCheck extends AbstractProhibitFunctionCheck { public static final String RULE_KEY = "LogCheck";
// Path: src/main/java/org/sonar/plugins/xquery/rules/CheckClasses.java // public final class CheckClasses { // // public static final String REPOSITORY_KEY = "xquery"; // // private CheckClasses() { // } // // public static List<Class> getChecks() { // return ImmutableList.<Class>of( // DynamicFunctionCheck.class, // EffectiveBooleanCheck.class, // FunctionMappingCheck.class, // OperationsInPredicateCheck.class, // OrderByRangeCheck.class, // ParseErrorCheck.class, // StrongTypingInFLWORCheck.class, // StrongTypingInFunctionDeclarationCheck.class, // StrongTypingInModuleVariableCheck.class, // XPathDescendantStepsCheck.class, // XPathSubExpressionsInPredicateCheck.class, // XPathTextStepsCheck.class, // XQueryVersionCheck.class // ); // } // } // Path: src/main/java/org/sonar/plugins/xquery/checks/LogCheck.java import org.sonar.check.Rule; import org.sonar.plugins.xquery.rules.CheckClasses; import org.sonar.api.rule.RuleKey; import org.sonar.check.Priority; /* * © 2014 by Intellectual Reserve, Inc. All rights reserved. */ package org.sonar.plugins.xquery.checks; /** * Checks for usage of the xdmp:log function. * * @since 1.1 */ @Rule( key = LogCheck.RULE_KEY, name = "Log Function Usage (Marklogic)", description = "Favor using xdmp:trace() instead of xdmp:log().\n" + "Please note that this check is Marklogic specific.", priority = Priority.MINOR) public class LogCheck extends AbstractProhibitFunctionCheck { public static final String RULE_KEY = "LogCheck";
private static final RuleKey RULE = RuleKey.of(CheckClasses.REPOSITORY_KEY, RULE_KEY);
datafibers-community/df_data_service
src/main/java/com/datafibers/test_tool/KafkaClientTest.java
// Path: src/main/java/com/datafibers/util/KafkaAdminClient.java // public class KafkaAdminClient // { // private static final String DEFAULT_BOOTSTRAP_SERVERS_HOST_PORT = "localhost:9092"; // // public static AdminClient createAdminClient (String BOOTSTRAP_SERVERS_HOST_PORT) { // Properties props = new Properties(); // props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS_HOST_PORT); // return AdminClient.create(props); // } // // /** // * Given its name, checks if a topic exists on the Kafka broker. // * // * @param topicName The name of the topic. // * // * @return <code>true</code> if the topic exists on the broker, // * <code>false</code> if it doesn't. // */ // static boolean existsTopic (AdminClient adminClient, String topicName) { // try { // ListTopicsResult listTopicsResult = adminClient.listTopics(); // return listTopicsResult.names().get().contains(topicName); // // } catch (ExecutionException | InterruptedException e) { // e.printStackTrace(); // } // return false; // } // // /** // * Creates new topics, which remain persistent on the Kafka broker. // * // * @param topicName The names of the topic separated by ,. // * @param partitions The number of partitions in the topic. // * @param replication The number of brokers to host the topic. // */ // public static void createTopic (String BOOTSTRAP_SERVERS_HOST_PORT, String topicName, int partitions, int replication) { // AdminClient adminClient = createAdminClient(BOOTSTRAP_SERVERS_HOST_PORT); // if(!existsTopic(adminClient, topicName)) { // NewTopic topic = new NewTopic(topicName, partitions, (short)replication); // CreateTopicsResult createTopicsResult = adminClient.createTopics(Collections.singleton(topic)); // try { // createTopicsResult.all().get(); // // real failure cause is wrapped inside the raised ExecutionException // } catch (ExecutionException | InterruptedException e) { // e.printStackTrace(); // } finally { // adminClient.close(); // } // } else { // System.out.println(topicName + " already exists and will not create"); // } // } // // public static void createTopic (String topicName, int partitions, int replication) { // createTopic(DEFAULT_BOOTSTRAP_SERVERS_HOST_PORT, topicName, partitions, replication); // } // // public static void createTopic (String topicName) { // createTopic(DEFAULT_BOOTSTRAP_SERVERS_HOST_PORT, topicName, 1, 1); // } // // /** // * Given its name, deletes a topic on the Kafka broker. // * // * @param topicsName The name of the topic. // */ // public static void deleteTopics (String BOOTSTRAP_SERVERS_HOST_PORT, String topicsName) { // AdminClient adminClient = createAdminClient(BOOTSTRAP_SERVERS_HOST_PORT); // // remove topic which is not already exists // DeleteTopicsResult deleteTopicsResult = adminClient.deleteTopics(Arrays.asList(topicsName.split(","))); // try { // deleteTopicsResult.all().get(); // // real failure cause is wrapped inside the raised ExecutionException // } catch (ExecutionException | InterruptedException e) { // if (e.getCause() instanceof UnknownTopicOrPartitionException) { // System.err.println("Topic not exists !!"); // } else if (e.getCause() instanceof TimeoutException) { // System.err.println("Timeout !!"); // } // e.printStackTrace(); // } finally { // adminClient.close(); // } // } // // public static void deleteTopics (String topicsName) { // deleteTopics(DEFAULT_BOOTSTRAP_SERVERS_HOST_PORT, topicsName); // } // // /** // * Lists all topics on the Kafka broker. // */ // public static Set<String> listTopics (String BOOTSTRAP_SERVERS_HOST_PORT) { // AdminClient adminClient = createAdminClient(BOOTSTRAP_SERVERS_HOST_PORT); // try { // return adminClient.listTopics().names().get(); // } catch (ExecutionException | InterruptedException e) { // e.printStackTrace(); // } finally { // adminClient.close(); // } // return null; // } // // public static Set<String> listTopics () { // return listTopics(DEFAULT_BOOTSTRAP_SERVERS_HOST_PORT); // } // // /** // * Given its name, deletes a topic on the Kafka broker. // * // * @param topicsName The name of the topic. // */ // public static void describeTopics (String BOOTSTRAP_SERVERS_HOST_PORT, String topicsName) { // AdminClient adminClient = createAdminClient(BOOTSTRAP_SERVERS_HOST_PORT); // // remove topic which is not already exists // DescribeTopicsResult describeTopicsResult = adminClient.describeTopics(Arrays.asList(topicsName.split(","))); // try { // describeTopicsResult.all().get().forEach((key, value) -> { // System.out.println("Key : " + key + " Value : " + value); // }); // // real failure cause is wrapped inside the raised ExecutionException // } catch (ExecutionException | InterruptedException e) { // if (e.getCause() instanceof UnknownTopicOrPartitionException) { // System.err.println("Topic not exists !!"); // } else if (e.getCause() instanceof TimeoutException) { // System.err.println("Timeout !!"); // } // e.printStackTrace(); // } finally { // adminClient.close(); // } // } // // }
import com.datafibers.util.KafkaAdminClient;
package com.datafibers.test_tool; public class KafkaClientTest { public static void main(String[] args) {
// Path: src/main/java/com/datafibers/util/KafkaAdminClient.java // public class KafkaAdminClient // { // private static final String DEFAULT_BOOTSTRAP_SERVERS_HOST_PORT = "localhost:9092"; // // public static AdminClient createAdminClient (String BOOTSTRAP_SERVERS_HOST_PORT) { // Properties props = new Properties(); // props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVERS_HOST_PORT); // return AdminClient.create(props); // } // // /** // * Given its name, checks if a topic exists on the Kafka broker. // * // * @param topicName The name of the topic. // * // * @return <code>true</code> if the topic exists on the broker, // * <code>false</code> if it doesn't. // */ // static boolean existsTopic (AdminClient adminClient, String topicName) { // try { // ListTopicsResult listTopicsResult = adminClient.listTopics(); // return listTopicsResult.names().get().contains(topicName); // // } catch (ExecutionException | InterruptedException e) { // e.printStackTrace(); // } // return false; // } // // /** // * Creates new topics, which remain persistent on the Kafka broker. // * // * @param topicName The names of the topic separated by ,. // * @param partitions The number of partitions in the topic. // * @param replication The number of brokers to host the topic. // */ // public static void createTopic (String BOOTSTRAP_SERVERS_HOST_PORT, String topicName, int partitions, int replication) { // AdminClient adminClient = createAdminClient(BOOTSTRAP_SERVERS_HOST_PORT); // if(!existsTopic(adminClient, topicName)) { // NewTopic topic = new NewTopic(topicName, partitions, (short)replication); // CreateTopicsResult createTopicsResult = adminClient.createTopics(Collections.singleton(topic)); // try { // createTopicsResult.all().get(); // // real failure cause is wrapped inside the raised ExecutionException // } catch (ExecutionException | InterruptedException e) { // e.printStackTrace(); // } finally { // adminClient.close(); // } // } else { // System.out.println(topicName + " already exists and will not create"); // } // } // // public static void createTopic (String topicName, int partitions, int replication) { // createTopic(DEFAULT_BOOTSTRAP_SERVERS_HOST_PORT, topicName, partitions, replication); // } // // public static void createTopic (String topicName) { // createTopic(DEFAULT_BOOTSTRAP_SERVERS_HOST_PORT, topicName, 1, 1); // } // // /** // * Given its name, deletes a topic on the Kafka broker. // * // * @param topicsName The name of the topic. // */ // public static void deleteTopics (String BOOTSTRAP_SERVERS_HOST_PORT, String topicsName) { // AdminClient adminClient = createAdminClient(BOOTSTRAP_SERVERS_HOST_PORT); // // remove topic which is not already exists // DeleteTopicsResult deleteTopicsResult = adminClient.deleteTopics(Arrays.asList(topicsName.split(","))); // try { // deleteTopicsResult.all().get(); // // real failure cause is wrapped inside the raised ExecutionException // } catch (ExecutionException | InterruptedException e) { // if (e.getCause() instanceof UnknownTopicOrPartitionException) { // System.err.println("Topic not exists !!"); // } else if (e.getCause() instanceof TimeoutException) { // System.err.println("Timeout !!"); // } // e.printStackTrace(); // } finally { // adminClient.close(); // } // } // // public static void deleteTopics (String topicsName) { // deleteTopics(DEFAULT_BOOTSTRAP_SERVERS_HOST_PORT, topicsName); // } // // /** // * Lists all topics on the Kafka broker. // */ // public static Set<String> listTopics (String BOOTSTRAP_SERVERS_HOST_PORT) { // AdminClient adminClient = createAdminClient(BOOTSTRAP_SERVERS_HOST_PORT); // try { // return adminClient.listTopics().names().get(); // } catch (ExecutionException | InterruptedException e) { // e.printStackTrace(); // } finally { // adminClient.close(); // } // return null; // } // // public static Set<String> listTopics () { // return listTopics(DEFAULT_BOOTSTRAP_SERVERS_HOST_PORT); // } // // /** // * Given its name, deletes a topic on the Kafka broker. // * // * @param topicsName The name of the topic. // */ // public static void describeTopics (String BOOTSTRAP_SERVERS_HOST_PORT, String topicsName) { // AdminClient adminClient = createAdminClient(BOOTSTRAP_SERVERS_HOST_PORT); // // remove topic which is not already exists // DescribeTopicsResult describeTopicsResult = adminClient.describeTopics(Arrays.asList(topicsName.split(","))); // try { // describeTopicsResult.all().get().forEach((key, value) -> { // System.out.println("Key : " + key + " Value : " + value); // }); // // real failure cause is wrapped inside the raised ExecutionException // } catch (ExecutionException | InterruptedException e) { // if (e.getCause() instanceof UnknownTopicOrPartitionException) { // System.err.println("Topic not exists !!"); // } else if (e.getCause() instanceof TimeoutException) { // System.err.println("Timeout !!"); // } // e.printStackTrace(); // } finally { // adminClient.close(); // } // } // // } // Path: src/main/java/com/datafibers/test_tool/KafkaClientTest.java import com.datafibers.util.KafkaAdminClient; package com.datafibers.test_tool; public class KafkaClientTest { public static void main(String[] args) {
KafkaAdminClient.listTopics("localhost:9092")
wzgiceman/RxjavaRetrofitDemo-string-master
app/src/main/java/com/example/retrofit/activity/CombinApiActivity.java
// Path: app/src/main/java/com/example/retrofit/entity/api/CombinApi.java // public class CombinApi extends HttpManagerApi { // // public CombinApi(HttpOnNextListener onNextListener, RxAppCompatActivity appCompatActivity) { // super(onNextListener, appCompatActivity); // /*统一设置*/ // setCache(true); // } // // public CombinApi(HttpOnNextSubListener onNextSubListener, RxAppCompatActivity appCompatActivity) { // super(onNextSubListener, appCompatActivity); // /*统一设置*/ // setCache(true); // } // // // /** // * post请求演示 // * api-1 // * // * @param all 参数 // */ // public void postApi(final boolean all) { // /*也可单独设置请求,会覆盖统一设置*/ // setCache(false); // setMethod("AppFiftyToneGraph/videoLink"); // HttpPostService httpService = getRetrofit().create(HttpPostService.class); // doHttpDeal(httpService.getAllVedioBy(all)); // } // // /** // * post请求演示 // * api-2 // * // * @param all 参数 // */ // public void postApiOther(boolean all) { // setCache(true); // setMethod("AppFiftyToneGraph/videoLink"); // HttpPostService httpService = getRetrofit().create(HttpPostService.class); // doHttpDeal(httpService.getAllVedioBy(all)); // } // // } // // Path: app/src/main/java/com/example/retrofit/entity/resulte/BaseResultEntity.java // public class BaseResultEntity<T>{ // // 判断标示 // private int ret; // // 提示信息 // private String msg; // //显示数据(用户需要关心的数据) // private T data; // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // // public int getRet() { // return ret; // } // // public void setRet(int ret) { // this.ret = ret; // } // // public T getData() { // return data; // } // // public void setData(T data) { // this.data = data; // } // } // // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/exception/ApiException.java // public class ApiException extends Exception{ // /*错误码*/ // private int code; // /*显示的信息*/ // private String displayMessage; // // public ApiException(Throwable e) { // super(e); // } // // public ApiException(Throwable cause, int code, String showMsg) { // super(showMsg, cause); // setCode(code); // setDisplayMessage(showMsg); // } // // public int getCode() { // return code; // } // // public void setCode( int code) { // this.code = code; // } // // public String getDisplayMessage() { // return displayMessage; // } // // public void setDisplayMessage(String displayMessage) { // this.displayMessage = displayMessage; // } // } // // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/listener/HttpOnNextListener.java // public interface HttpOnNextListener { // /** // * 成功后回调方法 // * // * @param resulte // * @param method // */ // void onNext(String resulte, String method); // // /** // * 失败 // * 失败或者错误方法 // * 自定义异常处理 // * // * @param e // * @param method // */ // void onError(ApiException e, String method); // }
import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; import com.example.retrofit.R; import com.example.retrofit.entity.api.CombinApi; import com.example.retrofit.entity.resulte.BaseResultEntity; import com.example.retrofit.entity.resulte.SubjectResulte; import com.trello.rxlifecycle.components.support.RxAppCompatActivity; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.exception.ApiException; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener; import java.util.ArrayList;
package com.example.retrofit.activity; /** * 统一api类处理方案界面 * * @author wzg */ public class CombinApiActivity extends RxAppCompatActivity implements HttpOnNextListener { private TextView tvMsg;
// Path: app/src/main/java/com/example/retrofit/entity/api/CombinApi.java // public class CombinApi extends HttpManagerApi { // // public CombinApi(HttpOnNextListener onNextListener, RxAppCompatActivity appCompatActivity) { // super(onNextListener, appCompatActivity); // /*统一设置*/ // setCache(true); // } // // public CombinApi(HttpOnNextSubListener onNextSubListener, RxAppCompatActivity appCompatActivity) { // super(onNextSubListener, appCompatActivity); // /*统一设置*/ // setCache(true); // } // // // /** // * post请求演示 // * api-1 // * // * @param all 参数 // */ // public void postApi(final boolean all) { // /*也可单独设置请求,会覆盖统一设置*/ // setCache(false); // setMethod("AppFiftyToneGraph/videoLink"); // HttpPostService httpService = getRetrofit().create(HttpPostService.class); // doHttpDeal(httpService.getAllVedioBy(all)); // } // // /** // * post请求演示 // * api-2 // * // * @param all 参数 // */ // public void postApiOther(boolean all) { // setCache(true); // setMethod("AppFiftyToneGraph/videoLink"); // HttpPostService httpService = getRetrofit().create(HttpPostService.class); // doHttpDeal(httpService.getAllVedioBy(all)); // } // // } // // Path: app/src/main/java/com/example/retrofit/entity/resulte/BaseResultEntity.java // public class BaseResultEntity<T>{ // // 判断标示 // private int ret; // // 提示信息 // private String msg; // //显示数据(用户需要关心的数据) // private T data; // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // // public int getRet() { // return ret; // } // // public void setRet(int ret) { // this.ret = ret; // } // // public T getData() { // return data; // } // // public void setData(T data) { // this.data = data; // } // } // // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/exception/ApiException.java // public class ApiException extends Exception{ // /*错误码*/ // private int code; // /*显示的信息*/ // private String displayMessage; // // public ApiException(Throwable e) { // super(e); // } // // public ApiException(Throwable cause, int code, String showMsg) { // super(showMsg, cause); // setCode(code); // setDisplayMessage(showMsg); // } // // public int getCode() { // return code; // } // // public void setCode( int code) { // this.code = code; // } // // public String getDisplayMessage() { // return displayMessage; // } // // public void setDisplayMessage(String displayMessage) { // this.displayMessage = displayMessage; // } // } // // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/listener/HttpOnNextListener.java // public interface HttpOnNextListener { // /** // * 成功后回调方法 // * // * @param resulte // * @param method // */ // void onNext(String resulte, String method); // // /** // * 失败 // * 失败或者错误方法 // * 自定义异常处理 // * // * @param e // * @param method // */ // void onError(ApiException e, String method); // } // Path: app/src/main/java/com/example/retrofit/activity/CombinApiActivity.java import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; import com.example.retrofit.R; import com.example.retrofit.entity.api.CombinApi; import com.example.retrofit.entity.resulte.BaseResultEntity; import com.example.retrofit.entity.resulte.SubjectResulte; import com.trello.rxlifecycle.components.support.RxAppCompatActivity; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.exception.ApiException; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener; import java.util.ArrayList; package com.example.retrofit.activity; /** * 统一api类处理方案界面 * * @author wzg */ public class CombinApiActivity extends RxAppCompatActivity implements HttpOnNextListener { private TextView tvMsg;
CombinApi api;
wzgiceman/RxjavaRetrofitDemo-string-master
app/src/main/java/com/example/retrofit/activity/CombinApiActivity.java
// Path: app/src/main/java/com/example/retrofit/entity/api/CombinApi.java // public class CombinApi extends HttpManagerApi { // // public CombinApi(HttpOnNextListener onNextListener, RxAppCompatActivity appCompatActivity) { // super(onNextListener, appCompatActivity); // /*统一设置*/ // setCache(true); // } // // public CombinApi(HttpOnNextSubListener onNextSubListener, RxAppCompatActivity appCompatActivity) { // super(onNextSubListener, appCompatActivity); // /*统一设置*/ // setCache(true); // } // // // /** // * post请求演示 // * api-1 // * // * @param all 参数 // */ // public void postApi(final boolean all) { // /*也可单独设置请求,会覆盖统一设置*/ // setCache(false); // setMethod("AppFiftyToneGraph/videoLink"); // HttpPostService httpService = getRetrofit().create(HttpPostService.class); // doHttpDeal(httpService.getAllVedioBy(all)); // } // // /** // * post请求演示 // * api-2 // * // * @param all 参数 // */ // public void postApiOther(boolean all) { // setCache(true); // setMethod("AppFiftyToneGraph/videoLink"); // HttpPostService httpService = getRetrofit().create(HttpPostService.class); // doHttpDeal(httpService.getAllVedioBy(all)); // } // // } // // Path: app/src/main/java/com/example/retrofit/entity/resulte/BaseResultEntity.java // public class BaseResultEntity<T>{ // // 判断标示 // private int ret; // // 提示信息 // private String msg; // //显示数据(用户需要关心的数据) // private T data; // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // // public int getRet() { // return ret; // } // // public void setRet(int ret) { // this.ret = ret; // } // // public T getData() { // return data; // } // // public void setData(T data) { // this.data = data; // } // } // // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/exception/ApiException.java // public class ApiException extends Exception{ // /*错误码*/ // private int code; // /*显示的信息*/ // private String displayMessage; // // public ApiException(Throwable e) { // super(e); // } // // public ApiException(Throwable cause, int code, String showMsg) { // super(showMsg, cause); // setCode(code); // setDisplayMessage(showMsg); // } // // public int getCode() { // return code; // } // // public void setCode( int code) { // this.code = code; // } // // public String getDisplayMessage() { // return displayMessage; // } // // public void setDisplayMessage(String displayMessage) { // this.displayMessage = displayMessage; // } // } // // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/listener/HttpOnNextListener.java // public interface HttpOnNextListener { // /** // * 成功后回调方法 // * // * @param resulte // * @param method // */ // void onNext(String resulte, String method); // // /** // * 失败 // * 失败或者错误方法 // * 自定义异常处理 // * // * @param e // * @param method // */ // void onError(ApiException e, String method); // }
import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; import com.example.retrofit.R; import com.example.retrofit.entity.api.CombinApi; import com.example.retrofit.entity.resulte.BaseResultEntity; import com.example.retrofit.entity.resulte.SubjectResulte; import com.trello.rxlifecycle.components.support.RxAppCompatActivity; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.exception.ApiException; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener; import java.util.ArrayList;
package com.example.retrofit.activity; /** * 统一api类处理方案界面 * * @author wzg */ public class CombinApiActivity extends RxAppCompatActivity implements HttpOnNextListener { private TextView tvMsg; CombinApi api; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_combin_api); api = new CombinApi(this, this); tvMsg = (TextView) findViewById(R.id.tv_msg); findViewById(R.id.btn_rx_all).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { api.postApi(true); } }); findViewById(R.id.btn_rx_all_2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { api.postApiOther(true); } }); } @Override public void onNext(String resulte, String method) {
// Path: app/src/main/java/com/example/retrofit/entity/api/CombinApi.java // public class CombinApi extends HttpManagerApi { // // public CombinApi(HttpOnNextListener onNextListener, RxAppCompatActivity appCompatActivity) { // super(onNextListener, appCompatActivity); // /*统一设置*/ // setCache(true); // } // // public CombinApi(HttpOnNextSubListener onNextSubListener, RxAppCompatActivity appCompatActivity) { // super(onNextSubListener, appCompatActivity); // /*统一设置*/ // setCache(true); // } // // // /** // * post请求演示 // * api-1 // * // * @param all 参数 // */ // public void postApi(final boolean all) { // /*也可单独设置请求,会覆盖统一设置*/ // setCache(false); // setMethod("AppFiftyToneGraph/videoLink"); // HttpPostService httpService = getRetrofit().create(HttpPostService.class); // doHttpDeal(httpService.getAllVedioBy(all)); // } // // /** // * post请求演示 // * api-2 // * // * @param all 参数 // */ // public void postApiOther(boolean all) { // setCache(true); // setMethod("AppFiftyToneGraph/videoLink"); // HttpPostService httpService = getRetrofit().create(HttpPostService.class); // doHttpDeal(httpService.getAllVedioBy(all)); // } // // } // // Path: app/src/main/java/com/example/retrofit/entity/resulte/BaseResultEntity.java // public class BaseResultEntity<T>{ // // 判断标示 // private int ret; // // 提示信息 // private String msg; // //显示数据(用户需要关心的数据) // private T data; // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // // public int getRet() { // return ret; // } // // public void setRet(int ret) { // this.ret = ret; // } // // public T getData() { // return data; // } // // public void setData(T data) { // this.data = data; // } // } // // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/exception/ApiException.java // public class ApiException extends Exception{ // /*错误码*/ // private int code; // /*显示的信息*/ // private String displayMessage; // // public ApiException(Throwable e) { // super(e); // } // // public ApiException(Throwable cause, int code, String showMsg) { // super(showMsg, cause); // setCode(code); // setDisplayMessage(showMsg); // } // // public int getCode() { // return code; // } // // public void setCode( int code) { // this.code = code; // } // // public String getDisplayMessage() { // return displayMessage; // } // // public void setDisplayMessage(String displayMessage) { // this.displayMessage = displayMessage; // } // } // // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/listener/HttpOnNextListener.java // public interface HttpOnNextListener { // /** // * 成功后回调方法 // * // * @param resulte // * @param method // */ // void onNext(String resulte, String method); // // /** // * 失败 // * 失败或者错误方法 // * 自定义异常处理 // * // * @param e // * @param method // */ // void onError(ApiException e, String method); // } // Path: app/src/main/java/com/example/retrofit/activity/CombinApiActivity.java import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; import com.example.retrofit.R; import com.example.retrofit.entity.api.CombinApi; import com.example.retrofit.entity.resulte.BaseResultEntity; import com.example.retrofit.entity.resulte.SubjectResulte; import com.trello.rxlifecycle.components.support.RxAppCompatActivity; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.exception.ApiException; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener; import java.util.ArrayList; package com.example.retrofit.activity; /** * 统一api类处理方案界面 * * @author wzg */ public class CombinApiActivity extends RxAppCompatActivity implements HttpOnNextListener { private TextView tvMsg; CombinApi api; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_combin_api); api = new CombinApi(this, this); tvMsg = (TextView) findViewById(R.id.tv_msg); findViewById(R.id.btn_rx_all).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { api.postApi(true); } }); findViewById(R.id.btn_rx_all_2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { api.postApiOther(true); } }); } @Override public void onNext(String resulte, String method) {
BaseResultEntity<ArrayList<SubjectResulte>> subjectResulte = JSONObject.parseObject(resulte, new
wzgiceman/RxjavaRetrofitDemo-string-master
app/src/main/java/com/example/retrofit/activity/CombinApiActivity.java
// Path: app/src/main/java/com/example/retrofit/entity/api/CombinApi.java // public class CombinApi extends HttpManagerApi { // // public CombinApi(HttpOnNextListener onNextListener, RxAppCompatActivity appCompatActivity) { // super(onNextListener, appCompatActivity); // /*统一设置*/ // setCache(true); // } // // public CombinApi(HttpOnNextSubListener onNextSubListener, RxAppCompatActivity appCompatActivity) { // super(onNextSubListener, appCompatActivity); // /*统一设置*/ // setCache(true); // } // // // /** // * post请求演示 // * api-1 // * // * @param all 参数 // */ // public void postApi(final boolean all) { // /*也可单独设置请求,会覆盖统一设置*/ // setCache(false); // setMethod("AppFiftyToneGraph/videoLink"); // HttpPostService httpService = getRetrofit().create(HttpPostService.class); // doHttpDeal(httpService.getAllVedioBy(all)); // } // // /** // * post请求演示 // * api-2 // * // * @param all 参数 // */ // public void postApiOther(boolean all) { // setCache(true); // setMethod("AppFiftyToneGraph/videoLink"); // HttpPostService httpService = getRetrofit().create(HttpPostService.class); // doHttpDeal(httpService.getAllVedioBy(all)); // } // // } // // Path: app/src/main/java/com/example/retrofit/entity/resulte/BaseResultEntity.java // public class BaseResultEntity<T>{ // // 判断标示 // private int ret; // // 提示信息 // private String msg; // //显示数据(用户需要关心的数据) // private T data; // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // // public int getRet() { // return ret; // } // // public void setRet(int ret) { // this.ret = ret; // } // // public T getData() { // return data; // } // // public void setData(T data) { // this.data = data; // } // } // // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/exception/ApiException.java // public class ApiException extends Exception{ // /*错误码*/ // private int code; // /*显示的信息*/ // private String displayMessage; // // public ApiException(Throwable e) { // super(e); // } // // public ApiException(Throwable cause, int code, String showMsg) { // super(showMsg, cause); // setCode(code); // setDisplayMessage(showMsg); // } // // public int getCode() { // return code; // } // // public void setCode( int code) { // this.code = code; // } // // public String getDisplayMessage() { // return displayMessage; // } // // public void setDisplayMessage(String displayMessage) { // this.displayMessage = displayMessage; // } // } // // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/listener/HttpOnNextListener.java // public interface HttpOnNextListener { // /** // * 成功后回调方法 // * // * @param resulte // * @param method // */ // void onNext(String resulte, String method); // // /** // * 失败 // * 失败或者错误方法 // * 自定义异常处理 // * // * @param e // * @param method // */ // void onError(ApiException e, String method); // }
import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; import com.example.retrofit.R; import com.example.retrofit.entity.api.CombinApi; import com.example.retrofit.entity.resulte.BaseResultEntity; import com.example.retrofit.entity.resulte.SubjectResulte; import com.trello.rxlifecycle.components.support.RxAppCompatActivity; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.exception.ApiException; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener; import java.util.ArrayList;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_combin_api); api = new CombinApi(this, this); tvMsg = (TextView) findViewById(R.id.tv_msg); findViewById(R.id.btn_rx_all).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { api.postApi(true); } }); findViewById(R.id.btn_rx_all_2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { api.postApiOther(true); } }); } @Override public void onNext(String resulte, String method) { BaseResultEntity<ArrayList<SubjectResulte>> subjectResulte = JSONObject.parseObject(resulte, new TypeReference<BaseResultEntity<ArrayList<SubjectResulte>>>() { }); tvMsg.setText("统一post返回:\n" + subjectResulte.getData().toString()); } @Override
// Path: app/src/main/java/com/example/retrofit/entity/api/CombinApi.java // public class CombinApi extends HttpManagerApi { // // public CombinApi(HttpOnNextListener onNextListener, RxAppCompatActivity appCompatActivity) { // super(onNextListener, appCompatActivity); // /*统一设置*/ // setCache(true); // } // // public CombinApi(HttpOnNextSubListener onNextSubListener, RxAppCompatActivity appCompatActivity) { // super(onNextSubListener, appCompatActivity); // /*统一设置*/ // setCache(true); // } // // // /** // * post请求演示 // * api-1 // * // * @param all 参数 // */ // public void postApi(final boolean all) { // /*也可单独设置请求,会覆盖统一设置*/ // setCache(false); // setMethod("AppFiftyToneGraph/videoLink"); // HttpPostService httpService = getRetrofit().create(HttpPostService.class); // doHttpDeal(httpService.getAllVedioBy(all)); // } // // /** // * post请求演示 // * api-2 // * // * @param all 参数 // */ // public void postApiOther(boolean all) { // setCache(true); // setMethod("AppFiftyToneGraph/videoLink"); // HttpPostService httpService = getRetrofit().create(HttpPostService.class); // doHttpDeal(httpService.getAllVedioBy(all)); // } // // } // // Path: app/src/main/java/com/example/retrofit/entity/resulte/BaseResultEntity.java // public class BaseResultEntity<T>{ // // 判断标示 // private int ret; // // 提示信息 // private String msg; // //显示数据(用户需要关心的数据) // private T data; // // public String getMsg() { // return msg; // } // // public void setMsg(String msg) { // this.msg = msg; // } // // // public int getRet() { // return ret; // } // // public void setRet(int ret) { // this.ret = ret; // } // // public T getData() { // return data; // } // // public void setData(T data) { // this.data = data; // } // } // // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/exception/ApiException.java // public class ApiException extends Exception{ // /*错误码*/ // private int code; // /*显示的信息*/ // private String displayMessage; // // public ApiException(Throwable e) { // super(e); // } // // public ApiException(Throwable cause, int code, String showMsg) { // super(showMsg, cause); // setCode(code); // setDisplayMessage(showMsg); // } // // public int getCode() { // return code; // } // // public void setCode( int code) { // this.code = code; // } // // public String getDisplayMessage() { // return displayMessage; // } // // public void setDisplayMessage(String displayMessage) { // this.displayMessage = displayMessage; // } // } // // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/listener/HttpOnNextListener.java // public interface HttpOnNextListener { // /** // * 成功后回调方法 // * // * @param resulte // * @param method // */ // void onNext(String resulte, String method); // // /** // * 失败 // * 失败或者错误方法 // * 自定义异常处理 // * // * @param e // * @param method // */ // void onError(ApiException e, String method); // } // Path: app/src/main/java/com/example/retrofit/activity/CombinApiActivity.java import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; import com.example.retrofit.R; import com.example.retrofit.entity.api.CombinApi; import com.example.retrofit.entity.resulte.BaseResultEntity; import com.example.retrofit.entity.resulte.SubjectResulte; import com.trello.rxlifecycle.components.support.RxAppCompatActivity; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.exception.ApiException; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener; import java.util.ArrayList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_combin_api); api = new CombinApi(this, this); tvMsg = (TextView) findViewById(R.id.tv_msg); findViewById(R.id.btn_rx_all).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { api.postApi(true); } }); findViewById(R.id.btn_rx_all_2).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { api.postApiOther(true); } }); } @Override public void onNext(String resulte, String method) { BaseResultEntity<ArrayList<SubjectResulte>> subjectResulte = JSONObject.parseObject(resulte, new TypeReference<BaseResultEntity<ArrayList<SubjectResulte>>>() { }); tvMsg.setText("统一post返回:\n" + subjectResulte.getData().toString()); } @Override
public void onError(ApiException e, String method) {
wzgiceman/RxjavaRetrofitDemo-string-master
rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/http/func/ExceptionFunc.java
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/exception/FactoryException.java // public class FactoryException { // private static final String HttpException_MSG = "网络错误"; // private static final String ConnectException_MSG = "连接失败"; // private static final String JSONException_MSG = "fastjeson解析失败"; // private static final String UnknownHostException_MSG = "无法解析该域名"; // // /** // * 解析异常 // * // * @param e // * @return // */ // public static ApiException analysisExcetpion(Throwable e) { // ApiException apiException = new ApiException(e); // if (e instanceof HttpException) { // /*网络异常*/ // apiException.setCode(CodeException.HTTP_ERROR); // apiException.setDisplayMessage(HttpException_MSG); // } else if (e instanceof HttpTimeException) { // /*自定义运行时异常*/ // HttpTimeException exception = (HttpTimeException) e; // apiException.setCode(CodeException.RUNTIME_ERROR); // apiException.setDisplayMessage(exception.getMessage()); // } else if (e instanceof ConnectException||e instanceof SocketTimeoutException) { // /*链接异常*/ // apiException.setCode(CodeException.HTTP_ERROR); // apiException.setDisplayMessage(ConnectException_MSG); // } else if ( e instanceof JSONException || e instanceof ParseException) { // apiException.setCode(CodeException.JSON_ERROR); // apiException.setDisplayMessage(JSONException_MSG); // }else if (e instanceof UnknownHostException){ // /*无法解析该域名异常*/ // apiException.setCode(CodeException.UNKOWNHOST_ERROR); // apiException.setDisplayMessage(UnknownHostException_MSG); // } else { // /*未知异常*/ // apiException.setCode(CodeException.UNKNOWN_ERROR); // apiException.setDisplayMessage(e.getMessage()); // } // return apiException; // } // }
import android.util.Log; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.exception.FactoryException; import rx.Observable; import rx.functions.Func1;
package com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.func; /** * 异常处理 * Created by WZG on 2017/3/23. */ public class ExceptionFunc implements Func1<Throwable, Observable> { @Override public Observable call(Throwable throwable) { Log.e("Tag","-------->"+throwable.getMessage());
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/exception/FactoryException.java // public class FactoryException { // private static final String HttpException_MSG = "网络错误"; // private static final String ConnectException_MSG = "连接失败"; // private static final String JSONException_MSG = "fastjeson解析失败"; // private static final String UnknownHostException_MSG = "无法解析该域名"; // // /** // * 解析异常 // * // * @param e // * @return // */ // public static ApiException analysisExcetpion(Throwable e) { // ApiException apiException = new ApiException(e); // if (e instanceof HttpException) { // /*网络异常*/ // apiException.setCode(CodeException.HTTP_ERROR); // apiException.setDisplayMessage(HttpException_MSG); // } else if (e instanceof HttpTimeException) { // /*自定义运行时异常*/ // HttpTimeException exception = (HttpTimeException) e; // apiException.setCode(CodeException.RUNTIME_ERROR); // apiException.setDisplayMessage(exception.getMessage()); // } else if (e instanceof ConnectException||e instanceof SocketTimeoutException) { // /*链接异常*/ // apiException.setCode(CodeException.HTTP_ERROR); // apiException.setDisplayMessage(ConnectException_MSG); // } else if ( e instanceof JSONException || e instanceof ParseException) { // apiException.setCode(CodeException.JSON_ERROR); // apiException.setDisplayMessage(JSONException_MSG); // }else if (e instanceof UnknownHostException){ // /*无法解析该域名异常*/ // apiException.setCode(CodeException.UNKOWNHOST_ERROR); // apiException.setDisplayMessage(UnknownHostException_MSG); // } else { // /*未知异常*/ // apiException.setCode(CodeException.UNKNOWN_ERROR); // apiException.setDisplayMessage(e.getMessage()); // } // return apiException; // } // } // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/http/func/ExceptionFunc.java import android.util.Log; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.exception.FactoryException; import rx.Observable; import rx.functions.Func1; package com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.func; /** * 异常处理 * Created by WZG on 2017/3/23. */ public class ExceptionFunc implements Func1<Throwable, Observable> { @Override public Observable call(Throwable throwable) { Log.e("Tag","-------->"+throwable.getMessage());
return Observable.error(FactoryException.analysisExcetpion(throwable));
wzgiceman/RxjavaRetrofitDemo-string-master
app/src/main/java/com/example/retrofit/entity/api/CombinApi.java
// Path: app/src/main/java/com/example/retrofit/HttpPostService.java // public interface HttpPostService { // // // @GET("AppFiftyToneGraph/videoLink/{once_no}") // Observable<String> getAllVedioBy(@Query("once_no") boolean once_no); // // } // // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/Api/HttpManagerApi.java // public class HttpManagerApi extends BaseApi { // private HttpManager manager; // // public HttpManagerApi(HttpOnNextListener onNextListener, RxAppCompatActivity appCompatActivity) { // manager = new HttpManager(onNextListener, appCompatActivity); // } // // public HttpManagerApi(HttpOnNextSubListener onNextSubListener, RxAppCompatActivity appCompatActivity) { // manager = new HttpManager(onNextSubListener, appCompatActivity); // } // // protected Retrofit getRetrofit() { // return manager.getReTrofit(this); // } // // // protected void doHttpDeal(Retrofit retrofit) { // manager.httpDeal(retrofit, this); // } // // @Override // public Observable getObservable(Retrofit retrofit) { // return null; // } // } // // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/listener/HttpOnNextListener.java // public interface HttpOnNextListener { // /** // * 成功后回调方法 // * // * @param resulte // * @param method // */ // void onNext(String resulte, String method); // // /** // * 失败 // * 失败或者错误方法 // * 自定义异常处理 // * // * @param e // * @param method // */ // void onError(ApiException e, String method); // } // // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/listener/HttpOnNextSubListener.java // public interface HttpOnNextSubListener { // // /** // * ober成功回调 // * @param observable // * @param method // */ // void onNext(Observable observable,String method); // }
import com.example.retrofit.HttpPostService; import com.trello.rxlifecycle.components.support.RxAppCompatActivity; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.Api.HttpManagerApi; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextSubListener;
package com.example.retrofit.entity.api; /** * 多api共存方案 * Created by WZG on 2017/4/13. */ public class CombinApi extends HttpManagerApi { public CombinApi(HttpOnNextListener onNextListener, RxAppCompatActivity appCompatActivity) { super(onNextListener, appCompatActivity); /*统一设置*/ setCache(true); }
// Path: app/src/main/java/com/example/retrofit/HttpPostService.java // public interface HttpPostService { // // // @GET("AppFiftyToneGraph/videoLink/{once_no}") // Observable<String> getAllVedioBy(@Query("once_no") boolean once_no); // // } // // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/Api/HttpManagerApi.java // public class HttpManagerApi extends BaseApi { // private HttpManager manager; // // public HttpManagerApi(HttpOnNextListener onNextListener, RxAppCompatActivity appCompatActivity) { // manager = new HttpManager(onNextListener, appCompatActivity); // } // // public HttpManagerApi(HttpOnNextSubListener onNextSubListener, RxAppCompatActivity appCompatActivity) { // manager = new HttpManager(onNextSubListener, appCompatActivity); // } // // protected Retrofit getRetrofit() { // return manager.getReTrofit(this); // } // // // protected void doHttpDeal(Retrofit retrofit) { // manager.httpDeal(retrofit, this); // } // // @Override // public Observable getObservable(Retrofit retrofit) { // return null; // } // } // // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/listener/HttpOnNextListener.java // public interface HttpOnNextListener { // /** // * 成功后回调方法 // * // * @param resulte // * @param method // */ // void onNext(String resulte, String method); // // /** // * 失败 // * 失败或者错误方法 // * 自定义异常处理 // * // * @param e // * @param method // */ // void onError(ApiException e, String method); // } // // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/listener/HttpOnNextSubListener.java // public interface HttpOnNextSubListener { // // /** // * ober成功回调 // * @param observable // * @param method // */ // void onNext(Observable observable,String method); // } // Path: app/src/main/java/com/example/retrofit/entity/api/CombinApi.java import com.example.retrofit.HttpPostService; import com.trello.rxlifecycle.components.support.RxAppCompatActivity; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.Api.HttpManagerApi; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextSubListener; package com.example.retrofit.entity.api; /** * 多api共存方案 * Created by WZG on 2017/4/13. */ public class CombinApi extends HttpManagerApi { public CombinApi(HttpOnNextListener onNextListener, RxAppCompatActivity appCompatActivity) { super(onNextListener, appCompatActivity); /*统一设置*/ setCache(true); }
public CombinApi(HttpOnNextSubListener onNextSubListener, RxAppCompatActivity appCompatActivity) {
wzgiceman/RxjavaRetrofitDemo-string-master
app/src/main/java/com/example/retrofit/entity/api/CombinApi.java
// Path: app/src/main/java/com/example/retrofit/HttpPostService.java // public interface HttpPostService { // // // @GET("AppFiftyToneGraph/videoLink/{once_no}") // Observable<String> getAllVedioBy(@Query("once_no") boolean once_no); // // } // // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/Api/HttpManagerApi.java // public class HttpManagerApi extends BaseApi { // private HttpManager manager; // // public HttpManagerApi(HttpOnNextListener onNextListener, RxAppCompatActivity appCompatActivity) { // manager = new HttpManager(onNextListener, appCompatActivity); // } // // public HttpManagerApi(HttpOnNextSubListener onNextSubListener, RxAppCompatActivity appCompatActivity) { // manager = new HttpManager(onNextSubListener, appCompatActivity); // } // // protected Retrofit getRetrofit() { // return manager.getReTrofit(this); // } // // // protected void doHttpDeal(Retrofit retrofit) { // manager.httpDeal(retrofit, this); // } // // @Override // public Observable getObservable(Retrofit retrofit) { // return null; // } // } // // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/listener/HttpOnNextListener.java // public interface HttpOnNextListener { // /** // * 成功后回调方法 // * // * @param resulte // * @param method // */ // void onNext(String resulte, String method); // // /** // * 失败 // * 失败或者错误方法 // * 自定义异常处理 // * // * @param e // * @param method // */ // void onError(ApiException e, String method); // } // // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/listener/HttpOnNextSubListener.java // public interface HttpOnNextSubListener { // // /** // * ober成功回调 // * @param observable // * @param method // */ // void onNext(Observable observable,String method); // }
import com.example.retrofit.HttpPostService; import com.trello.rxlifecycle.components.support.RxAppCompatActivity; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.Api.HttpManagerApi; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextSubListener;
package com.example.retrofit.entity.api; /** * 多api共存方案 * Created by WZG on 2017/4/13. */ public class CombinApi extends HttpManagerApi { public CombinApi(HttpOnNextListener onNextListener, RxAppCompatActivity appCompatActivity) { super(onNextListener, appCompatActivity); /*统一设置*/ setCache(true); } public CombinApi(HttpOnNextSubListener onNextSubListener, RxAppCompatActivity appCompatActivity) { super(onNextSubListener, appCompatActivity); /*统一设置*/ setCache(true); } /** * post请求演示 * api-1 * * @param all 参数 */ public void postApi(final boolean all) { /*也可单独设置请求,会覆盖统一设置*/ setCache(false); setMethod("AppFiftyToneGraph/videoLink");
// Path: app/src/main/java/com/example/retrofit/HttpPostService.java // public interface HttpPostService { // // // @GET("AppFiftyToneGraph/videoLink/{once_no}") // Observable<String> getAllVedioBy(@Query("once_no") boolean once_no); // // } // // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/Api/HttpManagerApi.java // public class HttpManagerApi extends BaseApi { // private HttpManager manager; // // public HttpManagerApi(HttpOnNextListener onNextListener, RxAppCompatActivity appCompatActivity) { // manager = new HttpManager(onNextListener, appCompatActivity); // } // // public HttpManagerApi(HttpOnNextSubListener onNextSubListener, RxAppCompatActivity appCompatActivity) { // manager = new HttpManager(onNextSubListener, appCompatActivity); // } // // protected Retrofit getRetrofit() { // return manager.getReTrofit(this); // } // // // protected void doHttpDeal(Retrofit retrofit) { // manager.httpDeal(retrofit, this); // } // // @Override // public Observable getObservable(Retrofit retrofit) { // return null; // } // } // // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/listener/HttpOnNextListener.java // public interface HttpOnNextListener { // /** // * 成功后回调方法 // * // * @param resulte // * @param method // */ // void onNext(String resulte, String method); // // /** // * 失败 // * 失败或者错误方法 // * 自定义异常处理 // * // * @param e // * @param method // */ // void onError(ApiException e, String method); // } // // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/listener/HttpOnNextSubListener.java // public interface HttpOnNextSubListener { // // /** // * ober成功回调 // * @param observable // * @param method // */ // void onNext(Observable observable,String method); // } // Path: app/src/main/java/com/example/retrofit/entity/api/CombinApi.java import com.example.retrofit.HttpPostService; import com.trello.rxlifecycle.components.support.RxAppCompatActivity; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.Api.HttpManagerApi; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextSubListener; package com.example.retrofit.entity.api; /** * 多api共存方案 * Created by WZG on 2017/4/13. */ public class CombinApi extends HttpManagerApi { public CombinApi(HttpOnNextListener onNextListener, RxAppCompatActivity appCompatActivity) { super(onNextListener, appCompatActivity); /*统一设置*/ setCache(true); } public CombinApi(HttpOnNextSubListener onNextSubListener, RxAppCompatActivity appCompatActivity) { super(onNextSubListener, appCompatActivity); /*统一设置*/ setCache(true); } /** * post请求演示 * api-1 * * @param all 参数 */ public void postApi(final boolean all) { /*也可单独设置请求,会覆盖统一设置*/ setCache(false); setMethod("AppFiftyToneGraph/videoLink");
HttpPostService httpService = getRetrofit().create(HttpPostService.class);
wzgiceman/RxjavaRetrofitDemo-string-master
rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/utils/CookieDbUtil.java
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/RxRetrofitApp.java // public class RxRetrofitApp { // private static Application application; // private static boolean debug; // // // public static void init(Application app){ // setApplication(app); // setDebug(true); // } // // public static void init(Application app,boolean debug){ // setApplication(app); // setDebug(debug); // } // // public static Application getApplication() { // return application; // } // // private static void setApplication(Application application) { // RxRetrofitApp.application = application; // } // // public static boolean isDebug() { // return debug; // } // // public static void setDebug(boolean debug) { // RxRetrofitApp.debug = debug; // } // }
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.RxRetrofitApp; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.cookie.CookieResulte; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.cookie.CookieResulteDao; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.cookie.DaoMaster; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.cookie.DaoSession; import org.greenrobot.greendao.query.QueryBuilder; import java.util.List;
package com.wzgiceman.rxretrofitlibrary.retrofit_rx.utils; /** * 数据缓存 * 数据库工具类-geendao运用 * Created by WZG on 2016/10/25. */ public class CookieDbUtil { private static CookieDbUtil db; private final static String dbName = "tests_db"; private DaoMaster.DevOpenHelper openHelper; private Context context; public CookieDbUtil() {
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/RxRetrofitApp.java // public class RxRetrofitApp { // private static Application application; // private static boolean debug; // // // public static void init(Application app){ // setApplication(app); // setDebug(true); // } // // public static void init(Application app,boolean debug){ // setApplication(app); // setDebug(debug); // } // // public static Application getApplication() { // return application; // } // // private static void setApplication(Application application) { // RxRetrofitApp.application = application; // } // // public static boolean isDebug() { // return debug; // } // // public static void setDebug(boolean debug) { // RxRetrofitApp.debug = debug; // } // } // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/utils/CookieDbUtil.java import android.content.Context; import android.database.sqlite.SQLiteDatabase; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.RxRetrofitApp; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.cookie.CookieResulte; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.cookie.CookieResulteDao; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.cookie.DaoMaster; import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.cookie.DaoSession; import org.greenrobot.greendao.query.QueryBuilder; import java.util.List; package com.wzgiceman.rxretrofitlibrary.retrofit_rx.utils; /** * 数据缓存 * 数据库工具类-geendao运用 * Created by WZG on 2016/10/25. */ public class CookieDbUtil { private static CookieDbUtil db; private final static String dbName = "tests_db"; private DaoMaster.DevOpenHelper openHelper; private Context context; public CookieDbUtil() {
context= RxRetrofitApp.getApplication();
wzgiceman/RxjavaRetrofitDemo-string-master
rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/http/func/ResulteFunc.java
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/exception/HttpTimeException.java // public class HttpTimeException extends RuntimeException { // /*未知错误*/ // public static final int UNKNOWN_ERROR = 0x1002; // /*本地无缓存错误*/ // public static final int NO_CHACHE_ERROR = 0x1003; // /*缓存过时错误*/ // public static final int CHACHE_TIMEOUT_ERROR = 0x1004; // /*断点下载错误*/ // public static final int CHACHE_DOWN_ERROR = 0x1005; // /*服务器down了,无返回数据*/ // public static final int CHACHE_HTTP_ERROR = 0x1006; // /*tokean过期,需要重新登录*/ // public static final int CHACHE_TOKEAN_ERROR = 0x1007; // /*http请求返回失败*/ // public static final int CHACHE_HTTP_POST_ERROR = 0x1008; // /*用户在其他设备登录*/ // public static final int CHACHE_MORE_LOGIN_ERROR = 0x1009; // /*交互取消*/ // public static final int HTTP_CANCEL = 0x1010; // /*交互取消*/ // public static final int HTTP_DATA_NULL = 0x1011; // /*获取tokean失败*/ // public static final int HTTP_TOKEAN_ERROR = 0x10112; // /*CONFIG失败*/ // public static final int HTTP_CONFIG_ERROR = 0x10118; // /*下周文件写入io错误*/ // public static final int HTTP_DOWN_WRITE = 0x10119; // // /** // * 服务器定义的错误code // */ // private int code; // // public HttpTimeException(int code, String detailMessage) { // super(detailMessage); // setCode(code); // } // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // }
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.exception.HttpTimeException; import rx.functions.Func1;
package com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.func; /** * 服务器返回数据判断 * Created by WZG on 2017/3/23. */ public class ResulteFunc implements Func1<Object, Object> { @Override public Object call(Object o) { if (o == null || "".equals(o.toString())) {
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/exception/HttpTimeException.java // public class HttpTimeException extends RuntimeException { // /*未知错误*/ // public static final int UNKNOWN_ERROR = 0x1002; // /*本地无缓存错误*/ // public static final int NO_CHACHE_ERROR = 0x1003; // /*缓存过时错误*/ // public static final int CHACHE_TIMEOUT_ERROR = 0x1004; // /*断点下载错误*/ // public static final int CHACHE_DOWN_ERROR = 0x1005; // /*服务器down了,无返回数据*/ // public static final int CHACHE_HTTP_ERROR = 0x1006; // /*tokean过期,需要重新登录*/ // public static final int CHACHE_TOKEAN_ERROR = 0x1007; // /*http请求返回失败*/ // public static final int CHACHE_HTTP_POST_ERROR = 0x1008; // /*用户在其他设备登录*/ // public static final int CHACHE_MORE_LOGIN_ERROR = 0x1009; // /*交互取消*/ // public static final int HTTP_CANCEL = 0x1010; // /*交互取消*/ // public static final int HTTP_DATA_NULL = 0x1011; // /*获取tokean失败*/ // public static final int HTTP_TOKEAN_ERROR = 0x10112; // /*CONFIG失败*/ // public static final int HTTP_CONFIG_ERROR = 0x10118; // /*下周文件写入io错误*/ // public static final int HTTP_DOWN_WRITE = 0x10119; // // /** // * 服务器定义的错误code // */ // private int code; // // public HttpTimeException(int code, String detailMessage) { // super(detailMessage); // setCode(code); // } // // public int getCode() { // return code; // } // // public void setCode(int code) { // this.code = code; // } // } // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/http/func/ResulteFunc.java import com.wzgiceman.rxretrofitlibrary.retrofit_rx.exception.HttpTimeException; import rx.functions.Func1; package com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.func; /** * 服务器返回数据判断 * Created by WZG on 2017/3/23. */ public class ResulteFunc implements Func1<Object, Object> { @Override public Object call(Object o) { if (o == null || "".equals(o.toString())) {
throw new HttpTimeException(HttpTimeException.CHACHE_HTTP_POST_ERROR, "数据错误");
wzgiceman/RxjavaRetrofitDemo-string-master
rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/listener/HttpOnNextListener.java
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/exception/ApiException.java // public class ApiException extends Exception{ // /*错误码*/ // private int code; // /*显示的信息*/ // private String displayMessage; // // public ApiException(Throwable e) { // super(e); // } // // public ApiException(Throwable cause, int code, String showMsg) { // super(showMsg, cause); // setCode(code); // setDisplayMessage(showMsg); // } // // public int getCode() { // return code; // } // // public void setCode( int code) { // this.code = code; // } // // public String getDisplayMessage() { // return displayMessage; // } // // public void setDisplayMessage(String displayMessage) { // this.displayMessage = displayMessage; // } // }
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.exception.ApiException;
package com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener; /** * 成功回调处理 * Created by WZG on 2016/7/16. */ public interface HttpOnNextListener { /** * 成功后回调方法 * * @param resulte * @param method */ void onNext(String resulte, String method); /** * 失败 * 失败或者错误方法 * 自定义异常处理 * * @param e * @param method */
// Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/exception/ApiException.java // public class ApiException extends Exception{ // /*错误码*/ // private int code; // /*显示的信息*/ // private String displayMessage; // // public ApiException(Throwable e) { // super(e); // } // // public ApiException(Throwable cause, int code, String showMsg) { // super(showMsg, cause); // setCode(code); // setDisplayMessage(showMsg); // } // // public int getCode() { // return code; // } // // public void setCode( int code) { // this.code = code; // } // // public String getDisplayMessage() { // return displayMessage; // } // // public void setDisplayMessage(String displayMessage) { // this.displayMessage = displayMessage; // } // } // Path: rxretrofitlibrary/src/main/java/com/wzgiceman/rxretrofitlibrary/retrofit_rx/listener/HttpOnNextListener.java import com.wzgiceman.rxretrofitlibrary.retrofit_rx.exception.ApiException; package com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener; /** * 成功回调处理 * Created by WZG on 2016/7/16. */ public interface HttpOnNextListener { /** * 成功后回调方法 * * @param resulte * @param method */ void onNext(String resulte, String method); /** * 失败 * 失败或者错误方法 * 自定义异常处理 * * @param e * @param method */
void onError(ApiException e, String method);
abstratt/eclipsegraphviz
plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/IGraphicalContentProvider.java
// Path: plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/IGraphicalContentProvider.java // enum GraphicFileFormat { // JPEG("jpg"), PNG("png"), GIF("gif"), TIFF("tif"), BITMAP("bmp"), SVG("svg"), DOT("dot"); // String extension; // GraphicFileFormat(String extension) { // this.extension = extension; // } // public static GraphicFileFormat byExtension(String toMatch) { // return Arrays.stream(values()).filter(it -> it.extension.equals(toMatch)).findAny().orElse(null); // } // public String getExtension() { // return extension; // } // }
import java.util.Arrays; import java.util.EnumSet; import java.util.Set; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.jface.viewers.IContentProvider; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Display; import static com.abstratt.imageviewer.IGraphicalContentProvider.GraphicFileFormat.*;
package com.abstratt.imageviewer; /** * A content provider that can render a graphical output. */ public interface IGraphicalContentProvider extends IContentProvider { /** * Returns this provider's current image. * * @param suggestedDimension * * @throws IllegalStateException * if no input has been set * @return the rendered image */ public Image getImage(); public void setSuggestedSize(Point suggested); /** * Returns an image produced from the given input. This method might be * invoked from a non-UI thread. * * @param display * @param suggestedSize * @param newInput * @return the image loaded * @throws CoreException * if an error occurs while producing the image */ public Image loadImage(Display display, Point suggestedSize, Object newInput) throws CoreException; /** * Generates an image at the given location. * * @param display * @param suggestedSize * @param input * @param location * @throws CoreException */
// Path: plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/IGraphicalContentProvider.java // enum GraphicFileFormat { // JPEG("jpg"), PNG("png"), GIF("gif"), TIFF("tif"), BITMAP("bmp"), SVG("svg"), DOT("dot"); // String extension; // GraphicFileFormat(String extension) { // this.extension = extension; // } // public static GraphicFileFormat byExtension(String toMatch) { // return Arrays.stream(values()).filter(it -> it.extension.equals(toMatch)).findAny().orElse(null); // } // public String getExtension() { // return extension; // } // } // Path: plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/IGraphicalContentProvider.java import java.util.Arrays; import java.util.EnumSet; import java.util.Set; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.jface.viewers.IContentProvider; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Display; import static com.abstratt.imageviewer.IGraphicalContentProvider.GraphicFileFormat.*; package com.abstratt.imageviewer; /** * A content provider that can render a graphical output. */ public interface IGraphicalContentProvider extends IContentProvider { /** * Returns this provider's current image. * * @param suggestedDimension * * @throws IllegalStateException * if no input has been set * @return the rendered image */ public Image getImage(); public void setSuggestedSize(Point suggested); /** * Returns an image produced from the given input. This method might be * invoked from a non-UI thread. * * @param display * @param suggestedSize * @param newInput * @return the image loaded * @throws CoreException * if an error occurs while producing the image */ public Image loadImage(Display display, Point suggestedSize, Object newInput) throws CoreException; /** * Generates an image at the given location. * * @param display * @param suggestedSize * @param input * @param location * @throws CoreException */
public void saveImage(Display display, Point suggestedSize, Object input, IPath location, GraphicFileFormat fileFormat)
abstratt/eclipsegraphviz
plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/GraphicalView.java
// Path: plugins/com.abstratt.content/src/com/abstratt/content/ContentSupport.java // public class ContentSupport { // public static final String PLUGIN_ID = ContentSupport.class.getPackage().getName(); // // private static IContentProviderRegistry registry = new ContentProviderRegistry(); // // public static IContentProviderRegistry getContentProviderRegistry() { // return registry; // } // } // // Path: plugins/com.abstratt.content/src/com/abstratt/content/IContentProviderRegistry.java // public interface IProviderDescription { // public IContentProvider getProvider(); // // /** // * Converts the given source object (using one of the contributed // * readers) to the format expected by the content provider. // * // * @param source // * object to convert // * @return the converted contents that are consumable by the content // * provider // */ // public Object read(Object source); // }
import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.content.IContentDescription; import org.eclipse.jface.action.ActionContributionItem; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IPartListener2; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartReference; import org.eclipse.ui.part.ViewPart; import com.abstratt.content.ContentSupport; import com.abstratt.content.IContentProviderRegistry.IProviderDescription;
package com.abstratt.imageviewer; /** * A view that wraps a {@link GraphicalViewer}. */ public class GraphicalView extends ViewPart implements IResourceChangeListener, IPartListener2, ISelectionListener { public final static String VIEW_ID = "com.abstratt.imageviewer.GraphicalView"; private Canvas canvas; private GraphicalViewer viewer; private String basePartName; private IFile selectedFile;
// Path: plugins/com.abstratt.content/src/com/abstratt/content/ContentSupport.java // public class ContentSupport { // public static final String PLUGIN_ID = ContentSupport.class.getPackage().getName(); // // private static IContentProviderRegistry registry = new ContentProviderRegistry(); // // public static IContentProviderRegistry getContentProviderRegistry() { // return registry; // } // } // // Path: plugins/com.abstratt.content/src/com/abstratt/content/IContentProviderRegistry.java // public interface IProviderDescription { // public IContentProvider getProvider(); // // /** // * Converts the given source object (using one of the contributed // * readers) to the format expected by the content provider. // * // * @param source // * object to convert // * @return the converted contents that are consumable by the content // * provider // */ // public Object read(Object source); // } // Path: plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/GraphicalView.java import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.content.IContentDescription; import org.eclipse.jface.action.ActionContributionItem; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IPartListener2; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartReference; import org.eclipse.ui.part.ViewPart; import com.abstratt.content.ContentSupport; import com.abstratt.content.IContentProviderRegistry.IProviderDescription; package com.abstratt.imageviewer; /** * A view that wraps a {@link GraphicalViewer}. */ public class GraphicalView extends ViewPart implements IResourceChangeListener, IPartListener2, ISelectionListener { public final static String VIEW_ID = "com.abstratt.imageviewer.GraphicalView"; private Canvas canvas; private GraphicalViewer viewer; private String basePartName; private IFile selectedFile;
private IProviderDescription providerDefinition;
abstratt/eclipsegraphviz
plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/GraphicalView.java
// Path: plugins/com.abstratt.content/src/com/abstratt/content/ContentSupport.java // public class ContentSupport { // public static final String PLUGIN_ID = ContentSupport.class.getPackage().getName(); // // private static IContentProviderRegistry registry = new ContentProviderRegistry(); // // public static IContentProviderRegistry getContentProviderRegistry() { // return registry; // } // } // // Path: plugins/com.abstratt.content/src/com/abstratt/content/IContentProviderRegistry.java // public interface IProviderDescription { // public IContentProvider getProvider(); // // /** // * Converts the given source object (using one of the contributed // * readers) to the format expected by the content provider. // * // * @param source // * object to convert // * @return the converted contents that are consumable by the content // * provider // */ // public Object read(Object source); // }
import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.content.IContentDescription; import org.eclipse.jface.action.ActionContributionItem; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IPartListener2; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartReference; import org.eclipse.ui.part.ViewPart; import com.abstratt.content.ContentSupport; import com.abstratt.content.IContentProviderRegistry.IProviderDescription;
if (selectedFile == null) { IFile asFile = (IFile) editorPart.getAdapter(IFile.class); if (asFile == null) asFile = (IFile) editorPart.getEditorInput().getAdapter(IFile.class); if (asFile == null) return; selectedFile = asFile; } requestUpdate(); } private void reload(IFile file) { setPartName(basePartName); this.providerDefinition = null; this.selectedFile = null; if (file == null || !file.exists()) return; if (viewer.getContentProvider() != null) // to avoid one provider trying to interpret an // incompatible input viewer.setInput(null); IContentDescription contentDescription = null; try { contentDescription = file.getContentDescription(); } catch (CoreException e) { if (Platform.inDebugMode()) Activator.logUnexpected(null, e); } if (contentDescription == null || contentDescription.getContentType() == null) return;
// Path: plugins/com.abstratt.content/src/com/abstratt/content/ContentSupport.java // public class ContentSupport { // public static final String PLUGIN_ID = ContentSupport.class.getPackage().getName(); // // private static IContentProviderRegistry registry = new ContentProviderRegistry(); // // public static IContentProviderRegistry getContentProviderRegistry() { // return registry; // } // } // // Path: plugins/com.abstratt.content/src/com/abstratt/content/IContentProviderRegistry.java // public interface IProviderDescription { // public IContentProvider getProvider(); // // /** // * Converts the given source object (using one of the contributed // * readers) to the format expected by the content provider. // * // * @param source // * object to convert // * @return the converted contents that are consumable by the content // * provider // */ // public Object read(Object source); // } // Path: plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/GraphicalView.java import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.content.IContentDescription; import org.eclipse.jface.action.ActionContributionItem; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IPartListener2; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartReference; import org.eclipse.ui.part.ViewPart; import com.abstratt.content.ContentSupport; import com.abstratt.content.IContentProviderRegistry.IProviderDescription; if (selectedFile == null) { IFile asFile = (IFile) editorPart.getAdapter(IFile.class); if (asFile == null) asFile = (IFile) editorPart.getEditorInput().getAdapter(IFile.class); if (asFile == null) return; selectedFile = asFile; } requestUpdate(); } private void reload(IFile file) { setPartName(basePartName); this.providerDefinition = null; this.selectedFile = null; if (file == null || !file.exists()) return; if (viewer.getContentProvider() != null) // to avoid one provider trying to interpret an // incompatible input viewer.setInput(null); IContentDescription contentDescription = null; try { contentDescription = file.getContentDescription(); } catch (CoreException e) { if (Platform.inDebugMode()) Activator.logUnexpected(null, e); } if (contentDescription == null || contentDescription.getContentType() == null) return;
IProviderDescription providerDefinition = ContentSupport.getContentProviderRegistry().findContentProvider(
abstratt/eclipsegraphviz
plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/AbstractGraphicalContentProvider.java
// Path: plugins/com.abstratt.pluginutils/src/com/abstratt/pluginutils/LogUtils.java // public class LogUtils { // public static void log(int severity, String pluginId, Supplier<String> message, Throwable exception) { // log(() -> new Status(severity, pluginId, message.get(), exception)); // } // // public static void log(int severity, String pluginId, String message, Throwable exception) { // log(() -> new Status(severity, pluginId, message, exception)); // } // // public static void log(IStatus status) { // log(() -> status); // } // public static void log(Supplier<IStatus> statusSupplier) { // IStatus status = statusSupplier.get(); // if (!Platform.isRunning()) { // System.err.println(status.getMessage()); // if (status.getException() != null) // status.getException().printStackTrace(); // if (status.isMultiStatus()) // for (IStatus child : status.getChildren()) // log(child); // return; // } // Bundle bundle = Platform.getBundle(status.getPlugin()); // if (bundle == null) { // String thisPluginId = LogUtils.class.getPackage().getName(); // bundle = Platform.getBundle(thisPluginId); // Platform.getLog(bundle).log( // new Status(IStatus.WARNING, thisPluginId, "Could not find a plugin " + status.getPlugin() // + " for logging as")); // } // Platform.getLog(bundle).log(status); // } // // public static void logError(String pluginId, String message, Throwable e) { // log(IStatus.ERROR, pluginId, message, e); // } // // public static void logWarning(String pluginId, String message, Throwable e) { // log(IStatus.WARNING, pluginId, message, e); // } // // public static void logInfo(String pluginId, String message, Throwable e) { // log(IStatus.INFO, pluginId, message, e); // } // // public static void debug(String pluginId, String message) { // debug(pluginId, () -> message); // } // // public static void debug(String pluginId, Supplier<String> message) { // if (Boolean.getBoolean(pluginId + ".debug")) // log(IStatus.INFO, pluginId, message.get(), null); // } // // public static void logError(Class pluginClass, String message, Throwable e) { // logError(pluginClass.getPackage().getName(), message, e); // } // // public static void logWarning(Class pluginClass, String message, Throwable e) { // logWarning(pluginClass.getPackage().getName(), message, e); // } // // public static void logInfo(Class pluginClass, String message, Throwable e) { // logInfo(pluginClass.getPackage().getName(), message, e); // } // // public static void debug(Class pluginClass, String message) { // debug(pluginClass.getName(), () -> message); // } // // public static void debug(Class pluginClass, Supplier<String> message) { // debug(pluginClass.getName(), message); // } // // public static void log(int severity, Class pluginClass, Supplier<String> message, Throwable exception) { // log(severity, pluginClass.getPackage().getName(), message, exception); // } // // public static void log(int severity, Class pluginClass, String message, Throwable exception) { // log(severity, pluginClass.getPackage().getName(), message, exception); // } // // // }
import java.io.ByteArrayOutputStream; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.ISchedulingRule; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.ImageLoader; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Display; import com.abstratt.pluginutils.LogUtils;
}; class ContentLoader extends Job { private static final long IMAGE_LOAD_DELAY = 100; static final String JOB_FAMILY = "ContentLoader"; private Object input; private Viewer viewer; public ContentLoader() { super("Image loading job"); setSystem(true); setPriority(Job.INTERACTIVE); } @Override protected IStatus run(final IProgressMonitor monitor) { monitor.beginTask("loading image", 100); getJobManager().beginRule(CONTENT_LOADING_RULE, monitor); try { if (monitor.isCanceled()) return Status.CANCEL_STATUS; disposeImage(); monitor.worked(50); try { setImage(AbstractGraphicalContentProvider.this.loadImage(Display.getDefault(), getSuggestedSize(), input)); } catch (CoreException e) { if (!e.getStatus().isOK())
// Path: plugins/com.abstratt.pluginutils/src/com/abstratt/pluginutils/LogUtils.java // public class LogUtils { // public static void log(int severity, String pluginId, Supplier<String> message, Throwable exception) { // log(() -> new Status(severity, pluginId, message.get(), exception)); // } // // public static void log(int severity, String pluginId, String message, Throwable exception) { // log(() -> new Status(severity, pluginId, message, exception)); // } // // public static void log(IStatus status) { // log(() -> status); // } // public static void log(Supplier<IStatus> statusSupplier) { // IStatus status = statusSupplier.get(); // if (!Platform.isRunning()) { // System.err.println(status.getMessage()); // if (status.getException() != null) // status.getException().printStackTrace(); // if (status.isMultiStatus()) // for (IStatus child : status.getChildren()) // log(child); // return; // } // Bundle bundle = Platform.getBundle(status.getPlugin()); // if (bundle == null) { // String thisPluginId = LogUtils.class.getPackage().getName(); // bundle = Platform.getBundle(thisPluginId); // Platform.getLog(bundle).log( // new Status(IStatus.WARNING, thisPluginId, "Could not find a plugin " + status.getPlugin() // + " for logging as")); // } // Platform.getLog(bundle).log(status); // } // // public static void logError(String pluginId, String message, Throwable e) { // log(IStatus.ERROR, pluginId, message, e); // } // // public static void logWarning(String pluginId, String message, Throwable e) { // log(IStatus.WARNING, pluginId, message, e); // } // // public static void logInfo(String pluginId, String message, Throwable e) { // log(IStatus.INFO, pluginId, message, e); // } // // public static void debug(String pluginId, String message) { // debug(pluginId, () -> message); // } // // public static void debug(String pluginId, Supplier<String> message) { // if (Boolean.getBoolean(pluginId + ".debug")) // log(IStatus.INFO, pluginId, message.get(), null); // } // // public static void logError(Class pluginClass, String message, Throwable e) { // logError(pluginClass.getPackage().getName(), message, e); // } // // public static void logWarning(Class pluginClass, String message, Throwable e) { // logWarning(pluginClass.getPackage().getName(), message, e); // } // // public static void logInfo(Class pluginClass, String message, Throwable e) { // logInfo(pluginClass.getPackage().getName(), message, e); // } // // public static void debug(Class pluginClass, String message) { // debug(pluginClass.getName(), () -> message); // } // // public static void debug(Class pluginClass, Supplier<String> message) { // debug(pluginClass.getName(), message); // } // // public static void log(int severity, Class pluginClass, Supplier<String> message, Throwable exception) { // log(severity, pluginClass.getPackage().getName(), message, exception); // } // // public static void log(int severity, Class pluginClass, String message, Throwable exception) { // log(severity, pluginClass.getPackage().getName(), message, exception); // } // // // } // Path: plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/AbstractGraphicalContentProvider.java import java.io.ByteArrayOutputStream; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.ISchedulingRule; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.viewers.Viewer; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.ImageLoader; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Display; import com.abstratt.pluginutils.LogUtils; }; class ContentLoader extends Job { private static final long IMAGE_LOAD_DELAY = 100; static final String JOB_FAMILY = "ContentLoader"; private Object input; private Viewer viewer; public ContentLoader() { super("Image loading job"); setSystem(true); setPriority(Job.INTERACTIVE); } @Override protected IStatus run(final IProgressMonitor monitor) { monitor.beginTask("loading image", 100); getJobManager().beginRule(CONTENT_LOADING_RULE, monitor); try { if (monitor.isCanceled()) return Status.CANCEL_STATUS; disposeImage(); monitor.worked(50); try { setImage(AbstractGraphicalContentProvider.this.loadImage(Display.getDefault(), getSuggestedSize(), input)); } catch (CoreException e) { if (!e.getStatus().isOK())
LogUtils.log(e.getStatus());
abstratt/eclipsegraphviz
plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/Activator.java
// Path: plugins/com.abstratt.content/src/com/abstratt/content/ContentSupport.java // public class ContentSupport { // public static final String PLUGIN_ID = ContentSupport.class.getPackage().getName(); // // private static IContentProviderRegistry registry = new ContentProviderRegistry(); // // public static IContentProviderRegistry getContentProviderRegistry() { // return registry; // } // } // // Path: plugins/com.abstratt.pluginutils/src/com/abstratt/pluginutils/LogUtils.java // public class LogUtils { // public static void log(int severity, String pluginId, Supplier<String> message, Throwable exception) { // log(() -> new Status(severity, pluginId, message.get(), exception)); // } // // public static void log(int severity, String pluginId, String message, Throwable exception) { // log(() -> new Status(severity, pluginId, message, exception)); // } // // public static void log(IStatus status) { // log(() -> status); // } // public static void log(Supplier<IStatus> statusSupplier) { // IStatus status = statusSupplier.get(); // if (!Platform.isRunning()) { // System.err.println(status.getMessage()); // if (status.getException() != null) // status.getException().printStackTrace(); // if (status.isMultiStatus()) // for (IStatus child : status.getChildren()) // log(child); // return; // } // Bundle bundle = Platform.getBundle(status.getPlugin()); // if (bundle == null) { // String thisPluginId = LogUtils.class.getPackage().getName(); // bundle = Platform.getBundle(thisPluginId); // Platform.getLog(bundle).log( // new Status(IStatus.WARNING, thisPluginId, "Could not find a plugin " + status.getPlugin() // + " for logging as")); // } // Platform.getLog(bundle).log(status); // } // // public static void logError(String pluginId, String message, Throwable e) { // log(IStatus.ERROR, pluginId, message, e); // } // // public static void logWarning(String pluginId, String message, Throwable e) { // log(IStatus.WARNING, pluginId, message, e); // } // // public static void logInfo(String pluginId, String message, Throwable e) { // log(IStatus.INFO, pluginId, message, e); // } // // public static void debug(String pluginId, String message) { // debug(pluginId, () -> message); // } // // public static void debug(String pluginId, Supplier<String> message) { // if (Boolean.getBoolean(pluginId + ".debug")) // log(IStatus.INFO, pluginId, message.get(), null); // } // // public static void logError(Class pluginClass, String message, Throwable e) { // logError(pluginClass.getPackage().getName(), message, e); // } // // public static void logWarning(Class pluginClass, String message, Throwable e) { // logWarning(pluginClass.getPackage().getName(), message, e); // } // // public static void logInfo(Class pluginClass, String message, Throwable e) { // logInfo(pluginClass.getPackage().getName(), message, e); // } // // public static void debug(Class pluginClass, String message) { // debug(pluginClass.getName(), () -> message); // } // // public static void debug(Class pluginClass, Supplier<String> message) { // debug(pluginClass.getName(), message); // } // // public static void log(int severity, Class pluginClass, Supplier<String> message, Throwable exception) { // log(severity, pluginClass.getPackage().getName(), message, exception); // } // // public static void log(int severity, Class pluginClass, String message, Throwable exception) { // log(severity, pluginClass.getPackage().getName(), message, exception); // } // // // }
import org.eclipse.core.runtime.Plugin; import org.osgi.framework.BundleContext; import com.abstratt.content.ContentSupport; import com.abstratt.pluginutils.LogUtils;
package com.abstratt.imageviewer; /** * The activator class controls the plug-in life cycle */ public class Activator extends Plugin { // The plug-in ID public static final String PLUGIN_ID = "com.abstratt.imageviewer"; // The shared instance private static Activator plugin; /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } public static void logUnexpected(String message, Exception e) {
// Path: plugins/com.abstratt.content/src/com/abstratt/content/ContentSupport.java // public class ContentSupport { // public static final String PLUGIN_ID = ContentSupport.class.getPackage().getName(); // // private static IContentProviderRegistry registry = new ContentProviderRegistry(); // // public static IContentProviderRegistry getContentProviderRegistry() { // return registry; // } // } // // Path: plugins/com.abstratt.pluginutils/src/com/abstratt/pluginutils/LogUtils.java // public class LogUtils { // public static void log(int severity, String pluginId, Supplier<String> message, Throwable exception) { // log(() -> new Status(severity, pluginId, message.get(), exception)); // } // // public static void log(int severity, String pluginId, String message, Throwable exception) { // log(() -> new Status(severity, pluginId, message, exception)); // } // // public static void log(IStatus status) { // log(() -> status); // } // public static void log(Supplier<IStatus> statusSupplier) { // IStatus status = statusSupplier.get(); // if (!Platform.isRunning()) { // System.err.println(status.getMessage()); // if (status.getException() != null) // status.getException().printStackTrace(); // if (status.isMultiStatus()) // for (IStatus child : status.getChildren()) // log(child); // return; // } // Bundle bundle = Platform.getBundle(status.getPlugin()); // if (bundle == null) { // String thisPluginId = LogUtils.class.getPackage().getName(); // bundle = Platform.getBundle(thisPluginId); // Platform.getLog(bundle).log( // new Status(IStatus.WARNING, thisPluginId, "Could not find a plugin " + status.getPlugin() // + " for logging as")); // } // Platform.getLog(bundle).log(status); // } // // public static void logError(String pluginId, String message, Throwable e) { // log(IStatus.ERROR, pluginId, message, e); // } // // public static void logWarning(String pluginId, String message, Throwable e) { // log(IStatus.WARNING, pluginId, message, e); // } // // public static void logInfo(String pluginId, String message, Throwable e) { // log(IStatus.INFO, pluginId, message, e); // } // // public static void debug(String pluginId, String message) { // debug(pluginId, () -> message); // } // // public static void debug(String pluginId, Supplier<String> message) { // if (Boolean.getBoolean(pluginId + ".debug")) // log(IStatus.INFO, pluginId, message.get(), null); // } // // public static void logError(Class pluginClass, String message, Throwable e) { // logError(pluginClass.getPackage().getName(), message, e); // } // // public static void logWarning(Class pluginClass, String message, Throwable e) { // logWarning(pluginClass.getPackage().getName(), message, e); // } // // public static void logInfo(Class pluginClass, String message, Throwable e) { // logInfo(pluginClass.getPackage().getName(), message, e); // } // // public static void debug(Class pluginClass, String message) { // debug(pluginClass.getName(), () -> message); // } // // public static void debug(Class pluginClass, Supplier<String> message) { // debug(pluginClass.getName(), message); // } // // public static void log(int severity, Class pluginClass, Supplier<String> message, Throwable exception) { // log(severity, pluginClass.getPackage().getName(), message, exception); // } // // public static void log(int severity, Class pluginClass, String message, Throwable exception) { // log(severity, pluginClass.getPackage().getName(), message, exception); // } // // // } // Path: plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/Activator.java import org.eclipse.core.runtime.Plugin; import org.osgi.framework.BundleContext; import com.abstratt.content.ContentSupport; import com.abstratt.pluginutils.LogUtils; package com.abstratt.imageviewer; /** * The activator class controls the plug-in life cycle */ public class Activator extends Plugin { // The plug-in ID public static final String PLUGIN_ID = "com.abstratt.imageviewer"; // The shared instance private static Activator plugin; /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } public static void logUnexpected(String message, Exception e) {
LogUtils.logError(ContentSupport.PLUGIN_ID, message, e);
abstratt/eclipsegraphviz
plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/Activator.java
// Path: plugins/com.abstratt.content/src/com/abstratt/content/ContentSupport.java // public class ContentSupport { // public static final String PLUGIN_ID = ContentSupport.class.getPackage().getName(); // // private static IContentProviderRegistry registry = new ContentProviderRegistry(); // // public static IContentProviderRegistry getContentProviderRegistry() { // return registry; // } // } // // Path: plugins/com.abstratt.pluginutils/src/com/abstratt/pluginutils/LogUtils.java // public class LogUtils { // public static void log(int severity, String pluginId, Supplier<String> message, Throwable exception) { // log(() -> new Status(severity, pluginId, message.get(), exception)); // } // // public static void log(int severity, String pluginId, String message, Throwable exception) { // log(() -> new Status(severity, pluginId, message, exception)); // } // // public static void log(IStatus status) { // log(() -> status); // } // public static void log(Supplier<IStatus> statusSupplier) { // IStatus status = statusSupplier.get(); // if (!Platform.isRunning()) { // System.err.println(status.getMessage()); // if (status.getException() != null) // status.getException().printStackTrace(); // if (status.isMultiStatus()) // for (IStatus child : status.getChildren()) // log(child); // return; // } // Bundle bundle = Platform.getBundle(status.getPlugin()); // if (bundle == null) { // String thisPluginId = LogUtils.class.getPackage().getName(); // bundle = Platform.getBundle(thisPluginId); // Platform.getLog(bundle).log( // new Status(IStatus.WARNING, thisPluginId, "Could not find a plugin " + status.getPlugin() // + " for logging as")); // } // Platform.getLog(bundle).log(status); // } // // public static void logError(String pluginId, String message, Throwable e) { // log(IStatus.ERROR, pluginId, message, e); // } // // public static void logWarning(String pluginId, String message, Throwable e) { // log(IStatus.WARNING, pluginId, message, e); // } // // public static void logInfo(String pluginId, String message, Throwable e) { // log(IStatus.INFO, pluginId, message, e); // } // // public static void debug(String pluginId, String message) { // debug(pluginId, () -> message); // } // // public static void debug(String pluginId, Supplier<String> message) { // if (Boolean.getBoolean(pluginId + ".debug")) // log(IStatus.INFO, pluginId, message.get(), null); // } // // public static void logError(Class pluginClass, String message, Throwable e) { // logError(pluginClass.getPackage().getName(), message, e); // } // // public static void logWarning(Class pluginClass, String message, Throwable e) { // logWarning(pluginClass.getPackage().getName(), message, e); // } // // public static void logInfo(Class pluginClass, String message, Throwable e) { // logInfo(pluginClass.getPackage().getName(), message, e); // } // // public static void debug(Class pluginClass, String message) { // debug(pluginClass.getName(), () -> message); // } // // public static void debug(Class pluginClass, Supplier<String> message) { // debug(pluginClass.getName(), message); // } // // public static void log(int severity, Class pluginClass, Supplier<String> message, Throwable exception) { // log(severity, pluginClass.getPackage().getName(), message, exception); // } // // public static void log(int severity, Class pluginClass, String message, Throwable exception) { // log(severity, pluginClass.getPackage().getName(), message, exception); // } // // // }
import org.eclipse.core.runtime.Plugin; import org.osgi.framework.BundleContext; import com.abstratt.content.ContentSupport; import com.abstratt.pluginutils.LogUtils;
package com.abstratt.imageviewer; /** * The activator class controls the plug-in life cycle */ public class Activator extends Plugin { // The plug-in ID public static final String PLUGIN_ID = "com.abstratt.imageviewer"; // The shared instance private static Activator plugin; /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } public static void logUnexpected(String message, Exception e) {
// Path: plugins/com.abstratt.content/src/com/abstratt/content/ContentSupport.java // public class ContentSupport { // public static final String PLUGIN_ID = ContentSupport.class.getPackage().getName(); // // private static IContentProviderRegistry registry = new ContentProviderRegistry(); // // public static IContentProviderRegistry getContentProviderRegistry() { // return registry; // } // } // // Path: plugins/com.abstratt.pluginutils/src/com/abstratt/pluginutils/LogUtils.java // public class LogUtils { // public static void log(int severity, String pluginId, Supplier<String> message, Throwable exception) { // log(() -> new Status(severity, pluginId, message.get(), exception)); // } // // public static void log(int severity, String pluginId, String message, Throwable exception) { // log(() -> new Status(severity, pluginId, message, exception)); // } // // public static void log(IStatus status) { // log(() -> status); // } // public static void log(Supplier<IStatus> statusSupplier) { // IStatus status = statusSupplier.get(); // if (!Platform.isRunning()) { // System.err.println(status.getMessage()); // if (status.getException() != null) // status.getException().printStackTrace(); // if (status.isMultiStatus()) // for (IStatus child : status.getChildren()) // log(child); // return; // } // Bundle bundle = Platform.getBundle(status.getPlugin()); // if (bundle == null) { // String thisPluginId = LogUtils.class.getPackage().getName(); // bundle = Platform.getBundle(thisPluginId); // Platform.getLog(bundle).log( // new Status(IStatus.WARNING, thisPluginId, "Could not find a plugin " + status.getPlugin() // + " for logging as")); // } // Platform.getLog(bundle).log(status); // } // // public static void logError(String pluginId, String message, Throwable e) { // log(IStatus.ERROR, pluginId, message, e); // } // // public static void logWarning(String pluginId, String message, Throwable e) { // log(IStatus.WARNING, pluginId, message, e); // } // // public static void logInfo(String pluginId, String message, Throwable e) { // log(IStatus.INFO, pluginId, message, e); // } // // public static void debug(String pluginId, String message) { // debug(pluginId, () -> message); // } // // public static void debug(String pluginId, Supplier<String> message) { // if (Boolean.getBoolean(pluginId + ".debug")) // log(IStatus.INFO, pluginId, message.get(), null); // } // // public static void logError(Class pluginClass, String message, Throwable e) { // logError(pluginClass.getPackage().getName(), message, e); // } // // public static void logWarning(Class pluginClass, String message, Throwable e) { // logWarning(pluginClass.getPackage().getName(), message, e); // } // // public static void logInfo(Class pluginClass, String message, Throwable e) { // logInfo(pluginClass.getPackage().getName(), message, e); // } // // public static void debug(Class pluginClass, String message) { // debug(pluginClass.getName(), () -> message); // } // // public static void debug(Class pluginClass, Supplier<String> message) { // debug(pluginClass.getName(), message); // } // // public static void log(int severity, Class pluginClass, Supplier<String> message, Throwable exception) { // log(severity, pluginClass.getPackage().getName(), message, exception); // } // // public static void log(int severity, Class pluginClass, String message, Throwable exception) { // log(severity, pluginClass.getPackage().getName(), message, exception); // } // // // } // Path: plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/Activator.java import org.eclipse.core.runtime.Plugin; import org.osgi.framework.BundleContext; import com.abstratt.content.ContentSupport; import com.abstratt.pluginutils.LogUtils; package com.abstratt.imageviewer; /** * The activator class controls the plug-in life cycle */ public class Activator extends Plugin { // The plug-in ID public static final String PLUGIN_ID = "com.abstratt.imageviewer"; // The shared instance private static Activator plugin; /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } public static void logUnexpected(String message, Exception e) {
LogUtils.logError(ContentSupport.PLUGIN_ID, message, e);
abstratt/eclipsegraphviz
plugins/com.abstratt.content/src/com/abstratt/content/ContentSupport.java
// Path: plugins/com.abstratt.content/src/com/abstratt/internal/content/ContentProviderRegistry.java // public class ContentProviderRegistry implements IContentProviderRegistry { // public class ContentProviderDescriptor implements IProviderDescription { // private IConfigurationElement configElement; // private Set<IContentType> associations = new HashSet<IContentType>(); // private List<Object> readers = new ArrayList<Object>(); // // public ContentProviderDescriptor(IConfigurationElement configElement) { // this.configElement = configElement; // IConfigurationElement[] associationElements = configElement.getChildren("association"); // IContentTypeManager pcm = Platform.getContentTypeManager(); // for (IConfigurationElement associationEl : associationElements) // associations.add(pcm.getContentType(associationEl.getAttribute("contentType"))); // IConfigurationElement[] readerElements = configElement.getChildren("reader"); // for (IConfigurationElement readerEl : readerElements) // try { // Object reader = readerEl.createExecutableExtension("class"); // readers.add(reader); // } catch (CoreException e) { // LogUtils.logError(ContentSupport.PLUGIN_ID, "Error processing content provider extension " // + configElement.getNamespaceIdentifier(), e); // } // } // // public boolean canRead(Class<?> sourceType) { // return findReader(sourceType) != null; // } // // public Object findReader(Class<?> sourceType) { // for (Object reader : readers) // if (getReaderMethod(reader, sourceType) != null) // return reader; // return null; // } // // public Set<IContentType> getAssociations() { // return associations; // } // // public IContentProvider getProvider() { // try { // return (IContentProvider) configElement.createExecutableExtension("class"); // } catch (CoreException e) { // LogUtils.logError(ContentSupport.PLUGIN_ID, "Could not instantiate content provider", e); // } // return null; // } // // private Method getReaderMethod(Object reader, Class<?> sourceType) { // Method method = MethodUtils.getMatchingAccessibleMethod(reader.getClass(), "read", // new Class[] { sourceType }); // return method == null || method.getReturnType() == Void.class ? null : method; // } // // public Object read(Object source) { // Object reader = findReader(source.getClass()); // if (reader == null) // throw new IllegalArgumentException("Cannot read " + source); // Method readerMethod = getReaderMethod(reader, source.getClass()); // try { // return readerMethod.invoke(reader, source); // } catch (IllegalAccessException e) { // Activator.logUnexpected(null, e); // } catch (InvocationTargetException e) { // Activator.logUnexpected(null, e); // } // return null; // } // } // // private static final String CONTENT_PROVIDER_XP = ContentSupport.PLUGIN_ID + ".contentProvider"; //$NON-NLS-1$ // // public List<ContentProviderDescriptor> providerDescriptors = new ArrayList<ContentProviderDescriptor>(); // // public ContentProviderRegistry() { // build(); // } // // private void addProvider(IConfigurationElement element) { // providerDescriptors.add(new ContentProviderDescriptor(element)); // } // // private void build() { // IExtensionRegistry registry = RegistryFactory.getRegistry(); // new RegistryReader() { // @Override // protected String getNamespace() { // return ContentSupport.PLUGIN_ID; // } // // @Override // protected boolean readElement(IConfigurationElement element) { // addProvider(element); // return true; // } // }.readRegistry(registry, CONTENT_PROVIDER_XP); // } // // /* // * (non-Javadoc) // * // * @see // * com.abstratt.content.IContentProviderRegistry#findContentProvider(org // * .eclipse.core.runtime.content.IContentType, java.lang.Class) // */ // public IProviderDescription findContentProvider(IContentType target, // Class<? extends IContentProvider> minimumProtocol) { // for (ContentProviderDescriptor descriptor : providerDescriptors) // for (IContentType contentType : descriptor.getAssociations()) // if (target.isKindOf(contentType)) { // if (minimumProtocol != null && minimumProtocol.isInstance(descriptor.getProvider())) // return descriptor; // } // return null; // } // // }
import com.abstratt.internal.content.ContentProviderRegistry;
package com.abstratt.content; public class ContentSupport { public static final String PLUGIN_ID = ContentSupport.class.getPackage().getName();
// Path: plugins/com.abstratt.content/src/com/abstratt/internal/content/ContentProviderRegistry.java // public class ContentProviderRegistry implements IContentProviderRegistry { // public class ContentProviderDescriptor implements IProviderDescription { // private IConfigurationElement configElement; // private Set<IContentType> associations = new HashSet<IContentType>(); // private List<Object> readers = new ArrayList<Object>(); // // public ContentProviderDescriptor(IConfigurationElement configElement) { // this.configElement = configElement; // IConfigurationElement[] associationElements = configElement.getChildren("association"); // IContentTypeManager pcm = Platform.getContentTypeManager(); // for (IConfigurationElement associationEl : associationElements) // associations.add(pcm.getContentType(associationEl.getAttribute("contentType"))); // IConfigurationElement[] readerElements = configElement.getChildren("reader"); // for (IConfigurationElement readerEl : readerElements) // try { // Object reader = readerEl.createExecutableExtension("class"); // readers.add(reader); // } catch (CoreException e) { // LogUtils.logError(ContentSupport.PLUGIN_ID, "Error processing content provider extension " // + configElement.getNamespaceIdentifier(), e); // } // } // // public boolean canRead(Class<?> sourceType) { // return findReader(sourceType) != null; // } // // public Object findReader(Class<?> sourceType) { // for (Object reader : readers) // if (getReaderMethod(reader, sourceType) != null) // return reader; // return null; // } // // public Set<IContentType> getAssociations() { // return associations; // } // // public IContentProvider getProvider() { // try { // return (IContentProvider) configElement.createExecutableExtension("class"); // } catch (CoreException e) { // LogUtils.logError(ContentSupport.PLUGIN_ID, "Could not instantiate content provider", e); // } // return null; // } // // private Method getReaderMethod(Object reader, Class<?> sourceType) { // Method method = MethodUtils.getMatchingAccessibleMethod(reader.getClass(), "read", // new Class[] { sourceType }); // return method == null || method.getReturnType() == Void.class ? null : method; // } // // public Object read(Object source) { // Object reader = findReader(source.getClass()); // if (reader == null) // throw new IllegalArgumentException("Cannot read " + source); // Method readerMethod = getReaderMethod(reader, source.getClass()); // try { // return readerMethod.invoke(reader, source); // } catch (IllegalAccessException e) { // Activator.logUnexpected(null, e); // } catch (InvocationTargetException e) { // Activator.logUnexpected(null, e); // } // return null; // } // } // // private static final String CONTENT_PROVIDER_XP = ContentSupport.PLUGIN_ID + ".contentProvider"; //$NON-NLS-1$ // // public List<ContentProviderDescriptor> providerDescriptors = new ArrayList<ContentProviderDescriptor>(); // // public ContentProviderRegistry() { // build(); // } // // private void addProvider(IConfigurationElement element) { // providerDescriptors.add(new ContentProviderDescriptor(element)); // } // // private void build() { // IExtensionRegistry registry = RegistryFactory.getRegistry(); // new RegistryReader() { // @Override // protected String getNamespace() { // return ContentSupport.PLUGIN_ID; // } // // @Override // protected boolean readElement(IConfigurationElement element) { // addProvider(element); // return true; // } // }.readRegistry(registry, CONTENT_PROVIDER_XP); // } // // /* // * (non-Javadoc) // * // * @see // * com.abstratt.content.IContentProviderRegistry#findContentProvider(org // * .eclipse.core.runtime.content.IContentType, java.lang.Class) // */ // public IProviderDescription findContentProvider(IContentType target, // Class<? extends IContentProvider> minimumProtocol) { // for (ContentProviderDescriptor descriptor : providerDescriptors) // for (IContentType contentType : descriptor.getAssociations()) // if (target.isKindOf(contentType)) { // if (minimumProtocol != null && minimumProtocol.isInstance(descriptor.getProvider())) // return descriptor; // } // return null; // } // // } // Path: plugins/com.abstratt.content/src/com/abstratt/content/ContentSupport.java import com.abstratt.internal.content.ContentProviderRegistry; package com.abstratt.content; public class ContentSupport { public static final String PLUGIN_ID = ContentSupport.class.getPackage().getName();
private static IContentProviderRegistry registry = new ContentProviderRegistry();
abstratt/eclipsegraphviz
plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/SaveToFileAction.java
// Path: plugins/com.abstratt.content/src/com/abstratt/content/IContentProviderRegistry.java // public interface IProviderDescription { // public IContentProvider getProvider(); // // /** // * Converts the given source object (using one of the contributed // * readers) to the format expected by the content provider. // * // * @param source // * object to convert // * @return the converted contents that are consumable by the content // * provider // */ // public Object read(Object source); // } // // Path: plugins/com.abstratt.content/src/com/abstratt/content/PlaceholderProviderDescription.java // public class PlaceholderProviderDescription implements IProviderDescription { // // private Object input; // private IContentProvider contentProvider; // // public PlaceholderProviderDescription(Object input, IContentProvider contentProvider) { // this.input = input; // this.contentProvider = contentProvider; // } // // @Override // public IContentProvider getProvider() { // return contentProvider; // } // // @Override // public Object read(Object source) { // return input; // } // // } // // Path: plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/IGraphicalContentProvider.java // enum GraphicFileFormat { // JPEG("jpg"), PNG("png"), GIF("gif"), TIFF("tif"), BITMAP("bmp"), SVG("svg"), DOT("dot"); // String extension; // GraphicFileFormat(String extension) { // this.extension = extension; // } // public static GraphicFileFormat byExtension(String toMatch) { // return Arrays.stream(values()).filter(it -> it.extension.equals(toMatch)).findAny().orElse(null); // } // public String getExtension() { // return extension; // } // }
import java.io.File; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.ui.IViewActionDelegate; import org.eclipse.ui.IViewPart; import com.abstratt.content.IContentProviderRegistry.IProviderDescription; import com.abstratt.content.PlaceholderProviderDescription; import com.abstratt.imageviewer.IGraphicalContentProvider.GraphicFileFormat;
package com.abstratt.imageviewer; public class SaveToFileAction implements IViewActionDelegate { private GraphicalView view; public void init(IViewPart view) { this.view = (GraphicalView) view; } public void run(IAction action) {
// Path: plugins/com.abstratt.content/src/com/abstratt/content/IContentProviderRegistry.java // public interface IProviderDescription { // public IContentProvider getProvider(); // // /** // * Converts the given source object (using one of the contributed // * readers) to the format expected by the content provider. // * // * @param source // * object to convert // * @return the converted contents that are consumable by the content // * provider // */ // public Object read(Object source); // } // // Path: plugins/com.abstratt.content/src/com/abstratt/content/PlaceholderProviderDescription.java // public class PlaceholderProviderDescription implements IProviderDescription { // // private Object input; // private IContentProvider contentProvider; // // public PlaceholderProviderDescription(Object input, IContentProvider contentProvider) { // this.input = input; // this.contentProvider = contentProvider; // } // // @Override // public IContentProvider getProvider() { // return contentProvider; // } // // @Override // public Object read(Object source) { // return input; // } // // } // // Path: plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/IGraphicalContentProvider.java // enum GraphicFileFormat { // JPEG("jpg"), PNG("png"), GIF("gif"), TIFF("tif"), BITMAP("bmp"), SVG("svg"), DOT("dot"); // String extension; // GraphicFileFormat(String extension) { // this.extension = extension; // } // public static GraphicFileFormat byExtension(String toMatch) { // return Arrays.stream(values()).filter(it -> it.extension.equals(toMatch)).findAny().orElse(null); // } // public String getExtension() { // return extension; // } // } // Path: plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/SaveToFileAction.java import java.io.File; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.ui.IViewActionDelegate; import org.eclipse.ui.IViewPart; import com.abstratt.content.IContentProviderRegistry.IProviderDescription; import com.abstratt.content.PlaceholderProviderDescription; import com.abstratt.imageviewer.IGraphicalContentProvider.GraphicFileFormat; package com.abstratt.imageviewer; public class SaveToFileAction implements IViewActionDelegate { private GraphicalView view; public void init(IViewPart view) { this.view = (GraphicalView) view; } public void run(IAction action) {
IProviderDescription providerDefinition = view.getContentProviderDescription();
abstratt/eclipsegraphviz
plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/SaveToFileAction.java
// Path: plugins/com.abstratt.content/src/com/abstratt/content/IContentProviderRegistry.java // public interface IProviderDescription { // public IContentProvider getProvider(); // // /** // * Converts the given source object (using one of the contributed // * readers) to the format expected by the content provider. // * // * @param source // * object to convert // * @return the converted contents that are consumable by the content // * provider // */ // public Object read(Object source); // } // // Path: plugins/com.abstratt.content/src/com/abstratt/content/PlaceholderProviderDescription.java // public class PlaceholderProviderDescription implements IProviderDescription { // // private Object input; // private IContentProvider contentProvider; // // public PlaceholderProviderDescription(Object input, IContentProvider contentProvider) { // this.input = input; // this.contentProvider = contentProvider; // } // // @Override // public IContentProvider getProvider() { // return contentProvider; // } // // @Override // public Object read(Object source) { // return input; // } // // } // // Path: plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/IGraphicalContentProvider.java // enum GraphicFileFormat { // JPEG("jpg"), PNG("png"), GIF("gif"), TIFF("tif"), BITMAP("bmp"), SVG("svg"), DOT("dot"); // String extension; // GraphicFileFormat(String extension) { // this.extension = extension; // } // public static GraphicFileFormat byExtension(String toMatch) { // return Arrays.stream(values()).filter(it -> it.extension.equals(toMatch)).findAny().orElse(null); // } // public String getExtension() { // return extension; // } // }
import java.io.File; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.ui.IViewActionDelegate; import org.eclipse.ui.IViewPart; import com.abstratt.content.IContentProviderRegistry.IProviderDescription; import com.abstratt.content.PlaceholderProviderDescription; import com.abstratt.imageviewer.IGraphicalContentProvider.GraphicFileFormat;
package com.abstratt.imageviewer; public class SaveToFileAction implements IViewActionDelegate { private GraphicalView view; public void init(IViewPart view) { this.view = (GraphicalView) view; } public void run(IAction action) { IProviderDescription providerDefinition = view.getContentProviderDescription(); IGraphicalContentProvider contentProvider = view.getContentProvider(); if (providerDefinition == null)
// Path: plugins/com.abstratt.content/src/com/abstratt/content/IContentProviderRegistry.java // public interface IProviderDescription { // public IContentProvider getProvider(); // // /** // * Converts the given source object (using one of the contributed // * readers) to the format expected by the content provider. // * // * @param source // * object to convert // * @return the converted contents that are consumable by the content // * provider // */ // public Object read(Object source); // } // // Path: plugins/com.abstratt.content/src/com/abstratt/content/PlaceholderProviderDescription.java // public class PlaceholderProviderDescription implements IProviderDescription { // // private Object input; // private IContentProvider contentProvider; // // public PlaceholderProviderDescription(Object input, IContentProvider contentProvider) { // this.input = input; // this.contentProvider = contentProvider; // } // // @Override // public IContentProvider getProvider() { // return contentProvider; // } // // @Override // public Object read(Object source) { // return input; // } // // } // // Path: plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/IGraphicalContentProvider.java // enum GraphicFileFormat { // JPEG("jpg"), PNG("png"), GIF("gif"), TIFF("tif"), BITMAP("bmp"), SVG("svg"), DOT("dot"); // String extension; // GraphicFileFormat(String extension) { // this.extension = extension; // } // public static GraphicFileFormat byExtension(String toMatch) { // return Arrays.stream(values()).filter(it -> it.extension.equals(toMatch)).findAny().orElse(null); // } // public String getExtension() { // return extension; // } // } // Path: plugins/com.abstratt.imageviewer/src/com/abstratt/imageviewer/SaveToFileAction.java import java.io.File; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.ui.IViewActionDelegate; import org.eclipse.ui.IViewPart; import com.abstratt.content.IContentProviderRegistry.IProviderDescription; import com.abstratt.content.PlaceholderProviderDescription; import com.abstratt.imageviewer.IGraphicalContentProvider.GraphicFileFormat; package com.abstratt.imageviewer; public class SaveToFileAction implements IViewActionDelegate { private GraphicalView view; public void init(IViewPart view) { this.view = (GraphicalView) view; } public void run(IAction action) { IProviderDescription providerDefinition = view.getContentProviderDescription(); IGraphicalContentProvider contentProvider = view.getContentProvider(); if (providerDefinition == null)
providerDefinition = new PlaceholderProviderDescription(view.getInput(), contentProvider);