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
|
---|---|---|---|---|---|---|
arquillian/arquillian-container-weld | impl/src/main/java/org/jboss/arquillian/container/weld/embedded/mock/TestContainer.java | // Path: impl/src/main/java/org/jboss/arquillian/container/weld/embedded/literals/DestroyedLiteral.java
// @SuppressWarnings("all")
// public class DestroyedLiteral extends AnnotationLiteral<Destroyed> implements Destroyed {
//
// public static final DestroyedLiteral APPLICATION = new DestroyedLiteral(ApplicationScoped.class);
//
// private Class<? extends Annotation> value;
//
// private DestroyedLiteral(Class<? extends Annotation> value) {
// this.value = value;
// }
//
// @Override
// public Class<? extends Annotation> value() {
// return value;
// }
// }
//
// Path: impl/src/main/java/org/jboss/arquillian/container/weld/embedded/literals/InitializedLiteral.java
// @SuppressWarnings("all")
// public class InitializedLiteral extends AnnotationLiteral<Initialized> implements Initialized {
//
// public static final InitializedLiteral APPLICATION = new InitializedLiteral(ApplicationScoped.class);
//
// private Class<? extends Annotation> value;
//
// private InitializedLiteral(Class<? extends Annotation> value) {
// this.value = value;
// }
//
// @Override
// public Class<? extends Annotation> value() {
// return value;
// }
// }
| import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jakarta.enterprise.context.spi.Context;
import jakarta.enterprise.inject.Instance;
import org.jboss.weld.Container;
import org.jboss.weld.bootstrap.WeldBootstrap;
import org.jboss.weld.bootstrap.api.Bootstrap;
import org.jboss.weld.bootstrap.api.Environment;
import org.jboss.weld.bootstrap.api.Environments;
import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive;
import org.jboss.weld.bootstrap.spi.BeansXml;
import org.jboss.weld.bootstrap.spi.Deployment;
import org.jboss.weld.context.RequestContext;
import org.jboss.weld.context.bound.BoundSessionContext;
import org.jboss.weld.context.unbound.UnboundLiteral;
import org.jboss.weld.manager.api.WeldManager;
import static java.util.Arrays.asList;
import org.jboss.arquillian.container.weld.embedded.literals.DestroyedLiteral;
import org.jboss.arquillian.container.weld.embedded.literals.InitializedLiteral; | public TestContainer ensureRequestActive() {
RequestContext requestContext = instance().select(RequestContext.class, UnboundLiteral.INSTANCE).get();
requestContext.activate();
// TODO deactivate the conversation context
BoundSessionContext sessionContext = instance().select(BoundSessionContext.class).get();
sessionContext.associate(sessionStore);
sessionContext.activate();
return this;
}
public TestContainer startContainer() {
return startContainer(Environments.SE);
}
/**
* Starts the container and begins the application
*/
public TestContainer startContainer(Environment environment) {
this.sessionStore = new HashMap<String, Object>();
this.environment = environment;
bootstrap
.startContainer(environment, deployment)
.startInitialization()
.deployBeans()
.validateBeans()
.endInitialization();
if (environment.equals(Environments.SE)) {
for (BeanDeploymentArchive beanDeploymentArchive : deployment.getBeanDeploymentArchives()) { | // Path: impl/src/main/java/org/jboss/arquillian/container/weld/embedded/literals/DestroyedLiteral.java
// @SuppressWarnings("all")
// public class DestroyedLiteral extends AnnotationLiteral<Destroyed> implements Destroyed {
//
// public static final DestroyedLiteral APPLICATION = new DestroyedLiteral(ApplicationScoped.class);
//
// private Class<? extends Annotation> value;
//
// private DestroyedLiteral(Class<? extends Annotation> value) {
// this.value = value;
// }
//
// @Override
// public Class<? extends Annotation> value() {
// return value;
// }
// }
//
// Path: impl/src/main/java/org/jboss/arquillian/container/weld/embedded/literals/InitializedLiteral.java
// @SuppressWarnings("all")
// public class InitializedLiteral extends AnnotationLiteral<Initialized> implements Initialized {
//
// public static final InitializedLiteral APPLICATION = new InitializedLiteral(ApplicationScoped.class);
//
// private Class<? extends Annotation> value;
//
// private InitializedLiteral(Class<? extends Annotation> value) {
// this.value = value;
// }
//
// @Override
// public Class<? extends Annotation> value() {
// return value;
// }
// }
// Path: impl/src/main/java/org/jboss/arquillian/container/weld/embedded/mock/TestContainer.java
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jakarta.enterprise.context.spi.Context;
import jakarta.enterprise.inject.Instance;
import org.jboss.weld.Container;
import org.jboss.weld.bootstrap.WeldBootstrap;
import org.jboss.weld.bootstrap.api.Bootstrap;
import org.jboss.weld.bootstrap.api.Environment;
import org.jboss.weld.bootstrap.api.Environments;
import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive;
import org.jboss.weld.bootstrap.spi.BeansXml;
import org.jboss.weld.bootstrap.spi.Deployment;
import org.jboss.weld.context.RequestContext;
import org.jboss.weld.context.bound.BoundSessionContext;
import org.jboss.weld.context.unbound.UnboundLiteral;
import org.jboss.weld.manager.api.WeldManager;
import static java.util.Arrays.asList;
import org.jboss.arquillian.container.weld.embedded.literals.DestroyedLiteral;
import org.jboss.arquillian.container.weld.embedded.literals.InitializedLiteral;
public TestContainer ensureRequestActive() {
RequestContext requestContext = instance().select(RequestContext.class, UnboundLiteral.INSTANCE).get();
requestContext.activate();
// TODO deactivate the conversation context
BoundSessionContext sessionContext = instance().select(BoundSessionContext.class).get();
sessionContext.associate(sessionStore);
sessionContext.activate();
return this;
}
public TestContainer startContainer() {
return startContainer(Environments.SE);
}
/**
* Starts the container and begins the application
*/
public TestContainer startContainer(Environment environment) {
this.sessionStore = new HashMap<String, Object>();
this.environment = environment;
bootstrap
.startContainer(environment, deployment)
.startInitialization()
.deployBeans()
.validateBeans()
.endInitialization();
if (environment.equals(Environments.SE)) {
for (BeanDeploymentArchive beanDeploymentArchive : deployment.getBeanDeploymentArchives()) { | bootstrap.getManager(beanDeploymentArchive).getEvent().select(InitializedLiteral.APPLICATION).fire(new Object()); |
arquillian/arquillian-container-weld | impl/src/main/java/org/jboss/arquillian/container/weld/embedded/mock/TestContainer.java | // Path: impl/src/main/java/org/jboss/arquillian/container/weld/embedded/literals/DestroyedLiteral.java
// @SuppressWarnings("all")
// public class DestroyedLiteral extends AnnotationLiteral<Destroyed> implements Destroyed {
//
// public static final DestroyedLiteral APPLICATION = new DestroyedLiteral(ApplicationScoped.class);
//
// private Class<? extends Annotation> value;
//
// private DestroyedLiteral(Class<? extends Annotation> value) {
// this.value = value;
// }
//
// @Override
// public Class<? extends Annotation> value() {
// return value;
// }
// }
//
// Path: impl/src/main/java/org/jboss/arquillian/container/weld/embedded/literals/InitializedLiteral.java
// @SuppressWarnings("all")
// public class InitializedLiteral extends AnnotationLiteral<Initialized> implements Initialized {
//
// public static final InitializedLiteral APPLICATION = new InitializedLiteral(ApplicationScoped.class);
//
// private Class<? extends Annotation> value;
//
// private InitializedLiteral(Class<? extends Annotation> value) {
// this.value = value;
// }
//
// @Override
// public Class<? extends Annotation> value() {
// return value;
// }
// }
| import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jakarta.enterprise.context.spi.Context;
import jakarta.enterprise.inject.Instance;
import org.jboss.weld.Container;
import org.jboss.weld.bootstrap.WeldBootstrap;
import org.jboss.weld.bootstrap.api.Bootstrap;
import org.jboss.weld.bootstrap.api.Environment;
import org.jboss.weld.bootstrap.api.Environments;
import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive;
import org.jboss.weld.bootstrap.spi.BeansXml;
import org.jboss.weld.bootstrap.spi.Deployment;
import org.jboss.weld.context.RequestContext;
import org.jboss.weld.context.bound.BoundSessionContext;
import org.jboss.weld.context.unbound.UnboundLiteral;
import org.jboss.weld.manager.api.WeldManager;
import static java.util.Arrays.asList;
import org.jboss.arquillian.container.weld.embedded.literals.DestroyedLiteral;
import org.jboss.arquillian.container.weld.embedded.literals.InitializedLiteral; |
public WeldManager getBeanManager(BeanDeploymentArchive beanDeploymentArchive) {
return bootstrap.getManager(beanDeploymentArchive);
}
public Deployment getDeployment() {
return deployment;
}
/**
* Clean up the container, ending any active contexts
*/
public TestContainer stopContainer() {
RequestContext requestContext = instance().select(RequestContext.class, UnboundLiteral.INSTANCE).get();
if (requestContext.isActive()) {
requestContext.invalidate();
requestContext.deactivate();
}
// TODO deactivate the conversation context
BoundSessionContext sessionContext = instance().select(BoundSessionContext.class).get();
if (sessionContext.isActive()) {
sessionContext.invalidate();
sessionContext.deactivate();
sessionContext.dissociate(sessionStore);
}
if (environment.equals(Environments.SE)) {
for (BeanDeploymentArchive beanDeploymentArchive : deployment.getBeanDeploymentArchives()) { | // Path: impl/src/main/java/org/jboss/arquillian/container/weld/embedded/literals/DestroyedLiteral.java
// @SuppressWarnings("all")
// public class DestroyedLiteral extends AnnotationLiteral<Destroyed> implements Destroyed {
//
// public static final DestroyedLiteral APPLICATION = new DestroyedLiteral(ApplicationScoped.class);
//
// private Class<? extends Annotation> value;
//
// private DestroyedLiteral(Class<? extends Annotation> value) {
// this.value = value;
// }
//
// @Override
// public Class<? extends Annotation> value() {
// return value;
// }
// }
//
// Path: impl/src/main/java/org/jboss/arquillian/container/weld/embedded/literals/InitializedLiteral.java
// @SuppressWarnings("all")
// public class InitializedLiteral extends AnnotationLiteral<Initialized> implements Initialized {
//
// public static final InitializedLiteral APPLICATION = new InitializedLiteral(ApplicationScoped.class);
//
// private Class<? extends Annotation> value;
//
// private InitializedLiteral(Class<? extends Annotation> value) {
// this.value = value;
// }
//
// @Override
// public Class<? extends Annotation> value() {
// return value;
// }
// }
// Path: impl/src/main/java/org/jboss/arquillian/container/weld/embedded/mock/TestContainer.java
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jakarta.enterprise.context.spi.Context;
import jakarta.enterprise.inject.Instance;
import org.jboss.weld.Container;
import org.jboss.weld.bootstrap.WeldBootstrap;
import org.jboss.weld.bootstrap.api.Bootstrap;
import org.jboss.weld.bootstrap.api.Environment;
import org.jboss.weld.bootstrap.api.Environments;
import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive;
import org.jboss.weld.bootstrap.spi.BeansXml;
import org.jboss.weld.bootstrap.spi.Deployment;
import org.jboss.weld.context.RequestContext;
import org.jboss.weld.context.bound.BoundSessionContext;
import org.jboss.weld.context.unbound.UnboundLiteral;
import org.jboss.weld.manager.api.WeldManager;
import static java.util.Arrays.asList;
import org.jboss.arquillian.container.weld.embedded.literals.DestroyedLiteral;
import org.jboss.arquillian.container.weld.embedded.literals.InitializedLiteral;
public WeldManager getBeanManager(BeanDeploymentArchive beanDeploymentArchive) {
return bootstrap.getManager(beanDeploymentArchive);
}
public Deployment getDeployment() {
return deployment;
}
/**
* Clean up the container, ending any active contexts
*/
public TestContainer stopContainer() {
RequestContext requestContext = instance().select(RequestContext.class, UnboundLiteral.INSTANCE).get();
if (requestContext.isActive()) {
requestContext.invalidate();
requestContext.deactivate();
}
// TODO deactivate the conversation context
BoundSessionContext sessionContext = instance().select(BoundSessionContext.class).get();
if (sessionContext.isActive()) {
sessionContext.invalidate();
sessionContext.deactivate();
sessionContext.dissociate(sessionStore);
}
if (environment.equals(Environments.SE)) {
for (BeanDeploymentArchive beanDeploymentArchive : deployment.getBeanDeploymentArchives()) { | bootstrap.getManager(beanDeploymentArchive).getEvent().select(DestroyedLiteral.APPLICATION).fire(new Object()); |
arquillian/arquillian-container-weld | impl/src/test/java/org/jboss/arquillian/container/weld/embedded/WeldEmbeddedIntegrationSessionScopeTestCase.java | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/Chicken.java
// @SessionScoped
// public class Chicken implements java.io.Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private Integer age;
//
// public Integer getAge()
// {
// return age;
// }
//
// public void setAge(Integer age)
// {
// this.age = age;
// }
//
// }
| import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.beans.Chicken;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith; | /*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.container.weld.embedded;
/**
* WeldEmbeddedIntegrationTestCase
*
* @author <a href="mailto:[email protected]">Aslak Knutsen</a>
* @version $Revision: $
*/
@RunWith(Arquillian.class)
public class WeldEmbeddedIntegrationSessionScopeTestCase
{
@Deployment
public static JavaArchive createdeployment()
{
return ShrinkWrap.create(JavaArchive.class)
.addClasses(
WeldEmbeddedIntegrationSessionScopeTestCase.class, | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/Chicken.java
// @SessionScoped
// public class Chicken implements java.io.Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private Integer age;
//
// public Integer getAge()
// {
// return age;
// }
//
// public void setAge(Integer age)
// {
// this.age = age;
// }
//
// }
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/WeldEmbeddedIntegrationSessionScopeTestCase.java
import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.beans.Chicken;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.container.weld.embedded;
/**
* WeldEmbeddedIntegrationTestCase
*
* @author <a href="mailto:[email protected]">Aslak Knutsen</a>
* @version $Revision: $
*/
@RunWith(Arquillian.class)
public class WeldEmbeddedIntegrationSessionScopeTestCase
{
@Deployment
public static JavaArchive createdeployment()
{
return ShrinkWrap.create(JavaArchive.class)
.addClasses(
WeldEmbeddedIntegrationSessionScopeTestCase.class, | Chicken.class) |
arquillian/arquillian-container-weld | impl/src/main/java/org/jboss/arquillian/container/weld/embedded/mock/BeanDeploymentArchiveImpl.java | // Path: impl/src/main/java/org/jboss/arquillian/container/weld/embedded/mock/Ejbs.java
// public static Collection<EjbDescriptor<?>> createEjbDescriptors(Iterable<Class<?>> classes) {
// // EJB API dependency is optional
// if (!Utils.isClassAccessible("jakarta.ejb.Singleton", Ejbs.class.getClassLoader())) {
// return Collections.emptySet();
// }
// List<EjbDescriptor<?>> ejbs = new ArrayList<EjbDescriptor<?>>();
// for (Class<?> ejbClass : findEjbs(classes)) {
// ejbs.add(MockEjbDescriptor.of(ejbClass));
// }
// return ejbs;
// }
| import static java.util.Arrays.asList;
import static org.jboss.arquillian.container.weld.embedded.mock.Ejbs.createEjbDescriptors;
import static org.jboss.weld.bootstrap.spi.BeansXml.EMPTY_BEANS_XML;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import org.jboss.weld.bootstrap.api.Environment;
import org.jboss.weld.bootstrap.api.Environments;
import org.jboss.weld.bootstrap.api.ServiceRegistry;
import org.jboss.weld.bootstrap.api.helpers.SimpleServiceRegistry;
import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive;
import org.jboss.weld.bootstrap.spi.BeansXml;
import org.jboss.weld.ejb.spi.EjbDescriptor;
import org.jboss.weld.injection.spi.EjbInjectionServices;
import org.jboss.weld.injection.spi.JpaInjectionServices;
import org.jboss.weld.injection.spi.ResourceInjectionServices; | }
public BeanDeploymentArchiveImpl(Iterable<Class<?>> classes, Environment environment) {
this("test", EMPTY_BEANS_XML, classes, environment);
}
public BeanDeploymentArchiveImpl(String id, Environment environment, Class<?>... classes) {
this(id, EMPTY_BEANS_XML, asList(classes), environment);
}
public BeanDeploymentArchiveImpl(String id, Class<?>... classes) {
this(id, EMPTY_BEANS_XML, asList(classes), Environments.SE);
}
public BeanDeploymentArchiveImpl(String id, BeansXml beansXml, Environment environment, Class<?>... classes) {
this(id, beansXml, asList(classes), environment);
}
public BeanDeploymentArchiveImpl(String id, BeansXml beansXml, Class<?>... classes) {
this(id, beansXml, asList(classes), Environments.SE);
}
public BeanDeploymentArchiveImpl(String id, BeansXml beansXml, Iterable<Class<?>> beanClasses, Environment environment) {
this.services = new SimpleServiceRegistry();
this.bdas = new HashSet<BeanDeploymentArchive>();
this.beanClasses = new ArrayList<String>();
for (Class<?> clazz : beanClasses) {
this.beanClasses.add(clazz.getName());
}
this.beansXml = beansXml; | // Path: impl/src/main/java/org/jboss/arquillian/container/weld/embedded/mock/Ejbs.java
// public static Collection<EjbDescriptor<?>> createEjbDescriptors(Iterable<Class<?>> classes) {
// // EJB API dependency is optional
// if (!Utils.isClassAccessible("jakarta.ejb.Singleton", Ejbs.class.getClassLoader())) {
// return Collections.emptySet();
// }
// List<EjbDescriptor<?>> ejbs = new ArrayList<EjbDescriptor<?>>();
// for (Class<?> ejbClass : findEjbs(classes)) {
// ejbs.add(MockEjbDescriptor.of(ejbClass));
// }
// return ejbs;
// }
// Path: impl/src/main/java/org/jboss/arquillian/container/weld/embedded/mock/BeanDeploymentArchiveImpl.java
import static java.util.Arrays.asList;
import static org.jboss.arquillian.container.weld.embedded.mock.Ejbs.createEjbDescriptors;
import static org.jboss.weld.bootstrap.spi.BeansXml.EMPTY_BEANS_XML;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import org.jboss.weld.bootstrap.api.Environment;
import org.jboss.weld.bootstrap.api.Environments;
import org.jboss.weld.bootstrap.api.ServiceRegistry;
import org.jboss.weld.bootstrap.api.helpers.SimpleServiceRegistry;
import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive;
import org.jboss.weld.bootstrap.spi.BeansXml;
import org.jboss.weld.ejb.spi.EjbDescriptor;
import org.jboss.weld.injection.spi.EjbInjectionServices;
import org.jboss.weld.injection.spi.JpaInjectionServices;
import org.jboss.weld.injection.spi.ResourceInjectionServices;
}
public BeanDeploymentArchiveImpl(Iterable<Class<?>> classes, Environment environment) {
this("test", EMPTY_BEANS_XML, classes, environment);
}
public BeanDeploymentArchiveImpl(String id, Environment environment, Class<?>... classes) {
this(id, EMPTY_BEANS_XML, asList(classes), environment);
}
public BeanDeploymentArchiveImpl(String id, Class<?>... classes) {
this(id, EMPTY_BEANS_XML, asList(classes), Environments.SE);
}
public BeanDeploymentArchiveImpl(String id, BeansXml beansXml, Environment environment, Class<?>... classes) {
this(id, beansXml, asList(classes), environment);
}
public BeanDeploymentArchiveImpl(String id, BeansXml beansXml, Class<?>... classes) {
this(id, beansXml, asList(classes), Environments.SE);
}
public BeanDeploymentArchiveImpl(String id, BeansXml beansXml, Iterable<Class<?>> beanClasses, Environment environment) {
this.services = new SimpleServiceRegistry();
this.bdas = new HashSet<BeanDeploymentArchive>();
this.beanClasses = new ArrayList<String>();
for (Class<?> clazz : beanClasses) {
this.beanClasses.add(clazz.getName());
}
this.beansXml = beansXml; | this.ejbs = createEjbDescriptors(beanClasses); |
arquillian/arquillian-container-weld | impl/src/test/java/org/jboss/arquillian/container/weld/embedded/ExcludedBeansTest.java | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/Chicken.java
// @SessionScoped
// public class Chicken implements java.io.Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private Integer age;
//
// public Integer getAge()
// {
// return age;
// }
//
// public void setAge(Integer age)
// {
// this.age = age;
// }
//
// }
//
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/MyBean.java
// @ApplicationScoped
// public class MyBean implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private String name = "aslak";
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
| import static org.junit.Assert.assertTrue;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.beans.Chicken;
import org.jboss.arquillian.container.weld.embedded.beans.MyBean;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.beans11.BeansDescriptor;
import org.junit.Test;
import org.junit.runner.RunWith; | package org.jboss.arquillian.container.weld.embedded;
/**
* @author Tomas Remes
*/
@RunWith(Arquillian.class)
public class ExcludedBeansTest {
private final static String NON_EXISTING_CLASS = "org.jboss.test.NonExistent";
@Inject | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/Chicken.java
// @SessionScoped
// public class Chicken implements java.io.Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private Integer age;
//
// public Integer getAge()
// {
// return age;
// }
//
// public void setAge(Integer age)
// {
// this.age = age;
// }
//
// }
//
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/MyBean.java
// @ApplicationScoped
// public class MyBean implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private String name = "aslak";
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/ExcludedBeansTest.java
import static org.junit.Assert.assertTrue;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.beans.Chicken;
import org.jboss.arquillian.container.weld.embedded.beans.MyBean;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.beans11.BeansDescriptor;
import org.junit.Test;
import org.junit.runner.RunWith;
package org.jboss.arquillian.container.weld.embedded;
/**
* @author Tomas Remes
*/
@RunWith(Arquillian.class)
public class ExcludedBeansTest {
private final static String NON_EXISTING_CLASS = "org.jboss.test.NonExistent";
@Inject | Instance<MyBean> myBeanInstance; |
arquillian/arquillian-container-weld | impl/src/test/java/org/jboss/arquillian/container/weld/embedded/ExcludedBeansTest.java | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/Chicken.java
// @SessionScoped
// public class Chicken implements java.io.Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private Integer age;
//
// public Integer getAge()
// {
// return age;
// }
//
// public void setAge(Integer age)
// {
// this.age = age;
// }
//
// }
//
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/MyBean.java
// @ApplicationScoped
// public class MyBean implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private String name = "aslak";
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
| import static org.junit.Assert.assertTrue;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.beans.Chicken;
import org.jboss.arquillian.container.weld.embedded.beans.MyBean;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.beans11.BeansDescriptor;
import org.junit.Test;
import org.junit.runner.RunWith; | package org.jboss.arquillian.container.weld.embedded;
/**
* @author Tomas Remes
*/
@RunWith(Arquillian.class)
public class ExcludedBeansTest {
private final static String NON_EXISTING_CLASS = "org.jboss.test.NonExistent";
@Inject
Instance<MyBean> myBeanInstance;
@Inject | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/Chicken.java
// @SessionScoped
// public class Chicken implements java.io.Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private Integer age;
//
// public Integer getAge()
// {
// return age;
// }
//
// public void setAge(Integer age)
// {
// this.age = age;
// }
//
// }
//
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/MyBean.java
// @ApplicationScoped
// public class MyBean implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private String name = "aslak";
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/ExcludedBeansTest.java
import static org.junit.Assert.assertTrue;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.beans.Chicken;
import org.jboss.arquillian.container.weld.embedded.beans.MyBean;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.beans11.BeansDescriptor;
import org.junit.Test;
import org.junit.runner.RunWith;
package org.jboss.arquillian.container.weld.embedded;
/**
* @author Tomas Remes
*/
@RunWith(Arquillian.class)
public class ExcludedBeansTest {
private final static String NON_EXISTING_CLASS = "org.jboss.test.NonExistent";
@Inject
Instance<MyBean> myBeanInstance;
@Inject | Instance<Chicken> chickenInstance; |
arquillian/arquillian-container-weld | impl/src/test/java/org/jboss/arquillian/container/weld/embedded/WeldEmbeddedIntegrationConversationScopeTestCase.java | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/TalkingChicken.java
// @ConversationScoped
// public class TalkingChicken implements java.io.Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private Integer age = -1;
//
// public Integer getAge()
// {
// return age;
// }
//
// public void setAge(Integer age)
// {
// this.age = age;
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import jakarta.enterprise.context.Conversation;
import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.beans.TalkingChicken;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith; | /*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.container.weld.embedded;
/**
* WeldEmbeddedIntegrationTestCase
*
* @author <a href="mailto:[email protected]">Aslak Knutsen</a>
* @version $Revision: $
*/
@RunWith(Arquillian.class)
public class WeldEmbeddedIntegrationConversationScopeTestCase
{
@Deployment
public static JavaArchive createdeployment()
{
return ShrinkWrap.create(JavaArchive.class)
.addClasses(
WeldEmbeddedIntegrationConversationScopeTestCase.class, | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/TalkingChicken.java
// @ConversationScoped
// public class TalkingChicken implements java.io.Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private Integer age = -1;
//
// public Integer getAge()
// {
// return age;
// }
//
// public void setAge(Integer age)
// {
// this.age = age;
// }
//
// }
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/WeldEmbeddedIntegrationConversationScopeTestCase.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import jakarta.enterprise.context.Conversation;
import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.beans.TalkingChicken;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.container.weld.embedded;
/**
* WeldEmbeddedIntegrationTestCase
*
* @author <a href="mailto:[email protected]">Aslak Knutsen</a>
* @version $Revision: $
*/
@RunWith(Arquillian.class)
public class WeldEmbeddedIntegrationConversationScopeTestCase
{
@Deployment
public static JavaArchive createdeployment()
{
return ShrinkWrap.create(JavaArchive.class)
.addClasses(
WeldEmbeddedIntegrationConversationScopeTestCase.class, | TalkingChicken.class) |
arquillian/arquillian-container-weld | impl/src/test/java/org/jboss/arquillian/container/weld/embedded/WeldEmbeddedCDIProviderTest.java | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/MyBean.java
// @ApplicationScoped
// public class MyBean implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private String name = "aslak";
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
| import jakarta.enterprise.inject.spi.CDI;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.beans.MyBean;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; | /*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.container.weld.embedded;
/**
* Note that this test will fail if using any of CDI 1.0 implementations (i.e. Weld 1.0.x and Weld 1.1.x).
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class WeldEmbeddedCDIProviderTest {
@Deployment
public static JavaArchive createTestArchive() { | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/MyBean.java
// @ApplicationScoped
// public class MyBean implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private String name = "aslak";
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/WeldEmbeddedCDIProviderTest.java
import jakarta.enterprise.inject.spi.CDI;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.beans.MyBean;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.container.weld.embedded;
/**
* Note that this test will fail if using any of CDI 1.0 implementations (i.e. Weld 1.0.x and Weld 1.1.x).
*
* @author Martin Kouba
*/
@RunWith(Arquillian.class)
public class WeldEmbeddedCDIProviderTest {
@Deployment
public static JavaArchive createTestArchive() { | return ShrinkWrap.create(JavaArchive.class).addClasses(WeldEmbeddedCDIProviderTest.class, MyBean.class) |
arquillian/arquillian-container-weld | impl/src/test/java/org/jboss/arquillian/container/weld/embedded/WeldEmbeddedBeforeAfterTestCase.java | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/MyBean.java
// @ApplicationScoped
// public class MyBean implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private String name = "aslak";
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
| import org.junit.runner.RunWith;
import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.beans.MyBean;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test; | /*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.container.weld.embedded;
/**
* WeldEmbeddedIntegrationTestCase
*
* @author <a href="mailto:[email protected]">Aslak Knutsen</a>
* @version $Revision: $
*/
@RunWith(Arquillian.class)
public class WeldEmbeddedBeforeAfterTestCase
{
@Deployment
public static JavaArchive createdeployment()
{
return ShrinkWrap.create(JavaArchive.class, "test.jar")
.addClasses(
WeldEmbeddedBeforeAfterTestCase.class, | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/MyBean.java
// @ApplicationScoped
// public class MyBean implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private String name = "aslak";
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/WeldEmbeddedBeforeAfterTestCase.java
import org.junit.runner.RunWith;
import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.beans.MyBean;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.container.weld.embedded;
/**
* WeldEmbeddedIntegrationTestCase
*
* @author <a href="mailto:[email protected]">Aslak Knutsen</a>
* @version $Revision: $
*/
@RunWith(Arquillian.class)
public class WeldEmbeddedBeforeAfterTestCase
{
@Deployment
public static JavaArchive createdeployment()
{
return ShrinkWrap.create(JavaArchive.class, "test.jar")
.addClasses(
WeldEmbeddedBeforeAfterTestCase.class, | MyBean.class) |
arquillian/arquillian-container-weld | impl/src/test/java/org/jboss/arquillian/container/weld/embedded/WeldEmbeddedIntegrationWARTestCase.java | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/MyBean.java
// @ApplicationScoped
// public class MyBean implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private String name = "aslak";
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
| import jakarta.enterprise.inject.spi.Extension;
import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.beans.MyBean;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith; | /*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.container.weld.embedded;
/**
* WeldEmbeddedIntegrationTestCase
*
* @author <a href="mailto:[email protected]">Aslak Knutsen</a>
* @version $Revision: $
*/
@RunWith(Arquillian.class)
public class WeldEmbeddedIntegrationWARTestCase
{
@Deployment
public static WebArchive createdeployment()
{
return ShrinkWrap.create(WebArchive.class, "test.war")
.addClasses(
WeldEmbeddedIntegrationWARTestCase.class,
BeforeBeanDiscoveryObserver.class, | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/MyBean.java
// @ApplicationScoped
// public class MyBean implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private String name = "aslak";
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/WeldEmbeddedIntegrationWARTestCase.java
import jakarta.enterprise.inject.spi.Extension;
import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.beans.MyBean;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.container.weld.embedded;
/**
* WeldEmbeddedIntegrationTestCase
*
* @author <a href="mailto:[email protected]">Aslak Knutsen</a>
* @version $Revision: $
*/
@RunWith(Arquillian.class)
public class WeldEmbeddedIntegrationWARTestCase
{
@Deployment
public static WebArchive createdeployment()
{
return ShrinkWrap.create(WebArchive.class, "test.war")
.addClasses(
WeldEmbeddedIntegrationWARTestCase.class,
BeforeBeanDiscoveryObserver.class, | MyBean.class) |
arquillian/arquillian-container-weld | impl/src/test/java/org/jboss/arquillian/container/weld/embedded/WeldEmbeddedIntegrationJARTestCase.java | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/MyBean.java
// @ApplicationScoped
// public class MyBean implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private String name = "aslak";
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
| import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.beans.MyBean;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith; | /*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.container.weld.embedded;
/**
* WeldEmbeddedIntegrationTestCase
*
* @author <a href="mailto:[email protected]">Aslak Knutsen</a>
* @version $Revision: $
*/
@RunWith(Arquillian.class)
public class WeldEmbeddedIntegrationJARTestCase
{
@Deployment
public static JavaArchive createdeployment()
{
return ShrinkWrap.create(JavaArchive.class)
.addClasses(
WeldEmbeddedIntegrationJARTestCase.class, | // Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/beans/MyBean.java
// @ApplicationScoped
// public class MyBean implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// private String name = "aslak";
//
// public String getName()
// {
// return name;
// }
//
// public void setName(String name)
// {
// this.name = name;
// }
// }
// Path: impl/src/test/java/org/jboss/arquillian/container/weld/embedded/WeldEmbeddedIntegrationJARTestCase.java
import jakarta.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.weld.embedded.beans.MyBean;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
/*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.container.weld.embedded;
/**
* WeldEmbeddedIntegrationTestCase
*
* @author <a href="mailto:[email protected]">Aslak Knutsen</a>
* @version $Revision: $
*/
@RunWith(Arquillian.class)
public class WeldEmbeddedIntegrationJARTestCase
{
@Deployment
public static JavaArchive createdeployment()
{
return ShrinkWrap.create(JavaArchive.class)
.addClasses(
WeldEmbeddedIntegrationJARTestCase.class, | MyBean.class) |
TreeCmp/TreeCmp | src/treecmp/spr/SprHeuristicMpRfcMetric.java | // Path: src/treecmp/metric/MatchingPairMetric.java
// public class MatchingPairMetric extends BaseMetric implements Metric {
//
// protected int[] rowsol;
// protected int[] colsol;
// protected int[][] assigncost;
//
// public MatchingPairMetric() {
// super();
// }
//
// @Override
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// if (t1.getExternalNodeCount() <= 2){
// return 0.0;
// }
//
// IdGroup id1 = TreeUtils.getLeafIdGroup(t1);
// int[][] lcaMatrix1 = TreeCmpUtils.calcLcaMatrix(t1, null);
// int[][] lcaMatrix2 = TreeCmpUtils.calcLcaMatrix(t2, id1);
//
// int intT1Num = t1.getInternalNodeCount();
// int intT2Num = t2.getInternalNodeCount();
//
// Node[] postOrderT1 = TreeCmpUtils.getNodesInPostOrder(t1);
// Node[] postOrderT2 = TreeCmpUtils.getNodesInPostOrder(t2);
//
// short[] cSize1 = new short[intT1Num];
// short[] cSize2 = new short[intT2Num];
//
// TreeCmpUtils.calcCladeSizes(t1, postOrderT1, cSize1);
// TreeCmpUtils.calcCladeSizes(t2, postOrderT2, cSize2);
//
// int N = t1.getExternalNodeCount();
//
// int size = Math.max(intT1Num, intT2Num);
// if (size <= 0) {
// return 0;
// }
//
// assigncost = new int[size][size];
// rowsol = new int[size];
// colsol = new int[size];
// int[] u = new int[size];
// int[] v = new int[size];
//
// //iterate by all possible pairs of leaves
// //and fill assigncont with the value of intersection size
// for (int i = 0; i < N; i++){
// for (int j = i+1; j < N; j++){
// int int1 = lcaMatrix1[i][j];
// int int2 = lcaMatrix2[i][j];
// assigncost[int1][int2]++;
// }
// }
// //count LCA pairs for t1
// int[] t1IntPairCount = new int[intT1Num];
// for (int i = 0; i < intT1Num; i++){
// //Node n = t1.getInternalNode(alias1[i]);
// Node n = t1.getInternalNode(i);
// t1IntPairCount[i] = coutChildrenPairs(n, cSize1);
// }
// //count LCA pairs for t2
// int[] t2IntPairCount = new int[intT2Num];
// for (int i = 0; i < intT2Num; i++){
// //Node n = t2.getInternalNode(alias2[i]);
// Node n = t2.getInternalNode(i);
// t2IntPairCount[i] = coutChildrenPairs(n, cSize2);
// }
//
// //calc xor valuses of pairs sets and store it in assigncost matrix
// for (int i = 0; i < size; i++){
// for (int j = 0; j < size; j++){
// if (i < intT1Num && j < intT2Num){
// assigncost[i][j] = t1IntPairCount[i]+t2IntPairCount[j] - (assigncost[i][j] << 1);
// } else if (i >= intT1Num && j < intT2Num){
// assigncost[i][j] = t2IntPairCount[j];
// } else if (i < intT1Num && j >= intT2Num){
// assigncost[i][j] = t1IntPairCount[i];
// }else {
// //normally should not happen
// assigncost[i][j] = 0;
// }
// }
// }
// int metric = LapSolver.lap(size, assigncost, rowsol, colsol, u, v);
// return (0.5 * (double) metric);
// }
//
//
// int coutChildrenPairs(Node n, short[] clustSizeTab) {
// int chCount = n.getChildCount();
// int[] cSize = new int[chCount];
//
// for (int i = 0; i < chCount; i++) {
// Node chNode = n.getChild(i);
// if (chNode.isLeaf()) {
// cSize[i] = 1;
// } else {
// cSize[i] = clustSizeTab[chNode.getNumber()];
// }
// }
// int pairCount = 0;
// for (int i = 0; i < cSize.length; i++) {
// for (int j = i + 1; j < cSize.length; j++) {
// pairCount += (cSize[i] * cSize[j]);
// }
// }
// return pairCount;
// }
// }
| import treecmp.metric.MatchingPairMetric;
import treecmp.metric.Metric; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class SprHeuristicMpRfcMetric extends SprHeuristicRfcBaseMetric{
@Override
protected Metric getMetric(){ | // Path: src/treecmp/metric/MatchingPairMetric.java
// public class MatchingPairMetric extends BaseMetric implements Metric {
//
// protected int[] rowsol;
// protected int[] colsol;
// protected int[][] assigncost;
//
// public MatchingPairMetric() {
// super();
// }
//
// @Override
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// if (t1.getExternalNodeCount() <= 2){
// return 0.0;
// }
//
// IdGroup id1 = TreeUtils.getLeafIdGroup(t1);
// int[][] lcaMatrix1 = TreeCmpUtils.calcLcaMatrix(t1, null);
// int[][] lcaMatrix2 = TreeCmpUtils.calcLcaMatrix(t2, id1);
//
// int intT1Num = t1.getInternalNodeCount();
// int intT2Num = t2.getInternalNodeCount();
//
// Node[] postOrderT1 = TreeCmpUtils.getNodesInPostOrder(t1);
// Node[] postOrderT2 = TreeCmpUtils.getNodesInPostOrder(t2);
//
// short[] cSize1 = new short[intT1Num];
// short[] cSize2 = new short[intT2Num];
//
// TreeCmpUtils.calcCladeSizes(t1, postOrderT1, cSize1);
// TreeCmpUtils.calcCladeSizes(t2, postOrderT2, cSize2);
//
// int N = t1.getExternalNodeCount();
//
// int size = Math.max(intT1Num, intT2Num);
// if (size <= 0) {
// return 0;
// }
//
// assigncost = new int[size][size];
// rowsol = new int[size];
// colsol = new int[size];
// int[] u = new int[size];
// int[] v = new int[size];
//
// //iterate by all possible pairs of leaves
// //and fill assigncont with the value of intersection size
// for (int i = 0; i < N; i++){
// for (int j = i+1; j < N; j++){
// int int1 = lcaMatrix1[i][j];
// int int2 = lcaMatrix2[i][j];
// assigncost[int1][int2]++;
// }
// }
// //count LCA pairs for t1
// int[] t1IntPairCount = new int[intT1Num];
// for (int i = 0; i < intT1Num; i++){
// //Node n = t1.getInternalNode(alias1[i]);
// Node n = t1.getInternalNode(i);
// t1IntPairCount[i] = coutChildrenPairs(n, cSize1);
// }
// //count LCA pairs for t2
// int[] t2IntPairCount = new int[intT2Num];
// for (int i = 0; i < intT2Num; i++){
// //Node n = t2.getInternalNode(alias2[i]);
// Node n = t2.getInternalNode(i);
// t2IntPairCount[i] = coutChildrenPairs(n, cSize2);
// }
//
// //calc xor valuses of pairs sets and store it in assigncost matrix
// for (int i = 0; i < size; i++){
// for (int j = 0; j < size; j++){
// if (i < intT1Num && j < intT2Num){
// assigncost[i][j] = t1IntPairCount[i]+t2IntPairCount[j] - (assigncost[i][j] << 1);
// } else if (i >= intT1Num && j < intT2Num){
// assigncost[i][j] = t2IntPairCount[j];
// } else if (i < intT1Num && j >= intT2Num){
// assigncost[i][j] = t1IntPairCount[i];
// }else {
// //normally should not happen
// assigncost[i][j] = 0;
// }
// }
// }
// int metric = LapSolver.lap(size, assigncost, rowsol, colsol, u, v);
// return (0.5 * (double) metric);
// }
//
//
// int coutChildrenPairs(Node n, short[] clustSizeTab) {
// int chCount = n.getChildCount();
// int[] cSize = new int[chCount];
//
// for (int i = 0; i < chCount; i++) {
// Node chNode = n.getChild(i);
// if (chNode.isLeaf()) {
// cSize[i] = 1;
// } else {
// cSize[i] = clustSizeTab[chNode.getNumber()];
// }
// }
// int pairCount = 0;
// for (int i = 0; i < cSize.length; i++) {
// for (int j = i + 1; j < cSize.length; j++) {
// pairCount += (cSize[i] * cSize[j]);
// }
// }
// return pairCount;
// }
// }
// Path: src/treecmp/spr/SprHeuristicMpRfcMetric.java
import treecmp.metric.MatchingPairMetric;
import treecmp.metric.Metric;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class SprHeuristicMpRfcMetric extends SprHeuristicRfcBaseMetric{
@Override
protected Metric getMetric(){ | return new MatchingPairMetric(); |
TreeCmp/TreeCmp | src/treecmp/common/ReportUtils.java | // Path: src/treecmp/config/IOSettings.java
// public class IOSettings {
//
// private static IOSettings IOConf;
// private String inputFile;
// private String outputFile;
// private String sSep;
// private String csvSep;
// private boolean zeroValueWeights;
// private boolean pruneTrees;
// private boolean randomComparison;
// private boolean optMsMcByRf;
// private boolean genAlignments;
// private boolean useMsMcFreeLeafSet;;
// private int iStep;
// //defalut false
// private boolean calcCorrelation;
// private boolean genSummary;
// private boolean bifurcatingOnly;
// private boolean rootedMetricUsed;
// private boolean saveComparedTreePairs;
// private boolean saveOnlyBinaryComparedTreePairs;
// private boolean genSackinIndexes;
//
// public boolean isUseMsMcFreeLeafSet() {
// return useMsMcFreeLeafSet;
// }
//
// public void setUseMsMcFreeLeafSet(boolean useMsMcFreeLeafSet) {
// this.useMsMcFreeLeafSet = useMsMcFreeLeafSet;
// }
//
// public boolean isGenSummary() {
// return genSummary;
// }
//
// public void setGenSummary(boolean genSummary) {
// this.genSummary = genSummary;
// }
//
// public boolean isBifurcatingOnly() { return bifurcatingOnly; }
//
// public void setBifurcatingOnly(boolean bifurcatingOnly) {
// this.bifurcatingOnly = bifurcatingOnly;
// }
//
// public boolean isRandomComparison() {
// return randomComparison;
// }
//
// public void setRandomComparison(boolean randomComparison) {
// this.randomComparison = randomComparison;
// }
//
// public boolean isCalcCorrelation() { return calcCorrelation; }
//
// public void setCalcCorrelation(boolean calcCorrelation) {
// this.calcCorrelation = calcCorrelation;
// }
//
// public String getSSep() {
// return sSep;
// }
//
// public void setSSep(String sSep) {
// this.sSep = sSep;
// }
//
// public String getCsvSep() {
// return csvSep;
// }
//
// public void setCsvSep(String csvSep) {
// this.csvSep = csvSep;
// }
//
// public int getIStep() {
// return iStep;
// }
//
// public void setIStep(int iStep) {
// this.iStep = iStep;
// }
//
// public String getInputFile() {
// return inputFile;
// }
//
// public void setInputFile(String inputFile) {
// this.inputFile = inputFile;
// }
//
// public String getOutputFile() {
// return outputFile;
// }
//
// public void setOutputFile(String outputFile) {
// this.outputFile = outputFile;
// }
//
//
// protected IOSettings()
// {
// inputFile = null;
// outputFile = null;
// iStep = 1;
// calcCorrelation = false;
// pruneTrees = false;
// randomComparison = false;
// optMsMcByRf = false;
// genAlignments = false;
// genSummary = false;
//
//
// }
// public static IOSettings getIOSettings()
// {
// if(IOConf==null)
// {
// IOConf=new IOSettings();
// }
// return IOConf;
// }
//
// public void setZeroValueWeights(boolean zeroValueWeights) {
// this.zeroValueWeights = zeroValueWeights;
// }
//
// public boolean isZeroValueWeights() { return zeroValueWeights; }
//
// public boolean isPruneTrees() {
// return pruneTrees;
// }
//
// public void setPruneTrees(boolean pruneTrees) {
// this.pruneTrees = pruneTrees;
// }
//
// public boolean isGenAlignments() {
// return genAlignments;
// }
//
// public void setGenAlignments(boolean genAlignments) {
// this.genAlignments = genAlignments;
// }
//
// public boolean isOptMsMcByRf() {
// return optMsMcByRf;
// }
//
// public void setOptMsMcByRf(boolean optMsMcByRf) {
// this.optMsMcByRf = optMsMcByRf;
// }
//
// public boolean isRootedMetricUsed() { return rootedMetricUsed; }
//
// public void setRootedMetricUsed(boolean rootedMetricUsed) {
// this.rootedMetricUsed = rootedMetricUsed;
// }
//
// public void setSaveComparedTreePairs(boolean saveComparedTreePairs) {
// this.saveComparedTreePairs = saveComparedTreePairs;
// }
// public boolean isSaveComparedTreePairs() { return saveComparedTreePairs; }
//
// public void setSaveOnlyBifurcatingComparedTreePairs(boolean saveOnlyBinaryComparedTreePairs) {
// this.saveOnlyBinaryComparedTreePairs = saveOnlyBinaryComparedTreePairs;
// }
// public boolean isSaveOnlyBinaryComparedTreePairs() { return saveOnlyBinaryComparedTreePairs; }
//
// public void setGenSackinIndexes(boolean genSackinIndexes) { this.genSackinIndexes = genSackinIndexes; }
//
// public boolean isGenSackinIndexes() { return genSackinIndexes; }
// }
| import java.util.ArrayList;
import java.util.Locale;
import treecmp.config.IOSettings; | /** This file is part of TreeCmp, a tool for comparing phylogenetic trees
using the Matching Split distance and other metrics.
Copyright (C) 2011, Damian Bogdanowicz
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package treecmp.common;
public class ReportUtils {
private final static int ROW_PRECISION = 4;
public final static String ROW_DATA_FORMAT="%1$."+ROW_PRECISION+"f"; | // Path: src/treecmp/config/IOSettings.java
// public class IOSettings {
//
// private static IOSettings IOConf;
// private String inputFile;
// private String outputFile;
// private String sSep;
// private String csvSep;
// private boolean zeroValueWeights;
// private boolean pruneTrees;
// private boolean randomComparison;
// private boolean optMsMcByRf;
// private boolean genAlignments;
// private boolean useMsMcFreeLeafSet;;
// private int iStep;
// //defalut false
// private boolean calcCorrelation;
// private boolean genSummary;
// private boolean bifurcatingOnly;
// private boolean rootedMetricUsed;
// private boolean saveComparedTreePairs;
// private boolean saveOnlyBinaryComparedTreePairs;
// private boolean genSackinIndexes;
//
// public boolean isUseMsMcFreeLeafSet() {
// return useMsMcFreeLeafSet;
// }
//
// public void setUseMsMcFreeLeafSet(boolean useMsMcFreeLeafSet) {
// this.useMsMcFreeLeafSet = useMsMcFreeLeafSet;
// }
//
// public boolean isGenSummary() {
// return genSummary;
// }
//
// public void setGenSummary(boolean genSummary) {
// this.genSummary = genSummary;
// }
//
// public boolean isBifurcatingOnly() { return bifurcatingOnly; }
//
// public void setBifurcatingOnly(boolean bifurcatingOnly) {
// this.bifurcatingOnly = bifurcatingOnly;
// }
//
// public boolean isRandomComparison() {
// return randomComparison;
// }
//
// public void setRandomComparison(boolean randomComparison) {
// this.randomComparison = randomComparison;
// }
//
// public boolean isCalcCorrelation() { return calcCorrelation; }
//
// public void setCalcCorrelation(boolean calcCorrelation) {
// this.calcCorrelation = calcCorrelation;
// }
//
// public String getSSep() {
// return sSep;
// }
//
// public void setSSep(String sSep) {
// this.sSep = sSep;
// }
//
// public String getCsvSep() {
// return csvSep;
// }
//
// public void setCsvSep(String csvSep) {
// this.csvSep = csvSep;
// }
//
// public int getIStep() {
// return iStep;
// }
//
// public void setIStep(int iStep) {
// this.iStep = iStep;
// }
//
// public String getInputFile() {
// return inputFile;
// }
//
// public void setInputFile(String inputFile) {
// this.inputFile = inputFile;
// }
//
// public String getOutputFile() {
// return outputFile;
// }
//
// public void setOutputFile(String outputFile) {
// this.outputFile = outputFile;
// }
//
//
// protected IOSettings()
// {
// inputFile = null;
// outputFile = null;
// iStep = 1;
// calcCorrelation = false;
// pruneTrees = false;
// randomComparison = false;
// optMsMcByRf = false;
// genAlignments = false;
// genSummary = false;
//
//
// }
// public static IOSettings getIOSettings()
// {
// if(IOConf==null)
// {
// IOConf=new IOSettings();
// }
// return IOConf;
// }
//
// public void setZeroValueWeights(boolean zeroValueWeights) {
// this.zeroValueWeights = zeroValueWeights;
// }
//
// public boolean isZeroValueWeights() { return zeroValueWeights; }
//
// public boolean isPruneTrees() {
// return pruneTrees;
// }
//
// public void setPruneTrees(boolean pruneTrees) {
// this.pruneTrees = pruneTrees;
// }
//
// public boolean isGenAlignments() {
// return genAlignments;
// }
//
// public void setGenAlignments(boolean genAlignments) {
// this.genAlignments = genAlignments;
// }
//
// public boolean isOptMsMcByRf() {
// return optMsMcByRf;
// }
//
// public void setOptMsMcByRf(boolean optMsMcByRf) {
// this.optMsMcByRf = optMsMcByRf;
// }
//
// public boolean isRootedMetricUsed() { return rootedMetricUsed; }
//
// public void setRootedMetricUsed(boolean rootedMetricUsed) {
// this.rootedMetricUsed = rootedMetricUsed;
// }
//
// public void setSaveComparedTreePairs(boolean saveComparedTreePairs) {
// this.saveComparedTreePairs = saveComparedTreePairs;
// }
// public boolean isSaveComparedTreePairs() { return saveComparedTreePairs; }
//
// public void setSaveOnlyBifurcatingComparedTreePairs(boolean saveOnlyBinaryComparedTreePairs) {
// this.saveOnlyBinaryComparedTreePairs = saveOnlyBinaryComparedTreePairs;
// }
// public boolean isSaveOnlyBinaryComparedTreePairs() { return saveOnlyBinaryComparedTreePairs; }
//
// public void setGenSackinIndexes(boolean genSackinIndexes) { this.genSackinIndexes = genSackinIndexes; }
//
// public boolean isGenSackinIndexes() { return genSackinIndexes; }
// }
// Path: src/treecmp/common/ReportUtils.java
import java.util.ArrayList;
import java.util.Locale;
import treecmp.config.IOSettings;
/** This file is part of TreeCmp, a tool for comparing phylogenetic trees
using the Matching Split distance and other metrics.
Copyright (C) 2011, Damian Bogdanowicz
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package treecmp.common;
public class ReportUtils {
private final static int ROW_PRECISION = 4;
public final static String ROW_DATA_FORMAT="%1$."+ROW_PRECISION+"f"; | private static IOSettings ioSet = IOSettings.getIOSettings(); |
TreeCmp/TreeCmp | src/treecmp/spr/UsprHeuristicMSMetric.java | // Path: src/treecmp/metric/MatchingSplitMetric.java
// public class MatchingSplitMetric extends BaseMetric implements Metric {
// private MatchingSplitMetricO3 ms03;
// private MatchingSplitMetricOptRF msRF;
// private MatchingSpliMetricFree msFree;
//
// public MatchingSplitMetric(){
// super();
// ms03 = new MatchingSplitMetricO3();
// msRF = new MatchingSplitMetricOptRF();
// msFree = new MatchingSpliMetricFree();
// }
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// if (IOSettings.getIOSettings().isOptMsMcByRf())
// return msRF.getDistance(t1, t2);
//
// if (IOSettings.getIOSettings().isUseMsMcFreeLeafSet()) {
// return msFree.getDistance(t1, t2);
// }
//
// return ms03.getDistance(t1, t2);
// }
//
// @Override
// public AlignInfo getAlignment() {
// if (IOSettings.getIOSettings().isOptMsMcByRf()) {
// return null;
// }
//
// if (IOSettings.getIOSettings().isUseMsMcFreeLeafSet()) {
// return null;
// }
// return ms03.getAlignment();
// }
// }
//
// Path: src/treecmp/metric/RFMetric.java
// public class RFMetric extends BaseMetric implements Metric{
//
// public static double getRFDistance(Tree t1, Tree t2) {
//
// int n = t1.getExternalNodeCount();
// if (n <= 3)
// return 0;
//
// IdGroup idGroup = TreeUtils.getLeafIdGroup(t1);
// BitSet[] s_t1=SplitDist.getSplits(t1, idGroup);
// BitSet[] s_t2=SplitDist.getSplits(t2, idGroup);
// int N1=s_t1.length;
// int N2=s_t2.length;
// int hashSetSize=(4*(N1+1))/3;
//
// HashSet<BitSet> s_t1_hs=new HashSet<BitSet>(hashSetSize);
//
// int i;
// for(i=0;i<N1;i++){
// s_t1_hs.add(s_t1[i]);
// }
//
// int common=0;
// for(i=0;i<N2;i++){
// if (s_t1_hs.contains(s_t2[i])){
// common++;
// }
// }
//
// double dist=((double)N1+(double)N2)*0.5-(double)common;
// return dist;
//
// }
//
//
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// return RFMetric.getRFDistance(t1, t2);
//
// }
// }
| import treecmp.metric.Metric;
import treecmp.metric.RFMetric;
import treecmp.metric.MatchingSplitMetric; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class UsprHeuristicMSMetric extends UsprHeuristicBaseMetric {
@Override
protected Metric getMetric(){ | // Path: src/treecmp/metric/MatchingSplitMetric.java
// public class MatchingSplitMetric extends BaseMetric implements Metric {
// private MatchingSplitMetricO3 ms03;
// private MatchingSplitMetricOptRF msRF;
// private MatchingSpliMetricFree msFree;
//
// public MatchingSplitMetric(){
// super();
// ms03 = new MatchingSplitMetricO3();
// msRF = new MatchingSplitMetricOptRF();
// msFree = new MatchingSpliMetricFree();
// }
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// if (IOSettings.getIOSettings().isOptMsMcByRf())
// return msRF.getDistance(t1, t2);
//
// if (IOSettings.getIOSettings().isUseMsMcFreeLeafSet()) {
// return msFree.getDistance(t1, t2);
// }
//
// return ms03.getDistance(t1, t2);
// }
//
// @Override
// public AlignInfo getAlignment() {
// if (IOSettings.getIOSettings().isOptMsMcByRf()) {
// return null;
// }
//
// if (IOSettings.getIOSettings().isUseMsMcFreeLeafSet()) {
// return null;
// }
// return ms03.getAlignment();
// }
// }
//
// Path: src/treecmp/metric/RFMetric.java
// public class RFMetric extends BaseMetric implements Metric{
//
// public static double getRFDistance(Tree t1, Tree t2) {
//
// int n = t1.getExternalNodeCount();
// if (n <= 3)
// return 0;
//
// IdGroup idGroup = TreeUtils.getLeafIdGroup(t1);
// BitSet[] s_t1=SplitDist.getSplits(t1, idGroup);
// BitSet[] s_t2=SplitDist.getSplits(t2, idGroup);
// int N1=s_t1.length;
// int N2=s_t2.length;
// int hashSetSize=(4*(N1+1))/3;
//
// HashSet<BitSet> s_t1_hs=new HashSet<BitSet>(hashSetSize);
//
// int i;
// for(i=0;i<N1;i++){
// s_t1_hs.add(s_t1[i]);
// }
//
// int common=0;
// for(i=0;i<N2;i++){
// if (s_t1_hs.contains(s_t2[i])){
// common++;
// }
// }
//
// double dist=((double)N1+(double)N2)*0.5-(double)common;
// return dist;
//
// }
//
//
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// return RFMetric.getRFDistance(t1, t2);
//
// }
// }
// Path: src/treecmp/spr/UsprHeuristicMSMetric.java
import treecmp.metric.Metric;
import treecmp.metric.RFMetric;
import treecmp.metric.MatchingSplitMetric;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class UsprHeuristicMSMetric extends UsprHeuristicBaseMetric {
@Override
protected Metric getMetric(){ | return new MatchingSplitMetric(); |
TreeCmp/TreeCmp | src/treecmp/spr/SprHeuristicBaseMetric.java | // Path: src/treecmp/common/TreeCmpException.java
// public class TreeCmpException extends Exception {
//
// private String errMsg;
// //----------------------------------------------
// // Default constructor - initializes instance variable to unknown
// public TreeCmpException()
// {
// super(); // call superclass constructor
// errMsg = "unknown";
// }
//
// //-----------------------------------------------
// // Constructor receives some kind of message that is saved in an instance variable.
// public TreeCmpException(String errMsg)
// {
// super(errMsg); // call super class constructor
// this.errMsg = errMsg; // save message
// }
//
// //------------------------------------------------
// // public method, callable by exception catcher. It returns the error message.
// public String getError()
// {
// return errMsg;
// }
// }
| import java.util.logging.Level;
import java.util.logging.Logger;
import pal.io.OutputTarget;
import treecmp.common.TreeCmpException;
import treecmp.metric.*;
import pal.tree.Tree;
import pal.tree.TreeUtils; | int sprDist = 0;
Tree[] treeList;
Tree bestTree = null;
Tree tempTree = null;
double bestDist, tempDist;
Tree currentStepTree = t1;
double bestDist1 = Double.POSITIVE_INFINITY, bestDist2 = Double.POSITIVE_INFINITY;
do {
treeList = SprUtils.generateRSprNeighbours(currentStepTree);
bestDist = Double.POSITIVE_INFINITY;
tempDist = 0;
sprDist++;
for (int i = 0; i < treeList.length; i++) {
tempTree = treeList[i];
tempDist = m.getDistance(tempTree, t2);
if (tempDist < bestDist) {
bestDist = tempDist;
bestTree = tempTree;
}
}
currentStepTree = bestTree;
bestDist1 = bestDist2;
bestDist2 = bestDist;
if (bestDist1 <= bestDist2) {
return Double.POSITIVE_INFINITY;
}
} while (bestDist != 0);
dist = (double) sprDist; | // Path: src/treecmp/common/TreeCmpException.java
// public class TreeCmpException extends Exception {
//
// private String errMsg;
// //----------------------------------------------
// // Default constructor - initializes instance variable to unknown
// public TreeCmpException()
// {
// super(); // call superclass constructor
// errMsg = "unknown";
// }
//
// //-----------------------------------------------
// // Constructor receives some kind of message that is saved in an instance variable.
// public TreeCmpException(String errMsg)
// {
// super(errMsg); // call super class constructor
// this.errMsg = errMsg; // save message
// }
//
// //------------------------------------------------
// // public method, callable by exception catcher. It returns the error message.
// public String getError()
// {
// return errMsg;
// }
// }
// Path: src/treecmp/spr/SprHeuristicBaseMetric.java
import java.util.logging.Level;
import java.util.logging.Logger;
import pal.io.OutputTarget;
import treecmp.common.TreeCmpException;
import treecmp.metric.*;
import pal.tree.Tree;
import pal.tree.TreeUtils;
int sprDist = 0;
Tree[] treeList;
Tree bestTree = null;
Tree tempTree = null;
double bestDist, tempDist;
Tree currentStepTree = t1;
double bestDist1 = Double.POSITIVE_INFINITY, bestDist2 = Double.POSITIVE_INFINITY;
do {
treeList = SprUtils.generateRSprNeighbours(currentStepTree);
bestDist = Double.POSITIVE_INFINITY;
tempDist = 0;
sprDist++;
for (int i = 0; i < treeList.length; i++) {
tempTree = treeList[i];
tempDist = m.getDistance(tempTree, t2);
if (tempDist < bestDist) {
bestDist = tempDist;
bestTree = tempTree;
}
}
currentStepTree = bestTree;
bestDist1 = bestDist2;
bestDist2 = bestDist;
if (bestDist1 <= bestDist2) {
return Double.POSITIVE_INFINITY;
}
} while (bestDist != 0);
dist = (double) sprDist; | } catch (TreeCmpException ex) { |
TreeCmp/TreeCmp | src/treecmp/spr/UsprHeuristicBaseMetric.java | // Path: src/treecmp/common/TreeCmpException.java
// public class TreeCmpException extends Exception {
//
// private String errMsg;
// //----------------------------------------------
// // Default constructor - initializes instance variable to unknown
// public TreeCmpException()
// {
// super(); // call superclass constructor
// errMsg = "unknown";
// }
//
// //-----------------------------------------------
// // Constructor receives some kind of message that is saved in an instance variable.
// public TreeCmpException(String errMsg)
// {
// super(errMsg); // call super class constructor
// this.errMsg = errMsg; // save message
// }
//
// //------------------------------------------------
// // public method, callable by exception catcher. It returns the error message.
// public String getError()
// {
// return errMsg;
// }
// }
| import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import pal.io.InputSource;
import pal.tree.ReadTree;
import pal.tree.SimpleTree;
import pal.tree.TreeParseException;
import treecmp.common.TreeCmpException;
import treecmp.metric.*;
import pal.tree.Tree; | bestDist = Double.POSITIVE_INFINITY;
tempDist = 0;
sprDist++;
for (int i = 0; i < treeList.length; i++) {
tempTree = treeList[i];
tempDist = m.getDistance(tempTree, t2);
if (tempDist < bestDist) {
bestDist = tempDist;
bestTree = tempTree;
}
}
//todo:poprawić
// zapisuję do stringu i odczytuje bo inaczej powstają błędy
// w postaci wierzchołków wewnętrznych stopnia 1
{
String bestTreeString = bestTree.toString();
InputSource is = InputSource.openString(bestTreeString);
currentStepTree = new ReadTree(is);
is.close();
}
bestDist1 = bestDist2;
bestDist2 = bestDist;
if (bestDist1 <= bestDist2) {
return Double.POSITIVE_INFINITY;
}
} while (bestDist != 0);
dist = (double) sprDist; | // Path: src/treecmp/common/TreeCmpException.java
// public class TreeCmpException extends Exception {
//
// private String errMsg;
// //----------------------------------------------
// // Default constructor - initializes instance variable to unknown
// public TreeCmpException()
// {
// super(); // call superclass constructor
// errMsg = "unknown";
// }
//
// //-----------------------------------------------
// // Constructor receives some kind of message that is saved in an instance variable.
// public TreeCmpException(String errMsg)
// {
// super(errMsg); // call super class constructor
// this.errMsg = errMsg; // save message
// }
//
// //------------------------------------------------
// // public method, callable by exception catcher. It returns the error message.
// public String getError()
// {
// return errMsg;
// }
// }
// Path: src/treecmp/spr/UsprHeuristicBaseMetric.java
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import pal.io.InputSource;
import pal.tree.ReadTree;
import pal.tree.SimpleTree;
import pal.tree.TreeParseException;
import treecmp.common.TreeCmpException;
import treecmp.metric.*;
import pal.tree.Tree;
bestDist = Double.POSITIVE_INFINITY;
tempDist = 0;
sprDist++;
for (int i = 0; i < treeList.length; i++) {
tempTree = treeList[i];
tempDist = m.getDistance(tempTree, t2);
if (tempDist < bestDist) {
bestDist = tempDist;
bestTree = tempTree;
}
}
//todo:poprawić
// zapisuję do stringu i odczytuje bo inaczej powstają błędy
// w postaci wierzchołków wewnętrznych stopnia 1
{
String bestTreeString = bestTree.toString();
InputSource is = InputSource.openString(bestTreeString);
currentStepTree = new ReadTree(is);
is.close();
}
bestDist1 = bestDist2;
bestDist2 = bestDist;
if (bestDist1 <= bestDist2) {
return Double.POSITIVE_INFINITY;
}
} while (bestDist != 0);
dist = (double) sprDist; | } catch (TreeCmpException ex) { |
TreeCmp/TreeCmp | src/treecmp/spr/SprHeuristicTtRfcMetric.java | // Path: src/treecmp/metric/TripletMetric.java
// public class TripletMetric extends BaseMetric implements Metric {
// private TripletMetric2 tt2;
// public TripletMetric(){
// super();
// tt2 = new TripletMetric2();
// }
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// if (TreeCmpUtils.isBinary(t1, true) && TreeCmpUtils.isBinary(t2, true)) {
// return getDistForBinary(t1, t2);
// }
// //run distance for arbitrary tree in O(n^2) time
// return tt2.getDistance(t1, t2);
//
// }
//
// public double getDistForBinary(Tree t1, Tree t2) {
// IdGroup id1 = TreeUtils.getLeafIdGroup(t1);
// int[][] lcaMatrix1 = TreeCmpUtils.calcLcaMatrix(t1, null);
// int[][] lcaMatrix2 = TreeCmpUtils.calcLcaMatrix(t2, id1);
// int n = lcaMatrix1.length;
// long n_l = (long) n;
// long val_l;
// long commonT = 0;
//
// for (int i = 0; i < n; i++) {
// List<Integer> numList = getPatternNum(i, lcaMatrix1, lcaMatrix2);
// for (Integer val : numList) {
// val_l = (long) val;
// commonT += val_l * (val_l - 1) / 2;
// }
// }
//
// long dist = n_l * (n_l - 1) * (n_l - 2) / 6 - commonT;
// return (double) dist;
// }
//
// class Pattern {
//
// public int a;
// public int b;
//
// public Pattern(int a, int b) {
// this.a = a;
// this.b = b;
// }
//
// @Override
// public int hashCode() {
// return 31 * a + b;
//
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (obj instanceof Pattern) {
// Pattern test = (Pattern) obj;
// if (a == test.a && b == test.b) {
// return true;
// }
// }
// return false;
// }
// }
//
// public List<Integer> getPatternNum(int x, int[][] a, int[][] b) {
//
// int n = a.length;
// int mapSize = (4 * n) / 3;
//
// List<Integer> mList = new ArrayList<Integer>();
//
// Map<Pattern, Integer> patternMap = new HashMap<Pattern, Integer>(mapSize);
// for (int i = 0; i < n; i++) {
// if (i == x) {
// continue;
// }
// Pattern p = new Pattern(a[x][i], b[x][i]);
// Integer num = patternMap.get(p);
// if (num == null) {
// patternMap.put(p, new Integer(1));
// } else {
// patternMap.put(p, num.intValue() + 1);
// }
//
// }
// for (Integer val : patternMap.values()) {
// if (val >= 2) {
// mList.add(val);
// }
// }
// return mList;
// }
//
//
// }
| import treecmp.metric.TripletMetric;
import treecmp.metric.Metric; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class SprHeuristicTtRfcMetric extends SprHeuristicRfcBaseMetric{
@Override
protected Metric getMetric(){ | // Path: src/treecmp/metric/TripletMetric.java
// public class TripletMetric extends BaseMetric implements Metric {
// private TripletMetric2 tt2;
// public TripletMetric(){
// super();
// tt2 = new TripletMetric2();
// }
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// if (TreeCmpUtils.isBinary(t1, true) && TreeCmpUtils.isBinary(t2, true)) {
// return getDistForBinary(t1, t2);
// }
// //run distance for arbitrary tree in O(n^2) time
// return tt2.getDistance(t1, t2);
//
// }
//
// public double getDistForBinary(Tree t1, Tree t2) {
// IdGroup id1 = TreeUtils.getLeafIdGroup(t1);
// int[][] lcaMatrix1 = TreeCmpUtils.calcLcaMatrix(t1, null);
// int[][] lcaMatrix2 = TreeCmpUtils.calcLcaMatrix(t2, id1);
// int n = lcaMatrix1.length;
// long n_l = (long) n;
// long val_l;
// long commonT = 0;
//
// for (int i = 0; i < n; i++) {
// List<Integer> numList = getPatternNum(i, lcaMatrix1, lcaMatrix2);
// for (Integer val : numList) {
// val_l = (long) val;
// commonT += val_l * (val_l - 1) / 2;
// }
// }
//
// long dist = n_l * (n_l - 1) * (n_l - 2) / 6 - commonT;
// return (double) dist;
// }
//
// class Pattern {
//
// public int a;
// public int b;
//
// public Pattern(int a, int b) {
// this.a = a;
// this.b = b;
// }
//
// @Override
// public int hashCode() {
// return 31 * a + b;
//
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (obj instanceof Pattern) {
// Pattern test = (Pattern) obj;
// if (a == test.a && b == test.b) {
// return true;
// }
// }
// return false;
// }
// }
//
// public List<Integer> getPatternNum(int x, int[][] a, int[][] b) {
//
// int n = a.length;
// int mapSize = (4 * n) / 3;
//
// List<Integer> mList = new ArrayList<Integer>();
//
// Map<Pattern, Integer> patternMap = new HashMap<Pattern, Integer>(mapSize);
// for (int i = 0; i < n; i++) {
// if (i == x) {
// continue;
// }
// Pattern p = new Pattern(a[x][i], b[x][i]);
// Integer num = patternMap.get(p);
// if (num == null) {
// patternMap.put(p, new Integer(1));
// } else {
// patternMap.put(p, num.intValue() + 1);
// }
//
// }
// for (Integer val : patternMap.values()) {
// if (val >= 2) {
// mList.add(val);
// }
// }
// return mList;
// }
//
//
// }
// Path: src/treecmp/spr/SprHeuristicTtRfcMetric.java
import treecmp.metric.TripletMetric;
import treecmp.metric.Metric;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class SprHeuristicTtRfcMetric extends SprHeuristicRfcBaseMetric{
@Override
protected Metric getMetric(){ | return new TripletMetric(); |
TreeCmp/TreeCmp | src/treecmp/metric/weighted/GeoMetricWrapper.java | // Path: src/treecmp/common/NodeUtilsExt.java
// public class NodeUtilsExt extends NodeUtils {
//
// public static int printNH(PrintWriter out, Node node,
// boolean printLengths, boolean printInternalLabels, int column, int fractionDigits) {
//
// if (!node.isLeaf()) {
// out.print("(");
// column++;
//
// for (int i = 0; i < node.getChildCount(); i++) {
// if (i != 0) {
// out.print(",");
// column++;
// }
//
// column = printNH(out, node.getChild(i), printLengths, printInternalLabels, column, fractionDigits);
// }
//
// out.print(")");
// column++;
// }
//
// if (!node.isRoot()) {
// if (node.isLeaf() || printInternalLabels) {
//
// String id = node.getIdentifier().toString();
// out.print(id);
// column += id.length();
// }
//
// if (printLengths) {
// out.print(":");
// column++;
//
// column += FormattedOutput.getInstance().displayDecimal(out, node.getBranchLength(), fractionDigits);
// }
// }
// return column;
// }
//
//
// public static String treeToSimpleString(Tree tree, boolean printLengths) {
// return treeToSimpleString(tree.getRoot(), printLengths);
// }
//
// public static String treeToSimpleString(Node node, boolean printLengths) {
// OutputTarget out = OutputTarget.openString();
// NodeUtilsExt.printNH(out, node, printLengths, false, 0, 6);
// String treeNewick = out.getString();
// out.close();
// return treeNewick;
// }
//
//
// public static void getSplitExternal(IdGroup idGroup, Node externalNode, boolean[] split) {
// // make sure split is reset
// for (int i = 0; i < split.length; i++) {
// split[i] = false;
// }
//
// if (externalNode.isLeaf()) {
// String name1 = externalNode.getIdentifier().getName();
// int index = idGroup.whichIdNumber(name1);
//
// if (index < 0) {
// throw new IllegalArgumentException("INCOMPATIBLE IDENTIFIER (" + name1 + ")");
// }
// split[index] = true;
// } else{
// throw new IllegalArgumentException("NOT EXTERNAL NODE CHOSEN: " + externalNode);
// }
//
// // standardize split (i.e. first index is alway true)
// if (split[0] == false) {
// for (int i = 0; i < split.length; i++) {
// if (split[i] == false) {
// split[i] = true;
// } else {
// split[i] = false;
// }
// }
// }
// }
// }
| import distanceAlg1.Geodesic;
import distanceAlg1.PhyloTree;
import pal.tree.*;
import polyAlg.PolyMain;
import treecmp.common.NodeUtilsExt;
import java.io.IOException; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.metric.weighted;
/**
*
* @author Damian
*/
/**
*
* @author Damian
*/
public class GeoMetricWrapper {
/**
*
* @param t1
* @param t2
* @param rooted
* @param logFileName - can be null
* @return
*/
public double getDistance(Tree t1, Tree t2, boolean rooted, String logFileName) { | // Path: src/treecmp/common/NodeUtilsExt.java
// public class NodeUtilsExt extends NodeUtils {
//
// public static int printNH(PrintWriter out, Node node,
// boolean printLengths, boolean printInternalLabels, int column, int fractionDigits) {
//
// if (!node.isLeaf()) {
// out.print("(");
// column++;
//
// for (int i = 0; i < node.getChildCount(); i++) {
// if (i != 0) {
// out.print(",");
// column++;
// }
//
// column = printNH(out, node.getChild(i), printLengths, printInternalLabels, column, fractionDigits);
// }
//
// out.print(")");
// column++;
// }
//
// if (!node.isRoot()) {
// if (node.isLeaf() || printInternalLabels) {
//
// String id = node.getIdentifier().toString();
// out.print(id);
// column += id.length();
// }
//
// if (printLengths) {
// out.print(":");
// column++;
//
// column += FormattedOutput.getInstance().displayDecimal(out, node.getBranchLength(), fractionDigits);
// }
// }
// return column;
// }
//
//
// public static String treeToSimpleString(Tree tree, boolean printLengths) {
// return treeToSimpleString(tree.getRoot(), printLengths);
// }
//
// public static String treeToSimpleString(Node node, boolean printLengths) {
// OutputTarget out = OutputTarget.openString();
// NodeUtilsExt.printNH(out, node, printLengths, false, 0, 6);
// String treeNewick = out.getString();
// out.close();
// return treeNewick;
// }
//
//
// public static void getSplitExternal(IdGroup idGroup, Node externalNode, boolean[] split) {
// // make sure split is reset
// for (int i = 0; i < split.length; i++) {
// split[i] = false;
// }
//
// if (externalNode.isLeaf()) {
// String name1 = externalNode.getIdentifier().getName();
// int index = idGroup.whichIdNumber(name1);
//
// if (index < 0) {
// throw new IllegalArgumentException("INCOMPATIBLE IDENTIFIER (" + name1 + ")");
// }
// split[index] = true;
// } else{
// throw new IllegalArgumentException("NOT EXTERNAL NODE CHOSEN: " + externalNode);
// }
//
// // standardize split (i.e. first index is alway true)
// if (split[0] == false) {
// for (int i = 0; i < split.length; i++) {
// if (split[i] == false) {
// split[i] = true;
// } else {
// split[i] = false;
// }
// }
// }
// }
// }
// Path: src/treecmp/metric/weighted/GeoMetricWrapper.java
import distanceAlg1.Geodesic;
import distanceAlg1.PhyloTree;
import pal.tree.*;
import polyAlg.PolyMain;
import treecmp.common.NodeUtilsExt;
import java.io.IOException;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.metric.weighted;
/**
*
* @author Damian
*/
/**
*
* @author Damian
*/
public class GeoMetricWrapper {
/**
*
* @param t1
* @param t2
* @param rooted
* @param logFileName - can be null
* @return
*/
public double getDistance(Tree t1, Tree t2, boolean rooted, String logFileName) { | String tree1Newick = NodeUtilsExt.treeToSimpleString(t1, true); |
TreeCmp/TreeCmp | src/treecmp/spr/SprHeuristicMastMetric.java | // Path: src/treecmp/metric/RMASTMetric.java
// public class RMASTMetric extends BaseMetric implements Metric {
//
// @Override
// public boolean isRooted() {
// return true;
// }
//
// @Override
// public double getDistance(Tree t1, Tree t2, int... indexes) {
// return Math.max(t1.getExternalNodeCount(), t2.getExternalNodeCount()) - crmast(t1, t2).getRMAST();
// }
//
// public static CRMAST crmast(Tree t1, Tree t2) {
// final int t1Leafs = t1.getExternalNodeCount();
// final int t2Leafs = t2.getExternalNodeCount();
//
// //dynamic programming array: first dimension are nodes from t1, second from t2
// //nodes are ordered according to their numbers: leafs first then internal nodes
// final CRMAST mast = new CRMAST(t1, t2);
//
// //fill values for pairs where at least one of nodes is a leaf
// for (int i=0; i<t1Leafs; i++) {
// final Node leaf1 = t1.getExternalNode(i);
// for (int j=0; j<t2Leafs; j++) {
// final Node leaf2 = t2.getExternalNode(j);
//
// if (leaf1.getIdentifier().equals(leaf2.getIdentifier())) {
// mast.set(i, j, 1);
//
// Node v1 = leaf1;
// do {
// v1 = v1.getParent();
// mast.set(v1, leaf2, 1);
// } while (!v1.isRoot());
//
// Node v2 = leaf2;
// do {
// v2 = v2.getParent();
// mast.set(leaf1, v2, 1);
// } while (!v2.isRoot());
// }
// }
// }
//
// final int[] internalNodeOrder1 = getInternalNodeOrder(t1);
// final int[] internalNodeOrder2 = getInternalNodeOrder(t2);
// //fill values for pairs of internal nodes
// for (int i=0; i<internalNodeOrder1.length; i++) {
// final Node v1 = t1.getInternalNode(internalNodeOrder1[i]);
// for (int j=0; j<internalNodeOrder2.length; j++) {
// final Node v2 = t2.getInternalNode(internalNodeOrder2[j]);
// mast.set(v1, v2, Math.max(diag(v1, t1, v2, t2, mast), match(v1, t1, v2, t2, mast)));
// }
// }
//
// return mast;
// }
//
// private static int diag(Node v1, Tree t1, Node v2, Tree t2, CRMAST mast) {
// int result = 0;
// for (int i=0; i<v2.getChildCount(); i++) {
// final Node child2 = v2.getChild(i);
// result = Math.max(result, mast.getRMAST(v1, child2));
// }
// for (int i=0; i<v1.getChildCount(); i++) {
// final Node child1 = v1.getChild(i);
// result = Math.max(result, mast.getRMAST(child1, v2));
// }
// return result;
// }
//
// //TODO verify proper complexity of match. For two trees all matchings should take O(n^2).
// private static int match(Node v1, Tree t1, Node v2, Tree t2, CRMAST mast) {
// final int v1Children = v1.getChildCount();
// final int v2Children = v2.getChildCount();
// final int size = Math.max(v1Children, v2Children);
// final int[][] w = new int[size][];
// for (int i=0; i<size; i++) {
// w[i] = new int[size];
// }
//
// for (int i=0; i<v1Children; i++) {
// final Node child1 = v1.getChild(i);
// for (int j=0; j<v2Children; j++) {
// final Node child2 = v2.getChild(j);
// w[i][j] = -mast.getRMAST(child1, child2);
// }
// }
//
// final int[] rowSol = new int[size];
// final int[] colSol = new int[size];
// final int[] u = new int[size];
// final int[] v = new int[size];
// return -LapSolver.lap(size, w, rowSol, colSol, u, v);
// }
//
// private static int[] getInternalNodeOrder(Tree t) {
// final int[] order = new int[t.getInternalNodeCount()];
// int qFront = order.length;
// int qEnd = order.length;
//
// //visit internal nodes in bfs order starting from root
// //and grow the order queue from the back
// order[--qEnd] = t.getRoot().getNumber();
// while (qFront > 0) {
// final Node v = t.getInternalNode(order[--qFront]);
// for (int i=0; i<v.getChildCount(); i++) {
// final Node child = v.getChild(i);
// if (!child.isLeaf()) {
// order[--qEnd] = child.getNumber();
// }
// }
// }
// return order;
// }
//
// }
| import treecmp.metric.RMASTMetric;
import treecmp.metric.Metric; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class SprHeuristicMastMetric extends SprHeuristicBaseMetric{
@Override
protected Metric getMetric(){ | // Path: src/treecmp/metric/RMASTMetric.java
// public class RMASTMetric extends BaseMetric implements Metric {
//
// @Override
// public boolean isRooted() {
// return true;
// }
//
// @Override
// public double getDistance(Tree t1, Tree t2, int... indexes) {
// return Math.max(t1.getExternalNodeCount(), t2.getExternalNodeCount()) - crmast(t1, t2).getRMAST();
// }
//
// public static CRMAST crmast(Tree t1, Tree t2) {
// final int t1Leafs = t1.getExternalNodeCount();
// final int t2Leafs = t2.getExternalNodeCount();
//
// //dynamic programming array: first dimension are nodes from t1, second from t2
// //nodes are ordered according to their numbers: leafs first then internal nodes
// final CRMAST mast = new CRMAST(t1, t2);
//
// //fill values for pairs where at least one of nodes is a leaf
// for (int i=0; i<t1Leafs; i++) {
// final Node leaf1 = t1.getExternalNode(i);
// for (int j=0; j<t2Leafs; j++) {
// final Node leaf2 = t2.getExternalNode(j);
//
// if (leaf1.getIdentifier().equals(leaf2.getIdentifier())) {
// mast.set(i, j, 1);
//
// Node v1 = leaf1;
// do {
// v1 = v1.getParent();
// mast.set(v1, leaf2, 1);
// } while (!v1.isRoot());
//
// Node v2 = leaf2;
// do {
// v2 = v2.getParent();
// mast.set(leaf1, v2, 1);
// } while (!v2.isRoot());
// }
// }
// }
//
// final int[] internalNodeOrder1 = getInternalNodeOrder(t1);
// final int[] internalNodeOrder2 = getInternalNodeOrder(t2);
// //fill values for pairs of internal nodes
// for (int i=0; i<internalNodeOrder1.length; i++) {
// final Node v1 = t1.getInternalNode(internalNodeOrder1[i]);
// for (int j=0; j<internalNodeOrder2.length; j++) {
// final Node v2 = t2.getInternalNode(internalNodeOrder2[j]);
// mast.set(v1, v2, Math.max(diag(v1, t1, v2, t2, mast), match(v1, t1, v2, t2, mast)));
// }
// }
//
// return mast;
// }
//
// private static int diag(Node v1, Tree t1, Node v2, Tree t2, CRMAST mast) {
// int result = 0;
// for (int i=0; i<v2.getChildCount(); i++) {
// final Node child2 = v2.getChild(i);
// result = Math.max(result, mast.getRMAST(v1, child2));
// }
// for (int i=0; i<v1.getChildCount(); i++) {
// final Node child1 = v1.getChild(i);
// result = Math.max(result, mast.getRMAST(child1, v2));
// }
// return result;
// }
//
// //TODO verify proper complexity of match. For two trees all matchings should take O(n^2).
// private static int match(Node v1, Tree t1, Node v2, Tree t2, CRMAST mast) {
// final int v1Children = v1.getChildCount();
// final int v2Children = v2.getChildCount();
// final int size = Math.max(v1Children, v2Children);
// final int[][] w = new int[size][];
// for (int i=0; i<size; i++) {
// w[i] = new int[size];
// }
//
// for (int i=0; i<v1Children; i++) {
// final Node child1 = v1.getChild(i);
// for (int j=0; j<v2Children; j++) {
// final Node child2 = v2.getChild(j);
// w[i][j] = -mast.getRMAST(child1, child2);
// }
// }
//
// final int[] rowSol = new int[size];
// final int[] colSol = new int[size];
// final int[] u = new int[size];
// final int[] v = new int[size];
// return -LapSolver.lap(size, w, rowSol, colSol, u, v);
// }
//
// private static int[] getInternalNodeOrder(Tree t) {
// final int[] order = new int[t.getInternalNodeCount()];
// int qFront = order.length;
// int qEnd = order.length;
//
// //visit internal nodes in bfs order starting from root
// //and grow the order queue from the back
// order[--qEnd] = t.getRoot().getNumber();
// while (qFront > 0) {
// final Node v = t.getInternalNode(order[--qFront]);
// for (int i=0; i<v.getChildCount(); i++) {
// final Node child = v.getChild(i);
// if (!child.isLeaf()) {
// order[--qEnd] = child.getNumber();
// }
// }
// }
// return order;
// }
//
// }
// Path: src/treecmp/spr/SprHeuristicMastMetric.java
import treecmp.metric.RMASTMetric;
import treecmp.metric.Metric;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class SprHeuristicMastMetric extends SprHeuristicBaseMetric{
@Override
protected Metric getMetric(){ | return new RMASTMetric(); |
TreeCmp/TreeCmp | src/treecmp/spr/SprHeuristicCophMetric.java | // Path: src/treecmp/metric/CopheneticL2Metric.java
// public class CopheneticL2Metric extends BaseMetric implements Metric {
//
// @Override
// public boolean isRooted() {
// return true;
// }
//
// public CopheneticL2Metric() {
// super();
// }
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// int extT1Num = t1.getExternalNodeCount();
// int extT2Num = t2.getExternalNodeCount();
// if (extT1Num <= 2) {
// return 0.0;
// }
// IdGroup id1 = TreeUtils.getLeafIdGroup(t1);
// int[][] lcaMatrix1 = TreeCmpUtils.calcLcaMatrix(t1, null);
// int[][] lcaMatrix2 = TreeCmpUtils.calcLcaMatrix(t2, id1);
//
// int intT1Num = t1.getInternalNodeCount();
// int intT2Num = t2.getInternalNodeCount();
//
// Node[] preOrderT1 = TreeCmpUtils.getNodesInPreOrder(t1);
// Node[] preOrderT2 = TreeCmpUtils.getNodesInPreOrder(t2);
//
// short[] intDepthT1 = new short[intT1Num];
// short[] intDepthT2 = new short[intT2Num];
//
// short[] extDepthT1 = new short[extT1Num];
// short[] extDepthT2 = new short[extT2Num];
//
// TreeCmpUtils.calcNodeDepth(t1, preOrderT1, extDepthT1, intDepthT1, null);
// TreeCmpUtils.calcNodeDepth(t2, preOrderT2, extDepthT2, intDepthT2, id1);
//
// double diff, dist = 0.0;
// int xNodeNum, yNodeNum, xyNodeNumT1, xyNodeNumT2;
// Node xNode, yNode;
// for (int i = 0; i < extT1Num; i++) {
// xNode = t1.getExternalNode(i);
// xNodeNum = xNode.getNumber();
// for (int j = i + 1; j < extT1Num; j++) {
// yNode = t1.getExternalNode(j);
// yNodeNum = yNode.getNumber();
// xyNodeNumT1 = lcaMatrix1[xNodeNum][yNodeNum];
// xyNodeNumT2 = lcaMatrix2[xNodeNum][yNodeNum];
//
// diff = intDepthT1[xyNodeNumT1] - intDepthT2[xyNodeNumT2];
// dist += diff * diff;
// }
// }
// for (int i = 0; i < extT1Num; i++) {
// xNode = t1.getExternalNode(i);
// xNodeNum = xNode.getNumber();
// diff = extDepthT1[xNodeNum] - extDepthT2[xNodeNum];
// dist += diff * diff;
// }
//
// return Math.sqrt(dist);
// }
// }
| import treecmp.metric.Metric;
import treecmp.metric.CopheneticL2Metric; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class SprHeuristicCophMetric extends SprHeuristicBaseMetric{
@Override
protected Metric getMetric(){ | // Path: src/treecmp/metric/CopheneticL2Metric.java
// public class CopheneticL2Metric extends BaseMetric implements Metric {
//
// @Override
// public boolean isRooted() {
// return true;
// }
//
// public CopheneticL2Metric() {
// super();
// }
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// int extT1Num = t1.getExternalNodeCount();
// int extT2Num = t2.getExternalNodeCount();
// if (extT1Num <= 2) {
// return 0.0;
// }
// IdGroup id1 = TreeUtils.getLeafIdGroup(t1);
// int[][] lcaMatrix1 = TreeCmpUtils.calcLcaMatrix(t1, null);
// int[][] lcaMatrix2 = TreeCmpUtils.calcLcaMatrix(t2, id1);
//
// int intT1Num = t1.getInternalNodeCount();
// int intT2Num = t2.getInternalNodeCount();
//
// Node[] preOrderT1 = TreeCmpUtils.getNodesInPreOrder(t1);
// Node[] preOrderT2 = TreeCmpUtils.getNodesInPreOrder(t2);
//
// short[] intDepthT1 = new short[intT1Num];
// short[] intDepthT2 = new short[intT2Num];
//
// short[] extDepthT1 = new short[extT1Num];
// short[] extDepthT2 = new short[extT2Num];
//
// TreeCmpUtils.calcNodeDepth(t1, preOrderT1, extDepthT1, intDepthT1, null);
// TreeCmpUtils.calcNodeDepth(t2, preOrderT2, extDepthT2, intDepthT2, id1);
//
// double diff, dist = 0.0;
// int xNodeNum, yNodeNum, xyNodeNumT1, xyNodeNumT2;
// Node xNode, yNode;
// for (int i = 0; i < extT1Num; i++) {
// xNode = t1.getExternalNode(i);
// xNodeNum = xNode.getNumber();
// for (int j = i + 1; j < extT1Num; j++) {
// yNode = t1.getExternalNode(j);
// yNodeNum = yNode.getNumber();
// xyNodeNumT1 = lcaMatrix1[xNodeNum][yNodeNum];
// xyNodeNumT2 = lcaMatrix2[xNodeNum][yNodeNum];
//
// diff = intDepthT1[xyNodeNumT1] - intDepthT2[xyNodeNumT2];
// dist += diff * diff;
// }
// }
// for (int i = 0; i < extT1Num; i++) {
// xNode = t1.getExternalNode(i);
// xNodeNum = xNode.getNumber();
// diff = extDepthT1[xNodeNum] - extDepthT2[xNodeNum];
// dist += diff * diff;
// }
//
// return Math.sqrt(dist);
// }
// }
// Path: src/treecmp/spr/SprHeuristicCophMetric.java
import treecmp.metric.Metric;
import treecmp.metric.CopheneticL2Metric;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class SprHeuristicCophMetric extends SprHeuristicBaseMetric{
@Override
protected Metric getMetric(){ | return new CopheneticL2Metric(); |
TreeCmp/TreeCmp | src/treecmp/spr/UsprHeuristicPDMetric.java | // Path: src/treecmp/metric/NodalL2Metric.java
// public class NodalL2Metric extends BaseMetric implements Metric {
//
// //This seems to be faster than old implementation
// public double getDistance(Tree t1, Tree t2, int... indexes) {
// double dist, diff;
//
// IdGroup id1 = TreeUtils.getLeafIdGroup(t1);
// int[][] nsMatrix1 = TreeCmpUtils.calcNodalSplittedMatrix(t1, null);
// int[][] nsMatrix2 = TreeCmpUtils.calcNodalSplittedMatrix(t2, id1);
//
// dist = 0.0;
// for (int i = 0; i < id1.getIdCount(); i++) {
// for (int j = i + 1; j < id1.getIdCount(); j++) {
// diff = nsMatrix1[i][j] + nsMatrix1[j][i] - nsMatrix2[i][j] - nsMatrix2[j][i];
// dist += diff * diff;
// }
// }
// return Math.sqrt(dist);
// }
//
// public double getDistanceOld(Tree t1, Tree t2) {
// double dist, diff;
//
//
// IdGroup id1 = TreeUtils.getLeafIdGroup(t1);
// TreeDistanceMatrix tr1 = new TreeDistanceMatrix(t1, true, 0);
// TreeDistanceMatrix tr2 = new TreeDistanceMatrix(t2, id1, true, 0);
//
// dist = 0.0;
// for (int i = 0; i < id1.getIdCount(); i++) {
// for (int j = i + 1; j < id1.getIdCount(); j++) {
// diff = tr1.getDistance(i, j) - tr2.getDistance(i, j);
// dist += diff * diff;
// }
// }
// return Math.sqrt(dist);
// }
// }
//
// Path: src/treecmp/metric/RFMetric.java
// public class RFMetric extends BaseMetric implements Metric{
//
// public static double getRFDistance(Tree t1, Tree t2) {
//
// int n = t1.getExternalNodeCount();
// if (n <= 3)
// return 0;
//
// IdGroup idGroup = TreeUtils.getLeafIdGroup(t1);
// BitSet[] s_t1=SplitDist.getSplits(t1, idGroup);
// BitSet[] s_t2=SplitDist.getSplits(t2, idGroup);
// int N1=s_t1.length;
// int N2=s_t2.length;
// int hashSetSize=(4*(N1+1))/3;
//
// HashSet<BitSet> s_t1_hs=new HashSet<BitSet>(hashSetSize);
//
// int i;
// for(i=0;i<N1;i++){
// s_t1_hs.add(s_t1[i]);
// }
//
// int common=0;
// for(i=0;i<N2;i++){
// if (s_t1_hs.contains(s_t2[i])){
// common++;
// }
// }
//
// double dist=((double)N1+(double)N2)*0.5-(double)common;
// return dist;
//
// }
//
//
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// return RFMetric.getRFDistance(t1, t2);
//
// }
// }
| import treecmp.metric.NodalL2Metric;
import treecmp.metric.RFMetric;
import treecmp.metric.Metric; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class UsprHeuristicPDMetric extends UsprHeuristicBaseMetric {
@Override | // Path: src/treecmp/metric/NodalL2Metric.java
// public class NodalL2Metric extends BaseMetric implements Metric {
//
// //This seems to be faster than old implementation
// public double getDistance(Tree t1, Tree t2, int... indexes) {
// double dist, diff;
//
// IdGroup id1 = TreeUtils.getLeafIdGroup(t1);
// int[][] nsMatrix1 = TreeCmpUtils.calcNodalSplittedMatrix(t1, null);
// int[][] nsMatrix2 = TreeCmpUtils.calcNodalSplittedMatrix(t2, id1);
//
// dist = 0.0;
// for (int i = 0; i < id1.getIdCount(); i++) {
// for (int j = i + 1; j < id1.getIdCount(); j++) {
// diff = nsMatrix1[i][j] + nsMatrix1[j][i] - nsMatrix2[i][j] - nsMatrix2[j][i];
// dist += diff * diff;
// }
// }
// return Math.sqrt(dist);
// }
//
// public double getDistanceOld(Tree t1, Tree t2) {
// double dist, diff;
//
//
// IdGroup id1 = TreeUtils.getLeafIdGroup(t1);
// TreeDistanceMatrix tr1 = new TreeDistanceMatrix(t1, true, 0);
// TreeDistanceMatrix tr2 = new TreeDistanceMatrix(t2, id1, true, 0);
//
// dist = 0.0;
// for (int i = 0; i < id1.getIdCount(); i++) {
// for (int j = i + 1; j < id1.getIdCount(); j++) {
// diff = tr1.getDistance(i, j) - tr2.getDistance(i, j);
// dist += diff * diff;
// }
// }
// return Math.sqrt(dist);
// }
// }
//
// Path: src/treecmp/metric/RFMetric.java
// public class RFMetric extends BaseMetric implements Metric{
//
// public static double getRFDistance(Tree t1, Tree t2) {
//
// int n = t1.getExternalNodeCount();
// if (n <= 3)
// return 0;
//
// IdGroup idGroup = TreeUtils.getLeafIdGroup(t1);
// BitSet[] s_t1=SplitDist.getSplits(t1, idGroup);
// BitSet[] s_t2=SplitDist.getSplits(t2, idGroup);
// int N1=s_t1.length;
// int N2=s_t2.length;
// int hashSetSize=(4*(N1+1))/3;
//
// HashSet<BitSet> s_t1_hs=new HashSet<BitSet>(hashSetSize);
//
// int i;
// for(i=0;i<N1;i++){
// s_t1_hs.add(s_t1[i]);
// }
//
// int common=0;
// for(i=0;i<N2;i++){
// if (s_t1_hs.contains(s_t2[i])){
// common++;
// }
// }
//
// double dist=((double)N1+(double)N2)*0.5-(double)common;
// return dist;
//
// }
//
//
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// return RFMetric.getRFDistance(t1, t2);
//
// }
// }
// Path: src/treecmp/spr/UsprHeuristicPDMetric.java
import treecmp.metric.NodalL2Metric;
import treecmp.metric.RFMetric;
import treecmp.metric.Metric;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class UsprHeuristicPDMetric extends UsprHeuristicBaseMetric {
@Override | protected Metric getMetric() { return new NodalL2Metric(); } |
TreeCmp/TreeCmp | src/treecmp/metric/RFClusterMetric.java | // Path: src/treecmp/common/ClusterDist.java
// public class ClusterDist {
//
// public ClusterDist() {
// }
//
// public static int clusterXor(boolean[] clade_t1, boolean[] clade_t2)
// {
// int n=clade_t1.length;
// int neq=0;
//
// for(int i=0;i<n;i++) {
// if(clade_t1[i]!=clade_t2[i]) neq++;
// }
//
// return neq;
// }
//
// public static BitSet[] RootedTree2BitSetArray(Tree t, IdGroup idGroup) {
// int N = t.getInternalNodeCount();
// int n = t.getExternalNodeCount();
// Node node;
// int j = 0;
// BitSet[] bsA = new BitSet[N - 1];
//
// for (int i = 0; i < N; i++) {
// node = t.getInternalNode(i);
// if (node.isRoot()) {
// continue;
// }
// bsA[j] = new BitSet(n);
// markRootedTreeNode(idGroup, node, bsA[j]);
// j++;
// }
//
// return bsA;
// }
//
// public static BitSet[] UnuootedTree2BitSetArray(Tree t, IdGroup idGroup) {
// int N = t.getInternalNodeCount();
// int n = t.getExternalNodeCount();
// Node node;
// int j = 0;
// BitSet[] bsA = new BitSet[N];
//
// for (int i = 0; i < N; i++) {
// node = t.getInternalNode(i);
// bsA[j] = new BitSet(n);
// markUnrootedTreeNode(idGroup, node, bsA[j]);
// j++;
// }
//
// // Arrays.sort(bsA, (BitSet lhs, BitSet rhs) -> compareBitSets(lhs, rhs));
// Arrays.sort(bsA, new Comparator<BitSet>() {
// @Override
// public int compare(BitSet lhs, BitSet rhs) {
// return compareBitSets(lhs, rhs);
// }
// });
// return bsA;
// }
//
// private static int compareBitSets(BitSet lhs, BitSet rhs) {
// if (lhs.equals(rhs)) return 0;
// if (lhs.cardinality() != rhs.cardinality()) {
// return lhs.cardinality() > rhs.cardinality() ? 1 : - 1;
// }
// else {
// return lhs.nextSetBit(0) > rhs.nextSetBit(0) ? 1 : - 1;
// }
// }
//
// private static void swap(BitSet lhs, BitSet rhs) {
// lhs.xor(rhs);
// rhs.xor(lhs);
// lhs.xor(rhs);
// }
//
// static void markRootedTreeNode(IdGroup idGroup, Node node, BitSet cluster) {
// if (node.isLeaf()) {
// String name = node.getIdentifier().getName();
// int index = idGroup.whichIdNumber(name);
//
// if (index < 0) {
// throw new IllegalArgumentException("INCOMPATIBLE IDENTIFIER (" + name + ")");
// }
// cluster.set(index);
// } else {
// for (int i = 0; i < node.getChildCount(); i++) {
// markRootedTreeNode(idGroup, node.getChild(i), cluster);
// }
// }
// }
//
// private static void markUnrootedTreeNode(IdGroup idGroup, Node node, BitSet cluster) {
// BitSet[] subTrees = new BitSet[3];
// for (int i = 0; i < 3; i++) subTrees[i] = new BitSet();
// markRootedTreeNode(idGroup, node.getChild(0), subTrees[0]);
// markRootedTreeNode(idGroup, node.getChild(1), subTrees[1]);
// subTrees[2].set(0, idGroup.getIdCount(), true);
// subTrees[2].andNot(subTrees[0]);
// subTrees[2].andNot(subTrees[1]);
// //Arrays.sort(subTrees, (BitSet lhs, BitSet rhs) -> compareBitSets(lhs, rhs));
// Arrays.sort(subTrees, new Comparator<BitSet>() {
// @Override
// public int compare(BitSet lhs, BitSet rhs) {
// return compareBitSets(lhs, rhs);
// }
// });
// cluster.or(subTrees[0]);
// cluster.or(subTrees[1]);
// }
//
// public static int getDistXorBit(BitSet cluster1, BitSet cluster2) {
//
// BitSet temp = (BitSet) cluster1.clone();
// temp.xor(cluster2);
// int d = temp.cardinality();
// return d;
// }
// public static int getAndBit(BitSet cluster1, BitSet cluster2) {
//
// BitSet temp = (BitSet) cluster1.clone();
// temp.and(cluster2);
// int d = temp.cardinality();
// return d;
// }
//
// public static int getDistToOAsMinBit(BitSet cluster) {
//
// int t = cluster.cardinality();
// return t;
//
// }
// }
| import treecmp.common.ClusterDist;
import java.util.BitSet;
import java.util.HashSet;
import pal.misc.IdGroup;
import pal.tree.*; | /** This file is part of TreeCmp, a tool for comparing phylogenetic trees
using the Matching Split distance and other metrics.
Copyright (C) 2011, Damian Bogdanowicz
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package treecmp.metric;
public class RFClusterMetric extends BaseMetric implements Metric{
public static double getRFClusterMetric(Tree t1, Tree t2) {
IdGroup idGroup = TreeUtils.getLeafIdGroup(t1);
| // Path: src/treecmp/common/ClusterDist.java
// public class ClusterDist {
//
// public ClusterDist() {
// }
//
// public static int clusterXor(boolean[] clade_t1, boolean[] clade_t2)
// {
// int n=clade_t1.length;
// int neq=0;
//
// for(int i=0;i<n;i++) {
// if(clade_t1[i]!=clade_t2[i]) neq++;
// }
//
// return neq;
// }
//
// public static BitSet[] RootedTree2BitSetArray(Tree t, IdGroup idGroup) {
// int N = t.getInternalNodeCount();
// int n = t.getExternalNodeCount();
// Node node;
// int j = 0;
// BitSet[] bsA = new BitSet[N - 1];
//
// for (int i = 0; i < N; i++) {
// node = t.getInternalNode(i);
// if (node.isRoot()) {
// continue;
// }
// bsA[j] = new BitSet(n);
// markRootedTreeNode(idGroup, node, bsA[j]);
// j++;
// }
//
// return bsA;
// }
//
// public static BitSet[] UnuootedTree2BitSetArray(Tree t, IdGroup idGroup) {
// int N = t.getInternalNodeCount();
// int n = t.getExternalNodeCount();
// Node node;
// int j = 0;
// BitSet[] bsA = new BitSet[N];
//
// for (int i = 0; i < N; i++) {
// node = t.getInternalNode(i);
// bsA[j] = new BitSet(n);
// markUnrootedTreeNode(idGroup, node, bsA[j]);
// j++;
// }
//
// // Arrays.sort(bsA, (BitSet lhs, BitSet rhs) -> compareBitSets(lhs, rhs));
// Arrays.sort(bsA, new Comparator<BitSet>() {
// @Override
// public int compare(BitSet lhs, BitSet rhs) {
// return compareBitSets(lhs, rhs);
// }
// });
// return bsA;
// }
//
// private static int compareBitSets(BitSet lhs, BitSet rhs) {
// if (lhs.equals(rhs)) return 0;
// if (lhs.cardinality() != rhs.cardinality()) {
// return lhs.cardinality() > rhs.cardinality() ? 1 : - 1;
// }
// else {
// return lhs.nextSetBit(0) > rhs.nextSetBit(0) ? 1 : - 1;
// }
// }
//
// private static void swap(BitSet lhs, BitSet rhs) {
// lhs.xor(rhs);
// rhs.xor(lhs);
// lhs.xor(rhs);
// }
//
// static void markRootedTreeNode(IdGroup idGroup, Node node, BitSet cluster) {
// if (node.isLeaf()) {
// String name = node.getIdentifier().getName();
// int index = idGroup.whichIdNumber(name);
//
// if (index < 0) {
// throw new IllegalArgumentException("INCOMPATIBLE IDENTIFIER (" + name + ")");
// }
// cluster.set(index);
// } else {
// for (int i = 0; i < node.getChildCount(); i++) {
// markRootedTreeNode(idGroup, node.getChild(i), cluster);
// }
// }
// }
//
// private static void markUnrootedTreeNode(IdGroup idGroup, Node node, BitSet cluster) {
// BitSet[] subTrees = new BitSet[3];
// for (int i = 0; i < 3; i++) subTrees[i] = new BitSet();
// markRootedTreeNode(idGroup, node.getChild(0), subTrees[0]);
// markRootedTreeNode(idGroup, node.getChild(1), subTrees[1]);
// subTrees[2].set(0, idGroup.getIdCount(), true);
// subTrees[2].andNot(subTrees[0]);
// subTrees[2].andNot(subTrees[1]);
// //Arrays.sort(subTrees, (BitSet lhs, BitSet rhs) -> compareBitSets(lhs, rhs));
// Arrays.sort(subTrees, new Comparator<BitSet>() {
// @Override
// public int compare(BitSet lhs, BitSet rhs) {
// return compareBitSets(lhs, rhs);
// }
// });
// cluster.or(subTrees[0]);
// cluster.or(subTrees[1]);
// }
//
// public static int getDistXorBit(BitSet cluster1, BitSet cluster2) {
//
// BitSet temp = (BitSet) cluster1.clone();
// temp.xor(cluster2);
// int d = temp.cardinality();
// return d;
// }
// public static int getAndBit(BitSet cluster1, BitSet cluster2) {
//
// BitSet temp = (BitSet) cluster1.clone();
// temp.and(cluster2);
// int d = temp.cardinality();
// return d;
// }
//
// public static int getDistToOAsMinBit(BitSet cluster) {
//
// int t = cluster.cardinality();
// return t;
//
// }
// }
// Path: src/treecmp/metric/RFClusterMetric.java
import treecmp.common.ClusterDist;
import java.util.BitSet;
import java.util.HashSet;
import pal.misc.IdGroup;
import pal.tree.*;
/** This file is part of TreeCmp, a tool for comparing phylogenetic trees
using the Matching Split distance and other metrics.
Copyright (C) 2011, Damian Bogdanowicz
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package treecmp.metric;
public class RFClusterMetric extends BaseMetric implements Metric{
public static double getRFClusterMetric(Tree t1, Tree t2) {
IdGroup idGroup = TreeUtils.getLeafIdGroup(t1);
| BitSet[] bs1 = ClusterDist.RootedTree2BitSetArray(t1, idGroup); |
TreeCmp/TreeCmp | src/treecmp/spr/SprHeuristicRfcBaseMetric.java | // Path: src/treecmp/common/TreeCmpException.java
// public class TreeCmpException extends Exception {
//
// private String errMsg;
// //----------------------------------------------
// // Default constructor - initializes instance variable to unknown
// public TreeCmpException()
// {
// super(); // call superclass constructor
// errMsg = "unknown";
// }
//
// //-----------------------------------------------
// // Constructor receives some kind of message that is saved in an instance variable.
// public TreeCmpException(String errMsg)
// {
// super(errMsg); // call super class constructor
// this.errMsg = errMsg; // save message
// }
//
// //------------------------------------------------
// // public method, callable by exception catcher. It returns the error message.
// public String getError()
// {
// return errMsg;
// }
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import pal.io.OutputTarget;
import treecmp.common.TreeCmpException;
import treecmp.metric.*;
import pal.tree.Tree;
import pal.tree.TreeUtils; | Tree currentStepTree = t1;
double bestDist1 = Double.POSITIVE_INFINITY, bestDist2 = Double.POSITIVE_INFINITY;
do {
treeList = SprUtils.generateRSprNeighbours(currentStepTree);
bestDist = Double.POSITIVE_INFINITY;
bestTreeList.clear();
tempDist = 0;
sprDist++;
for (int i = 0; i < treeList.length; i++) {
tempTree = treeList[i];
tempDist = mRF.getDistance(tempTree, t2);
if (tempDist < bestDist) {
bestTreeList.clear();
bestDist = tempDist;
bestTree = tempTree;
bestTreeList.add(bestTree);
} else if (tempDist == bestDist) {
bestTreeList.add(tempTree);
}
}
currentStepTree = findBestTree(bestTreeList, t2);
bestDist1 = bestDist2;
bestDist2 = bestDist;
if (bestDist1 <= bestDist2) {
return Double.POSITIVE_INFINITY;
}
} while (bestDist != 0);
dist = (double) sprDist; | // Path: src/treecmp/common/TreeCmpException.java
// public class TreeCmpException extends Exception {
//
// private String errMsg;
// //----------------------------------------------
// // Default constructor - initializes instance variable to unknown
// public TreeCmpException()
// {
// super(); // call superclass constructor
// errMsg = "unknown";
// }
//
// //-----------------------------------------------
// // Constructor receives some kind of message that is saved in an instance variable.
// public TreeCmpException(String errMsg)
// {
// super(errMsg); // call super class constructor
// this.errMsg = errMsg; // save message
// }
//
// //------------------------------------------------
// // public method, callable by exception catcher. It returns the error message.
// public String getError()
// {
// return errMsg;
// }
// }
// Path: src/treecmp/spr/SprHeuristicRfcBaseMetric.java
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import pal.io.OutputTarget;
import treecmp.common.TreeCmpException;
import treecmp.metric.*;
import pal.tree.Tree;
import pal.tree.TreeUtils;
Tree currentStepTree = t1;
double bestDist1 = Double.POSITIVE_INFINITY, bestDist2 = Double.POSITIVE_INFINITY;
do {
treeList = SprUtils.generateRSprNeighbours(currentStepTree);
bestDist = Double.POSITIVE_INFINITY;
bestTreeList.clear();
tempDist = 0;
sprDist++;
for (int i = 0; i < treeList.length; i++) {
tempTree = treeList[i];
tempDist = mRF.getDistance(tempTree, t2);
if (tempDist < bestDist) {
bestTreeList.clear();
bestDist = tempDist;
bestTree = tempTree;
bestTreeList.add(bestTree);
} else if (tempDist == bestDist) {
bestTreeList.add(tempTree);
}
}
currentStepTree = findBestTree(bestTreeList, t2);
bestDist1 = bestDist2;
bestDist2 = bestDist;
if (bestDist1 <= bestDist2) {
return Double.POSITIVE_INFINITY;
}
} while (bestDist != 0);
dist = (double) sprDist; | } catch (TreeCmpException ex) { |
TreeCmp/TreeCmp | src/treecmp/common/SummaryStatCalculator.java | // Path: src/treecmp/config/IOSettings.java
// public class IOSettings {
//
// private static IOSettings IOConf;
// private String inputFile;
// private String outputFile;
// private String sSep;
// private String csvSep;
// private boolean zeroValueWeights;
// private boolean pruneTrees;
// private boolean randomComparison;
// private boolean optMsMcByRf;
// private boolean genAlignments;
// private boolean useMsMcFreeLeafSet;;
// private int iStep;
// //defalut false
// private boolean calcCorrelation;
// private boolean genSummary;
// private boolean bifurcatingOnly;
// private boolean rootedMetricUsed;
// private boolean saveComparedTreePairs;
// private boolean saveOnlyBinaryComparedTreePairs;
// private boolean genSackinIndexes;
//
// public boolean isUseMsMcFreeLeafSet() {
// return useMsMcFreeLeafSet;
// }
//
// public void setUseMsMcFreeLeafSet(boolean useMsMcFreeLeafSet) {
// this.useMsMcFreeLeafSet = useMsMcFreeLeafSet;
// }
//
// public boolean isGenSummary() {
// return genSummary;
// }
//
// public void setGenSummary(boolean genSummary) {
// this.genSummary = genSummary;
// }
//
// public boolean isBifurcatingOnly() { return bifurcatingOnly; }
//
// public void setBifurcatingOnly(boolean bifurcatingOnly) {
// this.bifurcatingOnly = bifurcatingOnly;
// }
//
// public boolean isRandomComparison() {
// return randomComparison;
// }
//
// public void setRandomComparison(boolean randomComparison) {
// this.randomComparison = randomComparison;
// }
//
// public boolean isCalcCorrelation() { return calcCorrelation; }
//
// public void setCalcCorrelation(boolean calcCorrelation) {
// this.calcCorrelation = calcCorrelation;
// }
//
// public String getSSep() {
// return sSep;
// }
//
// public void setSSep(String sSep) {
// this.sSep = sSep;
// }
//
// public String getCsvSep() {
// return csvSep;
// }
//
// public void setCsvSep(String csvSep) {
// this.csvSep = csvSep;
// }
//
// public int getIStep() {
// return iStep;
// }
//
// public void setIStep(int iStep) {
// this.iStep = iStep;
// }
//
// public String getInputFile() {
// return inputFile;
// }
//
// public void setInputFile(String inputFile) {
// this.inputFile = inputFile;
// }
//
// public String getOutputFile() {
// return outputFile;
// }
//
// public void setOutputFile(String outputFile) {
// this.outputFile = outputFile;
// }
//
//
// protected IOSettings()
// {
// inputFile = null;
// outputFile = null;
// iStep = 1;
// calcCorrelation = false;
// pruneTrees = false;
// randomComparison = false;
// optMsMcByRf = false;
// genAlignments = false;
// genSummary = false;
//
//
// }
// public static IOSettings getIOSettings()
// {
// if(IOConf==null)
// {
// IOConf=new IOSettings();
// }
// return IOConf;
// }
//
// public void setZeroValueWeights(boolean zeroValueWeights) {
// this.zeroValueWeights = zeroValueWeights;
// }
//
// public boolean isZeroValueWeights() { return zeroValueWeights; }
//
// public boolean isPruneTrees() {
// return pruneTrees;
// }
//
// public void setPruneTrees(boolean pruneTrees) {
// this.pruneTrees = pruneTrees;
// }
//
// public boolean isGenAlignments() {
// return genAlignments;
// }
//
// public void setGenAlignments(boolean genAlignments) {
// this.genAlignments = genAlignments;
// }
//
// public boolean isOptMsMcByRf() {
// return optMsMcByRf;
// }
//
// public void setOptMsMcByRf(boolean optMsMcByRf) {
// this.optMsMcByRf = optMsMcByRf;
// }
//
// public boolean isRootedMetricUsed() { return rootedMetricUsed; }
//
// public void setRootedMetricUsed(boolean rootedMetricUsed) {
// this.rootedMetricUsed = rootedMetricUsed;
// }
//
// public void setSaveComparedTreePairs(boolean saveComparedTreePairs) {
// this.saveComparedTreePairs = saveComparedTreePairs;
// }
// public boolean isSaveComparedTreePairs() { return saveComparedTreePairs; }
//
// public void setSaveOnlyBifurcatingComparedTreePairs(boolean saveOnlyBinaryComparedTreePairs) {
// this.saveOnlyBinaryComparedTreePairs = saveOnlyBinaryComparedTreePairs;
// }
// public boolean isSaveOnlyBinaryComparedTreePairs() { return saveOnlyBinaryComparedTreePairs; }
//
// public void setGenSackinIndexes(boolean genSackinIndexes) { this.genSackinIndexes = genSackinIndexes; }
//
// public boolean isGenSackinIndexes() { return genSackinIndexes; }
// }
| import treecmp.io.ResultWriter;
import treecmp.config.IOSettings;
import treecmp.metric.Metric; | }
public int getCount()
{
return this.count;
}
public void insertValue(double dist)
{
sum+=dist;
count++;
sq_sum+=dist*dist;
if(dist<min) min=dist;
if(dist>max) max=dist;
}
public String getName() {
return this.met.getName();
}
public String getCommandLineName() {
return this.met.getCommandLineName();
}
public static void printSummary(ResultWriter out, SummaryStatCalculator[] sStatCalc) {
| // Path: src/treecmp/config/IOSettings.java
// public class IOSettings {
//
// private static IOSettings IOConf;
// private String inputFile;
// private String outputFile;
// private String sSep;
// private String csvSep;
// private boolean zeroValueWeights;
// private boolean pruneTrees;
// private boolean randomComparison;
// private boolean optMsMcByRf;
// private boolean genAlignments;
// private boolean useMsMcFreeLeafSet;;
// private int iStep;
// //defalut false
// private boolean calcCorrelation;
// private boolean genSummary;
// private boolean bifurcatingOnly;
// private boolean rootedMetricUsed;
// private boolean saveComparedTreePairs;
// private boolean saveOnlyBinaryComparedTreePairs;
// private boolean genSackinIndexes;
//
// public boolean isUseMsMcFreeLeafSet() {
// return useMsMcFreeLeafSet;
// }
//
// public void setUseMsMcFreeLeafSet(boolean useMsMcFreeLeafSet) {
// this.useMsMcFreeLeafSet = useMsMcFreeLeafSet;
// }
//
// public boolean isGenSummary() {
// return genSummary;
// }
//
// public void setGenSummary(boolean genSummary) {
// this.genSummary = genSummary;
// }
//
// public boolean isBifurcatingOnly() { return bifurcatingOnly; }
//
// public void setBifurcatingOnly(boolean bifurcatingOnly) {
// this.bifurcatingOnly = bifurcatingOnly;
// }
//
// public boolean isRandomComparison() {
// return randomComparison;
// }
//
// public void setRandomComparison(boolean randomComparison) {
// this.randomComparison = randomComparison;
// }
//
// public boolean isCalcCorrelation() { return calcCorrelation; }
//
// public void setCalcCorrelation(boolean calcCorrelation) {
// this.calcCorrelation = calcCorrelation;
// }
//
// public String getSSep() {
// return sSep;
// }
//
// public void setSSep(String sSep) {
// this.sSep = sSep;
// }
//
// public String getCsvSep() {
// return csvSep;
// }
//
// public void setCsvSep(String csvSep) {
// this.csvSep = csvSep;
// }
//
// public int getIStep() {
// return iStep;
// }
//
// public void setIStep(int iStep) {
// this.iStep = iStep;
// }
//
// public String getInputFile() {
// return inputFile;
// }
//
// public void setInputFile(String inputFile) {
// this.inputFile = inputFile;
// }
//
// public String getOutputFile() {
// return outputFile;
// }
//
// public void setOutputFile(String outputFile) {
// this.outputFile = outputFile;
// }
//
//
// protected IOSettings()
// {
// inputFile = null;
// outputFile = null;
// iStep = 1;
// calcCorrelation = false;
// pruneTrees = false;
// randomComparison = false;
// optMsMcByRf = false;
// genAlignments = false;
// genSummary = false;
//
//
// }
// public static IOSettings getIOSettings()
// {
// if(IOConf==null)
// {
// IOConf=new IOSettings();
// }
// return IOConf;
// }
//
// public void setZeroValueWeights(boolean zeroValueWeights) {
// this.zeroValueWeights = zeroValueWeights;
// }
//
// public boolean isZeroValueWeights() { return zeroValueWeights; }
//
// public boolean isPruneTrees() {
// return pruneTrees;
// }
//
// public void setPruneTrees(boolean pruneTrees) {
// this.pruneTrees = pruneTrees;
// }
//
// public boolean isGenAlignments() {
// return genAlignments;
// }
//
// public void setGenAlignments(boolean genAlignments) {
// this.genAlignments = genAlignments;
// }
//
// public boolean isOptMsMcByRf() {
// return optMsMcByRf;
// }
//
// public void setOptMsMcByRf(boolean optMsMcByRf) {
// this.optMsMcByRf = optMsMcByRf;
// }
//
// public boolean isRootedMetricUsed() { return rootedMetricUsed; }
//
// public void setRootedMetricUsed(boolean rootedMetricUsed) {
// this.rootedMetricUsed = rootedMetricUsed;
// }
//
// public void setSaveComparedTreePairs(boolean saveComparedTreePairs) {
// this.saveComparedTreePairs = saveComparedTreePairs;
// }
// public boolean isSaveComparedTreePairs() { return saveComparedTreePairs; }
//
// public void setSaveOnlyBifurcatingComparedTreePairs(boolean saveOnlyBinaryComparedTreePairs) {
// this.saveOnlyBinaryComparedTreePairs = saveOnlyBinaryComparedTreePairs;
// }
// public boolean isSaveOnlyBinaryComparedTreePairs() { return saveOnlyBinaryComparedTreePairs; }
//
// public void setGenSackinIndexes(boolean genSackinIndexes) { this.genSackinIndexes = genSackinIndexes; }
//
// public boolean isGenSackinIndexes() { return genSackinIndexes; }
// }
// Path: src/treecmp/common/SummaryStatCalculator.java
import treecmp.io.ResultWriter;
import treecmp.config.IOSettings;
import treecmp.metric.Metric;
}
public int getCount()
{
return this.count;
}
public void insertValue(double dist)
{
sum+=dist;
count++;
sq_sum+=dist*dist;
if(dist<min) min=dist;
if(dist>max) max=dist;
}
public String getName() {
return this.met.getName();
}
public String getCommandLineName() {
return this.met.getCommandLineName();
}
public static void printSummary(ResultWriter out, SummaryStatCalculator[] sStatCalc) {
| if (IOSettings.getIOSettings().isGenSummary()) { |
TreeCmp/TreeCmp | test/treecmp/spr/SprUtilsTest.java | // Path: src/treecmp/common/TreeCmpException.java
// public class TreeCmpException extends Exception {
//
// private String errMsg;
// //----------------------------------------------
// // Default constructor - initializes instance variable to unknown
// public TreeCmpException()
// {
// super(); // call superclass constructor
// errMsg = "unknown";
// }
//
// //-----------------------------------------------
// // Constructor receives some kind of message that is saved in an instance variable.
// public TreeCmpException(String errMsg)
// {
// super(errMsg); // call super class constructor
// this.errMsg = errMsg; // save message
// }
//
// //------------------------------------------------
// // public method, callable by exception catcher. It returns the error message.
// public String getError()
// {
// return errMsg;
// }
// }
//
// Path: src/treecmp/metric/RFMetric.java
// public class RFMetric extends BaseMetric implements Metric{
//
// public static double getRFDistance(Tree t1, Tree t2) {
//
// int n = t1.getExternalNodeCount();
// if (n <= 3)
// return 0;
//
// IdGroup idGroup = TreeUtils.getLeafIdGroup(t1);
// BitSet[] s_t1=SplitDist.getSplits(t1, idGroup);
// BitSet[] s_t2=SplitDist.getSplits(t2, idGroup);
// int N1=s_t1.length;
// int N2=s_t2.length;
// int hashSetSize=(4*(N1+1))/3;
//
// HashSet<BitSet> s_t1_hs=new HashSet<BitSet>(hashSetSize);
//
// int i;
// for(i=0;i<N1;i++){
// s_t1_hs.add(s_t1[i]);
// }
//
// int common=0;
// for(i=0;i<N2;i++){
// if (s_t1_hs.contains(s_t2[i])){
// common++;
// }
// }
//
// double dist=((double)N1+(double)N2)*0.5-(double)common;
// return dist;
//
// }
//
//
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// return RFMetric.getRFDistance(t1, t2);
//
// }
// }
| import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import pal.misc.IdGroup;
import pal.tree.Node;
import pal.tree.Tree;
import pal.tree.TreeUtils;
import treecmp.common.TreeCmpException;
import treecmp.metric.Metric;
import treecmp.metric.RFMetric;
import treecmp.test.util.TreeCreator;
import java.util.HashSet;
import java.util.Set; | assertEquals(neighSizeExpResult, treeList.length);
}
@Test
public void testGenerateRSprNeighboursShouldReturnExactly_24_Neighbours_testing_one_5_labels_tree() {
SprUtils instance = new SprUtils();
Tree baseTree = TreeCreator.getTreeFromString("((((1,2),3),4),5);");
Tree[] treeList;
//int neighSizeExpResult = instance.calcSprNeighbours(baseTree);
int neighSizeExpResult = 24;
treeList = SprUtils.generateRSprNeighbours(baseTree);
assertEquals(neighSizeExpResult, treeList.length);
}
@Test
public void testGenerateRSprNeighboursShouldReturnExactly_34812_Neighbours_testing_one_100_labels_tree() {
SprUtils instance = new SprUtils();
Tree baseTree = TreeCreator.getrootrdTreeWith_100_Labels();
Tree[] treeList;
//int neighSizeExpResult = instance.calcSprNeighbours(baseTree);
int neighSizeExpResult = 34812;
treeList = SprUtils.generateRSprNeighbours(baseTree);
assertEquals(neighSizeExpResult, treeList.length);
}
/**
* Tests of generateUSprNeighbours method, of class SprUtils.
*/
@Test | // Path: src/treecmp/common/TreeCmpException.java
// public class TreeCmpException extends Exception {
//
// private String errMsg;
// //----------------------------------------------
// // Default constructor - initializes instance variable to unknown
// public TreeCmpException()
// {
// super(); // call superclass constructor
// errMsg = "unknown";
// }
//
// //-----------------------------------------------
// // Constructor receives some kind of message that is saved in an instance variable.
// public TreeCmpException(String errMsg)
// {
// super(errMsg); // call super class constructor
// this.errMsg = errMsg; // save message
// }
//
// //------------------------------------------------
// // public method, callable by exception catcher. It returns the error message.
// public String getError()
// {
// return errMsg;
// }
// }
//
// Path: src/treecmp/metric/RFMetric.java
// public class RFMetric extends BaseMetric implements Metric{
//
// public static double getRFDistance(Tree t1, Tree t2) {
//
// int n = t1.getExternalNodeCount();
// if (n <= 3)
// return 0;
//
// IdGroup idGroup = TreeUtils.getLeafIdGroup(t1);
// BitSet[] s_t1=SplitDist.getSplits(t1, idGroup);
// BitSet[] s_t2=SplitDist.getSplits(t2, idGroup);
// int N1=s_t1.length;
// int N2=s_t2.length;
// int hashSetSize=(4*(N1+1))/3;
//
// HashSet<BitSet> s_t1_hs=new HashSet<BitSet>(hashSetSize);
//
// int i;
// for(i=0;i<N1;i++){
// s_t1_hs.add(s_t1[i]);
// }
//
// int common=0;
// for(i=0;i<N2;i++){
// if (s_t1_hs.contains(s_t2[i])){
// common++;
// }
// }
//
// double dist=((double)N1+(double)N2)*0.5-(double)common;
// return dist;
//
// }
//
//
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// return RFMetric.getRFDistance(t1, t2);
//
// }
// }
// Path: test/treecmp/spr/SprUtilsTest.java
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import pal.misc.IdGroup;
import pal.tree.Node;
import pal.tree.Tree;
import pal.tree.TreeUtils;
import treecmp.common.TreeCmpException;
import treecmp.metric.Metric;
import treecmp.metric.RFMetric;
import treecmp.test.util.TreeCreator;
import java.util.HashSet;
import java.util.Set;
assertEquals(neighSizeExpResult, treeList.length);
}
@Test
public void testGenerateRSprNeighboursShouldReturnExactly_24_Neighbours_testing_one_5_labels_tree() {
SprUtils instance = new SprUtils();
Tree baseTree = TreeCreator.getTreeFromString("((((1,2),3),4),5);");
Tree[] treeList;
//int neighSizeExpResult = instance.calcSprNeighbours(baseTree);
int neighSizeExpResult = 24;
treeList = SprUtils.generateRSprNeighbours(baseTree);
assertEquals(neighSizeExpResult, treeList.length);
}
@Test
public void testGenerateRSprNeighboursShouldReturnExactly_34812_Neighbours_testing_one_100_labels_tree() {
SprUtils instance = new SprUtils();
Tree baseTree = TreeCreator.getrootrdTreeWith_100_Labels();
Tree[] treeList;
//int neighSizeExpResult = instance.calcSprNeighbours(baseTree);
int neighSizeExpResult = 34812;
treeList = SprUtils.generateRSprNeighbours(baseTree);
assertEquals(neighSizeExpResult, treeList.length);
}
/**
* Tests of generateUSprNeighbours method, of class SprUtils.
*/
@Test | public void testGenerateUSprNeighboursShouldReturnExactly_12_Neighbours_testing_all_5_labels_trees() throws TreeCmpException { |
TreeCmp/TreeCmp | test/treecmp/spr/SprUtilsTest.java | // Path: src/treecmp/common/TreeCmpException.java
// public class TreeCmpException extends Exception {
//
// private String errMsg;
// //----------------------------------------------
// // Default constructor - initializes instance variable to unknown
// public TreeCmpException()
// {
// super(); // call superclass constructor
// errMsg = "unknown";
// }
//
// //-----------------------------------------------
// // Constructor receives some kind of message that is saved in an instance variable.
// public TreeCmpException(String errMsg)
// {
// super(errMsg); // call super class constructor
// this.errMsg = errMsg; // save message
// }
//
// //------------------------------------------------
// // public method, callable by exception catcher. It returns the error message.
// public String getError()
// {
// return errMsg;
// }
// }
//
// Path: src/treecmp/metric/RFMetric.java
// public class RFMetric extends BaseMetric implements Metric{
//
// public static double getRFDistance(Tree t1, Tree t2) {
//
// int n = t1.getExternalNodeCount();
// if (n <= 3)
// return 0;
//
// IdGroup idGroup = TreeUtils.getLeafIdGroup(t1);
// BitSet[] s_t1=SplitDist.getSplits(t1, idGroup);
// BitSet[] s_t2=SplitDist.getSplits(t2, idGroup);
// int N1=s_t1.length;
// int N2=s_t2.length;
// int hashSetSize=(4*(N1+1))/3;
//
// HashSet<BitSet> s_t1_hs=new HashSet<BitSet>(hashSetSize);
//
// int i;
// for(i=0;i<N1;i++){
// s_t1_hs.add(s_t1[i]);
// }
//
// int common=0;
// for(i=0;i<N2;i++){
// if (s_t1_hs.contains(s_t2[i])){
// common++;
// }
// }
//
// double dist=((double)N1+(double)N2)*0.5-(double)common;
// return dist;
//
// }
//
//
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// return RFMetric.getRFDistance(t1, t2);
//
// }
// }
| import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import pal.misc.IdGroup;
import pal.tree.Node;
import pal.tree.Tree;
import pal.tree.TreeUtils;
import treecmp.common.TreeCmpException;
import treecmp.metric.Metric;
import treecmp.metric.RFMetric;
import treecmp.test.util.TreeCreator;
import java.util.HashSet;
import java.util.Set; | }
@Test
public void testGenerateUSprNeighboursShouldReturnTreesWithRoot3Degree_testing_some_7_labels_trees() throws TreeCmpException {
SprUtils instance = new SprUtils();
Tree baseTrees[] = TreeCreator.getSomeUnrootedTreesWith_7_Labels();
Tree[] treeList;
for(Tree bt: baseTrees) {
treeList = SprUtils.generateUSprNeighbours(bt);
for (Tree t : treeList) {
assertEquals(3, t.getRoot().getChildCount());
}
}
}
@Test
public void testGenerateUSprNeighboursShouldReturnTreesWithRoot3Degree_testing_100_labels_tree() throws TreeCmpException {
SprUtils instance = new SprUtils();
Tree baseTree = TreeCreator.getUnrootedTreeWith_50_Labels();
//Tree baseTree = TreeCreator.getUnrootrdTreeWith_100_Labels();
Tree[] treeList;
treeList = SprUtils.generateUSprNeighbours(baseTree);
for (Tree t : treeList) {
assertEquals(3, t.getRoot().getChildCount());
}
}
@Test
public void testGenerateUSprNeighboursShoudReturnUniqueTrees() throws TreeCmpException {
SprUtils instance = new SprUtils(); | // Path: src/treecmp/common/TreeCmpException.java
// public class TreeCmpException extends Exception {
//
// private String errMsg;
// //----------------------------------------------
// // Default constructor - initializes instance variable to unknown
// public TreeCmpException()
// {
// super(); // call superclass constructor
// errMsg = "unknown";
// }
//
// //-----------------------------------------------
// // Constructor receives some kind of message that is saved in an instance variable.
// public TreeCmpException(String errMsg)
// {
// super(errMsg); // call super class constructor
// this.errMsg = errMsg; // save message
// }
//
// //------------------------------------------------
// // public method, callable by exception catcher. It returns the error message.
// public String getError()
// {
// return errMsg;
// }
// }
//
// Path: src/treecmp/metric/RFMetric.java
// public class RFMetric extends BaseMetric implements Metric{
//
// public static double getRFDistance(Tree t1, Tree t2) {
//
// int n = t1.getExternalNodeCount();
// if (n <= 3)
// return 0;
//
// IdGroup idGroup = TreeUtils.getLeafIdGroup(t1);
// BitSet[] s_t1=SplitDist.getSplits(t1, idGroup);
// BitSet[] s_t2=SplitDist.getSplits(t2, idGroup);
// int N1=s_t1.length;
// int N2=s_t2.length;
// int hashSetSize=(4*(N1+1))/3;
//
// HashSet<BitSet> s_t1_hs=new HashSet<BitSet>(hashSetSize);
//
// int i;
// for(i=0;i<N1;i++){
// s_t1_hs.add(s_t1[i]);
// }
//
// int common=0;
// for(i=0;i<N2;i++){
// if (s_t1_hs.contains(s_t2[i])){
// common++;
// }
// }
//
// double dist=((double)N1+(double)N2)*0.5-(double)common;
// return dist;
//
// }
//
//
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// return RFMetric.getRFDistance(t1, t2);
//
// }
// }
// Path: test/treecmp/spr/SprUtilsTest.java
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import pal.misc.IdGroup;
import pal.tree.Node;
import pal.tree.Tree;
import pal.tree.TreeUtils;
import treecmp.common.TreeCmpException;
import treecmp.metric.Metric;
import treecmp.metric.RFMetric;
import treecmp.test.util.TreeCreator;
import java.util.HashSet;
import java.util.Set;
}
@Test
public void testGenerateUSprNeighboursShouldReturnTreesWithRoot3Degree_testing_some_7_labels_trees() throws TreeCmpException {
SprUtils instance = new SprUtils();
Tree baseTrees[] = TreeCreator.getSomeUnrootedTreesWith_7_Labels();
Tree[] treeList;
for(Tree bt: baseTrees) {
treeList = SprUtils.generateUSprNeighbours(bt);
for (Tree t : treeList) {
assertEquals(3, t.getRoot().getChildCount());
}
}
}
@Test
public void testGenerateUSprNeighboursShouldReturnTreesWithRoot3Degree_testing_100_labels_tree() throws TreeCmpException {
SprUtils instance = new SprUtils();
Tree baseTree = TreeCreator.getUnrootedTreeWith_50_Labels();
//Tree baseTree = TreeCreator.getUnrootrdTreeWith_100_Labels();
Tree[] treeList;
treeList = SprUtils.generateUSprNeighbours(baseTree);
for (Tree t : treeList) {
assertEquals(3, t.getRoot().getChildCount());
}
}
@Test
public void testGenerateUSprNeighboursShoudReturnUniqueTrees() throws TreeCmpException {
SprUtils instance = new SprUtils(); | Metric rf = new RFMetric(); |
TreeCmp/TreeCmp | src/treecmp/spr/SprHeuristicCophRfcMetric.java | // Path: src/treecmp/metric/CopheneticL2Metric.java
// public class CopheneticL2Metric extends BaseMetric implements Metric {
//
// @Override
// public boolean isRooted() {
// return true;
// }
//
// public CopheneticL2Metric() {
// super();
// }
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// int extT1Num = t1.getExternalNodeCount();
// int extT2Num = t2.getExternalNodeCount();
// if (extT1Num <= 2) {
// return 0.0;
// }
// IdGroup id1 = TreeUtils.getLeafIdGroup(t1);
// int[][] lcaMatrix1 = TreeCmpUtils.calcLcaMatrix(t1, null);
// int[][] lcaMatrix2 = TreeCmpUtils.calcLcaMatrix(t2, id1);
//
// int intT1Num = t1.getInternalNodeCount();
// int intT2Num = t2.getInternalNodeCount();
//
// Node[] preOrderT1 = TreeCmpUtils.getNodesInPreOrder(t1);
// Node[] preOrderT2 = TreeCmpUtils.getNodesInPreOrder(t2);
//
// short[] intDepthT1 = new short[intT1Num];
// short[] intDepthT2 = new short[intT2Num];
//
// short[] extDepthT1 = new short[extT1Num];
// short[] extDepthT2 = new short[extT2Num];
//
// TreeCmpUtils.calcNodeDepth(t1, preOrderT1, extDepthT1, intDepthT1, null);
// TreeCmpUtils.calcNodeDepth(t2, preOrderT2, extDepthT2, intDepthT2, id1);
//
// double diff, dist = 0.0;
// int xNodeNum, yNodeNum, xyNodeNumT1, xyNodeNumT2;
// Node xNode, yNode;
// for (int i = 0; i < extT1Num; i++) {
// xNode = t1.getExternalNode(i);
// xNodeNum = xNode.getNumber();
// for (int j = i + 1; j < extT1Num; j++) {
// yNode = t1.getExternalNode(j);
// yNodeNum = yNode.getNumber();
// xyNodeNumT1 = lcaMatrix1[xNodeNum][yNodeNum];
// xyNodeNumT2 = lcaMatrix2[xNodeNum][yNodeNum];
//
// diff = intDepthT1[xyNodeNumT1] - intDepthT2[xyNodeNumT2];
// dist += diff * diff;
// }
// }
// for (int i = 0; i < extT1Num; i++) {
// xNode = t1.getExternalNode(i);
// xNodeNum = xNode.getNumber();
// diff = extDepthT1[xNodeNum] - extDepthT2[xNodeNum];
// dist += diff * diff;
// }
//
// return Math.sqrt(dist);
// }
// }
| import treecmp.metric.Metric;
import treecmp.metric.CopheneticL2Metric; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class SprHeuristicCophRfcMetric extends SprHeuristicRfcBaseMetric{
@Override
protected Metric getMetric(){ | // Path: src/treecmp/metric/CopheneticL2Metric.java
// public class CopheneticL2Metric extends BaseMetric implements Metric {
//
// @Override
// public boolean isRooted() {
// return true;
// }
//
// public CopheneticL2Metric() {
// super();
// }
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// int extT1Num = t1.getExternalNodeCount();
// int extT2Num = t2.getExternalNodeCount();
// if (extT1Num <= 2) {
// return 0.0;
// }
// IdGroup id1 = TreeUtils.getLeafIdGroup(t1);
// int[][] lcaMatrix1 = TreeCmpUtils.calcLcaMatrix(t1, null);
// int[][] lcaMatrix2 = TreeCmpUtils.calcLcaMatrix(t2, id1);
//
// int intT1Num = t1.getInternalNodeCount();
// int intT2Num = t2.getInternalNodeCount();
//
// Node[] preOrderT1 = TreeCmpUtils.getNodesInPreOrder(t1);
// Node[] preOrderT2 = TreeCmpUtils.getNodesInPreOrder(t2);
//
// short[] intDepthT1 = new short[intT1Num];
// short[] intDepthT2 = new short[intT2Num];
//
// short[] extDepthT1 = new short[extT1Num];
// short[] extDepthT2 = new short[extT2Num];
//
// TreeCmpUtils.calcNodeDepth(t1, preOrderT1, extDepthT1, intDepthT1, null);
// TreeCmpUtils.calcNodeDepth(t2, preOrderT2, extDepthT2, intDepthT2, id1);
//
// double diff, dist = 0.0;
// int xNodeNum, yNodeNum, xyNodeNumT1, xyNodeNumT2;
// Node xNode, yNode;
// for (int i = 0; i < extT1Num; i++) {
// xNode = t1.getExternalNode(i);
// xNodeNum = xNode.getNumber();
// for (int j = i + 1; j < extT1Num; j++) {
// yNode = t1.getExternalNode(j);
// yNodeNum = yNode.getNumber();
// xyNodeNumT1 = lcaMatrix1[xNodeNum][yNodeNum];
// xyNodeNumT2 = lcaMatrix2[xNodeNum][yNodeNum];
//
// diff = intDepthT1[xyNodeNumT1] - intDepthT2[xyNodeNumT2];
// dist += diff * diff;
// }
// }
// for (int i = 0; i < extT1Num; i++) {
// xNode = t1.getExternalNode(i);
// xNodeNum = xNode.getNumber();
// diff = extDepthT1[xNodeNum] - extDepthT2[xNodeNum];
// dist += diff * diff;
// }
//
// return Math.sqrt(dist);
// }
// }
// Path: src/treecmp/spr/SprHeuristicCophRfcMetric.java
import treecmp.metric.Metric;
import treecmp.metric.CopheneticL2Metric;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class SprHeuristicCophRfcMetric extends SprHeuristicRfcBaseMetric{
@Override
protected Metric getMetric(){ | return new CopheneticL2Metric(); |
TreeCmp/TreeCmp | test/treecmp/spr/UsprHeuristicRFMetricTest.java | // Path: src/treecmp/common/TreeCmpException.java
// public class TreeCmpException extends Exception {
//
// private String errMsg;
// //----------------------------------------------
// // Default constructor - initializes instance variable to unknown
// public TreeCmpException()
// {
// super(); // call superclass constructor
// errMsg = "unknown";
// }
//
// //-----------------------------------------------
// // Constructor receives some kind of message that is saved in an instance variable.
// public TreeCmpException(String errMsg)
// {
// super(errMsg); // call super class constructor
// this.errMsg = errMsg; // save message
// }
//
// //------------------------------------------------
// // public method, callable by exception catcher. It returns the error message.
// public String getError()
// {
// return errMsg;
// }
// }
| import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import pal.tree.Tree;
import treecmp.common.TreeCmpException;
import treecmp.metric.Metric;
import treecmp.test.util.TreeCreator;
import static org.junit.jupiter.api.Assertions.*; | package treecmp.spr;
class UsprHeuristicRFMetricTest {
@BeforeEach
void setUp() {
}
@AfterEach
void tearDown() {
}
@Test | // Path: src/treecmp/common/TreeCmpException.java
// public class TreeCmpException extends Exception {
//
// private String errMsg;
// //----------------------------------------------
// // Default constructor - initializes instance variable to unknown
// public TreeCmpException()
// {
// super(); // call superclass constructor
// errMsg = "unknown";
// }
//
// //-----------------------------------------------
// // Constructor receives some kind of message that is saved in an instance variable.
// public TreeCmpException(String errMsg)
// {
// super(errMsg); // call super class constructor
// this.errMsg = errMsg; // save message
// }
//
// //------------------------------------------------
// // public method, callable by exception catcher. It returns the error message.
// public String getError()
// {
// return errMsg;
// }
// }
// Path: test/treecmp/spr/UsprHeuristicRFMetricTest.java
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import pal.tree.Tree;
import treecmp.common.TreeCmpException;
import treecmp.metric.Metric;
import treecmp.test.util.TreeCreator;
import static org.junit.jupiter.api.Assertions.*;
package treecmp.spr;
class UsprHeuristicRFMetricTest {
@BeforeEach
void setUp() {
}
@AfterEach
void tearDown() {
}
@Test | void testGetMetricTwoMarsupialsTreesWithSPR_1_distance() throws TreeCmpException { |
TreeCmp/TreeCmp | test/treecmp/spr/UsprHeuristicMPUMetricTest.java | // Path: src/treecmp/common/TreeCmpException.java
// public class TreeCmpException extends Exception {
//
// private String errMsg;
// //----------------------------------------------
// // Default constructor - initializes instance variable to unknown
// public TreeCmpException()
// {
// super(); // call superclass constructor
// errMsg = "unknown";
// }
//
// //-----------------------------------------------
// // Constructor receives some kind of message that is saved in an instance variable.
// public TreeCmpException(String errMsg)
// {
// super(errMsg); // call super class constructor
// this.errMsg = errMsg; // save message
// }
//
// //------------------------------------------------
// // public method, callable by exception catcher. It returns the error message.
// public String getError()
// {
// return errMsg;
// }
// }
| import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import pal.tree.Tree;
import treecmp.common.TreeCmpException;
import treecmp.metric.Metric;
import treecmp.test.util.TreeCreator;
import static org.junit.jupiter.api.Assertions.*; | package treecmp.spr;
class UsprHeuristicMPUMetricTest {
@BeforeEach
void setUp() {
}
@AfterEach
void tearDown() {
}
@Test | // Path: src/treecmp/common/TreeCmpException.java
// public class TreeCmpException extends Exception {
//
// private String errMsg;
// //----------------------------------------------
// // Default constructor - initializes instance variable to unknown
// public TreeCmpException()
// {
// super(); // call superclass constructor
// errMsg = "unknown";
// }
//
// //-----------------------------------------------
// // Constructor receives some kind of message that is saved in an instance variable.
// public TreeCmpException(String errMsg)
// {
// super(errMsg); // call super class constructor
// this.errMsg = errMsg; // save message
// }
//
// //------------------------------------------------
// // public method, callable by exception catcher. It returns the error message.
// public String getError()
// {
// return errMsg;
// }
// }
// Path: test/treecmp/spr/UsprHeuristicMPUMetricTest.java
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import pal.tree.Tree;
import treecmp.common.TreeCmpException;
import treecmp.metric.Metric;
import treecmp.test.util.TreeCreator;
import static org.junit.jupiter.api.Assertions.*;
package treecmp.spr;
class UsprHeuristicMPUMetricTest {
@BeforeEach
void setUp() {
}
@AfterEach
void tearDown() {
}
@Test | void testGetMetricTwoMarsupialsTreesWithSPR_1_distance() throws TreeCmpException { |
TreeCmp/TreeCmp | src/treecmp/spr/SprHeuristicNsRfcMetric.java | // Path: src/treecmp/metric/NodalL2SplittedMetric.java
// public class NodalL2SplittedMetric extends BaseMetric implements Metric{
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// double dist,diff;
//
// IdGroup id1 = TreeUtils.getLeafIdGroup(t1);
// int [][] nsMatrix1 = TreeCmpUtils.calcNodalSplittedMatrix(t1, null);
// int [][] nsMatrix2 = TreeCmpUtils.calcNodalSplittedMatrix(t2, id1);
//
// dist = 0.0;
// for (int i = 0; i < id1.getIdCount(); i++) {
// for (int j = 0; j < id1.getIdCount(); j++) {
// diff = nsMatrix1[i][j] - nsMatrix2[i][j];
// dist += diff*diff;
// }
// }
// return Math.sqrt(dist);
// }
//
// }
| import treecmp.metric.NodalL2SplittedMetric;
import treecmp.metric.Metric; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class SprHeuristicNsRfcMetric extends SprHeuristicRfcBaseMetric{
@Override
protected Metric getMetric(){ | // Path: src/treecmp/metric/NodalL2SplittedMetric.java
// public class NodalL2SplittedMetric extends BaseMetric implements Metric{
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// double dist,diff;
//
// IdGroup id1 = TreeUtils.getLeafIdGroup(t1);
// int [][] nsMatrix1 = TreeCmpUtils.calcNodalSplittedMatrix(t1, null);
// int [][] nsMatrix2 = TreeCmpUtils.calcNodalSplittedMatrix(t2, id1);
//
// dist = 0.0;
// for (int i = 0; i < id1.getIdCount(); i++) {
// for (int j = 0; j < id1.getIdCount(); j++) {
// diff = nsMatrix1[i][j] - nsMatrix2[i][j];
// dist += diff*diff;
// }
// }
// return Math.sqrt(dist);
// }
//
// }
// Path: src/treecmp/spr/SprHeuristicNsRfcMetric.java
import treecmp.metric.NodalL2SplittedMetric;
import treecmp.metric.Metric;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class SprHeuristicNsRfcMetric extends SprHeuristicRfcBaseMetric{
@Override
protected Metric getMetric(){ | return new NodalL2SplittedMetric(); |
TreeCmp/TreeCmp | src/treecmp/spr/UsprHeuristicQTMetric.java | // Path: src/treecmp/metric/QuartetMetricDouble.java
// public class QuartetMetricDouble extends BaseMetric implements Metric {
//
// public QuartetMetricDouble() {
// }
//
// public static double getQuartetDistance(pal.tree.Tree tree1, pal.tree.Tree tree2) {
//
//
// OutputTarget tree1OT = OutputTarget.openString();
// OutputTarget tree2OT = OutputTarget.openString();
//
// TreeUtils.printNH(tree1, tree1OT, false, false);
// TreeUtils.printNH(tree2, tree2OT, false, false);
//
// String tree1Newick = tree1OT.getString();
// String tree2Newick = tree2OT.getString();
//
// tree1OT.close();
// tree2OT.close();
//
// Distance d = new GeneralN2DQDistDoubleShort();
// double dist = -1.0;
// try {
// treecmp.qt.Tree tree_tt1 = new treecmp.qt.Tree(tree1Newick);
// treecmp.qt.Tree tree_tt2 = new treecmp.qt.Tree(tree2Newick);
//
// DistResult dr = d.getMeasures(tree_tt1, tree_tt2);
// dist = (double) (dr.qdist() + dr.q1() + dr.q2());
// } catch (ParseException ex) {
// ex.printStackTrace();
// }
// return dist;
//
// }
//
// public double getDistance(pal.tree.Tree t1, pal.tree.Tree t2, int... indexes) {
//
// return QuartetMetricDouble.getQuartetDistance(t1, t2);
// }
// }
//
// Path: src/treecmp/metric/QuartetMetricLong.java
// public class QuartetMetricLong extends BaseMetric implements Metric {
//
// public QuartetMetricLong() {
// }
//
// public static double getQuartetDistance(pal.tree.Tree tree1, pal.tree.Tree tree2) {
//
//
// OutputTarget tree1OT = OutputTarget.openString();
// OutputTarget tree2OT = OutputTarget.openString();
//
// TreeUtils.printNH(tree1, tree1OT, false, false);
// TreeUtils.printNH(tree2, tree2OT, false, false);
//
// String tree1Newick = tree1OT.getString();
// String tree2Newick = tree2OT.getString();
//
// tree1OT.close();
// tree2OT.close();
//
// Distance d = new GeneralN2DQDistLongShort();
// double dist = -1.0;
// try {
// treecmp.qt.Tree tree_tt1 = new treecmp.qt.Tree(tree1Newick);
// treecmp.qt.Tree tree_tt2 = new treecmp.qt.Tree(tree2Newick);
//
// DistResult dr = d.getMeasures(tree_tt1, tree_tt2);
// dist = (double) (dr.qdist() + dr.q1() + dr.q2());
// } catch (ParseException ex) {
// ex.printStackTrace();
// }
// return dist;
//
// }
//
// public double getDistance(pal.tree.Tree t1, pal.tree.Tree t2, int... indexes) {
//
// return QuartetMetricLong.getQuartetDistance(t1, t2);
// }
// }
//
// Path: src/treecmp/metric/RFMetric.java
// public class RFMetric extends BaseMetric implements Metric{
//
// public static double getRFDistance(Tree t1, Tree t2) {
//
// int n = t1.getExternalNodeCount();
// if (n <= 3)
// return 0;
//
// IdGroup idGroup = TreeUtils.getLeafIdGroup(t1);
// BitSet[] s_t1=SplitDist.getSplits(t1, idGroup);
// BitSet[] s_t2=SplitDist.getSplits(t2, idGroup);
// int N1=s_t1.length;
// int N2=s_t2.length;
// int hashSetSize=(4*(N1+1))/3;
//
// HashSet<BitSet> s_t1_hs=new HashSet<BitSet>(hashSetSize);
//
// int i;
// for(i=0;i<N1;i++){
// s_t1_hs.add(s_t1[i]);
// }
//
// int common=0;
// for(i=0;i<N2;i++){
// if (s_t1_hs.contains(s_t2[i])){
// common++;
// }
// }
//
// double dist=((double)N1+(double)N2)*0.5-(double)common;
// return dist;
//
// }
//
//
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// return RFMetric.getRFDistance(t1, t2);
//
// }
// }
| import treecmp.metric.QuartetMetricDouble;
import treecmp.metric.QuartetMetricLong;
import treecmp.metric.RFMetric;
import treecmp.metric.Metric; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class UsprHeuristicQTMetric extends UsprHeuristicBaseMetric {
@Override
protected Metric getMetric(){ | // Path: src/treecmp/metric/QuartetMetricDouble.java
// public class QuartetMetricDouble extends BaseMetric implements Metric {
//
// public QuartetMetricDouble() {
// }
//
// public static double getQuartetDistance(pal.tree.Tree tree1, pal.tree.Tree tree2) {
//
//
// OutputTarget tree1OT = OutputTarget.openString();
// OutputTarget tree2OT = OutputTarget.openString();
//
// TreeUtils.printNH(tree1, tree1OT, false, false);
// TreeUtils.printNH(tree2, tree2OT, false, false);
//
// String tree1Newick = tree1OT.getString();
// String tree2Newick = tree2OT.getString();
//
// tree1OT.close();
// tree2OT.close();
//
// Distance d = new GeneralN2DQDistDoubleShort();
// double dist = -1.0;
// try {
// treecmp.qt.Tree tree_tt1 = new treecmp.qt.Tree(tree1Newick);
// treecmp.qt.Tree tree_tt2 = new treecmp.qt.Tree(tree2Newick);
//
// DistResult dr = d.getMeasures(tree_tt1, tree_tt2);
// dist = (double) (dr.qdist() + dr.q1() + dr.q2());
// } catch (ParseException ex) {
// ex.printStackTrace();
// }
// return dist;
//
// }
//
// public double getDistance(pal.tree.Tree t1, pal.tree.Tree t2, int... indexes) {
//
// return QuartetMetricDouble.getQuartetDistance(t1, t2);
// }
// }
//
// Path: src/treecmp/metric/QuartetMetricLong.java
// public class QuartetMetricLong extends BaseMetric implements Metric {
//
// public QuartetMetricLong() {
// }
//
// public static double getQuartetDistance(pal.tree.Tree tree1, pal.tree.Tree tree2) {
//
//
// OutputTarget tree1OT = OutputTarget.openString();
// OutputTarget tree2OT = OutputTarget.openString();
//
// TreeUtils.printNH(tree1, tree1OT, false, false);
// TreeUtils.printNH(tree2, tree2OT, false, false);
//
// String tree1Newick = tree1OT.getString();
// String tree2Newick = tree2OT.getString();
//
// tree1OT.close();
// tree2OT.close();
//
// Distance d = new GeneralN2DQDistLongShort();
// double dist = -1.0;
// try {
// treecmp.qt.Tree tree_tt1 = new treecmp.qt.Tree(tree1Newick);
// treecmp.qt.Tree tree_tt2 = new treecmp.qt.Tree(tree2Newick);
//
// DistResult dr = d.getMeasures(tree_tt1, tree_tt2);
// dist = (double) (dr.qdist() + dr.q1() + dr.q2());
// } catch (ParseException ex) {
// ex.printStackTrace();
// }
// return dist;
//
// }
//
// public double getDistance(pal.tree.Tree t1, pal.tree.Tree t2, int... indexes) {
//
// return QuartetMetricLong.getQuartetDistance(t1, t2);
// }
// }
//
// Path: src/treecmp/metric/RFMetric.java
// public class RFMetric extends BaseMetric implements Metric{
//
// public static double getRFDistance(Tree t1, Tree t2) {
//
// int n = t1.getExternalNodeCount();
// if (n <= 3)
// return 0;
//
// IdGroup idGroup = TreeUtils.getLeafIdGroup(t1);
// BitSet[] s_t1=SplitDist.getSplits(t1, idGroup);
// BitSet[] s_t2=SplitDist.getSplits(t2, idGroup);
// int N1=s_t1.length;
// int N2=s_t2.length;
// int hashSetSize=(4*(N1+1))/3;
//
// HashSet<BitSet> s_t1_hs=new HashSet<BitSet>(hashSetSize);
//
// int i;
// for(i=0;i<N1;i++){
// s_t1_hs.add(s_t1[i]);
// }
//
// int common=0;
// for(i=0;i<N2;i++){
// if (s_t1_hs.contains(s_t2[i])){
// common++;
// }
// }
//
// double dist=((double)N1+(double)N2)*0.5-(double)common;
// return dist;
//
// }
//
//
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// return RFMetric.getRFDistance(t1, t2);
//
// }
// }
// Path: src/treecmp/spr/UsprHeuristicQTMetric.java
import treecmp.metric.QuartetMetricDouble;
import treecmp.metric.QuartetMetricLong;
import treecmp.metric.RFMetric;
import treecmp.metric.Metric;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class UsprHeuristicQTMetric extends UsprHeuristicBaseMetric {
@Override
protected Metric getMetric(){ | return new QuartetMetricLong(); |
TreeCmp/TreeCmp | src/treecmp/spr/SprHeuristicMPMetric.java | // Path: src/treecmp/metric/MatchingPairMetric.java
// public class MatchingPairMetric extends BaseMetric implements Metric {
//
// protected int[] rowsol;
// protected int[] colsol;
// protected int[][] assigncost;
//
// public MatchingPairMetric() {
// super();
// }
//
// @Override
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// if (t1.getExternalNodeCount() <= 2){
// return 0.0;
// }
//
// IdGroup id1 = TreeUtils.getLeafIdGroup(t1);
// int[][] lcaMatrix1 = TreeCmpUtils.calcLcaMatrix(t1, null);
// int[][] lcaMatrix2 = TreeCmpUtils.calcLcaMatrix(t2, id1);
//
// int intT1Num = t1.getInternalNodeCount();
// int intT2Num = t2.getInternalNodeCount();
//
// Node[] postOrderT1 = TreeCmpUtils.getNodesInPostOrder(t1);
// Node[] postOrderT2 = TreeCmpUtils.getNodesInPostOrder(t2);
//
// short[] cSize1 = new short[intT1Num];
// short[] cSize2 = new short[intT2Num];
//
// TreeCmpUtils.calcCladeSizes(t1, postOrderT1, cSize1);
// TreeCmpUtils.calcCladeSizes(t2, postOrderT2, cSize2);
//
// int N = t1.getExternalNodeCount();
//
// int size = Math.max(intT1Num, intT2Num);
// if (size <= 0) {
// return 0;
// }
//
// assigncost = new int[size][size];
// rowsol = new int[size];
// colsol = new int[size];
// int[] u = new int[size];
// int[] v = new int[size];
//
// //iterate by all possible pairs of leaves
// //and fill assigncont with the value of intersection size
// for (int i = 0; i < N; i++){
// for (int j = i+1; j < N; j++){
// int int1 = lcaMatrix1[i][j];
// int int2 = lcaMatrix2[i][j];
// assigncost[int1][int2]++;
// }
// }
// //count LCA pairs for t1
// int[] t1IntPairCount = new int[intT1Num];
// for (int i = 0; i < intT1Num; i++){
// //Node n = t1.getInternalNode(alias1[i]);
// Node n = t1.getInternalNode(i);
// t1IntPairCount[i] = coutChildrenPairs(n, cSize1);
// }
// //count LCA pairs for t2
// int[] t2IntPairCount = new int[intT2Num];
// for (int i = 0; i < intT2Num; i++){
// //Node n = t2.getInternalNode(alias2[i]);
// Node n = t2.getInternalNode(i);
// t2IntPairCount[i] = coutChildrenPairs(n, cSize2);
// }
//
// //calc xor valuses of pairs sets and store it in assigncost matrix
// for (int i = 0; i < size; i++){
// for (int j = 0; j < size; j++){
// if (i < intT1Num && j < intT2Num){
// assigncost[i][j] = t1IntPairCount[i]+t2IntPairCount[j] - (assigncost[i][j] << 1);
// } else if (i >= intT1Num && j < intT2Num){
// assigncost[i][j] = t2IntPairCount[j];
// } else if (i < intT1Num && j >= intT2Num){
// assigncost[i][j] = t1IntPairCount[i];
// }else {
// //normally should not happen
// assigncost[i][j] = 0;
// }
// }
// }
// int metric = LapSolver.lap(size, assigncost, rowsol, colsol, u, v);
// return (0.5 * (double) metric);
// }
//
//
// int coutChildrenPairs(Node n, short[] clustSizeTab) {
// int chCount = n.getChildCount();
// int[] cSize = new int[chCount];
//
// for (int i = 0; i < chCount; i++) {
// Node chNode = n.getChild(i);
// if (chNode.isLeaf()) {
// cSize[i] = 1;
// } else {
// cSize[i] = clustSizeTab[chNode.getNumber()];
// }
// }
// int pairCount = 0;
// for (int i = 0; i < cSize.length; i++) {
// for (int j = i + 1; j < cSize.length; j++) {
// pairCount += (cSize[i] * cSize[j]);
// }
// }
// return pairCount;
// }
// }
| import treecmp.metric.MatchingPairMetric;
import treecmp.metric.Metric; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class SprHeuristicMPMetric extends SprHeuristicBaseMetric{
@Override
protected Metric getMetric(){ | // Path: src/treecmp/metric/MatchingPairMetric.java
// public class MatchingPairMetric extends BaseMetric implements Metric {
//
// protected int[] rowsol;
// protected int[] colsol;
// protected int[][] assigncost;
//
// public MatchingPairMetric() {
// super();
// }
//
// @Override
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// if (t1.getExternalNodeCount() <= 2){
// return 0.0;
// }
//
// IdGroup id1 = TreeUtils.getLeafIdGroup(t1);
// int[][] lcaMatrix1 = TreeCmpUtils.calcLcaMatrix(t1, null);
// int[][] lcaMatrix2 = TreeCmpUtils.calcLcaMatrix(t2, id1);
//
// int intT1Num = t1.getInternalNodeCount();
// int intT2Num = t2.getInternalNodeCount();
//
// Node[] postOrderT1 = TreeCmpUtils.getNodesInPostOrder(t1);
// Node[] postOrderT2 = TreeCmpUtils.getNodesInPostOrder(t2);
//
// short[] cSize1 = new short[intT1Num];
// short[] cSize2 = new short[intT2Num];
//
// TreeCmpUtils.calcCladeSizes(t1, postOrderT1, cSize1);
// TreeCmpUtils.calcCladeSizes(t2, postOrderT2, cSize2);
//
// int N = t1.getExternalNodeCount();
//
// int size = Math.max(intT1Num, intT2Num);
// if (size <= 0) {
// return 0;
// }
//
// assigncost = new int[size][size];
// rowsol = new int[size];
// colsol = new int[size];
// int[] u = new int[size];
// int[] v = new int[size];
//
// //iterate by all possible pairs of leaves
// //and fill assigncont with the value of intersection size
// for (int i = 0; i < N; i++){
// for (int j = i+1; j < N; j++){
// int int1 = lcaMatrix1[i][j];
// int int2 = lcaMatrix2[i][j];
// assigncost[int1][int2]++;
// }
// }
// //count LCA pairs for t1
// int[] t1IntPairCount = new int[intT1Num];
// for (int i = 0; i < intT1Num; i++){
// //Node n = t1.getInternalNode(alias1[i]);
// Node n = t1.getInternalNode(i);
// t1IntPairCount[i] = coutChildrenPairs(n, cSize1);
// }
// //count LCA pairs for t2
// int[] t2IntPairCount = new int[intT2Num];
// for (int i = 0; i < intT2Num; i++){
// //Node n = t2.getInternalNode(alias2[i]);
// Node n = t2.getInternalNode(i);
// t2IntPairCount[i] = coutChildrenPairs(n, cSize2);
// }
//
// //calc xor valuses of pairs sets and store it in assigncost matrix
// for (int i = 0; i < size; i++){
// for (int j = 0; j < size; j++){
// if (i < intT1Num && j < intT2Num){
// assigncost[i][j] = t1IntPairCount[i]+t2IntPairCount[j] - (assigncost[i][j] << 1);
// } else if (i >= intT1Num && j < intT2Num){
// assigncost[i][j] = t2IntPairCount[j];
// } else if (i < intT1Num && j >= intT2Num){
// assigncost[i][j] = t1IntPairCount[i];
// }else {
// //normally should not happen
// assigncost[i][j] = 0;
// }
// }
// }
// int metric = LapSolver.lap(size, assigncost, rowsol, colsol, u, v);
// return (0.5 * (double) metric);
// }
//
//
// int coutChildrenPairs(Node n, short[] clustSizeTab) {
// int chCount = n.getChildCount();
// int[] cSize = new int[chCount];
//
// for (int i = 0; i < chCount; i++) {
// Node chNode = n.getChild(i);
// if (chNode.isLeaf()) {
// cSize[i] = 1;
// } else {
// cSize[i] = clustSizeTab[chNode.getNumber()];
// }
// }
// int pairCount = 0;
// for (int i = 0; i < cSize.length; i++) {
// for (int j = i + 1; j < cSize.length; j++) {
// pairCount += (cSize[i] * cSize[j]);
// }
// }
// return pairCount;
// }
// }
// Path: src/treecmp/spr/SprHeuristicMPMetric.java
import treecmp.metric.MatchingPairMetric;
import treecmp.metric.Metric;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class SprHeuristicMPMetric extends SprHeuristicBaseMetric{
@Override
protected Metric getMetric(){ | return new MatchingPairMetric(); |
TreeCmp/TreeCmp | src/treecmp/spr/UsprHeuristicRFMetric.java | // Path: src/treecmp/metric/RFMetric.java
// public class RFMetric extends BaseMetric implements Metric{
//
// public static double getRFDistance(Tree t1, Tree t2) {
//
// int n = t1.getExternalNodeCount();
// if (n <= 3)
// return 0;
//
// IdGroup idGroup = TreeUtils.getLeafIdGroup(t1);
// BitSet[] s_t1=SplitDist.getSplits(t1, idGroup);
// BitSet[] s_t2=SplitDist.getSplits(t2, idGroup);
// int N1=s_t1.length;
// int N2=s_t2.length;
// int hashSetSize=(4*(N1+1))/3;
//
// HashSet<BitSet> s_t1_hs=new HashSet<BitSet>(hashSetSize);
//
// int i;
// for(i=0;i<N1;i++){
// s_t1_hs.add(s_t1[i]);
// }
//
// int common=0;
// for(i=0;i<N2;i++){
// if (s_t1_hs.contains(s_t2[i])){
// common++;
// }
// }
//
// double dist=((double)N1+(double)N2)*0.5-(double)common;
// return dist;
//
// }
//
//
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// return RFMetric.getRFDistance(t1, t2);
//
// }
// }
| import treecmp.metric.RFMetric;
import treecmp.metric.Metric; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class UsprHeuristicRFMetric extends UsprHeuristicBaseMetric {
@Override
protected Metric getMetric(){ | // Path: src/treecmp/metric/RFMetric.java
// public class RFMetric extends BaseMetric implements Metric{
//
// public static double getRFDistance(Tree t1, Tree t2) {
//
// int n = t1.getExternalNodeCount();
// if (n <= 3)
// return 0;
//
// IdGroup idGroup = TreeUtils.getLeafIdGroup(t1);
// BitSet[] s_t1=SplitDist.getSplits(t1, idGroup);
// BitSet[] s_t2=SplitDist.getSplits(t2, idGroup);
// int N1=s_t1.length;
// int N2=s_t2.length;
// int hashSetSize=(4*(N1+1))/3;
//
// HashSet<BitSet> s_t1_hs=new HashSet<BitSet>(hashSetSize);
//
// int i;
// for(i=0;i<N1;i++){
// s_t1_hs.add(s_t1[i]);
// }
//
// int common=0;
// for(i=0;i<N2;i++){
// if (s_t1_hs.contains(s_t2[i])){
// common++;
// }
// }
//
// double dist=((double)N1+(double)N2)*0.5-(double)common;
// return dist;
//
// }
//
//
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// return RFMetric.getRFDistance(t1, t2);
//
// }
// }
// Path: src/treecmp/spr/UsprHeuristicRFMetric.java
import treecmp.metric.RFMetric;
import treecmp.metric.Metric;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class UsprHeuristicRFMetric extends UsprHeuristicBaseMetric {
@Override
protected Metric getMetric(){ | return new RFMetric(); |
TreeCmp/TreeCmp | src/treecmp/spr/SprHeuristicNSMetric.java | // Path: src/treecmp/metric/NodalL2SplittedMetric.java
// public class NodalL2SplittedMetric extends BaseMetric implements Metric{
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// double dist,diff;
//
// IdGroup id1 = TreeUtils.getLeafIdGroup(t1);
// int [][] nsMatrix1 = TreeCmpUtils.calcNodalSplittedMatrix(t1, null);
// int [][] nsMatrix2 = TreeCmpUtils.calcNodalSplittedMatrix(t2, id1);
//
// dist = 0.0;
// for (int i = 0; i < id1.getIdCount(); i++) {
// for (int j = 0; j < id1.getIdCount(); j++) {
// diff = nsMatrix1[i][j] - nsMatrix2[i][j];
// dist += diff*diff;
// }
// }
// return Math.sqrt(dist);
// }
//
// }
| import treecmp.metric.NodalL2SplittedMetric;
import treecmp.metric.Metric; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class SprHeuristicNSMetric extends SprHeuristicBaseMetric{
@Override
protected Metric getMetric(){ | // Path: src/treecmp/metric/NodalL2SplittedMetric.java
// public class NodalL2SplittedMetric extends BaseMetric implements Metric{
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// double dist,diff;
//
// IdGroup id1 = TreeUtils.getLeafIdGroup(t1);
// int [][] nsMatrix1 = TreeCmpUtils.calcNodalSplittedMatrix(t1, null);
// int [][] nsMatrix2 = TreeCmpUtils.calcNodalSplittedMatrix(t2, id1);
//
// dist = 0.0;
// for (int i = 0; i < id1.getIdCount(); i++) {
// for (int j = 0; j < id1.getIdCount(); j++) {
// diff = nsMatrix1[i][j] - nsMatrix2[i][j];
// dist += diff*diff;
// }
// }
// return Math.sqrt(dist);
// }
//
// }
// Path: src/treecmp/spr/SprHeuristicNSMetric.java
import treecmp.metric.NodalL2SplittedMetric;
import treecmp.metric.Metric;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class SprHeuristicNSMetric extends SprHeuristicBaseMetric{
@Override
protected Metric getMetric(){ | return new NodalL2SplittedMetric(); |
TreeCmp/TreeCmp | test/treecmp/metric/weighted/RFCWeightMetricTest.java | // Path: src/treecmp/metric/RFClusterMetric.java
// public class RFClusterMetric extends BaseMetric implements Metric{
//
// public static double getRFClusterMetric(Tree t1, Tree t2) {
//
// IdGroup idGroup = TreeUtils.getLeafIdGroup(t1);
//
// BitSet[] bs1 = ClusterDist.RootedTree2BitSetArray(t1, idGroup);
// BitSet[] bs2 = ClusterDist.RootedTree2BitSetArray(t2, idGroup);
//
// int size1 = bs1.length;
// int size2 = bs2.length;
// int hashSetSize=(4*(size1+1))/3;
//
// HashSet<BitSet> hs1=new HashSet<BitSet>(hashSetSize);
//
// for(int i=0;i<size1;i++){
// hs1.add(bs1[i]);
// }
//
// int common=0;
// for(int i=0;i<size2;i++){
// if (hs1.contains(bs2[i]))
// common++;
// }
//
// double dist=((double)size1+(double)size2)*0.5-(double)common;
// return dist;
//
// }
//
//
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// return RFClusterMetric.getRFClusterMetric(t1, t2);
//
// }
// }
| import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import pal.tree.Tree;
import treecmp.metric.RFClusterMetric;
import treecmp.test.util.TreeCreator; | package treecmp.metric.weighted;
class RFCWeightMetricTest {
@BeforeEach
void setUp() {
}
@AfterEach
void tearDown() {
}
@Test
void testGetDistanceForTheSameTreesResult_0() {
RFCWeightMetric instance = new RFCWeightMetric(); | // Path: src/treecmp/metric/RFClusterMetric.java
// public class RFClusterMetric extends BaseMetric implements Metric{
//
// public static double getRFClusterMetric(Tree t1, Tree t2) {
//
// IdGroup idGroup = TreeUtils.getLeafIdGroup(t1);
//
// BitSet[] bs1 = ClusterDist.RootedTree2BitSetArray(t1, idGroup);
// BitSet[] bs2 = ClusterDist.RootedTree2BitSetArray(t2, idGroup);
//
// int size1 = bs1.length;
// int size2 = bs2.length;
// int hashSetSize=(4*(size1+1))/3;
//
// HashSet<BitSet> hs1=new HashSet<BitSet>(hashSetSize);
//
// for(int i=0;i<size1;i++){
// hs1.add(bs1[i]);
// }
//
// int common=0;
// for(int i=0;i<size2;i++){
// if (hs1.contains(bs2[i]))
// common++;
// }
//
// double dist=((double)size1+(double)size2)*0.5-(double)common;
// return dist;
//
// }
//
//
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// return RFClusterMetric.getRFClusterMetric(t1, t2);
//
// }
// }
// Path: test/treecmp/metric/weighted/RFCWeightMetricTest.java
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import pal.tree.Tree;
import treecmp.metric.RFClusterMetric;
import treecmp.test.util.TreeCreator;
package treecmp.metric.weighted;
class RFCWeightMetricTest {
@BeforeEach
void setUp() {
}
@AfterEach
void tearDown() {
}
@Test
void testGetDistanceForTheSameTreesResult_0() {
RFCWeightMetric instance = new RFCWeightMetric(); | RFClusterMetric rc = new RFClusterMetric(); |
TreeCmp/TreeCmp | src/treecmp/spr/SprHeuristicTTMetric.java | // Path: src/treecmp/metric/TripletMetric.java
// public class TripletMetric extends BaseMetric implements Metric {
// private TripletMetric2 tt2;
// public TripletMetric(){
// super();
// tt2 = new TripletMetric2();
// }
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// if (TreeCmpUtils.isBinary(t1, true) && TreeCmpUtils.isBinary(t2, true)) {
// return getDistForBinary(t1, t2);
// }
// //run distance for arbitrary tree in O(n^2) time
// return tt2.getDistance(t1, t2);
//
// }
//
// public double getDistForBinary(Tree t1, Tree t2) {
// IdGroup id1 = TreeUtils.getLeafIdGroup(t1);
// int[][] lcaMatrix1 = TreeCmpUtils.calcLcaMatrix(t1, null);
// int[][] lcaMatrix2 = TreeCmpUtils.calcLcaMatrix(t2, id1);
// int n = lcaMatrix1.length;
// long n_l = (long) n;
// long val_l;
// long commonT = 0;
//
// for (int i = 0; i < n; i++) {
// List<Integer> numList = getPatternNum(i, lcaMatrix1, lcaMatrix2);
// for (Integer val : numList) {
// val_l = (long) val;
// commonT += val_l * (val_l - 1) / 2;
// }
// }
//
// long dist = n_l * (n_l - 1) * (n_l - 2) / 6 - commonT;
// return (double) dist;
// }
//
// class Pattern {
//
// public int a;
// public int b;
//
// public Pattern(int a, int b) {
// this.a = a;
// this.b = b;
// }
//
// @Override
// public int hashCode() {
// return 31 * a + b;
//
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (obj instanceof Pattern) {
// Pattern test = (Pattern) obj;
// if (a == test.a && b == test.b) {
// return true;
// }
// }
// return false;
// }
// }
//
// public List<Integer> getPatternNum(int x, int[][] a, int[][] b) {
//
// int n = a.length;
// int mapSize = (4 * n) / 3;
//
// List<Integer> mList = new ArrayList<Integer>();
//
// Map<Pattern, Integer> patternMap = new HashMap<Pattern, Integer>(mapSize);
// for (int i = 0; i < n; i++) {
// if (i == x) {
// continue;
// }
// Pattern p = new Pattern(a[x][i], b[x][i]);
// Integer num = patternMap.get(p);
// if (num == null) {
// patternMap.put(p, new Integer(1));
// } else {
// patternMap.put(p, num.intValue() + 1);
// }
//
// }
// for (Integer val : patternMap.values()) {
// if (val >= 2) {
// mList.add(val);
// }
// }
// return mList;
// }
//
//
// }
| import treecmp.metric.TripletMetric;
import treecmp.metric.Metric; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class SprHeuristicTTMetric extends SprHeuristicBaseMetric{
@Override
protected Metric getMetric(){ | // Path: src/treecmp/metric/TripletMetric.java
// public class TripletMetric extends BaseMetric implements Metric {
// private TripletMetric2 tt2;
// public TripletMetric(){
// super();
// tt2 = new TripletMetric2();
// }
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// if (TreeCmpUtils.isBinary(t1, true) && TreeCmpUtils.isBinary(t2, true)) {
// return getDistForBinary(t1, t2);
// }
// //run distance for arbitrary tree in O(n^2) time
// return tt2.getDistance(t1, t2);
//
// }
//
// public double getDistForBinary(Tree t1, Tree t2) {
// IdGroup id1 = TreeUtils.getLeafIdGroup(t1);
// int[][] lcaMatrix1 = TreeCmpUtils.calcLcaMatrix(t1, null);
// int[][] lcaMatrix2 = TreeCmpUtils.calcLcaMatrix(t2, id1);
// int n = lcaMatrix1.length;
// long n_l = (long) n;
// long val_l;
// long commonT = 0;
//
// for (int i = 0; i < n; i++) {
// List<Integer> numList = getPatternNum(i, lcaMatrix1, lcaMatrix2);
// for (Integer val : numList) {
// val_l = (long) val;
// commonT += val_l * (val_l - 1) / 2;
// }
// }
//
// long dist = n_l * (n_l - 1) * (n_l - 2) / 6 - commonT;
// return (double) dist;
// }
//
// class Pattern {
//
// public int a;
// public int b;
//
// public Pattern(int a, int b) {
// this.a = a;
// this.b = b;
// }
//
// @Override
// public int hashCode() {
// return 31 * a + b;
//
// }
//
// @Override
// public boolean equals(Object obj) {
// if (obj == this) {
// return true;
// }
// if (obj instanceof Pattern) {
// Pattern test = (Pattern) obj;
// if (a == test.a && b == test.b) {
// return true;
// }
// }
// return false;
// }
// }
//
// public List<Integer> getPatternNum(int x, int[][] a, int[][] b) {
//
// int n = a.length;
// int mapSize = (4 * n) / 3;
//
// List<Integer> mList = new ArrayList<Integer>();
//
// Map<Pattern, Integer> patternMap = new HashMap<Pattern, Integer>(mapSize);
// for (int i = 0; i < n; i++) {
// if (i == x) {
// continue;
// }
// Pattern p = new Pattern(a[x][i], b[x][i]);
// Integer num = patternMap.get(p);
// if (num == null) {
// patternMap.put(p, new Integer(1));
// } else {
// patternMap.put(p, num.intValue() + 1);
// }
//
// }
// for (Integer val : patternMap.values()) {
// if (val >= 2) {
// mList.add(val);
// }
// }
// return mList;
// }
//
//
// }
// Path: src/treecmp/spr/SprHeuristicTTMetric.java
import treecmp.metric.TripletMetric;
import treecmp.metric.Metric;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class SprHeuristicTTMetric extends SprHeuristicBaseMetric{
@Override
protected Metric getMetric(){ | return new TripletMetric(); |
TreeCmp/TreeCmp | src/treecmp/spr/SprHeuristicMastRfcMetric.java | // Path: src/treecmp/metric/RMASTMetric.java
// public class RMASTMetric extends BaseMetric implements Metric {
//
// @Override
// public boolean isRooted() {
// return true;
// }
//
// @Override
// public double getDistance(Tree t1, Tree t2, int... indexes) {
// return Math.max(t1.getExternalNodeCount(), t2.getExternalNodeCount()) - crmast(t1, t2).getRMAST();
// }
//
// public static CRMAST crmast(Tree t1, Tree t2) {
// final int t1Leafs = t1.getExternalNodeCount();
// final int t2Leafs = t2.getExternalNodeCount();
//
// //dynamic programming array: first dimension are nodes from t1, second from t2
// //nodes are ordered according to their numbers: leafs first then internal nodes
// final CRMAST mast = new CRMAST(t1, t2);
//
// //fill values for pairs where at least one of nodes is a leaf
// for (int i=0; i<t1Leafs; i++) {
// final Node leaf1 = t1.getExternalNode(i);
// for (int j=0; j<t2Leafs; j++) {
// final Node leaf2 = t2.getExternalNode(j);
//
// if (leaf1.getIdentifier().equals(leaf2.getIdentifier())) {
// mast.set(i, j, 1);
//
// Node v1 = leaf1;
// do {
// v1 = v1.getParent();
// mast.set(v1, leaf2, 1);
// } while (!v1.isRoot());
//
// Node v2 = leaf2;
// do {
// v2 = v2.getParent();
// mast.set(leaf1, v2, 1);
// } while (!v2.isRoot());
// }
// }
// }
//
// final int[] internalNodeOrder1 = getInternalNodeOrder(t1);
// final int[] internalNodeOrder2 = getInternalNodeOrder(t2);
// //fill values for pairs of internal nodes
// for (int i=0; i<internalNodeOrder1.length; i++) {
// final Node v1 = t1.getInternalNode(internalNodeOrder1[i]);
// for (int j=0; j<internalNodeOrder2.length; j++) {
// final Node v2 = t2.getInternalNode(internalNodeOrder2[j]);
// mast.set(v1, v2, Math.max(diag(v1, t1, v2, t2, mast), match(v1, t1, v2, t2, mast)));
// }
// }
//
// return mast;
// }
//
// private static int diag(Node v1, Tree t1, Node v2, Tree t2, CRMAST mast) {
// int result = 0;
// for (int i=0; i<v2.getChildCount(); i++) {
// final Node child2 = v2.getChild(i);
// result = Math.max(result, mast.getRMAST(v1, child2));
// }
// for (int i=0; i<v1.getChildCount(); i++) {
// final Node child1 = v1.getChild(i);
// result = Math.max(result, mast.getRMAST(child1, v2));
// }
// return result;
// }
//
// //TODO verify proper complexity of match. For two trees all matchings should take O(n^2).
// private static int match(Node v1, Tree t1, Node v2, Tree t2, CRMAST mast) {
// final int v1Children = v1.getChildCount();
// final int v2Children = v2.getChildCount();
// final int size = Math.max(v1Children, v2Children);
// final int[][] w = new int[size][];
// for (int i=0; i<size; i++) {
// w[i] = new int[size];
// }
//
// for (int i=0; i<v1Children; i++) {
// final Node child1 = v1.getChild(i);
// for (int j=0; j<v2Children; j++) {
// final Node child2 = v2.getChild(j);
// w[i][j] = -mast.getRMAST(child1, child2);
// }
// }
//
// final int[] rowSol = new int[size];
// final int[] colSol = new int[size];
// final int[] u = new int[size];
// final int[] v = new int[size];
// return -LapSolver.lap(size, w, rowSol, colSol, u, v);
// }
//
// private static int[] getInternalNodeOrder(Tree t) {
// final int[] order = new int[t.getInternalNodeCount()];
// int qFront = order.length;
// int qEnd = order.length;
//
// //visit internal nodes in bfs order starting from root
// //and grow the order queue from the back
// order[--qEnd] = t.getRoot().getNumber();
// while (qFront > 0) {
// final Node v = t.getInternalNode(order[--qFront]);
// for (int i=0; i<v.getChildCount(); i++) {
// final Node child = v.getChild(i);
// if (!child.isLeaf()) {
// order[--qEnd] = child.getNumber();
// }
// }
// }
// return order;
// }
//
// }
| import treecmp.metric.RMASTMetric;
import treecmp.metric.Metric; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class SprHeuristicMastRfcMetric extends SprHeuristicRfcBaseMetric{
@Override
protected Metric getMetric(){ | // Path: src/treecmp/metric/RMASTMetric.java
// public class RMASTMetric extends BaseMetric implements Metric {
//
// @Override
// public boolean isRooted() {
// return true;
// }
//
// @Override
// public double getDistance(Tree t1, Tree t2, int... indexes) {
// return Math.max(t1.getExternalNodeCount(), t2.getExternalNodeCount()) - crmast(t1, t2).getRMAST();
// }
//
// public static CRMAST crmast(Tree t1, Tree t2) {
// final int t1Leafs = t1.getExternalNodeCount();
// final int t2Leafs = t2.getExternalNodeCount();
//
// //dynamic programming array: first dimension are nodes from t1, second from t2
// //nodes are ordered according to their numbers: leafs first then internal nodes
// final CRMAST mast = new CRMAST(t1, t2);
//
// //fill values for pairs where at least one of nodes is a leaf
// for (int i=0; i<t1Leafs; i++) {
// final Node leaf1 = t1.getExternalNode(i);
// for (int j=0; j<t2Leafs; j++) {
// final Node leaf2 = t2.getExternalNode(j);
//
// if (leaf1.getIdentifier().equals(leaf2.getIdentifier())) {
// mast.set(i, j, 1);
//
// Node v1 = leaf1;
// do {
// v1 = v1.getParent();
// mast.set(v1, leaf2, 1);
// } while (!v1.isRoot());
//
// Node v2 = leaf2;
// do {
// v2 = v2.getParent();
// mast.set(leaf1, v2, 1);
// } while (!v2.isRoot());
// }
// }
// }
//
// final int[] internalNodeOrder1 = getInternalNodeOrder(t1);
// final int[] internalNodeOrder2 = getInternalNodeOrder(t2);
// //fill values for pairs of internal nodes
// for (int i=0; i<internalNodeOrder1.length; i++) {
// final Node v1 = t1.getInternalNode(internalNodeOrder1[i]);
// for (int j=0; j<internalNodeOrder2.length; j++) {
// final Node v2 = t2.getInternalNode(internalNodeOrder2[j]);
// mast.set(v1, v2, Math.max(diag(v1, t1, v2, t2, mast), match(v1, t1, v2, t2, mast)));
// }
// }
//
// return mast;
// }
//
// private static int diag(Node v1, Tree t1, Node v2, Tree t2, CRMAST mast) {
// int result = 0;
// for (int i=0; i<v2.getChildCount(); i++) {
// final Node child2 = v2.getChild(i);
// result = Math.max(result, mast.getRMAST(v1, child2));
// }
// for (int i=0; i<v1.getChildCount(); i++) {
// final Node child1 = v1.getChild(i);
// result = Math.max(result, mast.getRMAST(child1, v2));
// }
// return result;
// }
//
// //TODO verify proper complexity of match. For two trees all matchings should take O(n^2).
// private static int match(Node v1, Tree t1, Node v2, Tree t2, CRMAST mast) {
// final int v1Children = v1.getChildCount();
// final int v2Children = v2.getChildCount();
// final int size = Math.max(v1Children, v2Children);
// final int[][] w = new int[size][];
// for (int i=0; i<size; i++) {
// w[i] = new int[size];
// }
//
// for (int i=0; i<v1Children; i++) {
// final Node child1 = v1.getChild(i);
// for (int j=0; j<v2Children; j++) {
// final Node child2 = v2.getChild(j);
// w[i][j] = -mast.getRMAST(child1, child2);
// }
// }
//
// final int[] rowSol = new int[size];
// final int[] colSol = new int[size];
// final int[] u = new int[size];
// final int[] v = new int[size];
// return -LapSolver.lap(size, w, rowSol, colSol, u, v);
// }
//
// private static int[] getInternalNodeOrder(Tree t) {
// final int[] order = new int[t.getInternalNodeCount()];
// int qFront = order.length;
// int qEnd = order.length;
//
// //visit internal nodes in bfs order starting from root
// //and grow the order queue from the back
// order[--qEnd] = t.getRoot().getNumber();
// while (qFront > 0) {
// final Node v = t.getInternalNode(order[--qFront]);
// for (int i=0; i<v.getChildCount(); i++) {
// final Node child = v.getChild(i);
// if (!child.isLeaf()) {
// order[--qEnd] = child.getNumber();
// }
// }
// }
// return order;
// }
//
// }
// Path: src/treecmp/spr/SprHeuristicMastRfcMetric.java
import treecmp.metric.RMASTMetric;
import treecmp.metric.Metric;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class SprHeuristicMastRfcMetric extends SprHeuristicRfcBaseMetric{
@Override
protected Metric getMetric(){ | return new RMASTMetric(); |
TreeCmp/TreeCmp | src/treecmp/spr/SprHeuristicRFCMetric.java | // Path: src/treecmp/metric/RFClusterMetric.java
// public class RFClusterMetric extends BaseMetric implements Metric{
//
// public static double getRFClusterMetric(Tree t1, Tree t2) {
//
// IdGroup idGroup = TreeUtils.getLeafIdGroup(t1);
//
// BitSet[] bs1 = ClusterDist.RootedTree2BitSetArray(t1, idGroup);
// BitSet[] bs2 = ClusterDist.RootedTree2BitSetArray(t2, idGroup);
//
// int size1 = bs1.length;
// int size2 = bs2.length;
// int hashSetSize=(4*(size1+1))/3;
//
// HashSet<BitSet> hs1=new HashSet<BitSet>(hashSetSize);
//
// for(int i=0;i<size1;i++){
// hs1.add(bs1[i]);
// }
//
// int common=0;
// for(int i=0;i<size2;i++){
// if (hs1.contains(bs2[i]))
// common++;
// }
//
// double dist=((double)size1+(double)size2)*0.5-(double)common;
// return dist;
//
// }
//
//
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// return RFClusterMetric.getRFClusterMetric(t1, t2);
//
// }
// }
| import treecmp.metric.RFClusterMetric;
import treecmp.metric.Metric; | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class SprHeuristicRFCMetric extends SprHeuristicBaseMetric{
@Override
protected Metric getMetric(){ | // Path: src/treecmp/metric/RFClusterMetric.java
// public class RFClusterMetric extends BaseMetric implements Metric{
//
// public static double getRFClusterMetric(Tree t1, Tree t2) {
//
// IdGroup idGroup = TreeUtils.getLeafIdGroup(t1);
//
// BitSet[] bs1 = ClusterDist.RootedTree2BitSetArray(t1, idGroup);
// BitSet[] bs2 = ClusterDist.RootedTree2BitSetArray(t2, idGroup);
//
// int size1 = bs1.length;
// int size2 = bs2.length;
// int hashSetSize=(4*(size1+1))/3;
//
// HashSet<BitSet> hs1=new HashSet<BitSet>(hashSetSize);
//
// for(int i=0;i<size1;i++){
// hs1.add(bs1[i]);
// }
//
// int common=0;
// for(int i=0;i<size2;i++){
// if (hs1.contains(bs2[i]))
// common++;
// }
//
// double dist=((double)size1+(double)size2)*0.5-(double)common;
// return dist;
//
// }
//
//
//
// public double getDistance(Tree t1, Tree t2, int... indexes) {
//
// return RFClusterMetric.getRFClusterMetric(t1, t2);
//
// }
// }
// Path: src/treecmp/spr/SprHeuristicRFCMetric.java
import treecmp.metric.RFClusterMetric;
import treecmp.metric.Metric;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package treecmp.spr;
/**
*
* @author Damian
*/
public class SprHeuristicRFCMetric extends SprHeuristicBaseMetric{
@Override
protected Metric getMetric(){ | return new RFClusterMetric(); |
TreeCmp/TreeCmp | src/treecmp/config/ConfigSettings.java | // Path: src/treecmp/metric/BaseMetric.java
// public abstract class BaseMetric implements Metric{
//
// protected String name;
// protected String commandLineName;
// protected String description;
// protected String unifomFileName;
// protected String yuleFileName;
// protected String alnFileSuffix;
//
// protected IMetircDistrbHolder unifomRandData;
// protected IMetircDistrbHolder yuleRandData;
//
// protected boolean rooted;
// protected boolean weighted;
// protected boolean diffLeafSets;
//
// public boolean isDiffLeafSets() {
// return diffLeafSets;
// }
//
// public void setDiffLeafSets(boolean diffLeafSets) {
// this.diffLeafSets = diffLeafSets;
// }
//
// public boolean isRooted() {
// return rooted;
// }
//
// public void setRooted(boolean rooted) {
// this.rooted = rooted;
// }
//
// public void setWeighted(boolean weighted) {
// this.weighted = weighted;
// }
//
// public boolean isWeighted() {
// return weighted;
// }
// public String getAlnFileSuffix() {
// return alnFileSuffix;
// }
//
// public void setAlnFileSuffix(String alnFileSuffix) {
// this.alnFileSuffix = alnFileSuffix;
// }
//
// public String getUnifomFileName() {
// return unifomFileName;
// }
//
// public void setUnifomFileName(String unifomFileName) {
// this.unifomFileName = unifomFileName;
// }
//
// public String getYuleFileName() {
// return yuleFileName;
// }
//
// public void setYuleFileName(String yuleFileName) {
// this.yuleFileName = yuleFileName;
// }
//
//
// public IMetircDistrbHolder getUnifomRandData() {
// return unifomRandData;
// }
//
//
// public IMetircDistrbHolder getYuleRandData() {
// return yuleRandData;
// }
//
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public BaseMetric() {
// this.rooted = false;
// this.diffLeafSets = false;
// }
//
// public String getCommandLineName() {
// return commandLineName;
// }
//
// public void setCommandLineName(String commandLineName) {
// this.commandLineName = commandLineName;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public abstract double getDistance(Tree t1, Tree t2, int... indexes) ;
// public AlignInfo getAlignment(){
// return null;
// }
//
// private IMetircDistrbHolder parseData(String dataDir, String dataFileName){
//
// MetircDistrbHolder mdh = new MetircDistrbHolder();
//
// String fullPath = dataDir + "/" + dataFileName;
//
// try {
// FileReader fr = new FileReader(fullPath);
// BufferedReader br = new BufferedReader(fr);
// int cnt = 0;
// String line;
// while ((line = br.readLine()) != null){
// cnt++;
// if(cnt > 1){
// MetricDistribution md = new MetricDistribution();
// md.readData(line);
// mdh.insertDistribution(md);
// }
// }
// br.close();
// }
// catch (IOException e) {
// Logger.getLogger(ConfigSettings.class.getName()).log(Level.SEVERE, "Error while reading data file:" + fullPath, e);
// mdh = null;
// }
// return mdh;
// }
//
// public void initData(){
// ConfigSettings config = ConfigSettings.getConfig();
// String dataDir = config.getDataDir();
// if (unifomRandData == null){
// if (unifomFileName != null){
// unifomRandData = parseData(dataDir, unifomFileName);
// }
// }
//
// if (yuleRandData == null){
// if (yuleFileName != null){
// yuleRandData = parseData(dataDir, yuleFileName);
// }
// }
// }
//
// }
| import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import treecmp.metric.BaseMetric; | String uniformFileName = "";
String yuleFileName = "";
String alnFileSuffix = "";
String rooted = "";
String weighted = "";
String diff_leaves = "";
/**
* Update defined metric set
*
*/
NodeList list = doc.getElementsByTagName("metric");
for (int i = 0; i < list.getLength(); i++) {
// Get element
Element element = (Element) list.item(i);
//System.out.println(getTextValue(element, "class"));
className = getTextValue(element, "class");
metricName = getTextValue(element, "name");
commandLineName = getTextValue(element, "command_name");
metricDesc = getTextValue(element, "description");
uniformFileName = getTextValue(element, "unif_data");
yuleFileName = getTextValue(element, "yule_data");
alnFileSuffix = getTextValue(element, "aln_file_suffix");
rooted = getTextValue(element, "rooted");
weighted = getTextValue(element, "weighted");
diff_leaves = getTextValue(element, "diff_leaves");
if (className != null) {
Class cl = Class.forName(className);
//Metric m=(Metric) cl.newInstance(); | // Path: src/treecmp/metric/BaseMetric.java
// public abstract class BaseMetric implements Metric{
//
// protected String name;
// protected String commandLineName;
// protected String description;
// protected String unifomFileName;
// protected String yuleFileName;
// protected String alnFileSuffix;
//
// protected IMetircDistrbHolder unifomRandData;
// protected IMetircDistrbHolder yuleRandData;
//
// protected boolean rooted;
// protected boolean weighted;
// protected boolean diffLeafSets;
//
// public boolean isDiffLeafSets() {
// return diffLeafSets;
// }
//
// public void setDiffLeafSets(boolean diffLeafSets) {
// this.diffLeafSets = diffLeafSets;
// }
//
// public boolean isRooted() {
// return rooted;
// }
//
// public void setRooted(boolean rooted) {
// this.rooted = rooted;
// }
//
// public void setWeighted(boolean weighted) {
// this.weighted = weighted;
// }
//
// public boolean isWeighted() {
// return weighted;
// }
// public String getAlnFileSuffix() {
// return alnFileSuffix;
// }
//
// public void setAlnFileSuffix(String alnFileSuffix) {
// this.alnFileSuffix = alnFileSuffix;
// }
//
// public String getUnifomFileName() {
// return unifomFileName;
// }
//
// public void setUnifomFileName(String unifomFileName) {
// this.unifomFileName = unifomFileName;
// }
//
// public String getYuleFileName() {
// return yuleFileName;
// }
//
// public void setYuleFileName(String yuleFileName) {
// this.yuleFileName = yuleFileName;
// }
//
//
// public IMetircDistrbHolder getUnifomRandData() {
// return unifomRandData;
// }
//
//
// public IMetircDistrbHolder getYuleRandData() {
// return yuleRandData;
// }
//
//
// public String getDescription() {
// return description;
// }
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public BaseMetric() {
// this.rooted = false;
// this.diffLeafSets = false;
// }
//
// public String getCommandLineName() {
// return commandLineName;
// }
//
// public void setCommandLineName(String commandLineName) {
// this.commandLineName = commandLineName;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public abstract double getDistance(Tree t1, Tree t2, int... indexes) ;
// public AlignInfo getAlignment(){
// return null;
// }
//
// private IMetircDistrbHolder parseData(String dataDir, String dataFileName){
//
// MetircDistrbHolder mdh = new MetircDistrbHolder();
//
// String fullPath = dataDir + "/" + dataFileName;
//
// try {
// FileReader fr = new FileReader(fullPath);
// BufferedReader br = new BufferedReader(fr);
// int cnt = 0;
// String line;
// while ((line = br.readLine()) != null){
// cnt++;
// if(cnt > 1){
// MetricDistribution md = new MetricDistribution();
// md.readData(line);
// mdh.insertDistribution(md);
// }
// }
// br.close();
// }
// catch (IOException e) {
// Logger.getLogger(ConfigSettings.class.getName()).log(Level.SEVERE, "Error while reading data file:" + fullPath, e);
// mdh = null;
// }
// return mdh;
// }
//
// public void initData(){
// ConfigSettings config = ConfigSettings.getConfig();
// String dataDir = config.getDataDir();
// if (unifomRandData == null){
// if (unifomFileName != null){
// unifomRandData = parseData(dataDir, unifomFileName);
// }
// }
//
// if (yuleRandData == null){
// if (yuleFileName != null){
// yuleRandData = parseData(dataDir, yuleFileName);
// }
// }
// }
//
// }
// Path: src/treecmp/config/ConfigSettings.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import treecmp.metric.BaseMetric;
String uniformFileName = "";
String yuleFileName = "";
String alnFileSuffix = "";
String rooted = "";
String weighted = "";
String diff_leaves = "";
/**
* Update defined metric set
*
*/
NodeList list = doc.getElementsByTagName("metric");
for (int i = 0; i < list.getLength(); i++) {
// Get element
Element element = (Element) list.item(i);
//System.out.println(getTextValue(element, "class"));
className = getTextValue(element, "class");
metricName = getTextValue(element, "name");
commandLineName = getTextValue(element, "command_name");
metricDesc = getTextValue(element, "description");
uniformFileName = getTextValue(element, "unif_data");
yuleFileName = getTextValue(element, "yule_data");
alnFileSuffix = getTextValue(element, "aln_file_suffix");
rooted = getTextValue(element, "rooted");
weighted = getTextValue(element, "weighted");
diff_leaves = getTextValue(element, "diff_leaves");
if (className != null) {
Class cl = Class.forName(className);
//Metric m=(Metric) cl.newInstance(); | BaseMetric m = (BaseMetric) cl.newInstance(); |
vert-x3/vertx-jdbc-client | src/main/java/io/vertx/ext/sql/SQLClient.java | // Path: src/main/java/io/vertx/ext/sql/impl/RowStreamWrapper.java
// public class RowStreamWrapper implements SQLRowStream {
//
// private final SQLConnection connection;
// private final SQLRowStream rowStream;
//
// public RowStreamWrapper(SQLConnection connection, SQLRowStream rowStream) {
// this.connection = connection;
// this.rowStream = rowStream;
// }
//
// private void closeConnection(Handler<AsyncResult<Void>> handler) {
// connection.close(handler);
// }
//
// @Override
// public SQLRowStream exceptionHandler(Handler<Throwable> handler) {
// if (handler == null) {
// rowStream.exceptionHandler(h1 -> closeConnection(h2 -> {}));
// } else {
// rowStream.exceptionHandler(h1 -> closeConnection(h2 -> handler.handle(h1)));
// }
// return this;
// }
//
// @Override
// public SQLRowStream handler(Handler<JsonArray> handler) {
// rowStream.handler(handler);
// return this;
// }
//
// @Override
// public SQLRowStream fetch(long amount) {
// rowStream.fetch(amount);
// return this;
// }
//
// @Override
// public SQLRowStream pause() {
// rowStream.pause();
// return this;
// }
//
// @Override
// public SQLRowStream resume() {
// rowStream.resume();
// return this;
// }
//
// @Override
// public SQLRowStream endHandler(Handler<Void> endHandler) {
// if (endHandler == null) {
// rowStream.endHandler(h1 -> closeConnection(h2 -> {}));
// } else {
// rowStream.endHandler(h1 -> closeConnection(h2 -> endHandler.handle(h1)));
// }
// return this;
// }
//
// @Override
// public int column(String name) {
// return rowStream.column(name);
// }
//
// @Override
// public List<String> columns() {
// return rowStream.columns();
// }
//
// @Override
// public SQLRowStream resultSetClosedHandler(Handler<Void> handler) {
// rowStream.resultSetClosedHandler(handler);
// return this;
// }
//
// @Override
// public void moreResults() {
// rowStream.moreResults();
// }
//
// @Override
// public void close() {
// close(null);
// }
//
// @Override
// public void close(Handler<AsyncResult<Void>> handler) {
// rowStream.close(h1 -> closeConnection(h2 -> {
// if (handler != null) {
// handler.handle(h1);
// }
// }));
// }
// }
| import io.vertx.codegen.annotations.Fluent;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.json.JsonArray;
import io.vertx.ext.sql.impl.RowStreamWrapper; | return this;
}
/**
* Executes the given SQL <code>SELECT</code> statement which returns the results of the query as a read stream.
*
* @param sql the SQL to execute. For example <code>SELECT * FROM table ...</code>.
* @param handler the handler which is called once the operation completes. It will return a {@code SQLRowStream}.
*
* @see java.sql.Statement#executeQuery(String)
* @see java.sql.PreparedStatement#executeQuery(String)
*/
@Fluent
@Override
default SQLClient queryStream(String sql, Handler<AsyncResult<SQLRowStream>> handler) {
getConnection(getConnection -> {
if (getConnection.failed()) {
handler.handle(Future.failedFuture(getConnection.cause()));
} else {
final SQLConnection conn = getConnection.result();
conn.queryStream(sql, query -> {
if (query.failed()) {
conn.close(close -> {
if (close.failed()) {
handler.handle(Future.failedFuture(close.cause()));
} else {
handler.handle(Future.failedFuture(query.cause()));
}
});
} else { | // Path: src/main/java/io/vertx/ext/sql/impl/RowStreamWrapper.java
// public class RowStreamWrapper implements SQLRowStream {
//
// private final SQLConnection connection;
// private final SQLRowStream rowStream;
//
// public RowStreamWrapper(SQLConnection connection, SQLRowStream rowStream) {
// this.connection = connection;
// this.rowStream = rowStream;
// }
//
// private void closeConnection(Handler<AsyncResult<Void>> handler) {
// connection.close(handler);
// }
//
// @Override
// public SQLRowStream exceptionHandler(Handler<Throwable> handler) {
// if (handler == null) {
// rowStream.exceptionHandler(h1 -> closeConnection(h2 -> {}));
// } else {
// rowStream.exceptionHandler(h1 -> closeConnection(h2 -> handler.handle(h1)));
// }
// return this;
// }
//
// @Override
// public SQLRowStream handler(Handler<JsonArray> handler) {
// rowStream.handler(handler);
// return this;
// }
//
// @Override
// public SQLRowStream fetch(long amount) {
// rowStream.fetch(amount);
// return this;
// }
//
// @Override
// public SQLRowStream pause() {
// rowStream.pause();
// return this;
// }
//
// @Override
// public SQLRowStream resume() {
// rowStream.resume();
// return this;
// }
//
// @Override
// public SQLRowStream endHandler(Handler<Void> endHandler) {
// if (endHandler == null) {
// rowStream.endHandler(h1 -> closeConnection(h2 -> {}));
// } else {
// rowStream.endHandler(h1 -> closeConnection(h2 -> endHandler.handle(h1)));
// }
// return this;
// }
//
// @Override
// public int column(String name) {
// return rowStream.column(name);
// }
//
// @Override
// public List<String> columns() {
// return rowStream.columns();
// }
//
// @Override
// public SQLRowStream resultSetClosedHandler(Handler<Void> handler) {
// rowStream.resultSetClosedHandler(handler);
// return this;
// }
//
// @Override
// public void moreResults() {
// rowStream.moreResults();
// }
//
// @Override
// public void close() {
// close(null);
// }
//
// @Override
// public void close(Handler<AsyncResult<Void>> handler) {
// rowStream.close(h1 -> closeConnection(h2 -> {
// if (handler != null) {
// handler.handle(h1);
// }
// }));
// }
// }
// Path: src/main/java/io/vertx/ext/sql/SQLClient.java
import io.vertx.codegen.annotations.Fluent;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.json.JsonArray;
import io.vertx.ext.sql.impl.RowStreamWrapper;
return this;
}
/**
* Executes the given SQL <code>SELECT</code> statement which returns the results of the query as a read stream.
*
* @param sql the SQL to execute. For example <code>SELECT * FROM table ...</code>.
* @param handler the handler which is called once the operation completes. It will return a {@code SQLRowStream}.
*
* @see java.sql.Statement#executeQuery(String)
* @see java.sql.PreparedStatement#executeQuery(String)
*/
@Fluent
@Override
default SQLClient queryStream(String sql, Handler<AsyncResult<SQLRowStream>> handler) {
getConnection(getConnection -> {
if (getConnection.failed()) {
handler.handle(Future.failedFuture(getConnection.cause()));
} else {
final SQLConnection conn = getConnection.result();
conn.queryStream(sql, query -> {
if (query.failed()) {
conn.close(close -> {
if (close.failed()) {
handler.handle(Future.failedFuture(close.cause()));
} else {
handler.handle(Future.failedFuture(query.cause()));
}
});
} else { | SQLRowStream wrapped = new RowStreamWrapper(conn, query.result()); |
vert-x3/vertx-jdbc-client | src/test/java/io/vertx/ext/jdbc/spi/impl/AgroalCPDataSourceProviderTest.java | // Path: src/test/java/io/vertx/ThreadLeakCheckerRule.java
// public class ThreadLeakCheckerRule implements TestRule {
//
// private final Predicate<Thread> predicate;
//
// public ThreadLeakCheckerRule() {
// this(t ->
// t.getName().equals("vertx-jdbc-service-get-connection-thread") ||
// t.getName().startsWith("C3P0PooledConnectionPoolManager")
// );
// }
//
// public ThreadLeakCheckerRule(Predicate<Thread> predicate) {
// this.predicate = predicate;
// }
//
// @Override
// public Statement apply(Statement statement, Description description) {
// return new Statement() {
// @Override
// public void evaluate() throws Throwable {
// check("before");
// statement.evaluate();
// check("after");
// }
// };
// }
//
// private void check(String when) {
// long start = System.nanoTime(), stop;
// List<Thread> threads;
// for (; ; ) {
// // Make a check
// threads = findThreads(predicate);
// if (threads.isEmpty()) {
// return;
// }
// stop = System.nanoTime();
// if (SECONDS.convert(stop - start, NANOSECONDS) >= 5) {
// break;
// } else {
// try {
// MILLISECONDS.sleep(10);
// } catch (InterruptedException e) {
// Thread.currentThread().interrupt();
// break;
// }
// }
// }
// StringBuilder msg = new StringBuilder(threads.stream()
// .map(t -> t.getName() + ": state=" + t.getState().name() + "/alive=" + t.isAlive())
// .collect(Collectors.joining(", ", "Unexpected threads " + when + " test:", ".")));
// ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
// for (ThreadInfo ti : threadMxBean.dumpAllThreads(true, true)) {
// msg.append(System.getProperty("line.separator")).append(ti.toString());
// }
// fail(msg.toString());
// }
//
// public static List<Thread> findThreads(Predicate<Thread> predicate) {
// return Thread.getAllStackTraces()
// .keySet()
// .stream()
// .filter(predicate)
// .collect(Collectors.toList());
// }
// }
| import io.vertx.ThreadLeakCheckerRule;
import io.vertx.core.json.JsonObject;
import org.junit.Rule;
import org.junit.Test;
import javax.sql.DataSource;
import java.sql.SQLException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; | package io.vertx.ext.jdbc.spi.impl;
/**
* Checks the behavior of {@link AgroalCPDataSourceProvider}.
*/
public class AgroalCPDataSourceProviderTest {
@Rule | // Path: src/test/java/io/vertx/ThreadLeakCheckerRule.java
// public class ThreadLeakCheckerRule implements TestRule {
//
// private final Predicate<Thread> predicate;
//
// public ThreadLeakCheckerRule() {
// this(t ->
// t.getName().equals("vertx-jdbc-service-get-connection-thread") ||
// t.getName().startsWith("C3P0PooledConnectionPoolManager")
// );
// }
//
// public ThreadLeakCheckerRule(Predicate<Thread> predicate) {
// this.predicate = predicate;
// }
//
// @Override
// public Statement apply(Statement statement, Description description) {
// return new Statement() {
// @Override
// public void evaluate() throws Throwable {
// check("before");
// statement.evaluate();
// check("after");
// }
// };
// }
//
// private void check(String when) {
// long start = System.nanoTime(), stop;
// List<Thread> threads;
// for (; ; ) {
// // Make a check
// threads = findThreads(predicate);
// if (threads.isEmpty()) {
// return;
// }
// stop = System.nanoTime();
// if (SECONDS.convert(stop - start, NANOSECONDS) >= 5) {
// break;
// } else {
// try {
// MILLISECONDS.sleep(10);
// } catch (InterruptedException e) {
// Thread.currentThread().interrupt();
// break;
// }
// }
// }
// StringBuilder msg = new StringBuilder(threads.stream()
// .map(t -> t.getName() + ": state=" + t.getState().name() + "/alive=" + t.isAlive())
// .collect(Collectors.joining(", ", "Unexpected threads " + when + " test:", ".")));
// ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
// for (ThreadInfo ti : threadMxBean.dumpAllThreads(true, true)) {
// msg.append(System.getProperty("line.separator")).append(ti.toString());
// }
// fail(msg.toString());
// }
//
// public static List<Thread> findThreads(Predicate<Thread> predicate) {
// return Thread.getAllStackTraces()
// .keySet()
// .stream()
// .filter(predicate)
// .collect(Collectors.toList());
// }
// }
// Path: src/test/java/io/vertx/ext/jdbc/spi/impl/AgroalCPDataSourceProviderTest.java
import io.vertx.ThreadLeakCheckerRule;
import io.vertx.core.json.JsonObject;
import org.junit.Rule;
import org.junit.Test;
import javax.sql.DataSource;
import java.sql.SQLException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
package io.vertx.ext.jdbc.spi.impl;
/**
* Checks the behavior of {@link AgroalCPDataSourceProvider}.
*/
public class AgroalCPDataSourceProviderTest {
@Rule | public ThreadLeakCheckerRule rule = new ThreadLeakCheckerRule(); |
vert-x3/vertx-jdbc-client | src/main/java/io/vertx/ext/jdbc/impl/actions/JDBCAutoCommit.java | // Path: src/main/java/io/vertx/ext/sql/SQLOptions.java
// @DataObject(generateConverter = true)
// public class SQLOptions {
//
// // connection
// private boolean readOnly;
// private String catalog;
// private TransactionIsolation transactionIsolation;
// private ResultSetType resultSetType;
// private ResultSetConcurrency resultSetConcurrency;
// // backwards compatibility
// private boolean autoGeneratedKeys = true;
// private JsonArray autoGeneratedKeysIndexes;
// private String schema;
// // statement
// private int queryTimeout;
// private int maxRows;
// // resultset
// private FetchDirection fetchDirection;
// private int fetchSize;
//
// /**
// * Default constructor
// */
// public SQLOptions() {
// }
//
// /**
// * Copy constructor
// *
// * @param other the result to copy
// */
// public SQLOptions(SQLOptions other) {
// this.readOnly = other.isReadOnly();
// this.catalog = other.getCatalog();
// this.transactionIsolation = other.getTransactionIsolation();
// this.resultSetType = other.getResultSetType();
// this.resultSetConcurrency = other.getResultSetConcurrency();
// this.autoGeneratedKeys = other.isAutoGeneratedKeys();
// this.autoGeneratedKeysIndexes = other.getAutoGeneratedKeysIndexes();
// this.schema = other.getSchema();
// this.queryTimeout = other.getQueryTimeout();
// this.fetchDirection = other.getFetchDirection();
// this.fetchSize = other.getFetchSize();
// this.maxRows = other.getMaxRows();
// }
//
// /**
// * Constructor from JSON
// *
// * @param json the json
// */
// public SQLOptions(JsonObject json) {
// SQLOptionsConverter.fromJson(json, this);
// }
//
// public boolean isReadOnly() {
// return readOnly;
// }
//
// public SQLOptions setReadOnly(boolean readOnly) {
// this.readOnly = readOnly;
// return this;
// }
//
// public String getCatalog() {
// return catalog;
// }
//
// public SQLOptions setCatalog(String catalog) {
// this.catalog = catalog;
// return this;
// }
//
// public TransactionIsolation getTransactionIsolation() {
// return transactionIsolation;
// }
//
// public SQLOptions setTransactionIsolation(TransactionIsolation transactionIsolation) {
// this.transactionIsolation = transactionIsolation;
// return this;
// }
//
// public ResultSetType getResultSetType() {
// return resultSetType;
// }
//
// public SQLOptions setResultSetType(ResultSetType resultSetType) {
// this.resultSetType = resultSetType;
// return this;
// }
//
// public ResultSetConcurrency getResultSetConcurrency() {
// return resultSetConcurrency;
// }
//
// public SQLOptions setResultSetConcurrency(ResultSetConcurrency resultSetConcurrency) {
// this.resultSetConcurrency = resultSetConcurrency;
// return this;
// }
//
// public boolean isAutoGeneratedKeys() {
// return autoGeneratedKeys;
// }
//
// public SQLOptions setAutoGeneratedKeys(boolean autoGeneratedKeys) {
// this.autoGeneratedKeys = autoGeneratedKeys;
// return this;
// }
//
// public String getSchema() {
// return schema;
// }
//
// public SQLOptions setSchema(String schema) {
// this.schema = schema;
// return this;
// }
//
// public int getQueryTimeout() {
// return queryTimeout;
// }
//
// public SQLOptions setQueryTimeout(int queryTimeout) {
// this.queryTimeout = queryTimeout;
// return this;
// }
//
// public FetchDirection getFetchDirection() {
// return fetchDirection;
// }
//
// public SQLOptions setFetchDirection(FetchDirection fetchDirection) {
// this.fetchDirection = fetchDirection;
// return this;
// }
//
// public int getFetchSize() {
// return fetchSize;
// }
//
// public SQLOptions setFetchSize(int fetchSize) {
// this.fetchSize = fetchSize;
// return this;
// }
//
// public JsonArray getAutoGeneratedKeysIndexes() {
// return autoGeneratedKeysIndexes;
// }
//
// public SQLOptions setAutoGeneratedKeysIndexes(JsonArray autoGeneratedKeysIndexes) {
// this.autoGeneratedKeysIndexes = autoGeneratedKeysIndexes;
// return this;
// }
//
// public int getMaxRows() {
// return maxRows;
// }
//
// public SQLOptions setMaxRows(int maxRows) {
// this.maxRows = maxRows;
// return this;
// }
// }
| import io.vertx.ext.sql.SQLOptions;
import java.sql.Connection;
import java.sql.SQLException; | /*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.ext.jdbc.impl.actions;
/**
* @author <a href="mailto:[email protected]">Nick Scavelli</a>
*/
public class JDBCAutoCommit extends AbstractJDBCAction<Void> {
private boolean autoCommit;
| // Path: src/main/java/io/vertx/ext/sql/SQLOptions.java
// @DataObject(generateConverter = true)
// public class SQLOptions {
//
// // connection
// private boolean readOnly;
// private String catalog;
// private TransactionIsolation transactionIsolation;
// private ResultSetType resultSetType;
// private ResultSetConcurrency resultSetConcurrency;
// // backwards compatibility
// private boolean autoGeneratedKeys = true;
// private JsonArray autoGeneratedKeysIndexes;
// private String schema;
// // statement
// private int queryTimeout;
// private int maxRows;
// // resultset
// private FetchDirection fetchDirection;
// private int fetchSize;
//
// /**
// * Default constructor
// */
// public SQLOptions() {
// }
//
// /**
// * Copy constructor
// *
// * @param other the result to copy
// */
// public SQLOptions(SQLOptions other) {
// this.readOnly = other.isReadOnly();
// this.catalog = other.getCatalog();
// this.transactionIsolation = other.getTransactionIsolation();
// this.resultSetType = other.getResultSetType();
// this.resultSetConcurrency = other.getResultSetConcurrency();
// this.autoGeneratedKeys = other.isAutoGeneratedKeys();
// this.autoGeneratedKeysIndexes = other.getAutoGeneratedKeysIndexes();
// this.schema = other.getSchema();
// this.queryTimeout = other.getQueryTimeout();
// this.fetchDirection = other.getFetchDirection();
// this.fetchSize = other.getFetchSize();
// this.maxRows = other.getMaxRows();
// }
//
// /**
// * Constructor from JSON
// *
// * @param json the json
// */
// public SQLOptions(JsonObject json) {
// SQLOptionsConverter.fromJson(json, this);
// }
//
// public boolean isReadOnly() {
// return readOnly;
// }
//
// public SQLOptions setReadOnly(boolean readOnly) {
// this.readOnly = readOnly;
// return this;
// }
//
// public String getCatalog() {
// return catalog;
// }
//
// public SQLOptions setCatalog(String catalog) {
// this.catalog = catalog;
// return this;
// }
//
// public TransactionIsolation getTransactionIsolation() {
// return transactionIsolation;
// }
//
// public SQLOptions setTransactionIsolation(TransactionIsolation transactionIsolation) {
// this.transactionIsolation = transactionIsolation;
// return this;
// }
//
// public ResultSetType getResultSetType() {
// return resultSetType;
// }
//
// public SQLOptions setResultSetType(ResultSetType resultSetType) {
// this.resultSetType = resultSetType;
// return this;
// }
//
// public ResultSetConcurrency getResultSetConcurrency() {
// return resultSetConcurrency;
// }
//
// public SQLOptions setResultSetConcurrency(ResultSetConcurrency resultSetConcurrency) {
// this.resultSetConcurrency = resultSetConcurrency;
// return this;
// }
//
// public boolean isAutoGeneratedKeys() {
// return autoGeneratedKeys;
// }
//
// public SQLOptions setAutoGeneratedKeys(boolean autoGeneratedKeys) {
// this.autoGeneratedKeys = autoGeneratedKeys;
// return this;
// }
//
// public String getSchema() {
// return schema;
// }
//
// public SQLOptions setSchema(String schema) {
// this.schema = schema;
// return this;
// }
//
// public int getQueryTimeout() {
// return queryTimeout;
// }
//
// public SQLOptions setQueryTimeout(int queryTimeout) {
// this.queryTimeout = queryTimeout;
// return this;
// }
//
// public FetchDirection getFetchDirection() {
// return fetchDirection;
// }
//
// public SQLOptions setFetchDirection(FetchDirection fetchDirection) {
// this.fetchDirection = fetchDirection;
// return this;
// }
//
// public int getFetchSize() {
// return fetchSize;
// }
//
// public SQLOptions setFetchSize(int fetchSize) {
// this.fetchSize = fetchSize;
// return this;
// }
//
// public JsonArray getAutoGeneratedKeysIndexes() {
// return autoGeneratedKeysIndexes;
// }
//
// public SQLOptions setAutoGeneratedKeysIndexes(JsonArray autoGeneratedKeysIndexes) {
// this.autoGeneratedKeysIndexes = autoGeneratedKeysIndexes;
// return this;
// }
//
// public int getMaxRows() {
// return maxRows;
// }
//
// public SQLOptions setMaxRows(int maxRows) {
// this.maxRows = maxRows;
// return this;
// }
// }
// Path: src/main/java/io/vertx/ext/jdbc/impl/actions/JDBCAutoCommit.java
import io.vertx.ext.sql.SQLOptions;
import java.sql.Connection;
import java.sql.SQLException;
/*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.ext.jdbc.impl.actions;
/**
* @author <a href="mailto:[email protected]">Nick Scavelli</a>
*/
public class JDBCAutoCommit extends AbstractJDBCAction<Void> {
private boolean autoCommit;
| public JDBCAutoCommit(SQLOptions options, boolean autoCommit) { |
vert-x3/vertx-jdbc-client | src/main/java/io/vertx/ext/jdbc/spi/JDBCColumnDescriptorProvider.java | // Path: src/main/java/io/vertx/jdbcclient/impl/actions/JDBCColumnDescriptor.java
// public class JDBCColumnDescriptor implements ColumnDescriptor {
//
// private final String columnLabel;
// private final JDBCTypeWrapper jdbcTypeWrapper;
//
// private JDBCColumnDescriptor(String columnLabel, JDBCTypeWrapper jdbcTypeWrapper) {
// this.columnLabel = columnLabel;
// this.jdbcTypeWrapper = jdbcTypeWrapper;
// }
//
// @Override
// public String name() {
// return columnLabel;
// }
//
// @Override
// public boolean isArray() {
// return jdbcType() == JDBCType.ARRAY;
// }
//
// @Override
// public String typeName() {
// return jdbcTypeWrapper.vendorTypeName();
// }
//
// /**
// * Use {@link #jdbcTypeWrapper()} when converting an advanced data type depending on the specific database
// *
// * @return the most appropriate {@code JDBCType} or {@code null} if it is advanced type of specific database
// */
// @Override
// public JDBCType jdbcType() {
// return jdbcTypeWrapper.jdbcType();
// }
//
// /**
// * @return the jdbc type wrapper
// * @see JDBCTypeWrapper
// */
// public JDBCTypeWrapper jdbcTypeWrapper() {
// return this.jdbcTypeWrapper;
// }
//
// @Override
// public String toString() {
// return "JDBCColumnDescriptor[columnName=(" + columnLabel + "), jdbcTypeWrapper=(" + jdbcTypeWrapper + ")]";
// }
//
// public static JDBCColumnDescriptor create(JDBCPropertyAccessor<String> columnLabel,
// JDBCPropertyAccessor<Integer> vendorTypeNumber,
// JDBCPropertyAccessor<String> vendorTypeName,
// JDBCPropertyAccessor<String> vendorTypeClassName) throws SQLException {
// return new JDBCColumnDescriptor(columnLabel.get(), JDBCTypeWrapper.of(vendorTypeNumber.get(), vendorTypeName.get(),
// vendorTypeClassName.get()));
// }
//
// public static JDBCColumnDescriptor wrap(JDBCType jdbcType) {
// return new JDBCColumnDescriptor(null, JDBCTypeWrapper.of(jdbcType));
// }
//
// }
//
// Path: src/main/java/io/vertx/jdbcclient/impl/actions/JDBCPropertyAccessor.java
// public interface JDBCPropertyAccessor<T> {
//
// Logger LOG = LoggerFactory.getLogger(JDBCColumnDescriptor.class);
//
// T get() throws SQLException;
//
// static <T> JDBCPropertyAccessor<T> create(JDBCPropertyAccessor<T> accessor) {
// return create(accessor, null);
// }
//
// static <T> JDBCPropertyAccessor<T> create(JDBCPropertyAccessor<T> accessor, T fallbackIfUnsupported) {
// return () -> {
// try {
// return accessor.get();
// } catch (SQLFeatureNotSupportedException e) {
// LOG.debug("Unsupported access properties in SQL metadata", e);
// return fallbackIfUnsupported;
// }
// };
// }
//
// static JDBCPropertyAccessor<Integer> jdbcType(JDBCPropertyAccessor<Integer> accessor) {
// return create(accessor, JDBCType.OTHER.getVendorTypeNumber());
// }
//
// }
| import io.vertx.jdbcclient.impl.actions.JDBCColumnDescriptor;
import io.vertx.jdbcclient.impl.actions.JDBCPropertyAccessor;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException; | /*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.ext.jdbc.spi;
/**
* A shortcut provider that get a column information in the runtime SQL result or parameter metadata
*
* @since 4.2.2
*/
@FunctionalInterface
public interface JDBCColumnDescriptorProvider {
/**
* Create provider by parameter statement
*
* @param statement the prepared statement
* @return a new {@code JDBCTypeProvider} instance
* @see java.sql.PreparedStatement
*/
static JDBCColumnDescriptorProvider fromParameter(PreparedStatement statement) { | // Path: src/main/java/io/vertx/jdbcclient/impl/actions/JDBCColumnDescriptor.java
// public class JDBCColumnDescriptor implements ColumnDescriptor {
//
// private final String columnLabel;
// private final JDBCTypeWrapper jdbcTypeWrapper;
//
// private JDBCColumnDescriptor(String columnLabel, JDBCTypeWrapper jdbcTypeWrapper) {
// this.columnLabel = columnLabel;
// this.jdbcTypeWrapper = jdbcTypeWrapper;
// }
//
// @Override
// public String name() {
// return columnLabel;
// }
//
// @Override
// public boolean isArray() {
// return jdbcType() == JDBCType.ARRAY;
// }
//
// @Override
// public String typeName() {
// return jdbcTypeWrapper.vendorTypeName();
// }
//
// /**
// * Use {@link #jdbcTypeWrapper()} when converting an advanced data type depending on the specific database
// *
// * @return the most appropriate {@code JDBCType} or {@code null} if it is advanced type of specific database
// */
// @Override
// public JDBCType jdbcType() {
// return jdbcTypeWrapper.jdbcType();
// }
//
// /**
// * @return the jdbc type wrapper
// * @see JDBCTypeWrapper
// */
// public JDBCTypeWrapper jdbcTypeWrapper() {
// return this.jdbcTypeWrapper;
// }
//
// @Override
// public String toString() {
// return "JDBCColumnDescriptor[columnName=(" + columnLabel + "), jdbcTypeWrapper=(" + jdbcTypeWrapper + ")]";
// }
//
// public static JDBCColumnDescriptor create(JDBCPropertyAccessor<String> columnLabel,
// JDBCPropertyAccessor<Integer> vendorTypeNumber,
// JDBCPropertyAccessor<String> vendorTypeName,
// JDBCPropertyAccessor<String> vendorTypeClassName) throws SQLException {
// return new JDBCColumnDescriptor(columnLabel.get(), JDBCTypeWrapper.of(vendorTypeNumber.get(), vendorTypeName.get(),
// vendorTypeClassName.get()));
// }
//
// public static JDBCColumnDescriptor wrap(JDBCType jdbcType) {
// return new JDBCColumnDescriptor(null, JDBCTypeWrapper.of(jdbcType));
// }
//
// }
//
// Path: src/main/java/io/vertx/jdbcclient/impl/actions/JDBCPropertyAccessor.java
// public interface JDBCPropertyAccessor<T> {
//
// Logger LOG = LoggerFactory.getLogger(JDBCColumnDescriptor.class);
//
// T get() throws SQLException;
//
// static <T> JDBCPropertyAccessor<T> create(JDBCPropertyAccessor<T> accessor) {
// return create(accessor, null);
// }
//
// static <T> JDBCPropertyAccessor<T> create(JDBCPropertyAccessor<T> accessor, T fallbackIfUnsupported) {
// return () -> {
// try {
// return accessor.get();
// } catch (SQLFeatureNotSupportedException e) {
// LOG.debug("Unsupported access properties in SQL metadata", e);
// return fallbackIfUnsupported;
// }
// };
// }
//
// static JDBCPropertyAccessor<Integer> jdbcType(JDBCPropertyAccessor<Integer> accessor) {
// return create(accessor, JDBCType.OTHER.getVendorTypeNumber());
// }
//
// }
// Path: src/main/java/io/vertx/ext/jdbc/spi/JDBCColumnDescriptorProvider.java
import io.vertx.jdbcclient.impl.actions.JDBCColumnDescriptor;
import io.vertx.jdbcclient.impl.actions.JDBCPropertyAccessor;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
/*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.ext.jdbc.spi;
/**
* A shortcut provider that get a column information in the runtime SQL result or parameter metadata
*
* @since 4.2.2
*/
@FunctionalInterface
public interface JDBCColumnDescriptorProvider {
/**
* Create provider by parameter statement
*
* @param statement the prepared statement
* @return a new {@code JDBCTypeProvider} instance
* @see java.sql.PreparedStatement
*/
static JDBCColumnDescriptorProvider fromParameter(PreparedStatement statement) { | return col -> JDBCColumnDescriptor.create(() -> null, |
vert-x3/vertx-jdbc-client | src/main/java/io/vertx/ext/jdbc/spi/JDBCColumnDescriptorProvider.java | // Path: src/main/java/io/vertx/jdbcclient/impl/actions/JDBCColumnDescriptor.java
// public class JDBCColumnDescriptor implements ColumnDescriptor {
//
// private final String columnLabel;
// private final JDBCTypeWrapper jdbcTypeWrapper;
//
// private JDBCColumnDescriptor(String columnLabel, JDBCTypeWrapper jdbcTypeWrapper) {
// this.columnLabel = columnLabel;
// this.jdbcTypeWrapper = jdbcTypeWrapper;
// }
//
// @Override
// public String name() {
// return columnLabel;
// }
//
// @Override
// public boolean isArray() {
// return jdbcType() == JDBCType.ARRAY;
// }
//
// @Override
// public String typeName() {
// return jdbcTypeWrapper.vendorTypeName();
// }
//
// /**
// * Use {@link #jdbcTypeWrapper()} when converting an advanced data type depending on the specific database
// *
// * @return the most appropriate {@code JDBCType} or {@code null} if it is advanced type of specific database
// */
// @Override
// public JDBCType jdbcType() {
// return jdbcTypeWrapper.jdbcType();
// }
//
// /**
// * @return the jdbc type wrapper
// * @see JDBCTypeWrapper
// */
// public JDBCTypeWrapper jdbcTypeWrapper() {
// return this.jdbcTypeWrapper;
// }
//
// @Override
// public String toString() {
// return "JDBCColumnDescriptor[columnName=(" + columnLabel + "), jdbcTypeWrapper=(" + jdbcTypeWrapper + ")]";
// }
//
// public static JDBCColumnDescriptor create(JDBCPropertyAccessor<String> columnLabel,
// JDBCPropertyAccessor<Integer> vendorTypeNumber,
// JDBCPropertyAccessor<String> vendorTypeName,
// JDBCPropertyAccessor<String> vendorTypeClassName) throws SQLException {
// return new JDBCColumnDescriptor(columnLabel.get(), JDBCTypeWrapper.of(vendorTypeNumber.get(), vendorTypeName.get(),
// vendorTypeClassName.get()));
// }
//
// public static JDBCColumnDescriptor wrap(JDBCType jdbcType) {
// return new JDBCColumnDescriptor(null, JDBCTypeWrapper.of(jdbcType));
// }
//
// }
//
// Path: src/main/java/io/vertx/jdbcclient/impl/actions/JDBCPropertyAccessor.java
// public interface JDBCPropertyAccessor<T> {
//
// Logger LOG = LoggerFactory.getLogger(JDBCColumnDescriptor.class);
//
// T get() throws SQLException;
//
// static <T> JDBCPropertyAccessor<T> create(JDBCPropertyAccessor<T> accessor) {
// return create(accessor, null);
// }
//
// static <T> JDBCPropertyAccessor<T> create(JDBCPropertyAccessor<T> accessor, T fallbackIfUnsupported) {
// return () -> {
// try {
// return accessor.get();
// } catch (SQLFeatureNotSupportedException e) {
// LOG.debug("Unsupported access properties in SQL metadata", e);
// return fallbackIfUnsupported;
// }
// };
// }
//
// static JDBCPropertyAccessor<Integer> jdbcType(JDBCPropertyAccessor<Integer> accessor) {
// return create(accessor, JDBCType.OTHER.getVendorTypeNumber());
// }
//
// }
| import io.vertx.jdbcclient.impl.actions.JDBCColumnDescriptor;
import io.vertx.jdbcclient.impl.actions.JDBCPropertyAccessor;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException; | /*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.ext.jdbc.spi;
/**
* A shortcut provider that get a column information in the runtime SQL result or parameter metadata
*
* @since 4.2.2
*/
@FunctionalInterface
public interface JDBCColumnDescriptorProvider {
/**
* Create provider by parameter statement
*
* @param statement the prepared statement
* @return a new {@code JDBCTypeProvider} instance
* @see java.sql.PreparedStatement
*/
static JDBCColumnDescriptorProvider fromParameter(PreparedStatement statement) {
return col -> JDBCColumnDescriptor.create(() -> null, | // Path: src/main/java/io/vertx/jdbcclient/impl/actions/JDBCColumnDescriptor.java
// public class JDBCColumnDescriptor implements ColumnDescriptor {
//
// private final String columnLabel;
// private final JDBCTypeWrapper jdbcTypeWrapper;
//
// private JDBCColumnDescriptor(String columnLabel, JDBCTypeWrapper jdbcTypeWrapper) {
// this.columnLabel = columnLabel;
// this.jdbcTypeWrapper = jdbcTypeWrapper;
// }
//
// @Override
// public String name() {
// return columnLabel;
// }
//
// @Override
// public boolean isArray() {
// return jdbcType() == JDBCType.ARRAY;
// }
//
// @Override
// public String typeName() {
// return jdbcTypeWrapper.vendorTypeName();
// }
//
// /**
// * Use {@link #jdbcTypeWrapper()} when converting an advanced data type depending on the specific database
// *
// * @return the most appropriate {@code JDBCType} or {@code null} if it is advanced type of specific database
// */
// @Override
// public JDBCType jdbcType() {
// return jdbcTypeWrapper.jdbcType();
// }
//
// /**
// * @return the jdbc type wrapper
// * @see JDBCTypeWrapper
// */
// public JDBCTypeWrapper jdbcTypeWrapper() {
// return this.jdbcTypeWrapper;
// }
//
// @Override
// public String toString() {
// return "JDBCColumnDescriptor[columnName=(" + columnLabel + "), jdbcTypeWrapper=(" + jdbcTypeWrapper + ")]";
// }
//
// public static JDBCColumnDescriptor create(JDBCPropertyAccessor<String> columnLabel,
// JDBCPropertyAccessor<Integer> vendorTypeNumber,
// JDBCPropertyAccessor<String> vendorTypeName,
// JDBCPropertyAccessor<String> vendorTypeClassName) throws SQLException {
// return new JDBCColumnDescriptor(columnLabel.get(), JDBCTypeWrapper.of(vendorTypeNumber.get(), vendorTypeName.get(),
// vendorTypeClassName.get()));
// }
//
// public static JDBCColumnDescriptor wrap(JDBCType jdbcType) {
// return new JDBCColumnDescriptor(null, JDBCTypeWrapper.of(jdbcType));
// }
//
// }
//
// Path: src/main/java/io/vertx/jdbcclient/impl/actions/JDBCPropertyAccessor.java
// public interface JDBCPropertyAccessor<T> {
//
// Logger LOG = LoggerFactory.getLogger(JDBCColumnDescriptor.class);
//
// T get() throws SQLException;
//
// static <T> JDBCPropertyAccessor<T> create(JDBCPropertyAccessor<T> accessor) {
// return create(accessor, null);
// }
//
// static <T> JDBCPropertyAccessor<T> create(JDBCPropertyAccessor<T> accessor, T fallbackIfUnsupported) {
// return () -> {
// try {
// return accessor.get();
// } catch (SQLFeatureNotSupportedException e) {
// LOG.debug("Unsupported access properties in SQL metadata", e);
// return fallbackIfUnsupported;
// }
// };
// }
//
// static JDBCPropertyAccessor<Integer> jdbcType(JDBCPropertyAccessor<Integer> accessor) {
// return create(accessor, JDBCType.OTHER.getVendorTypeNumber());
// }
//
// }
// Path: src/main/java/io/vertx/ext/jdbc/spi/JDBCColumnDescriptorProvider.java
import io.vertx.jdbcclient.impl.actions.JDBCColumnDescriptor;
import io.vertx.jdbcclient.impl.actions.JDBCPropertyAccessor;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
/*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.ext.jdbc.spi;
/**
* A shortcut provider that get a column information in the runtime SQL result or parameter metadata
*
* @since 4.2.2
*/
@FunctionalInterface
public interface JDBCColumnDescriptorProvider {
/**
* Create provider by parameter statement
*
* @param statement the prepared statement
* @return a new {@code JDBCTypeProvider} instance
* @see java.sql.PreparedStatement
*/
static JDBCColumnDescriptorProvider fromParameter(PreparedStatement statement) {
return col -> JDBCColumnDescriptor.create(() -> null, | JDBCPropertyAccessor.jdbcType(() -> statement.getParameterMetaData().getParameterType(col)), |
vert-x3/vertx-jdbc-client | src/main/java/io/vertx/ext/jdbc/impl/actions/JDBCExecute.java | // Path: src/main/java/io/vertx/ext/sql/SQLOptions.java
// @DataObject(generateConverter = true)
// public class SQLOptions {
//
// // connection
// private boolean readOnly;
// private String catalog;
// private TransactionIsolation transactionIsolation;
// private ResultSetType resultSetType;
// private ResultSetConcurrency resultSetConcurrency;
// // backwards compatibility
// private boolean autoGeneratedKeys = true;
// private JsonArray autoGeneratedKeysIndexes;
// private String schema;
// // statement
// private int queryTimeout;
// private int maxRows;
// // resultset
// private FetchDirection fetchDirection;
// private int fetchSize;
//
// /**
// * Default constructor
// */
// public SQLOptions() {
// }
//
// /**
// * Copy constructor
// *
// * @param other the result to copy
// */
// public SQLOptions(SQLOptions other) {
// this.readOnly = other.isReadOnly();
// this.catalog = other.getCatalog();
// this.transactionIsolation = other.getTransactionIsolation();
// this.resultSetType = other.getResultSetType();
// this.resultSetConcurrency = other.getResultSetConcurrency();
// this.autoGeneratedKeys = other.isAutoGeneratedKeys();
// this.autoGeneratedKeysIndexes = other.getAutoGeneratedKeysIndexes();
// this.schema = other.getSchema();
// this.queryTimeout = other.getQueryTimeout();
// this.fetchDirection = other.getFetchDirection();
// this.fetchSize = other.getFetchSize();
// this.maxRows = other.getMaxRows();
// }
//
// /**
// * Constructor from JSON
// *
// * @param json the json
// */
// public SQLOptions(JsonObject json) {
// SQLOptionsConverter.fromJson(json, this);
// }
//
// public boolean isReadOnly() {
// return readOnly;
// }
//
// public SQLOptions setReadOnly(boolean readOnly) {
// this.readOnly = readOnly;
// return this;
// }
//
// public String getCatalog() {
// return catalog;
// }
//
// public SQLOptions setCatalog(String catalog) {
// this.catalog = catalog;
// return this;
// }
//
// public TransactionIsolation getTransactionIsolation() {
// return transactionIsolation;
// }
//
// public SQLOptions setTransactionIsolation(TransactionIsolation transactionIsolation) {
// this.transactionIsolation = transactionIsolation;
// return this;
// }
//
// public ResultSetType getResultSetType() {
// return resultSetType;
// }
//
// public SQLOptions setResultSetType(ResultSetType resultSetType) {
// this.resultSetType = resultSetType;
// return this;
// }
//
// public ResultSetConcurrency getResultSetConcurrency() {
// return resultSetConcurrency;
// }
//
// public SQLOptions setResultSetConcurrency(ResultSetConcurrency resultSetConcurrency) {
// this.resultSetConcurrency = resultSetConcurrency;
// return this;
// }
//
// public boolean isAutoGeneratedKeys() {
// return autoGeneratedKeys;
// }
//
// public SQLOptions setAutoGeneratedKeys(boolean autoGeneratedKeys) {
// this.autoGeneratedKeys = autoGeneratedKeys;
// return this;
// }
//
// public String getSchema() {
// return schema;
// }
//
// public SQLOptions setSchema(String schema) {
// this.schema = schema;
// return this;
// }
//
// public int getQueryTimeout() {
// return queryTimeout;
// }
//
// public SQLOptions setQueryTimeout(int queryTimeout) {
// this.queryTimeout = queryTimeout;
// return this;
// }
//
// public FetchDirection getFetchDirection() {
// return fetchDirection;
// }
//
// public SQLOptions setFetchDirection(FetchDirection fetchDirection) {
// this.fetchDirection = fetchDirection;
// return this;
// }
//
// public int getFetchSize() {
// return fetchSize;
// }
//
// public SQLOptions setFetchSize(int fetchSize) {
// this.fetchSize = fetchSize;
// return this;
// }
//
// public JsonArray getAutoGeneratedKeysIndexes() {
// return autoGeneratedKeysIndexes;
// }
//
// public SQLOptions setAutoGeneratedKeysIndexes(JsonArray autoGeneratedKeysIndexes) {
// this.autoGeneratedKeysIndexes = autoGeneratedKeysIndexes;
// return this;
// }
//
// public int getMaxRows() {
// return maxRows;
// }
//
// public SQLOptions setMaxRows(int maxRows) {
// this.maxRows = maxRows;
// return this;
// }
// }
| import io.vertx.ext.sql.SQLOptions;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; | /*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.ext.jdbc.impl.actions;
/**
* @author <a href="mailto:[email protected]">Nick Scavelli</a>
*/
public class JDBCExecute extends AbstractJDBCAction<Void> {
private final String sql;
| // Path: src/main/java/io/vertx/ext/sql/SQLOptions.java
// @DataObject(generateConverter = true)
// public class SQLOptions {
//
// // connection
// private boolean readOnly;
// private String catalog;
// private TransactionIsolation transactionIsolation;
// private ResultSetType resultSetType;
// private ResultSetConcurrency resultSetConcurrency;
// // backwards compatibility
// private boolean autoGeneratedKeys = true;
// private JsonArray autoGeneratedKeysIndexes;
// private String schema;
// // statement
// private int queryTimeout;
// private int maxRows;
// // resultset
// private FetchDirection fetchDirection;
// private int fetchSize;
//
// /**
// * Default constructor
// */
// public SQLOptions() {
// }
//
// /**
// * Copy constructor
// *
// * @param other the result to copy
// */
// public SQLOptions(SQLOptions other) {
// this.readOnly = other.isReadOnly();
// this.catalog = other.getCatalog();
// this.transactionIsolation = other.getTransactionIsolation();
// this.resultSetType = other.getResultSetType();
// this.resultSetConcurrency = other.getResultSetConcurrency();
// this.autoGeneratedKeys = other.isAutoGeneratedKeys();
// this.autoGeneratedKeysIndexes = other.getAutoGeneratedKeysIndexes();
// this.schema = other.getSchema();
// this.queryTimeout = other.getQueryTimeout();
// this.fetchDirection = other.getFetchDirection();
// this.fetchSize = other.getFetchSize();
// this.maxRows = other.getMaxRows();
// }
//
// /**
// * Constructor from JSON
// *
// * @param json the json
// */
// public SQLOptions(JsonObject json) {
// SQLOptionsConverter.fromJson(json, this);
// }
//
// public boolean isReadOnly() {
// return readOnly;
// }
//
// public SQLOptions setReadOnly(boolean readOnly) {
// this.readOnly = readOnly;
// return this;
// }
//
// public String getCatalog() {
// return catalog;
// }
//
// public SQLOptions setCatalog(String catalog) {
// this.catalog = catalog;
// return this;
// }
//
// public TransactionIsolation getTransactionIsolation() {
// return transactionIsolation;
// }
//
// public SQLOptions setTransactionIsolation(TransactionIsolation transactionIsolation) {
// this.transactionIsolation = transactionIsolation;
// return this;
// }
//
// public ResultSetType getResultSetType() {
// return resultSetType;
// }
//
// public SQLOptions setResultSetType(ResultSetType resultSetType) {
// this.resultSetType = resultSetType;
// return this;
// }
//
// public ResultSetConcurrency getResultSetConcurrency() {
// return resultSetConcurrency;
// }
//
// public SQLOptions setResultSetConcurrency(ResultSetConcurrency resultSetConcurrency) {
// this.resultSetConcurrency = resultSetConcurrency;
// return this;
// }
//
// public boolean isAutoGeneratedKeys() {
// return autoGeneratedKeys;
// }
//
// public SQLOptions setAutoGeneratedKeys(boolean autoGeneratedKeys) {
// this.autoGeneratedKeys = autoGeneratedKeys;
// return this;
// }
//
// public String getSchema() {
// return schema;
// }
//
// public SQLOptions setSchema(String schema) {
// this.schema = schema;
// return this;
// }
//
// public int getQueryTimeout() {
// return queryTimeout;
// }
//
// public SQLOptions setQueryTimeout(int queryTimeout) {
// this.queryTimeout = queryTimeout;
// return this;
// }
//
// public FetchDirection getFetchDirection() {
// return fetchDirection;
// }
//
// public SQLOptions setFetchDirection(FetchDirection fetchDirection) {
// this.fetchDirection = fetchDirection;
// return this;
// }
//
// public int getFetchSize() {
// return fetchSize;
// }
//
// public SQLOptions setFetchSize(int fetchSize) {
// this.fetchSize = fetchSize;
// return this;
// }
//
// public JsonArray getAutoGeneratedKeysIndexes() {
// return autoGeneratedKeysIndexes;
// }
//
// public SQLOptions setAutoGeneratedKeysIndexes(JsonArray autoGeneratedKeysIndexes) {
// this.autoGeneratedKeysIndexes = autoGeneratedKeysIndexes;
// return this;
// }
//
// public int getMaxRows() {
// return maxRows;
// }
//
// public SQLOptions setMaxRows(int maxRows) {
// this.maxRows = maxRows;
// return this;
// }
// }
// Path: src/main/java/io/vertx/ext/jdbc/impl/actions/JDBCExecute.java
import io.vertx.ext.sql.SQLOptions;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.ext.jdbc.impl.actions;
/**
* @author <a href="mailto:[email protected]">Nick Scavelli</a>
*/
public class JDBCExecute extends AbstractJDBCAction<Void> {
private final String sql;
| public JDBCExecute(SQLOptions options, String sql) { |
vert-x3/vertx-jdbc-client | src/test/java/io/vertx/it/ClickHouseTest.java | // Path: src/main/java/io/vertx/jdbcclient/JDBCPool.java
// @VertxGen
// public interface JDBCPool extends Pool {
//
// /**
// * The property to be used to retrieve the generated keys
// */
// PropertyKind<Row> GENERATED_KEYS = PropertyKind.create("generated-keys", Row.class);
//
// /**
// * The property to be used to retrieve the output of the callable statement
// */
// PropertyKind<Boolean> OUTPUT = PropertyKind.create("callable-statement-output", Boolean.class);
//
// /**
// * Create a JDBC pool which maintains its own data source.
// *
// * @param vertx the Vert.x instance
// * @param connectOptions the options to configure the connection
// * @param poolOptions the connection pool options
// * @return the client
// */
// static JDBCPool pool(Vertx vertx, JDBCConnectOptions connectOptions, PoolOptions poolOptions) {
// final ContextInternal context = (ContextInternal) vertx.getOrCreateContext();
//
// return new JDBCPoolImpl(
// vertx,
// new JDBCClientImpl(vertx, new AgroalCPDataSourceProvider(connectOptions, poolOptions)),
// connectOptions,
// context.tracer() == null ?
// null :
// new QueryTracer(context.tracer(), connectOptions.getTracingPolicy(), connectOptions.getJdbcUrl(), connectOptions.getUser(), connectOptions.getDatabase()));
// }
//
// /**
// * Create a JDBC pool which maintains its own data source.
// *
// * @param vertx the Vert.x instance
// * @param config the options to configure the client using the same format as {@link io.vertx.ext.jdbc.JDBCClient}
// * @return the client
// */
// static JDBCPool pool(Vertx vertx, JsonObject config) {
// final ContextInternal context = (ContextInternal) vertx.getOrCreateContext();
// String jdbcUrl = config.getString("jdbcUrl", config.getString("url"));
// String user = config.getString("username", config.getString("user"));
// return new JDBCPoolImpl(
// vertx,
// new JDBCClientImpl(vertx, config, UUID.randomUUID().toString()),
// new SQLOptions(config),
// context.tracer() == null ?
// null :
// new QueryTracer(context.tracer(), TracingPolicy.PROPAGATE, jdbcUrl, user, config.getString("database")));
// }
//
// /**
// * Create a JDBC pool which maintains its own data source.
// *
// * @param vertx the Vert.x instance
// * @param dataSourceProvider the options to configure the client using the same format as {@link io.vertx.ext.jdbc.JDBCClient}
// * @return the client
// * @since 4.2.0
// */
// @GenIgnore(GenIgnore.PERMITTED_TYPE)
// static JDBCPool pool(Vertx vertx, DataSourceProvider dataSourceProvider) {
// final ContextInternal context = (ContextInternal) vertx.getOrCreateContext();
// final JsonObject config = dataSourceProvider.getInitialConfig();
// String jdbcUrl = config.getString("jdbcUrl", config.getString("url"));
// String user = config.getString("username", config.getString("user"));
// String database = config.getString("database");
// if (context.tracer() != null) {
// Objects.requireNonNull(jdbcUrl, "data source url config cannot be null");
// Objects.requireNonNull(user, "data source user config cannot be null");
// Objects.requireNonNull(database, "data source database config cannot be null");
// }
// return new JDBCPoolImpl(
// vertx,
// new JDBCClientImpl(vertx, dataSourceProvider),
// new SQLOptions(config),
// context.tracer() == null ?
// null :
// new QueryTracer(context.tracer(), TracingPolicy.PROPAGATE, jdbcUrl, user, database));
// }
//
// /**
// * Create a JDBC pool using a pre-initialized data source.
// *
// * @param vertx the Vert.x instance
// * @param dataSource a pre-initialized data source
// * @return the client
// * @since 4.2.0
// */
// @GenIgnore(GenIgnore.PERMITTED_TYPE)
// static JDBCPool pool(Vertx vertx, DataSource dataSource) {
// return pool(vertx, DataSourceProvider.create(dataSource, new JsonObject()));
// }
//
// /**
// * Create a JDBC pool using a pre-initialized data source. The config expects that at least the following properties
// * are set:
// *
// * <ul>
// * <li>{@code url} - the connection string</li>
// * <li>{@code user} - the connection user name</li>
// * <li>{@code database} - the database name</li>
// * <li>{@code maxPoolSize} - the max allowed number of connections in the pool</li>
// * </ul>
// *
// * @param vertx the Vert.x instance
// * @param dataSource a pre-initialized data source
// * @param config the pool configuration
// * @return the client
// * @since 4.2.0
// */
// @GenIgnore(GenIgnore.PERMITTED_TYPE)
// static JDBCPool pool(Vertx vertx, DataSource dataSource, JsonObject config) {
// return pool(vertx, DataSourceProvider.create(dataSource, config));
// }
// }
| import io.vertx.core.Vertx;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import io.vertx.jdbcclient.JDBCPool;
import io.vertx.sqlclient.Row;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.testcontainers.containers.ClickHouseContainer; | package io.vertx.it;
@RunWith(VertxUnitRunner.class)
public class ClickHouseTest {
private Vertx vertx;
private ClickHouseContainer container; | // Path: src/main/java/io/vertx/jdbcclient/JDBCPool.java
// @VertxGen
// public interface JDBCPool extends Pool {
//
// /**
// * The property to be used to retrieve the generated keys
// */
// PropertyKind<Row> GENERATED_KEYS = PropertyKind.create("generated-keys", Row.class);
//
// /**
// * The property to be used to retrieve the output of the callable statement
// */
// PropertyKind<Boolean> OUTPUT = PropertyKind.create("callable-statement-output", Boolean.class);
//
// /**
// * Create a JDBC pool which maintains its own data source.
// *
// * @param vertx the Vert.x instance
// * @param connectOptions the options to configure the connection
// * @param poolOptions the connection pool options
// * @return the client
// */
// static JDBCPool pool(Vertx vertx, JDBCConnectOptions connectOptions, PoolOptions poolOptions) {
// final ContextInternal context = (ContextInternal) vertx.getOrCreateContext();
//
// return new JDBCPoolImpl(
// vertx,
// new JDBCClientImpl(vertx, new AgroalCPDataSourceProvider(connectOptions, poolOptions)),
// connectOptions,
// context.tracer() == null ?
// null :
// new QueryTracer(context.tracer(), connectOptions.getTracingPolicy(), connectOptions.getJdbcUrl(), connectOptions.getUser(), connectOptions.getDatabase()));
// }
//
// /**
// * Create a JDBC pool which maintains its own data source.
// *
// * @param vertx the Vert.x instance
// * @param config the options to configure the client using the same format as {@link io.vertx.ext.jdbc.JDBCClient}
// * @return the client
// */
// static JDBCPool pool(Vertx vertx, JsonObject config) {
// final ContextInternal context = (ContextInternal) vertx.getOrCreateContext();
// String jdbcUrl = config.getString("jdbcUrl", config.getString("url"));
// String user = config.getString("username", config.getString("user"));
// return new JDBCPoolImpl(
// vertx,
// new JDBCClientImpl(vertx, config, UUID.randomUUID().toString()),
// new SQLOptions(config),
// context.tracer() == null ?
// null :
// new QueryTracer(context.tracer(), TracingPolicy.PROPAGATE, jdbcUrl, user, config.getString("database")));
// }
//
// /**
// * Create a JDBC pool which maintains its own data source.
// *
// * @param vertx the Vert.x instance
// * @param dataSourceProvider the options to configure the client using the same format as {@link io.vertx.ext.jdbc.JDBCClient}
// * @return the client
// * @since 4.2.0
// */
// @GenIgnore(GenIgnore.PERMITTED_TYPE)
// static JDBCPool pool(Vertx vertx, DataSourceProvider dataSourceProvider) {
// final ContextInternal context = (ContextInternal) vertx.getOrCreateContext();
// final JsonObject config = dataSourceProvider.getInitialConfig();
// String jdbcUrl = config.getString("jdbcUrl", config.getString("url"));
// String user = config.getString("username", config.getString("user"));
// String database = config.getString("database");
// if (context.tracer() != null) {
// Objects.requireNonNull(jdbcUrl, "data source url config cannot be null");
// Objects.requireNonNull(user, "data source user config cannot be null");
// Objects.requireNonNull(database, "data source database config cannot be null");
// }
// return new JDBCPoolImpl(
// vertx,
// new JDBCClientImpl(vertx, dataSourceProvider),
// new SQLOptions(config),
// context.tracer() == null ?
// null :
// new QueryTracer(context.tracer(), TracingPolicy.PROPAGATE, jdbcUrl, user, database));
// }
//
// /**
// * Create a JDBC pool using a pre-initialized data source.
// *
// * @param vertx the Vert.x instance
// * @param dataSource a pre-initialized data source
// * @return the client
// * @since 4.2.0
// */
// @GenIgnore(GenIgnore.PERMITTED_TYPE)
// static JDBCPool pool(Vertx vertx, DataSource dataSource) {
// return pool(vertx, DataSourceProvider.create(dataSource, new JsonObject()));
// }
//
// /**
// * Create a JDBC pool using a pre-initialized data source. The config expects that at least the following properties
// * are set:
// *
// * <ul>
// * <li>{@code url} - the connection string</li>
// * <li>{@code user} - the connection user name</li>
// * <li>{@code database} - the database name</li>
// * <li>{@code maxPoolSize} - the max allowed number of connections in the pool</li>
// * </ul>
// *
// * @param vertx the Vert.x instance
// * @param dataSource a pre-initialized data source
// * @param config the pool configuration
// * @return the client
// * @since 4.2.0
// */
// @GenIgnore(GenIgnore.PERMITTED_TYPE)
// static JDBCPool pool(Vertx vertx, DataSource dataSource, JsonObject config) {
// return pool(vertx, DataSourceProvider.create(dataSource, config));
// }
// }
// Path: src/test/java/io/vertx/it/ClickHouseTest.java
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import io.vertx.jdbcclient.JDBCPool;
import io.vertx.sqlclient.Row;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.testcontainers.containers.ClickHouseContainer;
package io.vertx.it;
@RunWith(VertxUnitRunner.class)
public class ClickHouseTest {
private Vertx vertx;
private ClickHouseContainer container; | protected JDBCPool client; |
vert-x3/vertx-jdbc-client | src/test/java/io/vertx/ext/jdbc/spi/impl/HikariCPDataSourceProviderTest.java | // Path: src/test/java/io/vertx/ThreadLeakCheckerRule.java
// public class ThreadLeakCheckerRule implements TestRule {
//
// private final Predicate<Thread> predicate;
//
// public ThreadLeakCheckerRule() {
// this(t ->
// t.getName().equals("vertx-jdbc-service-get-connection-thread") ||
// t.getName().startsWith("C3P0PooledConnectionPoolManager")
// );
// }
//
// public ThreadLeakCheckerRule(Predicate<Thread> predicate) {
// this.predicate = predicate;
// }
//
// @Override
// public Statement apply(Statement statement, Description description) {
// return new Statement() {
// @Override
// public void evaluate() throws Throwable {
// check("before");
// statement.evaluate();
// check("after");
// }
// };
// }
//
// private void check(String when) {
// long start = System.nanoTime(), stop;
// List<Thread> threads;
// for (; ; ) {
// // Make a check
// threads = findThreads(predicate);
// if (threads.isEmpty()) {
// return;
// }
// stop = System.nanoTime();
// if (SECONDS.convert(stop - start, NANOSECONDS) >= 5) {
// break;
// } else {
// try {
// MILLISECONDS.sleep(10);
// } catch (InterruptedException e) {
// Thread.currentThread().interrupt();
// break;
// }
// }
// }
// StringBuilder msg = new StringBuilder(threads.stream()
// .map(t -> t.getName() + ": state=" + t.getState().name() + "/alive=" + t.isAlive())
// .collect(Collectors.joining(", ", "Unexpected threads " + when + " test:", ".")));
// ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
// for (ThreadInfo ti : threadMxBean.dumpAllThreads(true, true)) {
// msg.append(System.getProperty("line.separator")).append(ti.toString());
// }
// fail(msg.toString());
// }
//
// public static List<Thread> findThreads(Predicate<Thread> predicate) {
// return Thread.getAllStackTraces()
// .keySet()
// .stream()
// .filter(predicate)
// .collect(Collectors.toList());
// }
// }
| import io.vertx.ThreadLeakCheckerRule;
import io.vertx.core.json.JsonObject;
import org.junit.Rule;
import org.junit.Test;
import javax.sql.DataSource;
import java.sql.SQLException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; | package io.vertx.ext.jdbc.spi.impl;
/**
* Checks the behavior of {@link HikariCPDataSourceProvider}.
*
* @author <a href="http://escoffier.me">Clement Escoffier</a>
*/
public class HikariCPDataSourceProviderTest {
@Rule | // Path: src/test/java/io/vertx/ThreadLeakCheckerRule.java
// public class ThreadLeakCheckerRule implements TestRule {
//
// private final Predicate<Thread> predicate;
//
// public ThreadLeakCheckerRule() {
// this(t ->
// t.getName().equals("vertx-jdbc-service-get-connection-thread") ||
// t.getName().startsWith("C3P0PooledConnectionPoolManager")
// );
// }
//
// public ThreadLeakCheckerRule(Predicate<Thread> predicate) {
// this.predicate = predicate;
// }
//
// @Override
// public Statement apply(Statement statement, Description description) {
// return new Statement() {
// @Override
// public void evaluate() throws Throwable {
// check("before");
// statement.evaluate();
// check("after");
// }
// };
// }
//
// private void check(String when) {
// long start = System.nanoTime(), stop;
// List<Thread> threads;
// for (; ; ) {
// // Make a check
// threads = findThreads(predicate);
// if (threads.isEmpty()) {
// return;
// }
// stop = System.nanoTime();
// if (SECONDS.convert(stop - start, NANOSECONDS) >= 5) {
// break;
// } else {
// try {
// MILLISECONDS.sleep(10);
// } catch (InterruptedException e) {
// Thread.currentThread().interrupt();
// break;
// }
// }
// }
// StringBuilder msg = new StringBuilder(threads.stream()
// .map(t -> t.getName() + ": state=" + t.getState().name() + "/alive=" + t.isAlive())
// .collect(Collectors.joining(", ", "Unexpected threads " + when + " test:", ".")));
// ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
// for (ThreadInfo ti : threadMxBean.dumpAllThreads(true, true)) {
// msg.append(System.getProperty("line.separator")).append(ti.toString());
// }
// fail(msg.toString());
// }
//
// public static List<Thread> findThreads(Predicate<Thread> predicate) {
// return Thread.getAllStackTraces()
// .keySet()
// .stream()
// .filter(predicate)
// .collect(Collectors.toList());
// }
// }
// Path: src/test/java/io/vertx/ext/jdbc/spi/impl/HikariCPDataSourceProviderTest.java
import io.vertx.ThreadLeakCheckerRule;
import io.vertx.core.json.JsonObject;
import org.junit.Rule;
import org.junit.Test;
import javax.sql.DataSource;
import java.sql.SQLException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
package io.vertx.ext.jdbc.spi.impl;
/**
* Checks the behavior of {@link HikariCPDataSourceProvider}.
*
* @author <a href="http://escoffier.me">Clement Escoffier</a>
*/
public class HikariCPDataSourceProviderTest {
@Rule | public ThreadLeakCheckerRule rule = new ThreadLeakCheckerRule(); |
vert-x3/vertx-jdbc-client | src/main/java/io/vertx/ext/jdbc/impl/actions/JDBCClose.java | // Path: src/main/java/io/vertx/ext/sql/SQLOptions.java
// @DataObject(generateConverter = true)
// public class SQLOptions {
//
// // connection
// private boolean readOnly;
// private String catalog;
// private TransactionIsolation transactionIsolation;
// private ResultSetType resultSetType;
// private ResultSetConcurrency resultSetConcurrency;
// // backwards compatibility
// private boolean autoGeneratedKeys = true;
// private JsonArray autoGeneratedKeysIndexes;
// private String schema;
// // statement
// private int queryTimeout;
// private int maxRows;
// // resultset
// private FetchDirection fetchDirection;
// private int fetchSize;
//
// /**
// * Default constructor
// */
// public SQLOptions() {
// }
//
// /**
// * Copy constructor
// *
// * @param other the result to copy
// */
// public SQLOptions(SQLOptions other) {
// this.readOnly = other.isReadOnly();
// this.catalog = other.getCatalog();
// this.transactionIsolation = other.getTransactionIsolation();
// this.resultSetType = other.getResultSetType();
// this.resultSetConcurrency = other.getResultSetConcurrency();
// this.autoGeneratedKeys = other.isAutoGeneratedKeys();
// this.autoGeneratedKeysIndexes = other.getAutoGeneratedKeysIndexes();
// this.schema = other.getSchema();
// this.queryTimeout = other.getQueryTimeout();
// this.fetchDirection = other.getFetchDirection();
// this.fetchSize = other.getFetchSize();
// this.maxRows = other.getMaxRows();
// }
//
// /**
// * Constructor from JSON
// *
// * @param json the json
// */
// public SQLOptions(JsonObject json) {
// SQLOptionsConverter.fromJson(json, this);
// }
//
// public boolean isReadOnly() {
// return readOnly;
// }
//
// public SQLOptions setReadOnly(boolean readOnly) {
// this.readOnly = readOnly;
// return this;
// }
//
// public String getCatalog() {
// return catalog;
// }
//
// public SQLOptions setCatalog(String catalog) {
// this.catalog = catalog;
// return this;
// }
//
// public TransactionIsolation getTransactionIsolation() {
// return transactionIsolation;
// }
//
// public SQLOptions setTransactionIsolation(TransactionIsolation transactionIsolation) {
// this.transactionIsolation = transactionIsolation;
// return this;
// }
//
// public ResultSetType getResultSetType() {
// return resultSetType;
// }
//
// public SQLOptions setResultSetType(ResultSetType resultSetType) {
// this.resultSetType = resultSetType;
// return this;
// }
//
// public ResultSetConcurrency getResultSetConcurrency() {
// return resultSetConcurrency;
// }
//
// public SQLOptions setResultSetConcurrency(ResultSetConcurrency resultSetConcurrency) {
// this.resultSetConcurrency = resultSetConcurrency;
// return this;
// }
//
// public boolean isAutoGeneratedKeys() {
// return autoGeneratedKeys;
// }
//
// public SQLOptions setAutoGeneratedKeys(boolean autoGeneratedKeys) {
// this.autoGeneratedKeys = autoGeneratedKeys;
// return this;
// }
//
// public String getSchema() {
// return schema;
// }
//
// public SQLOptions setSchema(String schema) {
// this.schema = schema;
// return this;
// }
//
// public int getQueryTimeout() {
// return queryTimeout;
// }
//
// public SQLOptions setQueryTimeout(int queryTimeout) {
// this.queryTimeout = queryTimeout;
// return this;
// }
//
// public FetchDirection getFetchDirection() {
// return fetchDirection;
// }
//
// public SQLOptions setFetchDirection(FetchDirection fetchDirection) {
// this.fetchDirection = fetchDirection;
// return this;
// }
//
// public int getFetchSize() {
// return fetchSize;
// }
//
// public SQLOptions setFetchSize(int fetchSize) {
// this.fetchSize = fetchSize;
// return this;
// }
//
// public JsonArray getAutoGeneratedKeysIndexes() {
// return autoGeneratedKeysIndexes;
// }
//
// public SQLOptions setAutoGeneratedKeysIndexes(JsonArray autoGeneratedKeysIndexes) {
// this.autoGeneratedKeysIndexes = autoGeneratedKeysIndexes;
// return this;
// }
//
// public int getMaxRows() {
// return maxRows;
// }
//
// public SQLOptions setMaxRows(int maxRows) {
// this.maxRows = maxRows;
// return this;
// }
// }
| import io.vertx.core.spi.metrics.PoolMetrics;
import io.vertx.ext.sql.SQLOptions;
import java.sql.Connection;
import java.sql.SQLException; | /*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.ext.jdbc.impl.actions;
/**
* @author <a href="mailto:[email protected]">Nick Scavelli</a>
*/
public class JDBCClose extends AbstractJDBCAction<Void> {
private final PoolMetrics metrics; // the pool metrics
private final Object metric; // the resource managed by the pool metrics
| // Path: src/main/java/io/vertx/ext/sql/SQLOptions.java
// @DataObject(generateConverter = true)
// public class SQLOptions {
//
// // connection
// private boolean readOnly;
// private String catalog;
// private TransactionIsolation transactionIsolation;
// private ResultSetType resultSetType;
// private ResultSetConcurrency resultSetConcurrency;
// // backwards compatibility
// private boolean autoGeneratedKeys = true;
// private JsonArray autoGeneratedKeysIndexes;
// private String schema;
// // statement
// private int queryTimeout;
// private int maxRows;
// // resultset
// private FetchDirection fetchDirection;
// private int fetchSize;
//
// /**
// * Default constructor
// */
// public SQLOptions() {
// }
//
// /**
// * Copy constructor
// *
// * @param other the result to copy
// */
// public SQLOptions(SQLOptions other) {
// this.readOnly = other.isReadOnly();
// this.catalog = other.getCatalog();
// this.transactionIsolation = other.getTransactionIsolation();
// this.resultSetType = other.getResultSetType();
// this.resultSetConcurrency = other.getResultSetConcurrency();
// this.autoGeneratedKeys = other.isAutoGeneratedKeys();
// this.autoGeneratedKeysIndexes = other.getAutoGeneratedKeysIndexes();
// this.schema = other.getSchema();
// this.queryTimeout = other.getQueryTimeout();
// this.fetchDirection = other.getFetchDirection();
// this.fetchSize = other.getFetchSize();
// this.maxRows = other.getMaxRows();
// }
//
// /**
// * Constructor from JSON
// *
// * @param json the json
// */
// public SQLOptions(JsonObject json) {
// SQLOptionsConverter.fromJson(json, this);
// }
//
// public boolean isReadOnly() {
// return readOnly;
// }
//
// public SQLOptions setReadOnly(boolean readOnly) {
// this.readOnly = readOnly;
// return this;
// }
//
// public String getCatalog() {
// return catalog;
// }
//
// public SQLOptions setCatalog(String catalog) {
// this.catalog = catalog;
// return this;
// }
//
// public TransactionIsolation getTransactionIsolation() {
// return transactionIsolation;
// }
//
// public SQLOptions setTransactionIsolation(TransactionIsolation transactionIsolation) {
// this.transactionIsolation = transactionIsolation;
// return this;
// }
//
// public ResultSetType getResultSetType() {
// return resultSetType;
// }
//
// public SQLOptions setResultSetType(ResultSetType resultSetType) {
// this.resultSetType = resultSetType;
// return this;
// }
//
// public ResultSetConcurrency getResultSetConcurrency() {
// return resultSetConcurrency;
// }
//
// public SQLOptions setResultSetConcurrency(ResultSetConcurrency resultSetConcurrency) {
// this.resultSetConcurrency = resultSetConcurrency;
// return this;
// }
//
// public boolean isAutoGeneratedKeys() {
// return autoGeneratedKeys;
// }
//
// public SQLOptions setAutoGeneratedKeys(boolean autoGeneratedKeys) {
// this.autoGeneratedKeys = autoGeneratedKeys;
// return this;
// }
//
// public String getSchema() {
// return schema;
// }
//
// public SQLOptions setSchema(String schema) {
// this.schema = schema;
// return this;
// }
//
// public int getQueryTimeout() {
// return queryTimeout;
// }
//
// public SQLOptions setQueryTimeout(int queryTimeout) {
// this.queryTimeout = queryTimeout;
// return this;
// }
//
// public FetchDirection getFetchDirection() {
// return fetchDirection;
// }
//
// public SQLOptions setFetchDirection(FetchDirection fetchDirection) {
// this.fetchDirection = fetchDirection;
// return this;
// }
//
// public int getFetchSize() {
// return fetchSize;
// }
//
// public SQLOptions setFetchSize(int fetchSize) {
// this.fetchSize = fetchSize;
// return this;
// }
//
// public JsonArray getAutoGeneratedKeysIndexes() {
// return autoGeneratedKeysIndexes;
// }
//
// public SQLOptions setAutoGeneratedKeysIndexes(JsonArray autoGeneratedKeysIndexes) {
// this.autoGeneratedKeysIndexes = autoGeneratedKeysIndexes;
// return this;
// }
//
// public int getMaxRows() {
// return maxRows;
// }
//
// public SQLOptions setMaxRows(int maxRows) {
// this.maxRows = maxRows;
// return this;
// }
// }
// Path: src/main/java/io/vertx/ext/jdbc/impl/actions/JDBCClose.java
import io.vertx.core.spi.metrics.PoolMetrics;
import io.vertx.ext.sql.SQLOptions;
import java.sql.Connection;
import java.sql.SQLException;
/*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.ext.jdbc.impl.actions;
/**
* @author <a href="mailto:[email protected]">Nick Scavelli</a>
*/
public class JDBCClose extends AbstractJDBCAction<Void> {
private final PoolMetrics metrics; // the pool metrics
private final Object metric; // the resource managed by the pool metrics
| public JDBCClose(SQLOptions options, PoolMetrics metrics, Object metric) { |
vert-x3/vertx-jdbc-client | src/main/java/io/vertx/ext/jdbc/impl/DataSourceHolder.java | // Path: src/main/java/io/vertx/ext/jdbc/spi/DataSourceProvider.java
// public interface DataSourceProvider {
//
// /**
// * Init provider with specific configuration
// *
// * @param sqlConfig SQL connection configuration
// * @return a reference to this for fluent API
// * @apiNote Use it conjunction with {@link #create(JsonObject)}
// * @since 4.2.0
// */
// default DataSourceProvider init(JsonObject sqlConfig) {
// return this;
// }
//
// /**
// * Get the SQL initial configuration
// *
// * @return an initial configuration
// * @apiNote Use it conjunction with {@link #init(JsonObject)}
// * @since 4.2.0
// */
// default JsonObject getInitialConfig() {
// return new JsonObject();
// }
//
// int maximumPoolSize(DataSource dataSource, JsonObject config) throws SQLException;
//
// DataSource getDataSource(JsonObject config) throws SQLException;
//
// void close(DataSource dataSource) throws SQLException;
//
// static DataSourceProvider create(JsonObject config) {
// String providerClass = config.getString("provider_class");
// if (providerClass == null) {
// providerClass = JDBCClient.DEFAULT_PROVIDER_CLASS;
// }
//
// if (Thread.currentThread().getContextClassLoader() != null) {
// try {
// // Try with the TCCL
// Class clazz = Thread.currentThread().getContextClassLoader().loadClass(providerClass);
// return ((DataSourceProvider) clazz.newInstance()).init(config);
// } catch (ClassNotFoundException e) {
// // Next try.
// } catch (InstantiationException | IllegalAccessException e) {
// throw new RuntimeException(e);
// }
// }
//
// try {
// // Try with the classloader of the current class.
// Class clazz = DataSourceProvider.class.getClassLoader().loadClass(providerClass);
// return ((DataSourceProvider) clazz.newInstance()).init(config);
// } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
// throw new RuntimeException(e);
// }
// }
//
// /**
// * Init provider with specific {@link DataSource} and config. The config expects that several properties are set:
// *
// * <ul>
// * <li>{@code url} - the connection string</li>
// * <li>{@code user} - the connection user name</li>
// * <li>{@code database} - the database name</li>
// * <li>{@code maxPoolSize} - the max allowed number of connections in the pool</li>
// * </ul>
// *
// * @param dataSource a pre initialized data source
// * @param config the configuration for the datasource
// * @return a reference to this for fluent API
// * @since 4.2.0
// */
// static DataSourceProvider create(final DataSource dataSource, final JsonObject config) {
// Objects.requireNonNull(config, "config must not be null");
//
// return new DataSourceProvider() {
//
// @Override
// public JsonObject getInitialConfig() {
// return config;
// }
//
// @Override
// public int maximumPoolSize(DataSource arg0, JsonObject arg1) {
// return config.getInteger("maxPoolSize", -1);
// }
//
// @Override
// public DataSource getDataSource(JsonObject arg0) {
// return dataSource;
// }
//
// @Override
// public void close(DataSource arg0) throws SQLException {
// if (dataSource instanceof AutoCloseable) {
// try {
// ((AutoCloseable) dataSource).close();
// } catch (Exception e) {
// throw new SQLException("Failed to close data source", e);
// }
// }
// }
// };
// }
// }
| import io.vertx.core.impl.TaskQueue;
import io.vertx.core.shareddata.Shareable;
import io.vertx.core.spi.metrics.PoolMetrics;
import io.vertx.ext.jdbc.spi.DataSourceProvider;
import javax.sql.DataSource;
import java.util.Objects;
import java.util.concurrent.ExecutorService; | /*
* Copyright (c) 2011-2019 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
* which is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
*/
package io.vertx.ext.jdbc.impl;
/**
* @author Thomas Segismont
*/
class DataSourceHolder implements Shareable {
final TaskQueue creationQueue; | // Path: src/main/java/io/vertx/ext/jdbc/spi/DataSourceProvider.java
// public interface DataSourceProvider {
//
// /**
// * Init provider with specific configuration
// *
// * @param sqlConfig SQL connection configuration
// * @return a reference to this for fluent API
// * @apiNote Use it conjunction with {@link #create(JsonObject)}
// * @since 4.2.0
// */
// default DataSourceProvider init(JsonObject sqlConfig) {
// return this;
// }
//
// /**
// * Get the SQL initial configuration
// *
// * @return an initial configuration
// * @apiNote Use it conjunction with {@link #init(JsonObject)}
// * @since 4.2.0
// */
// default JsonObject getInitialConfig() {
// return new JsonObject();
// }
//
// int maximumPoolSize(DataSource dataSource, JsonObject config) throws SQLException;
//
// DataSource getDataSource(JsonObject config) throws SQLException;
//
// void close(DataSource dataSource) throws SQLException;
//
// static DataSourceProvider create(JsonObject config) {
// String providerClass = config.getString("provider_class");
// if (providerClass == null) {
// providerClass = JDBCClient.DEFAULT_PROVIDER_CLASS;
// }
//
// if (Thread.currentThread().getContextClassLoader() != null) {
// try {
// // Try with the TCCL
// Class clazz = Thread.currentThread().getContextClassLoader().loadClass(providerClass);
// return ((DataSourceProvider) clazz.newInstance()).init(config);
// } catch (ClassNotFoundException e) {
// // Next try.
// } catch (InstantiationException | IllegalAccessException e) {
// throw new RuntimeException(e);
// }
// }
//
// try {
// // Try with the classloader of the current class.
// Class clazz = DataSourceProvider.class.getClassLoader().loadClass(providerClass);
// return ((DataSourceProvider) clazz.newInstance()).init(config);
// } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
// throw new RuntimeException(e);
// }
// }
//
// /**
// * Init provider with specific {@link DataSource} and config. The config expects that several properties are set:
// *
// * <ul>
// * <li>{@code url} - the connection string</li>
// * <li>{@code user} - the connection user name</li>
// * <li>{@code database} - the database name</li>
// * <li>{@code maxPoolSize} - the max allowed number of connections in the pool</li>
// * </ul>
// *
// * @param dataSource a pre initialized data source
// * @param config the configuration for the datasource
// * @return a reference to this for fluent API
// * @since 4.2.0
// */
// static DataSourceProvider create(final DataSource dataSource, final JsonObject config) {
// Objects.requireNonNull(config, "config must not be null");
//
// return new DataSourceProvider() {
//
// @Override
// public JsonObject getInitialConfig() {
// return config;
// }
//
// @Override
// public int maximumPoolSize(DataSource arg0, JsonObject arg1) {
// return config.getInteger("maxPoolSize", -1);
// }
//
// @Override
// public DataSource getDataSource(JsonObject arg0) {
// return dataSource;
// }
//
// @Override
// public void close(DataSource arg0) throws SQLException {
// if (dataSource instanceof AutoCloseable) {
// try {
// ((AutoCloseable) dataSource).close();
// } catch (Exception e) {
// throw new SQLException("Failed to close data source", e);
// }
// }
// }
// };
// }
// }
// Path: src/main/java/io/vertx/ext/jdbc/impl/DataSourceHolder.java
import io.vertx.core.impl.TaskQueue;
import io.vertx.core.shareddata.Shareable;
import io.vertx.core.spi.metrics.PoolMetrics;
import io.vertx.ext.jdbc.spi.DataSourceProvider;
import javax.sql.DataSource;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
/*
* Copyright (c) 2011-2019 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
* which is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
*/
package io.vertx.ext.jdbc.impl;
/**
* @author Thomas Segismont
*/
class DataSourceHolder implements Shareable {
final TaskQueue creationQueue; | final DataSourceProvider provider; |
vert-x3/vertx-jdbc-client | src/test/java/io/vertx/it/OracleTest.java | // Path: src/main/java/io/vertx/ext/jdbc/JDBCClient.java
// @VertxGen
// public interface JDBCClient extends SQLClient {
//
// /**
// * The default data source provider is C3P0
// */
// String DEFAULT_PROVIDER_CLASS = "io.vertx.ext.jdbc.spi.impl.C3P0DataSourceProvider";
//
// /**
// * The name of the default data source
// */
// String DEFAULT_DS_NAME = "DEFAULT_DS";
//
// /**
// * Create a JDBC client which maintains its own data source.
// *
// * @param vertx the Vert.x instance
// * @param config the configuration
// * @return the client
// */
// static JDBCClient create(Vertx vertx, JsonObject config) {
// return new JDBCClientImpl(vertx, config, UUID.randomUUID().toString());
// }
//
// /**
// * Create a JDBC client which shares its data source with any other JDBC clients created with the same
// * data source name
// *
// * @param vertx the Vert.x instance
// * @param config the configuration
// * @param dataSourceName the data source name
// * @return the client
// */
// static JDBCClient createShared(Vertx vertx, JsonObject config, String dataSourceName) {
// return new JDBCClientImpl(vertx, config, dataSourceName);
// }
//
// /**
// * Like {@link #createShared(io.vertx.core.Vertx, JsonObject, String)} but with the default data source name
// * @param vertx the Vert.x instance
// * @param config the configuration
// * @return the client
// */
// static JDBCClient createShared(Vertx vertx, JsonObject config) {
// return new JDBCClientImpl(vertx, config, DEFAULT_DS_NAME);
// }
//
// /**
// * Create a client using a pre-existing data source
// *
// * @param vertx the Vert.x instance
// * @param dataSource the datasource
// * @return the client
// */
// @GenIgnore
// static JDBCClient create(Vertx vertx, DataSource dataSource) {
// return new JDBCClientImpl(vertx, dataSource);
// }
//
// /**
// * Create a client using a data source provider
// *
// * @param vertx the Vert.x instance
// * @param dataSourceProvider the datasource provider
// * @return the client
// * @since 4.2.0
// */
// @GenIgnore
// static JDBCClient create(Vertx vertx, DataSourceProvider dataSourceProvider) {
// return new JDBCClientImpl(vertx, dataSourceProvider);
// }
//
// }
| import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.RunTestOnContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.testcontainers.containers.OracleContainer; | /*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.it;
/**
* @author <a href="mailto:[email protected]">Fyro</a>
*/
@RunWith(VertxUnitRunner.class)
@Ignore("This container doesn't start on GitHub")
public class OracleTest {
@ClassRule
public static final RunTestOnContext rule = new RunTestOnContext();
@ClassRule
public static final OracleContainer server = new OracleContainer("wnameless/oracle-xe-11g-r2:latest")
.withInitScript("init-oracle.sql");
@Test
public void simpleDeleteTest(TestContext should) {
final Async test = should.async(); | // Path: src/main/java/io/vertx/ext/jdbc/JDBCClient.java
// @VertxGen
// public interface JDBCClient extends SQLClient {
//
// /**
// * The default data source provider is C3P0
// */
// String DEFAULT_PROVIDER_CLASS = "io.vertx.ext.jdbc.spi.impl.C3P0DataSourceProvider";
//
// /**
// * The name of the default data source
// */
// String DEFAULT_DS_NAME = "DEFAULT_DS";
//
// /**
// * Create a JDBC client which maintains its own data source.
// *
// * @param vertx the Vert.x instance
// * @param config the configuration
// * @return the client
// */
// static JDBCClient create(Vertx vertx, JsonObject config) {
// return new JDBCClientImpl(vertx, config, UUID.randomUUID().toString());
// }
//
// /**
// * Create a JDBC client which shares its data source with any other JDBC clients created with the same
// * data source name
// *
// * @param vertx the Vert.x instance
// * @param config the configuration
// * @param dataSourceName the data source name
// * @return the client
// */
// static JDBCClient createShared(Vertx vertx, JsonObject config, String dataSourceName) {
// return new JDBCClientImpl(vertx, config, dataSourceName);
// }
//
// /**
// * Like {@link #createShared(io.vertx.core.Vertx, JsonObject, String)} but with the default data source name
// * @param vertx the Vert.x instance
// * @param config the configuration
// * @return the client
// */
// static JDBCClient createShared(Vertx vertx, JsonObject config) {
// return new JDBCClientImpl(vertx, config, DEFAULT_DS_NAME);
// }
//
// /**
// * Create a client using a pre-existing data source
// *
// * @param vertx the Vert.x instance
// * @param dataSource the datasource
// * @return the client
// */
// @GenIgnore
// static JDBCClient create(Vertx vertx, DataSource dataSource) {
// return new JDBCClientImpl(vertx, dataSource);
// }
//
// /**
// * Create a client using a data source provider
// *
// * @param vertx the Vert.x instance
// * @param dataSourceProvider the datasource provider
// * @return the client
// * @since 4.2.0
// */
// @GenIgnore
// static JDBCClient create(Vertx vertx, DataSourceProvider dataSourceProvider) {
// return new JDBCClientImpl(vertx, dataSourceProvider);
// }
//
// }
// Path: src/test/java/io/vertx/it/OracleTest.java
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.RunTestOnContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.testcontainers.containers.OracleContainer;
/*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.it;
/**
* @author <a href="mailto:[email protected]">Fyro</a>
*/
@RunWith(VertxUnitRunner.class)
@Ignore("This container doesn't start on GitHub")
public class OracleTest {
@ClassRule
public static final RunTestOnContext rule = new RunTestOnContext();
@ClassRule
public static final OracleContainer server = new OracleContainer("wnameless/oracle-xe-11g-r2:latest")
.withInitScript("init-oracle.sql");
@Test
public void simpleDeleteTest(TestContext should) {
final Async test = should.async(); | JDBCClient client = initJDBCClient(); |
vert-x3/vertx-jdbc-client | src/main/java/io/vertx/jdbcclient/SqlOutParam.java | // Path: src/main/java/io/vertx/jdbcclient/impl/SqlOutParamImpl.java
// public class SqlOutParamImpl implements SqlOutParam {
//
// final Object value;
// final int type;
// final boolean in;
//
// public SqlOutParamImpl(Object value, int type) {
// this.value = value;
// this.type = type;
// in = true;
// }
//
// public SqlOutParamImpl(int type) {
// this.value = null;
// this.type = type;
// in = false;
// }
//
// @Override
// public boolean in() {
// return in;
// }
//
// @Override
// public int type() {
// return type;
// }
//
// @Override
// public Object value() {
// return value;
// }
// }
| import io.vertx.codegen.annotations.VertxGen;
import io.vertx.jdbcclient.impl.SqlOutParamImpl;
import java.sql.JDBCType; | /*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.jdbcclient;
/**
* Tag if a parameter is of type OUT or INOUT.
*
* By default parameters are of type IN as they are provided by the user to the RDBMs engine. There are however cases
* where these must be tagged as OUT/INOUT when dealing with stored procedures/functions or complex statements.
*
* This interface allows marking the type of the param as required by the JDBC API.
*/
@VertxGen
public interface SqlOutParam {
/**
* Factory for a OUT parameter of type {@code out}.
* @param out the kind of the type according to JDBC types.
* @return new marker
*/
static SqlOutParam OUT(int out) { | // Path: src/main/java/io/vertx/jdbcclient/impl/SqlOutParamImpl.java
// public class SqlOutParamImpl implements SqlOutParam {
//
// final Object value;
// final int type;
// final boolean in;
//
// public SqlOutParamImpl(Object value, int type) {
// this.value = value;
// this.type = type;
// in = true;
// }
//
// public SqlOutParamImpl(int type) {
// this.value = null;
// this.type = type;
// in = false;
// }
//
// @Override
// public boolean in() {
// return in;
// }
//
// @Override
// public int type() {
// return type;
// }
//
// @Override
// public Object value() {
// return value;
// }
// }
// Path: src/main/java/io/vertx/jdbcclient/SqlOutParam.java
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.jdbcclient.impl.SqlOutParamImpl;
import java.sql.JDBCType;
/*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.jdbcclient;
/**
* Tag if a parameter is of type OUT or INOUT.
*
* By default parameters are of type IN as they are provided by the user to the RDBMs engine. There are however cases
* where these must be tagged as OUT/INOUT when dealing with stored procedures/functions or complex statements.
*
* This interface allows marking the type of the param as required by the JDBC API.
*/
@VertxGen
public interface SqlOutParam {
/**
* Factory for a OUT parameter of type {@code out}.
* @param out the kind of the type according to JDBC types.
* @return new marker
*/
static SqlOutParam OUT(int out) { | return new SqlOutParamImpl(out); |
vert-x3/vertx-jdbc-client | src/main/java/io/vertx/jdbcclient/impl/actions/JDBCResponse.java | // Path: src/main/java/io/vertx/jdbcclient/JDBCPool.java
// @VertxGen
// public interface JDBCPool extends Pool {
//
// /**
// * The property to be used to retrieve the generated keys
// */
// PropertyKind<Row> GENERATED_KEYS = PropertyKind.create("generated-keys", Row.class);
//
// /**
// * The property to be used to retrieve the output of the callable statement
// */
// PropertyKind<Boolean> OUTPUT = PropertyKind.create("callable-statement-output", Boolean.class);
//
// /**
// * Create a JDBC pool which maintains its own data source.
// *
// * @param vertx the Vert.x instance
// * @param connectOptions the options to configure the connection
// * @param poolOptions the connection pool options
// * @return the client
// */
// static JDBCPool pool(Vertx vertx, JDBCConnectOptions connectOptions, PoolOptions poolOptions) {
// final ContextInternal context = (ContextInternal) vertx.getOrCreateContext();
//
// return new JDBCPoolImpl(
// vertx,
// new JDBCClientImpl(vertx, new AgroalCPDataSourceProvider(connectOptions, poolOptions)),
// connectOptions,
// context.tracer() == null ?
// null :
// new QueryTracer(context.tracer(), connectOptions.getTracingPolicy(), connectOptions.getJdbcUrl(), connectOptions.getUser(), connectOptions.getDatabase()));
// }
//
// /**
// * Create a JDBC pool which maintains its own data source.
// *
// * @param vertx the Vert.x instance
// * @param config the options to configure the client using the same format as {@link io.vertx.ext.jdbc.JDBCClient}
// * @return the client
// */
// static JDBCPool pool(Vertx vertx, JsonObject config) {
// final ContextInternal context = (ContextInternal) vertx.getOrCreateContext();
// String jdbcUrl = config.getString("jdbcUrl", config.getString("url"));
// String user = config.getString("username", config.getString("user"));
// return new JDBCPoolImpl(
// vertx,
// new JDBCClientImpl(vertx, config, UUID.randomUUID().toString()),
// new SQLOptions(config),
// context.tracer() == null ?
// null :
// new QueryTracer(context.tracer(), TracingPolicy.PROPAGATE, jdbcUrl, user, config.getString("database")));
// }
//
// /**
// * Create a JDBC pool which maintains its own data source.
// *
// * @param vertx the Vert.x instance
// * @param dataSourceProvider the options to configure the client using the same format as {@link io.vertx.ext.jdbc.JDBCClient}
// * @return the client
// * @since 4.2.0
// */
// @GenIgnore(GenIgnore.PERMITTED_TYPE)
// static JDBCPool pool(Vertx vertx, DataSourceProvider dataSourceProvider) {
// final ContextInternal context = (ContextInternal) vertx.getOrCreateContext();
// final JsonObject config = dataSourceProvider.getInitialConfig();
// String jdbcUrl = config.getString("jdbcUrl", config.getString("url"));
// String user = config.getString("username", config.getString("user"));
// String database = config.getString("database");
// if (context.tracer() != null) {
// Objects.requireNonNull(jdbcUrl, "data source url config cannot be null");
// Objects.requireNonNull(user, "data source user config cannot be null");
// Objects.requireNonNull(database, "data source database config cannot be null");
// }
// return new JDBCPoolImpl(
// vertx,
// new JDBCClientImpl(vertx, dataSourceProvider),
// new SQLOptions(config),
// context.tracer() == null ?
// null :
// new QueryTracer(context.tracer(), TracingPolicy.PROPAGATE, jdbcUrl, user, database));
// }
//
// /**
// * Create a JDBC pool using a pre-initialized data source.
// *
// * @param vertx the Vert.x instance
// * @param dataSource a pre-initialized data source
// * @return the client
// * @since 4.2.0
// */
// @GenIgnore(GenIgnore.PERMITTED_TYPE)
// static JDBCPool pool(Vertx vertx, DataSource dataSource) {
// return pool(vertx, DataSourceProvider.create(dataSource, new JsonObject()));
// }
//
// /**
// * Create a JDBC pool using a pre-initialized data source. The config expects that at least the following properties
// * are set:
// *
// * <ul>
// * <li>{@code url} - the connection string</li>
// * <li>{@code user} - the connection user name</li>
// * <li>{@code database} - the database name</li>
// * <li>{@code maxPoolSize} - the max allowed number of connections in the pool</li>
// * </ul>
// *
// * @param vertx the Vert.x instance
// * @param dataSource a pre-initialized data source
// * @param config the pool configuration
// * @return the client
// * @since 4.2.0
// */
// @GenIgnore(GenIgnore.PERMITTED_TYPE)
// static JDBCPool pool(Vertx vertx, DataSource dataSource, JsonObject config) {
// return pool(vertx, DataSourceProvider.create(dataSource, config));
// }
// }
| import io.vertx.jdbcclient.JDBCPool;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.impl.QueryResultHandler;
import io.vertx.sqlclient.impl.RowDesc;
import java.util.ArrayList;
import java.util.List; | this.update = updateCount;
}
public void push(R decodeResultSet, RowDesc desc, int size) {
if (rs == null) {
rs = new ArrayList<>();
}
rs.add(new RS<>(decodeResultSet, desc, size));
}
public void returnedKeys(Row keys) {
this.ids = keys;
}
public void empty(R apply) {
this.empty = apply;
}
public void outputs(R decodeResultSet, RowDesc desc, int size) {
if (output == null) {
output = new ArrayList<>();
}
output.add(new RS<>(decodeResultSet, desc, size));
}
public void handle(QueryResultHandler<R> handler) {
if (rs != null) {
for (RS<R> rs : this.rs) {
handler.handleResult(update, rs.size, rs.desc, rs.holder, null);
if (ids != null) { | // Path: src/main/java/io/vertx/jdbcclient/JDBCPool.java
// @VertxGen
// public interface JDBCPool extends Pool {
//
// /**
// * The property to be used to retrieve the generated keys
// */
// PropertyKind<Row> GENERATED_KEYS = PropertyKind.create("generated-keys", Row.class);
//
// /**
// * The property to be used to retrieve the output of the callable statement
// */
// PropertyKind<Boolean> OUTPUT = PropertyKind.create("callable-statement-output", Boolean.class);
//
// /**
// * Create a JDBC pool which maintains its own data source.
// *
// * @param vertx the Vert.x instance
// * @param connectOptions the options to configure the connection
// * @param poolOptions the connection pool options
// * @return the client
// */
// static JDBCPool pool(Vertx vertx, JDBCConnectOptions connectOptions, PoolOptions poolOptions) {
// final ContextInternal context = (ContextInternal) vertx.getOrCreateContext();
//
// return new JDBCPoolImpl(
// vertx,
// new JDBCClientImpl(vertx, new AgroalCPDataSourceProvider(connectOptions, poolOptions)),
// connectOptions,
// context.tracer() == null ?
// null :
// new QueryTracer(context.tracer(), connectOptions.getTracingPolicy(), connectOptions.getJdbcUrl(), connectOptions.getUser(), connectOptions.getDatabase()));
// }
//
// /**
// * Create a JDBC pool which maintains its own data source.
// *
// * @param vertx the Vert.x instance
// * @param config the options to configure the client using the same format as {@link io.vertx.ext.jdbc.JDBCClient}
// * @return the client
// */
// static JDBCPool pool(Vertx vertx, JsonObject config) {
// final ContextInternal context = (ContextInternal) vertx.getOrCreateContext();
// String jdbcUrl = config.getString("jdbcUrl", config.getString("url"));
// String user = config.getString("username", config.getString("user"));
// return new JDBCPoolImpl(
// vertx,
// new JDBCClientImpl(vertx, config, UUID.randomUUID().toString()),
// new SQLOptions(config),
// context.tracer() == null ?
// null :
// new QueryTracer(context.tracer(), TracingPolicy.PROPAGATE, jdbcUrl, user, config.getString("database")));
// }
//
// /**
// * Create a JDBC pool which maintains its own data source.
// *
// * @param vertx the Vert.x instance
// * @param dataSourceProvider the options to configure the client using the same format as {@link io.vertx.ext.jdbc.JDBCClient}
// * @return the client
// * @since 4.2.0
// */
// @GenIgnore(GenIgnore.PERMITTED_TYPE)
// static JDBCPool pool(Vertx vertx, DataSourceProvider dataSourceProvider) {
// final ContextInternal context = (ContextInternal) vertx.getOrCreateContext();
// final JsonObject config = dataSourceProvider.getInitialConfig();
// String jdbcUrl = config.getString("jdbcUrl", config.getString("url"));
// String user = config.getString("username", config.getString("user"));
// String database = config.getString("database");
// if (context.tracer() != null) {
// Objects.requireNonNull(jdbcUrl, "data source url config cannot be null");
// Objects.requireNonNull(user, "data source user config cannot be null");
// Objects.requireNonNull(database, "data source database config cannot be null");
// }
// return new JDBCPoolImpl(
// vertx,
// new JDBCClientImpl(vertx, dataSourceProvider),
// new SQLOptions(config),
// context.tracer() == null ?
// null :
// new QueryTracer(context.tracer(), TracingPolicy.PROPAGATE, jdbcUrl, user, database));
// }
//
// /**
// * Create a JDBC pool using a pre-initialized data source.
// *
// * @param vertx the Vert.x instance
// * @param dataSource a pre-initialized data source
// * @return the client
// * @since 4.2.0
// */
// @GenIgnore(GenIgnore.PERMITTED_TYPE)
// static JDBCPool pool(Vertx vertx, DataSource dataSource) {
// return pool(vertx, DataSourceProvider.create(dataSource, new JsonObject()));
// }
//
// /**
// * Create a JDBC pool using a pre-initialized data source. The config expects that at least the following properties
// * are set:
// *
// * <ul>
// * <li>{@code url} - the connection string</li>
// * <li>{@code user} - the connection user name</li>
// * <li>{@code database} - the database name</li>
// * <li>{@code maxPoolSize} - the max allowed number of connections in the pool</li>
// * </ul>
// *
// * @param vertx the Vert.x instance
// * @param dataSource a pre-initialized data source
// * @param config the pool configuration
// * @return the client
// * @since 4.2.0
// */
// @GenIgnore(GenIgnore.PERMITTED_TYPE)
// static JDBCPool pool(Vertx vertx, DataSource dataSource, JsonObject config) {
// return pool(vertx, DataSourceProvider.create(dataSource, config));
// }
// }
// Path: src/main/java/io/vertx/jdbcclient/impl/actions/JDBCResponse.java
import io.vertx.jdbcclient.JDBCPool;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.impl.QueryResultHandler;
import io.vertx.sqlclient.impl.RowDesc;
import java.util.ArrayList;
import java.util.List;
this.update = updateCount;
}
public void push(R decodeResultSet, RowDesc desc, int size) {
if (rs == null) {
rs = new ArrayList<>();
}
rs.add(new RS<>(decodeResultSet, desc, size));
}
public void returnedKeys(Row keys) {
this.ids = keys;
}
public void empty(R apply) {
this.empty = apply;
}
public void outputs(R decodeResultSet, RowDesc desc, int size) {
if (output == null) {
output = new ArrayList<>();
}
output.add(new RS<>(decodeResultSet, desc, size));
}
public void handle(QueryResultHandler<R> handler) {
if (rs != null) {
for (RS<R> rs : this.rs) {
handler.handleResult(update, rs.size, rs.desc, rs.holder, null);
if (ids != null) { | handler.addProperty(JDBCPool.GENERATED_KEYS, ids); |
vert-x3/vertx-jdbc-client | src/main/java/io/vertx/ext/jdbc/spi/JDBCDecoder.java | // Path: src/main/java/io/vertx/ext/jdbc/impl/actions/SQLValueProvider.java
// @FunctionalInterface
// public interface SQLValueProvider {
//
// Object apply(Class cls) throws SQLException;
//
// }
//
// Path: src/main/java/io/vertx/jdbcclient/impl/actions/JDBCColumnDescriptor.java
// public class JDBCColumnDescriptor implements ColumnDescriptor {
//
// private final String columnLabel;
// private final JDBCTypeWrapper jdbcTypeWrapper;
//
// private JDBCColumnDescriptor(String columnLabel, JDBCTypeWrapper jdbcTypeWrapper) {
// this.columnLabel = columnLabel;
// this.jdbcTypeWrapper = jdbcTypeWrapper;
// }
//
// @Override
// public String name() {
// return columnLabel;
// }
//
// @Override
// public boolean isArray() {
// return jdbcType() == JDBCType.ARRAY;
// }
//
// @Override
// public String typeName() {
// return jdbcTypeWrapper.vendorTypeName();
// }
//
// /**
// * Use {@link #jdbcTypeWrapper()} when converting an advanced data type depending on the specific database
// *
// * @return the most appropriate {@code JDBCType} or {@code null} if it is advanced type of specific database
// */
// @Override
// public JDBCType jdbcType() {
// return jdbcTypeWrapper.jdbcType();
// }
//
// /**
// * @return the jdbc type wrapper
// * @see JDBCTypeWrapper
// */
// public JDBCTypeWrapper jdbcTypeWrapper() {
// return this.jdbcTypeWrapper;
// }
//
// @Override
// public String toString() {
// return "JDBCColumnDescriptor[columnName=(" + columnLabel + "), jdbcTypeWrapper=(" + jdbcTypeWrapper + ")]";
// }
//
// public static JDBCColumnDescriptor create(JDBCPropertyAccessor<String> columnLabel,
// JDBCPropertyAccessor<Integer> vendorTypeNumber,
// JDBCPropertyAccessor<String> vendorTypeName,
// JDBCPropertyAccessor<String> vendorTypeClassName) throws SQLException {
// return new JDBCColumnDescriptor(columnLabel.get(), JDBCTypeWrapper.of(vendorTypeNumber.get(), vendorTypeName.get(),
// vendorTypeClassName.get()));
// }
//
// public static JDBCColumnDescriptor wrap(JDBCType jdbcType) {
// return new JDBCColumnDescriptor(null, JDBCTypeWrapper.of(jdbcType));
// }
//
// }
| import io.vertx.ext.jdbc.impl.actions.SQLValueProvider;
import io.vertx.jdbcclient.impl.actions.JDBCColumnDescriptor;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException; | /*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.ext.jdbc.spi;
/**
* Represents for JDBC decoder from SQL value to Java value
* <p>
* The default decoder provides the best efforts to convert {@code SQL type} to standard {@code Java type} as {@code
* JDBC 4.2} spec.
* <p>
* You can replace it to adapt to a specific SQL driver by creating your owns then includes in the SPI file ({@code
* META-INF/services/io.vertx.ext.jdbc.spi.JDBCDecoder})
*
* @see <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/jdbc_42.html">Mapping of java.sql.Types to
* SQL types</a>
* @see io.vertx.ext.jdbc.spi.impl.JDBCDecoderImpl
* @see java.sql.JDBCType
* @see java.sql.SQLType
* @since 4.2.0
*/
public interface JDBCDecoder {
/**
* Parse SQL value to Java value
*
* @param rs JDBC result set
* @param pos the Database column position
* @param jdbcTypeLookup JDBCType provider
* @return java value
* @throws SQLException if any error in parsing
* @see ResultSet
* @see JDBCColumnDescriptorProvider
* @since 4.2.2
*/
Object parse(ResultSet rs, int pos, JDBCColumnDescriptorProvider jdbcTypeLookup) throws SQLException;
/**
* Parse SQL value to Java value
*
* @param cs JDBC callable statement
* @param pos the parameter column position
* @param jdbcTypeLookup JDBCType provider
* @return java value
* @throws SQLException if any error in parsing
* @see CallableStatement
* @see JDBCColumnDescriptorProvider
* @since 4.2.2
*/
Object parse(CallableStatement cs, int pos, JDBCColumnDescriptorProvider jdbcTypeLookup) throws SQLException;
/**
* Convert the SQL value to Java value based on jdbc type
*
* @param descriptor the JDBC column descriptor
* @param valueProvider the value provider
* @return java value
* @see SQLValueProvider
* @see JDBCColumnDescriptor
* @since 4.2.2
*/ | // Path: src/main/java/io/vertx/ext/jdbc/impl/actions/SQLValueProvider.java
// @FunctionalInterface
// public interface SQLValueProvider {
//
// Object apply(Class cls) throws SQLException;
//
// }
//
// Path: src/main/java/io/vertx/jdbcclient/impl/actions/JDBCColumnDescriptor.java
// public class JDBCColumnDescriptor implements ColumnDescriptor {
//
// private final String columnLabel;
// private final JDBCTypeWrapper jdbcTypeWrapper;
//
// private JDBCColumnDescriptor(String columnLabel, JDBCTypeWrapper jdbcTypeWrapper) {
// this.columnLabel = columnLabel;
// this.jdbcTypeWrapper = jdbcTypeWrapper;
// }
//
// @Override
// public String name() {
// return columnLabel;
// }
//
// @Override
// public boolean isArray() {
// return jdbcType() == JDBCType.ARRAY;
// }
//
// @Override
// public String typeName() {
// return jdbcTypeWrapper.vendorTypeName();
// }
//
// /**
// * Use {@link #jdbcTypeWrapper()} when converting an advanced data type depending on the specific database
// *
// * @return the most appropriate {@code JDBCType} or {@code null} if it is advanced type of specific database
// */
// @Override
// public JDBCType jdbcType() {
// return jdbcTypeWrapper.jdbcType();
// }
//
// /**
// * @return the jdbc type wrapper
// * @see JDBCTypeWrapper
// */
// public JDBCTypeWrapper jdbcTypeWrapper() {
// return this.jdbcTypeWrapper;
// }
//
// @Override
// public String toString() {
// return "JDBCColumnDescriptor[columnName=(" + columnLabel + "), jdbcTypeWrapper=(" + jdbcTypeWrapper + ")]";
// }
//
// public static JDBCColumnDescriptor create(JDBCPropertyAccessor<String> columnLabel,
// JDBCPropertyAccessor<Integer> vendorTypeNumber,
// JDBCPropertyAccessor<String> vendorTypeName,
// JDBCPropertyAccessor<String> vendorTypeClassName) throws SQLException {
// return new JDBCColumnDescriptor(columnLabel.get(), JDBCTypeWrapper.of(vendorTypeNumber.get(), vendorTypeName.get(),
// vendorTypeClassName.get()));
// }
//
// public static JDBCColumnDescriptor wrap(JDBCType jdbcType) {
// return new JDBCColumnDescriptor(null, JDBCTypeWrapper.of(jdbcType));
// }
//
// }
// Path: src/main/java/io/vertx/ext/jdbc/spi/JDBCDecoder.java
import io.vertx.ext.jdbc.impl.actions.SQLValueProvider;
import io.vertx.jdbcclient.impl.actions.JDBCColumnDescriptor;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.ext.jdbc.spi;
/**
* Represents for JDBC decoder from SQL value to Java value
* <p>
* The default decoder provides the best efforts to convert {@code SQL type} to standard {@code Java type} as {@code
* JDBC 4.2} spec.
* <p>
* You can replace it to adapt to a specific SQL driver by creating your owns then includes in the SPI file ({@code
* META-INF/services/io.vertx.ext.jdbc.spi.JDBCDecoder})
*
* @see <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/jdbc_42.html">Mapping of java.sql.Types to
* SQL types</a>
* @see io.vertx.ext.jdbc.spi.impl.JDBCDecoderImpl
* @see java.sql.JDBCType
* @see java.sql.SQLType
* @since 4.2.0
*/
public interface JDBCDecoder {
/**
* Parse SQL value to Java value
*
* @param rs JDBC result set
* @param pos the Database column position
* @param jdbcTypeLookup JDBCType provider
* @return java value
* @throws SQLException if any error in parsing
* @see ResultSet
* @see JDBCColumnDescriptorProvider
* @since 4.2.2
*/
Object parse(ResultSet rs, int pos, JDBCColumnDescriptorProvider jdbcTypeLookup) throws SQLException;
/**
* Parse SQL value to Java value
*
* @param cs JDBC callable statement
* @param pos the parameter column position
* @param jdbcTypeLookup JDBCType provider
* @return java value
* @throws SQLException if any error in parsing
* @see CallableStatement
* @see JDBCColumnDescriptorProvider
* @since 4.2.2
*/
Object parse(CallableStatement cs, int pos, JDBCColumnDescriptorProvider jdbcTypeLookup) throws SQLException;
/**
* Convert the SQL value to Java value based on jdbc type
*
* @param descriptor the JDBC column descriptor
* @param valueProvider the value provider
* @return java value
* @see SQLValueProvider
* @see JDBCColumnDescriptor
* @since 4.2.2
*/ | Object decode(JDBCColumnDescriptor descriptor, SQLValueProvider valueProvider) throws SQLException; |
vert-x3/vertx-jdbc-client | src/main/java/io/vertx/ext/jdbc/spi/JDBCDecoder.java | // Path: src/main/java/io/vertx/ext/jdbc/impl/actions/SQLValueProvider.java
// @FunctionalInterface
// public interface SQLValueProvider {
//
// Object apply(Class cls) throws SQLException;
//
// }
//
// Path: src/main/java/io/vertx/jdbcclient/impl/actions/JDBCColumnDescriptor.java
// public class JDBCColumnDescriptor implements ColumnDescriptor {
//
// private final String columnLabel;
// private final JDBCTypeWrapper jdbcTypeWrapper;
//
// private JDBCColumnDescriptor(String columnLabel, JDBCTypeWrapper jdbcTypeWrapper) {
// this.columnLabel = columnLabel;
// this.jdbcTypeWrapper = jdbcTypeWrapper;
// }
//
// @Override
// public String name() {
// return columnLabel;
// }
//
// @Override
// public boolean isArray() {
// return jdbcType() == JDBCType.ARRAY;
// }
//
// @Override
// public String typeName() {
// return jdbcTypeWrapper.vendorTypeName();
// }
//
// /**
// * Use {@link #jdbcTypeWrapper()} when converting an advanced data type depending on the specific database
// *
// * @return the most appropriate {@code JDBCType} or {@code null} if it is advanced type of specific database
// */
// @Override
// public JDBCType jdbcType() {
// return jdbcTypeWrapper.jdbcType();
// }
//
// /**
// * @return the jdbc type wrapper
// * @see JDBCTypeWrapper
// */
// public JDBCTypeWrapper jdbcTypeWrapper() {
// return this.jdbcTypeWrapper;
// }
//
// @Override
// public String toString() {
// return "JDBCColumnDescriptor[columnName=(" + columnLabel + "), jdbcTypeWrapper=(" + jdbcTypeWrapper + ")]";
// }
//
// public static JDBCColumnDescriptor create(JDBCPropertyAccessor<String> columnLabel,
// JDBCPropertyAccessor<Integer> vendorTypeNumber,
// JDBCPropertyAccessor<String> vendorTypeName,
// JDBCPropertyAccessor<String> vendorTypeClassName) throws SQLException {
// return new JDBCColumnDescriptor(columnLabel.get(), JDBCTypeWrapper.of(vendorTypeNumber.get(), vendorTypeName.get(),
// vendorTypeClassName.get()));
// }
//
// public static JDBCColumnDescriptor wrap(JDBCType jdbcType) {
// return new JDBCColumnDescriptor(null, JDBCTypeWrapper.of(jdbcType));
// }
//
// }
| import io.vertx.ext.jdbc.impl.actions.SQLValueProvider;
import io.vertx.jdbcclient.impl.actions.JDBCColumnDescriptor;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException; | /*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.ext.jdbc.spi;
/**
* Represents for JDBC decoder from SQL value to Java value
* <p>
* The default decoder provides the best efforts to convert {@code SQL type} to standard {@code Java type} as {@code
* JDBC 4.2} spec.
* <p>
* You can replace it to adapt to a specific SQL driver by creating your owns then includes in the SPI file ({@code
* META-INF/services/io.vertx.ext.jdbc.spi.JDBCDecoder})
*
* @see <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/jdbc_42.html">Mapping of java.sql.Types to
* SQL types</a>
* @see io.vertx.ext.jdbc.spi.impl.JDBCDecoderImpl
* @see java.sql.JDBCType
* @see java.sql.SQLType
* @since 4.2.0
*/
public interface JDBCDecoder {
/**
* Parse SQL value to Java value
*
* @param rs JDBC result set
* @param pos the Database column position
* @param jdbcTypeLookup JDBCType provider
* @return java value
* @throws SQLException if any error in parsing
* @see ResultSet
* @see JDBCColumnDescriptorProvider
* @since 4.2.2
*/
Object parse(ResultSet rs, int pos, JDBCColumnDescriptorProvider jdbcTypeLookup) throws SQLException;
/**
* Parse SQL value to Java value
*
* @param cs JDBC callable statement
* @param pos the parameter column position
* @param jdbcTypeLookup JDBCType provider
* @return java value
* @throws SQLException if any error in parsing
* @see CallableStatement
* @see JDBCColumnDescriptorProvider
* @since 4.2.2
*/
Object parse(CallableStatement cs, int pos, JDBCColumnDescriptorProvider jdbcTypeLookup) throws SQLException;
/**
* Convert the SQL value to Java value based on jdbc type
*
* @param descriptor the JDBC column descriptor
* @param valueProvider the value provider
* @return java value
* @see SQLValueProvider
* @see JDBCColumnDescriptor
* @since 4.2.2
*/ | // Path: src/main/java/io/vertx/ext/jdbc/impl/actions/SQLValueProvider.java
// @FunctionalInterface
// public interface SQLValueProvider {
//
// Object apply(Class cls) throws SQLException;
//
// }
//
// Path: src/main/java/io/vertx/jdbcclient/impl/actions/JDBCColumnDescriptor.java
// public class JDBCColumnDescriptor implements ColumnDescriptor {
//
// private final String columnLabel;
// private final JDBCTypeWrapper jdbcTypeWrapper;
//
// private JDBCColumnDescriptor(String columnLabel, JDBCTypeWrapper jdbcTypeWrapper) {
// this.columnLabel = columnLabel;
// this.jdbcTypeWrapper = jdbcTypeWrapper;
// }
//
// @Override
// public String name() {
// return columnLabel;
// }
//
// @Override
// public boolean isArray() {
// return jdbcType() == JDBCType.ARRAY;
// }
//
// @Override
// public String typeName() {
// return jdbcTypeWrapper.vendorTypeName();
// }
//
// /**
// * Use {@link #jdbcTypeWrapper()} when converting an advanced data type depending on the specific database
// *
// * @return the most appropriate {@code JDBCType} or {@code null} if it is advanced type of specific database
// */
// @Override
// public JDBCType jdbcType() {
// return jdbcTypeWrapper.jdbcType();
// }
//
// /**
// * @return the jdbc type wrapper
// * @see JDBCTypeWrapper
// */
// public JDBCTypeWrapper jdbcTypeWrapper() {
// return this.jdbcTypeWrapper;
// }
//
// @Override
// public String toString() {
// return "JDBCColumnDescriptor[columnName=(" + columnLabel + "), jdbcTypeWrapper=(" + jdbcTypeWrapper + ")]";
// }
//
// public static JDBCColumnDescriptor create(JDBCPropertyAccessor<String> columnLabel,
// JDBCPropertyAccessor<Integer> vendorTypeNumber,
// JDBCPropertyAccessor<String> vendorTypeName,
// JDBCPropertyAccessor<String> vendorTypeClassName) throws SQLException {
// return new JDBCColumnDescriptor(columnLabel.get(), JDBCTypeWrapper.of(vendorTypeNumber.get(), vendorTypeName.get(),
// vendorTypeClassName.get()));
// }
//
// public static JDBCColumnDescriptor wrap(JDBCType jdbcType) {
// return new JDBCColumnDescriptor(null, JDBCTypeWrapper.of(jdbcType));
// }
//
// }
// Path: src/main/java/io/vertx/ext/jdbc/spi/JDBCDecoder.java
import io.vertx.ext.jdbc.impl.actions.SQLValueProvider;
import io.vertx.jdbcclient.impl.actions.JDBCColumnDescriptor;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.ext.jdbc.spi;
/**
* Represents for JDBC decoder from SQL value to Java value
* <p>
* The default decoder provides the best efforts to convert {@code SQL type} to standard {@code Java type} as {@code
* JDBC 4.2} spec.
* <p>
* You can replace it to adapt to a specific SQL driver by creating your owns then includes in the SPI file ({@code
* META-INF/services/io.vertx.ext.jdbc.spi.JDBCDecoder})
*
* @see <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/jdbc_42.html">Mapping of java.sql.Types to
* SQL types</a>
* @see io.vertx.ext.jdbc.spi.impl.JDBCDecoderImpl
* @see java.sql.JDBCType
* @see java.sql.SQLType
* @since 4.2.0
*/
public interface JDBCDecoder {
/**
* Parse SQL value to Java value
*
* @param rs JDBC result set
* @param pos the Database column position
* @param jdbcTypeLookup JDBCType provider
* @return java value
* @throws SQLException if any error in parsing
* @see ResultSet
* @see JDBCColumnDescriptorProvider
* @since 4.2.2
*/
Object parse(ResultSet rs, int pos, JDBCColumnDescriptorProvider jdbcTypeLookup) throws SQLException;
/**
* Parse SQL value to Java value
*
* @param cs JDBC callable statement
* @param pos the parameter column position
* @param jdbcTypeLookup JDBCType provider
* @return java value
* @throws SQLException if any error in parsing
* @see CallableStatement
* @see JDBCColumnDescriptorProvider
* @since 4.2.2
*/
Object parse(CallableStatement cs, int pos, JDBCColumnDescriptorProvider jdbcTypeLookup) throws SQLException;
/**
* Convert the SQL value to Java value based on jdbc type
*
* @param descriptor the JDBC column descriptor
* @param valueProvider the value provider
* @return java value
* @see SQLValueProvider
* @see JDBCColumnDescriptor
* @since 4.2.2
*/ | Object decode(JDBCColumnDescriptor descriptor, SQLValueProvider valueProvider) throws SQLException; |
vert-x3/vertx-jdbc-client | src/main/java/io/vertx/ext/jdbc/spi/DataSourceProvider.java | // Path: src/main/java/io/vertx/ext/jdbc/JDBCClient.java
// @VertxGen
// public interface JDBCClient extends SQLClient {
//
// /**
// * The default data source provider is C3P0
// */
// String DEFAULT_PROVIDER_CLASS = "io.vertx.ext.jdbc.spi.impl.C3P0DataSourceProvider";
//
// /**
// * The name of the default data source
// */
// String DEFAULT_DS_NAME = "DEFAULT_DS";
//
// /**
// * Create a JDBC client which maintains its own data source.
// *
// * @param vertx the Vert.x instance
// * @param config the configuration
// * @return the client
// */
// static JDBCClient create(Vertx vertx, JsonObject config) {
// return new JDBCClientImpl(vertx, config, UUID.randomUUID().toString());
// }
//
// /**
// * Create a JDBC client which shares its data source with any other JDBC clients created with the same
// * data source name
// *
// * @param vertx the Vert.x instance
// * @param config the configuration
// * @param dataSourceName the data source name
// * @return the client
// */
// static JDBCClient createShared(Vertx vertx, JsonObject config, String dataSourceName) {
// return new JDBCClientImpl(vertx, config, dataSourceName);
// }
//
// /**
// * Like {@link #createShared(io.vertx.core.Vertx, JsonObject, String)} but with the default data source name
// * @param vertx the Vert.x instance
// * @param config the configuration
// * @return the client
// */
// static JDBCClient createShared(Vertx vertx, JsonObject config) {
// return new JDBCClientImpl(vertx, config, DEFAULT_DS_NAME);
// }
//
// /**
// * Create a client using a pre-existing data source
// *
// * @param vertx the Vert.x instance
// * @param dataSource the datasource
// * @return the client
// */
// @GenIgnore
// static JDBCClient create(Vertx vertx, DataSource dataSource) {
// return new JDBCClientImpl(vertx, dataSource);
// }
//
// /**
// * Create a client using a data source provider
// *
// * @param vertx the Vert.x instance
// * @param dataSourceProvider the datasource provider
// * @return the client
// * @since 4.2.0
// */
// @GenIgnore
// static JDBCClient create(Vertx vertx, DataSourceProvider dataSourceProvider) {
// return new JDBCClientImpl(vertx, dataSourceProvider);
// }
//
// }
| import java.sql.SQLException;
import java.util.Objects;
import javax.sql.DataSource;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.jdbc.JDBCClient; | /*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.ext.jdbc.spi;
/**
* @author <a href="mailto:[email protected]">Nick Scavelli</a>
*/
public interface DataSourceProvider {
/**
* Init provider with specific configuration
*
* @param sqlConfig SQL connection configuration
* @return a reference to this for fluent API
* @apiNote Use it conjunction with {@link #create(JsonObject)}
* @since 4.2.0
*/
default DataSourceProvider init(JsonObject sqlConfig) {
return this;
}
/**
* Get the SQL initial configuration
*
* @return an initial configuration
* @apiNote Use it conjunction with {@link #init(JsonObject)}
* @since 4.2.0
*/
default JsonObject getInitialConfig() {
return new JsonObject();
}
int maximumPoolSize(DataSource dataSource, JsonObject config) throws SQLException;
DataSource getDataSource(JsonObject config) throws SQLException;
void close(DataSource dataSource) throws SQLException;
static DataSourceProvider create(JsonObject config) {
String providerClass = config.getString("provider_class");
if (providerClass == null) { | // Path: src/main/java/io/vertx/ext/jdbc/JDBCClient.java
// @VertxGen
// public interface JDBCClient extends SQLClient {
//
// /**
// * The default data source provider is C3P0
// */
// String DEFAULT_PROVIDER_CLASS = "io.vertx.ext.jdbc.spi.impl.C3P0DataSourceProvider";
//
// /**
// * The name of the default data source
// */
// String DEFAULT_DS_NAME = "DEFAULT_DS";
//
// /**
// * Create a JDBC client which maintains its own data source.
// *
// * @param vertx the Vert.x instance
// * @param config the configuration
// * @return the client
// */
// static JDBCClient create(Vertx vertx, JsonObject config) {
// return new JDBCClientImpl(vertx, config, UUID.randomUUID().toString());
// }
//
// /**
// * Create a JDBC client which shares its data source with any other JDBC clients created with the same
// * data source name
// *
// * @param vertx the Vert.x instance
// * @param config the configuration
// * @param dataSourceName the data source name
// * @return the client
// */
// static JDBCClient createShared(Vertx vertx, JsonObject config, String dataSourceName) {
// return new JDBCClientImpl(vertx, config, dataSourceName);
// }
//
// /**
// * Like {@link #createShared(io.vertx.core.Vertx, JsonObject, String)} but with the default data source name
// * @param vertx the Vert.x instance
// * @param config the configuration
// * @return the client
// */
// static JDBCClient createShared(Vertx vertx, JsonObject config) {
// return new JDBCClientImpl(vertx, config, DEFAULT_DS_NAME);
// }
//
// /**
// * Create a client using a pre-existing data source
// *
// * @param vertx the Vert.x instance
// * @param dataSource the datasource
// * @return the client
// */
// @GenIgnore
// static JDBCClient create(Vertx vertx, DataSource dataSource) {
// return new JDBCClientImpl(vertx, dataSource);
// }
//
// /**
// * Create a client using a data source provider
// *
// * @param vertx the Vert.x instance
// * @param dataSourceProvider the datasource provider
// * @return the client
// * @since 4.2.0
// */
// @GenIgnore
// static JDBCClient create(Vertx vertx, DataSourceProvider dataSourceProvider) {
// return new JDBCClientImpl(vertx, dataSourceProvider);
// }
//
// }
// Path: src/main/java/io/vertx/ext/jdbc/spi/DataSourceProvider.java
import java.sql.SQLException;
import java.util.Objects;
import javax.sql.DataSource;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.jdbc.JDBCClient;
/*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.ext.jdbc.spi;
/**
* @author <a href="mailto:[email protected]">Nick Scavelli</a>
*/
public interface DataSourceProvider {
/**
* Init provider with specific configuration
*
* @param sqlConfig SQL connection configuration
* @return a reference to this for fluent API
* @apiNote Use it conjunction with {@link #create(JsonObject)}
* @since 4.2.0
*/
default DataSourceProvider init(JsonObject sqlConfig) {
return this;
}
/**
* Get the SQL initial configuration
*
* @return an initial configuration
* @apiNote Use it conjunction with {@link #init(JsonObject)}
* @since 4.2.0
*/
default JsonObject getInitialConfig() {
return new JsonObject();
}
int maximumPoolSize(DataSource dataSource, JsonObject config) throws SQLException;
DataSource getDataSource(JsonObject config) throws SQLException;
void close(DataSource dataSource) throws SQLException;
static DataSourceProvider create(JsonObject config) {
String providerClass = config.getString("provider_class");
if (providerClass == null) { | providerClass = JDBCClient.DEFAULT_PROVIDER_CLASS; |
vert-x3/vertx-jdbc-client | src/main/java/io/vertx/ext/jdbc/impl/actions/JDBCQuery.java | // Path: src/main/java/io/vertx/ext/sql/SQLOptions.java
// @DataObject(generateConverter = true)
// public class SQLOptions {
//
// // connection
// private boolean readOnly;
// private String catalog;
// private TransactionIsolation transactionIsolation;
// private ResultSetType resultSetType;
// private ResultSetConcurrency resultSetConcurrency;
// // backwards compatibility
// private boolean autoGeneratedKeys = true;
// private JsonArray autoGeneratedKeysIndexes;
// private String schema;
// // statement
// private int queryTimeout;
// private int maxRows;
// // resultset
// private FetchDirection fetchDirection;
// private int fetchSize;
//
// /**
// * Default constructor
// */
// public SQLOptions() {
// }
//
// /**
// * Copy constructor
// *
// * @param other the result to copy
// */
// public SQLOptions(SQLOptions other) {
// this.readOnly = other.isReadOnly();
// this.catalog = other.getCatalog();
// this.transactionIsolation = other.getTransactionIsolation();
// this.resultSetType = other.getResultSetType();
// this.resultSetConcurrency = other.getResultSetConcurrency();
// this.autoGeneratedKeys = other.isAutoGeneratedKeys();
// this.autoGeneratedKeysIndexes = other.getAutoGeneratedKeysIndexes();
// this.schema = other.getSchema();
// this.queryTimeout = other.getQueryTimeout();
// this.fetchDirection = other.getFetchDirection();
// this.fetchSize = other.getFetchSize();
// this.maxRows = other.getMaxRows();
// }
//
// /**
// * Constructor from JSON
// *
// * @param json the json
// */
// public SQLOptions(JsonObject json) {
// SQLOptionsConverter.fromJson(json, this);
// }
//
// public boolean isReadOnly() {
// return readOnly;
// }
//
// public SQLOptions setReadOnly(boolean readOnly) {
// this.readOnly = readOnly;
// return this;
// }
//
// public String getCatalog() {
// return catalog;
// }
//
// public SQLOptions setCatalog(String catalog) {
// this.catalog = catalog;
// return this;
// }
//
// public TransactionIsolation getTransactionIsolation() {
// return transactionIsolation;
// }
//
// public SQLOptions setTransactionIsolation(TransactionIsolation transactionIsolation) {
// this.transactionIsolation = transactionIsolation;
// return this;
// }
//
// public ResultSetType getResultSetType() {
// return resultSetType;
// }
//
// public SQLOptions setResultSetType(ResultSetType resultSetType) {
// this.resultSetType = resultSetType;
// return this;
// }
//
// public ResultSetConcurrency getResultSetConcurrency() {
// return resultSetConcurrency;
// }
//
// public SQLOptions setResultSetConcurrency(ResultSetConcurrency resultSetConcurrency) {
// this.resultSetConcurrency = resultSetConcurrency;
// return this;
// }
//
// public boolean isAutoGeneratedKeys() {
// return autoGeneratedKeys;
// }
//
// public SQLOptions setAutoGeneratedKeys(boolean autoGeneratedKeys) {
// this.autoGeneratedKeys = autoGeneratedKeys;
// return this;
// }
//
// public String getSchema() {
// return schema;
// }
//
// public SQLOptions setSchema(String schema) {
// this.schema = schema;
// return this;
// }
//
// public int getQueryTimeout() {
// return queryTimeout;
// }
//
// public SQLOptions setQueryTimeout(int queryTimeout) {
// this.queryTimeout = queryTimeout;
// return this;
// }
//
// public FetchDirection getFetchDirection() {
// return fetchDirection;
// }
//
// public SQLOptions setFetchDirection(FetchDirection fetchDirection) {
// this.fetchDirection = fetchDirection;
// return this;
// }
//
// public int getFetchSize() {
// return fetchSize;
// }
//
// public SQLOptions setFetchSize(int fetchSize) {
// this.fetchSize = fetchSize;
// return this;
// }
//
// public JsonArray getAutoGeneratedKeysIndexes() {
// return autoGeneratedKeysIndexes;
// }
//
// public SQLOptions setAutoGeneratedKeysIndexes(JsonArray autoGeneratedKeysIndexes) {
// this.autoGeneratedKeysIndexes = autoGeneratedKeysIndexes;
// return this;
// }
//
// public int getMaxRows() {
// return maxRows;
// }
//
// public SQLOptions setMaxRows(int maxRows) {
// this.maxRows = maxRows;
// return this;
// }
// }
| import io.vertx.core.json.JsonArray;
import io.vertx.ext.sql.SQLOptions;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; | /*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.ext.jdbc.impl.actions;
/**
* @author <a href="mailto:[email protected]">Nick Scavelli</a>
*/
public class JDBCQuery extends AbstractJDBCAction<io.vertx.ext.sql.ResultSet> {
private final String sql;
private final JsonArray in;
| // Path: src/main/java/io/vertx/ext/sql/SQLOptions.java
// @DataObject(generateConverter = true)
// public class SQLOptions {
//
// // connection
// private boolean readOnly;
// private String catalog;
// private TransactionIsolation transactionIsolation;
// private ResultSetType resultSetType;
// private ResultSetConcurrency resultSetConcurrency;
// // backwards compatibility
// private boolean autoGeneratedKeys = true;
// private JsonArray autoGeneratedKeysIndexes;
// private String schema;
// // statement
// private int queryTimeout;
// private int maxRows;
// // resultset
// private FetchDirection fetchDirection;
// private int fetchSize;
//
// /**
// * Default constructor
// */
// public SQLOptions() {
// }
//
// /**
// * Copy constructor
// *
// * @param other the result to copy
// */
// public SQLOptions(SQLOptions other) {
// this.readOnly = other.isReadOnly();
// this.catalog = other.getCatalog();
// this.transactionIsolation = other.getTransactionIsolation();
// this.resultSetType = other.getResultSetType();
// this.resultSetConcurrency = other.getResultSetConcurrency();
// this.autoGeneratedKeys = other.isAutoGeneratedKeys();
// this.autoGeneratedKeysIndexes = other.getAutoGeneratedKeysIndexes();
// this.schema = other.getSchema();
// this.queryTimeout = other.getQueryTimeout();
// this.fetchDirection = other.getFetchDirection();
// this.fetchSize = other.getFetchSize();
// this.maxRows = other.getMaxRows();
// }
//
// /**
// * Constructor from JSON
// *
// * @param json the json
// */
// public SQLOptions(JsonObject json) {
// SQLOptionsConverter.fromJson(json, this);
// }
//
// public boolean isReadOnly() {
// return readOnly;
// }
//
// public SQLOptions setReadOnly(boolean readOnly) {
// this.readOnly = readOnly;
// return this;
// }
//
// public String getCatalog() {
// return catalog;
// }
//
// public SQLOptions setCatalog(String catalog) {
// this.catalog = catalog;
// return this;
// }
//
// public TransactionIsolation getTransactionIsolation() {
// return transactionIsolation;
// }
//
// public SQLOptions setTransactionIsolation(TransactionIsolation transactionIsolation) {
// this.transactionIsolation = transactionIsolation;
// return this;
// }
//
// public ResultSetType getResultSetType() {
// return resultSetType;
// }
//
// public SQLOptions setResultSetType(ResultSetType resultSetType) {
// this.resultSetType = resultSetType;
// return this;
// }
//
// public ResultSetConcurrency getResultSetConcurrency() {
// return resultSetConcurrency;
// }
//
// public SQLOptions setResultSetConcurrency(ResultSetConcurrency resultSetConcurrency) {
// this.resultSetConcurrency = resultSetConcurrency;
// return this;
// }
//
// public boolean isAutoGeneratedKeys() {
// return autoGeneratedKeys;
// }
//
// public SQLOptions setAutoGeneratedKeys(boolean autoGeneratedKeys) {
// this.autoGeneratedKeys = autoGeneratedKeys;
// return this;
// }
//
// public String getSchema() {
// return schema;
// }
//
// public SQLOptions setSchema(String schema) {
// this.schema = schema;
// return this;
// }
//
// public int getQueryTimeout() {
// return queryTimeout;
// }
//
// public SQLOptions setQueryTimeout(int queryTimeout) {
// this.queryTimeout = queryTimeout;
// return this;
// }
//
// public FetchDirection getFetchDirection() {
// return fetchDirection;
// }
//
// public SQLOptions setFetchDirection(FetchDirection fetchDirection) {
// this.fetchDirection = fetchDirection;
// return this;
// }
//
// public int getFetchSize() {
// return fetchSize;
// }
//
// public SQLOptions setFetchSize(int fetchSize) {
// this.fetchSize = fetchSize;
// return this;
// }
//
// public JsonArray getAutoGeneratedKeysIndexes() {
// return autoGeneratedKeysIndexes;
// }
//
// public SQLOptions setAutoGeneratedKeysIndexes(JsonArray autoGeneratedKeysIndexes) {
// this.autoGeneratedKeysIndexes = autoGeneratedKeysIndexes;
// return this;
// }
//
// public int getMaxRows() {
// return maxRows;
// }
//
// public SQLOptions setMaxRows(int maxRows) {
// this.maxRows = maxRows;
// return this;
// }
// }
// Path: src/main/java/io/vertx/ext/jdbc/impl/actions/JDBCQuery.java
import io.vertx.core.json.JsonArray;
import io.vertx.ext.sql.SQLOptions;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.ext.jdbc.impl.actions;
/**
* @author <a href="mailto:[email protected]">Nick Scavelli</a>
*/
public class JDBCQuery extends AbstractJDBCAction<io.vertx.ext.sql.ResultSet> {
private final String sql;
private final JsonArray in;
| public JDBCQuery(JDBCStatementHelper helper, SQLOptions options, String sql, JsonArray in) { |
soluvas/sanad | app/src/main/java/org/soluvas/sanad/app/AppConfig.java | // Path: core/src/main/java/org/soluvas/sanad/core/mvc/SanadMvcConfig.java
// @Configuration
// @Import(SanadConfig.class)
// @ComponentScan("org.soluvas.sanad.core.mvc")
// @EnableTransactionManagement
// @EnableWebMvc
// @EnableSwagger
// public class SanadMvcConfig extends WebMvcConfigurerAdapter {
//
// private static final Logger log = LoggerFactory
// .getLogger(SanadMvcConfig.class);
//
// @Override
// public void addResourceHandlers(ResourceHandlerRegistry registry) {
// // registry.addResourceHandler("/swagger/**")
// // .addResourceLocations("classpath:/swagger/");
// }
//
// @Override
// public void configureDefaultServletHandling(
// DefaultServletHandlerConfigurer configurer) {
// configurer.enable();
// }
//
// @Override
// public void configureMessageConverters(
// List<HttpMessageConverter<?>> converters) {
// MappingJackson2HttpMessageConverter jackson2 = new MappingJackson2HttpMessageConverter();
// jackson2.setObjectMapper(JsonUtils.mapper);
// converters.add(jackson2);
// log.info("Spring MVC Message Converters: {}", converters);
// }
//
// }
| import java.io.File;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import org.soluvas.commons.AggregatingSupplier;
import org.soluvas.commons.AppManifest;
import org.soluvas.commons.SupplierXmiClasspathScanner;
import org.soluvas.commons.config.CommonsWebConfig;
import org.soluvas.commons.config.MultiTenantConfig;
import org.soluvas.commons.config.MultiTenantWebConfig;
import org.soluvas.commons.config.TenantSelector;
import org.soluvas.commons.tenant.TenantBeans;
import org.soluvas.commons.tenant.TenantUtils;
import org.soluvas.data.repository.CrudRepository;
import org.soluvas.sanad.core.mvc.SanadMvcConfig;
import org.soluvas.web.site.CssLink;
import org.soluvas.web.site.JavaScriptLink;
import org.soluvas.web.site.JavaScriptSource;
import org.soluvas.web.site.PageMetaProvider;
import org.soluvas.web.site.PermalinkConfig;
import org.soluvas.web.site.RulesPageMetaProvider;
import org.soluvas.web.site.SimpleSite;
import org.soluvas.web.site.Site;
import org.soluvas.web.site.compose.EmfGenericRepository;
import org.soluvas.web.site.compose.LiveContributor;
import org.soluvas.web.site.pagemeta.PageMetaCatalog;
import org.soluvas.web.site.pagemeta.PagemetaFactory;
import org.soluvas.web.site.pagemeta.PagemetaPackage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;
import org.springframework.core.env.Environment;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.eventbus.EventBus; | package org.soluvas.sanad.app;
/**
* @author ceefour
*
*/
@Configuration
@PropertySource("classpath:/META-INF/sanad.properties") | // Path: core/src/main/java/org/soluvas/sanad/core/mvc/SanadMvcConfig.java
// @Configuration
// @Import(SanadConfig.class)
// @ComponentScan("org.soluvas.sanad.core.mvc")
// @EnableTransactionManagement
// @EnableWebMvc
// @EnableSwagger
// public class SanadMvcConfig extends WebMvcConfigurerAdapter {
//
// private static final Logger log = LoggerFactory
// .getLogger(SanadMvcConfig.class);
//
// @Override
// public void addResourceHandlers(ResourceHandlerRegistry registry) {
// // registry.addResourceHandler("/swagger/**")
// // .addResourceLocations("classpath:/swagger/");
// }
//
// @Override
// public void configureDefaultServletHandling(
// DefaultServletHandlerConfigurer configurer) {
// configurer.enable();
// }
//
// @Override
// public void configureMessageConverters(
// List<HttpMessageConverter<?>> converters) {
// MappingJackson2HttpMessageConverter jackson2 = new MappingJackson2HttpMessageConverter();
// jackson2.setObjectMapper(JsonUtils.mapper);
// converters.add(jackson2);
// log.info("Spring MVC Message Converters: {}", converters);
// }
//
// }
// Path: app/src/main/java/org/soluvas/sanad/app/AppConfig.java
import java.io.File;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import org.soluvas.commons.AggregatingSupplier;
import org.soluvas.commons.AppManifest;
import org.soluvas.commons.SupplierXmiClasspathScanner;
import org.soluvas.commons.config.CommonsWebConfig;
import org.soluvas.commons.config.MultiTenantConfig;
import org.soluvas.commons.config.MultiTenantWebConfig;
import org.soluvas.commons.config.TenantSelector;
import org.soluvas.commons.tenant.TenantBeans;
import org.soluvas.commons.tenant.TenantUtils;
import org.soluvas.data.repository.CrudRepository;
import org.soluvas.sanad.core.mvc.SanadMvcConfig;
import org.soluvas.web.site.CssLink;
import org.soluvas.web.site.JavaScriptLink;
import org.soluvas.web.site.JavaScriptSource;
import org.soluvas.web.site.PageMetaProvider;
import org.soluvas.web.site.PermalinkConfig;
import org.soluvas.web.site.RulesPageMetaProvider;
import org.soluvas.web.site.SimpleSite;
import org.soluvas.web.site.Site;
import org.soluvas.web.site.compose.EmfGenericRepository;
import org.soluvas.web.site.compose.LiveContributor;
import org.soluvas.web.site.pagemeta.PageMetaCatalog;
import org.soluvas.web.site.pagemeta.PagemetaFactory;
import org.soluvas.web.site.pagemeta.PagemetaPackage;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;
import org.springframework.core.env.Environment;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.eventbus.EventBus;
package org.soluvas.sanad.app;
/**
* @author ceefour
*
*/
@Configuration
@PropertySource("classpath:/META-INF/sanad.properties") | @Import({SanadSecurityConfig.class, MultiTenantWebConfig.class, SanadMvcConfig.class}) |
soluvas/sanad | core/src/test/java/org/soluvas/sanad/core/mvc/AnnotationTest.java | // Path: core/src/test/java/org/soluvas/sanad/core/PropertyMockingApplicationContextInitializer.java
// public class PropertyMockingApplicationContextInitializer implements
// ApplicationContextInitializer<ConfigurableApplicationContext> {
//
// @Override
// public void initialize(ConfigurableApplicationContext applicationContext) {
// MutablePropertySources propertySources = applicationContext
// .getEnvironment().getPropertySources();
// MockPropertySource mockEnvVars = new MockPropertySource()
// // PostgresConfig
// .withProperty("sqlUrl", "jdbc:postgresql://localhost/sanad_sanad_dev")
// .withProperty("sqlUser", "postgres")
// .withProperty("sqlPassword", "bippo")
// .withProperty("jpaHbm2DdlAuto", "update")
// // Multitenancy
// .withProperty("tenantEnv", "dev")
// .withProperty("workspaceDir", new File(System.getProperty("user.home"), "sanad_sanad_dev"))
// .withProperty("tenantId", "sanad")
// .withProperty("tenantSource", TenantSource.CONFIG);
// propertySources.replace(
// StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME,
// mockEnvVars);
//
// final CustomScopeConfigurer scopeConfigurer = new CustomScopeConfigurer();
// scopeConfigurer.setScopes(ImmutableMap.<String, Object>of(WebApplicationContext.SCOPE_REQUEST, new RequestOrCommandScope()));
// applicationContext.addBeanFactoryPostProcessor(scopeConfigurer);
// }
//
// }
| import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.soluvas.sanad.core.PropertyMockingApplicationContextInitializer;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext; | package org.soluvas.sanad.core.mvc;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration | // Path: core/src/test/java/org/soluvas/sanad/core/PropertyMockingApplicationContextInitializer.java
// public class PropertyMockingApplicationContextInitializer implements
// ApplicationContextInitializer<ConfigurableApplicationContext> {
//
// @Override
// public void initialize(ConfigurableApplicationContext applicationContext) {
// MutablePropertySources propertySources = applicationContext
// .getEnvironment().getPropertySources();
// MockPropertySource mockEnvVars = new MockPropertySource()
// // PostgresConfig
// .withProperty("sqlUrl", "jdbc:postgresql://localhost/sanad_sanad_dev")
// .withProperty("sqlUser", "postgres")
// .withProperty("sqlPassword", "bippo")
// .withProperty("jpaHbm2DdlAuto", "update")
// // Multitenancy
// .withProperty("tenantEnv", "dev")
// .withProperty("workspaceDir", new File(System.getProperty("user.home"), "sanad_sanad_dev"))
// .withProperty("tenantId", "sanad")
// .withProperty("tenantSource", TenantSource.CONFIG);
// propertySources.replace(
// StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME,
// mockEnvVars);
//
// final CustomScopeConfigurer scopeConfigurer = new CustomScopeConfigurer();
// scopeConfigurer.setScopes(ImmutableMap.<String, Object>of(WebApplicationContext.SCOPE_REQUEST, new RequestOrCommandScope()));
// applicationContext.addBeanFactoryPostProcessor(scopeConfigurer);
// }
//
// }
// Path: core/src/test/java/org/soluvas/sanad/core/mvc/AnnotationTest.java
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.soluvas.sanad.core.PropertyMockingApplicationContextInitializer;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;
package org.soluvas.sanad.core.mvc;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration | @ContextConfiguration(classes=SanadMvcConfig.class, initializers=PropertyMockingApplicationContextInitializer.class) |
soluvas/sanad | core/src/main/java/org/soluvas/sanad/core/jpa/Literal.java | // Path: core/src/main/java/org/soluvas/sanad/core/AsciidocUtils.java
// public class AsciidocUtils {
//
// static final Pattern NOT_PRINT = Pattern.compile("([\\p{Punct}\\p{Cntrl}\\p{Sc}]|\\P{Print})+", Pattern.UNICODE_CHARACTER_CLASS);
// static final Pattern WHITESPACE = Pattern.compile("\\s+", Pattern.UNICODE_CHARACTER_CLASS);
//
// /**
// * Normalize with Unicode aware.
// * @param adoc
// * @return
// */
// public static String normalize(String adoc) {
// String normalized = Normalizer.normalize(adoc, Normalizer.Form.NFC);
// normalized = adoc.toLowerCase(Locale.ROOT);
// normalized = NOT_PRINT.matcher(adoc).replaceAll(" ");
// normalized = WHITESPACE.matcher(adoc).replaceAll(" ");
// normalized = normalized.trim();
// return normalized;
// }
//
// }
| import java.util.HashSet;
import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Index;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.soluvas.sanad.core.AsciidocUtils;
import com.google.common.html.HtmlEscapers; | * href="http://tools.ietf.org/html/bcp47">IETF BCP 47</a>. <!--
* end-model-doc -->
*
* @param newInLanguage
* the new value of the '{@link Literal#getInLanguage()
* inLanguage}' feature.
* @generated
*/
public void setInLanguage(String newInLanguage) {
inLanguage = newInLanguage;
}
/**
* A toString method which prints the values of all EAttributes of this
* instance. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public String toString() {
return "Literal " + " [normalized: " + getNormalized() + "]"
+ " [numeronym: " + getNumeronym() + "]" + " [inLanguage: "
+ getInLanguage() + "]" + " [adoc: " + getAdoc() + "]"
+ " [html: " + getHtml() + "]" + " [translator: "
+ getTranslator() + "]";
}
public void assignAdoc(String adoc) {
setAdoc(adoc);
setHtml(HtmlEscapers.htmlEscaper().escape(adoc)); | // Path: core/src/main/java/org/soluvas/sanad/core/AsciidocUtils.java
// public class AsciidocUtils {
//
// static final Pattern NOT_PRINT = Pattern.compile("([\\p{Punct}\\p{Cntrl}\\p{Sc}]|\\P{Print})+", Pattern.UNICODE_CHARACTER_CLASS);
// static final Pattern WHITESPACE = Pattern.compile("\\s+", Pattern.UNICODE_CHARACTER_CLASS);
//
// /**
// * Normalize with Unicode aware.
// * @param adoc
// * @return
// */
// public static String normalize(String adoc) {
// String normalized = Normalizer.normalize(adoc, Normalizer.Form.NFC);
// normalized = adoc.toLowerCase(Locale.ROOT);
// normalized = NOT_PRINT.matcher(adoc).replaceAll(" ");
// normalized = WHITESPACE.matcher(adoc).replaceAll(" ");
// normalized = normalized.trim();
// return normalized;
// }
//
// }
// Path: core/src/main/java/org/soluvas/sanad/core/jpa/Literal.java
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Index;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.soluvas.sanad.core.AsciidocUtils;
import com.google.common.html.HtmlEscapers;
* href="http://tools.ietf.org/html/bcp47">IETF BCP 47</a>. <!--
* end-model-doc -->
*
* @param newInLanguage
* the new value of the '{@link Literal#getInLanguage()
* inLanguage}' feature.
* @generated
*/
public void setInLanguage(String newInLanguage) {
inLanguage = newInLanguage;
}
/**
* A toString method which prints the values of all EAttributes of this
* instance. <!-- begin-user-doc --> <!-- end-user-doc -->
*
* @generated
*/
@Override
public String toString() {
return "Literal " + " [normalized: " + getNormalized() + "]"
+ " [numeronym: " + getNumeronym() + "]" + " [inLanguage: "
+ getInLanguage() + "]" + " [adoc: " + getAdoc() + "]"
+ " [html: " + getHtml() + "]" + " [translator: "
+ getTranslator() + "]";
}
public void assignAdoc(String adoc) {
setAdoc(adoc);
setHtml(HtmlEscapers.htmlEscaper().escape(adoc)); | setNormalized(AsciidocUtils.normalize(adoc)); |
soluvas/sanad | app/src/main/java/org/soluvas/sanad/app/ServletConfig.java | // Path: core/src/main/java/org/soluvas/sanad/core/mvc/SanadMvcConfig.java
// @Configuration
// @Import(SanadConfig.class)
// @ComponentScan("org.soluvas.sanad.core.mvc")
// @EnableTransactionManagement
// @EnableWebMvc
// @EnableSwagger
// public class SanadMvcConfig extends WebMvcConfigurerAdapter {
//
// private static final Logger log = LoggerFactory
// .getLogger(SanadMvcConfig.class);
//
// @Override
// public void addResourceHandlers(ResourceHandlerRegistry registry) {
// // registry.addResourceHandler("/swagger/**")
// // .addResourceLocations("classpath:/swagger/");
// }
//
// @Override
// public void configureDefaultServletHandling(
// DefaultServletHandlerConfigurer configurer) {
// configurer.enable();
// }
//
// @Override
// public void configureMessageConverters(
// List<HttpMessageConverter<?>> converters) {
// MappingJackson2HttpMessageConverter jackson2 = new MappingJackson2HttpMessageConverter();
// jackson2.setObjectMapper(JsonUtils.mapper);
// converters.add(jackson2);
// log.info("Spring MVC Message Converters: {}", converters);
// }
//
// }
| import javax.inject.Inject;
import org.soluvas.sanad.core.mvc.SanadMvcConfig;
import org.springframework.context.annotation.Configuration; | package org.soluvas.sanad.app;
@Configuration
public class ServletConfig {
@Inject | // Path: core/src/main/java/org/soluvas/sanad/core/mvc/SanadMvcConfig.java
// @Configuration
// @Import(SanadConfig.class)
// @ComponentScan("org.soluvas.sanad.core.mvc")
// @EnableTransactionManagement
// @EnableWebMvc
// @EnableSwagger
// public class SanadMvcConfig extends WebMvcConfigurerAdapter {
//
// private static final Logger log = LoggerFactory
// .getLogger(SanadMvcConfig.class);
//
// @Override
// public void addResourceHandlers(ResourceHandlerRegistry registry) {
// // registry.addResourceHandler("/swagger/**")
// // .addResourceLocations("classpath:/swagger/");
// }
//
// @Override
// public void configureDefaultServletHandling(
// DefaultServletHandlerConfigurer configurer) {
// configurer.enable();
// }
//
// @Override
// public void configureMessageConverters(
// List<HttpMessageConverter<?>> converters) {
// MappingJackson2HttpMessageConverter jackson2 = new MappingJackson2HttpMessageConverter();
// jackson2.setObjectMapper(JsonUtils.mapper);
// converters.add(jackson2);
// log.info("Spring MVC Message Converters: {}", converters);
// }
//
// }
// Path: app/src/main/java/org/soluvas/sanad/app/ServletConfig.java
import javax.inject.Inject;
import org.soluvas.sanad.core.mvc.SanadMvcConfig;
import org.springframework.context.annotation.Configuration;
package org.soluvas.sanad.app;
@Configuration
public class ServletConfig {
@Inject | SanadMvcConfig sanadMvcConfig; |
xinthink/xinkvpn | main/src/domain/xink/vpn/wrapper/L2tpProfile.java | // Path: main/src/domain/xink/vpn/AppException.java
// public class AppException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// private int messageCode;
//
// private Object[] messageArgs;
//
// public AppException(final String detailMessage) {
// super(detailMessage);
// }
//
// public AppException(final String message, final int msgCode, final Object... msgArgs) {
// super(message);
// this.messageCode = msgCode;
// this.messageArgs = msgArgs;
// }
//
// public AppException(final String message, final Throwable throwable, final int msgCode, final Object... msgArgs) {
// super(message, throwable);
// this.messageCode = msgCode;
// this.messageArgs = msgArgs;
// }
//
// public AppException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// public int getMessageCode() {
// return messageCode;
// }
//
// public Object[] getMessageArgs() {
// return messageArgs;
// }
//
// }
| import java.lang.reflect.Method;
import xink.vpn.AppException;
import xink.vpn.R;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log; | /*
* Copyright 2011 [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xink.vpn.wrapper;
public class L2tpProfile extends VpnProfile {
/** Key prefix for L2TP VPN. */
public static final String KEY_PREFIX_L2TP_SECRET = "VPN_l";
private KeyStore keyStore;
protected L2tpProfile(final Context ctx, final String stubClass) {
super(ctx, stubClass);
}
public L2tpProfile(final Context ctx) {
super(ctx, "android.net.vpn.L2tpProfile");
}
@Override
public VpnType getType() {
return VpnType.L2TP;
}
/**
* Enables/disables the secret for authenticating tunnel connection.
*/
public void setSecretEnabled(final boolean enabled) {
try {
Method m = getStubClass().getMethod("setSecretEnabled", boolean.class);
m.invoke(getStub(), enabled);
} catch (Throwable e) { | // Path: main/src/domain/xink/vpn/AppException.java
// public class AppException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// private int messageCode;
//
// private Object[] messageArgs;
//
// public AppException(final String detailMessage) {
// super(detailMessage);
// }
//
// public AppException(final String message, final int msgCode, final Object... msgArgs) {
// super(message);
// this.messageCode = msgCode;
// this.messageArgs = msgArgs;
// }
//
// public AppException(final String message, final Throwable throwable, final int msgCode, final Object... msgArgs) {
// super(message, throwable);
// this.messageCode = msgCode;
// this.messageArgs = msgArgs;
// }
//
// public AppException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// public int getMessageCode() {
// return messageCode;
// }
//
// public Object[] getMessageArgs() {
// return messageArgs;
// }
//
// }
// Path: main/src/domain/xink/vpn/wrapper/L2tpProfile.java
import java.lang.reflect.Method;
import xink.vpn.AppException;
import xink.vpn.R;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
/*
* Copyright 2011 [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xink.vpn.wrapper;
public class L2tpProfile extends VpnProfile {
/** Key prefix for L2TP VPN. */
public static final String KEY_PREFIX_L2TP_SECRET = "VPN_l";
private KeyStore keyStore;
protected L2tpProfile(final Context ctx, final String stubClass) {
super(ctx, stubClass);
}
public L2tpProfile(final Context ctx) {
super(ctx, "android.net.vpn.L2tpProfile");
}
@Override
public VpnType getType() {
return VpnType.L2TP;
}
/**
* Enables/disables the secret for authenticating tunnel connection.
*/
public void setSecretEnabled(final boolean enabled) {
try {
Method m = getStubClass().getMethod("setSecretEnabled", boolean.class);
m.invoke(getStub(), enabled);
} catch (Throwable e) { | throw new AppException("setSecretEnabled failed", e); |
xinthink/xinkvpn | main/src/service/xink/vpn/VpnAppWidgetProvider.java | // Path: main/src/java/xink/vpn/Constants.java
// public final class Constants {
// public static final int REQ_SELECT_VPN_TYPE = 1;
//
// public static final int REQ_ADD_VPN = 2;
//
// public static final int REQ_EDIT_VPN = 3;
//
// public static final String ACT_ADD_VPN = "xink.addVpnAction";
//
// public static final String ACT_VPN_SETTINGS = "android.net.vpn.SETTINGS";
//
// public static final String CAT_DEFAULT = "android.intent.category.DEFAULT";
//
// public static final String KEY_VPN_TYPE = "vpnType";
//
// public static final String KEY_VPN_PROFILE_ID = "vpnProfileId";
//
// public static final String KEY_VPN_PROFILE_NAME = "vpnProfileName";
//
// public static final String KEY_VPN_STATE = "activeVpnState";
//
// public static final int DLG_VPN_PROFILE_ALERT = 1;
//
// public static final int DLG_ABOUT = 2;
//
// public static final int DLG_BACKUP = 3;
//
// public static final int DLG_RESTORE = 4;
//
// public static final int DLG_HACK = 5;
//
// // Action for broadcasting a connectivity state.
// public static final String ACTION_VPN_CONNECTIVITY = "vpn.connectivity";
// /** Key to the profile name of a connectivity broadcast event. */
// public static final String BROADCAST_PROFILE_NAME = "profile_name";
// /** Key to the connectivity state of a connectivity broadcast event. */
// public static final String BROADCAST_CONNECTION_STATE = "connection_state";
// /** Key to the error code of a connectivity broadcast event. */
// public static final String BROADCAST_ERROR_CODE = "err";
// /** Error code to indicate an error from authentication. */
// public static final int VPN_ERROR_AUTH = 51;
// /** Error code to indicate the connection attempt failed. */
// public static final int VPN_ERROR_CONNECTION_FAILED = 101;
// /** Error code to indicate the server is not known. */
// public static final int VPN_ERROR_UNKNOWN_SERVER = 102;
// /** Error code to indicate an error from challenge response. */
// public static final int VPN_ERROR_CHALLENGE = 5;
// /** Error code to indicate an error of remote server hanging up. */
// public static final int VPN_ERROR_REMOTE_HUNG_UP = 7;
// /** Error code to indicate an error of remote PPP server hanging up. */
// public static final int VPN_ERROR_REMOTE_PPP_HUNG_UP = 48;
// /** Error code to indicate a PPP negotiation error. */
// public static final int VPN_ERROR_PPP_NEGOTIATION_FAILED = 42;
// /** Error code to indicate an error of losing connectivity. */
// public static final int VPN_ERROR_CONNECTION_LOST = 103;
// /** Largest error code used by VPN. */
// public static final int VPN_ERROR_LARGEST = 200;
// /** Error code to indicate a successful connection. */
// public static final int VPN_ERROR_NO_ERROR = 0;
//
// public static final String EXP_DIR_REGEX = "\\d{6}\\-\\d{6}";
//
// private Constants() {
//
// }
// }
//
// Path: main/src/domain/xink/vpn/wrapper/VpnState.java
// public enum VpnState {
// CONNECTING, DISCONNECTING, CANCELLED, CONNECTED, IDLE, UNUSABLE, UNKNOWN;
//
// /**
// * Whether this's a transitive state
// */
// public boolean isTransitive() {
// return this == CONNECTING || this == DISCONNECTING;
// }
//
// /**
// * Whether this's a stable state
// */
// public boolean isStable() {
// return this == VpnState.CONNECTED || this == VpnState.IDLE;
// }
// }
| import static xink.vpn.Constants.*;
import xink.vpn.wrapper.VpnState;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews; | /*
* Copyright 2011 [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xink.vpn;
/**
* Install / update app widgets, according to active vpn conn status.
*
* @author ywu
*
*/
public class VpnAppWidgetProvider extends AppWidgetProvider {
private static final String TAG = "xink.AppWidget";
private static final ComponentName THIS_APPWIDGET = new ComponentName("xink.vpn", "xink.vpn.VpnAppWidgetProvider");
private Context context;
@Override
public void onEnabled(final Context context) {
super.onEnabled(context);
Log.d(TAG, "VpnAppWidgetProvider enabled");
this.context = context;
updateViews(getActiveVpnState(context));
}
@Override
public void onUpdate(final Context context, final AppWidgetManager appWidgetManager, final int[] appWidgetIds) {
Log.d(TAG, "VpnAppWidgetProvider onUpdate");
this.context = context;
updateViews(getActiveVpnState(context));
}
| // Path: main/src/java/xink/vpn/Constants.java
// public final class Constants {
// public static final int REQ_SELECT_VPN_TYPE = 1;
//
// public static final int REQ_ADD_VPN = 2;
//
// public static final int REQ_EDIT_VPN = 3;
//
// public static final String ACT_ADD_VPN = "xink.addVpnAction";
//
// public static final String ACT_VPN_SETTINGS = "android.net.vpn.SETTINGS";
//
// public static final String CAT_DEFAULT = "android.intent.category.DEFAULT";
//
// public static final String KEY_VPN_TYPE = "vpnType";
//
// public static final String KEY_VPN_PROFILE_ID = "vpnProfileId";
//
// public static final String KEY_VPN_PROFILE_NAME = "vpnProfileName";
//
// public static final String KEY_VPN_STATE = "activeVpnState";
//
// public static final int DLG_VPN_PROFILE_ALERT = 1;
//
// public static final int DLG_ABOUT = 2;
//
// public static final int DLG_BACKUP = 3;
//
// public static final int DLG_RESTORE = 4;
//
// public static final int DLG_HACK = 5;
//
// // Action for broadcasting a connectivity state.
// public static final String ACTION_VPN_CONNECTIVITY = "vpn.connectivity";
// /** Key to the profile name of a connectivity broadcast event. */
// public static final String BROADCAST_PROFILE_NAME = "profile_name";
// /** Key to the connectivity state of a connectivity broadcast event. */
// public static final String BROADCAST_CONNECTION_STATE = "connection_state";
// /** Key to the error code of a connectivity broadcast event. */
// public static final String BROADCAST_ERROR_CODE = "err";
// /** Error code to indicate an error from authentication. */
// public static final int VPN_ERROR_AUTH = 51;
// /** Error code to indicate the connection attempt failed. */
// public static final int VPN_ERROR_CONNECTION_FAILED = 101;
// /** Error code to indicate the server is not known. */
// public static final int VPN_ERROR_UNKNOWN_SERVER = 102;
// /** Error code to indicate an error from challenge response. */
// public static final int VPN_ERROR_CHALLENGE = 5;
// /** Error code to indicate an error of remote server hanging up. */
// public static final int VPN_ERROR_REMOTE_HUNG_UP = 7;
// /** Error code to indicate an error of remote PPP server hanging up. */
// public static final int VPN_ERROR_REMOTE_PPP_HUNG_UP = 48;
// /** Error code to indicate a PPP negotiation error. */
// public static final int VPN_ERROR_PPP_NEGOTIATION_FAILED = 42;
// /** Error code to indicate an error of losing connectivity. */
// public static final int VPN_ERROR_CONNECTION_LOST = 103;
// /** Largest error code used by VPN. */
// public static final int VPN_ERROR_LARGEST = 200;
// /** Error code to indicate a successful connection. */
// public static final int VPN_ERROR_NO_ERROR = 0;
//
// public static final String EXP_DIR_REGEX = "\\d{6}\\-\\d{6}";
//
// private Constants() {
//
// }
// }
//
// Path: main/src/domain/xink/vpn/wrapper/VpnState.java
// public enum VpnState {
// CONNECTING, DISCONNECTING, CANCELLED, CONNECTED, IDLE, UNUSABLE, UNKNOWN;
//
// /**
// * Whether this's a transitive state
// */
// public boolean isTransitive() {
// return this == CONNECTING || this == DISCONNECTING;
// }
//
// /**
// * Whether this's a stable state
// */
// public boolean isStable() {
// return this == VpnState.CONNECTED || this == VpnState.IDLE;
// }
// }
// Path: main/src/service/xink/vpn/VpnAppWidgetProvider.java
import static xink.vpn.Constants.*;
import xink.vpn.wrapper.VpnState;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
/*
* Copyright 2011 [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xink.vpn;
/**
* Install / update app widgets, according to active vpn conn status.
*
* @author ywu
*
*/
public class VpnAppWidgetProvider extends AppWidgetProvider {
private static final String TAG = "xink.AppWidget";
private static final ComponentName THIS_APPWIDGET = new ComponentName("xink.vpn", "xink.vpn.VpnAppWidgetProvider");
private Context context;
@Override
public void onEnabled(final Context context) {
super.onEnabled(context);
Log.d(TAG, "VpnAppWidgetProvider enabled");
this.context = context;
updateViews(getActiveVpnState(context));
}
@Override
public void onUpdate(final Context context, final AppWidgetManager appWidgetManager, final int[] appWidgetIds) {
Log.d(TAG, "VpnAppWidgetProvider onUpdate");
this.context = context;
updateViews(getActiveVpnState(context));
}
| private VpnState getActiveVpnState(final Context context) { |
xinthink/xinkvpn | tests/src/android/xink/vpn/test/CompatibleTest.java | // Path: main/src/domain/xink/vpn/wrapper/KeyStore.java
// public class KeyStore extends AbstractWrapper {
//
// public static final String UNLOCK_ACTION = "android.credentials.UNLOCK";
//
// private static final int NO_ERROR = 1;
//
// /*
// private static final int LOCKED = 2;
// private static final int UNINITIALIZED = 3;
// private static final int SYSTEM_ERROR = 4;
// private static final int PROTOCOL_ERROR = 5;
// private static final int PERMISSION_DENIED = 6;
// private static final int KEY_NOT_FOUND = 7;
// private static final int VALUE_CORRUPTED = 8;
// private static final int UNDEFINED_ACTION = 9;
// private static final int WRONG_PASSWORD = 10;
// */
//
// public KeyStore(final Context ctx) {
// super(ctx, "android.security.KeyStore", new StubInstanceCreator() {
// @Override
// protected Object newStubInstance(final Class<?> stubClass, final Context ctx) throws Exception {
// Method method = stubClass.getMethod("getInstance");
// return method.invoke(null);
// }
// });
// }
//
// public boolean put(final String key, final String value) {
// return this.<Boolean> invokeStubMethod("put", key, value);
// }
//
// public boolean contains(final VpnProfile p) {
// String key = L2tpIpsecPskProfile.KEY_PREFIX_IPSEC_PSK + p.getId();
// return this.<Boolean> invokeStubMethod("contains", key);
// }
//
// public boolean delete(final String key) {
// return this.<Boolean> invokeStubMethod("delete", key);
// }
//
// public void unlock(final Activity ctx) {
// try {
// Intent intent = new Intent(UNLOCK_ACTION);
// ctx.startActivity(intent);
// } catch (ActivityNotFoundException e) {
// Log.e("xink", "unlock credentials failed", e);
// }
// }
//
// public boolean isUnlocked() {
// int err = this.<Integer> invokeStubMethod("test");
// Log.d("xink", "KeyStore.test result is: " + err);
// return err == NO_ERROR;
// }
//
// /**
// * Check whether the keystore is hacked by xink.
// */
// public boolean isHacked() {
// try {
// Method m = getStubClass().getDeclaredMethod("execute", int.class, byte[][].class);
// m.setAccessible(true);
// m.invoke(getStub(), 'x', new byte[0][]);
// } catch (Throwable e) {
// throw new AppException("verify failed", e);
// }
//
// int err = invokeStubMethod("getLastError");
// Log.d("xink", "cmd 'x' result=" + err);
// return err == NO_ERROR;
// }
// }
//
// Path: main/src/domain/xink/vpn/wrapper/PptpProfile.java
// public class PptpProfile extends VpnProfile {
//
// public PptpProfile(final Context ctx) {
// super(ctx, "android.net.vpn.PptpProfile");
// }
//
// @Override
// public VpnType getType() {
// return VpnType.PPTP;
// }
//
// /**
// * Enables/disables the encryption for PPTP tunnel.
// */
// public void setEncryptionEnabled(final boolean enabled) {
// try {
// Method m = getStubClass().getMethod("setEncryptionEnabled", boolean.class);
// m.invoke(getStub(), enabled);
// } catch (Throwable e) {
// throw new AppException("setEncryptionEnabled failed", e);
// }
// }
//
// public boolean isEncryptionEnabled() {
// return this.<Boolean>invokeStubMethod("isEncryptionEnabled");
// }
//
// /*
// * (non-Javadoc)
// *
// * @see xink.vpn.wrapper.VpnProfile#dulicateToConnect()
// */
// @Override
// public PptpProfile dulicateToConnect() {
// PptpProfile p = (PptpProfile) super.dulicateToConnect();
// p.setEncryptionEnabled(isEncryptionEnabled());
// return p;
// }
//
// }
| import java.lang.reflect.Method;
import xink.vpn.wrapper.KeyStore;
import xink.vpn.wrapper.PptpProfile;
import xink.vpn.wrapper.VpnManager;
import xink.vpn.wrapper.VpnService;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.test.AndroidTestCase; | /*
* Copyright 2011 [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xink.vpn.test;
public class CompatibleTest extends AndroidTestCase {
public void testVpnManager() throws Exception {
VpnManager vpnMgr = new VpnManager(getContext());
Class<?> stubClass = vpnMgr.getStubClass();
assertMethodDefined(stubClass, VpnManager.METHOD_START_VPN_SERVICE);
assertMethodDefined(stubClass, VpnManager.METHOD_STOP_VPN_SERVICE);
assertMethodDefined(stubClass, VpnManager.METHOD_BIND_VPN_SERVICE, ServiceConnection.class);
}
public void testVpnService() throws Exception {
VpnService vpnSrv = new VpnService(getContext());
Class<?> stubClass = vpnSrv.getStubClass();
assertMethodDefined(stubClass, "asInterface", IBinder.class);
| // Path: main/src/domain/xink/vpn/wrapper/KeyStore.java
// public class KeyStore extends AbstractWrapper {
//
// public static final String UNLOCK_ACTION = "android.credentials.UNLOCK";
//
// private static final int NO_ERROR = 1;
//
// /*
// private static final int LOCKED = 2;
// private static final int UNINITIALIZED = 3;
// private static final int SYSTEM_ERROR = 4;
// private static final int PROTOCOL_ERROR = 5;
// private static final int PERMISSION_DENIED = 6;
// private static final int KEY_NOT_FOUND = 7;
// private static final int VALUE_CORRUPTED = 8;
// private static final int UNDEFINED_ACTION = 9;
// private static final int WRONG_PASSWORD = 10;
// */
//
// public KeyStore(final Context ctx) {
// super(ctx, "android.security.KeyStore", new StubInstanceCreator() {
// @Override
// protected Object newStubInstance(final Class<?> stubClass, final Context ctx) throws Exception {
// Method method = stubClass.getMethod("getInstance");
// return method.invoke(null);
// }
// });
// }
//
// public boolean put(final String key, final String value) {
// return this.<Boolean> invokeStubMethod("put", key, value);
// }
//
// public boolean contains(final VpnProfile p) {
// String key = L2tpIpsecPskProfile.KEY_PREFIX_IPSEC_PSK + p.getId();
// return this.<Boolean> invokeStubMethod("contains", key);
// }
//
// public boolean delete(final String key) {
// return this.<Boolean> invokeStubMethod("delete", key);
// }
//
// public void unlock(final Activity ctx) {
// try {
// Intent intent = new Intent(UNLOCK_ACTION);
// ctx.startActivity(intent);
// } catch (ActivityNotFoundException e) {
// Log.e("xink", "unlock credentials failed", e);
// }
// }
//
// public boolean isUnlocked() {
// int err = this.<Integer> invokeStubMethod("test");
// Log.d("xink", "KeyStore.test result is: " + err);
// return err == NO_ERROR;
// }
//
// /**
// * Check whether the keystore is hacked by xink.
// */
// public boolean isHacked() {
// try {
// Method m = getStubClass().getDeclaredMethod("execute", int.class, byte[][].class);
// m.setAccessible(true);
// m.invoke(getStub(), 'x', new byte[0][]);
// } catch (Throwable e) {
// throw new AppException("verify failed", e);
// }
//
// int err = invokeStubMethod("getLastError");
// Log.d("xink", "cmd 'x' result=" + err);
// return err == NO_ERROR;
// }
// }
//
// Path: main/src/domain/xink/vpn/wrapper/PptpProfile.java
// public class PptpProfile extends VpnProfile {
//
// public PptpProfile(final Context ctx) {
// super(ctx, "android.net.vpn.PptpProfile");
// }
//
// @Override
// public VpnType getType() {
// return VpnType.PPTP;
// }
//
// /**
// * Enables/disables the encryption for PPTP tunnel.
// */
// public void setEncryptionEnabled(final boolean enabled) {
// try {
// Method m = getStubClass().getMethod("setEncryptionEnabled", boolean.class);
// m.invoke(getStub(), enabled);
// } catch (Throwable e) {
// throw new AppException("setEncryptionEnabled failed", e);
// }
// }
//
// public boolean isEncryptionEnabled() {
// return this.<Boolean>invokeStubMethod("isEncryptionEnabled");
// }
//
// /*
// * (non-Javadoc)
// *
// * @see xink.vpn.wrapper.VpnProfile#dulicateToConnect()
// */
// @Override
// public PptpProfile dulicateToConnect() {
// PptpProfile p = (PptpProfile) super.dulicateToConnect();
// p.setEncryptionEnabled(isEncryptionEnabled());
// return p;
// }
//
// }
// Path: tests/src/android/xink/vpn/test/CompatibleTest.java
import java.lang.reflect.Method;
import xink.vpn.wrapper.KeyStore;
import xink.vpn.wrapper.PptpProfile;
import xink.vpn.wrapper.VpnManager;
import xink.vpn.wrapper.VpnService;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.test.AndroidTestCase;
/*
* Copyright 2011 [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xink.vpn.test;
public class CompatibleTest extends AndroidTestCase {
public void testVpnManager() throws Exception {
VpnManager vpnMgr = new VpnManager(getContext());
Class<?> stubClass = vpnMgr.getStubClass();
assertMethodDefined(stubClass, VpnManager.METHOD_START_VPN_SERVICE);
assertMethodDefined(stubClass, VpnManager.METHOD_STOP_VPN_SERVICE);
assertMethodDefined(stubClass, VpnManager.METHOD_BIND_VPN_SERVICE, ServiceConnection.class);
}
public void testVpnService() throws Exception {
VpnService vpnSrv = new VpnService(getContext());
Class<?> stubClass = vpnSrv.getStubClass();
assertMethodDefined(stubClass, "asInterface", IBinder.class);
| Class<?> profileClass = new PptpProfile(getContext()).getGenericProfileClass(); |
xinthink/xinkvpn | tests/src/android/xink/vpn/test/CompatibleTest.java | // Path: main/src/domain/xink/vpn/wrapper/KeyStore.java
// public class KeyStore extends AbstractWrapper {
//
// public static final String UNLOCK_ACTION = "android.credentials.UNLOCK";
//
// private static final int NO_ERROR = 1;
//
// /*
// private static final int LOCKED = 2;
// private static final int UNINITIALIZED = 3;
// private static final int SYSTEM_ERROR = 4;
// private static final int PROTOCOL_ERROR = 5;
// private static final int PERMISSION_DENIED = 6;
// private static final int KEY_NOT_FOUND = 7;
// private static final int VALUE_CORRUPTED = 8;
// private static final int UNDEFINED_ACTION = 9;
// private static final int WRONG_PASSWORD = 10;
// */
//
// public KeyStore(final Context ctx) {
// super(ctx, "android.security.KeyStore", new StubInstanceCreator() {
// @Override
// protected Object newStubInstance(final Class<?> stubClass, final Context ctx) throws Exception {
// Method method = stubClass.getMethod("getInstance");
// return method.invoke(null);
// }
// });
// }
//
// public boolean put(final String key, final String value) {
// return this.<Boolean> invokeStubMethod("put", key, value);
// }
//
// public boolean contains(final VpnProfile p) {
// String key = L2tpIpsecPskProfile.KEY_PREFIX_IPSEC_PSK + p.getId();
// return this.<Boolean> invokeStubMethod("contains", key);
// }
//
// public boolean delete(final String key) {
// return this.<Boolean> invokeStubMethod("delete", key);
// }
//
// public void unlock(final Activity ctx) {
// try {
// Intent intent = new Intent(UNLOCK_ACTION);
// ctx.startActivity(intent);
// } catch (ActivityNotFoundException e) {
// Log.e("xink", "unlock credentials failed", e);
// }
// }
//
// public boolean isUnlocked() {
// int err = this.<Integer> invokeStubMethod("test");
// Log.d("xink", "KeyStore.test result is: " + err);
// return err == NO_ERROR;
// }
//
// /**
// * Check whether the keystore is hacked by xink.
// */
// public boolean isHacked() {
// try {
// Method m = getStubClass().getDeclaredMethod("execute", int.class, byte[][].class);
// m.setAccessible(true);
// m.invoke(getStub(), 'x', new byte[0][]);
// } catch (Throwable e) {
// throw new AppException("verify failed", e);
// }
//
// int err = invokeStubMethod("getLastError");
// Log.d("xink", "cmd 'x' result=" + err);
// return err == NO_ERROR;
// }
// }
//
// Path: main/src/domain/xink/vpn/wrapper/PptpProfile.java
// public class PptpProfile extends VpnProfile {
//
// public PptpProfile(final Context ctx) {
// super(ctx, "android.net.vpn.PptpProfile");
// }
//
// @Override
// public VpnType getType() {
// return VpnType.PPTP;
// }
//
// /**
// * Enables/disables the encryption for PPTP tunnel.
// */
// public void setEncryptionEnabled(final boolean enabled) {
// try {
// Method m = getStubClass().getMethod("setEncryptionEnabled", boolean.class);
// m.invoke(getStub(), enabled);
// } catch (Throwable e) {
// throw new AppException("setEncryptionEnabled failed", e);
// }
// }
//
// public boolean isEncryptionEnabled() {
// return this.<Boolean>invokeStubMethod("isEncryptionEnabled");
// }
//
// /*
// * (non-Javadoc)
// *
// * @see xink.vpn.wrapper.VpnProfile#dulicateToConnect()
// */
// @Override
// public PptpProfile dulicateToConnect() {
// PptpProfile p = (PptpProfile) super.dulicateToConnect();
// p.setEncryptionEnabled(isEncryptionEnabled());
// return p;
// }
//
// }
| import java.lang.reflect.Method;
import xink.vpn.wrapper.KeyStore;
import xink.vpn.wrapper.PptpProfile;
import xink.vpn.wrapper.VpnManager;
import xink.vpn.wrapper.VpnService;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.test.AndroidTestCase; | /*
* Copyright 2011 [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xink.vpn.test;
public class CompatibleTest extends AndroidTestCase {
public void testVpnManager() throws Exception {
VpnManager vpnMgr = new VpnManager(getContext());
Class<?> stubClass = vpnMgr.getStubClass();
assertMethodDefined(stubClass, VpnManager.METHOD_START_VPN_SERVICE);
assertMethodDefined(stubClass, VpnManager.METHOD_STOP_VPN_SERVICE);
assertMethodDefined(stubClass, VpnManager.METHOD_BIND_VPN_SERVICE, ServiceConnection.class);
}
public void testVpnService() throws Exception {
VpnService vpnSrv = new VpnService(getContext());
Class<?> stubClass = vpnSrv.getStubClass();
assertMethodDefined(stubClass, "asInterface", IBinder.class);
Class<?> profileClass = new PptpProfile(getContext()).getGenericProfileClass();
assertMethodDefined(stubClass, "connect", profileClass, String.class, String.class);
assertMethodDefined(stubClass, "disconnect");
assertMethodDefined(stubClass, "checkStatus", profileClass);
}
public void testKeyStore() throws Exception { | // Path: main/src/domain/xink/vpn/wrapper/KeyStore.java
// public class KeyStore extends AbstractWrapper {
//
// public static final String UNLOCK_ACTION = "android.credentials.UNLOCK";
//
// private static final int NO_ERROR = 1;
//
// /*
// private static final int LOCKED = 2;
// private static final int UNINITIALIZED = 3;
// private static final int SYSTEM_ERROR = 4;
// private static final int PROTOCOL_ERROR = 5;
// private static final int PERMISSION_DENIED = 6;
// private static final int KEY_NOT_FOUND = 7;
// private static final int VALUE_CORRUPTED = 8;
// private static final int UNDEFINED_ACTION = 9;
// private static final int WRONG_PASSWORD = 10;
// */
//
// public KeyStore(final Context ctx) {
// super(ctx, "android.security.KeyStore", new StubInstanceCreator() {
// @Override
// protected Object newStubInstance(final Class<?> stubClass, final Context ctx) throws Exception {
// Method method = stubClass.getMethod("getInstance");
// return method.invoke(null);
// }
// });
// }
//
// public boolean put(final String key, final String value) {
// return this.<Boolean> invokeStubMethod("put", key, value);
// }
//
// public boolean contains(final VpnProfile p) {
// String key = L2tpIpsecPskProfile.KEY_PREFIX_IPSEC_PSK + p.getId();
// return this.<Boolean> invokeStubMethod("contains", key);
// }
//
// public boolean delete(final String key) {
// return this.<Boolean> invokeStubMethod("delete", key);
// }
//
// public void unlock(final Activity ctx) {
// try {
// Intent intent = new Intent(UNLOCK_ACTION);
// ctx.startActivity(intent);
// } catch (ActivityNotFoundException e) {
// Log.e("xink", "unlock credentials failed", e);
// }
// }
//
// public boolean isUnlocked() {
// int err = this.<Integer> invokeStubMethod("test");
// Log.d("xink", "KeyStore.test result is: " + err);
// return err == NO_ERROR;
// }
//
// /**
// * Check whether the keystore is hacked by xink.
// */
// public boolean isHacked() {
// try {
// Method m = getStubClass().getDeclaredMethod("execute", int.class, byte[][].class);
// m.setAccessible(true);
// m.invoke(getStub(), 'x', new byte[0][]);
// } catch (Throwable e) {
// throw new AppException("verify failed", e);
// }
//
// int err = invokeStubMethod("getLastError");
// Log.d("xink", "cmd 'x' result=" + err);
// return err == NO_ERROR;
// }
// }
//
// Path: main/src/domain/xink/vpn/wrapper/PptpProfile.java
// public class PptpProfile extends VpnProfile {
//
// public PptpProfile(final Context ctx) {
// super(ctx, "android.net.vpn.PptpProfile");
// }
//
// @Override
// public VpnType getType() {
// return VpnType.PPTP;
// }
//
// /**
// * Enables/disables the encryption for PPTP tunnel.
// */
// public void setEncryptionEnabled(final boolean enabled) {
// try {
// Method m = getStubClass().getMethod("setEncryptionEnabled", boolean.class);
// m.invoke(getStub(), enabled);
// } catch (Throwable e) {
// throw new AppException("setEncryptionEnabled failed", e);
// }
// }
//
// public boolean isEncryptionEnabled() {
// return this.<Boolean>invokeStubMethod("isEncryptionEnabled");
// }
//
// /*
// * (non-Javadoc)
// *
// * @see xink.vpn.wrapper.VpnProfile#dulicateToConnect()
// */
// @Override
// public PptpProfile dulicateToConnect() {
// PptpProfile p = (PptpProfile) super.dulicateToConnect();
// p.setEncryptionEnabled(isEncryptionEnabled());
// return p;
// }
//
// }
// Path: tests/src/android/xink/vpn/test/CompatibleTest.java
import java.lang.reflect.Method;
import xink.vpn.wrapper.KeyStore;
import xink.vpn.wrapper.PptpProfile;
import xink.vpn.wrapper.VpnManager;
import xink.vpn.wrapper.VpnService;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.test.AndroidTestCase;
/*
* Copyright 2011 [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xink.vpn.test;
public class CompatibleTest extends AndroidTestCase {
public void testVpnManager() throws Exception {
VpnManager vpnMgr = new VpnManager(getContext());
Class<?> stubClass = vpnMgr.getStubClass();
assertMethodDefined(stubClass, VpnManager.METHOD_START_VPN_SERVICE);
assertMethodDefined(stubClass, VpnManager.METHOD_STOP_VPN_SERVICE);
assertMethodDefined(stubClass, VpnManager.METHOD_BIND_VPN_SERVICE, ServiceConnection.class);
}
public void testVpnService() throws Exception {
VpnService vpnSrv = new VpnService(getContext());
Class<?> stubClass = vpnSrv.getStubClass();
assertMethodDefined(stubClass, "asInterface", IBinder.class);
Class<?> profileClass = new PptpProfile(getContext()).getGenericProfileClass();
assertMethodDefined(stubClass, "connect", profileClass, String.class, String.class);
assertMethodDefined(stubClass, "disconnect");
assertMethodDefined(stubClass, "checkStatus", profileClass);
}
public void testKeyStore() throws Exception { | KeyStore ks = new KeyStore(getContext()); |
xinthink/xinkvpn | main/src/domain/xink/vpn/wrapper/KeyStore.java | // Path: main/src/domain/xink/vpn/AppException.java
// public class AppException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// private int messageCode;
//
// private Object[] messageArgs;
//
// public AppException(final String detailMessage) {
// super(detailMessage);
// }
//
// public AppException(final String message, final int msgCode, final Object... msgArgs) {
// super(message);
// this.messageCode = msgCode;
// this.messageArgs = msgArgs;
// }
//
// public AppException(final String message, final Throwable throwable, final int msgCode, final Object... msgArgs) {
// super(message, throwable);
// this.messageCode = msgCode;
// this.messageArgs = msgArgs;
// }
//
// public AppException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// public int getMessageCode() {
// return messageCode;
// }
//
// public Object[] getMessageArgs() {
// return messageArgs;
// }
//
// }
| import java.lang.reflect.Method;
import xink.vpn.AppException;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.util.Log; | }
public boolean delete(final String key) {
return this.<Boolean> invokeStubMethod("delete", key);
}
public void unlock(final Activity ctx) {
try {
Intent intent = new Intent(UNLOCK_ACTION);
ctx.startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.e("xink", "unlock credentials failed", e);
}
}
public boolean isUnlocked() {
int err = this.<Integer> invokeStubMethod("test");
Log.d("xink", "KeyStore.test result is: " + err);
return err == NO_ERROR;
}
/**
* Check whether the keystore is hacked by xink.
*/
public boolean isHacked() {
try {
Method m = getStubClass().getDeclaredMethod("execute", int.class, byte[][].class);
m.setAccessible(true);
m.invoke(getStub(), 'x', new byte[0][]);
} catch (Throwable e) { | // Path: main/src/domain/xink/vpn/AppException.java
// public class AppException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// private int messageCode;
//
// private Object[] messageArgs;
//
// public AppException(final String detailMessage) {
// super(detailMessage);
// }
//
// public AppException(final String message, final int msgCode, final Object... msgArgs) {
// super(message);
// this.messageCode = msgCode;
// this.messageArgs = msgArgs;
// }
//
// public AppException(final String message, final Throwable throwable, final int msgCode, final Object... msgArgs) {
// super(message, throwable);
// this.messageCode = msgCode;
// this.messageArgs = msgArgs;
// }
//
// public AppException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// public int getMessageCode() {
// return messageCode;
// }
//
// public Object[] getMessageArgs() {
// return messageArgs;
// }
//
// }
// Path: main/src/domain/xink/vpn/wrapper/KeyStore.java
import java.lang.reflect.Method;
import xink.vpn.AppException;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
}
public boolean delete(final String key) {
return this.<Boolean> invokeStubMethod("delete", key);
}
public void unlock(final Activity ctx) {
try {
Intent intent = new Intent(UNLOCK_ACTION);
ctx.startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.e("xink", "unlock credentials failed", e);
}
}
public boolean isUnlocked() {
int err = this.<Integer> invokeStubMethod("test");
Log.d("xink", "KeyStore.test result is: " + err);
return err == NO_ERROR;
}
/**
* Check whether the keystore is hacked by xink.
*/
public boolean isHacked() {
try {
Method m = getStubClass().getDeclaredMethod("execute", int.class, byte[][].class);
m.setAccessible(true);
m.invoke(getStub(), 'x', new byte[0][]);
} catch (Throwable e) { | throw new AppException("verify failed", e); |
xinthink/xinkvpn | main/src/java/xink/crypto/StreamCrypto.java | // Path: main/src/java/xink/vpn/Assert.java
// public final class Assert {
//
// // 不允许实例化
// private Assert() {
// // do nothing
// }
//
// /**
// * Asserts the expression to be true
// * @param expr expression to be tested
// */
// public static void isTrue(final boolean expr) {
// isTrue(expr, "[Assertion failed] expression is expected to be true");
// }
//
// /**
// * Asserts the expression to be true
// * @param expr expression to be tested
// * @param msg assertion failure message
// */
// public static void isTrue(final boolean expr, final String msg) {
// if (!expr) throw new AssertionError(msg);
// }
//
// /**
// * Asserts the expression to be false
// * @param expr expression to be tested
// */
// public static void isFalse(final boolean expr) {
// isFalse(expr, "[Assertion failed] expression is expected to be true");
// }
//
// /**
// * Asserts the expression to be false
// * @param expr expression to be tested
// * @param msg assertion failure message
// */
// public static void isFalse(final boolean expr, final String msg) {
// if (expr) throw new AssertionError(msg);
// }
//
// /**
// * Asserts the expression NOT null
// * @param expr expression to be tested
// */
// public static void notNull(final Object expr) {
// notNull(expr, "[Assertion failed] expression is expected NOT null");
// }
//
// /**
// * Asserts the expression NOT null
// * @param expr expression to be tested
// * @param msg assertion failure message
// */
// public static void notNull(final Object expr, final String msg) {
// if (expr == null) throw new AssertionError(msg);
// }
//
// /**
// * Asserts the expression to be null
// * @param expr expression to be tested
// */
// public static void isNull(final Object expr) {
// isNull(expr, "[Assertion failed] expression is expected to be null");
// }
//
// /**
// * Asserts the expression to be null
// * @param expr expression to be tested
// * @param msg assertion failure message
// */
// public static void isNull(final Object expr, final String msg) {
// if (expr != null) throw new AssertionError(msg);
// }
//
// /**
// * Asserts two objects are equals, NOT null
// * @param obj1 Object
// * @param obj2 Object
// */
// public static void isEquals(final Object obj1, final Object obj2) {
// isEquals(obj1, obj2, "[Assertion failed] objects are expected to be equals");
// }
//
// /**
// * Asserts two objects are equals, NOT null
// * @param obj1 Object
// * @param obj2 Object
// * @param msg assertion failure message
// */
// public static void isEquals(final Object obj1, final Object obj2, final String msg) {
// if (obj1 == null || !obj1.equals(obj2)) throw new AssertionError(msg);
// }
// }
| import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import xink.vpn.Assert;
import xink.vpn.R;
import android.content.Context; | /*
* Copyright 2011 [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xink.crypto;
public final class StreamCrypto {
/*
* Buffer size when reading input.
*/
private static final int BUF_SIZE = 128;
private static byte[] rawKey;
/**
* Initialization.
*
* @param ctx
* Context
*/
public static void init(final Context ctx) {
rawKey = ctx.getString(R.string.crypto_raw_key).getBytes(); | // Path: main/src/java/xink/vpn/Assert.java
// public final class Assert {
//
// // 不允许实例化
// private Assert() {
// // do nothing
// }
//
// /**
// * Asserts the expression to be true
// * @param expr expression to be tested
// */
// public static void isTrue(final boolean expr) {
// isTrue(expr, "[Assertion failed] expression is expected to be true");
// }
//
// /**
// * Asserts the expression to be true
// * @param expr expression to be tested
// * @param msg assertion failure message
// */
// public static void isTrue(final boolean expr, final String msg) {
// if (!expr) throw new AssertionError(msg);
// }
//
// /**
// * Asserts the expression to be false
// * @param expr expression to be tested
// */
// public static void isFalse(final boolean expr) {
// isFalse(expr, "[Assertion failed] expression is expected to be true");
// }
//
// /**
// * Asserts the expression to be false
// * @param expr expression to be tested
// * @param msg assertion failure message
// */
// public static void isFalse(final boolean expr, final String msg) {
// if (expr) throw new AssertionError(msg);
// }
//
// /**
// * Asserts the expression NOT null
// * @param expr expression to be tested
// */
// public static void notNull(final Object expr) {
// notNull(expr, "[Assertion failed] expression is expected NOT null");
// }
//
// /**
// * Asserts the expression NOT null
// * @param expr expression to be tested
// * @param msg assertion failure message
// */
// public static void notNull(final Object expr, final String msg) {
// if (expr == null) throw new AssertionError(msg);
// }
//
// /**
// * Asserts the expression to be null
// * @param expr expression to be tested
// */
// public static void isNull(final Object expr) {
// isNull(expr, "[Assertion failed] expression is expected to be null");
// }
//
// /**
// * Asserts the expression to be null
// * @param expr expression to be tested
// * @param msg assertion failure message
// */
// public static void isNull(final Object expr, final String msg) {
// if (expr != null) throw new AssertionError(msg);
// }
//
// /**
// * Asserts two objects are equals, NOT null
// * @param obj1 Object
// * @param obj2 Object
// */
// public static void isEquals(final Object obj1, final Object obj2) {
// isEquals(obj1, obj2, "[Assertion failed] objects are expected to be equals");
// }
//
// /**
// * Asserts two objects are equals, NOT null
// * @param obj1 Object
// * @param obj2 Object
// * @param msg assertion failure message
// */
// public static void isEquals(final Object obj1, final Object obj2, final String msg) {
// if (obj1 == null || !obj1.equals(obj2)) throw new AssertionError(msg);
// }
// }
// Path: main/src/java/xink/crypto/StreamCrypto.java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import xink.vpn.Assert;
import xink.vpn.R;
import android.content.Context;
/*
* Copyright 2011 [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xink.crypto;
public final class StreamCrypto {
/*
* Buffer size when reading input.
*/
private static final int BUF_SIZE = 128;
private static byte[] rawKey;
/**
* Initialization.
*
* @param ctx
* Context
*/
public static void init(final Context ctx) {
rawKey = ctx.getString(R.string.crypto_raw_key).getBytes(); | Assert.isEquals(rawKey.length, 16, "AES-128 requires a 16 bytes raw key"); |
xinthink/xinkvpn | main/src/domain/xink/vpn/wrapper/PptpProfile.java | // Path: main/src/domain/xink/vpn/AppException.java
// public class AppException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// private int messageCode;
//
// private Object[] messageArgs;
//
// public AppException(final String detailMessage) {
// super(detailMessage);
// }
//
// public AppException(final String message, final int msgCode, final Object... msgArgs) {
// super(message);
// this.messageCode = msgCode;
// this.messageArgs = msgArgs;
// }
//
// public AppException(final String message, final Throwable throwable, final int msgCode, final Object... msgArgs) {
// super(message, throwable);
// this.messageCode = msgCode;
// this.messageArgs = msgArgs;
// }
//
// public AppException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// public int getMessageCode() {
// return messageCode;
// }
//
// public Object[] getMessageArgs() {
// return messageArgs;
// }
//
// }
| import java.lang.reflect.Method;
import xink.vpn.AppException;
import android.content.Context; | /*
* Copyright 2011 [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xink.vpn.wrapper;
public class PptpProfile extends VpnProfile {
public PptpProfile(final Context ctx) {
super(ctx, "android.net.vpn.PptpProfile");
}
@Override
public VpnType getType() {
return VpnType.PPTP;
}
/**
* Enables/disables the encryption for PPTP tunnel.
*/
public void setEncryptionEnabled(final boolean enabled) {
try {
Method m = getStubClass().getMethod("setEncryptionEnabled", boolean.class);
m.invoke(getStub(), enabled);
} catch (Throwable e) { | // Path: main/src/domain/xink/vpn/AppException.java
// public class AppException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// private int messageCode;
//
// private Object[] messageArgs;
//
// public AppException(final String detailMessage) {
// super(detailMessage);
// }
//
// public AppException(final String message, final int msgCode, final Object... msgArgs) {
// super(message);
// this.messageCode = msgCode;
// this.messageArgs = msgArgs;
// }
//
// public AppException(final String message, final Throwable throwable, final int msgCode, final Object... msgArgs) {
// super(message, throwable);
// this.messageCode = msgCode;
// this.messageArgs = msgArgs;
// }
//
// public AppException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// public int getMessageCode() {
// return messageCode;
// }
//
// public Object[] getMessageArgs() {
// return messageArgs;
// }
//
// }
// Path: main/src/domain/xink/vpn/wrapper/PptpProfile.java
import java.lang.reflect.Method;
import xink.vpn.AppException;
import android.content.Context;
/*
* Copyright 2011 [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xink.vpn.wrapper;
public class PptpProfile extends VpnProfile {
public PptpProfile(final Context ctx) {
super(ctx, "android.net.vpn.PptpProfile");
}
@Override
public VpnType getType() {
return VpnType.PPTP;
}
/**
* Enables/disables the encryption for PPTP tunnel.
*/
public void setEncryptionEnabled(final boolean enabled) {
try {
Method m = getStubClass().getMethod("setEncryptionEnabled", boolean.class);
m.invoke(getStub(), enabled);
} catch (Throwable e) { | throw new AppException("setEncryptionEnabled failed", e); |
de-luxe/burstcoin-observer | src/main/java/burstcoin/observer/event/CrowdfundUpdateEvent.java | // Path: src/main/java/burstcoin/observer/bean/CrowdfundBean.java
// public class CrowdfundBean
// {
// private String at;
// private String atRS;
// private String creatorRS;
// private double percent;
//
// private String name;
// private String description;
// private String ratio;
//
// private String state;
//
// private String targetAmount;
// private String currentAmount;
//
// // remaining / finished ago
// private String blocksAgo;
// private String blocksToGo;
//
// public CrowdfundBean(String at, String atRS, String creatorRS, String name, String description, CrowdfundState state, String targetAmount,
// String currentAmount,
// String ratio, double percent, String blocks)
// {
// this.at = at;
// this.atRS = atRS;
// this.creatorRS = creatorRS;
// this.percent = percent;
// this.name = name;
// this.description = description;
// this.ratio = ratio;
//
// switch(state)
// {
// case ACTIVE:
// this.state = "Active";
// break;
// case FUNDED:
// this.state = "Funded";
// break;
// case NOT_FUNDED:
// this.state = "Not Funded";
// break;
// }
//
// this.targetAmount = targetAmount;
// this.currentAmount = currentAmount;
// this.blocksAgo = CrowdfundState.ACTIVE.equals(state) ? "0" : blocks;
// this.blocksToGo = CrowdfundState.ACTIVE.equals(state) ? blocks : "0";
// }
//
// public String getAt()
// {
// return at;
// }
//
// public String getAtRS()
// {
// return atRS;
// }
//
// public String getCreatorRS()
// {
// return creatorRS;
// }
//
// public String getName()
// {
// return name.length() > 22 ? name.substring(0, 19) + "..." : name;
// }
//
// public String getFullName()
// {
// return name;
// }
//
// public String getDescription()
// {
// return description;
// }
//
// public String getState()
// {
// return state;
// }
//
// public String getTargetAmount()
// {
// return targetAmount;
// }
//
// public String getCurrentAmount()
// {
// return currentAmount;
// }
//
// public String getBlocksAgo()
// {
// return blocksAgo;
// }
//
// public String getBlocksToGo()
// {
// return blocksToGo;
// }
//
// public String getRatio()
// {
// return ratio;
// }
//
// public double getPercent()
// {
// return percent;
// }
// }
| import burstcoin.observer.bean.CrowdfundBean;
import java.util.Date;
import java.util.List; | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package burstcoin.observer.event;
public class CrowdfundUpdateEvent
{ | // Path: src/main/java/burstcoin/observer/bean/CrowdfundBean.java
// public class CrowdfundBean
// {
// private String at;
// private String atRS;
// private String creatorRS;
// private double percent;
//
// private String name;
// private String description;
// private String ratio;
//
// private String state;
//
// private String targetAmount;
// private String currentAmount;
//
// // remaining / finished ago
// private String blocksAgo;
// private String blocksToGo;
//
// public CrowdfundBean(String at, String atRS, String creatorRS, String name, String description, CrowdfundState state, String targetAmount,
// String currentAmount,
// String ratio, double percent, String blocks)
// {
// this.at = at;
// this.atRS = atRS;
// this.creatorRS = creatorRS;
// this.percent = percent;
// this.name = name;
// this.description = description;
// this.ratio = ratio;
//
// switch(state)
// {
// case ACTIVE:
// this.state = "Active";
// break;
// case FUNDED:
// this.state = "Funded";
// break;
// case NOT_FUNDED:
// this.state = "Not Funded";
// break;
// }
//
// this.targetAmount = targetAmount;
// this.currentAmount = currentAmount;
// this.blocksAgo = CrowdfundState.ACTIVE.equals(state) ? "0" : blocks;
// this.blocksToGo = CrowdfundState.ACTIVE.equals(state) ? blocks : "0";
// }
//
// public String getAt()
// {
// return at;
// }
//
// public String getAtRS()
// {
// return atRS;
// }
//
// public String getCreatorRS()
// {
// return creatorRS;
// }
//
// public String getName()
// {
// return name.length() > 22 ? name.substring(0, 19) + "..." : name;
// }
//
// public String getFullName()
// {
// return name;
// }
//
// public String getDescription()
// {
// return description;
// }
//
// public String getState()
// {
// return state;
// }
//
// public String getTargetAmount()
// {
// return targetAmount;
// }
//
// public String getCurrentAmount()
// {
// return currentAmount;
// }
//
// public String getBlocksAgo()
// {
// return blocksAgo;
// }
//
// public String getBlocksToGo()
// {
// return blocksToGo;
// }
//
// public String getRatio()
// {
// return ratio;
// }
//
// public double getPercent()
// {
// return percent;
// }
// }
// Path: src/main/java/burstcoin/observer/event/CrowdfundUpdateEvent.java
import burstcoin.observer.bean.CrowdfundBean;
import java.util.Date;
import java.util.List;
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package burstcoin.observer.event;
public class CrowdfundUpdateEvent
{ | private List<CrowdfundBean> crowdfundBeans; |
de-luxe/burstcoin-observer | src/main/java/burstcoin/observer/event/PoolUpdateEvent.java | // Path: src/main/java/burstcoin/observer/bean/PoolBean.java
// public class PoolBean
// {
// private String accountId;
// private String accountRS;
// private String name;
// private String description;
// // pool balance
// private String balance;
// // accounts with reward assignment
// private Integer assignedMiners;
// // number of miners that found a block
// private int successfulMiners;
// // number of blocks found
// private int foundBlocks;
//
// private String earnedAmount;
//
//
// protected PoolBean()
// {
// }
//
// public PoolBean(String accountId, String accountRS, String name, String description, String balance, int assignedMiners, int foundBlocks,
// int successfulMiners, String earnedAmount)
// {
// this.accountId = accountId;
// this.accountRS = accountRS;
// this.name = name;
// this.description = description;
// this.balance = balance;
// this.assignedMiners = assignedMiners;
// this.foundBlocks = foundBlocks;
// this.successfulMiners = successfulMiners;
// this.earnedAmount = earnedAmount;
// }
//
// public String getAccountId()
// {
// return accountId;
// }
//
// public String getAccountRS()
// {
// return accountRS;
// }
//
// public String getName()
// {
// return name;
// }
//
// public String getDescription()
// {
// return description;
// }
//
// public String getBalance()
// {
// return balance;
// }
//
// public Integer getAssignedMiners()
// {
// return assignedMiners;
// }
//
// public int getSuccessfulMiners()
// {
// return successfulMiners;
// }
//
// public int getFoundBlocks()
// {
// return foundBlocks;
// }
//
// public String getEarnedAmount()
// {
// return earnedAmount;
// }
// }
| import burstcoin.observer.bean.PoolBean;
import java.util.Date;
import java.util.List; | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package burstcoin.observer.event;
public class PoolUpdateEvent
{ | // Path: src/main/java/burstcoin/observer/bean/PoolBean.java
// public class PoolBean
// {
// private String accountId;
// private String accountRS;
// private String name;
// private String description;
// // pool balance
// private String balance;
// // accounts with reward assignment
// private Integer assignedMiners;
// // number of miners that found a block
// private int successfulMiners;
// // number of blocks found
// private int foundBlocks;
//
// private String earnedAmount;
//
//
// protected PoolBean()
// {
// }
//
// public PoolBean(String accountId, String accountRS, String name, String description, String balance, int assignedMiners, int foundBlocks,
// int successfulMiners, String earnedAmount)
// {
// this.accountId = accountId;
// this.accountRS = accountRS;
// this.name = name;
// this.description = description;
// this.balance = balance;
// this.assignedMiners = assignedMiners;
// this.foundBlocks = foundBlocks;
// this.successfulMiners = successfulMiners;
// this.earnedAmount = earnedAmount;
// }
//
// public String getAccountId()
// {
// return accountId;
// }
//
// public String getAccountRS()
// {
// return accountRS;
// }
//
// public String getName()
// {
// return name;
// }
//
// public String getDescription()
// {
// return description;
// }
//
// public String getBalance()
// {
// return balance;
// }
//
// public Integer getAssignedMiners()
// {
// return assignedMiners;
// }
//
// public int getSuccessfulMiners()
// {
// return successfulMiners;
// }
//
// public int getFoundBlocks()
// {
// return foundBlocks;
// }
//
// public String getEarnedAmount()
// {
// return earnedAmount;
// }
// }
// Path: src/main/java/burstcoin/observer/event/PoolUpdateEvent.java
import burstcoin.observer.bean.PoolBean;
import java.util.Date;
import java.util.List;
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package burstcoin.observer.event;
public class PoolUpdateEvent
{ | private List<PoolBean> poolBeans; |
de-luxe/burstcoin-observer | src/main/java/burstcoin/observer/event/AssetUpdateEvent.java | // Path: src/main/java/burstcoin/observer/bean/AssetBean.java
// public class AssetBean
// {
// private String asset;
// private String name;
// private String description;
//
// private String accountRS;
// private String account;
//
// private String quantityQNT;
// private int decimals;
//
// private int numberOfAccounts;
// private int numberOfTransfers;
// private int numberOfTrades;
//
// private int numberOfBuyOrders;
// private int numberOfSellOrders;
// private String volume7Days;
// private String volume30Days;
//
// private String lastPrice;
//
// public AssetBean(String asset, String name, String description, String accountRS, String account, String quantityQNT, int decimals, int numberOfAccounts,
// int numberOfTransfers, int numberOfTrades, int numberOfBuyOrders, int numberOfSellOrders, String volume7Days, String volume30Days,
// String lastPrice)
// {
// this.asset = asset;
// this.name = name;
// this.description = description;
// this.accountRS = accountRS;
// this.account = account;
// this.quantityQNT = quantityQNT;
// this.decimals = decimals;
// this.numberOfAccounts = numberOfAccounts;
// this.numberOfTransfers = numberOfTransfers;
// this.numberOfTrades = numberOfTrades;
// this.numberOfBuyOrders = numberOfBuyOrders;
// this.numberOfSellOrders = numberOfSellOrders;
// this.volume7Days = volume7Days.equals("") ? "0" : volume7Days;
// this.volume30Days = volume30Days.equals("") ? "0" : volume30Days;
//
// this.lastPrice = lastPrice;
// }
//
// public String getLastPrice()
// {
// return lastPrice;
// }
//
// public String getVolume7Days()
// {
// return volume7Days;
// }
//
// public String getVolume30Days()
// {
// return volume30Days;
// }
//
// public String getAsset()
// {
// return asset;
// }
//
// public String getName()
// {
// return name;
// }
//
// public String getDescription()
// {
// return description;
// }
//
// public String getAccountRS()
// {
// return accountRS;
// }
//
// public String getAccount()
// {
// return account;
// }
//
// public String getQuantityQNT()
// {
// return quantityQNT;
// }
//
// public int getDecimals()
// {
// return decimals;
// }
//
// public int getNumberOfAccounts()
// {
// return numberOfAccounts;
// }
//
// public int getNumberOfTransfers()
// {
// return numberOfTransfers;
// }
//
// public int getNumberOfTrades()
// {
// return numberOfTrades;
// }
//
// public int getNumberOfBuyOrders()
// {
// return numberOfBuyOrders;
// }
//
// public int getNumberOfSellOrders()
// {
// return numberOfSellOrders;
// }
// }
//
// Path: src/main/java/burstcoin/observer/bean/AssetCandleStickBean.java
// public class AssetCandleStickBean
// {
// private String asset;
// private List candleStickData;
//
// public AssetCandleStickBean(String asset, List candleStickData)
// {
// this.asset = asset;
// this.candleStickData = candleStickData;
// }
//
// public String getAsset()
// {
// return asset;
// }
//
// public void setCandleStickData(List candleStickData)
// {
// this.candleStickData = candleStickData;
// }
//
// public List getCandleStickData()
// {
// return candleStickData;
// }
// }
| import burstcoin.observer.bean.AssetBean;
import burstcoin.observer.bean.AssetCandleStickBean;
import java.util.Date;
import java.util.List; | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package burstcoin.observer.event;
public class AssetUpdateEvent
{
private Date lastUpdate; | // Path: src/main/java/burstcoin/observer/bean/AssetBean.java
// public class AssetBean
// {
// private String asset;
// private String name;
// private String description;
//
// private String accountRS;
// private String account;
//
// private String quantityQNT;
// private int decimals;
//
// private int numberOfAccounts;
// private int numberOfTransfers;
// private int numberOfTrades;
//
// private int numberOfBuyOrders;
// private int numberOfSellOrders;
// private String volume7Days;
// private String volume30Days;
//
// private String lastPrice;
//
// public AssetBean(String asset, String name, String description, String accountRS, String account, String quantityQNT, int decimals, int numberOfAccounts,
// int numberOfTransfers, int numberOfTrades, int numberOfBuyOrders, int numberOfSellOrders, String volume7Days, String volume30Days,
// String lastPrice)
// {
// this.asset = asset;
// this.name = name;
// this.description = description;
// this.accountRS = accountRS;
// this.account = account;
// this.quantityQNT = quantityQNT;
// this.decimals = decimals;
// this.numberOfAccounts = numberOfAccounts;
// this.numberOfTransfers = numberOfTransfers;
// this.numberOfTrades = numberOfTrades;
// this.numberOfBuyOrders = numberOfBuyOrders;
// this.numberOfSellOrders = numberOfSellOrders;
// this.volume7Days = volume7Days.equals("") ? "0" : volume7Days;
// this.volume30Days = volume30Days.equals("") ? "0" : volume30Days;
//
// this.lastPrice = lastPrice;
// }
//
// public String getLastPrice()
// {
// return lastPrice;
// }
//
// public String getVolume7Days()
// {
// return volume7Days;
// }
//
// public String getVolume30Days()
// {
// return volume30Days;
// }
//
// public String getAsset()
// {
// return asset;
// }
//
// public String getName()
// {
// return name;
// }
//
// public String getDescription()
// {
// return description;
// }
//
// public String getAccountRS()
// {
// return accountRS;
// }
//
// public String getAccount()
// {
// return account;
// }
//
// public String getQuantityQNT()
// {
// return quantityQNT;
// }
//
// public int getDecimals()
// {
// return decimals;
// }
//
// public int getNumberOfAccounts()
// {
// return numberOfAccounts;
// }
//
// public int getNumberOfTransfers()
// {
// return numberOfTransfers;
// }
//
// public int getNumberOfTrades()
// {
// return numberOfTrades;
// }
//
// public int getNumberOfBuyOrders()
// {
// return numberOfBuyOrders;
// }
//
// public int getNumberOfSellOrders()
// {
// return numberOfSellOrders;
// }
// }
//
// Path: src/main/java/burstcoin/observer/bean/AssetCandleStickBean.java
// public class AssetCandleStickBean
// {
// private String asset;
// private List candleStickData;
//
// public AssetCandleStickBean(String asset, List candleStickData)
// {
// this.asset = asset;
// this.candleStickData = candleStickData;
// }
//
// public String getAsset()
// {
// return asset;
// }
//
// public void setCandleStickData(List candleStickData)
// {
// this.candleStickData = candleStickData;
// }
//
// public List getCandleStickData()
// {
// return candleStickData;
// }
// }
// Path: src/main/java/burstcoin/observer/event/AssetUpdateEvent.java
import burstcoin.observer.bean.AssetBean;
import burstcoin.observer.bean.AssetCandleStickBean;
import java.util.Date;
import java.util.List;
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package burstcoin.observer.event;
public class AssetUpdateEvent
{
private Date lastUpdate; | private List<AssetBean> assetBeans; |
de-luxe/burstcoin-observer | src/main/java/burstcoin/observer/event/AssetUpdateEvent.java | // Path: src/main/java/burstcoin/observer/bean/AssetBean.java
// public class AssetBean
// {
// private String asset;
// private String name;
// private String description;
//
// private String accountRS;
// private String account;
//
// private String quantityQNT;
// private int decimals;
//
// private int numberOfAccounts;
// private int numberOfTransfers;
// private int numberOfTrades;
//
// private int numberOfBuyOrders;
// private int numberOfSellOrders;
// private String volume7Days;
// private String volume30Days;
//
// private String lastPrice;
//
// public AssetBean(String asset, String name, String description, String accountRS, String account, String quantityQNT, int decimals, int numberOfAccounts,
// int numberOfTransfers, int numberOfTrades, int numberOfBuyOrders, int numberOfSellOrders, String volume7Days, String volume30Days,
// String lastPrice)
// {
// this.asset = asset;
// this.name = name;
// this.description = description;
// this.accountRS = accountRS;
// this.account = account;
// this.quantityQNT = quantityQNT;
// this.decimals = decimals;
// this.numberOfAccounts = numberOfAccounts;
// this.numberOfTransfers = numberOfTransfers;
// this.numberOfTrades = numberOfTrades;
// this.numberOfBuyOrders = numberOfBuyOrders;
// this.numberOfSellOrders = numberOfSellOrders;
// this.volume7Days = volume7Days.equals("") ? "0" : volume7Days;
// this.volume30Days = volume30Days.equals("") ? "0" : volume30Days;
//
// this.lastPrice = lastPrice;
// }
//
// public String getLastPrice()
// {
// return lastPrice;
// }
//
// public String getVolume7Days()
// {
// return volume7Days;
// }
//
// public String getVolume30Days()
// {
// return volume30Days;
// }
//
// public String getAsset()
// {
// return asset;
// }
//
// public String getName()
// {
// return name;
// }
//
// public String getDescription()
// {
// return description;
// }
//
// public String getAccountRS()
// {
// return accountRS;
// }
//
// public String getAccount()
// {
// return account;
// }
//
// public String getQuantityQNT()
// {
// return quantityQNT;
// }
//
// public int getDecimals()
// {
// return decimals;
// }
//
// public int getNumberOfAccounts()
// {
// return numberOfAccounts;
// }
//
// public int getNumberOfTransfers()
// {
// return numberOfTransfers;
// }
//
// public int getNumberOfTrades()
// {
// return numberOfTrades;
// }
//
// public int getNumberOfBuyOrders()
// {
// return numberOfBuyOrders;
// }
//
// public int getNumberOfSellOrders()
// {
// return numberOfSellOrders;
// }
// }
//
// Path: src/main/java/burstcoin/observer/bean/AssetCandleStickBean.java
// public class AssetCandleStickBean
// {
// private String asset;
// private List candleStickData;
//
// public AssetCandleStickBean(String asset, List candleStickData)
// {
// this.asset = asset;
// this.candleStickData = candleStickData;
// }
//
// public String getAsset()
// {
// return asset;
// }
//
// public void setCandleStickData(List candleStickData)
// {
// this.candleStickData = candleStickData;
// }
//
// public List getCandleStickData()
// {
// return candleStickData;
// }
// }
| import burstcoin.observer.bean.AssetBean;
import burstcoin.observer.bean.AssetCandleStickBean;
import java.util.Date;
import java.util.List; | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package burstcoin.observer.event;
public class AssetUpdateEvent
{
private Date lastUpdate;
private List<AssetBean> assetBeans; | // Path: src/main/java/burstcoin/observer/bean/AssetBean.java
// public class AssetBean
// {
// private String asset;
// private String name;
// private String description;
//
// private String accountRS;
// private String account;
//
// private String quantityQNT;
// private int decimals;
//
// private int numberOfAccounts;
// private int numberOfTransfers;
// private int numberOfTrades;
//
// private int numberOfBuyOrders;
// private int numberOfSellOrders;
// private String volume7Days;
// private String volume30Days;
//
// private String lastPrice;
//
// public AssetBean(String asset, String name, String description, String accountRS, String account, String quantityQNT, int decimals, int numberOfAccounts,
// int numberOfTransfers, int numberOfTrades, int numberOfBuyOrders, int numberOfSellOrders, String volume7Days, String volume30Days,
// String lastPrice)
// {
// this.asset = asset;
// this.name = name;
// this.description = description;
// this.accountRS = accountRS;
// this.account = account;
// this.quantityQNT = quantityQNT;
// this.decimals = decimals;
// this.numberOfAccounts = numberOfAccounts;
// this.numberOfTransfers = numberOfTransfers;
// this.numberOfTrades = numberOfTrades;
// this.numberOfBuyOrders = numberOfBuyOrders;
// this.numberOfSellOrders = numberOfSellOrders;
// this.volume7Days = volume7Days.equals("") ? "0" : volume7Days;
// this.volume30Days = volume30Days.equals("") ? "0" : volume30Days;
//
// this.lastPrice = lastPrice;
// }
//
// public String getLastPrice()
// {
// return lastPrice;
// }
//
// public String getVolume7Days()
// {
// return volume7Days;
// }
//
// public String getVolume30Days()
// {
// return volume30Days;
// }
//
// public String getAsset()
// {
// return asset;
// }
//
// public String getName()
// {
// return name;
// }
//
// public String getDescription()
// {
// return description;
// }
//
// public String getAccountRS()
// {
// return accountRS;
// }
//
// public String getAccount()
// {
// return account;
// }
//
// public String getQuantityQNT()
// {
// return quantityQNT;
// }
//
// public int getDecimals()
// {
// return decimals;
// }
//
// public int getNumberOfAccounts()
// {
// return numberOfAccounts;
// }
//
// public int getNumberOfTransfers()
// {
// return numberOfTransfers;
// }
//
// public int getNumberOfTrades()
// {
// return numberOfTrades;
// }
//
// public int getNumberOfBuyOrders()
// {
// return numberOfBuyOrders;
// }
//
// public int getNumberOfSellOrders()
// {
// return numberOfSellOrders;
// }
// }
//
// Path: src/main/java/burstcoin/observer/bean/AssetCandleStickBean.java
// public class AssetCandleStickBean
// {
// private String asset;
// private List candleStickData;
//
// public AssetCandleStickBean(String asset, List candleStickData)
// {
// this.asset = asset;
// this.candleStickData = candleStickData;
// }
//
// public String getAsset()
// {
// return asset;
// }
//
// public void setCandleStickData(List candleStickData)
// {
// this.candleStickData = candleStickData;
// }
//
// public List getCandleStickData()
// {
// return candleStickData;
// }
// }
// Path: src/main/java/burstcoin/observer/event/AssetUpdateEvent.java
import burstcoin.observer.bean.AssetBean;
import burstcoin.observer.bean.AssetCandleStickBean;
import java.util.Date;
import java.util.List;
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package burstcoin.observer.event;
public class AssetUpdateEvent
{
private Date lastUpdate;
private List<AssetBean> assetBeans; | private List<AssetCandleStickBean> assetCandleStickBeans; |
de-luxe/burstcoin-observer | src/main/java/burstcoin/observer/event/NodeUpdateEvent.java | // Path: src/main/java/burstcoin/observer/bean/NodeListBean.java
// public class NodeListBean
// {
// private String announcedAddress;
// private String ip;
// private String version;
// private String platform;
//
// private String country;
// private String region;
// private String city;
//
// private Date lastUpdate;
// private String updated;
//
// private String isp;
//
// public NodeListBean(Date lastUpdate, String announcedAddress, String ip, String version, String platform, String country, String region, String city, String isp)
// {
// this.lastUpdate = lastUpdate;
// this.announcedAddress = announcedAddress;
// this.ip = ip;
// this.version = version;
// this.platform = platform;
// this.country = country;
// this.region = region;
// this.city = city;
// this.isp = isp;
// }
//
// public String getUpdated()
// {
// return updated;
// }
//
// public void setUpdated(String updated)
// {
// this.updated = updated;
// }
//
// public Date getLastUpdate()
// {
// return lastUpdate;
// }
//
// public String getAnnouncedAddress()
// {
// return announcedAddress;
// }
//
// public String getIp()
// {
// return ip;
// }
//
// public String getVersion()
// {
// return version;
// }
//
// public String getPlatform()
// {
// return platform;
// }
//
// public String getCountry()
// {
// return country;
// }
//
// public String getRegion()
// {
// return region;
// }
//
// public String getCity()
// {
// return city;
// }
//
// public String getIsp()
// {
// return isp;
// }
// }
//
// Path: src/main/java/burstcoin/observer/bean/NodeStats.java
// public class NodeStats
// {
// private int nodeCount; // found active from wallet
// private int activeNodeCount; // last update within 24h
//
// private String peers;
//
// public NodeStats(int nodeCount, int activeNodeCount, String peers)
// {
// this.nodeCount = nodeCount;
// this.activeNodeCount = activeNodeCount;
// this.peers = peers;
// }
//
// public String getPeers()
// {
// return peers;
// }
//
// public int getActiveNodeCount()
// {
// return activeNodeCount;
// }
//
// public int getNodeCount()
// {
// return nodeCount;
// }
// }
| import burstcoin.observer.bean.NodeListBean;
import burstcoin.observer.bean.NodeStats;
import java.util.Date;
import java.util.List; | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package burstcoin.observer.event;
public class NodeUpdateEvent
{ | // Path: src/main/java/burstcoin/observer/bean/NodeListBean.java
// public class NodeListBean
// {
// private String announcedAddress;
// private String ip;
// private String version;
// private String platform;
//
// private String country;
// private String region;
// private String city;
//
// private Date lastUpdate;
// private String updated;
//
// private String isp;
//
// public NodeListBean(Date lastUpdate, String announcedAddress, String ip, String version, String platform, String country, String region, String city, String isp)
// {
// this.lastUpdate = lastUpdate;
// this.announcedAddress = announcedAddress;
// this.ip = ip;
// this.version = version;
// this.platform = platform;
// this.country = country;
// this.region = region;
// this.city = city;
// this.isp = isp;
// }
//
// public String getUpdated()
// {
// return updated;
// }
//
// public void setUpdated(String updated)
// {
// this.updated = updated;
// }
//
// public Date getLastUpdate()
// {
// return lastUpdate;
// }
//
// public String getAnnouncedAddress()
// {
// return announcedAddress;
// }
//
// public String getIp()
// {
// return ip;
// }
//
// public String getVersion()
// {
// return version;
// }
//
// public String getPlatform()
// {
// return platform;
// }
//
// public String getCountry()
// {
// return country;
// }
//
// public String getRegion()
// {
// return region;
// }
//
// public String getCity()
// {
// return city;
// }
//
// public String getIsp()
// {
// return isp;
// }
// }
//
// Path: src/main/java/burstcoin/observer/bean/NodeStats.java
// public class NodeStats
// {
// private int nodeCount; // found active from wallet
// private int activeNodeCount; // last update within 24h
//
// private String peers;
//
// public NodeStats(int nodeCount, int activeNodeCount, String peers)
// {
// this.nodeCount = nodeCount;
// this.activeNodeCount = activeNodeCount;
// this.peers = peers;
// }
//
// public String getPeers()
// {
// return peers;
// }
//
// public int getActiveNodeCount()
// {
// return activeNodeCount;
// }
//
// public int getNodeCount()
// {
// return nodeCount;
// }
// }
// Path: src/main/java/burstcoin/observer/event/NodeUpdateEvent.java
import burstcoin.observer.bean.NodeListBean;
import burstcoin.observer.bean.NodeStats;
import java.util.Date;
import java.util.List;
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package burstcoin.observer.event;
public class NodeUpdateEvent
{ | private List<NodeListBean> nodes; |
de-luxe/burstcoin-observer | src/main/java/burstcoin/observer/event/NodeUpdateEvent.java | // Path: src/main/java/burstcoin/observer/bean/NodeListBean.java
// public class NodeListBean
// {
// private String announcedAddress;
// private String ip;
// private String version;
// private String platform;
//
// private String country;
// private String region;
// private String city;
//
// private Date lastUpdate;
// private String updated;
//
// private String isp;
//
// public NodeListBean(Date lastUpdate, String announcedAddress, String ip, String version, String platform, String country, String region, String city, String isp)
// {
// this.lastUpdate = lastUpdate;
// this.announcedAddress = announcedAddress;
// this.ip = ip;
// this.version = version;
// this.platform = platform;
// this.country = country;
// this.region = region;
// this.city = city;
// this.isp = isp;
// }
//
// public String getUpdated()
// {
// return updated;
// }
//
// public void setUpdated(String updated)
// {
// this.updated = updated;
// }
//
// public Date getLastUpdate()
// {
// return lastUpdate;
// }
//
// public String getAnnouncedAddress()
// {
// return announcedAddress;
// }
//
// public String getIp()
// {
// return ip;
// }
//
// public String getVersion()
// {
// return version;
// }
//
// public String getPlatform()
// {
// return platform;
// }
//
// public String getCountry()
// {
// return country;
// }
//
// public String getRegion()
// {
// return region;
// }
//
// public String getCity()
// {
// return city;
// }
//
// public String getIsp()
// {
// return isp;
// }
// }
//
// Path: src/main/java/burstcoin/observer/bean/NodeStats.java
// public class NodeStats
// {
// private int nodeCount; // found active from wallet
// private int activeNodeCount; // last update within 24h
//
// private String peers;
//
// public NodeStats(int nodeCount, int activeNodeCount, String peers)
// {
// this.nodeCount = nodeCount;
// this.activeNodeCount = activeNodeCount;
// this.peers = peers;
// }
//
// public String getPeers()
// {
// return peers;
// }
//
// public int getActiveNodeCount()
// {
// return activeNodeCount;
// }
//
// public int getNodeCount()
// {
// return nodeCount;
// }
// }
| import burstcoin.observer.bean.NodeListBean;
import burstcoin.observer.bean.NodeStats;
import java.util.Date;
import java.util.List; | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package burstcoin.observer.event;
public class NodeUpdateEvent
{
private List<NodeListBean> nodes; | // Path: src/main/java/burstcoin/observer/bean/NodeListBean.java
// public class NodeListBean
// {
// private String announcedAddress;
// private String ip;
// private String version;
// private String platform;
//
// private String country;
// private String region;
// private String city;
//
// private Date lastUpdate;
// private String updated;
//
// private String isp;
//
// public NodeListBean(Date lastUpdate, String announcedAddress, String ip, String version, String platform, String country, String region, String city, String isp)
// {
// this.lastUpdate = lastUpdate;
// this.announcedAddress = announcedAddress;
// this.ip = ip;
// this.version = version;
// this.platform = platform;
// this.country = country;
// this.region = region;
// this.city = city;
// this.isp = isp;
// }
//
// public String getUpdated()
// {
// return updated;
// }
//
// public void setUpdated(String updated)
// {
// this.updated = updated;
// }
//
// public Date getLastUpdate()
// {
// return lastUpdate;
// }
//
// public String getAnnouncedAddress()
// {
// return announcedAddress;
// }
//
// public String getIp()
// {
// return ip;
// }
//
// public String getVersion()
// {
// return version;
// }
//
// public String getPlatform()
// {
// return platform;
// }
//
// public String getCountry()
// {
// return country;
// }
//
// public String getRegion()
// {
// return region;
// }
//
// public String getCity()
// {
// return city;
// }
//
// public String getIsp()
// {
// return isp;
// }
// }
//
// Path: src/main/java/burstcoin/observer/bean/NodeStats.java
// public class NodeStats
// {
// private int nodeCount; // found active from wallet
// private int activeNodeCount; // last update within 24h
//
// private String peers;
//
// public NodeStats(int nodeCount, int activeNodeCount, String peers)
// {
// this.nodeCount = nodeCount;
// this.activeNodeCount = activeNodeCount;
// this.peers = peers;
// }
//
// public String getPeers()
// {
// return peers;
// }
//
// public int getActiveNodeCount()
// {
// return activeNodeCount;
// }
//
// public int getNodeCount()
// {
// return nodeCount;
// }
// }
// Path: src/main/java/burstcoin/observer/event/NodeUpdateEvent.java
import burstcoin.observer.bean.NodeListBean;
import burstcoin.observer.bean.NodeStats;
import java.util.Date;
import java.util.List;
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package burstcoin.observer.event;
public class NodeUpdateEvent
{
private List<NodeListBean> nodes; | private NodeStats nodeStats; |
de-luxe/burstcoin-observer | src/main/java/burstcoin/observer/service/model/Account.java | // Path: src/main/java/burstcoin/observer/service/model/asset/AssetBalance.java
// public class AssetBalance
// {
// protected String asset;
// protected String balanceQNT;
//
// public String getAsset()
// {
// return asset;
// }
//
// public String getBalanceQNT()
// {
// return balanceQNT;
// }
// }
//
// Path: src/main/java/burstcoin/observer/service/model/asset/UnconfirmedAssetBalance.java
// public class UnconfirmedAssetBalance
// {
// protected String asset;
// protected String unconfirmedBalanceQNT;
//
// public String getAsset()
// {
// return asset;
// }
//
// public String getUnconfirmedBalanceQNT()
// {
// return unconfirmedBalanceQNT;
// }
// }
| import burstcoin.observer.service.model.asset.AssetBalance;
import burstcoin.observer.service.model.asset.UnconfirmedAssetBalance;
import java.util.List; | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package burstcoin.observer.service.model;
public class Account
extends IsResponse
{
protected String unconfirmedBalanceNQT;
protected Long effectiveBalanceNXT;
protected String description;
protected String forgedBalanceNQT;
protected String balanceNQT;
protected String publicKey; | // Path: src/main/java/burstcoin/observer/service/model/asset/AssetBalance.java
// public class AssetBalance
// {
// protected String asset;
// protected String balanceQNT;
//
// public String getAsset()
// {
// return asset;
// }
//
// public String getBalanceQNT()
// {
// return balanceQNT;
// }
// }
//
// Path: src/main/java/burstcoin/observer/service/model/asset/UnconfirmedAssetBalance.java
// public class UnconfirmedAssetBalance
// {
// protected String asset;
// protected String unconfirmedBalanceQNT;
//
// public String getAsset()
// {
// return asset;
// }
//
// public String getUnconfirmedBalanceQNT()
// {
// return unconfirmedBalanceQNT;
// }
// }
// Path: src/main/java/burstcoin/observer/service/model/Account.java
import burstcoin.observer.service.model.asset.AssetBalance;
import burstcoin.observer.service.model.asset.UnconfirmedAssetBalance;
import java.util.List;
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package burstcoin.observer.service.model;
public class Account
extends IsResponse
{
protected String unconfirmedBalanceNQT;
protected Long effectiveBalanceNXT;
protected String description;
protected String forgedBalanceNQT;
protected String balanceNQT;
protected String publicKey; | protected List<AssetBalance> assetBalances; |
de-luxe/burstcoin-observer | src/main/java/burstcoin/observer/service/model/Account.java | // Path: src/main/java/burstcoin/observer/service/model/asset/AssetBalance.java
// public class AssetBalance
// {
// protected String asset;
// protected String balanceQNT;
//
// public String getAsset()
// {
// return asset;
// }
//
// public String getBalanceQNT()
// {
// return balanceQNT;
// }
// }
//
// Path: src/main/java/burstcoin/observer/service/model/asset/UnconfirmedAssetBalance.java
// public class UnconfirmedAssetBalance
// {
// protected String asset;
// protected String unconfirmedBalanceQNT;
//
// public String getAsset()
// {
// return asset;
// }
//
// public String getUnconfirmedBalanceQNT()
// {
// return unconfirmedBalanceQNT;
// }
// }
| import burstcoin.observer.service.model.asset.AssetBalance;
import burstcoin.observer.service.model.asset.UnconfirmedAssetBalance;
import java.util.List; | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package burstcoin.observer.service.model;
public class Account
extends IsResponse
{
protected String unconfirmedBalanceNQT;
protected Long effectiveBalanceNXT;
protected String description;
protected String forgedBalanceNQT;
protected String balanceNQT;
protected String publicKey;
protected List<AssetBalance> assetBalances;
protected String guaranteedBalanceNQT; | // Path: src/main/java/burstcoin/observer/service/model/asset/AssetBalance.java
// public class AssetBalance
// {
// protected String asset;
// protected String balanceQNT;
//
// public String getAsset()
// {
// return asset;
// }
//
// public String getBalanceQNT()
// {
// return balanceQNT;
// }
// }
//
// Path: src/main/java/burstcoin/observer/service/model/asset/UnconfirmedAssetBalance.java
// public class UnconfirmedAssetBalance
// {
// protected String asset;
// protected String unconfirmedBalanceQNT;
//
// public String getAsset()
// {
// return asset;
// }
//
// public String getUnconfirmedBalanceQNT()
// {
// return unconfirmedBalanceQNT;
// }
// }
// Path: src/main/java/burstcoin/observer/service/model/Account.java
import burstcoin.observer.service.model.asset.AssetBalance;
import burstcoin.observer.service.model.asset.UnconfirmedAssetBalance;
import java.util.List;
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package burstcoin.observer.service.model;
public class Account
extends IsResponse
{
protected String unconfirmedBalanceNQT;
protected Long effectiveBalanceNXT;
protected String description;
protected String forgedBalanceNQT;
protected String balanceNQT;
protected String publicKey;
protected List<AssetBalance> assetBalances;
protected String guaranteedBalanceNQT; | protected List<UnconfirmedAssetBalance> unconfirmedAssetBalances; |
de-luxe/burstcoin-observer | src/main/java/burstcoin/observer/event/NetworkUpdateEvent.java | // Path: src/main/java/burstcoin/observer/bean/NetworkBean.java
// public class NetworkBean
// {
// private String height;
// private String domain;
// private String url;
// private String baseTarget;
// private String generationSignature;
// private String targetDeadline;
// private String type;
// private String https;
//
// private NetworkState state;
//
// private Boolean available;
//
// public NetworkBean(String domain)
// {
// this.domain = domain;
// this.type = "N/A";
// this.height = "";
// this.baseTarget = "";
// this.generationSignature = "";
// this.targetDeadline = "";
// this.available = false;
// this.url = domain;
// }
//
// public NetworkBean(String height, String domain, String url, String baseTarget, String generationSignature, String targetDeadline, String https)
// {
// this.height = height;
// this.domain = domain;
// this.url = url;
// this.baseTarget = baseTarget;
// this.generationSignature = generationSignature;
// this.https = https;
// this.state = NetworkState.OK;
// this.available = true;
//
// // week impl. wallet with pool in domain will show up as pool
// this.type = targetDeadline.equals("0") ? domain.contains("faucet") ? "Faucet" : domain.contains("pool") ? "Pool" : "Wallet" : "Pool";
// if(domain.contains("burstcoin.cc:3333"))
// {
// this.type = "Faucet";
// }
// if(domain.contains("neon") || domain.contains("btfg") || domain.contains("burst.cryptoguru.org") || domain.contains("5y.dk:8100"))
// {
// this.type = "Pool";
// }
// this.targetDeadline = targetDeadline.equals("0") ? "Pool".equals(type) ? "Unlimited" : "N/A" : targetDeadline;
// }
//
// public String getHeight()
// {
// return height;
// }
//
// public String getDomain()
// {
// return domain;
// }
//
// public String getBaseTarget()
// {
// return baseTarget;
// }
//
// public String getGenerationSignature()
// {
// return generationSignature;
// }
//
// public String getTargetDeadline()
// {
// return targetDeadline;
// }
//
// public String getType()
// {
// return type;
// }
//
// public NetworkState getState()
// {
// return state;
// }
//
// public void setState(NetworkState state)
// {
// this.state = state;
// }
//
// public String getUrl()
// {
// return url;
// }
//
// public String getHttps()
// {
// return https;
// }
//
// public Boolean getAvailable()
// {
// return available;
// }
//
// @Override
// public boolean equals(Object o)
// {
// if(this == o)
// {
// return true;
// }
// if(!(o instanceof NetworkBean))
// {
// return false;
// }
//
// NetworkBean that = (NetworkBean) o;
//
// return domain.equals(that.domain);
//
// }
//
// @Override
// public int hashCode()
// {
// return domain.hashCode();
// }
// }
| import burstcoin.observer.bean.NetworkBean;
import java.util.Date;
import java.util.List; | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package burstcoin.observer.event;
public class NetworkUpdateEvent
{
private Date lastUpdate; | // Path: src/main/java/burstcoin/observer/bean/NetworkBean.java
// public class NetworkBean
// {
// private String height;
// private String domain;
// private String url;
// private String baseTarget;
// private String generationSignature;
// private String targetDeadline;
// private String type;
// private String https;
//
// private NetworkState state;
//
// private Boolean available;
//
// public NetworkBean(String domain)
// {
// this.domain = domain;
// this.type = "N/A";
// this.height = "";
// this.baseTarget = "";
// this.generationSignature = "";
// this.targetDeadline = "";
// this.available = false;
// this.url = domain;
// }
//
// public NetworkBean(String height, String domain, String url, String baseTarget, String generationSignature, String targetDeadline, String https)
// {
// this.height = height;
// this.domain = domain;
// this.url = url;
// this.baseTarget = baseTarget;
// this.generationSignature = generationSignature;
// this.https = https;
// this.state = NetworkState.OK;
// this.available = true;
//
// // week impl. wallet with pool in domain will show up as pool
// this.type = targetDeadline.equals("0") ? domain.contains("faucet") ? "Faucet" : domain.contains("pool") ? "Pool" : "Wallet" : "Pool";
// if(domain.contains("burstcoin.cc:3333"))
// {
// this.type = "Faucet";
// }
// if(domain.contains("neon") || domain.contains("btfg") || domain.contains("burst.cryptoguru.org") || domain.contains("5y.dk:8100"))
// {
// this.type = "Pool";
// }
// this.targetDeadline = targetDeadline.equals("0") ? "Pool".equals(type) ? "Unlimited" : "N/A" : targetDeadline;
// }
//
// public String getHeight()
// {
// return height;
// }
//
// public String getDomain()
// {
// return domain;
// }
//
// public String getBaseTarget()
// {
// return baseTarget;
// }
//
// public String getGenerationSignature()
// {
// return generationSignature;
// }
//
// public String getTargetDeadline()
// {
// return targetDeadline;
// }
//
// public String getType()
// {
// return type;
// }
//
// public NetworkState getState()
// {
// return state;
// }
//
// public void setState(NetworkState state)
// {
// this.state = state;
// }
//
// public String getUrl()
// {
// return url;
// }
//
// public String getHttps()
// {
// return https;
// }
//
// public Boolean getAvailable()
// {
// return available;
// }
//
// @Override
// public boolean equals(Object o)
// {
// if(this == o)
// {
// return true;
// }
// if(!(o instanceof NetworkBean))
// {
// return false;
// }
//
// NetworkBean that = (NetworkBean) o;
//
// return domain.equals(that.domain);
//
// }
//
// @Override
// public int hashCode()
// {
// return domain.hashCode();
// }
// }
// Path: src/main/java/burstcoin/observer/event/NetworkUpdateEvent.java
import burstcoin.observer.bean.NetworkBean;
import java.util.Date;
import java.util.List;
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package burstcoin.observer.event;
public class NetworkUpdateEvent
{
private Date lastUpdate; | private List<NetworkBean> networkBeans; |
de-luxe/burstcoin-observer | src/main/java/burstcoin/observer/service/network/MiningInfoEvent.java | // Path: src/main/java/burstcoin/observer/service/model/MiningInfo.java
// public class MiningInfo
// implements Serializable
// {
// private String generationSignature;
// private String baseTarget;
// private long requestProcessingTime;
// private long height;
//
// // only if pool
// private long targetDeadline;
//
// public MiningInfo()
// {
// }
//
// public long getTargetDeadline()
// {
// return targetDeadline;
// }
//
// public void setTargetDeadline(long targetDeadline)
// {
// this.targetDeadline = targetDeadline;
// }
//
// public String getGenerationSignature()
// {
// return generationSignature;
// }
//
// public void setGenerationSignature(String generationSignature)
// {
// this.generationSignature = generationSignature;
// }
//
// public String getBaseTarget()
// {
// return baseTarget;
// }
//
// public void setBaseTarget(String baseTarget)
// {
// this.baseTarget = baseTarget;
// }
//
// public long getRequestProcessingTime()
// {
// return requestProcessingTime;
// }
//
// public void setRequestProcessingTime(long requestProcessingTime)
// {
// this.requestProcessingTime = requestProcessingTime;
// }
//
// public long getHeight()
// {
// return height;
// }
//
// public void setHeight(long height)
// {
// this.height = height;
// }
// }
| import burstcoin.observer.service.model.MiningInfo;
import org.springframework.context.ApplicationEvent;
import java.io.Serializable;
import java.util.UUID; | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package burstcoin.observer.service.network;
public class MiningInfoEvent
extends ApplicationEvent implements Serializable
{ | // Path: src/main/java/burstcoin/observer/service/model/MiningInfo.java
// public class MiningInfo
// implements Serializable
// {
// private String generationSignature;
// private String baseTarget;
// private long requestProcessingTime;
// private long height;
//
// // only if pool
// private long targetDeadline;
//
// public MiningInfo()
// {
// }
//
// public long getTargetDeadline()
// {
// return targetDeadline;
// }
//
// public void setTargetDeadline(long targetDeadline)
// {
// this.targetDeadline = targetDeadline;
// }
//
// public String getGenerationSignature()
// {
// return generationSignature;
// }
//
// public void setGenerationSignature(String generationSignature)
// {
// this.generationSignature = generationSignature;
// }
//
// public String getBaseTarget()
// {
// return baseTarget;
// }
//
// public void setBaseTarget(String baseTarget)
// {
// this.baseTarget = baseTarget;
// }
//
// public long getRequestProcessingTime()
// {
// return requestProcessingTime;
// }
//
// public void setRequestProcessingTime(long requestProcessingTime)
// {
// this.requestProcessingTime = requestProcessingTime;
// }
//
// public long getHeight()
// {
// return height;
// }
//
// public void setHeight(long height)
// {
// this.height = height;
// }
// }
// Path: src/main/java/burstcoin/observer/service/network/MiningInfoEvent.java
import burstcoin.observer.service.model.MiningInfo;
import org.springframework.context.ApplicationEvent;
import java.io.Serializable;
import java.util.UUID;
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies
* or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package burstcoin.observer.service.network;
public class MiningInfoEvent
extends ApplicationEvent implements Serializable
{ | private MiningInfo miningInfo; |
SilenceDut/NBAPlus | app/src/main/java/com/me/silencedut/nbaplus/network/NewsDetileAPI.java | // Path: app/src/main/java/com/me/silencedut/nbaplus/model/NewsDetile.java
// public class NewsDetile {
//
// private String author;
//
// private Map<String,ContentImage> articleMediaMap;
//
// private String content;
//
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
// public Map<String, ContentImage> getArticleMediaMap() {
// return articleMediaMap;
// }
//
// public void setArticleMediaMap(Map<String, ContentImage> articleMediaMap) {
// this.articleMediaMap = articleMediaMap;
// }
//
// public String getContent() {
// return content;
// }
//
// public void setContent(String content) {
// this.content = content;
// }
//
// public static class ContentImage {
// String url;
// int id;
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
// }
// }
| import com.me.silencedut.nbaplus.model.NewsDetile;
import retrofit.http.GET;
import retrofit.http.Path;
import rx.Observable; | package com.me.silencedut.nbaplus.network;
/**
* Created by SilenceDut on 2015/12/10.
*/
public interface NewsDetileAPI {
@GET("{date}/{detileId}") | // Path: app/src/main/java/com/me/silencedut/nbaplus/model/NewsDetile.java
// public class NewsDetile {
//
// private String author;
//
// private Map<String,ContentImage> articleMediaMap;
//
// private String content;
//
// public String getAuthor() {
// return author;
// }
//
// public void setAuthor(String author) {
// this.author = author;
// }
//
// public Map<String, ContentImage> getArticleMediaMap() {
// return articleMediaMap;
// }
//
// public void setArticleMediaMap(Map<String, ContentImage> articleMediaMap) {
// this.articleMediaMap = articleMediaMap;
// }
//
// public String getContent() {
// return content;
// }
//
// public void setContent(String content) {
// this.content = content;
// }
//
// public static class ContentImage {
// String url;
// int id;
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
// }
// }
// Path: app/src/main/java/com/me/silencedut/nbaplus/network/NewsDetileAPI.java
import com.me.silencedut.nbaplus.model.NewsDetile;
import retrofit.http.GET;
import retrofit.http.Path;
import rx.Observable;
package com.me.silencedut.nbaplus.network;
/**
* Created by SilenceDut on 2015/12/10.
*/
public interface NewsDetileAPI {
@GET("{date}/{detileId}") | Observable<NewsDetile> getNewsDetile(@Path("date") String type,@Path("detileId") String newsId); |
SilenceDut/NBAPlus | chartlibrary/src/com/db/chart/view/Tooltip.java | // Path: chartlibrary/src/com/db/chart/listener/OnTooltipEventListener.java
// public interface OnTooltipEventListener {
//
// void onEnter(View view);
// void onExit(View view);
//
// }
| import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.db.chart.listener.OnTooltipEventListener; | /*
* Copyright 2015 Diogo Bernardino
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.db.chart.view;
/**
* Class representing chart's tooltips. It works basically as a wrapper.
*/
public class Tooltip extends RelativeLayout{
private TextView mTooltipValue;
| // Path: chartlibrary/src/com/db/chart/listener/OnTooltipEventListener.java
// public interface OnTooltipEventListener {
//
// void onEnter(View view);
// void onExit(View view);
//
// }
// Path: chartlibrary/src/com/db/chart/view/Tooltip.java
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.db.chart.listener.OnTooltipEventListener;
/*
* Copyright 2015 Diogo Bernardino
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.db.chart.view;
/**
* Class representing chart's tooltips. It works basically as a wrapper.
*/
public class Tooltip extends RelativeLayout{
private TextView mTooltipValue;
| private OnTooltipEventListener mTooltipEventListener; |
SilenceDut/NBAPlus | app/src/main/java/com/me/silencedut/nbaplus/event/NewsEvent.java | // Path: app/src/main/java/com/me/silencedut/nbaplus/model/News.java
// public class News {
// /**
// * nextId : 116409785
// * newslist : [{"contentType":"ARTICLE","description":"央视体育频道女主播\u201c乌贼刘\u201d刘语熙在社交网络发文\u201c人生若只如初见,再见最前线!\u201d,以此正式宣布离开《","title":"告别NBA!最美女主播宣布退出","putdate":"20151204","imgUrlList":["http://img.res.meizu.com/img/download/reader/2015/1204/8/92edcd73/452f4cc1/81686264/66092ed4/original"],"randomNum":1449186657638,"articleId":116409942,"contentSourceName":"NBA","articleUrl":"http://reader.res.meizu.com/reader/articlecontent/20151204/116409942.json","type":"IMAGETEXT","topicVoteJson":null,"sourceType":"ZAKER"}]
// */
//
// private String nextId;
// /**
// * contentType : ARTICLE
// * description : 央视体育频道女主播“乌贼刘”刘语熙在社交网络发文“人生若只如初见,再见最前线!”,以此正式宣布离开《
// * title : 告别NBA!最美女主播宣布退出
// * putdate : 20151204
// * imgUrlList : ["http://img.res.meizu.com/img/download/reader/2015/1204/8/92edcd73/452f4cc1/81686264/66092ed4/original"]
// * randomNum : 1449186657638
// * articleId : 116409942
// * contentSourceName : NBA
// * articleUrl : http://reader.res.meizu.com/reader/articlecontent/20151204/116409942.json
// * type : IMAGETEXT
// * topicVoteJson : null
// * sourceType : ZAKER
// */
//
// private List<NewslistEntity> newslist;
//
// public void setNextId(String nextId) {
// this.nextId = nextId;
// }
//
// public void setNewslist(List<NewslistEntity> newslist) {
// this.newslist = newslist;
// }
//
// public String getNextId() {
// return nextId;
// }
//
// public List<NewslistEntity> getNewslist() {
// return newslist;
// }
//
// public static class NewslistEntity {
// private String description;
// private String title;
// private String putdate;
// private String articleId;
// private String contentSourceName;
// private String articleUrl;
// private Object topicVoteJson;
// private List<String> imgUrlList;
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public void setPutdate(String putdate) {
// this.putdate = putdate;
// }
//
// public void setArticleId(String articleId) {
// this.articleId = articleId;
// }
//
// public void setContentSourceName(String contentSourceName) {
// this.contentSourceName = contentSourceName;
// }
//
// public void setArticleUrl(String articleUrl) {
// this.articleUrl = articleUrl;
// }
//
// public void setTopicVoteJson(Object topicVoteJson) {
// this.topicVoteJson = topicVoteJson;
// }
//
// public void setImgUrlList(List<String> imgUrlList) {
// this.imgUrlList = imgUrlList;
// }
//
// public String getDescription() {
// return description;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getPutdate() {
// return putdate;
// }
//
// public String getArticleId() {
// return articleId;
// }
//
// public String getContentSourceName() {
// return contentSourceName;
// }
//
// public String getArticleUrl() {
// return articleUrl;
// }
//
// public Object getTopicVoteJson() {
// return topicVoteJson;
// }
//
// public List<String> getImgUrlList() {
// return imgUrlList;
// }
// }
// }
//
// Path: app/src/main/java/com/me/silencedut/nbaplus/data/Constant.java
// public enum GETNEWSWAY {
// INIT,UPDATE,LOADMORE;
// }
| import com.me.silencedut.nbaplus.model.News;
import com.me.silencedut.nbaplus.data.Constant.GETNEWSWAY; | package com.me.silencedut.nbaplus.event;
/**
* Created by Silencedut on 2015/11/28.
*/
public class NewsEvent extends Event {
private News news; | // Path: app/src/main/java/com/me/silencedut/nbaplus/model/News.java
// public class News {
// /**
// * nextId : 116409785
// * newslist : [{"contentType":"ARTICLE","description":"央视体育频道女主播\u201c乌贼刘\u201d刘语熙在社交网络发文\u201c人生若只如初见,再见最前线!\u201d,以此正式宣布离开《","title":"告别NBA!最美女主播宣布退出","putdate":"20151204","imgUrlList":["http://img.res.meizu.com/img/download/reader/2015/1204/8/92edcd73/452f4cc1/81686264/66092ed4/original"],"randomNum":1449186657638,"articleId":116409942,"contentSourceName":"NBA","articleUrl":"http://reader.res.meizu.com/reader/articlecontent/20151204/116409942.json","type":"IMAGETEXT","topicVoteJson":null,"sourceType":"ZAKER"}]
// */
//
// private String nextId;
// /**
// * contentType : ARTICLE
// * description : 央视体育频道女主播“乌贼刘”刘语熙在社交网络发文“人生若只如初见,再见最前线!”,以此正式宣布离开《
// * title : 告别NBA!最美女主播宣布退出
// * putdate : 20151204
// * imgUrlList : ["http://img.res.meizu.com/img/download/reader/2015/1204/8/92edcd73/452f4cc1/81686264/66092ed4/original"]
// * randomNum : 1449186657638
// * articleId : 116409942
// * contentSourceName : NBA
// * articleUrl : http://reader.res.meizu.com/reader/articlecontent/20151204/116409942.json
// * type : IMAGETEXT
// * topicVoteJson : null
// * sourceType : ZAKER
// */
//
// private List<NewslistEntity> newslist;
//
// public void setNextId(String nextId) {
// this.nextId = nextId;
// }
//
// public void setNewslist(List<NewslistEntity> newslist) {
// this.newslist = newslist;
// }
//
// public String getNextId() {
// return nextId;
// }
//
// public List<NewslistEntity> getNewslist() {
// return newslist;
// }
//
// public static class NewslistEntity {
// private String description;
// private String title;
// private String putdate;
// private String articleId;
// private String contentSourceName;
// private String articleUrl;
// private Object topicVoteJson;
// private List<String> imgUrlList;
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public void setPutdate(String putdate) {
// this.putdate = putdate;
// }
//
// public void setArticleId(String articleId) {
// this.articleId = articleId;
// }
//
// public void setContentSourceName(String contentSourceName) {
// this.contentSourceName = contentSourceName;
// }
//
// public void setArticleUrl(String articleUrl) {
// this.articleUrl = articleUrl;
// }
//
// public void setTopicVoteJson(Object topicVoteJson) {
// this.topicVoteJson = topicVoteJson;
// }
//
// public void setImgUrlList(List<String> imgUrlList) {
// this.imgUrlList = imgUrlList;
// }
//
// public String getDescription() {
// return description;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getPutdate() {
// return putdate;
// }
//
// public String getArticleId() {
// return articleId;
// }
//
// public String getContentSourceName() {
// return contentSourceName;
// }
//
// public String getArticleUrl() {
// return articleUrl;
// }
//
// public Object getTopicVoteJson() {
// return topicVoteJson;
// }
//
// public List<String> getImgUrlList() {
// return imgUrlList;
// }
// }
// }
//
// Path: app/src/main/java/com/me/silencedut/nbaplus/data/Constant.java
// public enum GETNEWSWAY {
// INIT,UPDATE,LOADMORE;
// }
// Path: app/src/main/java/com/me/silencedut/nbaplus/event/NewsEvent.java
import com.me.silencedut.nbaplus.model.News;
import com.me.silencedut.nbaplus.data.Constant.GETNEWSWAY;
package com.me.silencedut.nbaplus.event;
/**
* Created by Silencedut on 2015/11/28.
*/
public class NewsEvent extends Event {
private News news; | private GETNEWSWAY getNewsWay; |
SilenceDut/NBAPlus | app/src/main/java/com/me/silencedut/nbaplus/ui/adapter/RecycleAdapter/MainAdapter.java | // Path: app/src/main/java/com/me/silencedut/nbaplus/model/News.java
// public static class NewslistEntity {
// private String description;
// private String title;
// private String putdate;
// private String articleId;
// private String contentSourceName;
// private String articleUrl;
// private Object topicVoteJson;
// private List<String> imgUrlList;
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public void setPutdate(String putdate) {
// this.putdate = putdate;
// }
//
// public void setArticleId(String articleId) {
// this.articleId = articleId;
// }
//
// public void setContentSourceName(String contentSourceName) {
// this.contentSourceName = contentSourceName;
// }
//
// public void setArticleUrl(String articleUrl) {
// this.articleUrl = articleUrl;
// }
//
// public void setTopicVoteJson(Object topicVoteJson) {
// this.topicVoteJson = topicVoteJson;
// }
//
// public void setImgUrlList(List<String> imgUrlList) {
// this.imgUrlList = imgUrlList;
// }
//
// public String getDescription() {
// return description;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getPutdate() {
// return putdate;
// }
//
// public String getArticleId() {
// return articleId;
// }
//
// public String getContentSourceName() {
// return contentSourceName;
// }
//
// public String getArticleUrl() {
// return articleUrl;
// }
//
// public Object getTopicVoteJson() {
// return topicVoteJson;
// }
//
// public List<String> getImgUrlList() {
// return imgUrlList;
// }
// }
//
// Path: app/src/main/java/com/me/silencedut/nbaplus/utils/DateFormatter.java
// public class DateFormatter {
//
// public static String formatDate(String format) {
// if(TextUtils.isEmpty(format)) {
// format="yyyy/MM/dd hh:mm:ss";
// }
// DateTime data = new DateTime();
//
// return data.toString(format);
//
// }
//
// private static final long minute = 60 * 1000; //分钟
// private static final long hour = 60 * minute; //小时
// private static final long day = 24 * hour; //天
// private static final long week = 7 * day; //周
// private static final long month = 31 * day; //月
// private static final long year = 12 * month; //年
//
// public static String getRecentlyTimeFormatText(DateTime date) {
// if (date == null) {
// return null;
// }
// long diff = new Date().getTime() - date.getMillis();
// long r = 0;
// if (diff > year) {
//
// return date.toString("yyyy年MM月dd日");
// }
// if (diff > day) {
//
// return date.toString("MM月dd日");
// }
// if (diff > hour) {
// r = (diff / hour);
// return r + "小时前";
// }
// if (diff > minute) {
// r = (diff / minute);
// return r + "分钟前";
// }
// return "刚刚";
// }
//
// }
| import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.me.silencedut.nbaplus.R;
import com.me.silencedut.nbaplus.model.News.NewslistEntity;
import com.me.silencedut.nbaplus.utils.DateFormatter;
import org.joda.time.DateTime;
import java.util.List;
import butterknife.Bind; | case NORMAL:
viewHolder= new NomalNewsViewHolder(mInflater.inflate(R.layout.item_fragment_news_normal, parent, false));break;
default:
break;
}
return viewHolder;
}
class NomalNewsViewHolder extends EntityHolder {
@Bind(R.id.newsImage)
ImageView newsImage;
@Bind(R.id.newsTitle)
TextView newsTitleTV;
@Bind(R.id.newsTime)
TextView newsTimeTV;
String showTime;
public NomalNewsViewHolder(View itemView) {
super(itemView);
}
@Override
protected void update(int position) {
super.update(position);
Glide.with(mContext).load(newEntity.getImgUrlList().get(0))
.placeholder(R.mipmap.placeholder_small)
.into(newsImage);
newsTitleTV.setText(newEntity.getTitle());
if((Long.parseLong(newEntity.getPutdate()))<20151207){
showTime=newEntity.getPutdate().substring(4,6)+"月"+newEntity.getPutdate().substring(6,8)+"日";
}else{ | // Path: app/src/main/java/com/me/silencedut/nbaplus/model/News.java
// public static class NewslistEntity {
// private String description;
// private String title;
// private String putdate;
// private String articleId;
// private String contentSourceName;
// private String articleUrl;
// private Object topicVoteJson;
// private List<String> imgUrlList;
//
// public void setDescription(String description) {
// this.description = description;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public void setPutdate(String putdate) {
// this.putdate = putdate;
// }
//
// public void setArticleId(String articleId) {
// this.articleId = articleId;
// }
//
// public void setContentSourceName(String contentSourceName) {
// this.contentSourceName = contentSourceName;
// }
//
// public void setArticleUrl(String articleUrl) {
// this.articleUrl = articleUrl;
// }
//
// public void setTopicVoteJson(Object topicVoteJson) {
// this.topicVoteJson = topicVoteJson;
// }
//
// public void setImgUrlList(List<String> imgUrlList) {
// this.imgUrlList = imgUrlList;
// }
//
// public String getDescription() {
// return description;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getPutdate() {
// return putdate;
// }
//
// public String getArticleId() {
// return articleId;
// }
//
// public String getContentSourceName() {
// return contentSourceName;
// }
//
// public String getArticleUrl() {
// return articleUrl;
// }
//
// public Object getTopicVoteJson() {
// return topicVoteJson;
// }
//
// public List<String> getImgUrlList() {
// return imgUrlList;
// }
// }
//
// Path: app/src/main/java/com/me/silencedut/nbaplus/utils/DateFormatter.java
// public class DateFormatter {
//
// public static String formatDate(String format) {
// if(TextUtils.isEmpty(format)) {
// format="yyyy/MM/dd hh:mm:ss";
// }
// DateTime data = new DateTime();
//
// return data.toString(format);
//
// }
//
// private static final long minute = 60 * 1000; //分钟
// private static final long hour = 60 * minute; //小时
// private static final long day = 24 * hour; //天
// private static final long week = 7 * day; //周
// private static final long month = 31 * day; //月
// private static final long year = 12 * month; //年
//
// public static String getRecentlyTimeFormatText(DateTime date) {
// if (date == null) {
// return null;
// }
// long diff = new Date().getTime() - date.getMillis();
// long r = 0;
// if (diff > year) {
//
// return date.toString("yyyy年MM月dd日");
// }
// if (diff > day) {
//
// return date.toString("MM月dd日");
// }
// if (diff > hour) {
// r = (diff / hour);
// return r + "小时前";
// }
// if (diff > minute) {
// r = (diff / minute);
// return r + "分钟前";
// }
// return "刚刚";
// }
//
// }
// Path: app/src/main/java/com/me/silencedut/nbaplus/ui/adapter/RecycleAdapter/MainAdapter.java
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.me.silencedut.nbaplus.R;
import com.me.silencedut.nbaplus.model.News.NewslistEntity;
import com.me.silencedut.nbaplus.utils.DateFormatter;
import org.joda.time.DateTime;
import java.util.List;
import butterknife.Bind;
case NORMAL:
viewHolder= new NomalNewsViewHolder(mInflater.inflate(R.layout.item_fragment_news_normal, parent, false));break;
default:
break;
}
return viewHolder;
}
class NomalNewsViewHolder extends EntityHolder {
@Bind(R.id.newsImage)
ImageView newsImage;
@Bind(R.id.newsTitle)
TextView newsTitleTV;
@Bind(R.id.newsTime)
TextView newsTimeTV;
String showTime;
public NomalNewsViewHolder(View itemView) {
super(itemView);
}
@Override
protected void update(int position) {
super.update(position);
Glide.with(mContext).load(newEntity.getImgUrlList().get(0))
.placeholder(R.mipmap.placeholder_small)
.into(newsImage);
newsTitleTV.setText(newEntity.getTitle());
if((Long.parseLong(newEntity.getPutdate()))<20151207){
showTime=newEntity.getPutdate().substring(4,6)+"月"+newEntity.getPutdate().substring(6,8)+"日";
}else{ | showTime = DateFormatter.getRecentlyTimeFormatText(new DateTime(Long.parseLong(newEntity.getPutdate()))); |
SilenceDut/NBAPlus | app/src/main/java/com/me/silencedut/nbaplus/utils/AppUtils.java | // Path: app/src/main/java/com/me/silencedut/nbaplus/app/App.java
// public class App extends Application {
// private static Application sInstance;
// @Override
// public void onCreate() {
// super.onCreate();
// FIR.init(this);
// // mRefWatcher = LeakCanary.install(this);
// sInstance = this;
// AppService.getInstance().initService();
//
// }
// public static Context getContext() {
// return sInstance.getApplicationContext();
// }
//
// }
| import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Color;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.widget.TextView;
import com.me.silencedut.nbaplus.R;
import com.me.silencedut.nbaplus.app.App; | package com.me.silencedut.nbaplus.utils;
/**
* Created by SilenceDut on 2015/12/11.
*/
public class AppUtils {
public static String getVersionName(Context context) {
String versionName = null;
try {
versionName = context.getApplicationContext().getPackageManager()
.getPackageInfo(context.getApplicationContext().getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionName;
}
public static void showSnackBar(View view,int id) { | // Path: app/src/main/java/com/me/silencedut/nbaplus/app/App.java
// public class App extends Application {
// private static Application sInstance;
// @Override
// public void onCreate() {
// super.onCreate();
// FIR.init(this);
// // mRefWatcher = LeakCanary.install(this);
// sInstance = this;
// AppService.getInstance().initService();
//
// }
// public static Context getContext() {
// return sInstance.getApplicationContext();
// }
//
// }
// Path: app/src/main/java/com/me/silencedut/nbaplus/utils/AppUtils.java
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Color;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.widget.TextView;
import com.me.silencedut.nbaplus.R;
import com.me.silencedut.nbaplus.app.App;
package com.me.silencedut.nbaplus.utils;
/**
* Created by SilenceDut on 2015/12/11.
*/
public class AppUtils {
public static String getVersionName(Context context) {
String versionName = null;
try {
versionName = context.getApplicationContext().getPackageManager()
.getPackageInfo(context.getApplicationContext().getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionName;
}
public static void showSnackBar(View view,int id) { | Resources resources =App.getContext().getResources(); |
SilenceDut/NBAPlus | app/src/main/java/com/me/silencedut/nbaplus/event/StatEvent.java | // Path: app/src/main/java/com/me/silencedut/nbaplus/data/Constant.java
// public class Constant {
//
// public static final String APP_FIR_IM_URL="http://fir.im/nbaplus";
// public static final String API_TOKEN_FIR="ff55b0c5cb165ec0b04c473cf77c8995";
//
// public static final String LOADIMAGE = "LOADIMAGE";
// public static final String ACTILEFONTSIZE = "ACTILEFONTSIZE";
//
// public static final String CSS_STYLE ="<style>* {font-size:%spx;line-height:28px;}p {color:%s;}</style>";
//
// public final static String[] TEAM_NAMES={"骑士","猛龙","老鹰","步行者","热火","活塞","公牛","魔术"
// ,"黄蜂","凯尔特人","尼克斯","奇才","雄鹿","篮网","76人","勇士","马刺","雷霆","快船","小牛"
// ,"灰熊","火箭","爵士","太阳","掘金","森林狼","国王","开拓者","鹈鹕","湖人"};
// public final static int[] TEAM_ICONS={R.mipmap.cleveland,R.mipmap.toronto,R.mipmap.atlanta,R.mipmap.indiana
// ,R.mipmap.miami,R.mipmap.detroit,R.mipmap.chicago,R.mipmap.orlando,R.mipmap.charlotte,R.mipmap.boston
// ,R.mipmap.newyork,R.mipmap.washington,R.mipmap.milwaukee,R.mipmap.brooklyn,R.mipmap.phila,R.mipmap.goldenstate
// ,R.mipmap.sanantonio,R.mipmap.okc,R.mipmap.laclippers,R.mipmap.dallas,R.mipmap.memphis,R.mipmap.houston
// ,R.mipmap.utah,R.mipmap.phoenix,R.mipmap.denver,R.mipmap.minnesota,R.mipmap.sacramento,R.mipmap.portland
// ,R.mipmap.neworleans,R.mipmap.lalakers};
//
// private static final Map<String,Integer> sTeamIconMap=new HashMap<>();
//
// static {
// for (int index=0;index<TEAM_NAMES.length;index++){
// sTeamIconMap.put(TEAM_NAMES[index],TEAM_ICONS[index]);
// }
// }
//
// public static Map<String,Integer> getTeamIcons() {
// return sTeamIconMap;
// }
//
// public enum NEWSTYPE {
// NEWS("news"),BLOG("blog");
// private String newsType;
// NEWSTYPE(String newsType) {
// this.newsType=newsType;
// }
// public String getNewsType() {
// return newsType;
// }
// }
//
// public enum GETNEWSWAY {
// INIT,UPDATE,LOADMORE;
// }
//
// public enum Result {
// SUCCESS,FAIL,NORMAL;
// }
//
// }
| import com.me.silencedut.nbaplus.data.Constant; | package com.me.silencedut.nbaplus.event;
/**
* Created by SilenceDut on 2015/12/18.
*/
public class StatEvent extends Event {
private String mStatKind;
private String[][] mLables;
private String[][] mPlayerUrls;
private float[][] mStatValues; | // Path: app/src/main/java/com/me/silencedut/nbaplus/data/Constant.java
// public class Constant {
//
// public static final String APP_FIR_IM_URL="http://fir.im/nbaplus";
// public static final String API_TOKEN_FIR="ff55b0c5cb165ec0b04c473cf77c8995";
//
// public static final String LOADIMAGE = "LOADIMAGE";
// public static final String ACTILEFONTSIZE = "ACTILEFONTSIZE";
//
// public static final String CSS_STYLE ="<style>* {font-size:%spx;line-height:28px;}p {color:%s;}</style>";
//
// public final static String[] TEAM_NAMES={"骑士","猛龙","老鹰","步行者","热火","活塞","公牛","魔术"
// ,"黄蜂","凯尔特人","尼克斯","奇才","雄鹿","篮网","76人","勇士","马刺","雷霆","快船","小牛"
// ,"灰熊","火箭","爵士","太阳","掘金","森林狼","国王","开拓者","鹈鹕","湖人"};
// public final static int[] TEAM_ICONS={R.mipmap.cleveland,R.mipmap.toronto,R.mipmap.atlanta,R.mipmap.indiana
// ,R.mipmap.miami,R.mipmap.detroit,R.mipmap.chicago,R.mipmap.orlando,R.mipmap.charlotte,R.mipmap.boston
// ,R.mipmap.newyork,R.mipmap.washington,R.mipmap.milwaukee,R.mipmap.brooklyn,R.mipmap.phila,R.mipmap.goldenstate
// ,R.mipmap.sanantonio,R.mipmap.okc,R.mipmap.laclippers,R.mipmap.dallas,R.mipmap.memphis,R.mipmap.houston
// ,R.mipmap.utah,R.mipmap.phoenix,R.mipmap.denver,R.mipmap.minnesota,R.mipmap.sacramento,R.mipmap.portland
// ,R.mipmap.neworleans,R.mipmap.lalakers};
//
// private static final Map<String,Integer> sTeamIconMap=new HashMap<>();
//
// static {
// for (int index=0;index<TEAM_NAMES.length;index++){
// sTeamIconMap.put(TEAM_NAMES[index],TEAM_ICONS[index]);
// }
// }
//
// public static Map<String,Integer> getTeamIcons() {
// return sTeamIconMap;
// }
//
// public enum NEWSTYPE {
// NEWS("news"),BLOG("blog");
// private String newsType;
// NEWSTYPE(String newsType) {
// this.newsType=newsType;
// }
// public String getNewsType() {
// return newsType;
// }
// }
//
// public enum GETNEWSWAY {
// INIT,UPDATE,LOADMORE;
// }
//
// public enum Result {
// SUCCESS,FAIL,NORMAL;
// }
//
// }
// Path: app/src/main/java/com/me/silencedut/nbaplus/event/StatEvent.java
import com.me.silencedut.nbaplus.data.Constant;
package com.me.silencedut.nbaplus.event;
/**
* Created by SilenceDut on 2015/12/18.
*/
public class StatEvent extends Event {
private String mStatKind;
private String[][] mLables;
private String[][] mPlayerUrls;
private float[][] mStatValues; | private Constant.GETNEWSWAY getNewsWay; |
SilenceDut/NBAPlus | app/src/main/java/com/me/silencedut/nbaplus/event/TeamSortEvent.java | // Path: app/src/main/java/com/me/silencedut/nbaplus/data/Constant.java
// public class Constant {
//
// public static final String APP_FIR_IM_URL="http://fir.im/nbaplus";
// public static final String API_TOKEN_FIR="ff55b0c5cb165ec0b04c473cf77c8995";
//
// public static final String LOADIMAGE = "LOADIMAGE";
// public static final String ACTILEFONTSIZE = "ACTILEFONTSIZE";
//
// public static final String CSS_STYLE ="<style>* {font-size:%spx;line-height:28px;}p {color:%s;}</style>";
//
// public final static String[] TEAM_NAMES={"骑士","猛龙","老鹰","步行者","热火","活塞","公牛","魔术"
// ,"黄蜂","凯尔特人","尼克斯","奇才","雄鹿","篮网","76人","勇士","马刺","雷霆","快船","小牛"
// ,"灰熊","火箭","爵士","太阳","掘金","森林狼","国王","开拓者","鹈鹕","湖人"};
// public final static int[] TEAM_ICONS={R.mipmap.cleveland,R.mipmap.toronto,R.mipmap.atlanta,R.mipmap.indiana
// ,R.mipmap.miami,R.mipmap.detroit,R.mipmap.chicago,R.mipmap.orlando,R.mipmap.charlotte,R.mipmap.boston
// ,R.mipmap.newyork,R.mipmap.washington,R.mipmap.milwaukee,R.mipmap.brooklyn,R.mipmap.phila,R.mipmap.goldenstate
// ,R.mipmap.sanantonio,R.mipmap.okc,R.mipmap.laclippers,R.mipmap.dallas,R.mipmap.memphis,R.mipmap.houston
// ,R.mipmap.utah,R.mipmap.phoenix,R.mipmap.denver,R.mipmap.minnesota,R.mipmap.sacramento,R.mipmap.portland
// ,R.mipmap.neworleans,R.mipmap.lalakers};
//
// private static final Map<String,Integer> sTeamIconMap=new HashMap<>();
//
// static {
// for (int index=0;index<TEAM_NAMES.length;index++){
// sTeamIconMap.put(TEAM_NAMES[index],TEAM_ICONS[index]);
// }
// }
//
// public static Map<String,Integer> getTeamIcons() {
// return sTeamIconMap;
// }
//
// public enum NEWSTYPE {
// NEWS("news"),BLOG("blog");
// private String newsType;
// NEWSTYPE(String newsType) {
// this.newsType=newsType;
// }
// public String getNewsType() {
// return newsType;
// }
// }
//
// public enum GETNEWSWAY {
// INIT,UPDATE,LOADMORE;
// }
//
// public enum Result {
// SUCCESS,FAIL,NORMAL;
// }
//
// }
//
// Path: app/src/main/java/com/me/silencedut/nbaplus/model/Teams.java
// public class Teams {
// /**
// * sort : 排名
// * winPercent : 胜率
// * win : 胜
// * lose : 负
// * gap : 胜差
// * team : 球队
// */
//
// private List<TeamsortEntity> teamsort;
//
// public void setTeamsort(List<TeamsortEntity> teamsort) {
// this.teamsort = teamsort;
// }
//
// public List<TeamsortEntity> getTeamsort() {
// return teamsort;
// }
//
// public static class TeamsortEntity {
// private String teamurl;
// private String sort;
// private String winPercent;
// private String win;
// private String lose;
// private String gap;
// private String team;
//
// public String getTeamurl() {
// return teamurl;
// }
//
// public void setTeamurl(String teamurl) {
// this.teamurl = teamurl;
// }
//
// public void setSort(String sort) {
// this.sort = sort;
// }
//
// public void setWinPercent(String winPercent) {
// this.winPercent = winPercent;
// }
//
// public void setWin(String win) {
// this.win = win;
// }
//
// public void setLose(String lose) {
// this.lose = lose;
// }
//
// public void setGap(String gap) {
// this.gap = gap;
// }
//
// public void setTeam(String team) {
// this.team = team;
// }
//
// public String getSort() {
// return sort;
// }
//
// public String getWinPercent() {
// return winPercent;
// }
//
// public String getWin() {
// return win;
// }
//
// public String getLose() {
// return lose;
// }
//
// public String getGap() {
// return gap;
// }
//
// public String getTeam() {
// return team;
// }
// }
// }
| import com.me.silencedut.nbaplus.data.Constant;
import com.me.silencedut.nbaplus.model.Teams; | package com.me.silencedut.nbaplus.event;
/**
* Created by SilenceDut on 2015/12/23.
*/
public class TeamSortEvent extends Event {
private Teams mTeams; | // Path: app/src/main/java/com/me/silencedut/nbaplus/data/Constant.java
// public class Constant {
//
// public static final String APP_FIR_IM_URL="http://fir.im/nbaplus";
// public static final String API_TOKEN_FIR="ff55b0c5cb165ec0b04c473cf77c8995";
//
// public static final String LOADIMAGE = "LOADIMAGE";
// public static final String ACTILEFONTSIZE = "ACTILEFONTSIZE";
//
// public static final String CSS_STYLE ="<style>* {font-size:%spx;line-height:28px;}p {color:%s;}</style>";
//
// public final static String[] TEAM_NAMES={"骑士","猛龙","老鹰","步行者","热火","活塞","公牛","魔术"
// ,"黄蜂","凯尔特人","尼克斯","奇才","雄鹿","篮网","76人","勇士","马刺","雷霆","快船","小牛"
// ,"灰熊","火箭","爵士","太阳","掘金","森林狼","国王","开拓者","鹈鹕","湖人"};
// public final static int[] TEAM_ICONS={R.mipmap.cleveland,R.mipmap.toronto,R.mipmap.atlanta,R.mipmap.indiana
// ,R.mipmap.miami,R.mipmap.detroit,R.mipmap.chicago,R.mipmap.orlando,R.mipmap.charlotte,R.mipmap.boston
// ,R.mipmap.newyork,R.mipmap.washington,R.mipmap.milwaukee,R.mipmap.brooklyn,R.mipmap.phila,R.mipmap.goldenstate
// ,R.mipmap.sanantonio,R.mipmap.okc,R.mipmap.laclippers,R.mipmap.dallas,R.mipmap.memphis,R.mipmap.houston
// ,R.mipmap.utah,R.mipmap.phoenix,R.mipmap.denver,R.mipmap.minnesota,R.mipmap.sacramento,R.mipmap.portland
// ,R.mipmap.neworleans,R.mipmap.lalakers};
//
// private static final Map<String,Integer> sTeamIconMap=new HashMap<>();
//
// static {
// for (int index=0;index<TEAM_NAMES.length;index++){
// sTeamIconMap.put(TEAM_NAMES[index],TEAM_ICONS[index]);
// }
// }
//
// public static Map<String,Integer> getTeamIcons() {
// return sTeamIconMap;
// }
//
// public enum NEWSTYPE {
// NEWS("news"),BLOG("blog");
// private String newsType;
// NEWSTYPE(String newsType) {
// this.newsType=newsType;
// }
// public String getNewsType() {
// return newsType;
// }
// }
//
// public enum GETNEWSWAY {
// INIT,UPDATE,LOADMORE;
// }
//
// public enum Result {
// SUCCESS,FAIL,NORMAL;
// }
//
// }
//
// Path: app/src/main/java/com/me/silencedut/nbaplus/model/Teams.java
// public class Teams {
// /**
// * sort : 排名
// * winPercent : 胜率
// * win : 胜
// * lose : 负
// * gap : 胜差
// * team : 球队
// */
//
// private List<TeamsortEntity> teamsort;
//
// public void setTeamsort(List<TeamsortEntity> teamsort) {
// this.teamsort = teamsort;
// }
//
// public List<TeamsortEntity> getTeamsort() {
// return teamsort;
// }
//
// public static class TeamsortEntity {
// private String teamurl;
// private String sort;
// private String winPercent;
// private String win;
// private String lose;
// private String gap;
// private String team;
//
// public String getTeamurl() {
// return teamurl;
// }
//
// public void setTeamurl(String teamurl) {
// this.teamurl = teamurl;
// }
//
// public void setSort(String sort) {
// this.sort = sort;
// }
//
// public void setWinPercent(String winPercent) {
// this.winPercent = winPercent;
// }
//
// public void setWin(String win) {
// this.win = win;
// }
//
// public void setLose(String lose) {
// this.lose = lose;
// }
//
// public void setGap(String gap) {
// this.gap = gap;
// }
//
// public void setTeam(String team) {
// this.team = team;
// }
//
// public String getSort() {
// return sort;
// }
//
// public String getWinPercent() {
// return winPercent;
// }
//
// public String getWin() {
// return win;
// }
//
// public String getLose() {
// return lose;
// }
//
// public String getGap() {
// return gap;
// }
//
// public String getTeam() {
// return team;
// }
// }
// }
// Path: app/src/main/java/com/me/silencedut/nbaplus/event/TeamSortEvent.java
import com.me.silencedut.nbaplus.data.Constant;
import com.me.silencedut.nbaplus.model.Teams;
package com.me.silencedut.nbaplus.event;
/**
* Created by SilenceDut on 2015/12/23.
*/
public class TeamSortEvent extends Event {
private Teams mTeams; | public TeamSortEvent(Teams teams,Constant.Result result) { |
SilenceDut/NBAPlus | app/src/main/java/com/me/silencedut/nbaplus/ui/activity/BaseActivity.java | // Path: app/src/main/java/com/me/silencedut/nbaplus/app/AppService.java
// public class AppService {
// private static final AppService NBAPLUS_SERVICE=new AppService();
// private static Gson sGson;
// private static EventBus sBus ;
// private static DBHelper sDBHelper;
// private static NbaplusAPI sNbaplusApi;
// private static NewsDetileAPI sNewsDetileApi;
// private static ExecutorService sSingleThreadExecutor;
// private Map<Integer,CompositeSubscription> mCompositeSubByTaskId;
// private Handler mIoHandler;
//
// private AppService(){}
//
// void initService() {
// sBus = EventBus.getDefault();
// sGson=new Gson();
// mCompositeSubByTaskId=new HashMap<Integer,CompositeSubscription>();
// //sSingleThreadExecutor= Executors.newSingleThreadExecutor();
// backGroundInit();
// }
//
// private void backGroundInit() {
// HandlerThread ioThread = new HandlerThread("IoThread");
// ioThread.start();
// mIoHandler= new Handler(ioThread.getLooper());
// mIoHandler.post(new Runnable() {
// @Override
// public void run() {
// sNbaplusApi = NbaplusFactory.getNbaplusInstance();
// sNewsDetileApi = NbaplusFactory.getNewsDetileInstance();
// sDBHelper = DBHelper.getInstance(App.getContext());
// }
// });
// // ThreadExecutor is not necessary currently
//
// // sSingleThreadExecutor.execute(new Runnable() {
// // @Override
// // public void run() {
// // sNbaplus = NbaplusFactory.getNbaplus();
// // sNewsDetileApi = NbaplusFactory.getNewsDetileInstance();
// // sDBHelper = DBHelper.getInstance(App.getContext());
// // }
// // });
//
// }
//
// public void addCompositeSub(int taskId) {
// CompositeSubscription compositeSubscription;
// if(mCompositeSubByTaskId.get(taskId)==null) {
// compositeSubscription = new CompositeSubscription();
// mCompositeSubByTaskId.put(taskId, compositeSubscription);
// }
// }
//
// public void removeCompositeSub(int taskId) {
// CompositeSubscription compositeSubscription;
// if(mCompositeSubByTaskId!=null&& mCompositeSubByTaskId.get(taskId)!=null){
// compositeSubscription= mCompositeSubByTaskId.get(taskId);
// compositeSubscription.unsubscribe();
// mCompositeSubByTaskId.remove(taskId);
// }
// }
//
// private CompositeSubscription getCompositeSubscription(int taskId) {
// CompositeSubscription compositeSubscription ;
// if(mCompositeSubByTaskId.get(taskId)==null) {
// compositeSubscription = new CompositeSubscription();
// mCompositeSubByTaskId.put(taskId, compositeSubscription);
// }else {
// compositeSubscription= mCompositeSubByTaskId.get(taskId);
// }
// return compositeSubscription;
// }
//
//
// public void initNews(int taskId,String type) {
// getCompositeSubscription(taskId).add(RxNews.initNews(type));
// }
//
// public void updateNews(int taskId,String type) {
// getCompositeSubscription(taskId).add(RxNews.updateNews(type));
// }
//
// public void loadMoreNews(int taskId,String type,String newsId) {
// getCompositeSubscription(taskId).add(RxNews.loadMoreNews(type, newsId));
// }
//
// public void getNewsDetail(int taskId,String date,String detailId) {
// getCompositeSubscription(taskId).add(RxNews.getNewsDetail(date, detailId));
// }
//
// public void initPerStat(int taskId,String statKind) {
// getCompositeSubscription(taskId).add(RxStats.initStat(statKind));
// }
//
// public void getPerStat(int taskId,String ...statKinds) {
// getCompositeSubscription(taskId).add(RxStats.getPerStat(statKinds));
// }
//
// public void getTeamSort(int taskId) {
// getCompositeSubscription(taskId).add(RxTeamSort.getTeams());
// }
//
// public void getGames(int taskId,String date) {
// getCompositeSubscription(taskId).add(RxGames.getTeams(date));
// }
//
//
// public static AppService getInstance() {
// return NBAPLUS_SERVICE;
// }
//
// public static EventBus getBus() {
// return sBus;
// }
//
// public static NbaplusAPI getNbaplus() {
// return sNbaplusApi;
// }
//
// public static NewsDetileAPI getNewsDetileApi() {
// return sNewsDetileApi;
// }
//
// public static DBHelper getDBHelper() {
// return sDBHelper;
// }
//
// public static Gson getGson() {
// return sGson;
// }
//
// public static ExecutorService getSingleThreadExecutor(){
// return sSingleThreadExecutor;
// }
//
// }
//
// Path: app/src/main/java/com/me/silencedut/nbaplus/event/Event.java
// public class Event {
// protected Result mEventResult;
//
// public void setEventResult(Result eventResult) {
// this.mEventResult=eventResult;
// }
//
// public Result getEventResult() {
// return mEventResult;
// }
// }
| import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.me.silencedut.nbaplus.app.AppService;
import com.me.silencedut.nbaplus.event.Event;
import butterknife.ButterKnife; | package com.me.silencedut.nbaplus.ui.activity;
/**
* Created by SilenceDut on 2015/11/28.
*/
public abstract class BaseActivity extends AppCompatActivity {
protected abstract void initViews();
protected abstract int getContentViewId();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getContentViewId()); | // Path: app/src/main/java/com/me/silencedut/nbaplus/app/AppService.java
// public class AppService {
// private static final AppService NBAPLUS_SERVICE=new AppService();
// private static Gson sGson;
// private static EventBus sBus ;
// private static DBHelper sDBHelper;
// private static NbaplusAPI sNbaplusApi;
// private static NewsDetileAPI sNewsDetileApi;
// private static ExecutorService sSingleThreadExecutor;
// private Map<Integer,CompositeSubscription> mCompositeSubByTaskId;
// private Handler mIoHandler;
//
// private AppService(){}
//
// void initService() {
// sBus = EventBus.getDefault();
// sGson=new Gson();
// mCompositeSubByTaskId=new HashMap<Integer,CompositeSubscription>();
// //sSingleThreadExecutor= Executors.newSingleThreadExecutor();
// backGroundInit();
// }
//
// private void backGroundInit() {
// HandlerThread ioThread = new HandlerThread("IoThread");
// ioThread.start();
// mIoHandler= new Handler(ioThread.getLooper());
// mIoHandler.post(new Runnable() {
// @Override
// public void run() {
// sNbaplusApi = NbaplusFactory.getNbaplusInstance();
// sNewsDetileApi = NbaplusFactory.getNewsDetileInstance();
// sDBHelper = DBHelper.getInstance(App.getContext());
// }
// });
// // ThreadExecutor is not necessary currently
//
// // sSingleThreadExecutor.execute(new Runnable() {
// // @Override
// // public void run() {
// // sNbaplus = NbaplusFactory.getNbaplus();
// // sNewsDetileApi = NbaplusFactory.getNewsDetileInstance();
// // sDBHelper = DBHelper.getInstance(App.getContext());
// // }
// // });
//
// }
//
// public void addCompositeSub(int taskId) {
// CompositeSubscription compositeSubscription;
// if(mCompositeSubByTaskId.get(taskId)==null) {
// compositeSubscription = new CompositeSubscription();
// mCompositeSubByTaskId.put(taskId, compositeSubscription);
// }
// }
//
// public void removeCompositeSub(int taskId) {
// CompositeSubscription compositeSubscription;
// if(mCompositeSubByTaskId!=null&& mCompositeSubByTaskId.get(taskId)!=null){
// compositeSubscription= mCompositeSubByTaskId.get(taskId);
// compositeSubscription.unsubscribe();
// mCompositeSubByTaskId.remove(taskId);
// }
// }
//
// private CompositeSubscription getCompositeSubscription(int taskId) {
// CompositeSubscription compositeSubscription ;
// if(mCompositeSubByTaskId.get(taskId)==null) {
// compositeSubscription = new CompositeSubscription();
// mCompositeSubByTaskId.put(taskId, compositeSubscription);
// }else {
// compositeSubscription= mCompositeSubByTaskId.get(taskId);
// }
// return compositeSubscription;
// }
//
//
// public void initNews(int taskId,String type) {
// getCompositeSubscription(taskId).add(RxNews.initNews(type));
// }
//
// public void updateNews(int taskId,String type) {
// getCompositeSubscription(taskId).add(RxNews.updateNews(type));
// }
//
// public void loadMoreNews(int taskId,String type,String newsId) {
// getCompositeSubscription(taskId).add(RxNews.loadMoreNews(type, newsId));
// }
//
// public void getNewsDetail(int taskId,String date,String detailId) {
// getCompositeSubscription(taskId).add(RxNews.getNewsDetail(date, detailId));
// }
//
// public void initPerStat(int taskId,String statKind) {
// getCompositeSubscription(taskId).add(RxStats.initStat(statKind));
// }
//
// public void getPerStat(int taskId,String ...statKinds) {
// getCompositeSubscription(taskId).add(RxStats.getPerStat(statKinds));
// }
//
// public void getTeamSort(int taskId) {
// getCompositeSubscription(taskId).add(RxTeamSort.getTeams());
// }
//
// public void getGames(int taskId,String date) {
// getCompositeSubscription(taskId).add(RxGames.getTeams(date));
// }
//
//
// public static AppService getInstance() {
// return NBAPLUS_SERVICE;
// }
//
// public static EventBus getBus() {
// return sBus;
// }
//
// public static NbaplusAPI getNbaplus() {
// return sNbaplusApi;
// }
//
// public static NewsDetileAPI getNewsDetileApi() {
// return sNewsDetileApi;
// }
//
// public static DBHelper getDBHelper() {
// return sDBHelper;
// }
//
// public static Gson getGson() {
// return sGson;
// }
//
// public static ExecutorService getSingleThreadExecutor(){
// return sSingleThreadExecutor;
// }
//
// }
//
// Path: app/src/main/java/com/me/silencedut/nbaplus/event/Event.java
// public class Event {
// protected Result mEventResult;
//
// public void setEventResult(Result eventResult) {
// this.mEventResult=eventResult;
// }
//
// public Result getEventResult() {
// return mEventResult;
// }
// }
// Path: app/src/main/java/com/me/silencedut/nbaplus/ui/activity/BaseActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.me.silencedut.nbaplus.app.AppService;
import com.me.silencedut.nbaplus.event.Event;
import butterknife.ButterKnife;
package com.me.silencedut.nbaplus.ui.activity;
/**
* Created by SilenceDut on 2015/11/28.
*/
public abstract class BaseActivity extends AppCompatActivity {
protected abstract void initViews();
protected abstract int getContentViewId();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getContentViewId()); | AppService.getInstance().addCompositeSub(getTaskId()); |
SilenceDut/NBAPlus | app/src/main/java/com/me/silencedut/nbaplus/ui/fragment/base/BaseFragment.java | // Path: app/src/main/java/com/me/silencedut/nbaplus/app/AppService.java
// public class AppService {
// private static final AppService NBAPLUS_SERVICE=new AppService();
// private static Gson sGson;
// private static EventBus sBus ;
// private static DBHelper sDBHelper;
// private static NbaplusAPI sNbaplusApi;
// private static NewsDetileAPI sNewsDetileApi;
// private static ExecutorService sSingleThreadExecutor;
// private Map<Integer,CompositeSubscription> mCompositeSubByTaskId;
// private Handler mIoHandler;
//
// private AppService(){}
//
// void initService() {
// sBus = EventBus.getDefault();
// sGson=new Gson();
// mCompositeSubByTaskId=new HashMap<Integer,CompositeSubscription>();
// //sSingleThreadExecutor= Executors.newSingleThreadExecutor();
// backGroundInit();
// }
//
// private void backGroundInit() {
// HandlerThread ioThread = new HandlerThread("IoThread");
// ioThread.start();
// mIoHandler= new Handler(ioThread.getLooper());
// mIoHandler.post(new Runnable() {
// @Override
// public void run() {
// sNbaplusApi = NbaplusFactory.getNbaplusInstance();
// sNewsDetileApi = NbaplusFactory.getNewsDetileInstance();
// sDBHelper = DBHelper.getInstance(App.getContext());
// }
// });
// // ThreadExecutor is not necessary currently
//
// // sSingleThreadExecutor.execute(new Runnable() {
// // @Override
// // public void run() {
// // sNbaplus = NbaplusFactory.getNbaplus();
// // sNewsDetileApi = NbaplusFactory.getNewsDetileInstance();
// // sDBHelper = DBHelper.getInstance(App.getContext());
// // }
// // });
//
// }
//
// public void addCompositeSub(int taskId) {
// CompositeSubscription compositeSubscription;
// if(mCompositeSubByTaskId.get(taskId)==null) {
// compositeSubscription = new CompositeSubscription();
// mCompositeSubByTaskId.put(taskId, compositeSubscription);
// }
// }
//
// public void removeCompositeSub(int taskId) {
// CompositeSubscription compositeSubscription;
// if(mCompositeSubByTaskId!=null&& mCompositeSubByTaskId.get(taskId)!=null){
// compositeSubscription= mCompositeSubByTaskId.get(taskId);
// compositeSubscription.unsubscribe();
// mCompositeSubByTaskId.remove(taskId);
// }
// }
//
// private CompositeSubscription getCompositeSubscription(int taskId) {
// CompositeSubscription compositeSubscription ;
// if(mCompositeSubByTaskId.get(taskId)==null) {
// compositeSubscription = new CompositeSubscription();
// mCompositeSubByTaskId.put(taskId, compositeSubscription);
// }else {
// compositeSubscription= mCompositeSubByTaskId.get(taskId);
// }
// return compositeSubscription;
// }
//
//
// public void initNews(int taskId,String type) {
// getCompositeSubscription(taskId).add(RxNews.initNews(type));
// }
//
// public void updateNews(int taskId,String type) {
// getCompositeSubscription(taskId).add(RxNews.updateNews(type));
// }
//
// public void loadMoreNews(int taskId,String type,String newsId) {
// getCompositeSubscription(taskId).add(RxNews.loadMoreNews(type, newsId));
// }
//
// public void getNewsDetail(int taskId,String date,String detailId) {
// getCompositeSubscription(taskId).add(RxNews.getNewsDetail(date, detailId));
// }
//
// public void initPerStat(int taskId,String statKind) {
// getCompositeSubscription(taskId).add(RxStats.initStat(statKind));
// }
//
// public void getPerStat(int taskId,String ...statKinds) {
// getCompositeSubscription(taskId).add(RxStats.getPerStat(statKinds));
// }
//
// public void getTeamSort(int taskId) {
// getCompositeSubscription(taskId).add(RxTeamSort.getTeams());
// }
//
// public void getGames(int taskId,String date) {
// getCompositeSubscription(taskId).add(RxGames.getTeams(date));
// }
//
//
// public static AppService getInstance() {
// return NBAPLUS_SERVICE;
// }
//
// public static EventBus getBus() {
// return sBus;
// }
//
// public static NbaplusAPI getNbaplus() {
// return sNbaplusApi;
// }
//
// public static NewsDetileAPI getNewsDetileApi() {
// return sNewsDetileApi;
// }
//
// public static DBHelper getDBHelper() {
// return sDBHelper;
// }
//
// public static Gson getGson() {
// return sGson;
// }
//
// public static ExecutorService getSingleThreadExecutor(){
// return sSingleThreadExecutor;
// }
//
// }
| import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.me.silencedut.nbaplus.app.AppService;
import butterknife.ButterKnife; | package com.me.silencedut.nbaplus.ui.fragment.base;
/**
* Created by SilenceDut on 2015/11/28.
*/
public abstract class BaseFragment extends Fragment {
private int mTaskId;
protected View rootView;
protected abstract void initViews() ;
protected abstract int getContentViewId();
protected int getTaskId (){
return mTaskId;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTaskId=getActivity().getTaskId(); | // Path: app/src/main/java/com/me/silencedut/nbaplus/app/AppService.java
// public class AppService {
// private static final AppService NBAPLUS_SERVICE=new AppService();
// private static Gson sGson;
// private static EventBus sBus ;
// private static DBHelper sDBHelper;
// private static NbaplusAPI sNbaplusApi;
// private static NewsDetileAPI sNewsDetileApi;
// private static ExecutorService sSingleThreadExecutor;
// private Map<Integer,CompositeSubscription> mCompositeSubByTaskId;
// private Handler mIoHandler;
//
// private AppService(){}
//
// void initService() {
// sBus = EventBus.getDefault();
// sGson=new Gson();
// mCompositeSubByTaskId=new HashMap<Integer,CompositeSubscription>();
// //sSingleThreadExecutor= Executors.newSingleThreadExecutor();
// backGroundInit();
// }
//
// private void backGroundInit() {
// HandlerThread ioThread = new HandlerThread("IoThread");
// ioThread.start();
// mIoHandler= new Handler(ioThread.getLooper());
// mIoHandler.post(new Runnable() {
// @Override
// public void run() {
// sNbaplusApi = NbaplusFactory.getNbaplusInstance();
// sNewsDetileApi = NbaplusFactory.getNewsDetileInstance();
// sDBHelper = DBHelper.getInstance(App.getContext());
// }
// });
// // ThreadExecutor is not necessary currently
//
// // sSingleThreadExecutor.execute(new Runnable() {
// // @Override
// // public void run() {
// // sNbaplus = NbaplusFactory.getNbaplus();
// // sNewsDetileApi = NbaplusFactory.getNewsDetileInstance();
// // sDBHelper = DBHelper.getInstance(App.getContext());
// // }
// // });
//
// }
//
// public void addCompositeSub(int taskId) {
// CompositeSubscription compositeSubscription;
// if(mCompositeSubByTaskId.get(taskId)==null) {
// compositeSubscription = new CompositeSubscription();
// mCompositeSubByTaskId.put(taskId, compositeSubscription);
// }
// }
//
// public void removeCompositeSub(int taskId) {
// CompositeSubscription compositeSubscription;
// if(mCompositeSubByTaskId!=null&& mCompositeSubByTaskId.get(taskId)!=null){
// compositeSubscription= mCompositeSubByTaskId.get(taskId);
// compositeSubscription.unsubscribe();
// mCompositeSubByTaskId.remove(taskId);
// }
// }
//
// private CompositeSubscription getCompositeSubscription(int taskId) {
// CompositeSubscription compositeSubscription ;
// if(mCompositeSubByTaskId.get(taskId)==null) {
// compositeSubscription = new CompositeSubscription();
// mCompositeSubByTaskId.put(taskId, compositeSubscription);
// }else {
// compositeSubscription= mCompositeSubByTaskId.get(taskId);
// }
// return compositeSubscription;
// }
//
//
// public void initNews(int taskId,String type) {
// getCompositeSubscription(taskId).add(RxNews.initNews(type));
// }
//
// public void updateNews(int taskId,String type) {
// getCompositeSubscription(taskId).add(RxNews.updateNews(type));
// }
//
// public void loadMoreNews(int taskId,String type,String newsId) {
// getCompositeSubscription(taskId).add(RxNews.loadMoreNews(type, newsId));
// }
//
// public void getNewsDetail(int taskId,String date,String detailId) {
// getCompositeSubscription(taskId).add(RxNews.getNewsDetail(date, detailId));
// }
//
// public void initPerStat(int taskId,String statKind) {
// getCompositeSubscription(taskId).add(RxStats.initStat(statKind));
// }
//
// public void getPerStat(int taskId,String ...statKinds) {
// getCompositeSubscription(taskId).add(RxStats.getPerStat(statKinds));
// }
//
// public void getTeamSort(int taskId) {
// getCompositeSubscription(taskId).add(RxTeamSort.getTeams());
// }
//
// public void getGames(int taskId,String date) {
// getCompositeSubscription(taskId).add(RxGames.getTeams(date));
// }
//
//
// public static AppService getInstance() {
// return NBAPLUS_SERVICE;
// }
//
// public static EventBus getBus() {
// return sBus;
// }
//
// public static NbaplusAPI getNbaplus() {
// return sNbaplusApi;
// }
//
// public static NewsDetileAPI getNewsDetileApi() {
// return sNewsDetileApi;
// }
//
// public static DBHelper getDBHelper() {
// return sDBHelper;
// }
//
// public static Gson getGson() {
// return sGson;
// }
//
// public static ExecutorService getSingleThreadExecutor(){
// return sSingleThreadExecutor;
// }
//
// }
// Path: app/src/main/java/com/me/silencedut/nbaplus/ui/fragment/base/BaseFragment.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.me.silencedut.nbaplus.app.AppService;
import butterknife.ButterKnife;
package com.me.silencedut.nbaplus.ui.fragment.base;
/**
* Created by SilenceDut on 2015/11/28.
*/
public abstract class BaseFragment extends Fragment {
private int mTaskId;
protected View rootView;
protected abstract void initViews() ;
protected abstract int getContentViewId();
protected int getTaskId (){
return mTaskId;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTaskId=getActivity().getTaskId(); | AppService.getInstance().getBus().register(this); |
adamcin/httpsig-java | ssh-jce/src/main/java/net/adamcin/httpsig/ssh/jce/UserKeysFingerprintKeyId.java | // Path: api/src/main/java/net/adamcin/httpsig/api/Key.java
// public interface Key {
//
// /**
// * @return the {@link Key}'s self-identification. This may end up not being unique within a keychain.
// */
// String getId();
//
// /**
// * @return the {@link Set} of Signature {@link Algorithm}s supported by this key.
// */
// Set<Algorithm> getAlgorithms();
//
// /**
// * @return true if this {@link Key} can be used for verification
// */
// boolean canVerify();
//
// /**
// * Verifies the {@code signatureBytes} against the {@code challengeHash} using an underlying public key
// * @param algorithm the selected Signature {@link Algorithm}
// * @param contentBytes the result of {@link RequestContent#getBytesToSign(java.util.List, java.nio.charset.Charset)}
// * @param signatureBytes the result of {@link net.adamcin.httpsig.api.Authorization#getSignatureBytes()}
// * @return true if signature is valid
// */
// boolean verify(Algorithm algorithm, byte[] contentBytes, byte[] signatureBytes);
//
// /**
// * @return true if this {@link Key} can be used for signing
// */
// boolean canSign();
//
// /**
// * Signs the {@code challengeHash} using the specified signature {@link Algorithm}
// * @param algorithm the selected Signature {@link Algorithm}
// * @param contentBytes the result of {@link RequestContent#getBytesToSign(java.util.List, java.nio.charset.Charset)}
// * @return byte array containing the challengeHash signature or null if a signature could not be generated.
// */
// byte[] sign(Algorithm algorithm, byte[] contentBytes);
// }
//
// Path: api/src/main/java/net/adamcin/httpsig/api/KeyId.java
// public interface KeyId {
//
// /**
// * @param key the {@link Key} to identify
// * @return the generated keyId or null if the {@link Key} cannot be identified
// */
// String getId(Key key);
// }
| import net.adamcin.httpsig.api.Key;
import net.adamcin.httpsig.api.KeyId; | /*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* For more information, please refer to <http://unlicense.org/>
*/
package net.adamcin.httpsig.ssh.jce;
/**
* Implementation of {@link KeyId} following the Joyent API convention of /$username/keys/$fingerprint
* @since 1.0.2
*/
public final class UserKeysFingerprintKeyId implements KeyId {
private final String username;
public UserKeysFingerprintKeyId(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
| // Path: api/src/main/java/net/adamcin/httpsig/api/Key.java
// public interface Key {
//
// /**
// * @return the {@link Key}'s self-identification. This may end up not being unique within a keychain.
// */
// String getId();
//
// /**
// * @return the {@link Set} of Signature {@link Algorithm}s supported by this key.
// */
// Set<Algorithm> getAlgorithms();
//
// /**
// * @return true if this {@link Key} can be used for verification
// */
// boolean canVerify();
//
// /**
// * Verifies the {@code signatureBytes} against the {@code challengeHash} using an underlying public key
// * @param algorithm the selected Signature {@link Algorithm}
// * @param contentBytes the result of {@link RequestContent#getBytesToSign(java.util.List, java.nio.charset.Charset)}
// * @param signatureBytes the result of {@link net.adamcin.httpsig.api.Authorization#getSignatureBytes()}
// * @return true if signature is valid
// */
// boolean verify(Algorithm algorithm, byte[] contentBytes, byte[] signatureBytes);
//
// /**
// * @return true if this {@link Key} can be used for signing
// */
// boolean canSign();
//
// /**
// * Signs the {@code challengeHash} using the specified signature {@link Algorithm}
// * @param algorithm the selected Signature {@link Algorithm}
// * @param contentBytes the result of {@link RequestContent#getBytesToSign(java.util.List, java.nio.charset.Charset)}
// * @return byte array containing the challengeHash signature or null if a signature could not be generated.
// */
// byte[] sign(Algorithm algorithm, byte[] contentBytes);
// }
//
// Path: api/src/main/java/net/adamcin/httpsig/api/KeyId.java
// public interface KeyId {
//
// /**
// * @param key the {@link Key} to identify
// * @return the generated keyId or null if the {@link Key} cannot be identified
// */
// String getId(Key key);
// }
// Path: ssh-jce/src/main/java/net/adamcin/httpsig/ssh/jce/UserKeysFingerprintKeyId.java
import net.adamcin.httpsig.api.Key;
import net.adamcin.httpsig.api.KeyId;
/*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* For more information, please refer to <http://unlicense.org/>
*/
package net.adamcin.httpsig.ssh.jce;
/**
* Implementation of {@link KeyId} following the Joyent API convention of /$username/keys/$fingerprint
* @since 1.0.2
*/
public final class UserKeysFingerprintKeyId implements KeyId {
private final String username;
public UserKeysFingerprintKeyId(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
| public String getId(Key key) { |
adamcin/httpsig-java | ssh-jce/src/main/java/net/adamcin/httpsig/ssh/jce/SSHKey.java | // Path: api/src/main/java/net/adamcin/httpsig/api/Algorithm.java
// public enum Algorithm {
// RSA_SHA1("rsa-sha1"),
// RSA_SHA256("rsa-sha256"),
// RSA_SHA512("rsa-sha512"),
// DSA_SHA1("dsa-sha1"),
// HMAC_SHA1("hmac-sha1"),
// HMAC_SHA256("hmac-sha256"),
// HMAC_SHA512("hmac-sha512"),
// SSH_RSA("ssh-rsa"),
// SSH_DSS("ssh-dss");
//
// private final String name;
//
// private Algorithm(String name) {
// this.name = name;
// }
//
// public String getName() {
// return name;
// }
//
// public static Algorithm forName(String name) {
// for (Algorithm algorithm : Algorithm.values()) {
// if (algorithm.getName().equalsIgnoreCase(name)) {
// return algorithm;
// }
// }
//
// return null;
// }
// }
| import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import net.adamcin.httpsig.api.Algorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | }
if (keyPair.getPublic() == null) {
throw new IllegalArgumentException("publicKey must not be null");
}
this.keyPair = keyPair;
this.fingerprint = keyFormat.getFingerprint(keyPair.getPublic());
}
public SSHKey(KeyFormat keyFormat, PublicKey publicKey,
PrivateKey privateKey) {
this(keyFormat, new KeyPair(publicKey, privateKey));
}
/**
* {@inheritDoc}
*/
public String getId() {
return this.fingerprint;
}
/**
* {@inheritDoc}
*/
public String getFingerprint() {
return this.fingerprint;
}
/**
* {@inheritDoc}
*/ | // Path: api/src/main/java/net/adamcin/httpsig/api/Algorithm.java
// public enum Algorithm {
// RSA_SHA1("rsa-sha1"),
// RSA_SHA256("rsa-sha256"),
// RSA_SHA512("rsa-sha512"),
// DSA_SHA1("dsa-sha1"),
// HMAC_SHA1("hmac-sha1"),
// HMAC_SHA256("hmac-sha256"),
// HMAC_SHA512("hmac-sha512"),
// SSH_RSA("ssh-rsa"),
// SSH_DSS("ssh-dss");
//
// private final String name;
//
// private Algorithm(String name) {
// this.name = name;
// }
//
// public String getName() {
// return name;
// }
//
// public static Algorithm forName(String name) {
// for (Algorithm algorithm : Algorithm.values()) {
// if (algorithm.getName().equalsIgnoreCase(name)) {
// return algorithm;
// }
// }
//
// return null;
// }
// }
// Path: ssh-jce/src/main/java/net/adamcin/httpsig/ssh/jce/SSHKey.java
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import net.adamcin.httpsig.api.Algorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
}
if (keyPair.getPublic() == null) {
throw new IllegalArgumentException("publicKey must not be null");
}
this.keyPair = keyPair;
this.fingerprint = keyFormat.getFingerprint(keyPair.getPublic());
}
public SSHKey(KeyFormat keyFormat, PublicKey publicKey,
PrivateKey privateKey) {
this(keyFormat, new KeyPair(publicKey, privateKey));
}
/**
* {@inheritDoc}
*/
public String getId() {
return this.fingerprint;
}
/**
* {@inheritDoc}
*/
public String getFingerprint() {
return this.fingerprint;
}
/**
* {@inheritDoc}
*/ | public Set<Algorithm> getAlgorithms() { |
adamcin/httpsig-java | hmac/src/main/java/net/adamcin/httpsig/hmac/HmacKey.java | // Path: api/src/main/java/net/adamcin/httpsig/api/Algorithm.java
// public enum Algorithm {
// RSA_SHA1("rsa-sha1"),
// RSA_SHA256("rsa-sha256"),
// RSA_SHA512("rsa-sha512"),
// DSA_SHA1("dsa-sha1"),
// HMAC_SHA1("hmac-sha1"),
// HMAC_SHA256("hmac-sha256"),
// HMAC_SHA512("hmac-sha512"),
// SSH_RSA("ssh-rsa"),
// SSH_DSS("ssh-dss");
//
// private final String name;
//
// private Algorithm(String name) {
// this.name = name;
// }
//
// public String getName() {
// return name;
// }
//
// public static Algorithm forName(String name) {
// for (Algorithm algorithm : Algorithm.values()) {
// if (algorithm.getName().equalsIgnoreCase(name)) {
// return algorithm;
// }
// }
//
// return null;
// }
// }
//
// Path: api/src/main/java/net/adamcin/httpsig/api/Key.java
// public interface Key {
//
// /**
// * @return the {@link Key}'s self-identification. This may end up not being unique within a keychain.
// */
// String getId();
//
// /**
// * @return the {@link Set} of Signature {@link Algorithm}s supported by this key.
// */
// Set<Algorithm> getAlgorithms();
//
// /**
// * @return true if this {@link Key} can be used for verification
// */
// boolean canVerify();
//
// /**
// * Verifies the {@code signatureBytes} against the {@code challengeHash} using an underlying public key
// * @param algorithm the selected Signature {@link Algorithm}
// * @param contentBytes the result of {@link RequestContent#getBytesToSign(java.util.List, java.nio.charset.Charset)}
// * @param signatureBytes the result of {@link net.adamcin.httpsig.api.Authorization#getSignatureBytes()}
// * @return true if signature is valid
// */
// boolean verify(Algorithm algorithm, byte[] contentBytes, byte[] signatureBytes);
//
// /**
// * @return true if this {@link Key} can be used for signing
// */
// boolean canSign();
//
// /**
// * Signs the {@code challengeHash} using the specified signature {@link Algorithm}
// * @param algorithm the selected Signature {@link Algorithm}
// * @param contentBytes the result of {@link RequestContent#getBytesToSign(java.util.List, java.nio.charset.Charset)}
// * @return byte array containing the challengeHash signature or null if a signature could not be generated.
// */
// byte[] sign(Algorithm algorithm, byte[] contentBytes);
// }
| import org.slf4j.LoggerFactory;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import net.adamcin.httpsig.api.Algorithm;
import net.adamcin.httpsig.api.Key;
import org.slf4j.Logger; | /*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* For more information, please refer to <http://unlicense.org/>
*/
package net.adamcin.httpsig.hmac;
public class HmacKey implements Key {
private final String keyId;
private final String secret;
private static final byte[] EMPTY_BYTES = new byte[0];
private static final Logger LOGGER = LoggerFactory.getLogger(HmacKey.class);
/**
* Instantiates a new HMAC key with an identifier and a secret used to sign
* @param keyId The keys identifier
* @param secret The secret used to sign
*/
public HmacKey(String keyId, String secret) {
if (keyId == null) {
throw new NullPointerException("keyId must not be null");
}
if (secret == null) {
throw new NullPointerException("secret must not be null");
}
this.keyId = keyId;
this.secret = secret;
}
/**
* @return the {@link net.adamcin.httpsig.api.Key}'s self-identification. This may end up not being unique within a keychain.
*/
public String getId() {
return keyId;
}
/**
* @return the {@link java.util.Set} of Signature {@link net.adamcin.httpsig.api.Algorithm}s supported by this key.
*/ | // Path: api/src/main/java/net/adamcin/httpsig/api/Algorithm.java
// public enum Algorithm {
// RSA_SHA1("rsa-sha1"),
// RSA_SHA256("rsa-sha256"),
// RSA_SHA512("rsa-sha512"),
// DSA_SHA1("dsa-sha1"),
// HMAC_SHA1("hmac-sha1"),
// HMAC_SHA256("hmac-sha256"),
// HMAC_SHA512("hmac-sha512"),
// SSH_RSA("ssh-rsa"),
// SSH_DSS("ssh-dss");
//
// private final String name;
//
// private Algorithm(String name) {
// this.name = name;
// }
//
// public String getName() {
// return name;
// }
//
// public static Algorithm forName(String name) {
// for (Algorithm algorithm : Algorithm.values()) {
// if (algorithm.getName().equalsIgnoreCase(name)) {
// return algorithm;
// }
// }
//
// return null;
// }
// }
//
// Path: api/src/main/java/net/adamcin/httpsig/api/Key.java
// public interface Key {
//
// /**
// * @return the {@link Key}'s self-identification. This may end up not being unique within a keychain.
// */
// String getId();
//
// /**
// * @return the {@link Set} of Signature {@link Algorithm}s supported by this key.
// */
// Set<Algorithm> getAlgorithms();
//
// /**
// * @return true if this {@link Key} can be used for verification
// */
// boolean canVerify();
//
// /**
// * Verifies the {@code signatureBytes} against the {@code challengeHash} using an underlying public key
// * @param algorithm the selected Signature {@link Algorithm}
// * @param contentBytes the result of {@link RequestContent#getBytesToSign(java.util.List, java.nio.charset.Charset)}
// * @param signatureBytes the result of {@link net.adamcin.httpsig.api.Authorization#getSignatureBytes()}
// * @return true if signature is valid
// */
// boolean verify(Algorithm algorithm, byte[] contentBytes, byte[] signatureBytes);
//
// /**
// * @return true if this {@link Key} can be used for signing
// */
// boolean canSign();
//
// /**
// * Signs the {@code challengeHash} using the specified signature {@link Algorithm}
// * @param algorithm the selected Signature {@link Algorithm}
// * @param contentBytes the result of {@link RequestContent#getBytesToSign(java.util.List, java.nio.charset.Charset)}
// * @return byte array containing the challengeHash signature or null if a signature could not be generated.
// */
// byte[] sign(Algorithm algorithm, byte[] contentBytes);
// }
// Path: hmac/src/main/java/net/adamcin/httpsig/hmac/HmacKey.java
import org.slf4j.LoggerFactory;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import net.adamcin.httpsig.api.Algorithm;
import net.adamcin.httpsig.api.Key;
import org.slf4j.Logger;
/*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* For more information, please refer to <http://unlicense.org/>
*/
package net.adamcin.httpsig.hmac;
public class HmacKey implements Key {
private final String keyId;
private final String secret;
private static final byte[] EMPTY_BYTES = new byte[0];
private static final Logger LOGGER = LoggerFactory.getLogger(HmacKey.class);
/**
* Instantiates a new HMAC key with an identifier and a secret used to sign
* @param keyId The keys identifier
* @param secret The secret used to sign
*/
public HmacKey(String keyId, String secret) {
if (keyId == null) {
throw new NullPointerException("keyId must not be null");
}
if (secret == null) {
throw new NullPointerException("secret must not be null");
}
this.keyId = keyId;
this.secret = secret;
}
/**
* @return the {@link net.adamcin.httpsig.api.Key}'s self-identification. This may end up not being unique within a keychain.
*/
public String getId() {
return keyId;
}
/**
* @return the {@link java.util.Set} of Signature {@link net.adamcin.httpsig.api.Algorithm}s supported by this key.
*/ | public Set<Algorithm> getAlgorithms() { |
keenlabs/KeenClient-Java | query/src/main/java/io/keen/client/java/SavedQueryPut.java | // Path: core/src/main/java/io/keen/client/java/http/HttpMethods.java
// public final class HttpMethods {
// private HttpMethods() {}
//
// public final static String GET = "GET";
// public final static String POST = "POST";
// public final static String PUT = "PUT";
// public final static String DELETE = "DELETE";
// }
| import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import io.keen.client.java.http.HttpMethods; | package io.keen.client.java;
/**
* Represents PUT requests performed against the Saved/Cached Queries API.
*
* @author masojus
*/
class SavedQueryPut extends SavedQueryRequest {
private final KeenQueryRequest query;
private final int refreshRate;
private final Map<String, Object> miscProperties;
SavedQueryPut(String queryName,
String displayName,
KeenQueryRequest query,
int refreshRate,
Map<String, ?> miscProperties) { | // Path: core/src/main/java/io/keen/client/java/http/HttpMethods.java
// public final class HttpMethods {
// private HttpMethods() {}
//
// public final static String GET = "GET";
// public final static String POST = "POST";
// public final static String PUT = "PUT";
// public final static String DELETE = "DELETE";
// }
// Path: query/src/main/java/io/keen/client/java/SavedQueryPut.java
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import io.keen.client.java.http.HttpMethods;
package io.keen.client.java;
/**
* Represents PUT requests performed against the Saved/Cached Queries API.
*
* @author masojus
*/
class SavedQueryPut extends SavedQueryRequest {
private final KeenQueryRequest query;
private final int refreshRate;
private final Map<String, Object> miscProperties;
SavedQueryPut(String queryName,
String displayName,
KeenQueryRequest query,
int refreshRate,
Map<String, ?> miscProperties) { | super(HttpMethods.PUT, true /* needsMasterKey */, queryName, displayName); |
keenlabs/KeenClient-Java | query/src/main/java/io/keen/client/java/CachedDatasets.java | // Path: query/src/main/java/io/keen/client/java/result/IntervalResultValue.java
// public class IntervalResultValue {
// private final AbsoluteTimeframe timeframe;
// private final QueryResult result;
//
// public IntervalResultValue(AbsoluteTimeframe timeframe, QueryResult result) {
// this.timeframe = timeframe;
// this.result = result;
// }
//
// public AbsoluteTimeframe getTimeframe() {
// return timeframe;
// }
//
// public QueryResult getResult() {
// return result;
// }
//
// @Override
// public String toString() {
// return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
//
// @Override
// public boolean equals(Object obj) {
// return EqualsBuilder.reflectionEquals(this, obj);
// }
//
// @Override
// public int hashCode() {
// return HashCodeBuilder.reflectionHashCode(this);
// }
// }
| import io.keen.client.java.result.IntervalResultValue;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map; | package io.keen.client.java;
/**
* Client interface for Cached Datasets.
* <p>
* Cached Datasets are a way to pre-compute data for hundreds or thousands of entities at once. They are a great way to
* improve your query efficiency as well as minimize your compute costs.
*
* @see <a href="https://keen.io/docs/compute/cached-datasets/">Cached Datasets</a>
* @see <a href="https://keen.io/docs/api/#cached-datasets/">Cached Dataset API Reference</a>
*/
public interface CachedDatasets {
/**
* Creates a Cached Dataset. Updates are not currently supported.
*
* @param datasetName The unique name for your new DS. It can only contain alphanumeric characters, hypens and underscores.
* @param displayName The human-readable string name for your Cached Dataset
* @param query The query definition you want Keen to optimize for your application.
* @param indexBy The event property names containing an identifier, such as user_id or store.id, that will be used to index and retrieve query results.
* @return The definition of created Dataset.
* @throws IOException If there was an error communicating with the server.
*/
DatasetDefinition create(String datasetName, String displayName, DatasetQuery query, Collection<String> indexBy) throws IOException;
/**
* Gets a Cached Dataset definition.
*
* @param datasetName The name of requested Dataset.
* @return The definition of specified Dataset.
* @throws IOException If there was an error communicating with the server.
*/
DatasetDefinition getDefinition(String datasetName) throws IOException;
/**
* Gets query results from a Cached Dataset.
*
* @param datasetDefinition A definition of Cached Dataset. Required as a definition determines the response format.
* @param indexByValues A map of [index identifier : index value] for all index properties defined in a Dataset definition.
* @param timeframe Limits retrieval of results to a specific portion of the Cached Dataset.
* @return Query results from a Cached Dataset.
* @throws IOException If there was an error communicating with the server.
* @see CachedDatasets#getDefinition(String)
*/ | // Path: query/src/main/java/io/keen/client/java/result/IntervalResultValue.java
// public class IntervalResultValue {
// private final AbsoluteTimeframe timeframe;
// private final QueryResult result;
//
// public IntervalResultValue(AbsoluteTimeframe timeframe, QueryResult result) {
// this.timeframe = timeframe;
// this.result = result;
// }
//
// public AbsoluteTimeframe getTimeframe() {
// return timeframe;
// }
//
// public QueryResult getResult() {
// return result;
// }
//
// @Override
// public String toString() {
// return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
//
// @Override
// public boolean equals(Object obj) {
// return EqualsBuilder.reflectionEquals(this, obj);
// }
//
// @Override
// public int hashCode() {
// return HashCodeBuilder.reflectionHashCode(this);
// }
// }
// Path: query/src/main/java/io/keen/client/java/CachedDatasets.java
import io.keen.client.java.result.IntervalResultValue;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
package io.keen.client.java;
/**
* Client interface for Cached Datasets.
* <p>
* Cached Datasets are a way to pre-compute data for hundreds or thousands of entities at once. They are a great way to
* improve your query efficiency as well as minimize your compute costs.
*
* @see <a href="https://keen.io/docs/compute/cached-datasets/">Cached Datasets</a>
* @see <a href="https://keen.io/docs/api/#cached-datasets/">Cached Dataset API Reference</a>
*/
public interface CachedDatasets {
/**
* Creates a Cached Dataset. Updates are not currently supported.
*
* @param datasetName The unique name for your new DS. It can only contain alphanumeric characters, hypens and underscores.
* @param displayName The human-readable string name for your Cached Dataset
* @param query The query definition you want Keen to optimize for your application.
* @param indexBy The event property names containing an identifier, such as user_id or store.id, that will be used to index and retrieve query results.
* @return The definition of created Dataset.
* @throws IOException If there was an error communicating with the server.
*/
DatasetDefinition create(String datasetName, String displayName, DatasetQuery query, Collection<String> indexBy) throws IOException;
/**
* Gets a Cached Dataset definition.
*
* @param datasetName The name of requested Dataset.
* @return The definition of specified Dataset.
* @throws IOException If there was an error communicating with the server.
*/
DatasetDefinition getDefinition(String datasetName) throws IOException;
/**
* Gets query results from a Cached Dataset.
*
* @param datasetDefinition A definition of Cached Dataset. Required as a definition determines the response format.
* @param indexByValues A map of [index identifier : index value] for all index properties defined in a Dataset definition.
* @param timeframe Limits retrieval of results to a specific portion of the Cached Dataset.
* @return Query results from a Cached Dataset.
* @throws IOException If there was an error communicating with the server.
* @see CachedDatasets#getDefinition(String)
*/ | List<IntervalResultValue> getResults(DatasetDefinition datasetDefinition, Map<String, ?> indexByValues, Timeframe timeframe) throws IOException; |
keenlabs/KeenClient-Java | query/src/main/java/io/keen/client/java/PersistentAnalysis.java | // Path: core/src/main/java/io/keen/client/java/http/HttpMethods.java
// public final class HttpMethods {
// private HttpMethods() {}
//
// public final static String GET = "GET";
// public final static String POST = "POST";
// public final static String PUT = "PUT";
// public final static String DELETE = "DELETE";
// }
| import io.keen.client.java.http.HttpMethods; | package io.keen.client.java;
/**
* Base class that represents requests to the endpoints for managing persistent analyses, such as
* <a href="https://keen.io/docs/api/#saved-queries">Saved/Cached Queries</a> and
* <a href="https://keen.io/docs/api/#cached-datasets">Cached Datasets</a>.
*
* Should be an interface, but KeenQueryRequest is meant to be a package-private interface defining
* package-private functionality, so until the next major version when we fix up public interface
* surface area, it's a package-private abstract class.
*
* @author masojus
*/
abstract class PersistentAnalysis extends KeenQueryRequest {
// This regex does not match strings like "árbol π" since the API only accepts ASCII in the URL.
private static final String RESOURCE_NAME_REGEX = "^[\\w-]*$";
private final String httpMethod;
private final boolean needsMasterKey;
// The name of the specific persistent analysis we're working on, if any--e.g. "max_signups".
private final String resourceName;
private final String displayName;
PersistentAnalysis(String httpMethod,
boolean needsMasterKey,
String resourceName,
String displayName) {
// HTTP Method is provided by our code, so let's trust it's valid.
this.httpMethod = httpMethod;
this.needsMasterKey = needsMasterKey;
// The resource name can only be omitted for a GET request. | // Path: core/src/main/java/io/keen/client/java/http/HttpMethods.java
// public final class HttpMethods {
// private HttpMethods() {}
//
// public final static String GET = "GET";
// public final static String POST = "POST";
// public final static String PUT = "PUT";
// public final static String DELETE = "DELETE";
// }
// Path: query/src/main/java/io/keen/client/java/PersistentAnalysis.java
import io.keen.client.java.http.HttpMethods;
package io.keen.client.java;
/**
* Base class that represents requests to the endpoints for managing persistent analyses, such as
* <a href="https://keen.io/docs/api/#saved-queries">Saved/Cached Queries</a> and
* <a href="https://keen.io/docs/api/#cached-datasets">Cached Datasets</a>.
*
* Should be an interface, but KeenQueryRequest is meant to be a package-private interface defining
* package-private functionality, so until the next major version when we fix up public interface
* surface area, it's a package-private abstract class.
*
* @author masojus
*/
abstract class PersistentAnalysis extends KeenQueryRequest {
// This regex does not match strings like "árbol π" since the API only accepts ASCII in the URL.
private static final String RESOURCE_NAME_REGEX = "^[\\w-]*$";
private final String httpMethod;
private final boolean needsMasterKey;
// The name of the specific persistent analysis we're working on, if any--e.g. "max_signups".
private final String resourceName;
private final String displayName;
PersistentAnalysis(String httpMethod,
boolean needsMasterKey,
String resourceName,
String displayName) {
// HTTP Method is provided by our code, so let's trust it's valid.
this.httpMethod = httpMethod;
this.needsMasterKey = needsMasterKey;
// The resource name can only be omitted for a GET request. | if (null == resourceName && !HttpMethods.GET.equals(httpMethod)) { |
keenlabs/KeenClient-Java | android/src/test/java/io/keen/client/android/AndroidJsonHandlerTest.java | // Path: core/src/main/java/io/keen/client/java/KeenConstants.java
// public final class KeenConstants {
// private KeenConstants() {}
//
// static final String SERVER_ADDRESS = "https://api.keen.io";
// static final String API_VERSION = "3.0";
//
// // Keen API constants
//
// static final int MAX_EVENT_DEPTH = 1000;
// static final int DEFAULT_MAX_ATTEMPTS = 3;
// static final String NAME_PARAM = "name";
// static final String SUCCESS_PARAM = "success";
// static final String ERROR_PARAM = "error";
// static final String DESCRIPTION_PARAM = "description";
// static final String INVALID_COLLECTION_NAME_ERROR = "InvalidCollectionNameError";
// static final String INVALID_PROPERTY_NAME_ERROR = "InvalidPropertyNameError";
// static final String INVALID_PROPERTY_VALUE_ERROR = "InvalidPropertyValueError";
//
// // Exported constants
//
// public static final String KEEN_FAKE_JSON_ROOT = "io.keen.client.java.__fake_root";
// }
| import org.hamcrest.Matchers;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.keen.client.java.KeenConstants;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when; |
// This string doesn't matter, but it's what we mimic with the mocks.
String mapResponse = "{\"result\": \"dummyResult\"}";
StringReader reader = new StringReader(mapResponse);
Map<String, Object> map = handler.readJson(reader);
assertNotNull(map);
assertEquals(1, map.size());
assertTrue(map.containsKey("result"));
assertEquals("dummyResult", map.get("result"));
}
@Test
public void readSimpleList() throws Exception {
JSONArray mockJsonArray = mock(JSONArray.class);
when(mockJsonArray.length()).thenReturn(1);
when(mockJsonArray.get(0)).thenReturn("dummyResult");
JSONTokener mockJsonTokener = mock(JSONTokener.class);
when(mockJsonTokener.nextValue()).thenReturn(mockJsonArray);
when(mockJsonObjectManager.newTokener(anyString())).thenReturn(mockJsonTokener);
// This string doesn't matter, but it's what we mimic with the mocks.
String listResponse = "[\"dummyResult\"]";
StringReader reader = new StringReader(listResponse);
Map<String, Object> map = handler.readJson(reader);
assertNotNull(map);
assertEquals(1, map.size());
// Validate that the raw JSON Array was wrapped in the fake root object. This behavior
// should change as soon as we can release a major version update to not do this dance. | // Path: core/src/main/java/io/keen/client/java/KeenConstants.java
// public final class KeenConstants {
// private KeenConstants() {}
//
// static final String SERVER_ADDRESS = "https://api.keen.io";
// static final String API_VERSION = "3.0";
//
// // Keen API constants
//
// static final int MAX_EVENT_DEPTH = 1000;
// static final int DEFAULT_MAX_ATTEMPTS = 3;
// static final String NAME_PARAM = "name";
// static final String SUCCESS_PARAM = "success";
// static final String ERROR_PARAM = "error";
// static final String DESCRIPTION_PARAM = "description";
// static final String INVALID_COLLECTION_NAME_ERROR = "InvalidCollectionNameError";
// static final String INVALID_PROPERTY_NAME_ERROR = "InvalidPropertyNameError";
// static final String INVALID_PROPERTY_VALUE_ERROR = "InvalidPropertyValueError";
//
// // Exported constants
//
// public static final String KEEN_FAKE_JSON_ROOT = "io.keen.client.java.__fake_root";
// }
// Path: android/src/test/java/io/keen/client/android/AndroidJsonHandlerTest.java
import org.hamcrest.Matchers;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.keen.client.java.KeenConstants;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
// This string doesn't matter, but it's what we mimic with the mocks.
String mapResponse = "{\"result\": \"dummyResult\"}";
StringReader reader = new StringReader(mapResponse);
Map<String, Object> map = handler.readJson(reader);
assertNotNull(map);
assertEquals(1, map.size());
assertTrue(map.containsKey("result"));
assertEquals("dummyResult", map.get("result"));
}
@Test
public void readSimpleList() throws Exception {
JSONArray mockJsonArray = mock(JSONArray.class);
when(mockJsonArray.length()).thenReturn(1);
when(mockJsonArray.get(0)).thenReturn("dummyResult");
JSONTokener mockJsonTokener = mock(JSONTokener.class);
when(mockJsonTokener.nextValue()).thenReturn(mockJsonArray);
when(mockJsonObjectManager.newTokener(anyString())).thenReturn(mockJsonTokener);
// This string doesn't matter, but it's what we mimic with the mocks.
String listResponse = "[\"dummyResult\"]";
StringReader reader = new StringReader(listResponse);
Map<String, Object> map = handler.readJson(reader);
assertNotNull(map);
assertEquals(1, map.size());
// Validate that the raw JSON Array was wrapped in the fake root object. This behavior
// should change as soon as we can release a major version update to not do this dance. | assertTrue(map.containsKey(KeenConstants.KEEN_FAKE_JSON_ROOT)); |
keenlabs/KeenClient-Java | query/src/main/java/io/keen/client/java/KeenQueryRequest.java | // Path: query/src/main/java/io/keen/client/java/exceptions/KeenQueryClientException.java
// public class KeenQueryClientException extends KeenException {
// private static final long serialVersionUID = -8714276738565293346L;
//
// public KeenQueryClientException() {
// super();
// }
//
// public KeenQueryClientException(Throwable cause) {
// super(cause);
// }
//
// public KeenQueryClientException(String message) {
// super(message);
// }
//
// public KeenQueryClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: core/src/main/java/io/keen/client/java/http/HttpMethods.java
// public final class HttpMethods {
// private HttpMethods() {}
//
// public final static String GET = "GET";
// public final static String POST = "POST";
// public final static String PUT = "PUT";
// public final static String DELETE = "DELETE";
// }
| import java.net.URL;
import java.util.Collection;
import java.util.Map;
import io.keen.client.java.exceptions.KeenQueryClientException;
import io.keen.client.java.http.HttpMethods; | package io.keen.client.java;
/**
* Interface to be implemented by a query request
*
* @author baumatron
*/
abstract class KeenQueryRequest {
abstract URL getRequestURL(RequestUrlBuilder urlBuilder, String projectId) | // Path: query/src/main/java/io/keen/client/java/exceptions/KeenQueryClientException.java
// public class KeenQueryClientException extends KeenException {
// private static final long serialVersionUID = -8714276738565293346L;
//
// public KeenQueryClientException() {
// super();
// }
//
// public KeenQueryClientException(Throwable cause) {
// super(cause);
// }
//
// public KeenQueryClientException(String message) {
// super(message);
// }
//
// public KeenQueryClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: core/src/main/java/io/keen/client/java/http/HttpMethods.java
// public final class HttpMethods {
// private HttpMethods() {}
//
// public final static String GET = "GET";
// public final static String POST = "POST";
// public final static String PUT = "PUT";
// public final static String DELETE = "DELETE";
// }
// Path: query/src/main/java/io/keen/client/java/KeenQueryRequest.java
import java.net.URL;
import java.util.Collection;
import java.util.Map;
import io.keen.client.java.exceptions.KeenQueryClientException;
import io.keen.client.java.http.HttpMethods;
package io.keen.client.java;
/**
* Interface to be implemented by a query request
*
* @author baumatron
*/
abstract class KeenQueryRequest {
abstract URL getRequestURL(RequestUrlBuilder urlBuilder, String projectId) | throws KeenQueryClientException; |
keenlabs/KeenClient-Java | query/src/main/java/io/keen/client/java/KeenQueryRequest.java | // Path: query/src/main/java/io/keen/client/java/exceptions/KeenQueryClientException.java
// public class KeenQueryClientException extends KeenException {
// private static final long serialVersionUID = -8714276738565293346L;
//
// public KeenQueryClientException() {
// super();
// }
//
// public KeenQueryClientException(Throwable cause) {
// super(cause);
// }
//
// public KeenQueryClientException(String message) {
// super(message);
// }
//
// public KeenQueryClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: core/src/main/java/io/keen/client/java/http/HttpMethods.java
// public final class HttpMethods {
// private HttpMethods() {}
//
// public final static String GET = "GET";
// public final static String POST = "POST";
// public final static String PUT = "PUT";
// public final static String DELETE = "DELETE";
// }
| import java.net.URL;
import java.util.Collection;
import java.util.Map;
import io.keen.client.java.exceptions.KeenQueryClientException;
import io.keen.client.java.http.HttpMethods; | package io.keen.client.java;
/**
* Interface to be implemented by a query request
*
* @author baumatron
*/
abstract class KeenQueryRequest {
abstract URL getRequestURL(RequestUrlBuilder urlBuilder, String projectId)
throws KeenQueryClientException;
// By default, we POST to get most of our query results.
String getHttpMethod() { | // Path: query/src/main/java/io/keen/client/java/exceptions/KeenQueryClientException.java
// public class KeenQueryClientException extends KeenException {
// private static final long serialVersionUID = -8714276738565293346L;
//
// public KeenQueryClientException() {
// super();
// }
//
// public KeenQueryClientException(Throwable cause) {
// super(cause);
// }
//
// public KeenQueryClientException(String message) {
// super(message);
// }
//
// public KeenQueryClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: core/src/main/java/io/keen/client/java/http/HttpMethods.java
// public final class HttpMethods {
// private HttpMethods() {}
//
// public final static String GET = "GET";
// public final static String POST = "POST";
// public final static String PUT = "PUT";
// public final static String DELETE = "DELETE";
// }
// Path: query/src/main/java/io/keen/client/java/KeenQueryRequest.java
import java.net.URL;
import java.util.Collection;
import java.util.Map;
import io.keen.client.java.exceptions.KeenQueryClientException;
import io.keen.client.java.http.HttpMethods;
package io.keen.client.java;
/**
* Interface to be implemented by a query request
*
* @author baumatron
*/
abstract class KeenQueryRequest {
abstract URL getRequestURL(RequestUrlBuilder urlBuilder, String projectId)
throws KeenQueryClientException;
// By default, we POST to get most of our query results.
String getHttpMethod() { | return HttpMethods.POST; |
keenlabs/KeenClient-Java | query/src/main/java/io/keen/client/java/SavedQueries.java | // Path: query/src/main/java/io/keen/client/java/result/QueryResult.java
// public abstract class QueryResult {
// /**
// * @return {@code false}
// */
// public boolean isDouble() {
// return false;
// }
//
// /**
// * @return {@code false}
// */
// public boolean isLong() {
// return false;
// }
//
// /**
// * @return {@code false}
// */
// public boolean isString() {
// return false;
// }
//
// /**
// * @return {@code false}
// */
// public boolean isListResult() {
// return false;
// }
//
// /**
// * @return {@code false}
// */
// public boolean isIntervalResult() {
// return false;
// }
//
// /**
// * @return {@code false}
// */
// public boolean isGroupResult() { return false; }
//
// /**
// * @return doubleValue, which is IllegalStateException in abstract class.
// */
// public double doubleValue() {
// throw new IllegalStateException();
// }
//
// /**
// * @return longValue, which is IllegalStateException in abstract class.
// */
// public long longValue() {
// throw new IllegalStateException();
// }
//
// /**
// * @return stringValue, which is IllegalStateException in abstract class.
// */
// public String stringValue() {
// throw new IllegalStateException();
// }
//
// /**
// * @return list results, which is IllegalStateException in abstract class.
// */
// public List<QueryResult> getListResults() {
// throw new IllegalStateException();
// }
//
// /**
// * @return map of AbsoluteTimeframe to QueryResult's, which is IllegalStateException in
// * abstract class.
// */
// public List<IntervalResultValue> getIntervalResults() { throw new IllegalStateException(); }
//
// /**
// * @return map of Group to QueryResult's, which is IllegalStateException in abstract class.
// */
// public Map<Group, QueryResult> getGroupResults() { throw new IllegalStateException(); }
//
// @Override
// public String toString() {
// return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
//
// @Override
// public boolean equals(Object obj) {
// return EqualsBuilder.reflectionEquals(this, obj);
// }
//
// @Override
// public int hashCode() {
// return HashCodeBuilder.reflectionHashCode(this);
// }
// }
| import java.io.IOException;
import java.util.List;
import java.util.Map;
import io.keen.client.java.result.QueryResult; | package io.keen.client.java;
/**
* Represents the set of operations that can be performed against the
* <a href="https://keen.io/docs/api/#saved-queries">Saved/Cached Query API</a> endpoints.
*
* @author masojus
*/
public interface SavedQueries {
/**
* Save the given query.
*
* @param queryName The resource name for the query. Alphanumerics, hyphens, and underscores.
* @param query The query definition.
*
* @return The raw return value of the PUT request as a Map containing the complete new
* Saved/Cached Query definition with auditing like created/updated/run information.
* @throws IOException If there is an error creating the Saved Query.
*/
Map<String, Object> createSavedQuery(String queryName,
KeenQueryRequest query) throws IOException;
/**
* Save the given query.
*
* @param queryName The resource name for the query. Alphanumerics, hyphens, and underscores.
* @param query The query definition.
* @param displayName The display name to be used for this resource.
*
* @return The raw return value of the PUT request as a Map containing the complete new
* Saved/Cached Query definition with auditing like created/updated/run information.
* @throws IOException If there is an error creating the Saved Query.
*/
Map<String, Object> createSavedQuery(String queryName,
KeenQueryRequest query,
String displayName) throws IOException;
/**
* Save the given query as a cached query.
*
* @param queryName The resource name for the query. Alphanumerics, hyphens, and underscores.
* @param query The query definition.
* @param refreshRate The refresh rate for this cached query, empirically in the range
* [14400, 86400] seconds or 4-24 hrs.
*
* @return The raw return value of the PUT request as a Map containing the complete new
* Saved/Cached Query definition with auditing like created/updated/run information.
* @throws IOException If there is an error creating the Cached Query.
*/
Map<String, Object> createCachedQuery(String queryName,
KeenQueryRequest query,
int refreshRate) throws IOException;
/**
* Save the given query as a cached query.
*
* @param queryName The resource name for the query. Alphanumerics, hyphens, and underscores.
* @param query The query definition.
* @param displayName The display name to be used for this resource.
* @param refreshRate The refresh rate for this cached query, empirically in the range
* [14400, 86400] seconds or 4-24 hrs.
*
* @return The raw return value of the PUT request as a Map containing the complete new
* Saved/Cached Query definition with auditing like created/updated/run information.
* @throws IOException If there is an error creating the Cached Query.
*/
Map<String, Object> createCachedQuery(String queryName,
KeenQueryRequest query,
String displayName,
int refreshRate) throws IOException;
/**
* Get a single Saved/Cached query definition.
*
* @param queryName The resource name for the query.
*
* @return The definition for the given query resource.
* @throws IOException If there is an error getting the Saved/Cached Query definition.
*/
Map<String, Object> getDefinition(String queryName) throws IOException;
/**
* Get all Saved/Cached Query definitions.
*
* @return All the Saved/Cached query definitions for this project.
* @throws IOException If there is an error getting the Saved/Cached Query definitions.
*/
List<Map<String, Object>> getAllDefinitions() throws IOException;
/**
* Get the result of the Saved/Cached query with the given resource name.
*
* @param queryName The resource name for the query.
*
* @return The result of the Saved/Cached query.
* @throws IOException If there is an error getting the Saved/Cached Query result.
*/ | // Path: query/src/main/java/io/keen/client/java/result/QueryResult.java
// public abstract class QueryResult {
// /**
// * @return {@code false}
// */
// public boolean isDouble() {
// return false;
// }
//
// /**
// * @return {@code false}
// */
// public boolean isLong() {
// return false;
// }
//
// /**
// * @return {@code false}
// */
// public boolean isString() {
// return false;
// }
//
// /**
// * @return {@code false}
// */
// public boolean isListResult() {
// return false;
// }
//
// /**
// * @return {@code false}
// */
// public boolean isIntervalResult() {
// return false;
// }
//
// /**
// * @return {@code false}
// */
// public boolean isGroupResult() { return false; }
//
// /**
// * @return doubleValue, which is IllegalStateException in abstract class.
// */
// public double doubleValue() {
// throw new IllegalStateException();
// }
//
// /**
// * @return longValue, which is IllegalStateException in abstract class.
// */
// public long longValue() {
// throw new IllegalStateException();
// }
//
// /**
// * @return stringValue, which is IllegalStateException in abstract class.
// */
// public String stringValue() {
// throw new IllegalStateException();
// }
//
// /**
// * @return list results, which is IllegalStateException in abstract class.
// */
// public List<QueryResult> getListResults() {
// throw new IllegalStateException();
// }
//
// /**
// * @return map of AbsoluteTimeframe to QueryResult's, which is IllegalStateException in
// * abstract class.
// */
// public List<IntervalResultValue> getIntervalResults() { throw new IllegalStateException(); }
//
// /**
// * @return map of Group to QueryResult's, which is IllegalStateException in abstract class.
// */
// public Map<Group, QueryResult> getGroupResults() { throw new IllegalStateException(); }
//
// @Override
// public String toString() {
// return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
// }
//
// @Override
// public boolean equals(Object obj) {
// return EqualsBuilder.reflectionEquals(this, obj);
// }
//
// @Override
// public int hashCode() {
// return HashCodeBuilder.reflectionHashCode(this);
// }
// }
// Path: query/src/main/java/io/keen/client/java/SavedQueries.java
import java.io.IOException;
import java.util.List;
import java.util.Map;
import io.keen.client.java.result.QueryResult;
package io.keen.client.java;
/**
* Represents the set of operations that can be performed against the
* <a href="https://keen.io/docs/api/#saved-queries">Saved/Cached Query API</a> endpoints.
*
* @author masojus
*/
public interface SavedQueries {
/**
* Save the given query.
*
* @param queryName The resource name for the query. Alphanumerics, hyphens, and underscores.
* @param query The query definition.
*
* @return The raw return value of the PUT request as a Map containing the complete new
* Saved/Cached Query definition with auditing like created/updated/run information.
* @throws IOException If there is an error creating the Saved Query.
*/
Map<String, Object> createSavedQuery(String queryName,
KeenQueryRequest query) throws IOException;
/**
* Save the given query.
*
* @param queryName The resource name for the query. Alphanumerics, hyphens, and underscores.
* @param query The query definition.
* @param displayName The display name to be used for this resource.
*
* @return The raw return value of the PUT request as a Map containing the complete new
* Saved/Cached Query definition with auditing like created/updated/run information.
* @throws IOException If there is an error creating the Saved Query.
*/
Map<String, Object> createSavedQuery(String queryName,
KeenQueryRequest query,
String displayName) throws IOException;
/**
* Save the given query as a cached query.
*
* @param queryName The resource name for the query. Alphanumerics, hyphens, and underscores.
* @param query The query definition.
* @param refreshRate The refresh rate for this cached query, empirically in the range
* [14400, 86400] seconds or 4-24 hrs.
*
* @return The raw return value of the PUT request as a Map containing the complete new
* Saved/Cached Query definition with auditing like created/updated/run information.
* @throws IOException If there is an error creating the Cached Query.
*/
Map<String, Object> createCachedQuery(String queryName,
KeenQueryRequest query,
int refreshRate) throws IOException;
/**
* Save the given query as a cached query.
*
* @param queryName The resource name for the query. Alphanumerics, hyphens, and underscores.
* @param query The query definition.
* @param displayName The display name to be used for this resource.
* @param refreshRate The refresh rate for this cached query, empirically in the range
* [14400, 86400] seconds or 4-24 hrs.
*
* @return The raw return value of the PUT request as a Map containing the complete new
* Saved/Cached Query definition with auditing like created/updated/run information.
* @throws IOException If there is an error creating the Cached Query.
*/
Map<String, Object> createCachedQuery(String queryName,
KeenQueryRequest query,
String displayName,
int refreshRate) throws IOException;
/**
* Get a single Saved/Cached query definition.
*
* @param queryName The resource name for the query.
*
* @return The definition for the given query resource.
* @throws IOException If there is an error getting the Saved/Cached Query definition.
*/
Map<String, Object> getDefinition(String queryName) throws IOException;
/**
* Get all Saved/Cached Query definitions.
*
* @return All the Saved/Cached query definitions for this project.
* @throws IOException If there is an error getting the Saved/Cached Query definitions.
*/
List<Map<String, Object>> getAllDefinitions() throws IOException;
/**
* Get the result of the Saved/Cached query with the given resource name.
*
* @param queryName The resource name for the query.
*
* @return The result of the Saved/Cached query.
* @throws IOException If there is an error getting the Saved/Cached Query result.
*/ | QueryResult getResult(String queryName) throws IOException; |
keenlabs/KeenClient-Java | query/src/main/java/io/keen/client/java/RequestUrlBuilder.java | // Path: query/src/main/java/io/keen/client/java/exceptions/KeenQueryClientException.java
// public class KeenQueryClientException extends KeenException {
// private static final long serialVersionUID = -8714276738565293346L;
//
// public KeenQueryClientException() {
// super();
// }
//
// public KeenQueryClientException(Throwable cause) {
// super(cause);
// }
//
// public KeenQueryClientException(String message) {
// super(message);
// }
//
// public KeenQueryClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
| import io.keen.client.java.exceptions.KeenQueryClientException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger; | package io.keen.client.java;
/**
* Class which handles formatting of request URLs.
*
* @author baumatron
*/
class RequestUrlBuilder {
// The API version string
private final String apiVersion;
// The base URL, including the scheme and domain
private final String baseUrl;
RequestUrlBuilder(String apiVersion, String baseUrl) {
if (null == apiVersion || apiVersion.trim().isEmpty()) {
throw new IllegalArgumentException("'apiVersion' is a required argument.");
}
if (null == baseUrl || baseUrl.trim().isEmpty()) {
throw new IllegalArgumentException("'baseUrl' is a required argument.");
}
this.apiVersion = apiVersion;
this.baseUrl = baseUrl;
}
/**
* Get a formatted URL for an analysis request.
*
* @param projectId The project id
* @param analysisPath The analysis url sub-path
* @return The complete URL.
* @throws KeenQueryClientException
*/ | // Path: query/src/main/java/io/keen/client/java/exceptions/KeenQueryClientException.java
// public class KeenQueryClientException extends KeenException {
// private static final long serialVersionUID = -8714276738565293346L;
//
// public KeenQueryClientException() {
// super();
// }
//
// public KeenQueryClientException(Throwable cause) {
// super(cause);
// }
//
// public KeenQueryClientException(String message) {
// super(message);
// }
//
// public KeenQueryClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: query/src/main/java/io/keen/client/java/RequestUrlBuilder.java
import io.keen.client.java.exceptions.KeenQueryClientException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
package io.keen.client.java;
/**
* Class which handles formatting of request URLs.
*
* @author baumatron
*/
class RequestUrlBuilder {
// The API version string
private final String apiVersion;
// The base URL, including the scheme and domain
private final String baseUrl;
RequestUrlBuilder(String apiVersion, String baseUrl) {
if (null == apiVersion || apiVersion.trim().isEmpty()) {
throw new IllegalArgumentException("'apiVersion' is a required argument.");
}
if (null == baseUrl || baseUrl.trim().isEmpty()) {
throw new IllegalArgumentException("'baseUrl' is a required argument.");
}
this.apiVersion = apiVersion;
this.baseUrl = baseUrl;
}
/**
* Get a formatted URL for an analysis request.
*
* @param projectId The project id
* @param analysisPath The analysis url sub-path
* @return The complete URL.
* @throws KeenQueryClientException
*/ | URL getAnalysisUrl(String projectId, String analysisPath) throws KeenQueryClientException { |
keenlabs/KeenClient-Java | query/src/main/java/io/keen/client/java/DatasetQuery.java | // Path: query/src/main/java/io/keen/client/java/KeenQueryConstants.java
// class KeenQueryConstants {
// // Query names
// static final String COUNT = "count";
// static final String COUNT_UNIQUE = "count_unique";
// static final String MINIMUM = "minimum";
// static final String MAXIMUM = "maximum";
// static final String AVERAGE = "average";
// static final String MEDIAN = "median";
// static final String PERCENTILE_RESOURCE = "percentile";
// static final String SUM = "sum";
// static final String SELECT_UNIQUE = "select_unique";
// static final String STANDARD_DEVIATION = "standard_deviation";
// static final String FUNNEL = "funnel";
// static final String MULTI_ANALYSIS = "multi_analysis";
//
// // Query parameters
// static final String EVENT_COLLECTION = "event_collection";
// static final String TARGET_PROPERTY = "target_property";
// static final String FILTERS = "filters";
// static final String TIMEFRAME = "timeframe";
// static final String INTERVAL = "interval";
// static final String TIMEZONE = "timezone";
// static final String GROUP_BY = "group_by";
// static final String MAX_AGE = "max_age";
// static final String PERCENTILE = "percentile";
//
// // Datasets parameters
// static final String INDEX_BY = "index_by";
// static final String LIMIT = "limit";
// static final String AFTER_NAME = "after_name";
//
// // filter property names
// static final String PROPERTY_NAME = "property_name";
// static final String OPERATOR = "operator";
// static final String PROPERTY_VALUE = "property_value";
//
// // filter operators
// static final String EQUAL_TO = "eq";
// static final String NOT_EQUAL = "ne";
// static final String LESS_THAN = "lt";
// static final String LESS_THAN_EQUAL = "lte";
// static final String GREATER_THAN = "gt";
// static final String GREATER_THAN_EQUAL = "gte";
// static final String EXISTS = "exists";
// static final String IN = "in";
// static final String CONTAINS = "contains";
// static final String NOT_CONTAINS = "not_contains";
// static final String WITHIN = "within";
// static final String REGEX = "regex";
//
// // funnel
// static final String ACTOR_PROPERTY = "actor_property";
// static final String STEPS = "steps";
// static final String INVERTED = "inverted";
// static final String OPTIONAL = "optional";
// static final String WITH_ACTORS = "with_actors";
// static final String ACTORS = "actors";
//
// // multi-analysis
// static final String ANALYSES = "analyses";
// static final String ANALYSIS_TYPE = "analysis_type";
//
// // return
// static final String RESULT = "result";
// static final String ERROR_CODE = "error_code";
// static final String MESSAGE = "message";
// static final String VALUE = "value";
//
// // absolute timeframe
// static final String START = "start";
// static final String END = "end";
//
// // Meta queries
// static final String SAVED = "saved";
// static final String DATASETS = "datasets";
// static final String QUERY = "query";
// static final String REFRESH_RATE = "refresh_rate";
// static final String METADATA = "metadata";
// static final String DISPLAY_NAME = "display_name";
// static final String QUERY_NAME = "query_name";
// }
| import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.util.*;
import static io.keen.client.java.KeenQueryConstants.*; | }
Map<String, Object> asMap() {
Map<String, Object> result = new HashMap<String, Object>();
if (analysisType != null) {
result.put(ANALYSIS_TYPE, analysisType);
}
if (targetProperty != null) {
result.put(TARGET_PROPERTY, targetProperty);
}
if (eventCollection != null) {
result.put(EVENT_COLLECTION, eventCollection);
}
if (timeframe != null) {
result.put(TIMEFRAME, timeframe);
}
if (timezone != null) {
result.put(TIMEZONE, timezone);
}
if (interval != null) {
result.put(INTERVAL, interval);
}
if (groupBy != null) {
result.put(GROUP_BY, groupBy);
}
if (analyses != null) {
Map<String, Map<String, Object>> analysesMap = new HashMap<String, Map<String, Object>>();
for (SubAnalysis analysis : analyses) {
analysesMap.put(analysis.getLabel(), analysis.constructParameterRequestArgs());
} | // Path: query/src/main/java/io/keen/client/java/KeenQueryConstants.java
// class KeenQueryConstants {
// // Query names
// static final String COUNT = "count";
// static final String COUNT_UNIQUE = "count_unique";
// static final String MINIMUM = "minimum";
// static final String MAXIMUM = "maximum";
// static final String AVERAGE = "average";
// static final String MEDIAN = "median";
// static final String PERCENTILE_RESOURCE = "percentile";
// static final String SUM = "sum";
// static final String SELECT_UNIQUE = "select_unique";
// static final String STANDARD_DEVIATION = "standard_deviation";
// static final String FUNNEL = "funnel";
// static final String MULTI_ANALYSIS = "multi_analysis";
//
// // Query parameters
// static final String EVENT_COLLECTION = "event_collection";
// static final String TARGET_PROPERTY = "target_property";
// static final String FILTERS = "filters";
// static final String TIMEFRAME = "timeframe";
// static final String INTERVAL = "interval";
// static final String TIMEZONE = "timezone";
// static final String GROUP_BY = "group_by";
// static final String MAX_AGE = "max_age";
// static final String PERCENTILE = "percentile";
//
// // Datasets parameters
// static final String INDEX_BY = "index_by";
// static final String LIMIT = "limit";
// static final String AFTER_NAME = "after_name";
//
// // filter property names
// static final String PROPERTY_NAME = "property_name";
// static final String OPERATOR = "operator";
// static final String PROPERTY_VALUE = "property_value";
//
// // filter operators
// static final String EQUAL_TO = "eq";
// static final String NOT_EQUAL = "ne";
// static final String LESS_THAN = "lt";
// static final String LESS_THAN_EQUAL = "lte";
// static final String GREATER_THAN = "gt";
// static final String GREATER_THAN_EQUAL = "gte";
// static final String EXISTS = "exists";
// static final String IN = "in";
// static final String CONTAINS = "contains";
// static final String NOT_CONTAINS = "not_contains";
// static final String WITHIN = "within";
// static final String REGEX = "regex";
//
// // funnel
// static final String ACTOR_PROPERTY = "actor_property";
// static final String STEPS = "steps";
// static final String INVERTED = "inverted";
// static final String OPTIONAL = "optional";
// static final String WITH_ACTORS = "with_actors";
// static final String ACTORS = "actors";
//
// // multi-analysis
// static final String ANALYSES = "analyses";
// static final String ANALYSIS_TYPE = "analysis_type";
//
// // return
// static final String RESULT = "result";
// static final String ERROR_CODE = "error_code";
// static final String MESSAGE = "message";
// static final String VALUE = "value";
//
// // absolute timeframe
// static final String START = "start";
// static final String END = "end";
//
// // Meta queries
// static final String SAVED = "saved";
// static final String DATASETS = "datasets";
// static final String QUERY = "query";
// static final String REFRESH_RATE = "refresh_rate";
// static final String METADATA = "metadata";
// static final String DISPLAY_NAME = "display_name";
// static final String QUERY_NAME = "query_name";
// }
// Path: query/src/main/java/io/keen/client/java/DatasetQuery.java
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.util.*;
import static io.keen.client.java.KeenQueryConstants.*;
}
Map<String, Object> asMap() {
Map<String, Object> result = new HashMap<String, Object>();
if (analysisType != null) {
result.put(ANALYSIS_TYPE, analysisType);
}
if (targetProperty != null) {
result.put(TARGET_PROPERTY, targetProperty);
}
if (eventCollection != null) {
result.put(EVENT_COLLECTION, eventCollection);
}
if (timeframe != null) {
result.put(TIMEFRAME, timeframe);
}
if (timezone != null) {
result.put(TIMEZONE, timezone);
}
if (interval != null) {
result.put(INTERVAL, interval);
}
if (groupBy != null) {
result.put(GROUP_BY, groupBy);
}
if (analyses != null) {
Map<String, Map<String, Object>> analysesMap = new HashMap<String, Map<String, Object>>();
for (SubAnalysis analysis : analyses) {
analysesMap.put(analysis.getLabel(), analysis.constructParameterRequestArgs());
} | result.put(KeenQueryConstants.ANALYSES, analysesMap); |
keenlabs/KeenClient-Java | query/src/main/java/io/keen/client/java/Funnel.java | // Path: query/src/main/java/io/keen/client/java/exceptions/KeenQueryClientException.java
// public class KeenQueryClientException extends KeenException {
// private static final long serialVersionUID = -8714276738565293346L;
//
// public KeenQueryClientException() {
// super();
// }
//
// public KeenQueryClientException(Throwable cause) {
// super(cause);
// }
//
// public KeenQueryClientException(String message) {
// super(message);
// }
//
// public KeenQueryClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
| import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.keen.client.java.exceptions.KeenQueryClientException; |
// Validate step properties that cannot be true for the first funnel step
FunnelStep firstStep = builder.steps.get(0);
if (null != firstStep.getInverted() &&
true == firstStep.getInverted()) {
throw new IllegalArgumentException(
"First step in funnel cannot have special parameter 'inverted' set to true.");
}
if (null != firstStep.getOptional() &&
true == firstStep.getOptional()) {
throw new IllegalArgumentException(
"First step in funnel cannot have special parameter 'optional' set to true.");
}
// The steps in the Builder are ordered, so the request params will be too.
this.steps = new RequestParameterCollection<FunnelStep>(builder.steps);
}
/**
* Get the URL for this request.
*
* @param urlBuilder The RequestUrlBuilder instance to use for building the URL.
* @param projectId The projectId to use for the URL.
* @return The URL for the request.
* @throws KeenQueryClientException Thrown if there are errors formatting the URL.
*/
@Override
URL getRequestURL(RequestUrlBuilder urlBuilder, String projectId) | // Path: query/src/main/java/io/keen/client/java/exceptions/KeenQueryClientException.java
// public class KeenQueryClientException extends KeenException {
// private static final long serialVersionUID = -8714276738565293346L;
//
// public KeenQueryClientException() {
// super();
// }
//
// public KeenQueryClientException(Throwable cause) {
// super(cause);
// }
//
// public KeenQueryClientException(String message) {
// super(message);
// }
//
// public KeenQueryClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
// Path: query/src/main/java/io/keen/client/java/Funnel.java
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.keen.client.java.exceptions.KeenQueryClientException;
// Validate step properties that cannot be true for the first funnel step
FunnelStep firstStep = builder.steps.get(0);
if (null != firstStep.getInverted() &&
true == firstStep.getInverted()) {
throw new IllegalArgumentException(
"First step in funnel cannot have special parameter 'inverted' set to true.");
}
if (null != firstStep.getOptional() &&
true == firstStep.getOptional()) {
throw new IllegalArgumentException(
"First step in funnel cannot have special parameter 'optional' set to true.");
}
// The steps in the Builder are ordered, so the request params will be too.
this.steps = new RequestParameterCollection<FunnelStep>(builder.steps);
}
/**
* Get the URL for this request.
*
* @param urlBuilder The RequestUrlBuilder instance to use for building the URL.
* @param projectId The projectId to use for the URL.
* @return The URL for the request.
* @throws KeenQueryClientException Thrown if there are errors formatting the URL.
*/
@Override
URL getRequestURL(RequestUrlBuilder urlBuilder, String projectId) | throws KeenQueryClientException { |
keenlabs/KeenClient-Java | query/src/main/java/io/keen/client/java/CachedDatasetRequest.java | // Path: query/src/main/java/io/keen/client/java/exceptions/KeenQueryClientException.java
// public class KeenQueryClientException extends KeenException {
// private static final long serialVersionUID = -8714276738565293346L;
//
// public KeenQueryClientException() {
// super();
// }
//
// public KeenQueryClientException(Throwable cause) {
// super(cause);
// }
//
// public KeenQueryClientException(String message) {
// super(message);
// }
//
// public KeenQueryClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: core/src/main/java/io/keen/client/java/http/HttpMethods.java
// public final class HttpMethods {
// private HttpMethods() {}
//
// public final static String GET = "GET";
// public final static String POST = "POST";
// public final static String PUT = "PUT";
// public final static String DELETE = "DELETE";
// }
| import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import io.keen.client.java.exceptions.KeenQueryClientException;
import io.keen.client.java.http.HttpMethods;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static java.util.Collections.emptyMap; | package io.keen.client.java;
abstract class CachedDatasetRequest extends PersistentAnalysis {
private CachedDatasetRequest(String httpMethod, boolean needsMasterKey, String datasetName) {
super(httpMethod, needsMasterKey, datasetName, null);
}
static KeenQueryRequest definitionRequest(String datasetName) { | // Path: query/src/main/java/io/keen/client/java/exceptions/KeenQueryClientException.java
// public class KeenQueryClientException extends KeenException {
// private static final long serialVersionUID = -8714276738565293346L;
//
// public KeenQueryClientException() {
// super();
// }
//
// public KeenQueryClientException(Throwable cause) {
// super(cause);
// }
//
// public KeenQueryClientException(String message) {
// super(message);
// }
//
// public KeenQueryClientException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: core/src/main/java/io/keen/client/java/http/HttpMethods.java
// public final class HttpMethods {
// private HttpMethods() {}
//
// public final static String GET = "GET";
// public final static String POST = "POST";
// public final static String PUT = "PUT";
// public final static String DELETE = "DELETE";
// }
// Path: query/src/main/java/io/keen/client/java/CachedDatasetRequest.java
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import io.keen.client.java.exceptions.KeenQueryClientException;
import io.keen.client.java.http.HttpMethods;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static java.util.Collections.emptyMap;
package io.keen.client.java;
abstract class CachedDatasetRequest extends PersistentAnalysis {
private CachedDatasetRequest(String httpMethod, boolean needsMasterKey, String datasetName) {
super(httpMethod, needsMasterKey, datasetName, null);
}
static KeenQueryRequest definitionRequest(String datasetName) { | return new CachedDatasetRequest(HttpMethods.GET, false, datasetName) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.