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
|
---|---|---|---|---|---|---|
lewisd32/authrite | authrite-service/src/main/java/com/lewisd/authrite/AuthriteServiceConfiguration.java | // Path: authrite-service/src/main/java/com/lewisd/authrite/auth/JWTConfiguration.java
// public class JWTConfiguration {
// private String jwtSecret = "secret";
// private int jwtExpirySeconds = 3600;
// private String cookieName = "jwtToken";
//
// @JsonProperty
// public String getJwtSecret() {
// return jwtSecret;
// }
//
// public void setJwtSecret(final String jwtSecret) {
// this.jwtSecret = jwtSecret;
// }
//
// @JsonProperty
// public int getJwtExpirySeconds() {
// return jwtExpirySeconds;
// }
//
// public void setJwtExpirySeconds(final int jwtExpirySeconds) {
// this.jwtExpirySeconds = jwtExpirySeconds;
// }
//
// @JsonProperty
// public String getCookieName() {
// return cookieName;
// }
//
// public void setCookieName(final String cookieName) {
// this.cookieName = cookieName;
// }
//
// public JWTAuthFilter<User> buildAuthFilter() {
// return new JWTAuthFilter.Builder<User>()
// .setCookieName(this.getCookieName())
// .setAuthenticator(new JWTAuthenticator(buildTokenManager()))
// // .setAuthorizer(new ExampleAuthorizer())
// .buildAuthFilter();
// }
//
// public JwtTokenManager buildTokenManager() {
// return new JwtTokenManager(jwtSecret, jwtExpirySeconds);
// }
//
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/auth/PasswordManagementConfiguration.java
// public class PasswordManagementConfiguration {
//
// public static final int MIN_LENGTH = 8;
// public static final int MAX_LENGTH = 100;
//
// private int bcryptCost;
//
// @JsonProperty
// public int getBcryptCost() {
// return bcryptCost;
// }
//
// @JsonProperty
// public void setBcryptCost(final int bcryptCost) {
// this.bcryptCost = bcryptCost;
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.lewisd.authrite.auth.JWTConfiguration;
import com.lewisd.authrite.auth.PasswordManagementConfiguration;
import io.dropwizard.Configuration;
import io.dropwizard.db.DataSourceFactory;
import javax.validation.Valid;
import javax.validation.constraints.NotNull; | package com.lewisd.authrite;
public class AuthriteServiceConfiguration extends Configuration {
@Valid
@NotNull | // Path: authrite-service/src/main/java/com/lewisd/authrite/auth/JWTConfiguration.java
// public class JWTConfiguration {
// private String jwtSecret = "secret";
// private int jwtExpirySeconds = 3600;
// private String cookieName = "jwtToken";
//
// @JsonProperty
// public String getJwtSecret() {
// return jwtSecret;
// }
//
// public void setJwtSecret(final String jwtSecret) {
// this.jwtSecret = jwtSecret;
// }
//
// @JsonProperty
// public int getJwtExpirySeconds() {
// return jwtExpirySeconds;
// }
//
// public void setJwtExpirySeconds(final int jwtExpirySeconds) {
// this.jwtExpirySeconds = jwtExpirySeconds;
// }
//
// @JsonProperty
// public String getCookieName() {
// return cookieName;
// }
//
// public void setCookieName(final String cookieName) {
// this.cookieName = cookieName;
// }
//
// public JWTAuthFilter<User> buildAuthFilter() {
// return new JWTAuthFilter.Builder<User>()
// .setCookieName(this.getCookieName())
// .setAuthenticator(new JWTAuthenticator(buildTokenManager()))
// // .setAuthorizer(new ExampleAuthorizer())
// .buildAuthFilter();
// }
//
// public JwtTokenManager buildTokenManager() {
// return new JwtTokenManager(jwtSecret, jwtExpirySeconds);
// }
//
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/auth/PasswordManagementConfiguration.java
// public class PasswordManagementConfiguration {
//
// public static final int MIN_LENGTH = 8;
// public static final int MAX_LENGTH = 100;
//
// private int bcryptCost;
//
// @JsonProperty
// public int getBcryptCost() {
// return bcryptCost;
// }
//
// @JsonProperty
// public void setBcryptCost(final int bcryptCost) {
// this.bcryptCost = bcryptCost;
// }
// }
// Path: authrite-service/src/main/java/com/lewisd/authrite/AuthriteServiceConfiguration.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.lewisd.authrite.auth.JWTConfiguration;
import com.lewisd.authrite.auth.PasswordManagementConfiguration;
import io.dropwizard.Configuration;
import io.dropwizard.db.DataSourceFactory;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
package com.lewisd.authrite;
public class AuthriteServiceConfiguration extends Configuration {
@Valid
@NotNull | private JWTConfiguration jwt = new JWTConfiguration(); |
lewisd32/authrite | authrite-service/src/main/java/com/lewisd/authrite/AuthriteServiceConfiguration.java | // Path: authrite-service/src/main/java/com/lewisd/authrite/auth/JWTConfiguration.java
// public class JWTConfiguration {
// private String jwtSecret = "secret";
// private int jwtExpirySeconds = 3600;
// private String cookieName = "jwtToken";
//
// @JsonProperty
// public String getJwtSecret() {
// return jwtSecret;
// }
//
// public void setJwtSecret(final String jwtSecret) {
// this.jwtSecret = jwtSecret;
// }
//
// @JsonProperty
// public int getJwtExpirySeconds() {
// return jwtExpirySeconds;
// }
//
// public void setJwtExpirySeconds(final int jwtExpirySeconds) {
// this.jwtExpirySeconds = jwtExpirySeconds;
// }
//
// @JsonProperty
// public String getCookieName() {
// return cookieName;
// }
//
// public void setCookieName(final String cookieName) {
// this.cookieName = cookieName;
// }
//
// public JWTAuthFilter<User> buildAuthFilter() {
// return new JWTAuthFilter.Builder<User>()
// .setCookieName(this.getCookieName())
// .setAuthenticator(new JWTAuthenticator(buildTokenManager()))
// // .setAuthorizer(new ExampleAuthorizer())
// .buildAuthFilter();
// }
//
// public JwtTokenManager buildTokenManager() {
// return new JwtTokenManager(jwtSecret, jwtExpirySeconds);
// }
//
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/auth/PasswordManagementConfiguration.java
// public class PasswordManagementConfiguration {
//
// public static final int MIN_LENGTH = 8;
// public static final int MAX_LENGTH = 100;
//
// private int bcryptCost;
//
// @JsonProperty
// public int getBcryptCost() {
// return bcryptCost;
// }
//
// @JsonProperty
// public void setBcryptCost(final int bcryptCost) {
// this.bcryptCost = bcryptCost;
// }
// }
| import com.fasterxml.jackson.annotation.JsonProperty;
import com.lewisd.authrite.auth.JWTConfiguration;
import com.lewisd.authrite.auth.PasswordManagementConfiguration;
import io.dropwizard.Configuration;
import io.dropwizard.db.DataSourceFactory;
import javax.validation.Valid;
import javax.validation.constraints.NotNull; | package com.lewisd.authrite;
public class AuthriteServiceConfiguration extends Configuration {
@Valid
@NotNull
private JWTConfiguration jwt = new JWTConfiguration();
@Valid
@NotNull
private DataSourceFactory database = new DataSourceFactory();
@Valid
@NotNull | // Path: authrite-service/src/main/java/com/lewisd/authrite/auth/JWTConfiguration.java
// public class JWTConfiguration {
// private String jwtSecret = "secret";
// private int jwtExpirySeconds = 3600;
// private String cookieName = "jwtToken";
//
// @JsonProperty
// public String getJwtSecret() {
// return jwtSecret;
// }
//
// public void setJwtSecret(final String jwtSecret) {
// this.jwtSecret = jwtSecret;
// }
//
// @JsonProperty
// public int getJwtExpirySeconds() {
// return jwtExpirySeconds;
// }
//
// public void setJwtExpirySeconds(final int jwtExpirySeconds) {
// this.jwtExpirySeconds = jwtExpirySeconds;
// }
//
// @JsonProperty
// public String getCookieName() {
// return cookieName;
// }
//
// public void setCookieName(final String cookieName) {
// this.cookieName = cookieName;
// }
//
// public JWTAuthFilter<User> buildAuthFilter() {
// return new JWTAuthFilter.Builder<User>()
// .setCookieName(this.getCookieName())
// .setAuthenticator(new JWTAuthenticator(buildTokenManager()))
// // .setAuthorizer(new ExampleAuthorizer())
// .buildAuthFilter();
// }
//
// public JwtTokenManager buildTokenManager() {
// return new JwtTokenManager(jwtSecret, jwtExpirySeconds);
// }
//
// }
//
// Path: authrite-service/src/main/java/com/lewisd/authrite/auth/PasswordManagementConfiguration.java
// public class PasswordManagementConfiguration {
//
// public static final int MIN_LENGTH = 8;
// public static final int MAX_LENGTH = 100;
//
// private int bcryptCost;
//
// @JsonProperty
// public int getBcryptCost() {
// return bcryptCost;
// }
//
// @JsonProperty
// public void setBcryptCost(final int bcryptCost) {
// this.bcryptCost = bcryptCost;
// }
// }
// Path: authrite-service/src/main/java/com/lewisd/authrite/AuthriteServiceConfiguration.java
import com.fasterxml.jackson.annotation.JsonProperty;
import com.lewisd.authrite.auth.JWTConfiguration;
import com.lewisd.authrite.auth.PasswordManagementConfiguration;
import io.dropwizard.Configuration;
import io.dropwizard.db.DataSourceFactory;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
package com.lewisd.authrite;
public class AuthriteServiceConfiguration extends Configuration {
@Valid
@NotNull
private JWTConfiguration jwt = new JWTConfiguration();
@Valid
@NotNull
private DataSourceFactory database = new DataSourceFactory();
@Valid
@NotNull | private PasswordManagementConfiguration passwordManagement = new PasswordManagementConfiguration(); |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/internal/DefaultVertexFactory.java | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/handlers/VertexHandler.java
// public interface VertexHandler {
//
// /**
// * Specifies if this handler can manage the subject.
// */
// boolean canHandle(Object subject);
//
// /**
// * Handle the passed vertex based on the subject.
// */
// void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder);
//
// class Composite implements VertexHandler {
//
// private final List<VertexHandler> delegates;
//
// public Composite(List<VertexHandler> delegates) {
// this.delegates = delegates;
// }
//
// @Override
// public boolean canHandle(Object subject) {
// for (VertexHandler vertexHandler : delegates) {
// if (vertexHandler.canHandle(subject)) {
// return true;
// }
// }
//
// return false;
// }
//
// @Override
// public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) {
// for (VertexHandler vertexHandler : delegates) {
// if (vertexHandler.canHandle(subject)) {
// vertexHandler.handle(vertex, subject, vertexFieldAdder);
// return;
// }
// }
// }
// }
//
// class MapVertexHandler extends TypeBasedHandler<Map<Object, Object>> {
//
// public MapVertexHandler() {
// super(Map.class);
// }
//
// @Override
// public void typedHandle(Vertex vertex, Map<Object, Object> subject, VertexFieldAdder vertexFieldAdder) {
// int i = -1;
// for (Map.Entry<Object, Object> entry : subject.entrySet()) {
// i++;
// final Object key = entry.getKey();
// final Object value = entry.getValue();
// final boolean primitiveKey = ReflectUtils.isPrimitive(key.getClass());
//
// if (primitiveKey) {
// vertexFieldAdder.addField(vertex, key.toString(), value);
// }
//
// if (!primitiveKey) {
// final Vertex entryVertex = new Vertex(Map.Entry.class, System.identityHashCode(entry) + "");
// vertexFieldAdder.addField(entryVertex, "key", key);
// vertexFieldAdder.addField(entryVertex, "value", value);
// vertex.getReferences().add(new Edge("entry_" + i, entryVertex));
// }
// }
// }
// }
//
// class ArrayHandler implements VertexHandler {
//
// public boolean canHandle(Object subject) {
// return subject.getClass().isArray();
// }
//
// public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) {
// int arrayLength = Array.getLength(subject);
// for (int i = 0; i < arrayLength; i++) {
// Object item = Array.get(subject, i);
// vertexFieldAdder.addField(vertex, i + "", item);
// }
// }
// }
//
// class ClassTypeHandler extends TypeBasedHandler<Class> {
//
// public ClassTypeHandler() {
// super(Class.class);
// }
//
// @Override
// protected void typedHandle(Vertex vertex, Class subject, VertexFieldAdder vertexFieldAdder) {
// vertexFieldAdder.addField(vertex, "name", subject.getName());
// }
// }
//
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.handlers.VertexHandler;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Set; | package org.laborra.beantrace.internal;
public class DefaultVertexFactory implements VertexFactory {
private final Map<Object, Vertex> visitedMap = new IdentityHashMap<>(); | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/handlers/VertexHandler.java
// public interface VertexHandler {
//
// /**
// * Specifies if this handler can manage the subject.
// */
// boolean canHandle(Object subject);
//
// /**
// * Handle the passed vertex based on the subject.
// */
// void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder);
//
// class Composite implements VertexHandler {
//
// private final List<VertexHandler> delegates;
//
// public Composite(List<VertexHandler> delegates) {
// this.delegates = delegates;
// }
//
// @Override
// public boolean canHandle(Object subject) {
// for (VertexHandler vertexHandler : delegates) {
// if (vertexHandler.canHandle(subject)) {
// return true;
// }
// }
//
// return false;
// }
//
// @Override
// public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) {
// for (VertexHandler vertexHandler : delegates) {
// if (vertexHandler.canHandle(subject)) {
// vertexHandler.handle(vertex, subject, vertexFieldAdder);
// return;
// }
// }
// }
// }
//
// class MapVertexHandler extends TypeBasedHandler<Map<Object, Object>> {
//
// public MapVertexHandler() {
// super(Map.class);
// }
//
// @Override
// public void typedHandle(Vertex vertex, Map<Object, Object> subject, VertexFieldAdder vertexFieldAdder) {
// int i = -1;
// for (Map.Entry<Object, Object> entry : subject.entrySet()) {
// i++;
// final Object key = entry.getKey();
// final Object value = entry.getValue();
// final boolean primitiveKey = ReflectUtils.isPrimitive(key.getClass());
//
// if (primitiveKey) {
// vertexFieldAdder.addField(vertex, key.toString(), value);
// }
//
// if (!primitiveKey) {
// final Vertex entryVertex = new Vertex(Map.Entry.class, System.identityHashCode(entry) + "");
// vertexFieldAdder.addField(entryVertex, "key", key);
// vertexFieldAdder.addField(entryVertex, "value", value);
// vertex.getReferences().add(new Edge("entry_" + i, entryVertex));
// }
// }
// }
// }
//
// class ArrayHandler implements VertexHandler {
//
// public boolean canHandle(Object subject) {
// return subject.getClass().isArray();
// }
//
// public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) {
// int arrayLength = Array.getLength(subject);
// for (int i = 0; i < arrayLength; i++) {
// Object item = Array.get(subject, i);
// vertexFieldAdder.addField(vertex, i + "", item);
// }
// }
// }
//
// class ClassTypeHandler extends TypeBasedHandler<Class> {
//
// public ClassTypeHandler() {
// super(Class.class);
// }
//
// @Override
// protected void typedHandle(Vertex vertex, Class subject, VertexFieldAdder vertexFieldAdder) {
// vertexFieldAdder.addField(vertex, "name", subject.getName());
// }
// }
//
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/internal/DefaultVertexFactory.java
import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.handlers.VertexHandler;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Set;
package org.laborra.beantrace.internal;
public class DefaultVertexFactory implements VertexFactory {
private final Map<Object, Vertex> visitedMap = new IdentityHashMap<>(); | private final VertexHandler vertexHandler; |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/internal/DefaultVertexFactory.java | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/handlers/VertexHandler.java
// public interface VertexHandler {
//
// /**
// * Specifies if this handler can manage the subject.
// */
// boolean canHandle(Object subject);
//
// /**
// * Handle the passed vertex based on the subject.
// */
// void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder);
//
// class Composite implements VertexHandler {
//
// private final List<VertexHandler> delegates;
//
// public Composite(List<VertexHandler> delegates) {
// this.delegates = delegates;
// }
//
// @Override
// public boolean canHandle(Object subject) {
// for (VertexHandler vertexHandler : delegates) {
// if (vertexHandler.canHandle(subject)) {
// return true;
// }
// }
//
// return false;
// }
//
// @Override
// public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) {
// for (VertexHandler vertexHandler : delegates) {
// if (vertexHandler.canHandle(subject)) {
// vertexHandler.handle(vertex, subject, vertexFieldAdder);
// return;
// }
// }
// }
// }
//
// class MapVertexHandler extends TypeBasedHandler<Map<Object, Object>> {
//
// public MapVertexHandler() {
// super(Map.class);
// }
//
// @Override
// public void typedHandle(Vertex vertex, Map<Object, Object> subject, VertexFieldAdder vertexFieldAdder) {
// int i = -1;
// for (Map.Entry<Object, Object> entry : subject.entrySet()) {
// i++;
// final Object key = entry.getKey();
// final Object value = entry.getValue();
// final boolean primitiveKey = ReflectUtils.isPrimitive(key.getClass());
//
// if (primitiveKey) {
// vertexFieldAdder.addField(vertex, key.toString(), value);
// }
//
// if (!primitiveKey) {
// final Vertex entryVertex = new Vertex(Map.Entry.class, System.identityHashCode(entry) + "");
// vertexFieldAdder.addField(entryVertex, "key", key);
// vertexFieldAdder.addField(entryVertex, "value", value);
// vertex.getReferences().add(new Edge("entry_" + i, entryVertex));
// }
// }
// }
// }
//
// class ArrayHandler implements VertexHandler {
//
// public boolean canHandle(Object subject) {
// return subject.getClass().isArray();
// }
//
// public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) {
// int arrayLength = Array.getLength(subject);
// for (int i = 0; i < arrayLength; i++) {
// Object item = Array.get(subject, i);
// vertexFieldAdder.addField(vertex, i + "", item);
// }
// }
// }
//
// class ClassTypeHandler extends TypeBasedHandler<Class> {
//
// public ClassTypeHandler() {
// super(Class.class);
// }
//
// @Override
// protected void typedHandle(Vertex vertex, Class subject, VertexFieldAdder vertexFieldAdder) {
// vertexFieldAdder.addField(vertex, "name", subject.getName());
// }
// }
//
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.handlers.VertexHandler;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Set; | package org.laborra.beantrace.internal;
public class DefaultVertexFactory implements VertexFactory {
private final Map<Object, Vertex> visitedMap = new IdentityHashMap<>();
private final VertexHandler vertexHandler; | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/handlers/VertexHandler.java
// public interface VertexHandler {
//
// /**
// * Specifies if this handler can manage the subject.
// */
// boolean canHandle(Object subject);
//
// /**
// * Handle the passed vertex based on the subject.
// */
// void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder);
//
// class Composite implements VertexHandler {
//
// private final List<VertexHandler> delegates;
//
// public Composite(List<VertexHandler> delegates) {
// this.delegates = delegates;
// }
//
// @Override
// public boolean canHandle(Object subject) {
// for (VertexHandler vertexHandler : delegates) {
// if (vertexHandler.canHandle(subject)) {
// return true;
// }
// }
//
// return false;
// }
//
// @Override
// public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) {
// for (VertexHandler vertexHandler : delegates) {
// if (vertexHandler.canHandle(subject)) {
// vertexHandler.handle(vertex, subject, vertexFieldAdder);
// return;
// }
// }
// }
// }
//
// class MapVertexHandler extends TypeBasedHandler<Map<Object, Object>> {
//
// public MapVertexHandler() {
// super(Map.class);
// }
//
// @Override
// public void typedHandle(Vertex vertex, Map<Object, Object> subject, VertexFieldAdder vertexFieldAdder) {
// int i = -1;
// for (Map.Entry<Object, Object> entry : subject.entrySet()) {
// i++;
// final Object key = entry.getKey();
// final Object value = entry.getValue();
// final boolean primitiveKey = ReflectUtils.isPrimitive(key.getClass());
//
// if (primitiveKey) {
// vertexFieldAdder.addField(vertex, key.toString(), value);
// }
//
// if (!primitiveKey) {
// final Vertex entryVertex = new Vertex(Map.Entry.class, System.identityHashCode(entry) + "");
// vertexFieldAdder.addField(entryVertex, "key", key);
// vertexFieldAdder.addField(entryVertex, "value", value);
// vertex.getReferences().add(new Edge("entry_" + i, entryVertex));
// }
// }
// }
// }
//
// class ArrayHandler implements VertexHandler {
//
// public boolean canHandle(Object subject) {
// return subject.getClass().isArray();
// }
//
// public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) {
// int arrayLength = Array.getLength(subject);
// for (int i = 0; i < arrayLength; i++) {
// Object item = Array.get(subject, i);
// vertexFieldAdder.addField(vertex, i + "", item);
// }
// }
// }
//
// class ClassTypeHandler extends TypeBasedHandler<Class> {
//
// public ClassTypeHandler() {
// super(Class.class);
// }
//
// @Override
// protected void typedHandle(Vertex vertex, Class subject, VertexFieldAdder vertexFieldAdder) {
// vertexFieldAdder.addField(vertex, "name", subject.getName());
// }
// }
//
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/internal/DefaultVertexFactory.java
import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.handlers.VertexHandler;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Set;
package org.laborra.beantrace.internal;
public class DefaultVertexFactory implements VertexFactory {
private final Map<Object, Vertex> visitedMap = new IdentityHashMap<>();
private final VertexHandler vertexHandler; | private final VertexFieldAdder vertexFieldAdder; |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/handlers/URLTypeHandler.java | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Vertex;
import java.net.URL; | package org.laborra.beantrace.handlers;
class URLTypeHandler extends TypeBasedHandler<URL> {
URLTypeHandler() {
super(URL.class);
}
@Override | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/handlers/URLTypeHandler.java
import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Vertex;
import java.net.URL;
package org.laborra.beantrace.handlers;
class URLTypeHandler extends TypeBasedHandler<URL> {
URLTypeHandler() {
super(URL.class);
}
@Override | protected void typedHandle(Vertex vertex, URL subject, VertexFieldAdder vertexFieldAdder) { |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/handlers/URLTypeHandler.java | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Vertex;
import java.net.URL; | package org.laborra.beantrace.handlers;
class URLTypeHandler extends TypeBasedHandler<URL> {
URLTypeHandler() {
super(URL.class);
}
@Override | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/handlers/URLTypeHandler.java
import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Vertex;
import java.net.URL;
package org.laborra.beantrace.handlers;
class URLTypeHandler extends TypeBasedHandler<URL> {
URLTypeHandler() {
super(URL.class);
}
@Override | protected void typedHandle(Vertex vertex, URL subject, VertexFieldAdder vertexFieldAdder) { |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/handlers/URLTypeHandler.java | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Vertex;
import java.net.URL; | package org.laborra.beantrace.handlers;
class URLTypeHandler extends TypeBasedHandler<URL> {
URLTypeHandler() {
super(URL.class);
}
@Override
protected void typedHandle(Vertex vertex, URL subject, VertexFieldAdder vertexFieldAdder) { | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/handlers/URLTypeHandler.java
import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Vertex;
import java.net.URL;
package org.laborra.beantrace.handlers;
class URLTypeHandler extends TypeBasedHandler<URL> {
URLTypeHandler() {
super(URL.class);
}
@Override
protected void typedHandle(Vertex vertex, URL subject, VertexFieldAdder vertexFieldAdder) { | vertex.getAttributes().add(new Attribute<>("url", subject.toString())); |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/internal/DefaultVertexFieldAdder.java | // Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex; | package org.laborra.beantrace.internal;
/**
* Populates the references and the attributes of the vertex based on the
* passed field of the object.
*/
public class DefaultVertexFieldAdder implements org.laborra.beantrace.VertexFieldAdder {
private final VertexFactory vertexFactory;
public DefaultVertexFieldAdder(VertexFactory vertexFactory) {
this.vertexFactory = vertexFactory;
}
@Override | // Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/internal/DefaultVertexFieldAdder.java
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
package org.laborra.beantrace.internal;
/**
* Populates the references and the attributes of the vertex based on the
* passed field of the object.
*/
public class DefaultVertexFieldAdder implements org.laborra.beantrace.VertexFieldAdder {
private final VertexFactory vertexFactory;
public DefaultVertexFieldAdder(VertexFactory vertexFactory) {
this.vertexFactory = vertexFactory;
}
@Override | public void addField(Vertex vertex, String fieldName, Object item) { |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/internal/DefaultVertexFieldAdder.java | // Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex; | package org.laborra.beantrace.internal;
/**
* Populates the references and the attributes of the vertex based on the
* passed field of the object.
*/
public class DefaultVertexFieldAdder implements org.laborra.beantrace.VertexFieldAdder {
private final VertexFactory vertexFactory;
public DefaultVertexFieldAdder(VertexFactory vertexFactory) {
this.vertexFactory = vertexFactory;
}
@Override
public void addField(Vertex vertex, String fieldName, Object item) {
if (item == null) {
return;
}
if (ReflectUtils.isPrimitive(item.getClass())) { | // Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/internal/DefaultVertexFieldAdder.java
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
package org.laborra.beantrace.internal;
/**
* Populates the references and the attributes of the vertex based on the
* passed field of the object.
*/
public class DefaultVertexFieldAdder implements org.laborra.beantrace.VertexFieldAdder {
private final VertexFactory vertexFactory;
public DefaultVertexFieldAdder(VertexFactory vertexFactory) {
this.vertexFactory = vertexFactory;
}
@Override
public void addField(Vertex vertex, String fieldName, Object item) {
if (item == null) {
return;
}
if (ReflectUtils.isPrimitive(item.getClass())) { | vertex.getAttributes().add(new Attribute<>(fieldName, item)); |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/internal/DefaultVertexFieldAdder.java | // Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex; | package org.laborra.beantrace.internal;
/**
* Populates the references and the attributes of the vertex based on the
* passed field of the object.
*/
public class DefaultVertexFieldAdder implements org.laborra.beantrace.VertexFieldAdder {
private final VertexFactory vertexFactory;
public DefaultVertexFieldAdder(VertexFactory vertexFactory) {
this.vertexFactory = vertexFactory;
}
@Override
public void addField(Vertex vertex, String fieldName, Object item) {
if (item == null) {
return;
}
if (ReflectUtils.isPrimitive(item.getClass())) {
vertex.getAttributes().add(new Attribute<>(fieldName, item));
return;
}
| // Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/internal/DefaultVertexFieldAdder.java
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
package org.laborra.beantrace.internal;
/**
* Populates the references and the attributes of the vertex based on the
* passed field of the object.
*/
public class DefaultVertexFieldAdder implements org.laborra.beantrace.VertexFieldAdder {
private final VertexFactory vertexFactory;
public DefaultVertexFieldAdder(VertexFactory vertexFactory) {
this.vertexFactory = vertexFactory;
}
@Override
public void addField(Vertex vertex, String fieldName, Object item) {
if (item == null) {
return;
}
if (ReflectUtils.isPrimitive(item.getClass())) {
vertex.getAttributes().add(new Attribute<>(fieldName, item));
return;
}
| vertex.getReferences().add(new Edge( |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/renderers/GraphRenderers.java | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
| import org.laborra.beantrace.BeanTraceException;
import java.io.*; | package org.laborra.beantrace.renderers;
/**
* Basic class to create graph renderers. They can be used to draw different king
* of bean traces.
*
* @see org.laborra.beantrace.BeanTraces#printBeanTrace(Object, org.laborra.beantrace.renderers.GraphRenderer)
* @see org.laborra.beantrace.TraceConfiguration#setGraphRenderer(org.laborra.beantrace.renderers.GraphRenderer)
*/
public class GraphRenderers {
/**
* Creates a new {@link GraphvizDotRenderer} that writes the contents to the given
* appendable.
*/
public static GraphvizDotRenderer newGraphviz(Writer output) {
return new GraphvizDotRenderer(output);
}
/**
* Shortcut to create a file graphviz renderer.
*
* @see #newGraphviz(Writer)
*/
public static GraphvizDotRenderer newGraphviz(File outputFile) {
try {
return newGraphviz(new BufferedWriter(new FileWriter(outputFile), 1));
} catch (IOException e) { | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
// Path: src/main/java/org/laborra/beantrace/renderers/GraphRenderers.java
import org.laborra.beantrace.BeanTraceException;
import java.io.*;
package org.laborra.beantrace.renderers;
/**
* Basic class to create graph renderers. They can be used to draw different king
* of bean traces.
*
* @see org.laborra.beantrace.BeanTraces#printBeanTrace(Object, org.laborra.beantrace.renderers.GraphRenderer)
* @see org.laborra.beantrace.TraceConfiguration#setGraphRenderer(org.laborra.beantrace.renderers.GraphRenderer)
*/
public class GraphRenderers {
/**
* Creates a new {@link GraphvizDotRenderer} that writes the contents to the given
* appendable.
*/
public static GraphvizDotRenderer newGraphviz(Writer output) {
return new GraphvizDotRenderer(output);
}
/**
* Shortcut to create a file graphviz renderer.
*
* @see #newGraphviz(Writer)
*/
public static GraphvizDotRenderer newGraphviz(File outputFile) {
try {
return newGraphviz(new BufferedWriter(new FileWriter(outputFile), 1));
} catch (IOException e) { | throw new BeanTraceException(e); |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/renderers/GraphvizDotRenderer.java | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/Graphs.java
// public class Graphs {
//
// /**
// * Collect all vertices in the given graph.
// *
// * @param root A vertex contained in the graph
// * @return A collection with all vertices
// */
// public static Collection<Vertex> collectAllVertices(Vertex root) {
// final CollectorVisitor collectorVisitor = new CollectorVisitor();
// traverse(root, collectorVisitor);
// return collectorVisitor.getResult();
// }
//
// /**
// * Traverse the graph where the root is contained with the given visitor.
// *
// * @param root The starting vertex
// * @param visitor The visitor to apply to all vertices
// */
// public static void traverse(Vertex root, VertexVisitor visitor) {
// traverse(root, visitor, new HashSet<Vertex>());
// }
//
// private static void traverse(Vertex vertex, VertexVisitor visitor, Set<Vertex> visited) {
// if (visited.contains(vertex)) {
// return;
// }
// visited.add(vertex);
//
// visitor.visit(vertex);
//
// final Set<Edge> references = vertex.getReferences();
// for (Edge reference : references) {
// traverse(reference.getTo(), visitor, visited);
// }
// }
//
// /**
// * Return a map view of the graph edges, where each key is an edge and the value is the
// * vertex the edge start from.
// *
// * @param subject The root vertex of the graph
// * @return The map representing the graph
// */
// public static Map<Edge, Vertex> mapEdgeToStartingVertex(Vertex subject) {
// final Map<Edge, Vertex> edgeMap = new HashMap<>();
// traverse(subject, new VertexVisitor() {
// @Override
// public void visit(Vertex vertex) {
// for (Edge edge : vertex.getReferences()) {
// edgeMap.put(edge, vertex);
// }
// }
// });
// return edgeMap;
// }
//
// public static Map<Vertex, Integer> mapVerticesToIndex(Collection<Vertex> vertices) {
// final Map<Vertex, Integer> vertexToIndexMap = new HashMap<>();
// int i=0;
// for (Vertex vertex : vertices) {
// vertexToIndexMap.put(vertex, i);
// i++;
// }
// return vertexToIndexMap;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.internal.Graphs;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.Writer;
import java.util.Collection;
import java.util.Map;
import java.util.Set; | package org.laborra.beantrace.renderers;
public class GraphvizDotRenderer implements GraphRenderer {
private final Writer writer;
public GraphvizDotRenderer(Writer writer) {
this.writer = writer;
}
@Override | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/Graphs.java
// public class Graphs {
//
// /**
// * Collect all vertices in the given graph.
// *
// * @param root A vertex contained in the graph
// * @return A collection with all vertices
// */
// public static Collection<Vertex> collectAllVertices(Vertex root) {
// final CollectorVisitor collectorVisitor = new CollectorVisitor();
// traverse(root, collectorVisitor);
// return collectorVisitor.getResult();
// }
//
// /**
// * Traverse the graph where the root is contained with the given visitor.
// *
// * @param root The starting vertex
// * @param visitor The visitor to apply to all vertices
// */
// public static void traverse(Vertex root, VertexVisitor visitor) {
// traverse(root, visitor, new HashSet<Vertex>());
// }
//
// private static void traverse(Vertex vertex, VertexVisitor visitor, Set<Vertex> visited) {
// if (visited.contains(vertex)) {
// return;
// }
// visited.add(vertex);
//
// visitor.visit(vertex);
//
// final Set<Edge> references = vertex.getReferences();
// for (Edge reference : references) {
// traverse(reference.getTo(), visitor, visited);
// }
// }
//
// /**
// * Return a map view of the graph edges, where each key is an edge and the value is the
// * vertex the edge start from.
// *
// * @param subject The root vertex of the graph
// * @return The map representing the graph
// */
// public static Map<Edge, Vertex> mapEdgeToStartingVertex(Vertex subject) {
// final Map<Edge, Vertex> edgeMap = new HashMap<>();
// traverse(subject, new VertexVisitor() {
// @Override
// public void visit(Vertex vertex) {
// for (Edge edge : vertex.getReferences()) {
// edgeMap.put(edge, vertex);
// }
// }
// });
// return edgeMap;
// }
//
// public static Map<Vertex, Integer> mapVerticesToIndex(Collection<Vertex> vertices) {
// final Map<Vertex, Integer> vertexToIndexMap = new HashMap<>();
// int i=0;
// for (Vertex vertex : vertices) {
// vertexToIndexMap.put(vertex, i);
// i++;
// }
// return vertexToIndexMap;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/renderers/GraphvizDotRenderer.java
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.internal.Graphs;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.Writer;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
package org.laborra.beantrace.renderers;
public class GraphvizDotRenderer implements GraphRenderer {
private final Writer writer;
public GraphvizDotRenderer(Writer writer) {
this.writer = writer;
}
@Override | public void render(Vertex subject) { |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/renderers/GraphvizDotRenderer.java | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/Graphs.java
// public class Graphs {
//
// /**
// * Collect all vertices in the given graph.
// *
// * @param root A vertex contained in the graph
// * @return A collection with all vertices
// */
// public static Collection<Vertex> collectAllVertices(Vertex root) {
// final CollectorVisitor collectorVisitor = new CollectorVisitor();
// traverse(root, collectorVisitor);
// return collectorVisitor.getResult();
// }
//
// /**
// * Traverse the graph where the root is contained with the given visitor.
// *
// * @param root The starting vertex
// * @param visitor The visitor to apply to all vertices
// */
// public static void traverse(Vertex root, VertexVisitor visitor) {
// traverse(root, visitor, new HashSet<Vertex>());
// }
//
// private static void traverse(Vertex vertex, VertexVisitor visitor, Set<Vertex> visited) {
// if (visited.contains(vertex)) {
// return;
// }
// visited.add(vertex);
//
// visitor.visit(vertex);
//
// final Set<Edge> references = vertex.getReferences();
// for (Edge reference : references) {
// traverse(reference.getTo(), visitor, visited);
// }
// }
//
// /**
// * Return a map view of the graph edges, where each key is an edge and the value is the
// * vertex the edge start from.
// *
// * @param subject The root vertex of the graph
// * @return The map representing the graph
// */
// public static Map<Edge, Vertex> mapEdgeToStartingVertex(Vertex subject) {
// final Map<Edge, Vertex> edgeMap = new HashMap<>();
// traverse(subject, new VertexVisitor() {
// @Override
// public void visit(Vertex vertex) {
// for (Edge edge : vertex.getReferences()) {
// edgeMap.put(edge, vertex);
// }
// }
// });
// return edgeMap;
// }
//
// public static Map<Vertex, Integer> mapVerticesToIndex(Collection<Vertex> vertices) {
// final Map<Vertex, Integer> vertexToIndexMap = new HashMap<>();
// int i=0;
// for (Vertex vertex : vertices) {
// vertexToIndexMap.put(vertex, i);
// i++;
// }
// return vertexToIndexMap;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.internal.Graphs;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.Writer;
import java.util.Collection;
import java.util.Map;
import java.util.Set; | package org.laborra.beantrace.renderers;
public class GraphvizDotRenderer implements GraphRenderer {
private final Writer writer;
public GraphvizDotRenderer(Writer writer) {
this.writer = writer;
}
@Override
public void render(Vertex subject) { | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/Graphs.java
// public class Graphs {
//
// /**
// * Collect all vertices in the given graph.
// *
// * @param root A vertex contained in the graph
// * @return A collection with all vertices
// */
// public static Collection<Vertex> collectAllVertices(Vertex root) {
// final CollectorVisitor collectorVisitor = new CollectorVisitor();
// traverse(root, collectorVisitor);
// return collectorVisitor.getResult();
// }
//
// /**
// * Traverse the graph where the root is contained with the given visitor.
// *
// * @param root The starting vertex
// * @param visitor The visitor to apply to all vertices
// */
// public static void traverse(Vertex root, VertexVisitor visitor) {
// traverse(root, visitor, new HashSet<Vertex>());
// }
//
// private static void traverse(Vertex vertex, VertexVisitor visitor, Set<Vertex> visited) {
// if (visited.contains(vertex)) {
// return;
// }
// visited.add(vertex);
//
// visitor.visit(vertex);
//
// final Set<Edge> references = vertex.getReferences();
// for (Edge reference : references) {
// traverse(reference.getTo(), visitor, visited);
// }
// }
//
// /**
// * Return a map view of the graph edges, where each key is an edge and the value is the
// * vertex the edge start from.
// *
// * @param subject The root vertex of the graph
// * @return The map representing the graph
// */
// public static Map<Edge, Vertex> mapEdgeToStartingVertex(Vertex subject) {
// final Map<Edge, Vertex> edgeMap = new HashMap<>();
// traverse(subject, new VertexVisitor() {
// @Override
// public void visit(Vertex vertex) {
// for (Edge edge : vertex.getReferences()) {
// edgeMap.put(edge, vertex);
// }
// }
// });
// return edgeMap;
// }
//
// public static Map<Vertex, Integer> mapVerticesToIndex(Collection<Vertex> vertices) {
// final Map<Vertex, Integer> vertexToIndexMap = new HashMap<>();
// int i=0;
// for (Vertex vertex : vertices) {
// vertexToIndexMap.put(vertex, i);
// i++;
// }
// return vertexToIndexMap;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/renderers/GraphvizDotRenderer.java
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.internal.Graphs;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.Writer;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
package org.laborra.beantrace.renderers;
public class GraphvizDotRenderer implements GraphRenderer {
private final Writer writer;
public GraphvizDotRenderer(Writer writer) {
this.writer = writer;
}
@Override
public void render(Vertex subject) { | final Collection<Vertex> vertices = Graphs.collectAllVertices(subject); |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/renderers/GraphvizDotRenderer.java | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/Graphs.java
// public class Graphs {
//
// /**
// * Collect all vertices in the given graph.
// *
// * @param root A vertex contained in the graph
// * @return A collection with all vertices
// */
// public static Collection<Vertex> collectAllVertices(Vertex root) {
// final CollectorVisitor collectorVisitor = new CollectorVisitor();
// traverse(root, collectorVisitor);
// return collectorVisitor.getResult();
// }
//
// /**
// * Traverse the graph where the root is contained with the given visitor.
// *
// * @param root The starting vertex
// * @param visitor The visitor to apply to all vertices
// */
// public static void traverse(Vertex root, VertexVisitor visitor) {
// traverse(root, visitor, new HashSet<Vertex>());
// }
//
// private static void traverse(Vertex vertex, VertexVisitor visitor, Set<Vertex> visited) {
// if (visited.contains(vertex)) {
// return;
// }
// visited.add(vertex);
//
// visitor.visit(vertex);
//
// final Set<Edge> references = vertex.getReferences();
// for (Edge reference : references) {
// traverse(reference.getTo(), visitor, visited);
// }
// }
//
// /**
// * Return a map view of the graph edges, where each key is an edge and the value is the
// * vertex the edge start from.
// *
// * @param subject The root vertex of the graph
// * @return The map representing the graph
// */
// public static Map<Edge, Vertex> mapEdgeToStartingVertex(Vertex subject) {
// final Map<Edge, Vertex> edgeMap = new HashMap<>();
// traverse(subject, new VertexVisitor() {
// @Override
// public void visit(Vertex vertex) {
// for (Edge edge : vertex.getReferences()) {
// edgeMap.put(edge, vertex);
// }
// }
// });
// return edgeMap;
// }
//
// public static Map<Vertex, Integer> mapVerticesToIndex(Collection<Vertex> vertices) {
// final Map<Vertex, Integer> vertexToIndexMap = new HashMap<>();
// int i=0;
// for (Vertex vertex : vertices) {
// vertexToIndexMap.put(vertex, i);
// i++;
// }
// return vertexToIndexMap;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.internal.Graphs;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.Writer;
import java.util.Collection;
import java.util.Map;
import java.util.Set; | package org.laborra.beantrace.renderers;
public class GraphvizDotRenderer implements GraphRenderer {
private final Writer writer;
public GraphvizDotRenderer(Writer writer) {
this.writer = writer;
}
@Override
public void render(Vertex subject) {
final Collection<Vertex> vertices = Graphs.collectAllVertices(subject); | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/Graphs.java
// public class Graphs {
//
// /**
// * Collect all vertices in the given graph.
// *
// * @param root A vertex contained in the graph
// * @return A collection with all vertices
// */
// public static Collection<Vertex> collectAllVertices(Vertex root) {
// final CollectorVisitor collectorVisitor = new CollectorVisitor();
// traverse(root, collectorVisitor);
// return collectorVisitor.getResult();
// }
//
// /**
// * Traverse the graph where the root is contained with the given visitor.
// *
// * @param root The starting vertex
// * @param visitor The visitor to apply to all vertices
// */
// public static void traverse(Vertex root, VertexVisitor visitor) {
// traverse(root, visitor, new HashSet<Vertex>());
// }
//
// private static void traverse(Vertex vertex, VertexVisitor visitor, Set<Vertex> visited) {
// if (visited.contains(vertex)) {
// return;
// }
// visited.add(vertex);
//
// visitor.visit(vertex);
//
// final Set<Edge> references = vertex.getReferences();
// for (Edge reference : references) {
// traverse(reference.getTo(), visitor, visited);
// }
// }
//
// /**
// * Return a map view of the graph edges, where each key is an edge and the value is the
// * vertex the edge start from.
// *
// * @param subject The root vertex of the graph
// * @return The map representing the graph
// */
// public static Map<Edge, Vertex> mapEdgeToStartingVertex(Vertex subject) {
// final Map<Edge, Vertex> edgeMap = new HashMap<>();
// traverse(subject, new VertexVisitor() {
// @Override
// public void visit(Vertex vertex) {
// for (Edge edge : vertex.getReferences()) {
// edgeMap.put(edge, vertex);
// }
// }
// });
// return edgeMap;
// }
//
// public static Map<Vertex, Integer> mapVerticesToIndex(Collection<Vertex> vertices) {
// final Map<Vertex, Integer> vertexToIndexMap = new HashMap<>();
// int i=0;
// for (Vertex vertex : vertices) {
// vertexToIndexMap.put(vertex, i);
// i++;
// }
// return vertexToIndexMap;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/renderers/GraphvizDotRenderer.java
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.internal.Graphs;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.Writer;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
package org.laborra.beantrace.renderers;
public class GraphvizDotRenderer implements GraphRenderer {
private final Writer writer;
public GraphvizDotRenderer(Writer writer) {
this.writer = writer;
}
@Override
public void render(Vertex subject) {
final Collection<Vertex> vertices = Graphs.collectAllVertices(subject); | final Map<Edge, Vertex> edgeMap = Graphs.mapEdgeToStartingVertex(subject); |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/renderers/GraphvizDotRenderer.java | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/Graphs.java
// public class Graphs {
//
// /**
// * Collect all vertices in the given graph.
// *
// * @param root A vertex contained in the graph
// * @return A collection with all vertices
// */
// public static Collection<Vertex> collectAllVertices(Vertex root) {
// final CollectorVisitor collectorVisitor = new CollectorVisitor();
// traverse(root, collectorVisitor);
// return collectorVisitor.getResult();
// }
//
// /**
// * Traverse the graph where the root is contained with the given visitor.
// *
// * @param root The starting vertex
// * @param visitor The visitor to apply to all vertices
// */
// public static void traverse(Vertex root, VertexVisitor visitor) {
// traverse(root, visitor, new HashSet<Vertex>());
// }
//
// private static void traverse(Vertex vertex, VertexVisitor visitor, Set<Vertex> visited) {
// if (visited.contains(vertex)) {
// return;
// }
// visited.add(vertex);
//
// visitor.visit(vertex);
//
// final Set<Edge> references = vertex.getReferences();
// for (Edge reference : references) {
// traverse(reference.getTo(), visitor, visited);
// }
// }
//
// /**
// * Return a map view of the graph edges, where each key is an edge and the value is the
// * vertex the edge start from.
// *
// * @param subject The root vertex of the graph
// * @return The map representing the graph
// */
// public static Map<Edge, Vertex> mapEdgeToStartingVertex(Vertex subject) {
// final Map<Edge, Vertex> edgeMap = new HashMap<>();
// traverse(subject, new VertexVisitor() {
// @Override
// public void visit(Vertex vertex) {
// for (Edge edge : vertex.getReferences()) {
// edgeMap.put(edge, vertex);
// }
// }
// });
// return edgeMap;
// }
//
// public static Map<Vertex, Integer> mapVerticesToIndex(Collection<Vertex> vertices) {
// final Map<Vertex, Integer> vertexToIndexMap = new HashMap<>();
// int i=0;
// for (Vertex vertex : vertices) {
// vertexToIndexMap.put(vertex, i);
// i++;
// }
// return vertexToIndexMap;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.internal.Graphs;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.Writer;
import java.util.Collection;
import java.util.Map;
import java.util.Set; | package org.laborra.beantrace.renderers;
public class GraphvizDotRenderer implements GraphRenderer {
private final Writer writer;
public GraphvizDotRenderer(Writer writer) {
this.writer = writer;
}
@Override
public void render(Vertex subject) {
final Collection<Vertex> vertices = Graphs.collectAllVertices(subject);
final Map<Edge, Vertex> edgeMap = Graphs.mapEdgeToStartingVertex(subject);
try (Writer output = writer) {
output.append(getHeader())
.append(formatEdges(edgeMap))
.append(formatVertices(vertices))
.append(getFooter());
} catch (IOException e) { | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/Graphs.java
// public class Graphs {
//
// /**
// * Collect all vertices in the given graph.
// *
// * @param root A vertex contained in the graph
// * @return A collection with all vertices
// */
// public static Collection<Vertex> collectAllVertices(Vertex root) {
// final CollectorVisitor collectorVisitor = new CollectorVisitor();
// traverse(root, collectorVisitor);
// return collectorVisitor.getResult();
// }
//
// /**
// * Traverse the graph where the root is contained with the given visitor.
// *
// * @param root The starting vertex
// * @param visitor The visitor to apply to all vertices
// */
// public static void traverse(Vertex root, VertexVisitor visitor) {
// traverse(root, visitor, new HashSet<Vertex>());
// }
//
// private static void traverse(Vertex vertex, VertexVisitor visitor, Set<Vertex> visited) {
// if (visited.contains(vertex)) {
// return;
// }
// visited.add(vertex);
//
// visitor.visit(vertex);
//
// final Set<Edge> references = vertex.getReferences();
// for (Edge reference : references) {
// traverse(reference.getTo(), visitor, visited);
// }
// }
//
// /**
// * Return a map view of the graph edges, where each key is an edge and the value is the
// * vertex the edge start from.
// *
// * @param subject The root vertex of the graph
// * @return The map representing the graph
// */
// public static Map<Edge, Vertex> mapEdgeToStartingVertex(Vertex subject) {
// final Map<Edge, Vertex> edgeMap = new HashMap<>();
// traverse(subject, new VertexVisitor() {
// @Override
// public void visit(Vertex vertex) {
// for (Edge edge : vertex.getReferences()) {
// edgeMap.put(edge, vertex);
// }
// }
// });
// return edgeMap;
// }
//
// public static Map<Vertex, Integer> mapVerticesToIndex(Collection<Vertex> vertices) {
// final Map<Vertex, Integer> vertexToIndexMap = new HashMap<>();
// int i=0;
// for (Vertex vertex : vertices) {
// vertexToIndexMap.put(vertex, i);
// i++;
// }
// return vertexToIndexMap;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/renderers/GraphvizDotRenderer.java
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.internal.Graphs;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.Writer;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
package org.laborra.beantrace.renderers;
public class GraphvizDotRenderer implements GraphRenderer {
private final Writer writer;
public GraphvizDotRenderer(Writer writer) {
this.writer = writer;
}
@Override
public void render(Vertex subject) {
final Collection<Vertex> vertices = Graphs.collectAllVertices(subject);
final Map<Edge, Vertex> edgeMap = Graphs.mapEdgeToStartingVertex(subject);
try (Writer output = writer) {
output.append(getHeader())
.append(formatEdges(edgeMap))
.append(formatVertices(vertices))
.append(getFooter());
} catch (IOException e) { | throw new BeanTraceException(e); |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/renderers/GraphvizDotRenderer.java | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/Graphs.java
// public class Graphs {
//
// /**
// * Collect all vertices in the given graph.
// *
// * @param root A vertex contained in the graph
// * @return A collection with all vertices
// */
// public static Collection<Vertex> collectAllVertices(Vertex root) {
// final CollectorVisitor collectorVisitor = new CollectorVisitor();
// traverse(root, collectorVisitor);
// return collectorVisitor.getResult();
// }
//
// /**
// * Traverse the graph where the root is contained with the given visitor.
// *
// * @param root The starting vertex
// * @param visitor The visitor to apply to all vertices
// */
// public static void traverse(Vertex root, VertexVisitor visitor) {
// traverse(root, visitor, new HashSet<Vertex>());
// }
//
// private static void traverse(Vertex vertex, VertexVisitor visitor, Set<Vertex> visited) {
// if (visited.contains(vertex)) {
// return;
// }
// visited.add(vertex);
//
// visitor.visit(vertex);
//
// final Set<Edge> references = vertex.getReferences();
// for (Edge reference : references) {
// traverse(reference.getTo(), visitor, visited);
// }
// }
//
// /**
// * Return a map view of the graph edges, where each key is an edge and the value is the
// * vertex the edge start from.
// *
// * @param subject The root vertex of the graph
// * @return The map representing the graph
// */
// public static Map<Edge, Vertex> mapEdgeToStartingVertex(Vertex subject) {
// final Map<Edge, Vertex> edgeMap = new HashMap<>();
// traverse(subject, new VertexVisitor() {
// @Override
// public void visit(Vertex vertex) {
// for (Edge edge : vertex.getReferences()) {
// edgeMap.put(edge, vertex);
// }
// }
// });
// return edgeMap;
// }
//
// public static Map<Vertex, Integer> mapVerticesToIndex(Collection<Vertex> vertices) {
// final Map<Vertex, Integer> vertexToIndexMap = new HashMap<>();
// int i=0;
// for (Vertex vertex : vertices) {
// vertexToIndexMap.put(vertex, i);
// i++;
// }
// return vertexToIndexMap;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.internal.Graphs;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.Writer;
import java.util.Collection;
import java.util.Map;
import java.util.Set; | throw new BeanTraceException(e);
}
}
private static String getHeader() {
return "digraph bean_trace {\n";
}
private String formatEdges(final Map<Edge, Vertex> edgeMap) {
final Iterable<String> chunks = Iterables.transform(edgeMap.entrySet(), new Function<Map.Entry<Edge, Vertex>, String>() {
@Override
public String apply(Map.Entry<Edge, Vertex> input) {
return input.getValue().getId() + " -> " + input.getKey().getTo().getId() + " [label=\"" + input.getKey().getName() + "\"];";
}
});
return Joiner.on("\n").join(chunks);
}
private String formatVertices(Collection<Vertex> vertices) {
final Iterable<String> chunks = Iterables.transform(vertices, new Function<Vertex, String>() {
@Override
public String apply(Vertex input) {
final StringBuilder sb = new StringBuilder(input.getId())
.append(" [shape=none margin=0 ")
.append("label=<<TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\" CELLPADDING=\"4\">")
.append("<TR><TD BGCOLOR=\"lightgrey\" COLSPAN=\"2\">")
.append(input.getClazz().getSimpleName())
.append("</TD></TR>");
| // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/Graphs.java
// public class Graphs {
//
// /**
// * Collect all vertices in the given graph.
// *
// * @param root A vertex contained in the graph
// * @return A collection with all vertices
// */
// public static Collection<Vertex> collectAllVertices(Vertex root) {
// final CollectorVisitor collectorVisitor = new CollectorVisitor();
// traverse(root, collectorVisitor);
// return collectorVisitor.getResult();
// }
//
// /**
// * Traverse the graph where the root is contained with the given visitor.
// *
// * @param root The starting vertex
// * @param visitor The visitor to apply to all vertices
// */
// public static void traverse(Vertex root, VertexVisitor visitor) {
// traverse(root, visitor, new HashSet<Vertex>());
// }
//
// private static void traverse(Vertex vertex, VertexVisitor visitor, Set<Vertex> visited) {
// if (visited.contains(vertex)) {
// return;
// }
// visited.add(vertex);
//
// visitor.visit(vertex);
//
// final Set<Edge> references = vertex.getReferences();
// for (Edge reference : references) {
// traverse(reference.getTo(), visitor, visited);
// }
// }
//
// /**
// * Return a map view of the graph edges, where each key is an edge and the value is the
// * vertex the edge start from.
// *
// * @param subject The root vertex of the graph
// * @return The map representing the graph
// */
// public static Map<Edge, Vertex> mapEdgeToStartingVertex(Vertex subject) {
// final Map<Edge, Vertex> edgeMap = new HashMap<>();
// traverse(subject, new VertexVisitor() {
// @Override
// public void visit(Vertex vertex) {
// for (Edge edge : vertex.getReferences()) {
// edgeMap.put(edge, vertex);
// }
// }
// });
// return edgeMap;
// }
//
// public static Map<Vertex, Integer> mapVerticesToIndex(Collection<Vertex> vertices) {
// final Map<Vertex, Integer> vertexToIndexMap = new HashMap<>();
// int i=0;
// for (Vertex vertex : vertices) {
// vertexToIndexMap.put(vertex, i);
// i++;
// }
// return vertexToIndexMap;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/renderers/GraphvizDotRenderer.java
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.internal.Graphs;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.Writer;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
throw new BeanTraceException(e);
}
}
private static String getHeader() {
return "digraph bean_trace {\n";
}
private String formatEdges(final Map<Edge, Vertex> edgeMap) {
final Iterable<String> chunks = Iterables.transform(edgeMap.entrySet(), new Function<Map.Entry<Edge, Vertex>, String>() {
@Override
public String apply(Map.Entry<Edge, Vertex> input) {
return input.getValue().getId() + " -> " + input.getKey().getTo().getId() + " [label=\"" + input.getKey().getName() + "\"];";
}
});
return Joiner.on("\n").join(chunks);
}
private String formatVertices(Collection<Vertex> vertices) {
final Iterable<String> chunks = Iterables.transform(vertices, new Function<Vertex, String>() {
@Override
public String apply(Vertex input) {
final StringBuilder sb = new StringBuilder(input.getId())
.append(" [shape=none margin=0 ")
.append("label=<<TABLE BORDER=\"0\" CELLBORDER=\"1\" CELLSPACING=\"0\" CELLPADDING=\"4\">")
.append("<TR><TD BGCOLOR=\"lightgrey\" COLSPAN=\"2\">")
.append(input.getClazz().getSimpleName())
.append("</TD></TR>");
| final Set<Attribute> attributes = input.getAttributes(); |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/handlers/CollectionHandler.java | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.model.Vertex;
import java.util.Collection; | package org.laborra.beantrace.handlers;
class CollectionHandler extends TypeBasedHandler<Collection<Object>> {
public CollectionHandler() {
super(Collection.class);
}
@Override | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/handlers/CollectionHandler.java
import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.model.Vertex;
import java.util.Collection;
package org.laborra.beantrace.handlers;
class CollectionHandler extends TypeBasedHandler<Collection<Object>> {
public CollectionHandler() {
super(Collection.class);
}
@Override | protected void typedHandle(Vertex vertex, Collection<Object> subject, VertexFieldAdder vertexFieldAdder) { |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/handlers/CollectionHandler.java | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.model.Vertex;
import java.util.Collection; | package org.laborra.beantrace.handlers;
class CollectionHandler extends TypeBasedHandler<Collection<Object>> {
public CollectionHandler() {
super(Collection.class);
}
@Override | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/handlers/CollectionHandler.java
import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.model.Vertex;
import java.util.Collection;
package org.laborra.beantrace.handlers;
class CollectionHandler extends TypeBasedHandler<Collection<Object>> {
public CollectionHandler() {
super(Collection.class);
}
@Override | protected void typedHandle(Vertex vertex, Collection<Object> subject, VertexFieldAdder vertexFieldAdder) { |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/internal/MaxDepthVertexFactoryDecorator.java | // Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Vertex; | package org.laborra.beantrace.internal;
/**
* This decorator implements the stop-on-depth logic.
*
* @see org.laborra.beantrace.TraceConfiguration#maxDepth
*/
public class MaxDepthVertexFactoryDecorator implements VertexFactory {
private final Integer maxDepth;
private final VertexFactory delegate;
private Integer depth = 1;
public MaxDepthVertexFactoryDecorator(Integer maxDepth, VertexFactory delegate) {
this.maxDepth = maxDepth;
this.delegate = delegate;
}
@Override | // Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/internal/MaxDepthVertexFactoryDecorator.java
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Vertex;
package org.laborra.beantrace.internal;
/**
* This decorator implements the stop-on-depth logic.
*
* @see org.laborra.beantrace.TraceConfiguration#maxDepth
*/
public class MaxDepthVertexFactoryDecorator implements VertexFactory {
private final Integer maxDepth;
private final VertexFactory delegate;
private Integer depth = 1;
public MaxDepthVertexFactoryDecorator(Integer maxDepth, VertexFactory delegate) {
this.maxDepth = maxDepth;
this.delegate = delegate;
}
@Override | public Vertex create(Object subject) { |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/internal/MaxDepthVertexFactoryDecorator.java | // Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Vertex; | package org.laborra.beantrace.internal;
/**
* This decorator implements the stop-on-depth logic.
*
* @see org.laborra.beantrace.TraceConfiguration#maxDepth
*/
public class MaxDepthVertexFactoryDecorator implements VertexFactory {
private final Integer maxDepth;
private final VertexFactory delegate;
private Integer depth = 1;
public MaxDepthVertexFactoryDecorator(Integer maxDepth, VertexFactory delegate) {
this.maxDepth = maxDepth;
this.delegate = delegate;
}
@Override
public Vertex create(Object subject) {
if (depth >= maxDepth) {
return makeProxy(subject);
}
try {
depth++;
return delegate.create(subject);
} finally {
depth--;
}
}
private Vertex makeProxy(Object subject) {
final Vertex ret = new Vertex(
subject.getClass(),
System.identityHashCode(subject) + ""
);
| // Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/internal/MaxDepthVertexFactoryDecorator.java
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Vertex;
package org.laborra.beantrace.internal;
/**
* This decorator implements the stop-on-depth logic.
*
* @see org.laborra.beantrace.TraceConfiguration#maxDepth
*/
public class MaxDepthVertexFactoryDecorator implements VertexFactory {
private final Integer maxDepth;
private final VertexFactory delegate;
private Integer depth = 1;
public MaxDepthVertexFactoryDecorator(Integer maxDepth, VertexFactory delegate) {
this.maxDepth = maxDepth;
this.delegate = delegate;
}
@Override
public Vertex create(Object subject) {
if (depth >= maxDepth) {
return makeProxy(subject);
}
try {
depth++;
return delegate.create(subject);
} finally {
depth--;
}
}
private Vertex makeProxy(Object subject) {
final Vertex ret = new Vertex(
subject.getClass(),
System.identityHashCode(subject) + ""
);
| ret.getAttributes().add(new Attribute<>("...", "...")); |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/handlers/VertexHandler.java | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/ReflectUtils.java
// public class ReflectUtils {
//
// private static final Set<Class> PRIMITIVE_TYPES = Sets.newHashSet(
// (Class) Integer.class, Long.class, String.class, Boolean.class, Byte.class,
// Character.class, Float.class, Double.class, Short.class
// );
//
// /**
// * Returns true if the given type is intended to be "primitive" by the library
// *
// * @param type The class to check
// * @return True if the give type is primitive, false otherwise
// */
// public static boolean isPrimitive(Class<?> type) {
// return type.isPrimitive() || PRIMITIVE_TYPES.contains(type);
// }
//
// public static List<Field> getFieldFromClassHierarchy(Class<?> clazz) {
// if (Object.class.equals(clazz)) {
// return Collections.emptyList();
// }
// final ArrayList<Field> fields = Lists.newArrayList(clazz.getDeclaredFields());
// fields.addAll(getFieldFromClassHierarchy(clazz.getSuperclass()));
// return fields;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.internal.ReflectUtils;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.lang.reflect.Array;
import java.util.List;
import java.util.Map; | package org.laborra.beantrace.handlers;
/**
* Manages the setup of a vertex based on the passed subject.
*/
public interface VertexHandler {
/**
* Specifies if this handler can manage the subject.
*/
boolean canHandle(Object subject);
/**
* Handle the passed vertex based on the subject.
*/ | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/ReflectUtils.java
// public class ReflectUtils {
//
// private static final Set<Class> PRIMITIVE_TYPES = Sets.newHashSet(
// (Class) Integer.class, Long.class, String.class, Boolean.class, Byte.class,
// Character.class, Float.class, Double.class, Short.class
// );
//
// /**
// * Returns true if the given type is intended to be "primitive" by the library
// *
// * @param type The class to check
// * @return True if the give type is primitive, false otherwise
// */
// public static boolean isPrimitive(Class<?> type) {
// return type.isPrimitive() || PRIMITIVE_TYPES.contains(type);
// }
//
// public static List<Field> getFieldFromClassHierarchy(Class<?> clazz) {
// if (Object.class.equals(clazz)) {
// return Collections.emptyList();
// }
// final ArrayList<Field> fields = Lists.newArrayList(clazz.getDeclaredFields());
// fields.addAll(getFieldFromClassHierarchy(clazz.getSuperclass()));
// return fields;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/handlers/VertexHandler.java
import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.internal.ReflectUtils;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.lang.reflect.Array;
import java.util.List;
import java.util.Map;
package org.laborra.beantrace.handlers;
/**
* Manages the setup of a vertex based on the passed subject.
*/
public interface VertexHandler {
/**
* Specifies if this handler can manage the subject.
*/
boolean canHandle(Object subject);
/**
* Handle the passed vertex based on the subject.
*/ | void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder); |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/handlers/VertexHandler.java | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/ReflectUtils.java
// public class ReflectUtils {
//
// private static final Set<Class> PRIMITIVE_TYPES = Sets.newHashSet(
// (Class) Integer.class, Long.class, String.class, Boolean.class, Byte.class,
// Character.class, Float.class, Double.class, Short.class
// );
//
// /**
// * Returns true if the given type is intended to be "primitive" by the library
// *
// * @param type The class to check
// * @return True if the give type is primitive, false otherwise
// */
// public static boolean isPrimitive(Class<?> type) {
// return type.isPrimitive() || PRIMITIVE_TYPES.contains(type);
// }
//
// public static List<Field> getFieldFromClassHierarchy(Class<?> clazz) {
// if (Object.class.equals(clazz)) {
// return Collections.emptyList();
// }
// final ArrayList<Field> fields = Lists.newArrayList(clazz.getDeclaredFields());
// fields.addAll(getFieldFromClassHierarchy(clazz.getSuperclass()));
// return fields;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.internal.ReflectUtils;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.lang.reflect.Array;
import java.util.List;
import java.util.Map; | package org.laborra.beantrace.handlers;
/**
* Manages the setup of a vertex based on the passed subject.
*/
public interface VertexHandler {
/**
* Specifies if this handler can manage the subject.
*/
boolean canHandle(Object subject);
/**
* Handle the passed vertex based on the subject.
*/ | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/ReflectUtils.java
// public class ReflectUtils {
//
// private static final Set<Class> PRIMITIVE_TYPES = Sets.newHashSet(
// (Class) Integer.class, Long.class, String.class, Boolean.class, Byte.class,
// Character.class, Float.class, Double.class, Short.class
// );
//
// /**
// * Returns true if the given type is intended to be "primitive" by the library
// *
// * @param type The class to check
// * @return True if the give type is primitive, false otherwise
// */
// public static boolean isPrimitive(Class<?> type) {
// return type.isPrimitive() || PRIMITIVE_TYPES.contains(type);
// }
//
// public static List<Field> getFieldFromClassHierarchy(Class<?> clazz) {
// if (Object.class.equals(clazz)) {
// return Collections.emptyList();
// }
// final ArrayList<Field> fields = Lists.newArrayList(clazz.getDeclaredFields());
// fields.addAll(getFieldFromClassHierarchy(clazz.getSuperclass()));
// return fields;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/handlers/VertexHandler.java
import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.internal.ReflectUtils;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.lang.reflect.Array;
import java.util.List;
import java.util.Map;
package org.laborra.beantrace.handlers;
/**
* Manages the setup of a vertex based on the passed subject.
*/
public interface VertexHandler {
/**
* Specifies if this handler can manage the subject.
*/
boolean canHandle(Object subject);
/**
* Handle the passed vertex based on the subject.
*/ | void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder); |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/handlers/VertexHandler.java | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/ReflectUtils.java
// public class ReflectUtils {
//
// private static final Set<Class> PRIMITIVE_TYPES = Sets.newHashSet(
// (Class) Integer.class, Long.class, String.class, Boolean.class, Byte.class,
// Character.class, Float.class, Double.class, Short.class
// );
//
// /**
// * Returns true if the given type is intended to be "primitive" by the library
// *
// * @param type The class to check
// * @return True if the give type is primitive, false otherwise
// */
// public static boolean isPrimitive(Class<?> type) {
// return type.isPrimitive() || PRIMITIVE_TYPES.contains(type);
// }
//
// public static List<Field> getFieldFromClassHierarchy(Class<?> clazz) {
// if (Object.class.equals(clazz)) {
// return Collections.emptyList();
// }
// final ArrayList<Field> fields = Lists.newArrayList(clazz.getDeclaredFields());
// fields.addAll(getFieldFromClassHierarchy(clazz.getSuperclass()));
// return fields;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.internal.ReflectUtils;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.lang.reflect.Array;
import java.util.List;
import java.util.Map; | }
}
return false;
}
@Override
public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) {
for (VertexHandler vertexHandler : delegates) {
if (vertexHandler.canHandle(subject)) {
vertexHandler.handle(vertex, subject, vertexFieldAdder);
return;
}
}
}
}
class MapVertexHandler extends TypeBasedHandler<Map<Object, Object>> {
public MapVertexHandler() {
super(Map.class);
}
@Override
public void typedHandle(Vertex vertex, Map<Object, Object> subject, VertexFieldAdder vertexFieldAdder) {
int i = -1;
for (Map.Entry<Object, Object> entry : subject.entrySet()) {
i++;
final Object key = entry.getKey();
final Object value = entry.getValue(); | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/ReflectUtils.java
// public class ReflectUtils {
//
// private static final Set<Class> PRIMITIVE_TYPES = Sets.newHashSet(
// (Class) Integer.class, Long.class, String.class, Boolean.class, Byte.class,
// Character.class, Float.class, Double.class, Short.class
// );
//
// /**
// * Returns true if the given type is intended to be "primitive" by the library
// *
// * @param type The class to check
// * @return True if the give type is primitive, false otherwise
// */
// public static boolean isPrimitive(Class<?> type) {
// return type.isPrimitive() || PRIMITIVE_TYPES.contains(type);
// }
//
// public static List<Field> getFieldFromClassHierarchy(Class<?> clazz) {
// if (Object.class.equals(clazz)) {
// return Collections.emptyList();
// }
// final ArrayList<Field> fields = Lists.newArrayList(clazz.getDeclaredFields());
// fields.addAll(getFieldFromClassHierarchy(clazz.getSuperclass()));
// return fields;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/handlers/VertexHandler.java
import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.internal.ReflectUtils;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.lang.reflect.Array;
import java.util.List;
import java.util.Map;
}
}
return false;
}
@Override
public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) {
for (VertexHandler vertexHandler : delegates) {
if (vertexHandler.canHandle(subject)) {
vertexHandler.handle(vertex, subject, vertexFieldAdder);
return;
}
}
}
}
class MapVertexHandler extends TypeBasedHandler<Map<Object, Object>> {
public MapVertexHandler() {
super(Map.class);
}
@Override
public void typedHandle(Vertex vertex, Map<Object, Object> subject, VertexFieldAdder vertexFieldAdder) {
int i = -1;
for (Map.Entry<Object, Object> entry : subject.entrySet()) {
i++;
final Object key = entry.getKey();
final Object value = entry.getValue(); | final boolean primitiveKey = ReflectUtils.isPrimitive(key.getClass()); |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/handlers/VertexHandler.java | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/ReflectUtils.java
// public class ReflectUtils {
//
// private static final Set<Class> PRIMITIVE_TYPES = Sets.newHashSet(
// (Class) Integer.class, Long.class, String.class, Boolean.class, Byte.class,
// Character.class, Float.class, Double.class, Short.class
// );
//
// /**
// * Returns true if the given type is intended to be "primitive" by the library
// *
// * @param type The class to check
// * @return True if the give type is primitive, false otherwise
// */
// public static boolean isPrimitive(Class<?> type) {
// return type.isPrimitive() || PRIMITIVE_TYPES.contains(type);
// }
//
// public static List<Field> getFieldFromClassHierarchy(Class<?> clazz) {
// if (Object.class.equals(clazz)) {
// return Collections.emptyList();
// }
// final ArrayList<Field> fields = Lists.newArrayList(clazz.getDeclaredFields());
// fields.addAll(getFieldFromClassHierarchy(clazz.getSuperclass()));
// return fields;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.internal.ReflectUtils;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.lang.reflect.Array;
import java.util.List;
import java.util.Map; | vertexHandler.handle(vertex, subject, vertexFieldAdder);
return;
}
}
}
}
class MapVertexHandler extends TypeBasedHandler<Map<Object, Object>> {
public MapVertexHandler() {
super(Map.class);
}
@Override
public void typedHandle(Vertex vertex, Map<Object, Object> subject, VertexFieldAdder vertexFieldAdder) {
int i = -1;
for (Map.Entry<Object, Object> entry : subject.entrySet()) {
i++;
final Object key = entry.getKey();
final Object value = entry.getValue();
final boolean primitiveKey = ReflectUtils.isPrimitive(key.getClass());
if (primitiveKey) {
vertexFieldAdder.addField(vertex, key.toString(), value);
}
if (!primitiveKey) {
final Vertex entryVertex = new Vertex(Map.Entry.class, System.identityHashCode(entry) + "");
vertexFieldAdder.addField(entryVertex, "key", key);
vertexFieldAdder.addField(entryVertex, "value", value); | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/ReflectUtils.java
// public class ReflectUtils {
//
// private static final Set<Class> PRIMITIVE_TYPES = Sets.newHashSet(
// (Class) Integer.class, Long.class, String.class, Boolean.class, Byte.class,
// Character.class, Float.class, Double.class, Short.class
// );
//
// /**
// * Returns true if the given type is intended to be "primitive" by the library
// *
// * @param type The class to check
// * @return True if the give type is primitive, false otherwise
// */
// public static boolean isPrimitive(Class<?> type) {
// return type.isPrimitive() || PRIMITIVE_TYPES.contains(type);
// }
//
// public static List<Field> getFieldFromClassHierarchy(Class<?> clazz) {
// if (Object.class.equals(clazz)) {
// return Collections.emptyList();
// }
// final ArrayList<Field> fields = Lists.newArrayList(clazz.getDeclaredFields());
// fields.addAll(getFieldFromClassHierarchy(clazz.getSuperclass()));
// return fields;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/handlers/VertexHandler.java
import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.internal.ReflectUtils;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.lang.reflect.Array;
import java.util.List;
import java.util.Map;
vertexHandler.handle(vertex, subject, vertexFieldAdder);
return;
}
}
}
}
class MapVertexHandler extends TypeBasedHandler<Map<Object, Object>> {
public MapVertexHandler() {
super(Map.class);
}
@Override
public void typedHandle(Vertex vertex, Map<Object, Object> subject, VertexFieldAdder vertexFieldAdder) {
int i = -1;
for (Map.Entry<Object, Object> entry : subject.entrySet()) {
i++;
final Object key = entry.getKey();
final Object value = entry.getValue();
final boolean primitiveKey = ReflectUtils.isPrimitive(key.getClass());
if (primitiveKey) {
vertexFieldAdder.addField(vertex, key.toString(), value);
}
if (!primitiveKey) {
final Vertex entryVertex = new Vertex(Map.Entry.class, System.identityHashCode(entry) + "");
vertexFieldAdder.addField(entryVertex, "key", key);
vertexFieldAdder.addField(entryVertex, "value", value); | vertex.getReferences().add(new Edge("entry_" + i, entryVertex)); |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/internal/Graphs.java | // Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.util.*; | package org.laborra.beantrace.internal;
/**
* Utility class to interact with vertex graphs.
*
*/
public class Graphs {
/**
* Collect all vertices in the given graph.
*
* @param root A vertex contained in the graph
* @return A collection with all vertices
*/
public static Collection<Vertex> collectAllVertices(Vertex root) {
final CollectorVisitor collectorVisitor = new CollectorVisitor();
traverse(root, collectorVisitor);
return collectorVisitor.getResult();
}
/**
* Traverse the graph where the root is contained with the given visitor.
*
* @param root The starting vertex
* @param visitor The visitor to apply to all vertices
*/
public static void traverse(Vertex root, VertexVisitor visitor) {
traverse(root, visitor, new HashSet<Vertex>());
}
private static void traverse(Vertex vertex, VertexVisitor visitor, Set<Vertex> visited) {
if (visited.contains(vertex)) {
return;
}
visited.add(vertex);
visitor.visit(vertex);
| // Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/internal/Graphs.java
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.util.*;
package org.laborra.beantrace.internal;
/**
* Utility class to interact with vertex graphs.
*
*/
public class Graphs {
/**
* Collect all vertices in the given graph.
*
* @param root A vertex contained in the graph
* @return A collection with all vertices
*/
public static Collection<Vertex> collectAllVertices(Vertex root) {
final CollectorVisitor collectorVisitor = new CollectorVisitor();
traverse(root, collectorVisitor);
return collectorVisitor.getResult();
}
/**
* Traverse the graph where the root is contained with the given visitor.
*
* @param root The starting vertex
* @param visitor The visitor to apply to all vertices
*/
public static void traverse(Vertex root, VertexVisitor visitor) {
traverse(root, visitor, new HashSet<Vertex>());
}
private static void traverse(Vertex vertex, VertexVisitor visitor, Set<Vertex> visited) {
if (visited.contains(vertex)) {
return;
}
visited.add(vertex);
visitor.visit(vertex);
| final Set<Edge> references = vertex.getReferences(); |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/handlers/TypeBasedHandler.java | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.model.Vertex; | package org.laborra.beantrace.handlers;
abstract class TypeBasedHandler<T> implements VertexHandler {
private final Class<?> handledType;
protected TypeBasedHandler(Class<?> handledType) {
this.handledType = handledType;
}
@Override
public boolean canHandle(Object subject) {
return handledType.isAssignableFrom(subject.getClass());
}
@Override
@SuppressWarnings("unchecked") | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/handlers/TypeBasedHandler.java
import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.model.Vertex;
package org.laborra.beantrace.handlers;
abstract class TypeBasedHandler<T> implements VertexHandler {
private final Class<?> handledType;
protected TypeBasedHandler(Class<?> handledType) {
this.handledType = handledType;
}
@Override
public boolean canHandle(Object subject) {
return handledType.isAssignableFrom(subject.getClass());
}
@Override
@SuppressWarnings("unchecked") | public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) { |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/handlers/TypeBasedHandler.java | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.model.Vertex; | package org.laborra.beantrace.handlers;
abstract class TypeBasedHandler<T> implements VertexHandler {
private final Class<?> handledType;
protected TypeBasedHandler(Class<?> handledType) {
this.handledType = handledType;
}
@Override
public boolean canHandle(Object subject) {
return handledType.isAssignableFrom(subject.getClass());
}
@Override
@SuppressWarnings("unchecked") | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/handlers/TypeBasedHandler.java
import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.model.Vertex;
package org.laborra.beantrace.handlers;
abstract class TypeBasedHandler<T> implements VertexHandler {
private final Class<?> handledType;
protected TypeBasedHandler(Class<?> handledType) {
this.handledType = handledType;
}
@Override
public boolean canHandle(Object subject) {
return handledType.isAssignableFrom(subject.getClass());
}
@Override
@SuppressWarnings("unchecked") | public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) { |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/renderers/JsonRenderer.java | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/Graphs.java
// public class Graphs {
//
// /**
// * Collect all vertices in the given graph.
// *
// * @param root A vertex contained in the graph
// * @return A collection with all vertices
// */
// public static Collection<Vertex> collectAllVertices(Vertex root) {
// final CollectorVisitor collectorVisitor = new CollectorVisitor();
// traverse(root, collectorVisitor);
// return collectorVisitor.getResult();
// }
//
// /**
// * Traverse the graph where the root is contained with the given visitor.
// *
// * @param root The starting vertex
// * @param visitor The visitor to apply to all vertices
// */
// public static void traverse(Vertex root, VertexVisitor visitor) {
// traverse(root, visitor, new HashSet<Vertex>());
// }
//
// private static void traverse(Vertex vertex, VertexVisitor visitor, Set<Vertex> visited) {
// if (visited.contains(vertex)) {
// return;
// }
// visited.add(vertex);
//
// visitor.visit(vertex);
//
// final Set<Edge> references = vertex.getReferences();
// for (Edge reference : references) {
// traverse(reference.getTo(), visitor, visited);
// }
// }
//
// /**
// * Return a map view of the graph edges, where each key is an edge and the value is the
// * vertex the edge start from.
// *
// * @param subject The root vertex of the graph
// * @return The map representing the graph
// */
// public static Map<Edge, Vertex> mapEdgeToStartingVertex(Vertex subject) {
// final Map<Edge, Vertex> edgeMap = new HashMap<>();
// traverse(subject, new VertexVisitor() {
// @Override
// public void visit(Vertex vertex) {
// for (Edge edge : vertex.getReferences()) {
// edgeMap.put(edge, vertex);
// }
// }
// });
// return edgeMap;
// }
//
// public static Map<Vertex, Integer> mapVerticesToIndex(Collection<Vertex> vertices) {
// final Map<Vertex, Integer> vertexToIndexMap = new HashMap<>();
// int i=0;
// for (Vertex vertex : vertices) {
// vertexToIndexMap.put(vertex, i);
// i++;
// }
// return vertexToIndexMap;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.escape.Escaper;
import com.google.common.escape.Escapers;
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.internal.Graphs;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.Writer;
import java.util.*; | package org.laborra.beantrace.renderers;
public class JsonRenderer implements GraphRenderer {
private final Writer writer;
private static final Escaper ESCAPER = Escapers.builder()
.addEscape('"', "\\\"")
.build();
public JsonRenderer(Writer writer) {
this.writer = writer;
}
@Override | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/Graphs.java
// public class Graphs {
//
// /**
// * Collect all vertices in the given graph.
// *
// * @param root A vertex contained in the graph
// * @return A collection with all vertices
// */
// public static Collection<Vertex> collectAllVertices(Vertex root) {
// final CollectorVisitor collectorVisitor = new CollectorVisitor();
// traverse(root, collectorVisitor);
// return collectorVisitor.getResult();
// }
//
// /**
// * Traverse the graph where the root is contained with the given visitor.
// *
// * @param root The starting vertex
// * @param visitor The visitor to apply to all vertices
// */
// public static void traverse(Vertex root, VertexVisitor visitor) {
// traverse(root, visitor, new HashSet<Vertex>());
// }
//
// private static void traverse(Vertex vertex, VertexVisitor visitor, Set<Vertex> visited) {
// if (visited.contains(vertex)) {
// return;
// }
// visited.add(vertex);
//
// visitor.visit(vertex);
//
// final Set<Edge> references = vertex.getReferences();
// for (Edge reference : references) {
// traverse(reference.getTo(), visitor, visited);
// }
// }
//
// /**
// * Return a map view of the graph edges, where each key is an edge and the value is the
// * vertex the edge start from.
// *
// * @param subject The root vertex of the graph
// * @return The map representing the graph
// */
// public static Map<Edge, Vertex> mapEdgeToStartingVertex(Vertex subject) {
// final Map<Edge, Vertex> edgeMap = new HashMap<>();
// traverse(subject, new VertexVisitor() {
// @Override
// public void visit(Vertex vertex) {
// for (Edge edge : vertex.getReferences()) {
// edgeMap.put(edge, vertex);
// }
// }
// });
// return edgeMap;
// }
//
// public static Map<Vertex, Integer> mapVerticesToIndex(Collection<Vertex> vertices) {
// final Map<Vertex, Integer> vertexToIndexMap = new HashMap<>();
// int i=0;
// for (Vertex vertex : vertices) {
// vertexToIndexMap.put(vertex, i);
// i++;
// }
// return vertexToIndexMap;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/renderers/JsonRenderer.java
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.escape.Escaper;
import com.google.common.escape.Escapers;
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.internal.Graphs;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.Writer;
import java.util.*;
package org.laborra.beantrace.renderers;
public class JsonRenderer implements GraphRenderer {
private final Writer writer;
private static final Escaper ESCAPER = Escapers.builder()
.addEscape('"', "\\\"")
.build();
public JsonRenderer(Writer writer) {
this.writer = writer;
}
@Override | public void render(Vertex subject) { |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/renderers/JsonRenderer.java | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/Graphs.java
// public class Graphs {
//
// /**
// * Collect all vertices in the given graph.
// *
// * @param root A vertex contained in the graph
// * @return A collection with all vertices
// */
// public static Collection<Vertex> collectAllVertices(Vertex root) {
// final CollectorVisitor collectorVisitor = new CollectorVisitor();
// traverse(root, collectorVisitor);
// return collectorVisitor.getResult();
// }
//
// /**
// * Traverse the graph where the root is contained with the given visitor.
// *
// * @param root The starting vertex
// * @param visitor The visitor to apply to all vertices
// */
// public static void traverse(Vertex root, VertexVisitor visitor) {
// traverse(root, visitor, new HashSet<Vertex>());
// }
//
// private static void traverse(Vertex vertex, VertexVisitor visitor, Set<Vertex> visited) {
// if (visited.contains(vertex)) {
// return;
// }
// visited.add(vertex);
//
// visitor.visit(vertex);
//
// final Set<Edge> references = vertex.getReferences();
// for (Edge reference : references) {
// traverse(reference.getTo(), visitor, visited);
// }
// }
//
// /**
// * Return a map view of the graph edges, where each key is an edge and the value is the
// * vertex the edge start from.
// *
// * @param subject The root vertex of the graph
// * @return The map representing the graph
// */
// public static Map<Edge, Vertex> mapEdgeToStartingVertex(Vertex subject) {
// final Map<Edge, Vertex> edgeMap = new HashMap<>();
// traverse(subject, new VertexVisitor() {
// @Override
// public void visit(Vertex vertex) {
// for (Edge edge : vertex.getReferences()) {
// edgeMap.put(edge, vertex);
// }
// }
// });
// return edgeMap;
// }
//
// public static Map<Vertex, Integer> mapVerticesToIndex(Collection<Vertex> vertices) {
// final Map<Vertex, Integer> vertexToIndexMap = new HashMap<>();
// int i=0;
// for (Vertex vertex : vertices) {
// vertexToIndexMap.put(vertex, i);
// i++;
// }
// return vertexToIndexMap;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.escape.Escaper;
import com.google.common.escape.Escapers;
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.internal.Graphs;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.Writer;
import java.util.*; | package org.laborra.beantrace.renderers;
public class JsonRenderer implements GraphRenderer {
private final Writer writer;
private static final Escaper ESCAPER = Escapers.builder()
.addEscape('"', "\\\"")
.build();
public JsonRenderer(Writer writer) {
this.writer = writer;
}
@Override
public void render(Vertex subject) {
| // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/Graphs.java
// public class Graphs {
//
// /**
// * Collect all vertices in the given graph.
// *
// * @param root A vertex contained in the graph
// * @return A collection with all vertices
// */
// public static Collection<Vertex> collectAllVertices(Vertex root) {
// final CollectorVisitor collectorVisitor = new CollectorVisitor();
// traverse(root, collectorVisitor);
// return collectorVisitor.getResult();
// }
//
// /**
// * Traverse the graph where the root is contained with the given visitor.
// *
// * @param root The starting vertex
// * @param visitor The visitor to apply to all vertices
// */
// public static void traverse(Vertex root, VertexVisitor visitor) {
// traverse(root, visitor, new HashSet<Vertex>());
// }
//
// private static void traverse(Vertex vertex, VertexVisitor visitor, Set<Vertex> visited) {
// if (visited.contains(vertex)) {
// return;
// }
// visited.add(vertex);
//
// visitor.visit(vertex);
//
// final Set<Edge> references = vertex.getReferences();
// for (Edge reference : references) {
// traverse(reference.getTo(), visitor, visited);
// }
// }
//
// /**
// * Return a map view of the graph edges, where each key is an edge and the value is the
// * vertex the edge start from.
// *
// * @param subject The root vertex of the graph
// * @return The map representing the graph
// */
// public static Map<Edge, Vertex> mapEdgeToStartingVertex(Vertex subject) {
// final Map<Edge, Vertex> edgeMap = new HashMap<>();
// traverse(subject, new VertexVisitor() {
// @Override
// public void visit(Vertex vertex) {
// for (Edge edge : vertex.getReferences()) {
// edgeMap.put(edge, vertex);
// }
// }
// });
// return edgeMap;
// }
//
// public static Map<Vertex, Integer> mapVerticesToIndex(Collection<Vertex> vertices) {
// final Map<Vertex, Integer> vertexToIndexMap = new HashMap<>();
// int i=0;
// for (Vertex vertex : vertices) {
// vertexToIndexMap.put(vertex, i);
// i++;
// }
// return vertexToIndexMap;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/renderers/JsonRenderer.java
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.escape.Escaper;
import com.google.common.escape.Escapers;
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.internal.Graphs;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.Writer;
import java.util.*;
package org.laborra.beantrace.renderers;
public class JsonRenderer implements GraphRenderer {
private final Writer writer;
private static final Escaper ESCAPER = Escapers.builder()
.addEscape('"', "\\\"")
.build();
public JsonRenderer(Writer writer) {
this.writer = writer;
}
@Override
public void render(Vertex subject) {
| final Collection<Vertex> vertices = Graphs.collectAllVertices(subject); |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/renderers/JsonRenderer.java | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/Graphs.java
// public class Graphs {
//
// /**
// * Collect all vertices in the given graph.
// *
// * @param root A vertex contained in the graph
// * @return A collection with all vertices
// */
// public static Collection<Vertex> collectAllVertices(Vertex root) {
// final CollectorVisitor collectorVisitor = new CollectorVisitor();
// traverse(root, collectorVisitor);
// return collectorVisitor.getResult();
// }
//
// /**
// * Traverse the graph where the root is contained with the given visitor.
// *
// * @param root The starting vertex
// * @param visitor The visitor to apply to all vertices
// */
// public static void traverse(Vertex root, VertexVisitor visitor) {
// traverse(root, visitor, new HashSet<Vertex>());
// }
//
// private static void traverse(Vertex vertex, VertexVisitor visitor, Set<Vertex> visited) {
// if (visited.contains(vertex)) {
// return;
// }
// visited.add(vertex);
//
// visitor.visit(vertex);
//
// final Set<Edge> references = vertex.getReferences();
// for (Edge reference : references) {
// traverse(reference.getTo(), visitor, visited);
// }
// }
//
// /**
// * Return a map view of the graph edges, where each key is an edge and the value is the
// * vertex the edge start from.
// *
// * @param subject The root vertex of the graph
// * @return The map representing the graph
// */
// public static Map<Edge, Vertex> mapEdgeToStartingVertex(Vertex subject) {
// final Map<Edge, Vertex> edgeMap = new HashMap<>();
// traverse(subject, new VertexVisitor() {
// @Override
// public void visit(Vertex vertex) {
// for (Edge edge : vertex.getReferences()) {
// edgeMap.put(edge, vertex);
// }
// }
// });
// return edgeMap;
// }
//
// public static Map<Vertex, Integer> mapVerticesToIndex(Collection<Vertex> vertices) {
// final Map<Vertex, Integer> vertexToIndexMap = new HashMap<>();
// int i=0;
// for (Vertex vertex : vertices) {
// vertexToIndexMap.put(vertex, i);
// i++;
// }
// return vertexToIndexMap;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.escape.Escaper;
import com.google.common.escape.Escapers;
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.internal.Graphs;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.Writer;
import java.util.*; | package org.laborra.beantrace.renderers;
public class JsonRenderer implements GraphRenderer {
private final Writer writer;
private static final Escaper ESCAPER = Escapers.builder()
.addEscape('"', "\\\"")
.build();
public JsonRenderer(Writer writer) {
this.writer = writer;
}
@Override
public void render(Vertex subject) {
final Collection<Vertex> vertices = Graphs.collectAllVertices(subject);
final Map<Vertex, Integer> vertexToIndexMap = Graphs.mapVerticesToIndex(vertices);
final Iterable<String> verticesAsJson = Iterables.transform(vertices, new Function<Vertex, String>() {
@Override
public String apply(Vertex input) {
return vertexAsJson(input);
}
});
| // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/Graphs.java
// public class Graphs {
//
// /**
// * Collect all vertices in the given graph.
// *
// * @param root A vertex contained in the graph
// * @return A collection with all vertices
// */
// public static Collection<Vertex> collectAllVertices(Vertex root) {
// final CollectorVisitor collectorVisitor = new CollectorVisitor();
// traverse(root, collectorVisitor);
// return collectorVisitor.getResult();
// }
//
// /**
// * Traverse the graph where the root is contained with the given visitor.
// *
// * @param root The starting vertex
// * @param visitor The visitor to apply to all vertices
// */
// public static void traverse(Vertex root, VertexVisitor visitor) {
// traverse(root, visitor, new HashSet<Vertex>());
// }
//
// private static void traverse(Vertex vertex, VertexVisitor visitor, Set<Vertex> visited) {
// if (visited.contains(vertex)) {
// return;
// }
// visited.add(vertex);
//
// visitor.visit(vertex);
//
// final Set<Edge> references = vertex.getReferences();
// for (Edge reference : references) {
// traverse(reference.getTo(), visitor, visited);
// }
// }
//
// /**
// * Return a map view of the graph edges, where each key is an edge and the value is the
// * vertex the edge start from.
// *
// * @param subject The root vertex of the graph
// * @return The map representing the graph
// */
// public static Map<Edge, Vertex> mapEdgeToStartingVertex(Vertex subject) {
// final Map<Edge, Vertex> edgeMap = new HashMap<>();
// traverse(subject, new VertexVisitor() {
// @Override
// public void visit(Vertex vertex) {
// for (Edge edge : vertex.getReferences()) {
// edgeMap.put(edge, vertex);
// }
// }
// });
// return edgeMap;
// }
//
// public static Map<Vertex, Integer> mapVerticesToIndex(Collection<Vertex> vertices) {
// final Map<Vertex, Integer> vertexToIndexMap = new HashMap<>();
// int i=0;
// for (Vertex vertex : vertices) {
// vertexToIndexMap.put(vertex, i);
// i++;
// }
// return vertexToIndexMap;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/renderers/JsonRenderer.java
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.escape.Escaper;
import com.google.common.escape.Escapers;
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.internal.Graphs;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.Writer;
import java.util.*;
package org.laborra.beantrace.renderers;
public class JsonRenderer implements GraphRenderer {
private final Writer writer;
private static final Escaper ESCAPER = Escapers.builder()
.addEscape('"', "\\\"")
.build();
public JsonRenderer(Writer writer) {
this.writer = writer;
}
@Override
public void render(Vertex subject) {
final Collection<Vertex> vertices = Graphs.collectAllVertices(subject);
final Map<Vertex, Integer> vertexToIndexMap = Graphs.mapVerticesToIndex(vertices);
final Iterable<String> verticesAsJson = Iterables.transform(vertices, new Function<Vertex, String>() {
@Override
public String apply(Vertex input) {
return vertexAsJson(input);
}
});
| final Map<Edge, Vertex> edgeMap = Graphs.mapEdgeToStartingVertex(subject); |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/renderers/JsonRenderer.java | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/Graphs.java
// public class Graphs {
//
// /**
// * Collect all vertices in the given graph.
// *
// * @param root A vertex contained in the graph
// * @return A collection with all vertices
// */
// public static Collection<Vertex> collectAllVertices(Vertex root) {
// final CollectorVisitor collectorVisitor = new CollectorVisitor();
// traverse(root, collectorVisitor);
// return collectorVisitor.getResult();
// }
//
// /**
// * Traverse the graph where the root is contained with the given visitor.
// *
// * @param root The starting vertex
// * @param visitor The visitor to apply to all vertices
// */
// public static void traverse(Vertex root, VertexVisitor visitor) {
// traverse(root, visitor, new HashSet<Vertex>());
// }
//
// private static void traverse(Vertex vertex, VertexVisitor visitor, Set<Vertex> visited) {
// if (visited.contains(vertex)) {
// return;
// }
// visited.add(vertex);
//
// visitor.visit(vertex);
//
// final Set<Edge> references = vertex.getReferences();
// for (Edge reference : references) {
// traverse(reference.getTo(), visitor, visited);
// }
// }
//
// /**
// * Return a map view of the graph edges, where each key is an edge and the value is the
// * vertex the edge start from.
// *
// * @param subject The root vertex of the graph
// * @return The map representing the graph
// */
// public static Map<Edge, Vertex> mapEdgeToStartingVertex(Vertex subject) {
// final Map<Edge, Vertex> edgeMap = new HashMap<>();
// traverse(subject, new VertexVisitor() {
// @Override
// public void visit(Vertex vertex) {
// for (Edge edge : vertex.getReferences()) {
// edgeMap.put(edge, vertex);
// }
// }
// });
// return edgeMap;
// }
//
// public static Map<Vertex, Integer> mapVerticesToIndex(Collection<Vertex> vertices) {
// final Map<Vertex, Integer> vertexToIndexMap = new HashMap<>();
// int i=0;
// for (Vertex vertex : vertices) {
// vertexToIndexMap.put(vertex, i);
// i++;
// }
// return vertexToIndexMap;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.escape.Escaper;
import com.google.common.escape.Escapers;
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.internal.Graphs;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.Writer;
import java.util.*; | @Override
public void render(Vertex subject) {
final Collection<Vertex> vertices = Graphs.collectAllVertices(subject);
final Map<Vertex, Integer> vertexToIndexMap = Graphs.mapVerticesToIndex(vertices);
final Iterable<String> verticesAsJson = Iterables.transform(vertices, new Function<Vertex, String>() {
@Override
public String apply(Vertex input) {
return vertexAsJson(input);
}
});
final Map<Edge, Vertex> edgeMap = Graphs.mapEdgeToStartingVertex(subject);
final Iterable<String> edgesAsJson = Iterables.transform(edgeMap.keySet(), new Function<Edge, String>() {
@Override
public String apply(Edge input) {
return edgeAsJson(edgeMap, vertexToIndexMap, input);
}
});
try {
writer.write(
curly(
jsonArrayField("nodes", verticesAsJson),
jsonArrayField("links", edgesAsJson)
)
);
} catch (IOException e) { | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/Graphs.java
// public class Graphs {
//
// /**
// * Collect all vertices in the given graph.
// *
// * @param root A vertex contained in the graph
// * @return A collection with all vertices
// */
// public static Collection<Vertex> collectAllVertices(Vertex root) {
// final CollectorVisitor collectorVisitor = new CollectorVisitor();
// traverse(root, collectorVisitor);
// return collectorVisitor.getResult();
// }
//
// /**
// * Traverse the graph where the root is contained with the given visitor.
// *
// * @param root The starting vertex
// * @param visitor The visitor to apply to all vertices
// */
// public static void traverse(Vertex root, VertexVisitor visitor) {
// traverse(root, visitor, new HashSet<Vertex>());
// }
//
// private static void traverse(Vertex vertex, VertexVisitor visitor, Set<Vertex> visited) {
// if (visited.contains(vertex)) {
// return;
// }
// visited.add(vertex);
//
// visitor.visit(vertex);
//
// final Set<Edge> references = vertex.getReferences();
// for (Edge reference : references) {
// traverse(reference.getTo(), visitor, visited);
// }
// }
//
// /**
// * Return a map view of the graph edges, where each key is an edge and the value is the
// * vertex the edge start from.
// *
// * @param subject The root vertex of the graph
// * @return The map representing the graph
// */
// public static Map<Edge, Vertex> mapEdgeToStartingVertex(Vertex subject) {
// final Map<Edge, Vertex> edgeMap = new HashMap<>();
// traverse(subject, new VertexVisitor() {
// @Override
// public void visit(Vertex vertex) {
// for (Edge edge : vertex.getReferences()) {
// edgeMap.put(edge, vertex);
// }
// }
// });
// return edgeMap;
// }
//
// public static Map<Vertex, Integer> mapVerticesToIndex(Collection<Vertex> vertices) {
// final Map<Vertex, Integer> vertexToIndexMap = new HashMap<>();
// int i=0;
// for (Vertex vertex : vertices) {
// vertexToIndexMap.put(vertex, i);
// i++;
// }
// return vertexToIndexMap;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/renderers/JsonRenderer.java
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.escape.Escaper;
import com.google.common.escape.Escapers;
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.internal.Graphs;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.Writer;
import java.util.*;
@Override
public void render(Vertex subject) {
final Collection<Vertex> vertices = Graphs.collectAllVertices(subject);
final Map<Vertex, Integer> vertexToIndexMap = Graphs.mapVerticesToIndex(vertices);
final Iterable<String> verticesAsJson = Iterables.transform(vertices, new Function<Vertex, String>() {
@Override
public String apply(Vertex input) {
return vertexAsJson(input);
}
});
final Map<Edge, Vertex> edgeMap = Graphs.mapEdgeToStartingVertex(subject);
final Iterable<String> edgesAsJson = Iterables.transform(edgeMap.keySet(), new Function<Edge, String>() {
@Override
public String apply(Edge input) {
return edgeAsJson(edgeMap, vertexToIndexMap, input);
}
});
try {
writer.write(
curly(
jsonArrayField("nodes", verticesAsJson),
jsonArrayField("links", edgesAsJson)
)
);
} catch (IOException e) { | throw new BeanTraceException(e); |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/renderers/JsonRenderer.java | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/Graphs.java
// public class Graphs {
//
// /**
// * Collect all vertices in the given graph.
// *
// * @param root A vertex contained in the graph
// * @return A collection with all vertices
// */
// public static Collection<Vertex> collectAllVertices(Vertex root) {
// final CollectorVisitor collectorVisitor = new CollectorVisitor();
// traverse(root, collectorVisitor);
// return collectorVisitor.getResult();
// }
//
// /**
// * Traverse the graph where the root is contained with the given visitor.
// *
// * @param root The starting vertex
// * @param visitor The visitor to apply to all vertices
// */
// public static void traverse(Vertex root, VertexVisitor visitor) {
// traverse(root, visitor, new HashSet<Vertex>());
// }
//
// private static void traverse(Vertex vertex, VertexVisitor visitor, Set<Vertex> visited) {
// if (visited.contains(vertex)) {
// return;
// }
// visited.add(vertex);
//
// visitor.visit(vertex);
//
// final Set<Edge> references = vertex.getReferences();
// for (Edge reference : references) {
// traverse(reference.getTo(), visitor, visited);
// }
// }
//
// /**
// * Return a map view of the graph edges, where each key is an edge and the value is the
// * vertex the edge start from.
// *
// * @param subject The root vertex of the graph
// * @return The map representing the graph
// */
// public static Map<Edge, Vertex> mapEdgeToStartingVertex(Vertex subject) {
// final Map<Edge, Vertex> edgeMap = new HashMap<>();
// traverse(subject, new VertexVisitor() {
// @Override
// public void visit(Vertex vertex) {
// for (Edge edge : vertex.getReferences()) {
// edgeMap.put(edge, vertex);
// }
// }
// });
// return edgeMap;
// }
//
// public static Map<Vertex, Integer> mapVerticesToIndex(Collection<Vertex> vertices) {
// final Map<Vertex, Integer> vertexToIndexMap = new HashMap<>();
// int i=0;
// for (Vertex vertex : vertices) {
// vertexToIndexMap.put(vertex, i);
// i++;
// }
// return vertexToIndexMap;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.escape.Escaper;
import com.google.common.escape.Escapers;
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.internal.Graphs;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.Writer;
import java.util.*; | final Iterable<String> verticesAsJson = Iterables.transform(vertices, new Function<Vertex, String>() {
@Override
public String apply(Vertex input) {
return vertexAsJson(input);
}
});
final Map<Edge, Vertex> edgeMap = Graphs.mapEdgeToStartingVertex(subject);
final Iterable<String> edgesAsJson = Iterables.transform(edgeMap.keySet(), new Function<Edge, String>() {
@Override
public String apply(Edge input) {
return edgeAsJson(edgeMap, vertexToIndexMap, input);
}
});
try {
writer.write(
curly(
jsonArrayField("nodes", verticesAsJson),
jsonArrayField("links", edgesAsJson)
)
);
} catch (IOException e) {
throw new BeanTraceException(e);
}
}
private static String vertexAsJson(Vertex subject) {
final List<String> fields = new LinkedList<>(); | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/internal/Graphs.java
// public class Graphs {
//
// /**
// * Collect all vertices in the given graph.
// *
// * @param root A vertex contained in the graph
// * @return A collection with all vertices
// */
// public static Collection<Vertex> collectAllVertices(Vertex root) {
// final CollectorVisitor collectorVisitor = new CollectorVisitor();
// traverse(root, collectorVisitor);
// return collectorVisitor.getResult();
// }
//
// /**
// * Traverse the graph where the root is contained with the given visitor.
// *
// * @param root The starting vertex
// * @param visitor The visitor to apply to all vertices
// */
// public static void traverse(Vertex root, VertexVisitor visitor) {
// traverse(root, visitor, new HashSet<Vertex>());
// }
//
// private static void traverse(Vertex vertex, VertexVisitor visitor, Set<Vertex> visited) {
// if (visited.contains(vertex)) {
// return;
// }
// visited.add(vertex);
//
// visitor.visit(vertex);
//
// final Set<Edge> references = vertex.getReferences();
// for (Edge reference : references) {
// traverse(reference.getTo(), visitor, visited);
// }
// }
//
// /**
// * Return a map view of the graph edges, where each key is an edge and the value is the
// * vertex the edge start from.
// *
// * @param subject The root vertex of the graph
// * @return The map representing the graph
// */
// public static Map<Edge, Vertex> mapEdgeToStartingVertex(Vertex subject) {
// final Map<Edge, Vertex> edgeMap = new HashMap<>();
// traverse(subject, new VertexVisitor() {
// @Override
// public void visit(Vertex vertex) {
// for (Edge edge : vertex.getReferences()) {
// edgeMap.put(edge, vertex);
// }
// }
// });
// return edgeMap;
// }
//
// public static Map<Vertex, Integer> mapVerticesToIndex(Collection<Vertex> vertices) {
// final Map<Vertex, Integer> vertexToIndexMap = new HashMap<>();
// int i=0;
// for (Vertex vertex : vertices) {
// vertexToIndexMap.put(vertex, i);
// i++;
// }
// return vertexToIndexMap;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/renderers/JsonRenderer.java
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.escape.Escaper;
import com.google.common.escape.Escapers;
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.internal.Graphs;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.Writer;
import java.util.*;
final Iterable<String> verticesAsJson = Iterables.transform(vertices, new Function<Vertex, String>() {
@Override
public String apply(Vertex input) {
return vertexAsJson(input);
}
});
final Map<Edge, Vertex> edgeMap = Graphs.mapEdgeToStartingVertex(subject);
final Iterable<String> edgesAsJson = Iterables.transform(edgeMap.keySet(), new Function<Edge, String>() {
@Override
public String apply(Edge input) {
return edgeAsJson(edgeMap, vertexToIndexMap, input);
}
});
try {
writer.write(
curly(
jsonArrayField("nodes", verticesAsJson),
jsonArrayField("links", edgesAsJson)
)
);
} catch (IOException e) {
throw new BeanTraceException(e);
}
}
private static String vertexAsJson(Vertex subject) {
final List<String> fields = new LinkedList<>(); | for (Attribute attribute : subject.getAttributes()) { |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/renderers/AsciiRenderer.java | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashSet;
import java.util.Set; | package org.laborra.beantrace.renderers;
/**
* Print the object graph to {@link java.lang.Appendable} specified by the {@link Config},
* using ASCII characters.
*/
public class AsciiRenderer implements GraphRenderer {
private Config config;
| // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/renderers/AsciiRenderer.java
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashSet;
import java.util.Set;
package org.laborra.beantrace.renderers;
/**
* Print the object graph to {@link java.lang.Appendable} specified by the {@link Config},
* using ASCII characters.
*/
public class AsciiRenderer implements GraphRenderer {
private Config config;
| private final Set<Vertex> visited = new HashSet<>(); |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/renderers/AsciiRenderer.java | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashSet;
import java.util.Set; | package org.laborra.beantrace.renderers;
/**
* Print the object graph to {@link java.lang.Appendable} specified by the {@link Config},
* using ASCII characters.
*/
public class AsciiRenderer implements GraphRenderer {
private Config config;
private final Set<Vertex> visited = new HashSet<>();
/**
* Initialize the renderer using the default configuration.
*/
public AsciiRenderer() {
this(new Config());
}
public AsciiRenderer(Config config) {
this.config = config;
}
public Config getConfig() {
return config;
}
@Override
public void render(Vertex subject) {
renderLinks(subject);
}
private void renderLinks(Vertex subject) {
try {
final Writer output = config.getOutput();
renderNode(output, subject, 0, "");
output.flush();
} catch (IOException e) { | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/renderers/AsciiRenderer.java
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashSet;
import java.util.Set;
package org.laborra.beantrace.renderers;
/**
* Print the object graph to {@link java.lang.Appendable} specified by the {@link Config},
* using ASCII characters.
*/
public class AsciiRenderer implements GraphRenderer {
private Config config;
private final Set<Vertex> visited = new HashSet<>();
/**
* Initialize the renderer using the default configuration.
*/
public AsciiRenderer() {
this(new Config());
}
public AsciiRenderer(Config config) {
this.config = config;
}
public Config getConfig() {
return config;
}
@Override
public void render(Vertex subject) {
renderLinks(subject);
}
private void renderLinks(Vertex subject) {
try {
final Writer output = config.getOutput();
renderNode(output, subject, 0, "");
output.flush();
} catch (IOException e) { | throw new BeanTraceException(e); |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/renderers/AsciiRenderer.java | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashSet;
import java.util.Set; | renderLinks(subject);
}
private void renderLinks(Vertex subject) {
try {
final Writer output = config.getOutput();
renderNode(output, subject, 0, "");
output.flush();
} catch (IOException e) {
throw new BeanTraceException(e);
}
}
private void renderNode(Writer output, Vertex vertex, int depth, String prefix) throws IOException {
indent(depth, output);
output.append(prefix);
output.append(vertex.getClazz().getSimpleName());
if (config.isPrintId()) {
output.append("@").append(vertex.getId());
}
if (visited.contains(vertex)) {
return;
}
visited.add(vertex);
| // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/renderers/AsciiRenderer.java
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashSet;
import java.util.Set;
renderLinks(subject);
}
private void renderLinks(Vertex subject) {
try {
final Writer output = config.getOutput();
renderNode(output, subject, 0, "");
output.flush();
} catch (IOException e) {
throw new BeanTraceException(e);
}
}
private void renderNode(Writer output, Vertex vertex, int depth, String prefix) throws IOException {
indent(depth, output);
output.append(prefix);
output.append(vertex.getClazz().getSimpleName());
if (config.isPrintId()) {
output.append("@").append(vertex.getId());
}
if (visited.contains(vertex)) {
return;
}
visited.add(vertex);
| final Set<Attribute> attributes = vertex.getAttributes(); |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/renderers/AsciiRenderer.java | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashSet;
import java.util.Set; | }
private void renderLinks(Vertex subject) {
try {
final Writer output = config.getOutput();
renderNode(output, subject, 0, "");
output.flush();
} catch (IOException e) {
throw new BeanTraceException(e);
}
}
private void renderNode(Writer output, Vertex vertex, int depth, String prefix) throws IOException {
indent(depth, output);
output.append(prefix);
output.append(vertex.getClazz().getSimpleName());
if (config.isPrintId()) {
output.append("@").append(vertex.getId());
}
if (visited.contains(vertex)) {
return;
}
visited.add(vertex);
final Set<Attribute> attributes = vertex.getAttributes(); | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Edge.java
// public class Edge {
// private String name;
// private Vertex to;
//
// public Edge(String name, Vertex to) {
// this.name = name;
// this.to = to;
// }
//
// public String getName() {
// return name;
// }
//
// public Vertex getTo() {
// return to;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/renderers/AsciiRenderer.java
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Edge;
import org.laborra.beantrace.model.Vertex;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.HashSet;
import java.util.Set;
}
private void renderLinks(Vertex subject) {
try {
final Writer output = config.getOutput();
renderNode(output, subject, 0, "");
output.flush();
} catch (IOException e) {
throw new BeanTraceException(e);
}
}
private void renderNode(Writer output, Vertex vertex, int depth, String prefix) throws IOException {
indent(depth, output);
output.append(prefix);
output.append(vertex.getClazz().getSimpleName());
if (config.isPrintId()) {
output.append("@").append(vertex.getId());
}
if (visited.contains(vertex)) {
return;
}
visited.add(vertex);
final Set<Attribute> attributes = vertex.getAttributes(); | final Set<Edge> references = vertex.getReferences(); |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/handlers/TypedStopVertexHandler.java | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.model.Vertex; | package org.laborra.beantrace.handlers;
/**
* This class stops the propagation of the scanning on the given object type.
*/
class TypedStopVertexHandler<T> extends TypeBasedHandler<T> {
TypedStopVertexHandler(Class<?> handledType) {
super(handledType);
}
@Override | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/handlers/TypedStopVertexHandler.java
import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.model.Vertex;
package org.laborra.beantrace.handlers;
/**
* This class stops the propagation of the scanning on the given object type.
*/
class TypedStopVertexHandler<T> extends TypeBasedHandler<T> {
TypedStopVertexHandler(Class<?> handledType) {
super(handledType);
}
@Override | protected void typedHandle(Vertex vertex, T subject, VertexFieldAdder vertexFieldAdder) { |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/handlers/TypedStopVertexHandler.java | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.model.Vertex; | package org.laborra.beantrace.handlers;
/**
* This class stops the propagation of the scanning on the given object type.
*/
class TypedStopVertexHandler<T> extends TypeBasedHandler<T> {
TypedStopVertexHandler(Class<?> handledType) {
super(handledType);
}
@Override | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/handlers/TypedStopVertexHandler.java
import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.model.Vertex;
package org.laborra.beantrace.handlers;
/**
* This class stops the propagation of the scanning on the given object type.
*/
class TypedStopVertexHandler<T> extends TypeBasedHandler<T> {
TypedStopVertexHandler(Class<?> handledType) {
super(handledType);
}
@Override | protected void typedHandle(Vertex vertex, T subject, VertexFieldAdder vertexFieldAdder) { |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/renderers/D3JSRenderer.java | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.model.Vertex;
import java.io.*; | package org.laborra.beantrace.renderers;
public class D3JSRenderer implements GraphRenderer {
private final Writer destinationWrite;
private final Reader templateReader;
public D3JSRenderer(Writer destinationWrite, Reader templateReader) {
this.destinationWrite = destinationWrite;
this.templateReader = templateReader;
}
@Override | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/renderers/D3JSRenderer.java
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.model.Vertex;
import java.io.*;
package org.laborra.beantrace.renderers;
public class D3JSRenderer implements GraphRenderer {
private final Writer destinationWrite;
private final Reader templateReader;
public D3JSRenderer(Writer destinationWrite, Reader templateReader) {
this.destinationWrite = destinationWrite;
this.templateReader = templateReader;
}
@Override | public void render(Vertex subject) { |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/renderers/D3JSRenderer.java | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.model.Vertex;
import java.io.*; | package org.laborra.beantrace.renderers;
public class D3JSRenderer implements GraphRenderer {
private final Writer destinationWrite;
private final Reader templateReader;
public D3JSRenderer(Writer destinationWrite, Reader templateReader) {
this.destinationWrite = destinationWrite;
this.templateReader = templateReader;
}
@Override
public void render(Vertex subject) {
final StringWriter stringWriter = new StringWriter();
new JsonRenderer(stringWriter).render(subject);
try (
final BufferedReader bufferedReader = new BufferedReader(templateReader);
final PrintWriter printWriter = new PrintWriter(destinationWrite)
) {
String line;
while ((line = bufferedReader.readLine()) != null) {
final String toWriteLine = line.replace("###JSON_DATA_TOKEN###", stringWriter.toString());
printWriter.println(toWriteLine);
}
} catch (IOException e) { | // Path: src/main/java/org/laborra/beantrace/BeanTraceException.java
// public class BeanTraceException extends RuntimeException {
// public BeanTraceException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/renderers/D3JSRenderer.java
import org.laborra.beantrace.BeanTraceException;
import org.laborra.beantrace.model.Vertex;
import java.io.*;
package org.laborra.beantrace.renderers;
public class D3JSRenderer implements GraphRenderer {
private final Writer destinationWrite;
private final Reader templateReader;
public D3JSRenderer(Writer destinationWrite, Reader templateReader) {
this.destinationWrite = destinationWrite;
this.templateReader = templateReader;
}
@Override
public void render(Vertex subject) {
final StringWriter stringWriter = new StringWriter();
new JsonRenderer(stringWriter).render(subject);
try (
final BufferedReader bufferedReader = new BufferedReader(templateReader);
final PrintWriter printWriter = new PrintWriter(destinationWrite)
) {
String line;
while ((line = bufferedReader.readLine()) != null) {
final String toWriteLine = line.replace("###JSON_DATA_TOKEN###", stringWriter.toString());
printWriter.println(toWriteLine);
}
} catch (IOException e) { | throw new BeanTraceException(e); |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/handlers/SystemObjectHandler.java | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Vertex;
import java.util.HashMap;
import java.util.Map; | package org.laborra.beantrace.handlers;
/**
* This handler manage system object like System.out, in order to stop the scanning
* and collect more useful information.
*/
public class SystemObjectHandler implements VertexHandler {
private final Map<Integer, String> hashCodeToName;
public SystemObjectHandler(Map<Integer, String> hashCodeToName) {
this.hashCodeToName = hashCodeToName;
}
public static SystemObjectHandler makeDefault() {
final Map<Integer, String> map = new HashMap<>();
map.put(System.out.hashCode(), "System OUT");
map.put(System.err.hashCode(), "System ERR");
return new SystemObjectHandler(map);
}
@Override
public boolean canHandle(Object subject) {
return hashCodeToName.containsKey(subject.hashCode());
}
@Override | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/handlers/SystemObjectHandler.java
import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Vertex;
import java.util.HashMap;
import java.util.Map;
package org.laborra.beantrace.handlers;
/**
* This handler manage system object like System.out, in order to stop the scanning
* and collect more useful information.
*/
public class SystemObjectHandler implements VertexHandler {
private final Map<Integer, String> hashCodeToName;
public SystemObjectHandler(Map<Integer, String> hashCodeToName) {
this.hashCodeToName = hashCodeToName;
}
public static SystemObjectHandler makeDefault() {
final Map<Integer, String> map = new HashMap<>();
map.put(System.out.hashCode(), "System OUT");
map.put(System.err.hashCode(), "System ERR");
return new SystemObjectHandler(map);
}
@Override
public boolean canHandle(Object subject) {
return hashCodeToName.containsKey(subject.hashCode());
}
@Override | public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) { |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/handlers/SystemObjectHandler.java | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Vertex;
import java.util.HashMap;
import java.util.Map; | package org.laborra.beantrace.handlers;
/**
* This handler manage system object like System.out, in order to stop the scanning
* and collect more useful information.
*/
public class SystemObjectHandler implements VertexHandler {
private final Map<Integer, String> hashCodeToName;
public SystemObjectHandler(Map<Integer, String> hashCodeToName) {
this.hashCodeToName = hashCodeToName;
}
public static SystemObjectHandler makeDefault() {
final Map<Integer, String> map = new HashMap<>();
map.put(System.out.hashCode(), "System OUT");
map.put(System.err.hashCode(), "System ERR");
return new SystemObjectHandler(map);
}
@Override
public boolean canHandle(Object subject) {
return hashCodeToName.containsKey(subject.hashCode());
}
@Override | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/handlers/SystemObjectHandler.java
import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Vertex;
import java.util.HashMap;
import java.util.Map;
package org.laborra.beantrace.handlers;
/**
* This handler manage system object like System.out, in order to stop the scanning
* and collect more useful information.
*/
public class SystemObjectHandler implements VertexHandler {
private final Map<Integer, String> hashCodeToName;
public SystemObjectHandler(Map<Integer, String> hashCodeToName) {
this.hashCodeToName = hashCodeToName;
}
public static SystemObjectHandler makeDefault() {
final Map<Integer, String> map = new HashMap<>();
map.put(System.out.hashCode(), "System OUT");
map.put(System.err.hashCode(), "System ERR");
return new SystemObjectHandler(map);
}
@Override
public boolean canHandle(Object subject) {
return hashCodeToName.containsKey(subject.hashCode());
}
@Override | public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) { |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/handlers/SystemObjectHandler.java | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
| import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Vertex;
import java.util.HashMap;
import java.util.Map; | package org.laborra.beantrace.handlers;
/**
* This handler manage system object like System.out, in order to stop the scanning
* and collect more useful information.
*/
public class SystemObjectHandler implements VertexHandler {
private final Map<Integer, String> hashCodeToName;
public SystemObjectHandler(Map<Integer, String> hashCodeToName) {
this.hashCodeToName = hashCodeToName;
}
public static SystemObjectHandler makeDefault() {
final Map<Integer, String> map = new HashMap<>();
map.put(System.out.hashCode(), "System OUT");
map.put(System.err.hashCode(), "System ERR");
return new SystemObjectHandler(map);
}
@Override
public boolean canHandle(Object subject) {
return hashCodeToName.containsKey(subject.hashCode());
}
@Override
public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) { | // Path: src/main/java/org/laborra/beantrace/VertexFieldAdder.java
// public interface VertexFieldAdder {
// void addField(Vertex vertex, String fieldName, Object item);
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Attribute.java
// public class Attribute<T> {
// private String name;
// private T value;
//
// public Attribute(String name, T value) {
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public T getValue() {
// return value;
// }
// }
//
// Path: src/main/java/org/laborra/beantrace/model/Vertex.java
// public class Vertex {
// private Class<?> clazz;
// private String id;
// private Set<Edge> references = new HashSet<>();
// private Set<Attribute> attributes = new HashSet<>();
//
// public Vertex(Class<?> clazz, String id) {
// this(clazz, id, new HashSet<Edge>(), new HashSet<Attribute>());
// }
//
// public Vertex(Class<?> clazz, String id, Set<Edge> references, Set<Attribute> attributes) {
// this.id = id;
// this.clazz = clazz;
// this.references = references;
// this.attributes = attributes;
// }
//
// public Set<Edge> getReferences() {
// return references;
// }
//
// public Set<Attribute> getAttributes() {
// return attributes;
// }
//
// public Class<?> getClazz() {
// return clazz;
// }
//
// public String getId() {
// return id;
// }
// }
// Path: src/main/java/org/laborra/beantrace/handlers/SystemObjectHandler.java
import org.laborra.beantrace.VertexFieldAdder;
import org.laborra.beantrace.model.Attribute;
import org.laborra.beantrace.model.Vertex;
import java.util.HashMap;
import java.util.Map;
package org.laborra.beantrace.handlers;
/**
* This handler manage system object like System.out, in order to stop the scanning
* and collect more useful information.
*/
public class SystemObjectHandler implements VertexHandler {
private final Map<Integer, String> hashCodeToName;
public SystemObjectHandler(Map<Integer, String> hashCodeToName) {
this.hashCodeToName = hashCodeToName;
}
public static SystemObjectHandler makeDefault() {
final Map<Integer, String> map = new HashMap<>();
map.put(System.out.hashCode(), "System OUT");
map.put(System.err.hashCode(), "System ERR");
return new SystemObjectHandler(map);
}
@Override
public boolean canHandle(Object subject) {
return hashCodeToName.containsKey(subject.hashCode());
}
@Override
public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) { | vertex.getAttributes().add(new Attribute<>( |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/TraceConfiguration.java | // Path: src/main/java/org/laborra/beantrace/handlers/VertexHandler.java
// public interface VertexHandler {
//
// /**
// * Specifies if this handler can manage the subject.
// */
// boolean canHandle(Object subject);
//
// /**
// * Handle the passed vertex based on the subject.
// */
// void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder);
//
// class Composite implements VertexHandler {
//
// private final List<VertexHandler> delegates;
//
// public Composite(List<VertexHandler> delegates) {
// this.delegates = delegates;
// }
//
// @Override
// public boolean canHandle(Object subject) {
// for (VertexHandler vertexHandler : delegates) {
// if (vertexHandler.canHandle(subject)) {
// return true;
// }
// }
//
// return false;
// }
//
// @Override
// public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) {
// for (VertexHandler vertexHandler : delegates) {
// if (vertexHandler.canHandle(subject)) {
// vertexHandler.handle(vertex, subject, vertexFieldAdder);
// return;
// }
// }
// }
// }
//
// class MapVertexHandler extends TypeBasedHandler<Map<Object, Object>> {
//
// public MapVertexHandler() {
// super(Map.class);
// }
//
// @Override
// public void typedHandle(Vertex vertex, Map<Object, Object> subject, VertexFieldAdder vertexFieldAdder) {
// int i = -1;
// for (Map.Entry<Object, Object> entry : subject.entrySet()) {
// i++;
// final Object key = entry.getKey();
// final Object value = entry.getValue();
// final boolean primitiveKey = ReflectUtils.isPrimitive(key.getClass());
//
// if (primitiveKey) {
// vertexFieldAdder.addField(vertex, key.toString(), value);
// }
//
// if (!primitiveKey) {
// final Vertex entryVertex = new Vertex(Map.Entry.class, System.identityHashCode(entry) + "");
// vertexFieldAdder.addField(entryVertex, "key", key);
// vertexFieldAdder.addField(entryVertex, "value", value);
// vertex.getReferences().add(new Edge("entry_" + i, entryVertex));
// }
// }
// }
// }
//
// class ArrayHandler implements VertexHandler {
//
// public boolean canHandle(Object subject) {
// return subject.getClass().isArray();
// }
//
// public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) {
// int arrayLength = Array.getLength(subject);
// for (int i = 0; i < arrayLength; i++) {
// Object item = Array.get(subject, i);
// vertexFieldAdder.addField(vertex, i + "", item);
// }
// }
// }
//
// class ClassTypeHandler extends TypeBasedHandler<Class> {
//
// public ClassTypeHandler() {
// super(Class.class);
// }
//
// @Override
// protected void typedHandle(Vertex vertex, Class subject, VertexFieldAdder vertexFieldAdder) {
// vertexFieldAdder.addField(vertex, "name", subject.getName());
// }
// }
//
// }
//
// Path: src/main/java/org/laborra/beantrace/renderers/GraphRenderer.java
// public interface GraphRenderer {
// public void render(Vertex subject);
// }
//
// Path: src/main/java/org/laborra/beantrace/renderers/GraphRenderers.java
// public class GraphRenderers {
//
// /**
// * Creates a new {@link GraphvizDotRenderer} that writes the contents to the given
// * appendable.
// */
// public static GraphvizDotRenderer newGraphviz(Writer output) {
// return new GraphvizDotRenderer(output);
// }
//
// /**
// * Shortcut to create a file graphviz renderer.
// *
// * @see #newGraphviz(Writer)
// */
// public static GraphvizDotRenderer newGraphviz(File outputFile) {
// try {
// return newGraphviz(new BufferedWriter(new FileWriter(outputFile), 1));
// } catch (IOException e) {
// throw new BeanTraceException(e);
// }
// }
//
// /**
// * Creates a new {@link AsciiRenderer} that prints the graphs to the
// * standard output.
// */
// public static AsciiRenderer newAscii() {
// return newAscii(new PrintWriter(System.out));
// }
//
// /**
// * Creates a new {@link AsciiRenderer} that prints
// * the graph to the given appendable.
// *
// * @param output Where to write the graph
// * @return the create renderer
// */
// public static AsciiRenderer newAscii(Writer output) {
// final AsciiRenderer ret = new AsciiRenderer();
// ret.getConfig().setOutput(output);
// return ret;
// }
//
// /**
// * Shortcut to create an ascii renderer that writes to a file.
// *
// * @see #newAscii(Writer)
// */
// public static AsciiRenderer newAscii(File outputFile) {
// try {
// return newAscii(new BufferedWriter(new FileWriter(outputFile), 1));
// } catch (IOException e) {
// throw new BeanTraceException(e);
// }
// }
// }
| import org.laborra.beantrace.handlers.VertexHandler;
import org.laborra.beantrace.renderers.GraphRenderer;
import org.laborra.beantrace.renderers.GraphRenderers;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List; | package org.laborra.beantrace;
/**
* This class represents the bean trace algorithm options.
*/
public class TraceConfiguration {
/**
* Default max depth to stop when scanning objects.
*/
public static final Integer DEFAULT_MAX_DEPTH = 10;
/**
* The graph renderer to use.
*/ | // Path: src/main/java/org/laborra/beantrace/handlers/VertexHandler.java
// public interface VertexHandler {
//
// /**
// * Specifies if this handler can manage the subject.
// */
// boolean canHandle(Object subject);
//
// /**
// * Handle the passed vertex based on the subject.
// */
// void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder);
//
// class Composite implements VertexHandler {
//
// private final List<VertexHandler> delegates;
//
// public Composite(List<VertexHandler> delegates) {
// this.delegates = delegates;
// }
//
// @Override
// public boolean canHandle(Object subject) {
// for (VertexHandler vertexHandler : delegates) {
// if (vertexHandler.canHandle(subject)) {
// return true;
// }
// }
//
// return false;
// }
//
// @Override
// public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) {
// for (VertexHandler vertexHandler : delegates) {
// if (vertexHandler.canHandle(subject)) {
// vertexHandler.handle(vertex, subject, vertexFieldAdder);
// return;
// }
// }
// }
// }
//
// class MapVertexHandler extends TypeBasedHandler<Map<Object, Object>> {
//
// public MapVertexHandler() {
// super(Map.class);
// }
//
// @Override
// public void typedHandle(Vertex vertex, Map<Object, Object> subject, VertexFieldAdder vertexFieldAdder) {
// int i = -1;
// for (Map.Entry<Object, Object> entry : subject.entrySet()) {
// i++;
// final Object key = entry.getKey();
// final Object value = entry.getValue();
// final boolean primitiveKey = ReflectUtils.isPrimitive(key.getClass());
//
// if (primitiveKey) {
// vertexFieldAdder.addField(vertex, key.toString(), value);
// }
//
// if (!primitiveKey) {
// final Vertex entryVertex = new Vertex(Map.Entry.class, System.identityHashCode(entry) + "");
// vertexFieldAdder.addField(entryVertex, "key", key);
// vertexFieldAdder.addField(entryVertex, "value", value);
// vertex.getReferences().add(new Edge("entry_" + i, entryVertex));
// }
// }
// }
// }
//
// class ArrayHandler implements VertexHandler {
//
// public boolean canHandle(Object subject) {
// return subject.getClass().isArray();
// }
//
// public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) {
// int arrayLength = Array.getLength(subject);
// for (int i = 0; i < arrayLength; i++) {
// Object item = Array.get(subject, i);
// vertexFieldAdder.addField(vertex, i + "", item);
// }
// }
// }
//
// class ClassTypeHandler extends TypeBasedHandler<Class> {
//
// public ClassTypeHandler() {
// super(Class.class);
// }
//
// @Override
// protected void typedHandle(Vertex vertex, Class subject, VertexFieldAdder vertexFieldAdder) {
// vertexFieldAdder.addField(vertex, "name", subject.getName());
// }
// }
//
// }
//
// Path: src/main/java/org/laborra/beantrace/renderers/GraphRenderer.java
// public interface GraphRenderer {
// public void render(Vertex subject);
// }
//
// Path: src/main/java/org/laborra/beantrace/renderers/GraphRenderers.java
// public class GraphRenderers {
//
// /**
// * Creates a new {@link GraphvizDotRenderer} that writes the contents to the given
// * appendable.
// */
// public static GraphvizDotRenderer newGraphviz(Writer output) {
// return new GraphvizDotRenderer(output);
// }
//
// /**
// * Shortcut to create a file graphviz renderer.
// *
// * @see #newGraphviz(Writer)
// */
// public static GraphvizDotRenderer newGraphviz(File outputFile) {
// try {
// return newGraphviz(new BufferedWriter(new FileWriter(outputFile), 1));
// } catch (IOException e) {
// throw new BeanTraceException(e);
// }
// }
//
// /**
// * Creates a new {@link AsciiRenderer} that prints the graphs to the
// * standard output.
// */
// public static AsciiRenderer newAscii() {
// return newAscii(new PrintWriter(System.out));
// }
//
// /**
// * Creates a new {@link AsciiRenderer} that prints
// * the graph to the given appendable.
// *
// * @param output Where to write the graph
// * @return the create renderer
// */
// public static AsciiRenderer newAscii(Writer output) {
// final AsciiRenderer ret = new AsciiRenderer();
// ret.getConfig().setOutput(output);
// return ret;
// }
//
// /**
// * Shortcut to create an ascii renderer that writes to a file.
// *
// * @see #newAscii(Writer)
// */
// public static AsciiRenderer newAscii(File outputFile) {
// try {
// return newAscii(new BufferedWriter(new FileWriter(outputFile), 1));
// } catch (IOException e) {
// throw new BeanTraceException(e);
// }
// }
// }
// Path: src/main/java/org/laborra/beantrace/TraceConfiguration.java
import org.laborra.beantrace.handlers.VertexHandler;
import org.laborra.beantrace.renderers.GraphRenderer;
import org.laborra.beantrace.renderers.GraphRenderers;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
package org.laborra.beantrace;
/**
* This class represents the bean trace algorithm options.
*/
public class TraceConfiguration {
/**
* Default max depth to stop when scanning objects.
*/
public static final Integer DEFAULT_MAX_DEPTH = 10;
/**
* The graph renderer to use.
*/ | private GraphRenderer graphRenderer = GraphRenderers.newAscii(); |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/TraceConfiguration.java | // Path: src/main/java/org/laborra/beantrace/handlers/VertexHandler.java
// public interface VertexHandler {
//
// /**
// * Specifies if this handler can manage the subject.
// */
// boolean canHandle(Object subject);
//
// /**
// * Handle the passed vertex based on the subject.
// */
// void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder);
//
// class Composite implements VertexHandler {
//
// private final List<VertexHandler> delegates;
//
// public Composite(List<VertexHandler> delegates) {
// this.delegates = delegates;
// }
//
// @Override
// public boolean canHandle(Object subject) {
// for (VertexHandler vertexHandler : delegates) {
// if (vertexHandler.canHandle(subject)) {
// return true;
// }
// }
//
// return false;
// }
//
// @Override
// public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) {
// for (VertexHandler vertexHandler : delegates) {
// if (vertexHandler.canHandle(subject)) {
// vertexHandler.handle(vertex, subject, vertexFieldAdder);
// return;
// }
// }
// }
// }
//
// class MapVertexHandler extends TypeBasedHandler<Map<Object, Object>> {
//
// public MapVertexHandler() {
// super(Map.class);
// }
//
// @Override
// public void typedHandle(Vertex vertex, Map<Object, Object> subject, VertexFieldAdder vertexFieldAdder) {
// int i = -1;
// for (Map.Entry<Object, Object> entry : subject.entrySet()) {
// i++;
// final Object key = entry.getKey();
// final Object value = entry.getValue();
// final boolean primitiveKey = ReflectUtils.isPrimitive(key.getClass());
//
// if (primitiveKey) {
// vertexFieldAdder.addField(vertex, key.toString(), value);
// }
//
// if (!primitiveKey) {
// final Vertex entryVertex = new Vertex(Map.Entry.class, System.identityHashCode(entry) + "");
// vertexFieldAdder.addField(entryVertex, "key", key);
// vertexFieldAdder.addField(entryVertex, "value", value);
// vertex.getReferences().add(new Edge("entry_" + i, entryVertex));
// }
// }
// }
// }
//
// class ArrayHandler implements VertexHandler {
//
// public boolean canHandle(Object subject) {
// return subject.getClass().isArray();
// }
//
// public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) {
// int arrayLength = Array.getLength(subject);
// for (int i = 0; i < arrayLength; i++) {
// Object item = Array.get(subject, i);
// vertexFieldAdder.addField(vertex, i + "", item);
// }
// }
// }
//
// class ClassTypeHandler extends TypeBasedHandler<Class> {
//
// public ClassTypeHandler() {
// super(Class.class);
// }
//
// @Override
// protected void typedHandle(Vertex vertex, Class subject, VertexFieldAdder vertexFieldAdder) {
// vertexFieldAdder.addField(vertex, "name", subject.getName());
// }
// }
//
// }
//
// Path: src/main/java/org/laborra/beantrace/renderers/GraphRenderer.java
// public interface GraphRenderer {
// public void render(Vertex subject);
// }
//
// Path: src/main/java/org/laborra/beantrace/renderers/GraphRenderers.java
// public class GraphRenderers {
//
// /**
// * Creates a new {@link GraphvizDotRenderer} that writes the contents to the given
// * appendable.
// */
// public static GraphvizDotRenderer newGraphviz(Writer output) {
// return new GraphvizDotRenderer(output);
// }
//
// /**
// * Shortcut to create a file graphviz renderer.
// *
// * @see #newGraphviz(Writer)
// */
// public static GraphvizDotRenderer newGraphviz(File outputFile) {
// try {
// return newGraphviz(new BufferedWriter(new FileWriter(outputFile), 1));
// } catch (IOException e) {
// throw new BeanTraceException(e);
// }
// }
//
// /**
// * Creates a new {@link AsciiRenderer} that prints the graphs to the
// * standard output.
// */
// public static AsciiRenderer newAscii() {
// return newAscii(new PrintWriter(System.out));
// }
//
// /**
// * Creates a new {@link AsciiRenderer} that prints
// * the graph to the given appendable.
// *
// * @param output Where to write the graph
// * @return the create renderer
// */
// public static AsciiRenderer newAscii(Writer output) {
// final AsciiRenderer ret = new AsciiRenderer();
// ret.getConfig().setOutput(output);
// return ret;
// }
//
// /**
// * Shortcut to create an ascii renderer that writes to a file.
// *
// * @see #newAscii(Writer)
// */
// public static AsciiRenderer newAscii(File outputFile) {
// try {
// return newAscii(new BufferedWriter(new FileWriter(outputFile), 1));
// } catch (IOException e) {
// throw new BeanTraceException(e);
// }
// }
// }
| import org.laborra.beantrace.handlers.VertexHandler;
import org.laborra.beantrace.renderers.GraphRenderer;
import org.laborra.beantrace.renderers.GraphRenderers;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List; | package org.laborra.beantrace;
/**
* This class represents the bean trace algorithm options.
*/
public class TraceConfiguration {
/**
* Default max depth to stop when scanning objects.
*/
public static final Integer DEFAULT_MAX_DEPTH = 10;
/**
* The graph renderer to use.
*/ | // Path: src/main/java/org/laborra/beantrace/handlers/VertexHandler.java
// public interface VertexHandler {
//
// /**
// * Specifies if this handler can manage the subject.
// */
// boolean canHandle(Object subject);
//
// /**
// * Handle the passed vertex based on the subject.
// */
// void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder);
//
// class Composite implements VertexHandler {
//
// private final List<VertexHandler> delegates;
//
// public Composite(List<VertexHandler> delegates) {
// this.delegates = delegates;
// }
//
// @Override
// public boolean canHandle(Object subject) {
// for (VertexHandler vertexHandler : delegates) {
// if (vertexHandler.canHandle(subject)) {
// return true;
// }
// }
//
// return false;
// }
//
// @Override
// public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) {
// for (VertexHandler vertexHandler : delegates) {
// if (vertexHandler.canHandle(subject)) {
// vertexHandler.handle(vertex, subject, vertexFieldAdder);
// return;
// }
// }
// }
// }
//
// class MapVertexHandler extends TypeBasedHandler<Map<Object, Object>> {
//
// public MapVertexHandler() {
// super(Map.class);
// }
//
// @Override
// public void typedHandle(Vertex vertex, Map<Object, Object> subject, VertexFieldAdder vertexFieldAdder) {
// int i = -1;
// for (Map.Entry<Object, Object> entry : subject.entrySet()) {
// i++;
// final Object key = entry.getKey();
// final Object value = entry.getValue();
// final boolean primitiveKey = ReflectUtils.isPrimitive(key.getClass());
//
// if (primitiveKey) {
// vertexFieldAdder.addField(vertex, key.toString(), value);
// }
//
// if (!primitiveKey) {
// final Vertex entryVertex = new Vertex(Map.Entry.class, System.identityHashCode(entry) + "");
// vertexFieldAdder.addField(entryVertex, "key", key);
// vertexFieldAdder.addField(entryVertex, "value", value);
// vertex.getReferences().add(new Edge("entry_" + i, entryVertex));
// }
// }
// }
// }
//
// class ArrayHandler implements VertexHandler {
//
// public boolean canHandle(Object subject) {
// return subject.getClass().isArray();
// }
//
// public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) {
// int arrayLength = Array.getLength(subject);
// for (int i = 0; i < arrayLength; i++) {
// Object item = Array.get(subject, i);
// vertexFieldAdder.addField(vertex, i + "", item);
// }
// }
// }
//
// class ClassTypeHandler extends TypeBasedHandler<Class> {
//
// public ClassTypeHandler() {
// super(Class.class);
// }
//
// @Override
// protected void typedHandle(Vertex vertex, Class subject, VertexFieldAdder vertexFieldAdder) {
// vertexFieldAdder.addField(vertex, "name", subject.getName());
// }
// }
//
// }
//
// Path: src/main/java/org/laborra/beantrace/renderers/GraphRenderer.java
// public interface GraphRenderer {
// public void render(Vertex subject);
// }
//
// Path: src/main/java/org/laborra/beantrace/renderers/GraphRenderers.java
// public class GraphRenderers {
//
// /**
// * Creates a new {@link GraphvizDotRenderer} that writes the contents to the given
// * appendable.
// */
// public static GraphvizDotRenderer newGraphviz(Writer output) {
// return new GraphvizDotRenderer(output);
// }
//
// /**
// * Shortcut to create a file graphviz renderer.
// *
// * @see #newGraphviz(Writer)
// */
// public static GraphvizDotRenderer newGraphviz(File outputFile) {
// try {
// return newGraphviz(new BufferedWriter(new FileWriter(outputFile), 1));
// } catch (IOException e) {
// throw new BeanTraceException(e);
// }
// }
//
// /**
// * Creates a new {@link AsciiRenderer} that prints the graphs to the
// * standard output.
// */
// public static AsciiRenderer newAscii() {
// return newAscii(new PrintWriter(System.out));
// }
//
// /**
// * Creates a new {@link AsciiRenderer} that prints
// * the graph to the given appendable.
// *
// * @param output Where to write the graph
// * @return the create renderer
// */
// public static AsciiRenderer newAscii(Writer output) {
// final AsciiRenderer ret = new AsciiRenderer();
// ret.getConfig().setOutput(output);
// return ret;
// }
//
// /**
// * Shortcut to create an ascii renderer that writes to a file.
// *
// * @see #newAscii(Writer)
// */
// public static AsciiRenderer newAscii(File outputFile) {
// try {
// return newAscii(new BufferedWriter(new FileWriter(outputFile), 1));
// } catch (IOException e) {
// throw new BeanTraceException(e);
// }
// }
// }
// Path: src/main/java/org/laborra/beantrace/TraceConfiguration.java
import org.laborra.beantrace.handlers.VertexHandler;
import org.laborra.beantrace.renderers.GraphRenderer;
import org.laborra.beantrace.renderers.GraphRenderers;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
package org.laborra.beantrace;
/**
* This class represents the bean trace algorithm options.
*/
public class TraceConfiguration {
/**
* Default max depth to stop when scanning objects.
*/
public static final Integer DEFAULT_MAX_DEPTH = 10;
/**
* The graph renderer to use.
*/ | private GraphRenderer graphRenderer = GraphRenderers.newAscii(); |
zeeke/bean-trace | src/main/java/org/laborra/beantrace/TraceConfiguration.java | // Path: src/main/java/org/laborra/beantrace/handlers/VertexHandler.java
// public interface VertexHandler {
//
// /**
// * Specifies if this handler can manage the subject.
// */
// boolean canHandle(Object subject);
//
// /**
// * Handle the passed vertex based on the subject.
// */
// void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder);
//
// class Composite implements VertexHandler {
//
// private final List<VertexHandler> delegates;
//
// public Composite(List<VertexHandler> delegates) {
// this.delegates = delegates;
// }
//
// @Override
// public boolean canHandle(Object subject) {
// for (VertexHandler vertexHandler : delegates) {
// if (vertexHandler.canHandle(subject)) {
// return true;
// }
// }
//
// return false;
// }
//
// @Override
// public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) {
// for (VertexHandler vertexHandler : delegates) {
// if (vertexHandler.canHandle(subject)) {
// vertexHandler.handle(vertex, subject, vertexFieldAdder);
// return;
// }
// }
// }
// }
//
// class MapVertexHandler extends TypeBasedHandler<Map<Object, Object>> {
//
// public MapVertexHandler() {
// super(Map.class);
// }
//
// @Override
// public void typedHandle(Vertex vertex, Map<Object, Object> subject, VertexFieldAdder vertexFieldAdder) {
// int i = -1;
// for (Map.Entry<Object, Object> entry : subject.entrySet()) {
// i++;
// final Object key = entry.getKey();
// final Object value = entry.getValue();
// final boolean primitiveKey = ReflectUtils.isPrimitive(key.getClass());
//
// if (primitiveKey) {
// vertexFieldAdder.addField(vertex, key.toString(), value);
// }
//
// if (!primitiveKey) {
// final Vertex entryVertex = new Vertex(Map.Entry.class, System.identityHashCode(entry) + "");
// vertexFieldAdder.addField(entryVertex, "key", key);
// vertexFieldAdder.addField(entryVertex, "value", value);
// vertex.getReferences().add(new Edge("entry_" + i, entryVertex));
// }
// }
// }
// }
//
// class ArrayHandler implements VertexHandler {
//
// public boolean canHandle(Object subject) {
// return subject.getClass().isArray();
// }
//
// public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) {
// int arrayLength = Array.getLength(subject);
// for (int i = 0; i < arrayLength; i++) {
// Object item = Array.get(subject, i);
// vertexFieldAdder.addField(vertex, i + "", item);
// }
// }
// }
//
// class ClassTypeHandler extends TypeBasedHandler<Class> {
//
// public ClassTypeHandler() {
// super(Class.class);
// }
//
// @Override
// protected void typedHandle(Vertex vertex, Class subject, VertexFieldAdder vertexFieldAdder) {
// vertexFieldAdder.addField(vertex, "name", subject.getName());
// }
// }
//
// }
//
// Path: src/main/java/org/laborra/beantrace/renderers/GraphRenderer.java
// public interface GraphRenderer {
// public void render(Vertex subject);
// }
//
// Path: src/main/java/org/laborra/beantrace/renderers/GraphRenderers.java
// public class GraphRenderers {
//
// /**
// * Creates a new {@link GraphvizDotRenderer} that writes the contents to the given
// * appendable.
// */
// public static GraphvizDotRenderer newGraphviz(Writer output) {
// return new GraphvizDotRenderer(output);
// }
//
// /**
// * Shortcut to create a file graphviz renderer.
// *
// * @see #newGraphviz(Writer)
// */
// public static GraphvizDotRenderer newGraphviz(File outputFile) {
// try {
// return newGraphviz(new BufferedWriter(new FileWriter(outputFile), 1));
// } catch (IOException e) {
// throw new BeanTraceException(e);
// }
// }
//
// /**
// * Creates a new {@link AsciiRenderer} that prints the graphs to the
// * standard output.
// */
// public static AsciiRenderer newAscii() {
// return newAscii(new PrintWriter(System.out));
// }
//
// /**
// * Creates a new {@link AsciiRenderer} that prints
// * the graph to the given appendable.
// *
// * @param output Where to write the graph
// * @return the create renderer
// */
// public static AsciiRenderer newAscii(Writer output) {
// final AsciiRenderer ret = new AsciiRenderer();
// ret.getConfig().setOutput(output);
// return ret;
// }
//
// /**
// * Shortcut to create an ascii renderer that writes to a file.
// *
// * @see #newAscii(Writer)
// */
// public static AsciiRenderer newAscii(File outputFile) {
// try {
// return newAscii(new BufferedWriter(new FileWriter(outputFile), 1));
// } catch (IOException e) {
// throw new BeanTraceException(e);
// }
// }
// }
| import org.laborra.beantrace.handlers.VertexHandler;
import org.laborra.beantrace.renderers.GraphRenderer;
import org.laborra.beantrace.renderers.GraphRenderers;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List; | package org.laborra.beantrace;
/**
* This class represents the bean trace algorithm options.
*/
public class TraceConfiguration {
/**
* Default max depth to stop when scanning objects.
*/
public static final Integer DEFAULT_MAX_DEPTH = 10;
/**
* The graph renderer to use.
*/
private GraphRenderer graphRenderer = GraphRenderers.newAscii(); | // Path: src/main/java/org/laborra/beantrace/handlers/VertexHandler.java
// public interface VertexHandler {
//
// /**
// * Specifies if this handler can manage the subject.
// */
// boolean canHandle(Object subject);
//
// /**
// * Handle the passed vertex based on the subject.
// */
// void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder);
//
// class Composite implements VertexHandler {
//
// private final List<VertexHandler> delegates;
//
// public Composite(List<VertexHandler> delegates) {
// this.delegates = delegates;
// }
//
// @Override
// public boolean canHandle(Object subject) {
// for (VertexHandler vertexHandler : delegates) {
// if (vertexHandler.canHandle(subject)) {
// return true;
// }
// }
//
// return false;
// }
//
// @Override
// public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) {
// for (VertexHandler vertexHandler : delegates) {
// if (vertexHandler.canHandle(subject)) {
// vertexHandler.handle(vertex, subject, vertexFieldAdder);
// return;
// }
// }
// }
// }
//
// class MapVertexHandler extends TypeBasedHandler<Map<Object, Object>> {
//
// public MapVertexHandler() {
// super(Map.class);
// }
//
// @Override
// public void typedHandle(Vertex vertex, Map<Object, Object> subject, VertexFieldAdder vertexFieldAdder) {
// int i = -1;
// for (Map.Entry<Object, Object> entry : subject.entrySet()) {
// i++;
// final Object key = entry.getKey();
// final Object value = entry.getValue();
// final boolean primitiveKey = ReflectUtils.isPrimitive(key.getClass());
//
// if (primitiveKey) {
// vertexFieldAdder.addField(vertex, key.toString(), value);
// }
//
// if (!primitiveKey) {
// final Vertex entryVertex = new Vertex(Map.Entry.class, System.identityHashCode(entry) + "");
// vertexFieldAdder.addField(entryVertex, "key", key);
// vertexFieldAdder.addField(entryVertex, "value", value);
// vertex.getReferences().add(new Edge("entry_" + i, entryVertex));
// }
// }
// }
// }
//
// class ArrayHandler implements VertexHandler {
//
// public boolean canHandle(Object subject) {
// return subject.getClass().isArray();
// }
//
// public void handle(Vertex vertex, Object subject, VertexFieldAdder vertexFieldAdder) {
// int arrayLength = Array.getLength(subject);
// for (int i = 0; i < arrayLength; i++) {
// Object item = Array.get(subject, i);
// vertexFieldAdder.addField(vertex, i + "", item);
// }
// }
// }
//
// class ClassTypeHandler extends TypeBasedHandler<Class> {
//
// public ClassTypeHandler() {
// super(Class.class);
// }
//
// @Override
// protected void typedHandle(Vertex vertex, Class subject, VertexFieldAdder vertexFieldAdder) {
// vertexFieldAdder.addField(vertex, "name", subject.getName());
// }
// }
//
// }
//
// Path: src/main/java/org/laborra/beantrace/renderers/GraphRenderer.java
// public interface GraphRenderer {
// public void render(Vertex subject);
// }
//
// Path: src/main/java/org/laborra/beantrace/renderers/GraphRenderers.java
// public class GraphRenderers {
//
// /**
// * Creates a new {@link GraphvizDotRenderer} that writes the contents to the given
// * appendable.
// */
// public static GraphvizDotRenderer newGraphviz(Writer output) {
// return new GraphvizDotRenderer(output);
// }
//
// /**
// * Shortcut to create a file graphviz renderer.
// *
// * @see #newGraphviz(Writer)
// */
// public static GraphvizDotRenderer newGraphviz(File outputFile) {
// try {
// return newGraphviz(new BufferedWriter(new FileWriter(outputFile), 1));
// } catch (IOException e) {
// throw new BeanTraceException(e);
// }
// }
//
// /**
// * Creates a new {@link AsciiRenderer} that prints the graphs to the
// * standard output.
// */
// public static AsciiRenderer newAscii() {
// return newAscii(new PrintWriter(System.out));
// }
//
// /**
// * Creates a new {@link AsciiRenderer} that prints
// * the graph to the given appendable.
// *
// * @param output Where to write the graph
// * @return the create renderer
// */
// public static AsciiRenderer newAscii(Writer output) {
// final AsciiRenderer ret = new AsciiRenderer();
// ret.getConfig().setOutput(output);
// return ret;
// }
//
// /**
// * Shortcut to create an ascii renderer that writes to a file.
// *
// * @see #newAscii(Writer)
// */
// public static AsciiRenderer newAscii(File outputFile) {
// try {
// return newAscii(new BufferedWriter(new FileWriter(outputFile), 1));
// } catch (IOException e) {
// throw new BeanTraceException(e);
// }
// }
// }
// Path: src/main/java/org/laborra/beantrace/TraceConfiguration.java
import org.laborra.beantrace.handlers.VertexHandler;
import org.laborra.beantrace.renderers.GraphRenderer;
import org.laborra.beantrace.renderers.GraphRenderers;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
package org.laborra.beantrace;
/**
* This class represents the bean trace algorithm options.
*/
public class TraceConfiguration {
/**
* Default max depth to stop when scanning objects.
*/
public static final Integer DEFAULT_MAX_DEPTH = 10;
/**
* The graph renderer to use.
*/
private GraphRenderer graphRenderer = GraphRenderers.newAscii(); | private List<VertexHandler> customHandlers = new LinkedList<>(); |
cloudendpoints/endpoints-management-java | endpoints-control/src/main/java/com/google/api/control/model/MethodRegistry.java | // Path: endpoints-control/src/main/java/com/google/api/control/util/StringUtils.java
// public final class StringUtils {
// /**
// * Strips the trailing slash from a string if it has a trailing slash; otherwise return the
// * string unchanged.
// */
// public static String stripTrailingSlash(String s) {
// return s == null ? null : CharMatcher.is('/').trimTrailingFrom(s);
// }
//
// private StringUtils() { }
// }
| import com.google.api.AuthRequirement;
import com.google.api.AuthenticationRule;
import com.google.api.HttpRule;
import com.google.api.MetricRule;
import com.google.api.Service;
import com.google.api.SystemParameter;
import com.google.api.SystemParameterRule;
import com.google.api.UsageRule;
import com.google.api.control.util.StringUtils;
import com.google.auto.value.AutoValue;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.flogger.FluentLogger;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable; | /*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.api.control.model;
/**
* MethodRegistry provides registry of the API methods defined by a Service.
*/
public class MethodRegistry {
private static final FluentLogger log = FluentLogger.forEnclosingClass();
private static final String OPTIONS_VERB = "OPTIONS";
private final Service theService;
private final Map<String, AuthInfo> authInfos;
private final Map<String, QuotaInfo> quotaInfos;
private final Map<String, List<Info>> infosByHttpMethod;
private final Map<String, Info> extractedMethods;
/**
* @param s contains the methods to be registered
*/
public MethodRegistry(Service s) {
Preconditions.checkNotNull(s, "The service must be specified");
Preconditions.checkArgument(!Strings.isNullOrEmpty(s.getName()),
"The service name must be specified");
theService = s;
infosByHttpMethod = Maps.newHashMap();
extractedMethods = Maps.newHashMap();
authInfos = extractAuth(s);
quotaInfos = extractQuota(s);
extractMethods();
}
/**
* Finds the {@code Info} instance that matches {@code httpMethod} and {@code url}.
*
* @param httpMethod the method of a HTTP request
* @param url the url of a HTTP request
* @return an {@code Info} corresponding to the url and method, or null if none is found
*/
public @Nullable Info lookup(String httpMethod, String url) {
httpMethod = httpMethod.toLowerCase();
if (url.startsWith("/")) {
url = url.substring(1);
} | // Path: endpoints-control/src/main/java/com/google/api/control/util/StringUtils.java
// public final class StringUtils {
// /**
// * Strips the trailing slash from a string if it has a trailing slash; otherwise return the
// * string unchanged.
// */
// public static String stripTrailingSlash(String s) {
// return s == null ? null : CharMatcher.is('/').trimTrailingFrom(s);
// }
//
// private StringUtils() { }
// }
// Path: endpoints-control/src/main/java/com/google/api/control/model/MethodRegistry.java
import com.google.api.AuthRequirement;
import com.google.api.AuthenticationRule;
import com.google.api.HttpRule;
import com.google.api.MetricRule;
import com.google.api.Service;
import com.google.api.SystemParameter;
import com.google.api.SystemParameterRule;
import com.google.api.UsageRule;
import com.google.api.control.util.StringUtils;
import com.google.auto.value.AutoValue;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.flogger.FluentLogger;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.api.control.model;
/**
* MethodRegistry provides registry of the API methods defined by a Service.
*/
public class MethodRegistry {
private static final FluentLogger log = FluentLogger.forEnclosingClass();
private static final String OPTIONS_VERB = "OPTIONS";
private final Service theService;
private final Map<String, AuthInfo> authInfos;
private final Map<String, QuotaInfo> quotaInfos;
private final Map<String, List<Info>> infosByHttpMethod;
private final Map<String, Info> extractedMethods;
/**
* @param s contains the methods to be registered
*/
public MethodRegistry(Service s) {
Preconditions.checkNotNull(s, "The service must be specified");
Preconditions.checkArgument(!Strings.isNullOrEmpty(s.getName()),
"The service name must be specified");
theService = s;
infosByHttpMethod = Maps.newHashMap();
extractedMethods = Maps.newHashMap();
authInfos = extractAuth(s);
quotaInfos = extractQuota(s);
extractMethods();
}
/**
* Finds the {@code Info} instance that matches {@code httpMethod} and {@code url}.
*
* @param httpMethod the method of a HTTP request
* @param url the url of a HTTP request
* @return an {@code Info} corresponding to the url and method, or null if none is found
*/
public @Nullable Info lookup(String httpMethod, String url) {
httpMethod = httpMethod.toLowerCase();
if (url.startsWith("/")) {
url = url.substring(1);
} | url = StringUtils.stripTrailingSlash(url); |
cloudendpoints/endpoints-management-java | endpoints-control/src/main/java/com/google/api/control/ServiceManagementConfigFilter.java | // Path: endpoints-service-config/src/main/java/com/google/api/config/ServiceConfigFetcher.java
// public class ServiceConfigFetcher {
//
// private final Supplier<Service> serviceSupplier;
//
// @VisibleForTesting
// ServiceConfigFetcher(Supplier<Service> supplier) {
// this.serviceSupplier = Suppliers.memoizeWithExpiration(supplier, 10, TimeUnit.MINUTES);
// }
//
// public Service fetch() {
// return this.serviceSupplier.get();
// }
//
// public static ServiceConfigFetcher create() {
// return new ServiceConfigFetcher(ServiceConfigSupplier.create());
// }
// }
| import com.google.api.Service;
import com.google.api.config.ServiceConfigFetcher;
import java.io.IOException; | /*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.api.control;
/**
* ServiceManagementConfigFilter is a {@link ConfigFilter} where the service definition is loaded
* from the service management api.
*/
public class ServiceManagementConfigFilter extends ConfigFilter {
private static final Loader LOADER = new Loader() {
@Override
public Service load() throws IOException { | // Path: endpoints-service-config/src/main/java/com/google/api/config/ServiceConfigFetcher.java
// public class ServiceConfigFetcher {
//
// private final Supplier<Service> serviceSupplier;
//
// @VisibleForTesting
// ServiceConfigFetcher(Supplier<Service> supplier) {
// this.serviceSupplier = Suppliers.memoizeWithExpiration(supplier, 10, TimeUnit.MINUTES);
// }
//
// public Service fetch() {
// return this.serviceSupplier.get();
// }
//
// public static ServiceConfigFetcher create() {
// return new ServiceConfigFetcher(ServiceConfigSupplier.create());
// }
// }
// Path: endpoints-control/src/main/java/com/google/api/control/ServiceManagementConfigFilter.java
import com.google.api.Service;
import com.google.api.config.ServiceConfigFetcher;
import java.io.IOException;
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.api.control;
/**
* ServiceManagementConfigFilter is a {@link ConfigFilter} where the service definition is loaded
* from the service management api.
*/
public class ServiceManagementConfigFilter extends ConfigFilter {
private static final Loader LOADER = new Loader() {
@Override
public Service load() throws IOException { | return ServiceConfigFetcher.create().fetch(); |
cloudendpoints/endpoints-management-java | endpoints-auth/src/integration-test/java/com/google/api/auth/IntegrationTest.java | // Path: endpoints-control/src/main/java/com/google/api/control/model/MethodRegistry.java
// public static final class AuthInfo {
// private final Map<String, Set<String>> providerIdsToAudiences;
//
// public AuthInfo(Map<String, Set<String>> providerIdsToAudiences) {
// Preconditions.checkNotNull(providerIdsToAudiences);
// this.providerIdsToAudiences = providerIdsToAudiences;
// }
//
// public boolean isProviderIdAllowed(String providerid) {
// Preconditions.checkNotNull(providerid);
// return this.providerIdsToAudiences.containsKey(providerid);
// }
//
// public Set<String> getAudiencesForProvider(String providerId) {
// Preconditions.checkNotNull(providerId);
//
// if (this.providerIdsToAudiences.containsKey(providerId)) {
// return this.providerIdsToAudiences.get(providerId);
// }
// return ImmutableSet.<String>of();
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.api.AuthProvider;
import com.google.api.AuthProvider.Builder;
import com.google.api.Authentication;
import com.google.api.client.util.Clock;
import com.google.api.control.model.MethodRegistry.AuthInfo;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.net.HttpHeaders;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.jose4j.jwk.JsonWebKeySet;
import org.jose4j.jwk.RsaJsonWebKey;
import org.jose4j.jwt.NumericDate;
import org.jose4j.lang.JoseException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType; | /*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.api.auth;
public final class IntegrationTest {
private static final String JWKS_PATH = "jwks";
private static final String X509_PATH = "x509";
private static final int TEST_SERVER_PORT = 8765;
private static final String ISSUER = "https://localhost" + ":" + TEST_SERVER_PORT;
private static final String PROVIDER_ID = "provider-id";
private static final String TEST_SERVER_URL = ISSUER;
private static final String KEY_ID = "key-id";
private static final RsaJsonWebKey RSA_JSON_WEB_KEY = TestUtils.generateRsaJsonWebKey(KEY_ID);
private static final Set<String> AUDIENCES = ImmutableSet.of("aud1", "aud2");
private static final String EMAIL = "[email protected]";
private static final String SERVICE_NAME = "service-name";
private static final String SUBJECT = "subject-id";
private static final Map<String, Set<String>> PROVIDER_ID_AUDIENCES =
ImmutableMap.of(PROVIDER_ID, AUDIENCES);
private static final IntegrationTestServer server =
new IntegrationTestServer(TEST_SERVER_PORT, Resource.class);
private final HttpServletRequest httpRequest = mock(HttpServletRequest.class); | // Path: endpoints-control/src/main/java/com/google/api/control/model/MethodRegistry.java
// public static final class AuthInfo {
// private final Map<String, Set<String>> providerIdsToAudiences;
//
// public AuthInfo(Map<String, Set<String>> providerIdsToAudiences) {
// Preconditions.checkNotNull(providerIdsToAudiences);
// this.providerIdsToAudiences = providerIdsToAudiences;
// }
//
// public boolean isProviderIdAllowed(String providerid) {
// Preconditions.checkNotNull(providerid);
// return this.providerIdsToAudiences.containsKey(providerid);
// }
//
// public Set<String> getAudiencesForProvider(String providerId) {
// Preconditions.checkNotNull(providerId);
//
// if (this.providerIdsToAudiences.containsKey(providerId)) {
// return this.providerIdsToAudiences.get(providerId);
// }
// return ImmutableSet.<String>of();
// }
// }
// Path: endpoints-auth/src/integration-test/java/com/google/api/auth/IntegrationTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.api.AuthProvider;
import com.google.api.AuthProvider.Builder;
import com.google.api.Authentication;
import com.google.api.client.util.Clock;
import com.google.api.control.model.MethodRegistry.AuthInfo;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.net.HttpHeaders;
import com.google.common.util.concurrent.UncheckedExecutionException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.jose4j.jwk.JsonWebKeySet;
import org.jose4j.jwk.RsaJsonWebKey;
import org.jose4j.jwt.NumericDate;
import org.jose4j.lang.JoseException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.api.auth;
public final class IntegrationTest {
private static final String JWKS_PATH = "jwks";
private static final String X509_PATH = "x509";
private static final int TEST_SERVER_PORT = 8765;
private static final String ISSUER = "https://localhost" + ":" + TEST_SERVER_PORT;
private static final String PROVIDER_ID = "provider-id";
private static final String TEST_SERVER_URL = ISSUER;
private static final String KEY_ID = "key-id";
private static final RsaJsonWebKey RSA_JSON_WEB_KEY = TestUtils.generateRsaJsonWebKey(KEY_ID);
private static final Set<String> AUDIENCES = ImmutableSet.of("aud1", "aud2");
private static final String EMAIL = "[email protected]";
private static final String SERVICE_NAME = "service-name";
private static final String SUBJECT = "subject-id";
private static final Map<String, Set<String>> PROVIDER_ID_AUDIENCES =
ImmutableMap.of(PROVIDER_ID, AUDIENCES);
private static final IntegrationTestServer server =
new IntegrationTestServer(TEST_SERVER_PORT, Resource.class);
private final HttpServletRequest httpRequest = mock(HttpServletRequest.class); | private final AuthInfo authInfo = new AuthInfo(PROVIDER_ID_AUDIENCES); |
cloudendpoints/endpoints-management-java | endpoints-control/src/main/java/com/google/api/control/aggregator/QuotaOperationAggregator.java | // Path: endpoints-control/src/main/java/com/google/api/control/model/Timestamps.java
// public final class Timestamps {
// private static final int MILLIS_PER_SECOND = 1000;
// private static final int NANOS_PER_MILLI = 1000000;
//
// private Timestamps() {}
//
// /**
// * A {@code Comparator} of {@link Timestamp}
// */
// public static Comparator<Timestamp> COMPARATOR = new Comparator<Timestamp>() {
// @Override
// public int compare(Timestamp o1, Timestamp o2) {
// int secondsOrder = Long.compare(o1.getSeconds(), o2.getSeconds());
// if (secondsOrder != 0) {
// return secondsOrder;
// } else {
// return Long.compare(o1.getNanos(), o2.getNanos());
// }
// }
// };
//
// /**
// * Obtain the current time from a {@link Clock}
// *
// * @param clock gives the current time
// * @return a {@code Timestamp} corresponding to the ticker's current value
// */
// public static Timestamp now(Clock clock) {
// return fromEpoch(clock.currentTimeMillis());
// }
//
// /**
// * Obtain the current time from the unix epoch
// *
// * @param epochMillis gives the current time in milliseconds since since the epoch
// * @return a {@code Timestamp} corresponding to the ticker's current value
// */
// public static Timestamp fromEpoch(long epochMillis) {
// return Timestamp
// .newBuilder()
// .setNanos((int) ((epochMillis % MILLIS_PER_SECOND) * NANOS_PER_MILLI))
// .setSeconds(epochMillis / MILLIS_PER_SECOND)
// .build();
// }
// }
| import com.google.api.MetricDescriptor.MetricKind;
import com.google.api.control.model.Timestamps;
import com.google.api.servicecontrol.v1.MetricValue;
import com.google.api.servicecontrol.v1.MetricValueSet;
import com.google.api.servicecontrol.v1.QuotaOperation;
import com.google.common.collect.Maps;
import com.google.common.flogger.FluentLogger;
import java.util.Map; | MetricValue val = metricValueSets.get(mvSet.getMetricName());
if (val == null) {
metricValueSets.put(mvSet.getMetricName(), mvSet.getMetricValues(0));
} else {
metricValueSets.put(
mvSet.getMetricName(),
MetricValues.merge(MetricKind.DELTA, val, mvSet.getMetricValues(0)));
}
}
}
public QuotaOperation asQuotaOperation() {
QuotaOperation.Builder op = this.op.clone().clearQuotaMetrics();
for (Map.Entry<String, MetricValue> entry : metricValueSets.entrySet()) {
op.addQuotaMetrics(MetricValueSet.newBuilder()
.setMetricName(entry.getKey())
.addMetricValues(entry.getValue()));
}
return op.build();
}
private MetricValue mergeDeltaMetricValue(MetricValue from, MetricValue to) {
if (to.getValueCase() != from.getValueCase()) {
log.atWarning().log("Could not merge different types of metric: %s, %s", from, to);
return to;
}
MetricValue.Builder builder = to.toBuilder();
if (from.hasStartTime()) {
if (!to.hasStartTime() || | // Path: endpoints-control/src/main/java/com/google/api/control/model/Timestamps.java
// public final class Timestamps {
// private static final int MILLIS_PER_SECOND = 1000;
// private static final int NANOS_PER_MILLI = 1000000;
//
// private Timestamps() {}
//
// /**
// * A {@code Comparator} of {@link Timestamp}
// */
// public static Comparator<Timestamp> COMPARATOR = new Comparator<Timestamp>() {
// @Override
// public int compare(Timestamp o1, Timestamp o2) {
// int secondsOrder = Long.compare(o1.getSeconds(), o2.getSeconds());
// if (secondsOrder != 0) {
// return secondsOrder;
// } else {
// return Long.compare(o1.getNanos(), o2.getNanos());
// }
// }
// };
//
// /**
// * Obtain the current time from a {@link Clock}
// *
// * @param clock gives the current time
// * @return a {@code Timestamp} corresponding to the ticker's current value
// */
// public static Timestamp now(Clock clock) {
// return fromEpoch(clock.currentTimeMillis());
// }
//
// /**
// * Obtain the current time from the unix epoch
// *
// * @param epochMillis gives the current time in milliseconds since since the epoch
// * @return a {@code Timestamp} corresponding to the ticker's current value
// */
// public static Timestamp fromEpoch(long epochMillis) {
// return Timestamp
// .newBuilder()
// .setNanos((int) ((epochMillis % MILLIS_PER_SECOND) * NANOS_PER_MILLI))
// .setSeconds(epochMillis / MILLIS_PER_SECOND)
// .build();
// }
// }
// Path: endpoints-control/src/main/java/com/google/api/control/aggregator/QuotaOperationAggregator.java
import com.google.api.MetricDescriptor.MetricKind;
import com.google.api.control.model.Timestamps;
import com.google.api.servicecontrol.v1.MetricValue;
import com.google.api.servicecontrol.v1.MetricValueSet;
import com.google.api.servicecontrol.v1.QuotaOperation;
import com.google.common.collect.Maps;
import com.google.common.flogger.FluentLogger;
import java.util.Map;
MetricValue val = metricValueSets.get(mvSet.getMetricName());
if (val == null) {
metricValueSets.put(mvSet.getMetricName(), mvSet.getMetricValues(0));
} else {
metricValueSets.put(
mvSet.getMetricName(),
MetricValues.merge(MetricKind.DELTA, val, mvSet.getMetricValues(0)));
}
}
}
public QuotaOperation asQuotaOperation() {
QuotaOperation.Builder op = this.op.clone().clearQuotaMetrics();
for (Map.Entry<String, MetricValue> entry : metricValueSets.entrySet()) {
op.addQuotaMetrics(MetricValueSet.newBuilder()
.setMetricName(entry.getKey())
.addMetricValues(entry.getValue()));
}
return op.build();
}
private MetricValue mergeDeltaMetricValue(MetricValue from, MetricValue to) {
if (to.getValueCase() != from.getValueCase()) {
log.atWarning().log("Could not merge different types of metric: %s, %s", from, to);
return to;
}
MetricValue.Builder builder = to.toBuilder();
if (from.hasStartTime()) {
if (!to.hasStartTime() || | Timestamps.COMPARATOR.compare(from.getStartTime(), to.getStartTime()) == -1) { |
cloudendpoints/endpoints-management-java | endpoints-control/src/main/java/com/google/api/control/aggregator/OperationAggregator.java | // Path: endpoints-control/src/main/java/com/google/api/control/model/Timestamps.java
// public final class Timestamps {
// private static final int MILLIS_PER_SECOND = 1000;
// private static final int NANOS_PER_MILLI = 1000000;
//
// private Timestamps() {}
//
// /**
// * A {@code Comparator} of {@link Timestamp}
// */
// public static Comparator<Timestamp> COMPARATOR = new Comparator<Timestamp>() {
// @Override
// public int compare(Timestamp o1, Timestamp o2) {
// int secondsOrder = Long.compare(o1.getSeconds(), o2.getSeconds());
// if (secondsOrder != 0) {
// return secondsOrder;
// } else {
// return Long.compare(o1.getNanos(), o2.getNanos());
// }
// }
// };
//
// /**
// * Obtain the current time from a {@link Clock}
// *
// * @param clock gives the current time
// * @return a {@code Timestamp} corresponding to the ticker's current value
// */
// public static Timestamp now(Clock clock) {
// return fromEpoch(clock.currentTimeMillis());
// }
//
// /**
// * Obtain the current time from the unix epoch
// *
// * @param epochMillis gives the current time in milliseconds since since the epoch
// * @return a {@code Timestamp} corresponding to the ticker's current value
// */
// public static Timestamp fromEpoch(long epochMillis) {
// return Timestamp
// .newBuilder()
// .setNanos((int) ((epochMillis % MILLIS_PER_SECOND) * NANOS_PER_MILLI))
// .setSeconds(epochMillis / MILLIS_PER_SECOND)
// .build();
// }
// }
| import com.google.api.MetricDescriptor.MetricKind;
import com.google.api.control.model.Timestamps;
import com.google.api.servicecontrol.v1.MetricValue;
import com.google.api.servicecontrol.v1.MetricValueSet;
import com.google.api.servicecontrol.v1.Operation;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set; | MetricValueSet.newBuilder().setMetricName(name).addAllMetricValues(values));
}
return op.build();
}
private void mergeMetricValues(Operation other) {
List<MetricValueSet> mvSets = other.getMetricValueSetsList();
for (MetricValueSet mvSet : mvSets) {
Map<String, MetricValue> bySignature = this.metricValues.get(mvSet.getMetricName());
if (bySignature == null) {
bySignature = Maps.newHashMap();
this.metricValues.put(mvSet.getMetricName(), bySignature);
}
for (MetricValue mv : mvSet.getMetricValuesList()) {
String signature = MetricValues.sign(mv).toString();
MetricValue prior = bySignature.get(signature);
if (prior == null) {
bySignature.put(signature, mv);
} else {
MetricKind kind = this.kinds.get(mvSet.getMetricName());
if (kind == null) {
kind = DEFAULT_KIND;
}
bySignature.put(signature, MetricValues.merge(kind, prior, mv));
}
}
}
}
private void mergeTimestamps(Operation other) { | // Path: endpoints-control/src/main/java/com/google/api/control/model/Timestamps.java
// public final class Timestamps {
// private static final int MILLIS_PER_SECOND = 1000;
// private static final int NANOS_PER_MILLI = 1000000;
//
// private Timestamps() {}
//
// /**
// * A {@code Comparator} of {@link Timestamp}
// */
// public static Comparator<Timestamp> COMPARATOR = new Comparator<Timestamp>() {
// @Override
// public int compare(Timestamp o1, Timestamp o2) {
// int secondsOrder = Long.compare(o1.getSeconds(), o2.getSeconds());
// if (secondsOrder != 0) {
// return secondsOrder;
// } else {
// return Long.compare(o1.getNanos(), o2.getNanos());
// }
// }
// };
//
// /**
// * Obtain the current time from a {@link Clock}
// *
// * @param clock gives the current time
// * @return a {@code Timestamp} corresponding to the ticker's current value
// */
// public static Timestamp now(Clock clock) {
// return fromEpoch(clock.currentTimeMillis());
// }
//
// /**
// * Obtain the current time from the unix epoch
// *
// * @param epochMillis gives the current time in milliseconds since since the epoch
// * @return a {@code Timestamp} corresponding to the ticker's current value
// */
// public static Timestamp fromEpoch(long epochMillis) {
// return Timestamp
// .newBuilder()
// .setNanos((int) ((epochMillis % MILLIS_PER_SECOND) * NANOS_PER_MILLI))
// .setSeconds(epochMillis / MILLIS_PER_SECOND)
// .build();
// }
// }
// Path: endpoints-control/src/main/java/com/google/api/control/aggregator/OperationAggregator.java
import com.google.api.MetricDescriptor.MetricKind;
import com.google.api.control.model.Timestamps;
import com.google.api.servicecontrol.v1.MetricValue;
import com.google.api.servicecontrol.v1.MetricValueSet;
import com.google.api.servicecontrol.v1.Operation;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
MetricValueSet.newBuilder().setMetricName(name).addAllMetricValues(values));
}
return op.build();
}
private void mergeMetricValues(Operation other) {
List<MetricValueSet> mvSets = other.getMetricValueSetsList();
for (MetricValueSet mvSet : mvSets) {
Map<String, MetricValue> bySignature = this.metricValues.get(mvSet.getMetricName());
if (bySignature == null) {
bySignature = Maps.newHashMap();
this.metricValues.put(mvSet.getMetricName(), bySignature);
}
for (MetricValue mv : mvSet.getMetricValuesList()) {
String signature = MetricValues.sign(mv).toString();
MetricValue prior = bySignature.get(signature);
if (prior == null) {
bySignature.put(signature, mv);
} else {
MetricKind kind = this.kinds.get(mvSet.getMetricName());
if (kind == null) {
kind = DEFAULT_KIND;
}
bySignature.put(signature, MetricValues.merge(kind, prior, mv));
}
}
}
}
private void mergeTimestamps(Operation other) { | if (Timestamps.COMPARATOR.compare(other.getStartTime(), op.getStartTime()) == -1) { |
cloudendpoints/endpoints-management-java | endpoints-auth/src/main/java/com/google/api/auth/Authenticator.java | // Path: endpoints-service-config/src/main/java/com/google/api/config/ServiceConfigFetcher.java
// public class ServiceConfigFetcher {
//
// private final Supplier<Service> serviceSupplier;
//
// @VisibleForTesting
// ServiceConfigFetcher(Supplier<Service> supplier) {
// this.serviceSupplier = Suppliers.memoizeWithExpiration(supplier, 10, TimeUnit.MINUTES);
// }
//
// public Service fetch() {
// return this.serviceSupplier.get();
// }
//
// public static ServiceConfigFetcher create() {
// return new ServiceConfigFetcher(ServiceConfigSupplier.create());
// }
// }
//
// Path: endpoints-control/src/main/java/com/google/api/control/model/MethodRegistry.java
// public static final class AuthInfo {
// private final Map<String, Set<String>> providerIdsToAudiences;
//
// public AuthInfo(Map<String, Set<String>> providerIdsToAudiences) {
// Preconditions.checkNotNull(providerIdsToAudiences);
// this.providerIdsToAudiences = providerIdsToAudiences;
// }
//
// public boolean isProviderIdAllowed(String providerid) {
// Preconditions.checkNotNull(providerid);
// return this.providerIdsToAudiences.containsKey(providerid);
// }
//
// public Set<String> getAudiencesForProvider(String providerId) {
// Preconditions.checkNotNull(providerId);
//
// if (this.providerIdsToAudiences.containsKey(providerId)) {
// return this.providerIdsToAudiences.get(providerId);
// }
// return ImmutableSet.<String>of();
// }
// }
| import com.google.api.AuthProvider;
import com.google.api.Authentication;
import com.google.api.Service;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.util.Clock;
import com.google.api.client.util.Maps;
import com.google.api.config.ServiceConfigFetcher;
import com.google.api.control.model.MethodRegistry.AuthInfo;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import com.google.common.flogger.FluentLogger;
import com.google.common.net.HttpHeaders;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.MalformedClaimException;
import org.jose4j.jwt.NumericDate;
import org.jose4j.jwt.ReservedClaimNames; | /*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.api.auth;
/**
* An authenticator that extracts the auth token from the HTTP request and
* constructs a {@link UserInfo} object based on the claims contained in the
* auth token.
*
* @author [email protected]
*
*/
public class Authenticator {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final String ACCESS_TOKEN_PARAM_NAME = "access_token";
private static final String BEARER_TOKEN_PREFIX = "Bearer ";
private static final String EMAIL_CLAIM_NAME = "email";
private final AuthTokenDecoder authTokenDecoder;
private final Clock clock;
private final Map<String, String> issuersToProviderIds;
/**
* Constructor.
*
* @param authTokenDecoder decodes auth tokens into {@link UserInfo} objects.
* @param clock provides the time.
* @param issuersToProviderIds maps from issuers to provider IDs.
*/
@VisibleForTesting
Authenticator(
AuthTokenDecoder authTokenDecoder,
Clock clock,
Map<String, String> issuersToProviderIds) {
this.authTokenDecoder = authTokenDecoder;
this.clock = clock;
this.issuersToProviderIds = issuersToProviderIds;
}
/**
* Authenticate the current HTTP request.
*
* @param httpServletRequest is the incoming HTTP request object.
* @param authInfo contains authentication configurations of the API method being called.
* @param serviceName is the name of this service.
* @return a constructed {@link UserInfo} object representing the identity of the caller.
*/
public UserInfo authenticate(
HttpServletRequest httpServletRequest, | // Path: endpoints-service-config/src/main/java/com/google/api/config/ServiceConfigFetcher.java
// public class ServiceConfigFetcher {
//
// private final Supplier<Service> serviceSupplier;
//
// @VisibleForTesting
// ServiceConfigFetcher(Supplier<Service> supplier) {
// this.serviceSupplier = Suppliers.memoizeWithExpiration(supplier, 10, TimeUnit.MINUTES);
// }
//
// public Service fetch() {
// return this.serviceSupplier.get();
// }
//
// public static ServiceConfigFetcher create() {
// return new ServiceConfigFetcher(ServiceConfigSupplier.create());
// }
// }
//
// Path: endpoints-control/src/main/java/com/google/api/control/model/MethodRegistry.java
// public static final class AuthInfo {
// private final Map<String, Set<String>> providerIdsToAudiences;
//
// public AuthInfo(Map<String, Set<String>> providerIdsToAudiences) {
// Preconditions.checkNotNull(providerIdsToAudiences);
// this.providerIdsToAudiences = providerIdsToAudiences;
// }
//
// public boolean isProviderIdAllowed(String providerid) {
// Preconditions.checkNotNull(providerid);
// return this.providerIdsToAudiences.containsKey(providerid);
// }
//
// public Set<String> getAudiencesForProvider(String providerId) {
// Preconditions.checkNotNull(providerId);
//
// if (this.providerIdsToAudiences.containsKey(providerId)) {
// return this.providerIdsToAudiences.get(providerId);
// }
// return ImmutableSet.<String>of();
// }
// }
// Path: endpoints-auth/src/main/java/com/google/api/auth/Authenticator.java
import com.google.api.AuthProvider;
import com.google.api.Authentication;
import com.google.api.Service;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.util.Clock;
import com.google.api.client.util.Maps;
import com.google.api.config.ServiceConfigFetcher;
import com.google.api.control.model.MethodRegistry.AuthInfo;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import com.google.common.flogger.FluentLogger;
import com.google.common.net.HttpHeaders;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.MalformedClaimException;
import org.jose4j.jwt.NumericDate;
import org.jose4j.jwt.ReservedClaimNames;
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.api.auth;
/**
* An authenticator that extracts the auth token from the HTTP request and
* constructs a {@link UserInfo} object based on the claims contained in the
* auth token.
*
* @author [email protected]
*
*/
public class Authenticator {
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final String ACCESS_TOKEN_PARAM_NAME = "access_token";
private static final String BEARER_TOKEN_PREFIX = "Bearer ";
private static final String EMAIL_CLAIM_NAME = "email";
private final AuthTokenDecoder authTokenDecoder;
private final Clock clock;
private final Map<String, String> issuersToProviderIds;
/**
* Constructor.
*
* @param authTokenDecoder decodes auth tokens into {@link UserInfo} objects.
* @param clock provides the time.
* @param issuersToProviderIds maps from issuers to provider IDs.
*/
@VisibleForTesting
Authenticator(
AuthTokenDecoder authTokenDecoder,
Clock clock,
Map<String, String> issuersToProviderIds) {
this.authTokenDecoder = authTokenDecoder;
this.clock = clock;
this.issuersToProviderIds = issuersToProviderIds;
}
/**
* Authenticate the current HTTP request.
*
* @param httpServletRequest is the incoming HTTP request object.
* @param authInfo contains authentication configurations of the API method being called.
* @param serviceName is the name of this service.
* @return a constructed {@link UserInfo} object representing the identity of the caller.
*/
public UserInfo authenticate(
HttpServletRequest httpServletRequest, | AuthInfo authInfo, |
cloudendpoints/endpoints-management-java | endpoints-auth/src/main/java/com/google/api/auth/Authenticator.java | // Path: endpoints-service-config/src/main/java/com/google/api/config/ServiceConfigFetcher.java
// public class ServiceConfigFetcher {
//
// private final Supplier<Service> serviceSupplier;
//
// @VisibleForTesting
// ServiceConfigFetcher(Supplier<Service> supplier) {
// this.serviceSupplier = Suppliers.memoizeWithExpiration(supplier, 10, TimeUnit.MINUTES);
// }
//
// public Service fetch() {
// return this.serviceSupplier.get();
// }
//
// public static ServiceConfigFetcher create() {
// return new ServiceConfigFetcher(ServiceConfigSupplier.create());
// }
// }
//
// Path: endpoints-control/src/main/java/com/google/api/control/model/MethodRegistry.java
// public static final class AuthInfo {
// private final Map<String, Set<String>> providerIdsToAudiences;
//
// public AuthInfo(Map<String, Set<String>> providerIdsToAudiences) {
// Preconditions.checkNotNull(providerIdsToAudiences);
// this.providerIdsToAudiences = providerIdsToAudiences;
// }
//
// public boolean isProviderIdAllowed(String providerid) {
// Preconditions.checkNotNull(providerid);
// return this.providerIdsToAudiences.containsKey(providerid);
// }
//
// public Set<String> getAudiencesForProvider(String providerId) {
// Preconditions.checkNotNull(providerId);
//
// if (this.providerIdsToAudiences.containsKey(providerId)) {
// return this.providerIdsToAudiences.get(providerId);
// }
// return ImmutableSet.<String>of();
// }
// }
| import com.google.api.AuthProvider;
import com.google.api.Authentication;
import com.google.api.Service;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.util.Clock;
import com.google.api.client.util.Maps;
import com.google.api.config.ServiceConfigFetcher;
import com.google.api.control.model.MethodRegistry.AuthInfo;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import com.google.common.flogger.FluentLogger;
import com.google.common.net.HttpHeaders;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.MalformedClaimException;
import org.jose4j.jwt.NumericDate;
import org.jose4j.jwt.ReservedClaimNames; | }
// Check whether the JWT claims should be accepted.
private void checkJwtClaims(JwtClaims jwtClaims) {
Optional<NumericDate> expiration = getDateClaim(ReservedClaimNames.EXPIRATION_TIME, jwtClaims);
if (!expiration.isPresent()) {
throw new UnauthenticatedException("Missing expiration field");
}
Optional<NumericDate> notBefore = getDateClaim(ReservedClaimNames.NOT_BEFORE, jwtClaims);
NumericDate currentTime = NumericDate.fromMilliseconds(clock.currentTimeMillis());
if (expiration.get().isBefore(currentTime)) {
throw new UnauthenticatedException("The auth token has already expired");
}
if (notBefore.isPresent() && notBefore.get().isAfter(currentTime)) {
String message = "Current time is earlier than the \"nbf\" time";
throw new UnauthenticatedException(message);
}
}
/**
* Create an instance of {@link Authenticator} using the service configuration fetched from Google
* Service Management APIs.
*
* @return an {@code Authenticator}
* @throws java.lang.IllegalArgumentException if the authentication message is not defined in the
* fetched service config.
*/
public static Authenticator create() { | // Path: endpoints-service-config/src/main/java/com/google/api/config/ServiceConfigFetcher.java
// public class ServiceConfigFetcher {
//
// private final Supplier<Service> serviceSupplier;
//
// @VisibleForTesting
// ServiceConfigFetcher(Supplier<Service> supplier) {
// this.serviceSupplier = Suppliers.memoizeWithExpiration(supplier, 10, TimeUnit.MINUTES);
// }
//
// public Service fetch() {
// return this.serviceSupplier.get();
// }
//
// public static ServiceConfigFetcher create() {
// return new ServiceConfigFetcher(ServiceConfigSupplier.create());
// }
// }
//
// Path: endpoints-control/src/main/java/com/google/api/control/model/MethodRegistry.java
// public static final class AuthInfo {
// private final Map<String, Set<String>> providerIdsToAudiences;
//
// public AuthInfo(Map<String, Set<String>> providerIdsToAudiences) {
// Preconditions.checkNotNull(providerIdsToAudiences);
// this.providerIdsToAudiences = providerIdsToAudiences;
// }
//
// public boolean isProviderIdAllowed(String providerid) {
// Preconditions.checkNotNull(providerid);
// return this.providerIdsToAudiences.containsKey(providerid);
// }
//
// public Set<String> getAudiencesForProvider(String providerId) {
// Preconditions.checkNotNull(providerId);
//
// if (this.providerIdsToAudiences.containsKey(providerId)) {
// return this.providerIdsToAudiences.get(providerId);
// }
// return ImmutableSet.<String>of();
// }
// }
// Path: endpoints-auth/src/main/java/com/google/api/auth/Authenticator.java
import com.google.api.AuthProvider;
import com.google.api.Authentication;
import com.google.api.Service;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.util.Clock;
import com.google.api.client.util.Maps;
import com.google.api.config.ServiceConfigFetcher;
import com.google.api.control.model.MethodRegistry.AuthInfo;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import com.google.common.flogger.FluentLogger;
import com.google.common.net.HttpHeaders;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.MalformedClaimException;
import org.jose4j.jwt.NumericDate;
import org.jose4j.jwt.ReservedClaimNames;
}
// Check whether the JWT claims should be accepted.
private void checkJwtClaims(JwtClaims jwtClaims) {
Optional<NumericDate> expiration = getDateClaim(ReservedClaimNames.EXPIRATION_TIME, jwtClaims);
if (!expiration.isPresent()) {
throw new UnauthenticatedException("Missing expiration field");
}
Optional<NumericDate> notBefore = getDateClaim(ReservedClaimNames.NOT_BEFORE, jwtClaims);
NumericDate currentTime = NumericDate.fromMilliseconds(clock.currentTimeMillis());
if (expiration.get().isBefore(currentTime)) {
throw new UnauthenticatedException("The auth token has already expired");
}
if (notBefore.isPresent() && notBefore.get().isAfter(currentTime)) {
String message = "Current time is earlier than the \"nbf\" time";
throw new UnauthenticatedException(message);
}
}
/**
* Create an instance of {@link Authenticator} using the service configuration fetched from Google
* Service Management APIs.
*
* @return an {@code Authenticator}
* @throws java.lang.IllegalArgumentException if the authentication message is not defined in the
* fetched service config.
*/
public static Authenticator create() { | ServiceConfigFetcher fetcher = ServiceConfigFetcher.create(); |
cloudendpoints/endpoints-management-java | endpoints-auth/src/test/java/com/google/api/auth/AuthenticatorTest.java | // Path: endpoints-control/src/main/java/com/google/api/control/model/MethodRegistry.java
// public static final class AuthInfo {
// private final Map<String, Set<String>> providerIdsToAudiences;
//
// public AuthInfo(Map<String, Set<String>> providerIdsToAudiences) {
// Preconditions.checkNotNull(providerIdsToAudiences);
// this.providerIdsToAudiences = providerIdsToAudiences;
// }
//
// public boolean isProviderIdAllowed(String providerid) {
// Preconditions.checkNotNull(providerid);
// return this.providerIdsToAudiences.containsKey(providerid);
// }
//
// public Set<String> getAudiencesForProvider(String providerId) {
// Preconditions.checkNotNull(providerId);
//
// if (this.providerIdsToAudiences.containsKey(providerId)) {
// return this.providerIdsToAudiences.get(providerId);
// }
// return ImmutableSet.<String>of();
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.api.AuthProvider;
import com.google.api.Authentication;
import com.google.api.client.util.Clock;
import com.google.api.control.model.MethodRegistry.AuthInfo;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.net.HttpHeaders;
import org.jose4j.jwt.JwtClaims;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest; | /*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.api.auth;
/**
* Tests for {@link Authenticator}.
*
* @author [email protected]
*
*/
public class AuthenticatorTest {
private static final List<String> AUDIENCES = ImmutableList.of("aud1", "aud2");
private static final String AUTH_TOKEN = "auth-token";
private static final String EMAIL = "[email protected]";
private static final int EXPIRATION_IN_FUTURE = 5;
private static final String ID = "id";
private static final String ISSUER = "issuer";
private static final String PROVIDER_ID = "provider-id";
private static final int NOT_BEFORE_IN_PAST = 0;
private static final String SERVICE_NAME = "service-name";
private final Map<String, String> issuersToProviderIds =
ImmutableMap.<String, String>of(ISSUER, PROVIDER_ID);
private final AuthTokenDecoder authTokenDecoder = mock(AuthTokenDecoder.class);
private final Authenticator authenticator =
new Authenticator(authTokenDecoder, Clock.SYSTEM, issuersToProviderIds);
private final HttpServletRequest request = mock(HttpServletRequest.class);
private final JwtClaims jwtClaims =
createJwtClaims(AUDIENCES, EMAIL, EXPIRATION_IN_FUTURE, ID, NOT_BEFORE_IN_PAST, ISSUER);
private final UserInfo userInfo = new UserInfo(AUDIENCES, EMAIL, ID, ISSUER);
@Before
public void setUp() {
when(authTokenDecoder.decode(AUTH_TOKEN)).thenReturn(jwtClaims);
when(request.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn("Bearer " + AUTH_TOKEN);
}
@Test
public void testAuthenticate() { | // Path: endpoints-control/src/main/java/com/google/api/control/model/MethodRegistry.java
// public static final class AuthInfo {
// private final Map<String, Set<String>> providerIdsToAudiences;
//
// public AuthInfo(Map<String, Set<String>> providerIdsToAudiences) {
// Preconditions.checkNotNull(providerIdsToAudiences);
// this.providerIdsToAudiences = providerIdsToAudiences;
// }
//
// public boolean isProviderIdAllowed(String providerid) {
// Preconditions.checkNotNull(providerid);
// return this.providerIdsToAudiences.containsKey(providerid);
// }
//
// public Set<String> getAudiencesForProvider(String providerId) {
// Preconditions.checkNotNull(providerId);
//
// if (this.providerIdsToAudiences.containsKey(providerId)) {
// return this.providerIdsToAudiences.get(providerId);
// }
// return ImmutableSet.<String>of();
// }
// }
// Path: endpoints-auth/src/test/java/com/google/api/auth/AuthenticatorTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.api.AuthProvider;
import com.google.api.Authentication;
import com.google.api.client.util.Clock;
import com.google.api.control.model.MethodRegistry.AuthInfo;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.net.HttpHeaders;
import org.jose4j.jwt.JwtClaims;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.google.api.auth;
/**
* Tests for {@link Authenticator}.
*
* @author [email protected]
*
*/
public class AuthenticatorTest {
private static final List<String> AUDIENCES = ImmutableList.of("aud1", "aud2");
private static final String AUTH_TOKEN = "auth-token";
private static final String EMAIL = "[email protected]";
private static final int EXPIRATION_IN_FUTURE = 5;
private static final String ID = "id";
private static final String ISSUER = "issuer";
private static final String PROVIDER_ID = "provider-id";
private static final int NOT_BEFORE_IN_PAST = 0;
private static final String SERVICE_NAME = "service-name";
private final Map<String, String> issuersToProviderIds =
ImmutableMap.<String, String>of(ISSUER, PROVIDER_ID);
private final AuthTokenDecoder authTokenDecoder = mock(AuthTokenDecoder.class);
private final Authenticator authenticator =
new Authenticator(authTokenDecoder, Clock.SYSTEM, issuersToProviderIds);
private final HttpServletRequest request = mock(HttpServletRequest.class);
private final JwtClaims jwtClaims =
createJwtClaims(AUDIENCES, EMAIL, EXPIRATION_IN_FUTURE, ID, NOT_BEFORE_IN_PAST, ISSUER);
private final UserInfo userInfo = new UserInfo(AUDIENCES, EMAIL, ID, ISSUER);
@Before
public void setUp() {
when(authTokenDecoder.decode(AUTH_TOKEN)).thenReturn(jwtClaims);
when(request.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn("Bearer " + AUTH_TOKEN);
}
@Test
public void testAuthenticate() { | AuthInfo authInfo = |
cloudendpoints/endpoints-management-java | endpoints-control/src/test/java/com/google/api/control/model/MethodRegistryTest.java | // Path: endpoints-control/src/main/java/com/google/api/control/model/MethodRegistry.java
// public static class Info {
// private static final String API_KEY_NAME = "api_key";
//
// private final Optional<AuthInfo> authInfo;
// private final QuotaInfo quotaInfo;
//
// private boolean allowUnregisteredCalls;
// private String selector;
// private String backendAddress;
// private String bodyFieldPath;
// private Map<String, List<String>> urlQueryParams;
// private Map<String, List<String>> headerParams;
// private PathTemplate template;
//
// public Info(String selector, @CheckForNull AuthInfo authInfo,
// @CheckForNull QuotaInfo quotaInfo) {
// this.selector = selector;
// this.authInfo = Optional.<AuthInfo>fromNullable(authInfo);
// this.quotaInfo = quotaInfo != null ? quotaInfo : QuotaInfo.DEFAULT;
//
// this.urlQueryParams = Maps.newHashMap();
// this.headerParams = Maps.newHashMap();
// }
//
// public PathTemplate getTemplate() {
// return template;
// }
//
// public void setTemplate(PathTemplate template) {
// this.template = template;
// }
//
// public void addUrlQueryParam(String name, String param) {
// List<String> l = urlQueryParams.get(name);
// if (l == null) {
// l = Lists.newArrayList();
// urlQueryParams.put(name, l);
// }
// l.add(param);
// }
//
// public List<String> urlQueryParam(String name) {
// List<String> l = urlQueryParams.get(name);
// if (l == null) {
// return Collections.emptyList();
// }
// return ImmutableList.copyOf(l);
// }
//
// public List<String> apiKeyUrlQueryParam() {
// return urlQueryParam(API_KEY_NAME);
// }
//
// public void addHeaderParam(String name, String param) {
// List<String> l = headerParams.get(name);
// if (l == null) {
// l = Lists.newArrayList();
// headerParams.put(name, l);
// }
// l.add(param);
// }
//
// public List<String> headerParam(String name) {
// List<String> l = headerParams.get(name);
// if (l == null) {
// return Collections.emptyList();
// }
// return ImmutableList.copyOf(l);
// }
//
// public List<String> apiKeyHeaderParam() {
// return headerParam(API_KEY_NAME);
// }
//
// public Optional<AuthInfo> getAuthInfo() {
// return this.authInfo;
// }
//
// public QuotaInfo getQuotaInfo() {
// return quotaInfo;
// }
//
// public boolean shouldAllowUnregisteredCalls() {
// return allowUnregisteredCalls;
// }
//
// public void setAllowUnregisteredCalls(boolean allowRegisteredCalls) {
// this.allowUnregisteredCalls = allowRegisteredCalls;
// }
//
// public String getSelector() {
// return selector;
// }
//
// public void setSelector(String selector) {
// this.selector = selector;
// }
//
// public String getBackendAddress() {
// return backendAddress;
// }
//
// public void setBackendAddress(String backendAddress) {
// this.backendAddress = backendAddress;
// }
//
// public String getBodyFieldPath() {
// return bodyFieldPath;
// }
//
// public void setBodyFieldPath(String bodyFieldPath) {
// this.bodyFieldPath = bodyFieldPath;
// }
// }
| import static com.google.common.truth.Truth.assertThat;
import com.google.api.Http;
import com.google.api.HttpRule;
import com.google.api.Service;
import com.google.api.control.model.MethodRegistry.Info;
import org.junit.Test; | package com.google.api.control.model;
/**
* Tests for {@link MethodRegistry}.
*/
public class MethodRegistryTest {
private static final String SELECTOR = "a.selector";
private static final String SLASH_SELECTOR = "slash.selector";
private static final Service SERVICE = Service.newBuilder()
.setName("the-service")
.setHttp(Http.newBuilder()
.addRules(HttpRule.newBuilder()
.setSelector(SELECTOR)
.setGet("/v1/foo/{bar}/baz"))
.addRules(HttpRule.newBuilder()
.setSelector(SLASH_SELECTOR)
.setGet("/v1/baz/{bar}/foo/")))
.build();
@Test
public void lookup_matchesWithOrWithoutTrailingSlashes() {
MethodRegistry r = new MethodRegistry(SERVICE);
assertSuccess(r.lookup("GET", "/v1/foo/2/baz"), SELECTOR);
assertSuccess(r.lookup("GET", "/v1/foo/2/baz/"), SELECTOR);
assertFailure(r.lookup("POST", "/v1/foo/2/baz"));
assertFailure(r.lookup("POST", "/v1/foo/2/baz/"));
assertSuccess(r.lookup("GET", "/v1/baz/2/foo"), SLASH_SELECTOR);
assertSuccess(r.lookup("GET", "/v1/baz/2/foo/"), SLASH_SELECTOR);
assertFailure(r.lookup("POST", "/v1/baz/2/foo"));
assertFailure(r.lookup("POST", "/v1/baz/2/foo/"));
}
| // Path: endpoints-control/src/main/java/com/google/api/control/model/MethodRegistry.java
// public static class Info {
// private static final String API_KEY_NAME = "api_key";
//
// private final Optional<AuthInfo> authInfo;
// private final QuotaInfo quotaInfo;
//
// private boolean allowUnregisteredCalls;
// private String selector;
// private String backendAddress;
// private String bodyFieldPath;
// private Map<String, List<String>> urlQueryParams;
// private Map<String, List<String>> headerParams;
// private PathTemplate template;
//
// public Info(String selector, @CheckForNull AuthInfo authInfo,
// @CheckForNull QuotaInfo quotaInfo) {
// this.selector = selector;
// this.authInfo = Optional.<AuthInfo>fromNullable(authInfo);
// this.quotaInfo = quotaInfo != null ? quotaInfo : QuotaInfo.DEFAULT;
//
// this.urlQueryParams = Maps.newHashMap();
// this.headerParams = Maps.newHashMap();
// }
//
// public PathTemplate getTemplate() {
// return template;
// }
//
// public void setTemplate(PathTemplate template) {
// this.template = template;
// }
//
// public void addUrlQueryParam(String name, String param) {
// List<String> l = urlQueryParams.get(name);
// if (l == null) {
// l = Lists.newArrayList();
// urlQueryParams.put(name, l);
// }
// l.add(param);
// }
//
// public List<String> urlQueryParam(String name) {
// List<String> l = urlQueryParams.get(name);
// if (l == null) {
// return Collections.emptyList();
// }
// return ImmutableList.copyOf(l);
// }
//
// public List<String> apiKeyUrlQueryParam() {
// return urlQueryParam(API_KEY_NAME);
// }
//
// public void addHeaderParam(String name, String param) {
// List<String> l = headerParams.get(name);
// if (l == null) {
// l = Lists.newArrayList();
// headerParams.put(name, l);
// }
// l.add(param);
// }
//
// public List<String> headerParam(String name) {
// List<String> l = headerParams.get(name);
// if (l == null) {
// return Collections.emptyList();
// }
// return ImmutableList.copyOf(l);
// }
//
// public List<String> apiKeyHeaderParam() {
// return headerParam(API_KEY_NAME);
// }
//
// public Optional<AuthInfo> getAuthInfo() {
// return this.authInfo;
// }
//
// public QuotaInfo getQuotaInfo() {
// return quotaInfo;
// }
//
// public boolean shouldAllowUnregisteredCalls() {
// return allowUnregisteredCalls;
// }
//
// public void setAllowUnregisteredCalls(boolean allowRegisteredCalls) {
// this.allowUnregisteredCalls = allowRegisteredCalls;
// }
//
// public String getSelector() {
// return selector;
// }
//
// public void setSelector(String selector) {
// this.selector = selector;
// }
//
// public String getBackendAddress() {
// return backendAddress;
// }
//
// public void setBackendAddress(String backendAddress) {
// this.backendAddress = backendAddress;
// }
//
// public String getBodyFieldPath() {
// return bodyFieldPath;
// }
//
// public void setBodyFieldPath(String bodyFieldPath) {
// this.bodyFieldPath = bodyFieldPath;
// }
// }
// Path: endpoints-control/src/test/java/com/google/api/control/model/MethodRegistryTest.java
import static com.google.common.truth.Truth.assertThat;
import com.google.api.Http;
import com.google.api.HttpRule;
import com.google.api.Service;
import com.google.api.control.model.MethodRegistry.Info;
import org.junit.Test;
package com.google.api.control.model;
/**
* Tests for {@link MethodRegistry}.
*/
public class MethodRegistryTest {
private static final String SELECTOR = "a.selector";
private static final String SLASH_SELECTOR = "slash.selector";
private static final Service SERVICE = Service.newBuilder()
.setName("the-service")
.setHttp(Http.newBuilder()
.addRules(HttpRule.newBuilder()
.setSelector(SELECTOR)
.setGet("/v1/foo/{bar}/baz"))
.addRules(HttpRule.newBuilder()
.setSelector(SLASH_SELECTOR)
.setGet("/v1/baz/{bar}/foo/")))
.build();
@Test
public void lookup_matchesWithOrWithoutTrailingSlashes() {
MethodRegistry r = new MethodRegistry(SERVICE);
assertSuccess(r.lookup("GET", "/v1/foo/2/baz"), SELECTOR);
assertSuccess(r.lookup("GET", "/v1/foo/2/baz/"), SELECTOR);
assertFailure(r.lookup("POST", "/v1/foo/2/baz"));
assertFailure(r.lookup("POST", "/v1/foo/2/baz/"));
assertSuccess(r.lookup("GET", "/v1/baz/2/foo"), SLASH_SELECTOR);
assertSuccess(r.lookup("GET", "/v1/baz/2/foo/"), SLASH_SELECTOR);
assertFailure(r.lookup("POST", "/v1/baz/2/foo"));
assertFailure(r.lookup("POST", "/v1/baz/2/foo/"));
}
| private static void assertFailure(Info info) { |
trinidad/trinidad | src/trinidad-rb/java/rb/trinidad/logging/DefaultFormatter.java | // Path: src/trinidad-rb/java/rb/trinidad/logging/LoggingHelpers.java
// public abstract class LoggingHelpers {
//
// public static boolean isContextLogger(final String logger) {
// if ( logger == null ) return false;
// if ( ! logger.startsWith("org.apache.catalina.core.ContainerBase.") ) return false;
// // e.g. org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/foo]
// // or org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[default]
// final int end = logger.length() - 1;
// if ( logger.charAt(end) != ']' ) return false;
// final int i = logger.lastIndexOf('[') + 1; if ( i <= 0 ) return false;
// return true;
// }
//
// public static String getContextName(final String logger) {
// if ( logger == null ) return null;
// if ( ! logger.startsWith("org.apache.catalina.core.ContainerBase.") ) return null;
// // e.g. org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/foo]
// // or org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[default]
// final int end = logger.length() - 1;
// if ( logger.charAt(end) != ']' ) return null;
// final int i = logger.lastIndexOf('[') + 1; if ( i <= 0 ) return null;
// return logger.substring(i, end);
// }
//
// public static CharSequence formatThrown(final Throwable thrown) {
// if ( thrown == null ) return null;
// final StringBuilder buffer = new StringBuilder();
// formatThrown(thrown, buffer);
// return buffer;
// }
//
// public static void formatThrown(final Throwable thrown, final StringBuilder buffer) {
// if ( thrown == null ) return;
// StringWriter stringWriter = new StringWriter(512);
// PrintWriter printWriter = new PrintWriter(stringWriter);
// thrown.printStackTrace(printWriter);
// printWriter.println();
// printWriter.close();
// buffer.append( stringWriter.getBuffer() );
// }
//
// static final String LINE_SEPARATOR = System.getProperty("line.separator");
//
// static boolean endsWithLineSeparator(final CharSequence msg) {
// final int len = msg.length();
// final String ls = LINE_SEPARATOR;
// if ( ls != null && len > ls.length() ) {
// final int end = len - ls.length();
// return ls.equals( msg.subSequence(end, len) );
// }
// return false;
// }
//
// }
| import java.util.logging.Formatter;
import java.util.logging.LogRecord;
import static rb.trinidad.logging.LoggingHelpers.*;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone; | }
public DefaultFormatter(DateFormat dateFormat) {
if ( dateFormat == null ) {
throw new IllegalArgumentException("no format given");
}
this.dateFormat = dateFormat;
}
public DateFormat getDateFormat() {
return dateFormat;
}
@Override
public String format(final LogRecord record) {
String message = record.getMessage();
StringBuffer msg = new StringBuffer(32 + 2 + 7 + 1 + message.length());
Date millis = new Date(record.getMillis());
synchronized(dateFormat) {
dateFormat.format(millis, msg, dummyPosition);
}
msg.append(' ').append(record.getLevel().getName()).append(':'); // WARNING:
msg.append(' ').append(formatMessage(record)); // message
if ( ! endsWithLineSeparator(msg) ) msg.append(LINE_SEPARATOR);
final CharSequence thrown = formatThrown(record);
if ( thrown != null ) msg.append(thrown);
return msg.toString();
}
protected CharSequence formatThrown(final LogRecord record) { | // Path: src/trinidad-rb/java/rb/trinidad/logging/LoggingHelpers.java
// public abstract class LoggingHelpers {
//
// public static boolean isContextLogger(final String logger) {
// if ( logger == null ) return false;
// if ( ! logger.startsWith("org.apache.catalina.core.ContainerBase.") ) return false;
// // e.g. org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/foo]
// // or org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[default]
// final int end = logger.length() - 1;
// if ( logger.charAt(end) != ']' ) return false;
// final int i = logger.lastIndexOf('[') + 1; if ( i <= 0 ) return false;
// return true;
// }
//
// public static String getContextName(final String logger) {
// if ( logger == null ) return null;
// if ( ! logger.startsWith("org.apache.catalina.core.ContainerBase.") ) return null;
// // e.g. org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/foo]
// // or org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[default]
// final int end = logger.length() - 1;
// if ( logger.charAt(end) != ']' ) return null;
// final int i = logger.lastIndexOf('[') + 1; if ( i <= 0 ) return null;
// return logger.substring(i, end);
// }
//
// public static CharSequence formatThrown(final Throwable thrown) {
// if ( thrown == null ) return null;
// final StringBuilder buffer = new StringBuilder();
// formatThrown(thrown, buffer);
// return buffer;
// }
//
// public static void formatThrown(final Throwable thrown, final StringBuilder buffer) {
// if ( thrown == null ) return;
// StringWriter stringWriter = new StringWriter(512);
// PrintWriter printWriter = new PrintWriter(stringWriter);
// thrown.printStackTrace(printWriter);
// printWriter.println();
// printWriter.close();
// buffer.append( stringWriter.getBuffer() );
// }
//
// static final String LINE_SEPARATOR = System.getProperty("line.separator");
//
// static boolean endsWithLineSeparator(final CharSequence msg) {
// final int len = msg.length();
// final String ls = LINE_SEPARATOR;
// if ( ls != null && len > ls.length() ) {
// final int end = len - ls.length();
// return ls.equals( msg.subSequence(end, len) );
// }
// return false;
// }
//
// }
// Path: src/trinidad-rb/java/rb/trinidad/logging/DefaultFormatter.java
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
import static rb.trinidad.logging.LoggingHelpers.*;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
}
public DefaultFormatter(DateFormat dateFormat) {
if ( dateFormat == null ) {
throw new IllegalArgumentException("no format given");
}
this.dateFormat = dateFormat;
}
public DateFormat getDateFormat() {
return dateFormat;
}
@Override
public String format(final LogRecord record) {
String message = record.getMessage();
StringBuffer msg = new StringBuffer(32 + 2 + 7 + 1 + message.length());
Date millis = new Date(record.getMillis());
synchronized(dateFormat) {
dateFormat.format(millis, msg, dummyPosition);
}
msg.append(' ').append(record.getLevel().getName()).append(':'); // WARNING:
msg.append(' ').append(formatMessage(record)); // message
if ( ! endsWithLineSeparator(msg) ) msg.append(LINE_SEPARATOR);
final CharSequence thrown = formatThrown(record);
if ( thrown != null ) msg.append(thrown);
return msg.toString();
}
protected CharSequence formatThrown(final LogRecord record) { | return LoggingHelpers.formatThrown( record.getThrown() ); |
otto-de/jlineup | web/src/main/java/de/otto/jlineup/service/InvalidRunStateException.java | // Path: web/src/main/java/de/otto/jlineup/web/State.java
// public enum State {
// BEFORE_PENDING("'before' pending"),
// BEFORE_RUNNING("'before' running"),
// BEFORE_DONE("'before' done"),
// AFTER_PENDING("'after' pending"),
// AFTER_RUNNING("'after' running"),
// FINISHED_WITHOUT_DIFFERENCES("finished without differences"),
// FINISHED_WITH_DIFFERENCES("finished with differences"),
// ERROR("error"),
// DEAD("dead");
//
// private final String humanReadableName;
//
// State(String humanReadableName) {
// this.humanReadableName = humanReadableName;
// }
//
// public String getHumanReadableName() {
// return humanReadableName;
// }
//
// public boolean isDone() {
// return this == FINISHED_WITH_DIFFERENCES || this == FINISHED_WITHOUT_DIFFERENCES || this == ERROR || this == DEAD;
// }
//
// public boolean isNonPersistable() {
// return this == BEFORE_PENDING || this == BEFORE_RUNNING || this == AFTER_PENDING || this == AFTER_RUNNING;
// }
// }
| import de.otto.jlineup.web.State; | package de.otto.jlineup.service;
public class InvalidRunStateException extends Exception {
private final String id; | // Path: web/src/main/java/de/otto/jlineup/web/State.java
// public enum State {
// BEFORE_PENDING("'before' pending"),
// BEFORE_RUNNING("'before' running"),
// BEFORE_DONE("'before' done"),
// AFTER_PENDING("'after' pending"),
// AFTER_RUNNING("'after' running"),
// FINISHED_WITHOUT_DIFFERENCES("finished without differences"),
// FINISHED_WITH_DIFFERENCES("finished with differences"),
// ERROR("error"),
// DEAD("dead");
//
// private final String humanReadableName;
//
// State(String humanReadableName) {
// this.humanReadableName = humanReadableName;
// }
//
// public String getHumanReadableName() {
// return humanReadableName;
// }
//
// public boolean isDone() {
// return this == FINISHED_WITH_DIFFERENCES || this == FINISHED_WITHOUT_DIFFERENCES || this == ERROR || this == DEAD;
// }
//
// public boolean isNonPersistable() {
// return this == BEFORE_PENDING || this == BEFORE_RUNNING || this == AFTER_PENDING || this == AFTER_RUNNING;
// }
// }
// Path: web/src/main/java/de/otto/jlineup/service/InvalidRunStateException.java
import de.otto.jlineup.web.State;
package de.otto.jlineup.service;
public class InvalidRunStateException extends Exception {
private final String id; | private final State currentState; |
otto-de/jlineup | core/src/main/java/de/otto/jlineup/config/JobConfigValidator.java | // Path: core/src/main/java/de/otto/jlineup/exceptions/ValidationError.java
// public class ValidationError extends RuntimeException {
// public ValidationError(String message) {
// super("Error during job config validation:\n" + message + "\nPlease check your jlineup job config.");
// }
// }
| import de.otto.jlineup.exceptions.ValidationError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.stream.Collectors;
import static java.lang.invoke.MethodHandles.lookup; | package de.otto.jlineup.config;
public class JobConfigValidator {
private final static Logger LOG = LoggerFactory.getLogger(lookup().lookupClass());
public static void validateJobConfig(JobConfig jobConfig) {
//Check urls
if (jobConfig.urls == null || jobConfig.urls.isEmpty()) { | // Path: core/src/main/java/de/otto/jlineup/exceptions/ValidationError.java
// public class ValidationError extends RuntimeException {
// public ValidationError(String message) {
// super("Error during job config validation:\n" + message + "\nPlease check your jlineup job config.");
// }
// }
// Path: core/src/main/java/de/otto/jlineup/config/JobConfigValidator.java
import de.otto.jlineup.exceptions.ValidationError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.stream.Collectors;
import static java.lang.invoke.MethodHandles.lookup;
package de.otto.jlineup.config;
public class JobConfigValidator {
private final static Logger LOG = LoggerFactory.getLogger(lookup().lookupClass());
public static void validateJobConfig(JobConfig jobConfig) {
//Check urls
if (jobConfig.urls == null || jobConfig.urls.isEmpty()) { | throw new ValidationError("No URLs configured."); |
otto-de/jlineup | web/src/main/java/de/otto/jlineup/web/configuration/JLineupConfiguration.java | // Path: web/src/main/java/de/otto/jlineup/service/Housekeeper.java
// public class Housekeeper {
//
// private static final int DELETE_REPORTS_AFTER_DAYS = 7;
// private static final int DELETE_SCREENSHOTS_AFTER_DAYS = 1;
// private static final int ONE_HOUR_IN_MILLIS = 60 * 60 * 1000;
// private static final String SELENIUM_SCREENSHOT_PREFIX = "screenshot";
// private static final String SELENIUM_SCREENSHOT_EXTENTION = ".png";
//
// private final static Logger LOG = LoggerFactory.getLogger(lookup().lookupClass());
//
// private final Path path;
//
// public Housekeeper(Path path) {
// this.path = path;
// }
//
// @Scheduled(fixedRate = ONE_HOUR_IN_MILLIS)
// public void deleteOldFiles() throws IOException {
// this.deleteReportsOlderThan(Duration.ofDays(DELETE_REPORTS_AFTER_DAYS));
// // in case the jlineup server is permanently running the screenshots taken by selenium within the tmp dir
// // will not be removed after the webdriver.close, that is why the screenshots must be removed using this job
// this.deleteSeleniumScreenshotsOlderThan(Duration.ofDays(DELETE_SCREENSHOTS_AFTER_DAYS));
// }
//
// private void deleteSeleniumScreenshotsOlderThan(Duration duration) throws IOException {
//
// Instant pointInTime = Instant.now().minus(duration);
//
// LOG.info("delete selenium screenshots older than {}", pointInTime);
//
// File tmpDir = new File(System.getProperty("java.io.tmpdir"));
//
// File[] screenShotFiles = tmpDir.listFiles((dir, fileName) ->
// fileName.startsWith(SELENIUM_SCREENSHOT_PREFIX) && fileName.endsWith(SELENIUM_SCREENSHOT_EXTENTION));
//
// if (screenShotFiles != null) {
// Stream.of(screenShotFiles)
// .map(File::toPath)
// .filter(filesOlderThan(pointInTime))
// .forEach(this::deleteFile);
// }
// }
//
// private void deleteReportsOlderThan(Duration duration) throws IOException {
//
// Instant pointInTime = Instant.now().minus(duration);
//
// LOG.info("delete reports older than {}", pointInTime);
//
// Files.list(path)
// .filter(filesOlderThan(pointInTime))
// .forEach(deletePath());
// }
//
// private void deleteFile(Path path) {
// try {
// Files.delete(path);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// private Consumer<Path> deletePath() {
// return file -> {
// try {
// FileUtils.deleteDirectory(file);
// } catch (IOException e) {
// e.printStackTrace();
// }
// };
// }
//
// private Predicate<Path> filesOlderThan(Instant pointInTime) {
// return file -> {
// try {
// Instant fileDate = Files.getLastModifiedTime(file).toInstant();
// return fileDate.isBefore(pointInTime);
// } catch (IOException e) {
// e.printStackTrace();
// return false;
// }
// };
// }
//
// }
| import de.otto.jlineup.service.Housekeeper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.nio.file.Paths; | package de.otto.jlineup.web.configuration;
@Configuration
public class JLineupConfiguration {
@Bean | // Path: web/src/main/java/de/otto/jlineup/service/Housekeeper.java
// public class Housekeeper {
//
// private static final int DELETE_REPORTS_AFTER_DAYS = 7;
// private static final int DELETE_SCREENSHOTS_AFTER_DAYS = 1;
// private static final int ONE_HOUR_IN_MILLIS = 60 * 60 * 1000;
// private static final String SELENIUM_SCREENSHOT_PREFIX = "screenshot";
// private static final String SELENIUM_SCREENSHOT_EXTENTION = ".png";
//
// private final static Logger LOG = LoggerFactory.getLogger(lookup().lookupClass());
//
// private final Path path;
//
// public Housekeeper(Path path) {
// this.path = path;
// }
//
// @Scheduled(fixedRate = ONE_HOUR_IN_MILLIS)
// public void deleteOldFiles() throws IOException {
// this.deleteReportsOlderThan(Duration.ofDays(DELETE_REPORTS_AFTER_DAYS));
// // in case the jlineup server is permanently running the screenshots taken by selenium within the tmp dir
// // will not be removed after the webdriver.close, that is why the screenshots must be removed using this job
// this.deleteSeleniumScreenshotsOlderThan(Duration.ofDays(DELETE_SCREENSHOTS_AFTER_DAYS));
// }
//
// private void deleteSeleniumScreenshotsOlderThan(Duration duration) throws IOException {
//
// Instant pointInTime = Instant.now().minus(duration);
//
// LOG.info("delete selenium screenshots older than {}", pointInTime);
//
// File tmpDir = new File(System.getProperty("java.io.tmpdir"));
//
// File[] screenShotFiles = tmpDir.listFiles((dir, fileName) ->
// fileName.startsWith(SELENIUM_SCREENSHOT_PREFIX) && fileName.endsWith(SELENIUM_SCREENSHOT_EXTENTION));
//
// if (screenShotFiles != null) {
// Stream.of(screenShotFiles)
// .map(File::toPath)
// .filter(filesOlderThan(pointInTime))
// .forEach(this::deleteFile);
// }
// }
//
// private void deleteReportsOlderThan(Duration duration) throws IOException {
//
// Instant pointInTime = Instant.now().minus(duration);
//
// LOG.info("delete reports older than {}", pointInTime);
//
// Files.list(path)
// .filter(filesOlderThan(pointInTime))
// .forEach(deletePath());
// }
//
// private void deleteFile(Path path) {
// try {
// Files.delete(path);
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// private Consumer<Path> deletePath() {
// return file -> {
// try {
// FileUtils.deleteDirectory(file);
// } catch (IOException e) {
// e.printStackTrace();
// }
// };
// }
//
// private Predicate<Path> filesOlderThan(Instant pointInTime) {
// return file -> {
// try {
// Instant fileDate = Files.getLastModifiedTime(file).toInstant();
// return fileDate.isBefore(pointInTime);
// } catch (IOException e) {
// e.printStackTrace();
// return false;
// }
// };
// }
//
// }
// Path: web/src/main/java/de/otto/jlineup/web/configuration/JLineupConfiguration.java
import de.otto.jlineup.service.Housekeeper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.nio.file.Paths;
package de.otto.jlineup.web.configuration;
@Configuration
public class JLineupConfiguration {
@Bean | public Housekeeper houseKeeper(JLineupWebProperties properties) { |
otto-de/jlineup | web/src/test/java/de/otto/jlineup/service/HousekeeperTest.java | // Path: core/src/main/java/de/otto/jlineup/file/FileUtils.java
// public class FileUtils {
//
//
// public static void clearDirectory(String path) throws IOException {
// Path directory = Paths.get(path);
// try(DirectoryStream<Path> paths = Files.newDirectoryStream(directory);) {
// paths.forEach(file -> {
// try {
// if (Files.isDirectory(file)) {
// clearDirectory(file.toAbsolutePath().toString());
// }
//
// Files.delete(file);
// } catch (IOException e) {
// throw new UncheckedIOException(e);
// }
// });
// }
// }
//
// public static void deleteDirectory(Path path) throws IOException {
// clearDirectory(path.toString());
// Files.deleteIfExists(path);
// }
//
// public static void deleteDirectory(String path) throws IOException {
// deleteDirectory(Paths.get(path));
// }
//
// }
| import de.otto.jlineup.file.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.stream.Stream;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize; | package de.otto.jlineup.service;
public class HousekeeperTest {
private Path tempJLineupDirectory;
private Path tempDirectory;
private Housekeeper housekeeper;
@Before
public void before() throws IOException {
tempJLineupDirectory = Files.createTempDirectory("jlineup-web-test");
tempDirectory = new File(System.getProperty("java.io.tmpdir")).toPath();
housekeeper = new Housekeeper(tempJLineupDirectory);
}
@After
public void cleanUp() throws IOException { | // Path: core/src/main/java/de/otto/jlineup/file/FileUtils.java
// public class FileUtils {
//
//
// public static void clearDirectory(String path) throws IOException {
// Path directory = Paths.get(path);
// try(DirectoryStream<Path> paths = Files.newDirectoryStream(directory);) {
// paths.forEach(file -> {
// try {
// if (Files.isDirectory(file)) {
// clearDirectory(file.toAbsolutePath().toString());
// }
//
// Files.delete(file);
// } catch (IOException e) {
// throw new UncheckedIOException(e);
// }
// });
// }
// }
//
// public static void deleteDirectory(Path path) throws IOException {
// clearDirectory(path.toString());
// Files.deleteIfExists(path);
// }
//
// public static void deleteDirectory(String path) throws IOException {
// deleteDirectory(Paths.get(path));
// }
//
// }
// Path: web/src/test/java/de/otto/jlineup/service/HousekeeperTest.java
import de.otto.jlineup.file.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.stream.Stream;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
package de.otto.jlineup.service;
public class HousekeeperTest {
private Path tempJLineupDirectory;
private Path tempDirectory;
private Housekeeper housekeeper;
@Before
public void before() throws IOException {
tempJLineupDirectory = Files.createTempDirectory("jlineup-web-test");
tempDirectory = new File(System.getProperty("java.io.tmpdir")).toPath();
housekeeper = new Housekeeper(tempJLineupDirectory);
}
@After
public void cleanUp() throws IOException { | FileUtils.deleteDirectory(tempJLineupDirectory); |
otto-de/jlineup | core/src/main/java/de/otto/jlineup/RunStepConfig.java | // Path: core/src/main/java/de/otto/jlineup/config/Step.java
// public enum Step {
// before,
// after,
// compare
// }
| import de.otto.jlineup.config.Step;
import java.util.List;
import java.util.Map;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptyMap; | package de.otto.jlineup;
public class RunStepConfig {
private final String reportDirectory;
private final String workingDirectory;
private final String screenshotsDirectory; | // Path: core/src/main/java/de/otto/jlineup/config/Step.java
// public enum Step {
// before,
// after,
// compare
// }
// Path: core/src/main/java/de/otto/jlineup/RunStepConfig.java
import de.otto.jlineup.config.Step;
import java.util.List;
import java.util.Map;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptyMap;
package de.otto.jlineup;
public class RunStepConfig {
private final String reportDirectory;
private final String workingDirectory;
private final String screenshotsDirectory; | private final Step step; |
otto-de/jlineup | core/src/test/java/de/otto/jlineup/file/FileUtilsTest.java | // Path: core/src/main/java/de/otto/jlineup/file/FileUtils.java
// public static void clearDirectory(String path) throws IOException {
// Path directory = Paths.get(path);
// try(DirectoryStream<Path> paths = Files.newDirectoryStream(directory);) {
// paths.forEach(file -> {
// try {
// if (Files.isDirectory(file)) {
// clearDirectory(file.toAbsolutePath().toString());
// }
//
// Files.delete(file);
// } catch (IOException e) {
// throw new UncheckedIOException(e);
// }
// });
// }
// }
//
// Path: core/src/main/java/de/otto/jlineup/file/FileUtils.java
// public static void deleteDirectory(Path path) throws IOException {
// clearDirectory(path.toString());
// Files.deleteIfExists(path);
// }
| import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static de.otto.jlineup.file.FileUtils.clearDirectory;
import static de.otto.jlineup.file.FileUtils.deleteDirectory;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat; | package de.otto.jlineup.file;
public class FileUtilsTest {
@Test
public void shouldClearDirectory() throws IOException {
//given
final Path dirToClear = Files.createTempDirectory("jlineup-fileutils-test");
Files.createFile(dirToClear.resolve(Paths.get("test1")));
Files.createFile(dirToClear.resolve(Paths.get("test2")));
Files.createFile(dirToClear.resolve(Paths.get("test3")));
//when | // Path: core/src/main/java/de/otto/jlineup/file/FileUtils.java
// public static void clearDirectory(String path) throws IOException {
// Path directory = Paths.get(path);
// try(DirectoryStream<Path> paths = Files.newDirectoryStream(directory);) {
// paths.forEach(file -> {
// try {
// if (Files.isDirectory(file)) {
// clearDirectory(file.toAbsolutePath().toString());
// }
//
// Files.delete(file);
// } catch (IOException e) {
// throw new UncheckedIOException(e);
// }
// });
// }
// }
//
// Path: core/src/main/java/de/otto/jlineup/file/FileUtils.java
// public static void deleteDirectory(Path path) throws IOException {
// clearDirectory(path.toString());
// Files.deleteIfExists(path);
// }
// Path: core/src/test/java/de/otto/jlineup/file/FileUtilsTest.java
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static de.otto.jlineup.file.FileUtils.clearDirectory;
import static de.otto.jlineup.file.FileUtils.deleteDirectory;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
package de.otto.jlineup.file;
public class FileUtilsTest {
@Test
public void shouldClearDirectory() throws IOException {
//given
final Path dirToClear = Files.createTempDirectory("jlineup-fileutils-test");
Files.createFile(dirToClear.resolve(Paths.get("test1")));
Files.createFile(dirToClear.resolve(Paths.get("test2")));
Files.createFile(dirToClear.resolve(Paths.get("test3")));
//when | clearDirectory(dirToClear.toString()); |
otto-de/jlineup | core/src/test/java/de/otto/jlineup/file/FileUtilsTest.java | // Path: core/src/main/java/de/otto/jlineup/file/FileUtils.java
// public static void clearDirectory(String path) throws IOException {
// Path directory = Paths.get(path);
// try(DirectoryStream<Path> paths = Files.newDirectoryStream(directory);) {
// paths.forEach(file -> {
// try {
// if (Files.isDirectory(file)) {
// clearDirectory(file.toAbsolutePath().toString());
// }
//
// Files.delete(file);
// } catch (IOException e) {
// throw new UncheckedIOException(e);
// }
// });
// }
// }
//
// Path: core/src/main/java/de/otto/jlineup/file/FileUtils.java
// public static void deleteDirectory(Path path) throws IOException {
// clearDirectory(path.toString());
// Files.deleteIfExists(path);
// }
| import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static de.otto.jlineup.file.FileUtils.clearDirectory;
import static de.otto.jlineup.file.FileUtils.deleteDirectory;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat; | package de.otto.jlineup.file;
public class FileUtilsTest {
@Test
public void shouldClearDirectory() throws IOException {
//given
final Path dirToClear = Files.createTempDirectory("jlineup-fileutils-test");
Files.createFile(dirToClear.resolve(Paths.get("test1")));
Files.createFile(dirToClear.resolve(Paths.get("test2")));
Files.createFile(dirToClear.resolve(Paths.get("test3")));
//when
clearDirectory(dirToClear.toString());
//then
assertThat(dirToClear.toFile().list().length, is(0));
Files.delete(dirToClear);
}
@Test
public void shouldDeleteDirectory() throws IOException {
//given
final Path dirToDelete = Files.createTempDirectory("jlineup-fileutils-test");
Files.createDirectories(dirToDelete.resolve("one/two/three"));
//when | // Path: core/src/main/java/de/otto/jlineup/file/FileUtils.java
// public static void clearDirectory(String path) throws IOException {
// Path directory = Paths.get(path);
// try(DirectoryStream<Path> paths = Files.newDirectoryStream(directory);) {
// paths.forEach(file -> {
// try {
// if (Files.isDirectory(file)) {
// clearDirectory(file.toAbsolutePath().toString());
// }
//
// Files.delete(file);
// } catch (IOException e) {
// throw new UncheckedIOException(e);
// }
// });
// }
// }
//
// Path: core/src/main/java/de/otto/jlineup/file/FileUtils.java
// public static void deleteDirectory(Path path) throws IOException {
// clearDirectory(path.toString());
// Files.deleteIfExists(path);
// }
// Path: core/src/test/java/de/otto/jlineup/file/FileUtilsTest.java
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static de.otto.jlineup.file.FileUtils.clearDirectory;
import static de.otto.jlineup.file.FileUtils.deleteDirectory;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
package de.otto.jlineup.file;
public class FileUtilsTest {
@Test
public void shouldClearDirectory() throws IOException {
//given
final Path dirToClear = Files.createTempDirectory("jlineup-fileutils-test");
Files.createFile(dirToClear.resolve(Paths.get("test1")));
Files.createFile(dirToClear.resolve(Paths.get("test2")));
Files.createFile(dirToClear.resolve(Paths.get("test3")));
//when
clearDirectory(dirToClear.toString());
//then
assertThat(dirToClear.toFile().list().length, is(0));
Files.delete(dirToClear);
}
@Test
public void shouldDeleteDirectory() throws IOException {
//given
final Path dirToDelete = Files.createTempDirectory("jlineup-fileutils-test");
Files.createDirectories(dirToDelete.resolve("one/two/three"));
//when | deleteDirectory(dirToDelete); |
otto-de/jlineup | core/src/main/java/de/otto/jlineup/config/ReportFormatFilter.java | // Path: core/src/main/java/de/otto/jlineup/config/JobConfig.java
// public static final int DEFAULT_REPORT_FORMAT = 2;
| import static de.otto.jlineup.config.JobConfig.DEFAULT_REPORT_FORMAT; | package de.otto.jlineup.config;
public class ReportFormatFilter {
@Override
public boolean equals(Object obj) { | // Path: core/src/main/java/de/otto/jlineup/config/JobConfig.java
// public static final int DEFAULT_REPORT_FORMAT = 2;
// Path: core/src/main/java/de/otto/jlineup/config/ReportFormatFilter.java
import static de.otto.jlineup.config.JobConfig.DEFAULT_REPORT_FORMAT;
package de.otto.jlineup.config;
public class ReportFormatFilter {
@Override
public boolean equals(Object obj) { | return obj == null || obj.equals(DEFAULT_REPORT_FORMAT); |
otto-de/jlineup | cli/src/test/java/de/otto/jlineup/cli/RunStepConfigTest.java | // Path: core/src/main/java/de/otto/jlineup/RunStepConfig.java
// public class RunStepConfig {
//
// private final String reportDirectory;
// private final String workingDirectory;
// private final String screenshotsDirectory;
// private final Step step;
// private final Map<String, String> urlReplacements;
// private final List<String> chromeParameters;
// private final List<String> firefoxParameters;
//
// private RunStepConfig(Builder builder) {
// reportDirectory = builder.reportDirectory;
// workingDirectory = builder.workingDirectory;
// screenshotsDirectory = builder.screenshotsDirectory;
// step = builder.step;
// urlReplacements = builder.urlReplacements;
// chromeParameters = builder.chromeParameters;
// firefoxParameters = builder.firefoxParameters;
// }
//
// public static Builder jLineupRunConfigurationBuilder() {
// return new Builder();
// }
//
// public static Builder copyOfBuilder(RunStepConfig config) {
// return new Builder(config);
// }
//
// public String getReportDirectory() {
// return reportDirectory;
// }
//
// public String getWorkingDirectory() {
// return workingDirectory;
// }
//
// public String getScreenshotsDirectory() {
// return screenshotsDirectory;
// }
//
// public Step getStep() {
// return step;
// }
//
// public Map<String, String> getUrlReplacements() {
// return urlReplacements;
// }
//
// public List<String> getChromeParameters() {
// return chromeParameters;
// }
//
// public List<String> getFirefoxParameters() {
// return firefoxParameters;
// }
//
//
// public static final class Builder {
// private String reportDirectory;
// private String workingDirectory;
// private String screenshotsDirectory;
// private List<String> chromeParameters = emptyList();
// private List<String> firefoxParameters = emptyList();
// private Map<String, String> urlReplacements = emptyMap();
// private Step step;
//
// private Builder() {
// }
//
// private Builder(RunStepConfig copy) {
// this.reportDirectory = copy.getReportDirectory();
// this.workingDirectory = copy.getWorkingDirectory();
// this.screenshotsDirectory = copy.getScreenshotsDirectory();
// this.step = copy.getStep();
// this.urlReplacements = copy.getUrlReplacements();
// this.chromeParameters = copy.getChromeParameters();
// this.firefoxParameters = copy.getFirefoxParameters();
// }
//
// public Builder withReportDirectory(String val) {
// reportDirectory = val;
// return this;
// }
//
// public Builder withWorkingDirectory(String val) {
// workingDirectory = val;
// return this;
// }
//
// public Builder withScreenshotsDirectory(String val) {
// screenshotsDirectory = val;
// return this;
// }
//
// public Builder withStep(Step val) {
// step = val;
// return this;
// }
//
// public Builder withFirefoxParameters(List<String> val) {
// firefoxParameters = val;
// return this;
// }
//
// public Builder withChromeParameters(List<String> val) {
// chromeParameters = val;
// return this;
// }
//
// public RunStepConfig build() {
// return new RunStepConfig(this);
// }
//
// public Builder withUrlReplacements(Map<String, String> val) {
// urlReplacements = val;
// return this;
// }
// }
// }
//
// Path: core/src/main/java/de/otto/jlineup/config/Step.java
// public enum Step {
// before,
// after,
// compare
// }
| import de.otto.jlineup.RunStepConfig;
import de.otto.jlineup.config.Step;
import org.junit.Test;
import picocli.CommandLine;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is; | package de.otto.jlineup.cli;
public class RunStepConfigTest {
@Test
public void shouldConvertCommandlineParameters() {
JLineup commandLineParameters = new JLineup();
String[] params = {
"--screenshot-dir", "someScreenshotDirectory",
"--report-dir", "someReportDirectory",
"--working-dir", "someWorkingDirectory",
"--step", "after"
};
CommandLine commandLine = new CommandLine(commandLineParameters);
commandLine.parseArgs(params);
| // Path: core/src/main/java/de/otto/jlineup/RunStepConfig.java
// public class RunStepConfig {
//
// private final String reportDirectory;
// private final String workingDirectory;
// private final String screenshotsDirectory;
// private final Step step;
// private final Map<String, String> urlReplacements;
// private final List<String> chromeParameters;
// private final List<String> firefoxParameters;
//
// private RunStepConfig(Builder builder) {
// reportDirectory = builder.reportDirectory;
// workingDirectory = builder.workingDirectory;
// screenshotsDirectory = builder.screenshotsDirectory;
// step = builder.step;
// urlReplacements = builder.urlReplacements;
// chromeParameters = builder.chromeParameters;
// firefoxParameters = builder.firefoxParameters;
// }
//
// public static Builder jLineupRunConfigurationBuilder() {
// return new Builder();
// }
//
// public static Builder copyOfBuilder(RunStepConfig config) {
// return new Builder(config);
// }
//
// public String getReportDirectory() {
// return reportDirectory;
// }
//
// public String getWorkingDirectory() {
// return workingDirectory;
// }
//
// public String getScreenshotsDirectory() {
// return screenshotsDirectory;
// }
//
// public Step getStep() {
// return step;
// }
//
// public Map<String, String> getUrlReplacements() {
// return urlReplacements;
// }
//
// public List<String> getChromeParameters() {
// return chromeParameters;
// }
//
// public List<String> getFirefoxParameters() {
// return firefoxParameters;
// }
//
//
// public static final class Builder {
// private String reportDirectory;
// private String workingDirectory;
// private String screenshotsDirectory;
// private List<String> chromeParameters = emptyList();
// private List<String> firefoxParameters = emptyList();
// private Map<String, String> urlReplacements = emptyMap();
// private Step step;
//
// private Builder() {
// }
//
// private Builder(RunStepConfig copy) {
// this.reportDirectory = copy.getReportDirectory();
// this.workingDirectory = copy.getWorkingDirectory();
// this.screenshotsDirectory = copy.getScreenshotsDirectory();
// this.step = copy.getStep();
// this.urlReplacements = copy.getUrlReplacements();
// this.chromeParameters = copy.getChromeParameters();
// this.firefoxParameters = copy.getFirefoxParameters();
// }
//
// public Builder withReportDirectory(String val) {
// reportDirectory = val;
// return this;
// }
//
// public Builder withWorkingDirectory(String val) {
// workingDirectory = val;
// return this;
// }
//
// public Builder withScreenshotsDirectory(String val) {
// screenshotsDirectory = val;
// return this;
// }
//
// public Builder withStep(Step val) {
// step = val;
// return this;
// }
//
// public Builder withFirefoxParameters(List<String> val) {
// firefoxParameters = val;
// return this;
// }
//
// public Builder withChromeParameters(List<String> val) {
// chromeParameters = val;
// return this;
// }
//
// public RunStepConfig build() {
// return new RunStepConfig(this);
// }
//
// public Builder withUrlReplacements(Map<String, String> val) {
// urlReplacements = val;
// return this;
// }
// }
// }
//
// Path: core/src/main/java/de/otto/jlineup/config/Step.java
// public enum Step {
// before,
// after,
// compare
// }
// Path: cli/src/test/java/de/otto/jlineup/cli/RunStepConfigTest.java
import de.otto.jlineup.RunStepConfig;
import de.otto.jlineup.config.Step;
import org.junit.Test;
import picocli.CommandLine;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
package de.otto.jlineup.cli;
public class RunStepConfigTest {
@Test
public void shouldConvertCommandlineParameters() {
JLineup commandLineParameters = new JLineup();
String[] params = {
"--screenshot-dir", "someScreenshotDirectory",
"--report-dir", "someReportDirectory",
"--working-dir", "someWorkingDirectory",
"--step", "after"
};
CommandLine commandLine = new CommandLine(commandLineParameters);
commandLine.parseArgs(params);
| RunStepConfig runStepConfig = Utils.convertCommandLineParametersToRunConfiguration(commandLineParameters); |
otto-de/jlineup | cli/src/test/java/de/otto/jlineup/cli/RunStepConfigTest.java | // Path: core/src/main/java/de/otto/jlineup/RunStepConfig.java
// public class RunStepConfig {
//
// private final String reportDirectory;
// private final String workingDirectory;
// private final String screenshotsDirectory;
// private final Step step;
// private final Map<String, String> urlReplacements;
// private final List<String> chromeParameters;
// private final List<String> firefoxParameters;
//
// private RunStepConfig(Builder builder) {
// reportDirectory = builder.reportDirectory;
// workingDirectory = builder.workingDirectory;
// screenshotsDirectory = builder.screenshotsDirectory;
// step = builder.step;
// urlReplacements = builder.urlReplacements;
// chromeParameters = builder.chromeParameters;
// firefoxParameters = builder.firefoxParameters;
// }
//
// public static Builder jLineupRunConfigurationBuilder() {
// return new Builder();
// }
//
// public static Builder copyOfBuilder(RunStepConfig config) {
// return new Builder(config);
// }
//
// public String getReportDirectory() {
// return reportDirectory;
// }
//
// public String getWorkingDirectory() {
// return workingDirectory;
// }
//
// public String getScreenshotsDirectory() {
// return screenshotsDirectory;
// }
//
// public Step getStep() {
// return step;
// }
//
// public Map<String, String> getUrlReplacements() {
// return urlReplacements;
// }
//
// public List<String> getChromeParameters() {
// return chromeParameters;
// }
//
// public List<String> getFirefoxParameters() {
// return firefoxParameters;
// }
//
//
// public static final class Builder {
// private String reportDirectory;
// private String workingDirectory;
// private String screenshotsDirectory;
// private List<String> chromeParameters = emptyList();
// private List<String> firefoxParameters = emptyList();
// private Map<String, String> urlReplacements = emptyMap();
// private Step step;
//
// private Builder() {
// }
//
// private Builder(RunStepConfig copy) {
// this.reportDirectory = copy.getReportDirectory();
// this.workingDirectory = copy.getWorkingDirectory();
// this.screenshotsDirectory = copy.getScreenshotsDirectory();
// this.step = copy.getStep();
// this.urlReplacements = copy.getUrlReplacements();
// this.chromeParameters = copy.getChromeParameters();
// this.firefoxParameters = copy.getFirefoxParameters();
// }
//
// public Builder withReportDirectory(String val) {
// reportDirectory = val;
// return this;
// }
//
// public Builder withWorkingDirectory(String val) {
// workingDirectory = val;
// return this;
// }
//
// public Builder withScreenshotsDirectory(String val) {
// screenshotsDirectory = val;
// return this;
// }
//
// public Builder withStep(Step val) {
// step = val;
// return this;
// }
//
// public Builder withFirefoxParameters(List<String> val) {
// firefoxParameters = val;
// return this;
// }
//
// public Builder withChromeParameters(List<String> val) {
// chromeParameters = val;
// return this;
// }
//
// public RunStepConfig build() {
// return new RunStepConfig(this);
// }
//
// public Builder withUrlReplacements(Map<String, String> val) {
// urlReplacements = val;
// return this;
// }
// }
// }
//
// Path: core/src/main/java/de/otto/jlineup/config/Step.java
// public enum Step {
// before,
// after,
// compare
// }
| import de.otto.jlineup.RunStepConfig;
import de.otto.jlineup.config.Step;
import org.junit.Test;
import picocli.CommandLine;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is; | package de.otto.jlineup.cli;
public class RunStepConfigTest {
@Test
public void shouldConvertCommandlineParameters() {
JLineup commandLineParameters = new JLineup();
String[] params = {
"--screenshot-dir", "someScreenshotDirectory",
"--report-dir", "someReportDirectory",
"--working-dir", "someWorkingDirectory",
"--step", "after"
};
CommandLine commandLine = new CommandLine(commandLineParameters);
commandLine.parseArgs(params);
RunStepConfig runStepConfig = Utils.convertCommandLineParametersToRunConfiguration(commandLineParameters);
assertThat(runStepConfig.getReportDirectory(), is("someReportDirectory"));
assertThat(runStepConfig.getScreenshotsDirectory(), is("someScreenshotDirectory"));
assertThat(runStepConfig.getWorkingDirectory(), is("someWorkingDirectory")); | // Path: core/src/main/java/de/otto/jlineup/RunStepConfig.java
// public class RunStepConfig {
//
// private final String reportDirectory;
// private final String workingDirectory;
// private final String screenshotsDirectory;
// private final Step step;
// private final Map<String, String> urlReplacements;
// private final List<String> chromeParameters;
// private final List<String> firefoxParameters;
//
// private RunStepConfig(Builder builder) {
// reportDirectory = builder.reportDirectory;
// workingDirectory = builder.workingDirectory;
// screenshotsDirectory = builder.screenshotsDirectory;
// step = builder.step;
// urlReplacements = builder.urlReplacements;
// chromeParameters = builder.chromeParameters;
// firefoxParameters = builder.firefoxParameters;
// }
//
// public static Builder jLineupRunConfigurationBuilder() {
// return new Builder();
// }
//
// public static Builder copyOfBuilder(RunStepConfig config) {
// return new Builder(config);
// }
//
// public String getReportDirectory() {
// return reportDirectory;
// }
//
// public String getWorkingDirectory() {
// return workingDirectory;
// }
//
// public String getScreenshotsDirectory() {
// return screenshotsDirectory;
// }
//
// public Step getStep() {
// return step;
// }
//
// public Map<String, String> getUrlReplacements() {
// return urlReplacements;
// }
//
// public List<String> getChromeParameters() {
// return chromeParameters;
// }
//
// public List<String> getFirefoxParameters() {
// return firefoxParameters;
// }
//
//
// public static final class Builder {
// private String reportDirectory;
// private String workingDirectory;
// private String screenshotsDirectory;
// private List<String> chromeParameters = emptyList();
// private List<String> firefoxParameters = emptyList();
// private Map<String, String> urlReplacements = emptyMap();
// private Step step;
//
// private Builder() {
// }
//
// private Builder(RunStepConfig copy) {
// this.reportDirectory = copy.getReportDirectory();
// this.workingDirectory = copy.getWorkingDirectory();
// this.screenshotsDirectory = copy.getScreenshotsDirectory();
// this.step = copy.getStep();
// this.urlReplacements = copy.getUrlReplacements();
// this.chromeParameters = copy.getChromeParameters();
// this.firefoxParameters = copy.getFirefoxParameters();
// }
//
// public Builder withReportDirectory(String val) {
// reportDirectory = val;
// return this;
// }
//
// public Builder withWorkingDirectory(String val) {
// workingDirectory = val;
// return this;
// }
//
// public Builder withScreenshotsDirectory(String val) {
// screenshotsDirectory = val;
// return this;
// }
//
// public Builder withStep(Step val) {
// step = val;
// return this;
// }
//
// public Builder withFirefoxParameters(List<String> val) {
// firefoxParameters = val;
// return this;
// }
//
// public Builder withChromeParameters(List<String> val) {
// chromeParameters = val;
// return this;
// }
//
// public RunStepConfig build() {
// return new RunStepConfig(this);
// }
//
// public Builder withUrlReplacements(Map<String, String> val) {
// urlReplacements = val;
// return this;
// }
// }
// }
//
// Path: core/src/main/java/de/otto/jlineup/config/Step.java
// public enum Step {
// before,
// after,
// compare
// }
// Path: cli/src/test/java/de/otto/jlineup/cli/RunStepConfigTest.java
import de.otto.jlineup.RunStepConfig;
import de.otto.jlineup.config.Step;
import org.junit.Test;
import picocli.CommandLine;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
package de.otto.jlineup.cli;
public class RunStepConfigTest {
@Test
public void shouldConvertCommandlineParameters() {
JLineup commandLineParameters = new JLineup();
String[] params = {
"--screenshot-dir", "someScreenshotDirectory",
"--report-dir", "someReportDirectory",
"--working-dir", "someWorkingDirectory",
"--step", "after"
};
CommandLine commandLine = new CommandLine(commandLineParameters);
commandLine.parseArgs(params);
RunStepConfig runStepConfig = Utils.convertCommandLineParametersToRunConfiguration(commandLineParameters);
assertThat(runStepConfig.getReportDirectory(), is("someReportDirectory"));
assertThat(runStepConfig.getScreenshotsDirectory(), is("someScreenshotDirectory"));
assertThat(runStepConfig.getWorkingDirectory(), is("someWorkingDirectory")); | assertThat(runStepConfig.getStep(), is(Step.after)); |
otto-de/jlineup | core/src/test/java/de/otto/jlineup/image/ImageServiceTest.java | // Path: core/src/main/java/de/otto/jlineup/config/JobConfig.java
// public static final float DEFAULT_MAX_COLOR_DISTANCE = 2.3f;
//
// Path: core/src/main/java/de/otto/jlineup/image/ImageService.java
// public static boolean bufferedImagesEqual(BufferedImage image1, BufferedImage image2) {
// if (image1.getWidth() == image2.getWidth() && image1.getHeight() == image2.getHeight()) {
// for (int xPosition = 0; xPosition < image1.getWidth(); xPosition++) {
// for (int yPosition = 0; yPosition < image1.getHeight(); yPosition++) {
// if (image1.getRGB(xPosition, yPosition) != image2.getRGB(xPosition, yPosition))
// return false;
// }
// }
// } else {
// return false;
// }
// return true;
// }
| import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import static de.otto.jlineup.config.JobConfig.DEFAULT_MAX_COLOR_DISTANCE;
import static de.otto.jlineup.image.ImageService.bufferedImagesEqual;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan; | package de.otto.jlineup.image;
public class ImageServiceTest {
ImageService testee;
@Before
public void setup() {
testee = new ImageService();
}
@Test
public void shouldGenerateDifferenceImage() throws IOException {
//given
final int viewportHeight = 800;
final BufferedImage beforeImageBuffer = ImageIO.read(new File("src/test/resources/screenshots/http_url_root_ff3c40c_1001_02002_before.png"));
final BufferedImage afterImageBuffer = ImageIO.read(new File("src/test/resources/screenshots/http_url_root_ff3c40c_1001_02002_after.png"));
final BufferedImage referenceImageBuffer = ImageIO.read(new File("src/test/resources/screenshots/http_url_root_ff3c40c_1001_02002_DIFFERENCE_reference.png"));
//when
ImageService.ImageComparisonResult result = testee.compareImages(beforeImageBuffer, afterImageBuffer, viewportHeight);
//then
assertThat(result.getDifference(), is(0.07005)); | // Path: core/src/main/java/de/otto/jlineup/config/JobConfig.java
// public static final float DEFAULT_MAX_COLOR_DISTANCE = 2.3f;
//
// Path: core/src/main/java/de/otto/jlineup/image/ImageService.java
// public static boolean bufferedImagesEqual(BufferedImage image1, BufferedImage image2) {
// if (image1.getWidth() == image2.getWidth() && image1.getHeight() == image2.getHeight()) {
// for (int xPosition = 0; xPosition < image1.getWidth(); xPosition++) {
// for (int yPosition = 0; yPosition < image1.getHeight(); yPosition++) {
// if (image1.getRGB(xPosition, yPosition) != image2.getRGB(xPosition, yPosition))
// return false;
// }
// }
// } else {
// return false;
// }
// return true;
// }
// Path: core/src/test/java/de/otto/jlineup/image/ImageServiceTest.java
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import static de.otto.jlineup.config.JobConfig.DEFAULT_MAX_COLOR_DISTANCE;
import static de.otto.jlineup.image.ImageService.bufferedImagesEqual;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
package de.otto.jlineup.image;
public class ImageServiceTest {
ImageService testee;
@Before
public void setup() {
testee = new ImageService();
}
@Test
public void shouldGenerateDifferenceImage() throws IOException {
//given
final int viewportHeight = 800;
final BufferedImage beforeImageBuffer = ImageIO.read(new File("src/test/resources/screenshots/http_url_root_ff3c40c_1001_02002_before.png"));
final BufferedImage afterImageBuffer = ImageIO.read(new File("src/test/resources/screenshots/http_url_root_ff3c40c_1001_02002_after.png"));
final BufferedImage referenceImageBuffer = ImageIO.read(new File("src/test/resources/screenshots/http_url_root_ff3c40c_1001_02002_DIFFERENCE_reference.png"));
//when
ImageService.ImageComparisonResult result = testee.compareImages(beforeImageBuffer, afterImageBuffer, viewportHeight);
//then
assertThat(result.getDifference(), is(0.07005)); | assertThat(bufferedImagesEqual(referenceImageBuffer, result.getDifferenceImage().orElse(null)), is(true)); |
otto-de/jlineup | core/src/test/java/de/otto/jlineup/image/ImageServiceTest.java | // Path: core/src/main/java/de/otto/jlineup/config/JobConfig.java
// public static final float DEFAULT_MAX_COLOR_DISTANCE = 2.3f;
//
// Path: core/src/main/java/de/otto/jlineup/image/ImageService.java
// public static boolean bufferedImagesEqual(BufferedImage image1, BufferedImage image2) {
// if (image1.getWidth() == image2.getWidth() && image1.getHeight() == image2.getHeight()) {
// for (int xPosition = 0; xPosition < image1.getWidth(); xPosition++) {
// for (int yPosition = 0; yPosition < image1.getHeight(); yPosition++) {
// if (image1.getRGB(xPosition, yPosition) != image2.getRGB(xPosition, yPosition))
// return false;
// }
// }
// } else {
// return false;
// }
// return true;
// }
| import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import static de.otto.jlineup.config.JobConfig.DEFAULT_MAX_COLOR_DISTANCE;
import static de.otto.jlineup.image.ImageService.bufferedImagesEqual;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan; | package de.otto.jlineup.image;
public class ImageServiceTest {
ImageService testee;
@Before
public void setup() {
testee = new ImageService();
}
@Test
public void shouldGenerateDifferenceImage() throws IOException {
//given
final int viewportHeight = 800;
final BufferedImage beforeImageBuffer = ImageIO.read(new File("src/test/resources/screenshots/http_url_root_ff3c40c_1001_02002_before.png"));
final BufferedImage afterImageBuffer = ImageIO.read(new File("src/test/resources/screenshots/http_url_root_ff3c40c_1001_02002_after.png"));
final BufferedImage referenceImageBuffer = ImageIO.read(new File("src/test/resources/screenshots/http_url_root_ff3c40c_1001_02002_DIFFERENCE_reference.png"));
//when
ImageService.ImageComparisonResult result = testee.compareImages(beforeImageBuffer, afterImageBuffer, viewportHeight);
//then
assertThat(result.getDifference(), is(0.07005));
assertThat(bufferedImagesEqual(referenceImageBuffer, result.getDifferenceImage().orElse(null)), is(true));
}
@Test
public void shouldNotIgnoreSlightDifferencesInColorSpaceInStrictMode() throws IOException {
//given
final int viewportHeight = 800;
final BufferedImage beforeImageBuffer = ImageIO.read(new File("src/test/resources/screenshots/cases/chrome_rounded_edges_before.png"));
final BufferedImage afterImageBuffer = ImageIO.read(new File("src/test/resources/screenshots/cases/chrome_rounded_edges_after.png"));
final BufferedImage referenceImageBuffer = ImageIO.read(new File("src/test/resources/screenshots/cases/chrome_rounded_edges_DIFFERENCE.png"));
//when | // Path: core/src/main/java/de/otto/jlineup/config/JobConfig.java
// public static final float DEFAULT_MAX_COLOR_DISTANCE = 2.3f;
//
// Path: core/src/main/java/de/otto/jlineup/image/ImageService.java
// public static boolean bufferedImagesEqual(BufferedImage image1, BufferedImage image2) {
// if (image1.getWidth() == image2.getWidth() && image1.getHeight() == image2.getHeight()) {
// for (int xPosition = 0; xPosition < image1.getWidth(); xPosition++) {
// for (int yPosition = 0; yPosition < image1.getHeight(); yPosition++) {
// if (image1.getRGB(xPosition, yPosition) != image2.getRGB(xPosition, yPosition))
// return false;
// }
// }
// } else {
// return false;
// }
// return true;
// }
// Path: core/src/test/java/de/otto/jlineup/image/ImageServiceTest.java
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import static de.otto.jlineup.config.JobConfig.DEFAULT_MAX_COLOR_DISTANCE;
import static de.otto.jlineup.image.ImageService.bufferedImagesEqual;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
package de.otto.jlineup.image;
public class ImageServiceTest {
ImageService testee;
@Before
public void setup() {
testee = new ImageService();
}
@Test
public void shouldGenerateDifferenceImage() throws IOException {
//given
final int viewportHeight = 800;
final BufferedImage beforeImageBuffer = ImageIO.read(new File("src/test/resources/screenshots/http_url_root_ff3c40c_1001_02002_before.png"));
final BufferedImage afterImageBuffer = ImageIO.read(new File("src/test/resources/screenshots/http_url_root_ff3c40c_1001_02002_after.png"));
final BufferedImage referenceImageBuffer = ImageIO.read(new File("src/test/resources/screenshots/http_url_root_ff3c40c_1001_02002_DIFFERENCE_reference.png"));
//when
ImageService.ImageComparisonResult result = testee.compareImages(beforeImageBuffer, afterImageBuffer, viewportHeight);
//then
assertThat(result.getDifference(), is(0.07005));
assertThat(bufferedImagesEqual(referenceImageBuffer, result.getDifferenceImage().orElse(null)), is(true));
}
@Test
public void shouldNotIgnoreSlightDifferencesInColorSpaceInStrictMode() throws IOException {
//given
final int viewportHeight = 800;
final BufferedImage beforeImageBuffer = ImageIO.read(new File("src/test/resources/screenshots/cases/chrome_rounded_edges_before.png"));
final BufferedImage afterImageBuffer = ImageIO.read(new File("src/test/resources/screenshots/cases/chrome_rounded_edges_after.png"));
final BufferedImage referenceImageBuffer = ImageIO.read(new File("src/test/resources/screenshots/cases/chrome_rounded_edges_DIFFERENCE.png"));
//when | ImageService.ImageComparisonResult result = testee.compareImages(beforeImageBuffer, afterImageBuffer, viewportHeight, false, true, DEFAULT_MAX_COLOR_DISTANCE); |
otto-de/jlineup | web/src/main/java/de/otto/jlineup/service/Housekeeper.java | // Path: core/src/main/java/de/otto/jlineup/file/FileUtils.java
// public class FileUtils {
//
//
// public static void clearDirectory(String path) throws IOException {
// Path directory = Paths.get(path);
// try(DirectoryStream<Path> paths = Files.newDirectoryStream(directory);) {
// paths.forEach(file -> {
// try {
// if (Files.isDirectory(file)) {
// clearDirectory(file.toAbsolutePath().toString());
// }
//
// Files.delete(file);
// } catch (IOException e) {
// throw new UncheckedIOException(e);
// }
// });
// }
// }
//
// public static void deleteDirectory(Path path) throws IOException {
// clearDirectory(path.toString());
// Files.deleteIfExists(path);
// }
//
// public static void deleteDirectory(String path) throws IOException {
// deleteDirectory(Paths.get(path));
// }
//
// }
| import de.otto.jlineup.file.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Stream;
import static java.lang.invoke.MethodHandles.lookup; |
if (screenShotFiles != null) {
Stream.of(screenShotFiles)
.map(File::toPath)
.filter(filesOlderThan(pointInTime))
.forEach(this::deleteFile);
}
}
private void deleteReportsOlderThan(Duration duration) throws IOException {
Instant pointInTime = Instant.now().minus(duration);
LOG.info("delete reports older than {}", pointInTime);
Files.list(path)
.filter(filesOlderThan(pointInTime))
.forEach(deletePath());
}
private void deleteFile(Path path) {
try {
Files.delete(path);
} catch (IOException e) {
e.printStackTrace();
}
}
private Consumer<Path> deletePath() {
return file -> {
try { | // Path: core/src/main/java/de/otto/jlineup/file/FileUtils.java
// public class FileUtils {
//
//
// public static void clearDirectory(String path) throws IOException {
// Path directory = Paths.get(path);
// try(DirectoryStream<Path> paths = Files.newDirectoryStream(directory);) {
// paths.forEach(file -> {
// try {
// if (Files.isDirectory(file)) {
// clearDirectory(file.toAbsolutePath().toString());
// }
//
// Files.delete(file);
// } catch (IOException e) {
// throw new UncheckedIOException(e);
// }
// });
// }
// }
//
// public static void deleteDirectory(Path path) throws IOException {
// clearDirectory(path.toString());
// Files.deleteIfExists(path);
// }
//
// public static void deleteDirectory(String path) throws IOException {
// deleteDirectory(Paths.get(path));
// }
//
// }
// Path: web/src/main/java/de/otto/jlineup/service/Housekeeper.java
import de.otto.jlineup.file.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Stream;
import static java.lang.invoke.MethodHandles.lookup;
if (screenShotFiles != null) {
Stream.of(screenShotFiles)
.map(File::toPath)
.filter(filesOlderThan(pointInTime))
.forEach(this::deleteFile);
}
}
private void deleteReportsOlderThan(Duration duration) throws IOException {
Instant pointInTime = Instant.now().minus(duration);
LOG.info("delete reports older than {}", pointInTime);
Files.list(path)
.filter(filesOlderThan(pointInTime))
.forEach(deletePath());
}
private void deleteFile(Path path) {
try {
Files.delete(path);
} catch (IOException e) {
e.printStackTrace();
}
}
private Consumer<Path> deletePath() {
return file -> {
try { | FileUtils.deleteDirectory(file); |
otto-de/jlineup | cli/src/main/java/de/otto/jlineup/cli/Main.java | // Path: core/src/main/java/de/otto/jlineup/Utils.java
// public class Utils {
//
// private final static Logger LOG = LoggerFactory.getLogger(lookup().lookupClass());
//
// private final static AtomicInteger threadCounter = new AtomicInteger();
// public static final String JLINEUP_FILE_APPENDER = "JLineupFileAppender";
// public static final String SIFTING_APPENDER_NAME_IN_LOGBACK_XML = "SIFT";
//
// public static String readVersion() {
// Properties prop = new Properties();
// try {
// prop.load(Utils.class.getClassLoader().getResourceAsStream("version.properties"));
// } catch (Exception ex) {
// ex.printStackTrace();
// }
// return prop.getProperty("jlineup.version");
// }
//
// public static String readCommit() {
// Properties prop = new Properties();
// try {
// prop.load(Utils.class.getClassLoader().getResourceAsStream("version.properties"));
// } catch (Exception ex) {
// ex.printStackTrace();
// }
// return prop.getProperty("jlineup.commit");
// }
//
// public static ExecutorService createThreadPool(int threads, final String baseName) {
//
// if (threads < 1) {
// threads = 1;
// }
//
// final ThreadFactory factory = target -> {
// String name = String.format("%s-%d", baseName, threadCounter.getAndIncrement());
// final Thread thread = new Thread(target, name);
// LOG.debug("Created new worker thread.");
// thread.setUncaughtExceptionHandler((t, e) -> LOG.error("Exception", e));
// return thread;
// };
// return Executors.newFixedThreadPool(threads, factory);
// }
//
// public static void setLogLevelToDebug() {
// //ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
// //root.setLevel(Level.DEBUG);
// ch.qos.logback.classic.Logger otto = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("de.otto");
// otto.setLevel(Level.DEBUG);
// }
//
// public static void setDebugLogLevelsOfSelectedThirdPartyLibsToWarn() {
// ch.qos.logback.classic.Logger apache = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("org.apache.hc");
// apache.setLevel(Level.WARN);
// }
//
// public static void logToFile(String workingDir) {
// LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
// PatternLayoutEncoder ple = new PatternLayoutEncoder();
//
// ple.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
// ple.setContext(lc);
// ple.start();
// FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
// fileAppender.setName(JLINEUP_FILE_APPENDER);
// fileAppender.setFile(workingDir + "/jlineup.log");
// fileAppender.setEncoder(ple);
// fileAppender.setContext(lc);
// fileAppender.start();
//
// ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
// logger.addAppender(fileAppender);
// logger.setLevel(Level.DEBUG);
// }
//
// public static void stopFileLoggers() {
// ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
//
// Appender<ILoggingEvent> appender = logger.getAppender(JLINEUP_FILE_APPENDER);
// if (appender != null) {
// appender.stop();
// }
//
// appender = logger.getAppender(SIFTING_APPENDER_NAME_IN_LOGBACK_XML);
// if (appender != null) {
// appender.stop();
// }
// }
//
// public static boolean shouldUseLegacyReportFormat(JobConfig jobConfig) {
// return (jobConfig.reportFormat != null && jobConfig.reportFormat == 1) || (jobConfig.reportFormat == null && JobConfig.DEFAULT_REPORT_FORMAT == 1);
// }
//
// public static String getVersion() {
// return String.format("%s [%s]%n", readVersion(), readCommit());
// }
//
// public static void writeInfosForCommonErrors(String message) {
// if (message.contains("session deleted because of page crash")) {
// System.err.println("\n=====\n");
// System.err.println("It looks like you're using Google Chrome or Chromium and it crashes while browsing to your configured page.");
// System.err.println("Are you running inside a Docker container? Try to run JLineup with --chrome-parameter \"--disable-dev-shm-usage\" and this error might be gone.");
// System.err.println("\n=====\n");
// }
// }
// }
| import de.otto.jlineup.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import picocli.CommandLine;
import static java.lang.invoke.MethodHandles.lookup; | package de.otto.jlineup.cli;
public class Main {
private final static Logger LOG = LoggerFactory.getLogger(lookup().lookupClass());
static final int NO_EXIT = -1;
public static void main(String[] args) {
//For GraalVM support in WebdriverManager
String arch = System.getProperty("os.arch");
if (arch.endsWith("64") && "Substrate VM".equals(System.getProperty("java.vm.name"))) {
System.setProperty("wdm.architecture", "X64");
}
| // Path: core/src/main/java/de/otto/jlineup/Utils.java
// public class Utils {
//
// private final static Logger LOG = LoggerFactory.getLogger(lookup().lookupClass());
//
// private final static AtomicInteger threadCounter = new AtomicInteger();
// public static final String JLINEUP_FILE_APPENDER = "JLineupFileAppender";
// public static final String SIFTING_APPENDER_NAME_IN_LOGBACK_XML = "SIFT";
//
// public static String readVersion() {
// Properties prop = new Properties();
// try {
// prop.load(Utils.class.getClassLoader().getResourceAsStream("version.properties"));
// } catch (Exception ex) {
// ex.printStackTrace();
// }
// return prop.getProperty("jlineup.version");
// }
//
// public static String readCommit() {
// Properties prop = new Properties();
// try {
// prop.load(Utils.class.getClassLoader().getResourceAsStream("version.properties"));
// } catch (Exception ex) {
// ex.printStackTrace();
// }
// return prop.getProperty("jlineup.commit");
// }
//
// public static ExecutorService createThreadPool(int threads, final String baseName) {
//
// if (threads < 1) {
// threads = 1;
// }
//
// final ThreadFactory factory = target -> {
// String name = String.format("%s-%d", baseName, threadCounter.getAndIncrement());
// final Thread thread = new Thread(target, name);
// LOG.debug("Created new worker thread.");
// thread.setUncaughtExceptionHandler((t, e) -> LOG.error("Exception", e));
// return thread;
// };
// return Executors.newFixedThreadPool(threads, factory);
// }
//
// public static void setLogLevelToDebug() {
// //ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
// //root.setLevel(Level.DEBUG);
// ch.qos.logback.classic.Logger otto = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("de.otto");
// otto.setLevel(Level.DEBUG);
// }
//
// public static void setDebugLogLevelsOfSelectedThirdPartyLibsToWarn() {
// ch.qos.logback.classic.Logger apache = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("org.apache.hc");
// apache.setLevel(Level.WARN);
// }
//
// public static void logToFile(String workingDir) {
// LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
// PatternLayoutEncoder ple = new PatternLayoutEncoder();
//
// ple.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
// ple.setContext(lc);
// ple.start();
// FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
// fileAppender.setName(JLINEUP_FILE_APPENDER);
// fileAppender.setFile(workingDir + "/jlineup.log");
// fileAppender.setEncoder(ple);
// fileAppender.setContext(lc);
// fileAppender.start();
//
// ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
// logger.addAppender(fileAppender);
// logger.setLevel(Level.DEBUG);
// }
//
// public static void stopFileLoggers() {
// ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
//
// Appender<ILoggingEvent> appender = logger.getAppender(JLINEUP_FILE_APPENDER);
// if (appender != null) {
// appender.stop();
// }
//
// appender = logger.getAppender(SIFTING_APPENDER_NAME_IN_LOGBACK_XML);
// if (appender != null) {
// appender.stop();
// }
// }
//
// public static boolean shouldUseLegacyReportFormat(JobConfig jobConfig) {
// return (jobConfig.reportFormat != null && jobConfig.reportFormat == 1) || (jobConfig.reportFormat == null && JobConfig.DEFAULT_REPORT_FORMAT == 1);
// }
//
// public static String getVersion() {
// return String.format("%s [%s]%n", readVersion(), readCommit());
// }
//
// public static void writeInfosForCommonErrors(String message) {
// if (message.contains("session deleted because of page crash")) {
// System.err.println("\n=====\n");
// System.err.println("It looks like you're using Google Chrome or Chromium and it crashes while browsing to your configured page.");
// System.err.println("Are you running inside a Docker container? Try to run JLineup with --chrome-parameter \"--disable-dev-shm-usage\" and this error might be gone.");
// System.err.println("\n=====\n");
// }
// }
// }
// Path: cli/src/main/java/de/otto/jlineup/cli/Main.java
import de.otto.jlineup.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import picocli.CommandLine;
import static java.lang.invoke.MethodHandles.lookup;
package de.otto.jlineup.cli;
public class Main {
private final static Logger LOG = LoggerFactory.getLogger(lookup().lookupClass());
static final int NO_EXIT = -1;
public static void main(String[] args) {
//For GraalVM support in WebdriverManager
String arch = System.getProperty("os.arch");
if (arch.endsWith("64") && "Substrate VM".equals(System.getProperty("java.vm.name"))) {
System.setProperty("wdm.architecture", "X64");
}
| Utils.setDebugLogLevelsOfSelectedThirdPartyLibsToWarn(); |
ZorgeR/datFM | src/com/zlab/datFM/swiftp/server/CmdRETR.java | // Path: src/com/zlab/datFM/swiftp/Defaults.java
// public class Defaults {
// protected static int inputBufferSize = 256;
// public static int dataChunkSize = 65536; // do file I/O in 64k chunks
// protected static int sessionMonitorScrollBack = 10;
// protected static int serverLogScrollBack = 10;
// protected static int uiLogLevel = Defaults.release ? Log.INFO : Log.DEBUG;
// protected static int consoleLogLevel = Defaults.release ? Log.INFO : Log.DEBUG;
// protected static String settingsName = "SwiFTP";
// protected static String username = "ftp";
// protected static String password = "ftp";
// protected static int portNumber = 2121;
// // protected static int ipRetrievalAttempts = 5;
// public static final int tcpConnectionBacklog = 5;
// public static final String chrootDir = "/";
// public static final boolean acceptWifi = true;
// public static final boolean acceptNet = false; // don't incur bandwidth charges
// public static final boolean stayAwake = true;
// public static final int REMOTE_PROXY_PORT = 2222;
// public static final String STRING_ENCODING = "UTF-8";
// public static final int SO_TIMEOUT_MS = 30000; // socket timeout millis
// // FTP control sessions should start out in ASCII, according to the RFC.
// // However, many clients don't turn on UTF-8 even though they support it,
// // so we just turn it on by default.
// public static final String SESSION_ENCODING = "UTF-8";
//
// // This is a flag that should be true for public builds and false for dev builds
// public static final boolean release = true;
//
// // Try to fix the transfer stall bug, reopen the destination file periodically
// //public static final boolean do_reopen_hack = false;
// //public static final int bytes_between_reopen = 4000000;
//
// // Try to fix the transfer stall bug, flush the file periodically
// //public static final boolean do_flush_hack = false;
// //public static final int bytes_between_flush = 500000;
//
// public static final boolean do_mediascanner_notify = true;
//
//
// // public static int getIpRetrievalAttempts() {
// // return ipRetrievalAttempts;
// // }
//
// // public static void setIpRetrievalAttempts(int ipRetrievalAttempts) {
// // Defaults.ipRetrievalAttempts = ipRetrievalAttempts;
// // }
//
// public static int getPortNumber() {
// return portNumber;
// }
//
// public static void setPortNumber(int portNumber) {
// Defaults.portNumber = portNumber;
// }
//
// public static String getSettingsName() {
// return settingsName;
// }
//
// public static void setSettingsName(String settingsName) {
// Defaults.settingsName = settingsName;
// }
//
// public static int getSettingsMode() {
// return settingsMode;
// }
//
// public static void setSettingsMode(int settingsMode) {
// Defaults.settingsMode = settingsMode;
// }
//
// public static void setServerLogScrollBack(int serverLogScrollBack) {
// Defaults.serverLogScrollBack = serverLogScrollBack;
// }
//
// protected static int settingsMode = Context.MODE_WORLD_WRITEABLE;
//
// public static int getUiLogLevel() {
// return uiLogLevel;
// }
//
// public static void setUiLogLevel(int uiLogLevel) {
// Defaults.uiLogLevel = uiLogLevel;
// }
//
// public static int getInputBufferSize() {
// return inputBufferSize;
// }
//
// public static void setInputBufferSize(int inputBufferSize) {
// Defaults.inputBufferSize = inputBufferSize;
// }
//
// public static int getDataChunkSize() {
// return dataChunkSize;
// }
//
// public static void setDataChunkSize(int dataChunkSize) {
// Defaults.dataChunkSize = dataChunkSize;
// }
//
// public static int getSessionMonitorScrollBack() {
// return sessionMonitorScrollBack;
// }
//
// public static void setSessionMonitorScrollBack(
// int sessionMonitorScrollBack)
// {
// Defaults.sessionMonitorScrollBack = sessionMonitorScrollBack;
// }
//
// public static int getServerLogScrollBack() {
// return serverLogScrollBack;
// }
//
// public static void setLogScrollBack(int serverLogScrollBack) {
// Defaults.serverLogScrollBack = serverLogScrollBack;
// }
//
// public static int getConsoleLogLevel() {
// return consoleLogLevel;
// }
//
// public static void setConsoleLogLevel(int consoleLogLevel) {
// Defaults.consoleLogLevel = consoleLogLevel;
// }
//
//
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.util.Log;
import com.zlab.datFM.swiftp.Defaults; | Log.d(TAG, "RETR executing");
String param = getParameter(input);
File fileToRetr;
String errString = null;
mainblock: {
fileToRetr = inputPathToChrootedFile(sessionThread.getWorkingDir(), param);
if (violatesChroot(fileToRetr)) {
errString = "550 Invalid name or chroot violation\r\n";
break mainblock;
} else if (fileToRetr.isDirectory()) {
Log.d(TAG, "Ignoring RETR for directory");
errString = "550 Can't RETR a directory\r\n";
break mainblock;
} else if (!fileToRetr.exists()) {
Log.d(TAG, "Can't RETR nonexistent file: " + fileToRetr.getAbsolutePath());
errString = "550 File does not exist\r\n";
break mainblock;
} else if (!fileToRetr.canRead()) {
Log.i(TAG, "Failed RETR permission (canRead() is false)");
errString = "550 No read permissions\r\n";
break mainblock;
} /*
* else if(!sessionThread.isBinaryMode()) { myLog.l(Log.INFO,
* "Failed RETR in text mode"); errString =
* "550 Text mode RETR not supported\r\n"; break mainblock; }
*/
FileInputStream in = null;
try {
in = new FileInputStream(fileToRetr); | // Path: src/com/zlab/datFM/swiftp/Defaults.java
// public class Defaults {
// protected static int inputBufferSize = 256;
// public static int dataChunkSize = 65536; // do file I/O in 64k chunks
// protected static int sessionMonitorScrollBack = 10;
// protected static int serverLogScrollBack = 10;
// protected static int uiLogLevel = Defaults.release ? Log.INFO : Log.DEBUG;
// protected static int consoleLogLevel = Defaults.release ? Log.INFO : Log.DEBUG;
// protected static String settingsName = "SwiFTP";
// protected static String username = "ftp";
// protected static String password = "ftp";
// protected static int portNumber = 2121;
// // protected static int ipRetrievalAttempts = 5;
// public static final int tcpConnectionBacklog = 5;
// public static final String chrootDir = "/";
// public static final boolean acceptWifi = true;
// public static final boolean acceptNet = false; // don't incur bandwidth charges
// public static final boolean stayAwake = true;
// public static final int REMOTE_PROXY_PORT = 2222;
// public static final String STRING_ENCODING = "UTF-8";
// public static final int SO_TIMEOUT_MS = 30000; // socket timeout millis
// // FTP control sessions should start out in ASCII, according to the RFC.
// // However, many clients don't turn on UTF-8 even though they support it,
// // so we just turn it on by default.
// public static final String SESSION_ENCODING = "UTF-8";
//
// // This is a flag that should be true for public builds and false for dev builds
// public static final boolean release = true;
//
// // Try to fix the transfer stall bug, reopen the destination file periodically
// //public static final boolean do_reopen_hack = false;
// //public static final int bytes_between_reopen = 4000000;
//
// // Try to fix the transfer stall bug, flush the file periodically
// //public static final boolean do_flush_hack = false;
// //public static final int bytes_between_flush = 500000;
//
// public static final boolean do_mediascanner_notify = true;
//
//
// // public static int getIpRetrievalAttempts() {
// // return ipRetrievalAttempts;
// // }
//
// // public static void setIpRetrievalAttempts(int ipRetrievalAttempts) {
// // Defaults.ipRetrievalAttempts = ipRetrievalAttempts;
// // }
//
// public static int getPortNumber() {
// return portNumber;
// }
//
// public static void setPortNumber(int portNumber) {
// Defaults.portNumber = portNumber;
// }
//
// public static String getSettingsName() {
// return settingsName;
// }
//
// public static void setSettingsName(String settingsName) {
// Defaults.settingsName = settingsName;
// }
//
// public static int getSettingsMode() {
// return settingsMode;
// }
//
// public static void setSettingsMode(int settingsMode) {
// Defaults.settingsMode = settingsMode;
// }
//
// public static void setServerLogScrollBack(int serverLogScrollBack) {
// Defaults.serverLogScrollBack = serverLogScrollBack;
// }
//
// protected static int settingsMode = Context.MODE_WORLD_WRITEABLE;
//
// public static int getUiLogLevel() {
// return uiLogLevel;
// }
//
// public static void setUiLogLevel(int uiLogLevel) {
// Defaults.uiLogLevel = uiLogLevel;
// }
//
// public static int getInputBufferSize() {
// return inputBufferSize;
// }
//
// public static void setInputBufferSize(int inputBufferSize) {
// Defaults.inputBufferSize = inputBufferSize;
// }
//
// public static int getDataChunkSize() {
// return dataChunkSize;
// }
//
// public static void setDataChunkSize(int dataChunkSize) {
// Defaults.dataChunkSize = dataChunkSize;
// }
//
// public static int getSessionMonitorScrollBack() {
// return sessionMonitorScrollBack;
// }
//
// public static void setSessionMonitorScrollBack(
// int sessionMonitorScrollBack)
// {
// Defaults.sessionMonitorScrollBack = sessionMonitorScrollBack;
// }
//
// public static int getServerLogScrollBack() {
// return serverLogScrollBack;
// }
//
// public static void setLogScrollBack(int serverLogScrollBack) {
// Defaults.serverLogScrollBack = serverLogScrollBack;
// }
//
// public static int getConsoleLogLevel() {
// return consoleLogLevel;
// }
//
// public static void setConsoleLogLevel(int consoleLogLevel) {
// Defaults.consoleLogLevel = consoleLogLevel;
// }
//
//
// }
// Path: src/com/zlab/datFM/swiftp/server/CmdRETR.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import android.util.Log;
import com.zlab.datFM.swiftp.Defaults;
Log.d(TAG, "RETR executing");
String param = getParameter(input);
File fileToRetr;
String errString = null;
mainblock: {
fileToRetr = inputPathToChrootedFile(sessionThread.getWorkingDir(), param);
if (violatesChroot(fileToRetr)) {
errString = "550 Invalid name or chroot violation\r\n";
break mainblock;
} else if (fileToRetr.isDirectory()) {
Log.d(TAG, "Ignoring RETR for directory");
errString = "550 Can't RETR a directory\r\n";
break mainblock;
} else if (!fileToRetr.exists()) {
Log.d(TAG, "Can't RETR nonexistent file: " + fileToRetr.getAbsolutePath());
errString = "550 File does not exist\r\n";
break mainblock;
} else if (!fileToRetr.canRead()) {
Log.i(TAG, "Failed RETR permission (canRead() is false)");
errString = "550 No read permissions\r\n";
break mainblock;
} /*
* else if(!sessionThread.isBinaryMode()) { myLog.l(Log.INFO,
* "Failed RETR in text mode"); errString =
* "550 Text mode RETR not supported\r\n"; break mainblock; }
*/
FileInputStream in = null;
try {
in = new FileInputStream(fileToRetr); | byte[] buffer = new byte[Defaults.getDataChunkSize()]; |
ZorgeR/datFM | src/com/zlab/datFM/player/VideoControllerView.java | // Path: gen/com/zlab/datFM/R.java
// public final class R {
// }
| import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import com.zlab.datFM.R;
import java.lang.ref.WeakReference;
import java.util.Formatter;
import java.util.Locale; | if (uniqueDown) {
hide();
}
return true;
}
show(sDefaultTimeout);
return super.dispatchKeyEvent(event);
}
private View.OnClickListener mPauseListener = new View.OnClickListener() {
public void onClick(View v) {
doPauseResume();
show(sDefaultTimeout);
}
};
private View.OnClickListener mFullscreenListener = new View.OnClickListener() {
public void onClick(View v) {
doToggleFullscreen();
show(sDefaultTimeout);
}
};
public void updatePausePlay() {
if (mRoot == null || mPauseButton == null || mPlayer == null) {
return;
}
if (mPlayer.isPlaying()) { | // Path: gen/com/zlab/datFM/R.java
// public final class R {
// }
// Path: src/com/zlab/datFM/player/VideoControllerView.java
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import com.zlab.datFM.R;
import java.lang.ref.WeakReference;
import java.util.Formatter;
import java.util.Locale;
if (uniqueDown) {
hide();
}
return true;
}
show(sDefaultTimeout);
return super.dispatchKeyEvent(event);
}
private View.OnClickListener mPauseListener = new View.OnClickListener() {
public void onClick(View v) {
doPauseResume();
show(sDefaultTimeout);
}
};
private View.OnClickListener mFullscreenListener = new View.OnClickListener() {
public void onClick(View v) {
doToggleFullscreen();
show(sDefaultTimeout);
}
};
public void updatePausePlay() {
if (mRoot == null || mPauseButton == null || mPlayer == null) {
return;
}
if (mPlayer.isPlaying()) { | mPauseButton.setImageResource(R.drawable.ic_media_pause); |
ZorgeR/datFM | src/com/zlab/datFM/swiftp/server/CmdRMD.java | // Path: src/com/zlab/datFM/swiftp/MediaUpdater.java
// public enum MediaUpdater {
// INSTANCE;
//
// private final static String TAG = MediaUpdater.class.getSimpleName();
//
// // the systembroadcast to remount the media is only done after a little while (5s)
// private static Timer sTimer = new Timer();
//
// public static void notifyFileCreated(String path) {
// if (Defaults.do_mediascanner_notify) {
// Log.d(TAG, "Notifying others about new file: " + path);
// Context context = FtpServerApp.getAppContext();
// MediaScannerConnection.scanFile(context, new String[]{path}, null,
// new MediaScannerConnection.OnScanCompletedListener() {
// @Override
// public void onScanCompleted(String path, Uri uri) {
// }
// });
// }
// }
//
// public static void notifyFileDeleted(String path) {
// // The media mounted broadcast is very taxing on the system, so we only do this
// // if for 5 seconds there was no same request, otherwise we wait again.
// if (Defaults.do_mediascanner_notify) {
// Log.d(TAG, "Notifying others about deleted file: " + path);
// // the systembroadcast might have been requested already, cancel if so
// sTimer.cancel();
// // that timer is of no value any more, create a new one
// sTimer = new Timer();
// // and in 5s let it send the broadcast, might never hapen if before
// // that time it gets canceled by this code path
// sTimer.schedule(new TimerTask() {
// @Override
// public void run() {
// Log.d(TAG, "Sending ACTION_MEDIA_MOUNTED broadcast");
// final Context context = FtpServerApp.getAppContext();
// context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri
// .parse("file://" + Environment.getExternalStorageDirectory())));
// }
// }, 5000);
// }
// }
//
// }
| import com.zlab.datFM.swiftp.MediaUpdater;
import java.io.File;
import android.util.Log; | sessionThread.writeString(errString);
Log.i(TAG, "RMD failed: " + errString.trim());
} else {
sessionThread.writeString("250 Removed directory\r\n");
}
Log.d(TAG, "RMD finished");
}
/**
* Accepts a file or directory name, and recursively deletes the contents of that
* directory and all subdirectories.
*
* @param toDelete
* @return Whether the operation completed successfully
*/
protected boolean recursiveDelete(File toDelete) {
if (!toDelete.exists()) {
return false;
}
if (toDelete.isDirectory()) {
// If any of the recursive operations fail, then we return false
boolean success = true;
for (File entry : toDelete.listFiles()) {
success &= recursiveDelete(entry);
}
Log.d(TAG, "Recursively deleted: " + toDelete);
return success && toDelete.delete();
} else {
Log.d(TAG, "RMD deleting file: " + toDelete);
boolean success = toDelete.delete(); | // Path: src/com/zlab/datFM/swiftp/MediaUpdater.java
// public enum MediaUpdater {
// INSTANCE;
//
// private final static String TAG = MediaUpdater.class.getSimpleName();
//
// // the systembroadcast to remount the media is only done after a little while (5s)
// private static Timer sTimer = new Timer();
//
// public static void notifyFileCreated(String path) {
// if (Defaults.do_mediascanner_notify) {
// Log.d(TAG, "Notifying others about new file: " + path);
// Context context = FtpServerApp.getAppContext();
// MediaScannerConnection.scanFile(context, new String[]{path}, null,
// new MediaScannerConnection.OnScanCompletedListener() {
// @Override
// public void onScanCompleted(String path, Uri uri) {
// }
// });
// }
// }
//
// public static void notifyFileDeleted(String path) {
// // The media mounted broadcast is very taxing on the system, so we only do this
// // if for 5 seconds there was no same request, otherwise we wait again.
// if (Defaults.do_mediascanner_notify) {
// Log.d(TAG, "Notifying others about deleted file: " + path);
// // the systembroadcast might have been requested already, cancel if so
// sTimer.cancel();
// // that timer is of no value any more, create a new one
// sTimer = new Timer();
// // and in 5s let it send the broadcast, might never hapen if before
// // that time it gets canceled by this code path
// sTimer.schedule(new TimerTask() {
// @Override
// public void run() {
// Log.d(TAG, "Sending ACTION_MEDIA_MOUNTED broadcast");
// final Context context = FtpServerApp.getAppContext();
// context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri
// .parse("file://" + Environment.getExternalStorageDirectory())));
// }
// }, 5000);
// }
// }
//
// }
// Path: src/com/zlab/datFM/swiftp/server/CmdRMD.java
import com.zlab.datFM.swiftp.MediaUpdater;
import java.io.File;
import android.util.Log;
sessionThread.writeString(errString);
Log.i(TAG, "RMD failed: " + errString.trim());
} else {
sessionThread.writeString("250 Removed directory\r\n");
}
Log.d(TAG, "RMD finished");
}
/**
* Accepts a file or directory name, and recursively deletes the contents of that
* directory and all subdirectories.
*
* @param toDelete
* @return Whether the operation completed successfully
*/
protected boolean recursiveDelete(File toDelete) {
if (!toDelete.exists()) {
return false;
}
if (toDelete.isDirectory()) {
// If any of the recursive operations fail, then we return false
boolean success = true;
for (File entry : toDelete.listFiles()) {
success &= recursiveDelete(entry);
}
Log.d(TAG, "Recursively deleted: " + toDelete);
return success && toDelete.delete();
} else {
Log.d(TAG, "RMD deleting file: " + toDelete);
boolean success = toDelete.delete(); | MediaUpdater.notifyFileDeleted(toDelete.getPath()); |
ZorgeR/datFM | src/com/zlab/datFM/swiftp/server/CmdPASS.java | // Path: src/com/zlab/datFM/swiftp/FtpServerApp.java
// public class FtpServerApp extends Application {
//
// private static final String TAG = FtpServerApp.class.getSimpleName();
//
// private static Context sContext;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sContext = getApplicationContext();
// }
//
// /**
// * @return the Context of this application
// */
// public static Context getAppContext() {
// if (sContext == null){
// Log.e(TAG, "Global context not set");
// sContext = datFM.datFM_context;
// }
// return sContext;
// }
//
// /**
// * @return true if this is the free version
// */
// public static boolean isFreeVersion() {
// try {
// Context context = getAppContext();
// return context.getPackageName().contains("free");
// } catch (Exception swallow) {
// }
// return false;
// }
//
// /**
// * Get the version from the manifest.
// *
// * @return The version as a String.
// */
// public static String getVersion() {
// Context context = getAppContext();
// String packageName = context.getPackageName();
// try {
// PackageManager pm = context.getPackageManager();
// return pm.getPackageInfo(packageName, 0).versionName;
// } catch (NameNotFoundException e) {
// Log.e(TAG, "Unable to find the name " + packageName + " in the package");
// return null;
// }
// }
//
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import com.zlab.datFM.swiftp.FtpServerApp; | /*
Copyright 2009 David Revell
This file is part of SwiFTP.
SwiFTP 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.
SwiFTP 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 SwiFTP. If not, see <http://www.gnu.org/licenses/>.
*/
package com.zlab.datFM.swiftp.server;
public class CmdPASS extends FtpCmd implements Runnable {
private static final String TAG = CmdPASS.class.getSimpleName();
String input;
public CmdPASS(SessionThread sessionThread, String input) {
// We can just discard the password for now. We're just
// following the expected dialogue, we're going to allow
// access in any case.
super(sessionThread);
this.input = input;
}
@Override
public void run() {
Log.d(TAG, "Executing PASS");
// User must have already executed a USER command to
// populate the Account object's username
String attemptPassword = getParameter(input, true); // silent
String attemptUsername = sessionThread.account.getUsername();
if (attemptUsername == null) {
sessionThread.writeString("503 Must send USER first\r\n");
return;
} | // Path: src/com/zlab/datFM/swiftp/FtpServerApp.java
// public class FtpServerApp extends Application {
//
// private static final String TAG = FtpServerApp.class.getSimpleName();
//
// private static Context sContext;
//
// @Override
// public void onCreate() {
// super.onCreate();
// sContext = getApplicationContext();
// }
//
// /**
// * @return the Context of this application
// */
// public static Context getAppContext() {
// if (sContext == null){
// Log.e(TAG, "Global context not set");
// sContext = datFM.datFM_context;
// }
// return sContext;
// }
//
// /**
// * @return true if this is the free version
// */
// public static boolean isFreeVersion() {
// try {
// Context context = getAppContext();
// return context.getPackageName().contains("free");
// } catch (Exception swallow) {
// }
// return false;
// }
//
// /**
// * Get the version from the manifest.
// *
// * @return The version as a String.
// */
// public static String getVersion() {
// Context context = getAppContext();
// String packageName = context.getPackageName();
// try {
// PackageManager pm = context.getPackageManager();
// return pm.getPackageInfo(packageName, 0).versionName;
// } catch (NameNotFoundException e) {
// Log.e(TAG, "Unable to find the name " + packageName + " in the package");
// return null;
// }
// }
//
// }
// Path: src/com/zlab/datFM/swiftp/server/CmdPASS.java
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import com.zlab.datFM.swiftp.FtpServerApp;
/*
Copyright 2009 David Revell
This file is part of SwiFTP.
SwiFTP 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.
SwiFTP 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 SwiFTP. If not, see <http://www.gnu.org/licenses/>.
*/
package com.zlab.datFM.swiftp.server;
public class CmdPASS extends FtpCmd implements Runnable {
private static final String TAG = CmdPASS.class.getSimpleName();
String input;
public CmdPASS(SessionThread sessionThread, String input) {
// We can just discard the password for now. We're just
// following the expected dialogue, we're going to allow
// access in any case.
super(sessionThread);
this.input = input;
}
@Override
public void run() {
Log.d(TAG, "Executing PASS");
// User must have already executed a USER command to
// populate the Account object's username
String attemptPassword = getParameter(input, true); // silent
String attemptUsername = sessionThread.account.getUsername();
if (attemptUsername == null) {
sessionThread.writeString("503 Must send USER first\r\n");
return;
} | Context ctx = FtpServerApp.getAppContext(); |
ZorgeR/datFM | src/com/zlab/datFM/swiftp/RequestStartStopReceiver.java | // Path: gen/com/zlab/datFM/R.java
// public final class R {
// }
| import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.os.*;
import android.widget.*;
import android.view.*;
import com.zlab.datFM.R; | package com.zlab.datFM.swiftp;
public class RequestStartStopReceiver extends BroadcastReceiver {
static final String TAG = RequestStartStopReceiver.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "Received: " + intent.getAction());
// TODO: analog code as in ServerPreferenceActivity.start/stopServer(), refactor
if (intent.getAction().equals(FtpServerService.ACTION_START_FTPSERVER)) {
Intent serverService = new Intent(context, FtpServerService.class);
if (!FtpServerService.isRunning()) {
warnIfNoExternalStorage();
context.startService(serverService);
}
} else if (intent.getAction().equals(FtpServerService.ACTION_STOP_FTPSERVER)) {
Intent serverService = new Intent(context, FtpServerService.class);
context.stopService(serverService);
}
}
/**
* Will check if the device contains external storage (sdcard) and display a warning
* for the user if there is no external storage. Nothing more.
*/
private void warnIfNoExternalStorage() {
String storageState = Environment.getExternalStorageState();
if (!storageState.equals(Environment.MEDIA_MOUNTED)) {
Log.v(TAG, "Warning due to storage state " + storageState);
Toast toast = Toast.makeText(FtpServerApp.getAppContext(), | // Path: gen/com/zlab/datFM/R.java
// public final class R {
// }
// Path: src/com/zlab/datFM/swiftp/RequestStartStopReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.os.*;
import android.widget.*;
import android.view.*;
import com.zlab.datFM.R;
package com.zlab.datFM.swiftp;
public class RequestStartStopReceiver extends BroadcastReceiver {
static final String TAG = RequestStartStopReceiver.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "Received: " + intent.getAction());
// TODO: analog code as in ServerPreferenceActivity.start/stopServer(), refactor
if (intent.getAction().equals(FtpServerService.ACTION_START_FTPSERVER)) {
Intent serverService = new Intent(context, FtpServerService.class);
if (!FtpServerService.isRunning()) {
warnIfNoExternalStorage();
context.startService(serverService);
}
} else if (intent.getAction().equals(FtpServerService.ACTION_STOP_FTPSERVER)) {
Intent serverService = new Intent(context, FtpServerService.class);
context.stopService(serverService);
}
}
/**
* Will check if the device contains external storage (sdcard) and display a warning
* for the user if there is no external storage. Nothing more.
*/
private void warnIfNoExternalStorage() {
String storageState = Environment.getExternalStorageState();
if (!storageState.equals(Environment.MEDIA_MOUNTED)) {
Log.v(TAG, "Warning due to storage state " + storageState);
Toast toast = Toast.makeText(FtpServerApp.getAppContext(), | R.string.storage_warning, Toast.LENGTH_LONG); |
ZorgeR/datFM | src/com/zlab/datFM/swiftp/server/FtpCmd.java | // Path: src/com/zlab/datFM/swiftp/Globals.java
// public class Globals {
// private static String lastError;
// private static File chrootDir = null;
// private static String username = null;
//
// public static File getChrootDir() {
// return chrootDir;
// }
//
// public static void setChrootDir(File chrootDir) {
// if (chrootDir.isDirectory()) {
// Globals.chrootDir = chrootDir;
// }
// }
//
// public static String getLastError() {
// return lastError;
// }
//
// public static void setLastError(String lastError) {
// Globals.lastError = lastError;
// }
//
// public static String getUsername() {
// return username;
// }
//
// public static void setUsername(String username) {
// Globals.username = username;
// }
//
// }
| import android.util.Log;
import com.zlab.datFM.swiftp.Globals;
import java.io.File;
import java.lang.reflect.Constructor; | if (input == null) {
return "";
}
int firstSpacePosition = input.indexOf(' ');
if (firstSpacePosition == -1) {
return "";
}
String retString = input.substring(firstSpacePosition + 1);
// Remove trailing whitespace
// todo: trailing whitespace may be significant, just remove \r\n
retString = retString.replaceAll("\\s+$", "");
if (!silent) {
Log.d(TAG, "Parsed argument: " + retString);
}
return retString;
}
/**
* A wrapper around getParameter, for when we don't want it to be silent.
*/
static public String getParameter(String input) {
return getParameter(input, false);
}
public static File inputPathToChrootedFile(File existingPrefix, String param) {
try {
if (param.charAt(0) == '/') {
// The STOR contained an absolute path | // Path: src/com/zlab/datFM/swiftp/Globals.java
// public class Globals {
// private static String lastError;
// private static File chrootDir = null;
// private static String username = null;
//
// public static File getChrootDir() {
// return chrootDir;
// }
//
// public static void setChrootDir(File chrootDir) {
// if (chrootDir.isDirectory()) {
// Globals.chrootDir = chrootDir;
// }
// }
//
// public static String getLastError() {
// return lastError;
// }
//
// public static void setLastError(String lastError) {
// Globals.lastError = lastError;
// }
//
// public static String getUsername() {
// return username;
// }
//
// public static void setUsername(String username) {
// Globals.username = username;
// }
//
// }
// Path: src/com/zlab/datFM/swiftp/server/FtpCmd.java
import android.util.Log;
import com.zlab.datFM.swiftp.Globals;
import java.io.File;
import java.lang.reflect.Constructor;
if (input == null) {
return "";
}
int firstSpacePosition = input.indexOf(' ');
if (firstSpacePosition == -1) {
return "";
}
String retString = input.substring(firstSpacePosition + 1);
// Remove trailing whitespace
// todo: trailing whitespace may be significant, just remove \r\n
retString = retString.replaceAll("\\s+$", "");
if (!silent) {
Log.d(TAG, "Parsed argument: " + retString);
}
return retString;
}
/**
* A wrapper around getParameter, for when we don't want it to be silent.
*/
static public String getParameter(String input) {
return getParameter(input, false);
}
public static File inputPathToChrootedFile(File existingPrefix, String param) {
try {
if (param.charAt(0) == '/') {
// The STOR contained an absolute path | File chroot = Globals.getChrootDir(); |
ZorgeR/datFM | src/com/zlab/datFM/swiftp/server/CmdPWD.java | // Path: src/com/zlab/datFM/swiftp/Globals.java
// public class Globals {
// private static String lastError;
// private static File chrootDir = null;
// private static String username = null;
//
// public static File getChrootDir() {
// return chrootDir;
// }
//
// public static void setChrootDir(File chrootDir) {
// if (chrootDir.isDirectory()) {
// Globals.chrootDir = chrootDir;
// }
// }
//
// public static String getLastError() {
// return lastError;
// }
//
// public static void setLastError(String lastError) {
// Globals.lastError = lastError;
// }
//
// public static String getUsername() {
// return username;
// }
//
// public static void setUsername(String username) {
// Globals.username = username;
// }
//
// }
| import com.zlab.datFM.swiftp.Globals;
import java.io.IOException;
import android.util.Log; | /*
Copyright 2009 David Revell
This file is part of SwiFTP.
SwiFTP 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.
SwiFTP 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 SwiFTP. If not, see <http://www.gnu.org/licenses/>.
*/
package com.zlab.datFM.swiftp.server;
public class CmdPWD extends FtpCmd implements Runnable {
private static final String TAG = CmdPWD.class.getSimpleName();
public CmdPWD(SessionThread sessionThread, String input) {
super(sessionThread);
}
@Override
public void run() {
Log.d(TAG, "PWD executing");
// We assume that the chroot restriction has been applied, and that
// therefore the current directory is located somewhere within the
// chroot directory. Therefore, we can just slice of the chroot
// part of the current directory path in order to get the
// user-visible path (inside the chroot directory).
try {
String currentDir = sessionThread.getWorkingDir().getCanonicalPath(); | // Path: src/com/zlab/datFM/swiftp/Globals.java
// public class Globals {
// private static String lastError;
// private static File chrootDir = null;
// private static String username = null;
//
// public static File getChrootDir() {
// return chrootDir;
// }
//
// public static void setChrootDir(File chrootDir) {
// if (chrootDir.isDirectory()) {
// Globals.chrootDir = chrootDir;
// }
// }
//
// public static String getLastError() {
// return lastError;
// }
//
// public static void setLastError(String lastError) {
// Globals.lastError = lastError;
// }
//
// public static String getUsername() {
// return username;
// }
//
// public static void setUsername(String username) {
// Globals.username = username;
// }
//
// }
// Path: src/com/zlab/datFM/swiftp/server/CmdPWD.java
import com.zlab.datFM.swiftp.Globals;
import java.io.IOException;
import android.util.Log;
/*
Copyright 2009 David Revell
This file is part of SwiFTP.
SwiFTP 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.
SwiFTP 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 SwiFTP. If not, see <http://www.gnu.org/licenses/>.
*/
package com.zlab.datFM.swiftp.server;
public class CmdPWD extends FtpCmd implements Runnable {
private static final String TAG = CmdPWD.class.getSimpleName();
public CmdPWD(SessionThread sessionThread, String input) {
super(sessionThread);
}
@Override
public void run() {
Log.d(TAG, "PWD executing");
// We assume that the chroot restriction has been applied, and that
// therefore the current directory is located somewhere within the
// chroot directory. Therefore, we can just slice of the chroot
// part of the current directory path in order to get the
// user-visible path (inside the chroot directory).
try {
String currentDir = sessionThread.getWorkingDir().getCanonicalPath(); | currentDir = currentDir.substring(Globals.getChrootDir().getCanonicalPath() |
ZorgeR/datFM | src/com/zlab/datFM/swiftp/server/CmdDELE.java | // Path: src/com/zlab/datFM/swiftp/MediaUpdater.java
// public enum MediaUpdater {
// INSTANCE;
//
// private final static String TAG = MediaUpdater.class.getSimpleName();
//
// // the systembroadcast to remount the media is only done after a little while (5s)
// private static Timer sTimer = new Timer();
//
// public static void notifyFileCreated(String path) {
// if (Defaults.do_mediascanner_notify) {
// Log.d(TAG, "Notifying others about new file: " + path);
// Context context = FtpServerApp.getAppContext();
// MediaScannerConnection.scanFile(context, new String[]{path}, null,
// new MediaScannerConnection.OnScanCompletedListener() {
// @Override
// public void onScanCompleted(String path, Uri uri) {
// }
// });
// }
// }
//
// public static void notifyFileDeleted(String path) {
// // The media mounted broadcast is very taxing on the system, so we only do this
// // if for 5 seconds there was no same request, otherwise we wait again.
// if (Defaults.do_mediascanner_notify) {
// Log.d(TAG, "Notifying others about deleted file: " + path);
// // the systembroadcast might have been requested already, cancel if so
// sTimer.cancel();
// // that timer is of no value any more, create a new one
// sTimer = new Timer();
// // and in 5s let it send the broadcast, might never hapen if before
// // that time it gets canceled by this code path
// sTimer.schedule(new TimerTask() {
// @Override
// public void run() {
// Log.d(TAG, "Sending ACTION_MEDIA_MOUNTED broadcast");
// final Context context = FtpServerApp.getAppContext();
// context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri
// .parse("file://" + Environment.getExternalStorageDirectory())));
// }
// }, 5000);
// }
// }
//
// }
| import com.zlab.datFM.swiftp.MediaUpdater;
import java.io.File;
import android.util.Log; | /*
Copyright 2009 David Revell
This file is part of SwiFTP.
SwiFTP 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.
SwiFTP 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 SwiFTP. If not, see <http://www.gnu.org/licenses/>.
*/
package com.zlab.datFM.swiftp.server;
public class CmdDELE extends FtpCmd implements Runnable {
private static final String TAG = CmdDELE.class.getSimpleName();
protected String input;
public CmdDELE(SessionThread sessionThread, String input) {
super(sessionThread);
this.input = input;
}
@Override
public void run() {
Log.d(TAG, "DELE executing");
String param = getParameter(input);
File storeFile = inputPathToChrootedFile(sessionThread.getWorkingDir(), param);
String errString = null;
if (violatesChroot(storeFile)) {
errString = "550 Invalid name or chroot violation\r\n";
} else if (storeFile.isDirectory()) {
errString = "550 Can't DELE a directory\r\n";
} else if (!storeFile.delete()) {
errString = "450 Error deleting file\r\n";
}
if (errString != null) {
sessionThread.writeString(errString);
Log.i(TAG, "DELE failed: " + errString.trim());
} else {
sessionThread.writeString("250 File successfully deleted\r\n"); | // Path: src/com/zlab/datFM/swiftp/MediaUpdater.java
// public enum MediaUpdater {
// INSTANCE;
//
// private final static String TAG = MediaUpdater.class.getSimpleName();
//
// // the systembroadcast to remount the media is only done after a little while (5s)
// private static Timer sTimer = new Timer();
//
// public static void notifyFileCreated(String path) {
// if (Defaults.do_mediascanner_notify) {
// Log.d(TAG, "Notifying others about new file: " + path);
// Context context = FtpServerApp.getAppContext();
// MediaScannerConnection.scanFile(context, new String[]{path}, null,
// new MediaScannerConnection.OnScanCompletedListener() {
// @Override
// public void onScanCompleted(String path, Uri uri) {
// }
// });
// }
// }
//
// public static void notifyFileDeleted(String path) {
// // The media mounted broadcast is very taxing on the system, so we only do this
// // if for 5 seconds there was no same request, otherwise we wait again.
// if (Defaults.do_mediascanner_notify) {
// Log.d(TAG, "Notifying others about deleted file: " + path);
// // the systembroadcast might have been requested already, cancel if so
// sTimer.cancel();
// // that timer is of no value any more, create a new one
// sTimer = new Timer();
// // and in 5s let it send the broadcast, might never hapen if before
// // that time it gets canceled by this code path
// sTimer.schedule(new TimerTask() {
// @Override
// public void run() {
// Log.d(TAG, "Sending ACTION_MEDIA_MOUNTED broadcast");
// final Context context = FtpServerApp.getAppContext();
// context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri
// .parse("file://" + Environment.getExternalStorageDirectory())));
// }
// }, 5000);
// }
// }
//
// }
// Path: src/com/zlab/datFM/swiftp/server/CmdDELE.java
import com.zlab.datFM.swiftp.MediaUpdater;
import java.io.File;
import android.util.Log;
/*
Copyright 2009 David Revell
This file is part of SwiFTP.
SwiFTP 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.
SwiFTP 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 SwiFTP. If not, see <http://www.gnu.org/licenses/>.
*/
package com.zlab.datFM.swiftp.server;
public class CmdDELE extends FtpCmd implements Runnable {
private static final String TAG = CmdDELE.class.getSimpleName();
protected String input;
public CmdDELE(SessionThread sessionThread, String input) {
super(sessionThread);
this.input = input;
}
@Override
public void run() {
Log.d(TAG, "DELE executing");
String param = getParameter(input);
File storeFile = inputPathToChrootedFile(sessionThread.getWorkingDir(), param);
String errString = null;
if (violatesChroot(storeFile)) {
errString = "550 Invalid name or chroot violation\r\n";
} else if (storeFile.isDirectory()) {
errString = "550 Can't DELE a directory\r\n";
} else if (!storeFile.delete()) {
errString = "450 Error deleting file\r\n";
}
if (errString != null) {
sessionThread.writeString(errString);
Log.i(TAG, "DELE failed: " + errString.trim());
} else {
sessionThread.writeString("250 File successfully deleted\r\n"); | MediaUpdater.notifyFileDeleted(storeFile.getPath()); |
UnitedID/YubiHSM-java-api | src/test/java/org/unitedid/yhsm/utility/UtilsTest.java | // Path: src/main/java/org/unitedid/yhsm/internal/YubiHSMInputException.java
// public class YubiHSMInputException extends Exception {
// public YubiHSMInputException() {}
//
// public YubiHSMInputException(String message) {
// super(message);
// }
//
// public YubiHSMInputException(Throwable cause) {
// super(cause);
// }
//
// public YubiHSMInputException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/org/unitedid/yhsm/internal/Defines.java
// final static public int YSM_AEAD_NONCE_SIZE = 6;
| import org.testng.annotations.Test;
import org.unitedid.yhsm.internal.YubiHSMInputException;
import static org.testng.Assert.assertEquals;
import static org.unitedid.yhsm.internal.Defines.YSM_AEAD_NONCE_SIZE; | assertEquals(Utils.leIntToBA(8192), expected);
}
@Test
public void testRangeOfByteArray() throws Exception {
byte[] data = "ekoeko".getBytes();
byte[] expected = {0x6b, 0x6f};
assertEquals(Utils.rangeOfByteArray(data, 1, 2), expected);
}
@Test
public void testByteArrayToHexString() throws Exception {
byte[] data = "ekoeko".getBytes();
String expected = "656b6f656b6f";
assertEquals(Utils.byteArrayToHex(data), expected);
}
@Test
public void testHexToByteArray() throws Exception {
String data = "656b6f656b6f";
byte[] expected = {0x65,0x6b,0x6f,0x65,0x6b,0x6f};
assertEquals(Utils.hexToByteArray(data), expected);
}
@Test
public void testValidateNonce() throws Exception {
String data = "12"; | // Path: src/main/java/org/unitedid/yhsm/internal/YubiHSMInputException.java
// public class YubiHSMInputException extends Exception {
// public YubiHSMInputException() {}
//
// public YubiHSMInputException(String message) {
// super(message);
// }
//
// public YubiHSMInputException(Throwable cause) {
// super(cause);
// }
//
// public YubiHSMInputException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/org/unitedid/yhsm/internal/Defines.java
// final static public int YSM_AEAD_NONCE_SIZE = 6;
// Path: src/test/java/org/unitedid/yhsm/utility/UtilsTest.java
import org.testng.annotations.Test;
import org.unitedid.yhsm.internal.YubiHSMInputException;
import static org.testng.Assert.assertEquals;
import static org.unitedid.yhsm.internal.Defines.YSM_AEAD_NONCE_SIZE;
assertEquals(Utils.leIntToBA(8192), expected);
}
@Test
public void testRangeOfByteArray() throws Exception {
byte[] data = "ekoeko".getBytes();
byte[] expected = {0x6b, 0x6f};
assertEquals(Utils.rangeOfByteArray(data, 1, 2), expected);
}
@Test
public void testByteArrayToHexString() throws Exception {
byte[] data = "ekoeko".getBytes();
String expected = "656b6f656b6f";
assertEquals(Utils.byteArrayToHex(data), expected);
}
@Test
public void testHexToByteArray() throws Exception {
String data = "656b6f656b6f";
byte[] expected = {0x65,0x6b,0x6f,0x65,0x6b,0x6f};
assertEquals(Utils.hexToByteArray(data), expected);
}
@Test
public void testValidateNonce() throws Exception {
String data = "12"; | assertEquals(Utils.validateNonce(data.getBytes(), true).length, YSM_AEAD_NONCE_SIZE); |
UnitedID/YubiHSM-java-api | src/test/java/org/unitedid/yhsm/utility/UtilsTest.java | // Path: src/main/java/org/unitedid/yhsm/internal/YubiHSMInputException.java
// public class YubiHSMInputException extends Exception {
// public YubiHSMInputException() {}
//
// public YubiHSMInputException(String message) {
// super(message);
// }
//
// public YubiHSMInputException(Throwable cause) {
// super(cause);
// }
//
// public YubiHSMInputException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/org/unitedid/yhsm/internal/Defines.java
// final static public int YSM_AEAD_NONCE_SIZE = 6;
| import org.testng.annotations.Test;
import org.unitedid.yhsm.internal.YubiHSMInputException;
import static org.testng.Assert.assertEquals;
import static org.unitedid.yhsm.internal.Defines.YSM_AEAD_NONCE_SIZE; | byte[] data = "ekoeko".getBytes();
byte[] expected = {0x6b, 0x6f};
assertEquals(Utils.rangeOfByteArray(data, 1, 2), expected);
}
@Test
public void testByteArrayToHexString() throws Exception {
byte[] data = "ekoeko".getBytes();
String expected = "656b6f656b6f";
assertEquals(Utils.byteArrayToHex(data), expected);
}
@Test
public void testHexToByteArray() throws Exception {
String data = "656b6f656b6f";
byte[] expected = {0x65,0x6b,0x6f,0x65,0x6b,0x6f};
assertEquals(Utils.hexToByteArray(data), expected);
}
@Test
public void testValidateNonce() throws Exception {
String data = "12";
assertEquals(Utils.validateNonce(data.getBytes(), true).length, YSM_AEAD_NONCE_SIZE);
assertEquals(Utils.validateNonce(data.getBytes(), false).length, 2);
}
| // Path: src/main/java/org/unitedid/yhsm/internal/YubiHSMInputException.java
// public class YubiHSMInputException extends Exception {
// public YubiHSMInputException() {}
//
// public YubiHSMInputException(String message) {
// super(message);
// }
//
// public YubiHSMInputException(Throwable cause) {
// super(cause);
// }
//
// public YubiHSMInputException(String message, Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/org/unitedid/yhsm/internal/Defines.java
// final static public int YSM_AEAD_NONCE_SIZE = 6;
// Path: src/test/java/org/unitedid/yhsm/utility/UtilsTest.java
import org.testng.annotations.Test;
import org.unitedid.yhsm.internal.YubiHSMInputException;
import static org.testng.Assert.assertEquals;
import static org.unitedid.yhsm.internal.Defines.YSM_AEAD_NONCE_SIZE;
byte[] data = "ekoeko".getBytes();
byte[] expected = {0x6b, 0x6f};
assertEquals(Utils.rangeOfByteArray(data, 1, 2), expected);
}
@Test
public void testByteArrayToHexString() throws Exception {
byte[] data = "ekoeko".getBytes();
String expected = "656b6f656b6f";
assertEquals(Utils.byteArrayToHex(data), expected);
}
@Test
public void testHexToByteArray() throws Exception {
String data = "656b6f656b6f";
byte[] expected = {0x65,0x6b,0x6f,0x65,0x6b,0x6f};
assertEquals(Utils.hexToByteArray(data), expected);
}
@Test
public void testValidateNonce() throws Exception {
String data = "12";
assertEquals(Utils.validateNonce(data.getBytes(), true).length, YSM_AEAD_NONCE_SIZE);
assertEquals(Utils.validateNonce(data.getBytes(), false).length, 2);
}
| @Test(expectedExceptions = YubiHSMInputException.class, |
UnitedID/YubiHSM-java-api | src/test/java/org/unitedid/yhsm/internal/BufferCmdTest.java | // Path: src/test/java/org/unitedid/yhsm/SetupCommon.java
// public class SetupCommon {
// public YubiHSM hsm;
// public DeviceHandler deviceHandler;
// public int keyHandle = 8192;
// public final String configPassPhrase = "";
// public final String hsmPassPhrase = "badabada";
// public final String adminYubikey = "ftftftfteeee";
//
//
// @BeforeTest
// public void setUp() throws Exception {
// String deviceName = "/dev/ttyACM0";
// if (System.getProperty("hsm.test.deviceName") != null) {
// deviceName = System.getProperty("hsm.test.deviceName");
// }
// hsm = new YubiHSM(deviceName);
// deviceHandler = hsm.getRawDevice();
// }
//
// @AfterTest
// public void tearDown() throws Exception {
// hsm = null;
// deviceHandler = null;
// }
//
// }
//
// Path: src/main/java/org/unitedid/yhsm/internal/Defines.java
// final static public int YSM_DATA_BUF_SIZE = 64;
| import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.unitedid.yhsm.SetupCommon;
import java.util.Map;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotSame;
import static org.unitedid.yhsm.internal.Defines.YSM_DATA_BUF_SIZE; | /*
* Copyright (c) 2011 - 2013 United ID.
*
* 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.unitedid.yhsm.internal;
public class BufferCmdTest extends SetupCommon {
@BeforeTest
public void setUp() throws Exception {
super.setUp();
}
@AfterTest
public void tearDown() throws Exception {
super.tearDown();
}
@Test
public void testLoadData() throws YubiHSMErrorException {
assertEquals(BufferCmd.loadData(deviceHandler, "12345", 0), 5);
assertEquals(BufferCmd.loadData(deviceHandler, "12", 5), 7);
assertEquals(BufferCmd.loadData(deviceHandler, "12", 0), 2);
}
@Test
public void testRandom() throws YubiHSMCommandFailedException, YubiHSMErrorException, YubiHSMInputException {
String nonce = "112233445566";
hsm.loadRandomBufferData(20, 0);
Map aead1 = hsm.generateBufferAEAD(nonce, keyHandle);
hsm.loadRandomBufferData(20, 0);
Map aead2 = hsm.generateBufferAEAD(nonce, keyHandle);
assertNotSame(aead1, aead2);
}
@Test
public void testWouldOverflowBuffer() throws YubiHSMErrorException { | // Path: src/test/java/org/unitedid/yhsm/SetupCommon.java
// public class SetupCommon {
// public YubiHSM hsm;
// public DeviceHandler deviceHandler;
// public int keyHandle = 8192;
// public final String configPassPhrase = "";
// public final String hsmPassPhrase = "badabada";
// public final String adminYubikey = "ftftftfteeee";
//
//
// @BeforeTest
// public void setUp() throws Exception {
// String deviceName = "/dev/ttyACM0";
// if (System.getProperty("hsm.test.deviceName") != null) {
// deviceName = System.getProperty("hsm.test.deviceName");
// }
// hsm = new YubiHSM(deviceName);
// deviceHandler = hsm.getRawDevice();
// }
//
// @AfterTest
// public void tearDown() throws Exception {
// hsm = null;
// deviceHandler = null;
// }
//
// }
//
// Path: src/main/java/org/unitedid/yhsm/internal/Defines.java
// final static public int YSM_DATA_BUF_SIZE = 64;
// Path: src/test/java/org/unitedid/yhsm/internal/BufferCmdTest.java
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.unitedid.yhsm.SetupCommon;
import java.util.Map;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotSame;
import static org.unitedid.yhsm.internal.Defines.YSM_DATA_BUF_SIZE;
/*
* Copyright (c) 2011 - 2013 United ID.
*
* 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.unitedid.yhsm.internal;
public class BufferCmdTest extends SetupCommon {
@BeforeTest
public void setUp() throws Exception {
super.setUp();
}
@AfterTest
public void tearDown() throws Exception {
super.tearDown();
}
@Test
public void testLoadData() throws YubiHSMErrorException {
assertEquals(BufferCmd.loadData(deviceHandler, "12345", 0), 5);
assertEquals(BufferCmd.loadData(deviceHandler, "12", 5), 7);
assertEquals(BufferCmd.loadData(deviceHandler, "12", 0), 2);
}
@Test
public void testRandom() throws YubiHSMCommandFailedException, YubiHSMErrorException, YubiHSMInputException {
String nonce = "112233445566";
hsm.loadRandomBufferData(20, 0);
Map aead1 = hsm.generateBufferAEAD(nonce, keyHandle);
hsm.loadRandomBufferData(20, 0);
Map aead2 = hsm.generateBufferAEAD(nonce, keyHandle);
assertNotSame(aead1, aead2);
}
@Test
public void testWouldOverflowBuffer() throws YubiHSMErrorException { | assertEquals(hsm.loadRandomBufferData(16, YSM_DATA_BUF_SIZE - 8), 64); |
UnitedID/YubiHSM-java-api | src/test/java/org/unitedid/yhsm/internal/HMACCmdTest.java | // Path: src/test/java/org/unitedid/yhsm/SetupCommon.java
// public class SetupCommon {
// public YubiHSM hsm;
// public DeviceHandler deviceHandler;
// public int keyHandle = 8192;
// public final String configPassPhrase = "";
// public final String hsmPassPhrase = "badabada";
// public final String adminYubikey = "ftftftfteeee";
//
//
// @BeforeTest
// public void setUp() throws Exception {
// String deviceName = "/dev/ttyACM0";
// if (System.getProperty("hsm.test.deviceName") != null) {
// deviceName = System.getProperty("hsm.test.deviceName");
// }
// hsm = new YubiHSM(deviceName);
// deviceHandler = hsm.getRawDevice();
// }
//
// @AfterTest
// public void tearDown() throws Exception {
// hsm = null;
// deviceHandler = null;
// }
//
// }
//
// Path: src/main/java/org/unitedid/yhsm/internal/Defines.java
// final static public byte YSM_HMAC_SHA1_FINAL = 0x02;
//
// Path: src/main/java/org/unitedid/yhsm/internal/Defines.java
// final static public byte YSM_HMAC_SHA1_RESET = 0x01;
//
// Path: src/main/java/org/unitedid/yhsm/internal/Defines.java
// final static public int YSM_SHA1_HASH_SIZE = 20;
| import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.unitedid.yhsm.SetupCommon;
import java.util.Map;
import static org.testng.Assert.assertEquals;
import static org.unitedid.yhsm.internal.Defines.YSM_HMAC_SHA1_FINAL;
import static org.unitedid.yhsm.internal.Defines.YSM_HMAC_SHA1_RESET;
import static org.unitedid.yhsm.internal.Defines.YSM_SHA1_HASH_SIZE; | /*
* Copyright (c) 2011 - 2013 United ID.
*
* 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.unitedid.yhsm.internal;
public class HMACCmdTest extends SetupCommon {
private String data = "Sample #2";
private String expectedHash = "0922d3405faa3d194f82a45830737d5cc6c75d24";
private String expectedNextHash = "0000000000000000000000000000000000000000";
private int keyHandle = 12337;
@BeforeTest
public void setUp() throws Exception {
super.setUp();
}
@AfterTest
public void tearDown() throws Exception {
super.tearDown();
}
@Test
public void testHMACSHA1WithNumericFlags() throws Exception { | // Path: src/test/java/org/unitedid/yhsm/SetupCommon.java
// public class SetupCommon {
// public YubiHSM hsm;
// public DeviceHandler deviceHandler;
// public int keyHandle = 8192;
// public final String configPassPhrase = "";
// public final String hsmPassPhrase = "badabada";
// public final String adminYubikey = "ftftftfteeee";
//
//
// @BeforeTest
// public void setUp() throws Exception {
// String deviceName = "/dev/ttyACM0";
// if (System.getProperty("hsm.test.deviceName") != null) {
// deviceName = System.getProperty("hsm.test.deviceName");
// }
// hsm = new YubiHSM(deviceName);
// deviceHandler = hsm.getRawDevice();
// }
//
// @AfterTest
// public void tearDown() throws Exception {
// hsm = null;
// deviceHandler = null;
// }
//
// }
//
// Path: src/main/java/org/unitedid/yhsm/internal/Defines.java
// final static public byte YSM_HMAC_SHA1_FINAL = 0x02;
//
// Path: src/main/java/org/unitedid/yhsm/internal/Defines.java
// final static public byte YSM_HMAC_SHA1_RESET = 0x01;
//
// Path: src/main/java/org/unitedid/yhsm/internal/Defines.java
// final static public int YSM_SHA1_HASH_SIZE = 20;
// Path: src/test/java/org/unitedid/yhsm/internal/HMACCmdTest.java
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.unitedid.yhsm.SetupCommon;
import java.util.Map;
import static org.testng.Assert.assertEquals;
import static org.unitedid.yhsm.internal.Defines.YSM_HMAC_SHA1_FINAL;
import static org.unitedid.yhsm.internal.Defines.YSM_HMAC_SHA1_RESET;
import static org.unitedid.yhsm.internal.Defines.YSM_SHA1_HASH_SIZE;
/*
* Copyright (c) 2011 - 2013 United ID.
*
* 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.unitedid.yhsm.internal;
public class HMACCmdTest extends SetupCommon {
private String data = "Sample #2";
private String expectedHash = "0922d3405faa3d194f82a45830737d5cc6c75d24";
private String expectedNextHash = "0000000000000000000000000000000000000000";
private int keyHandle = 12337;
@BeforeTest
public void setUp() throws Exception {
super.setUp();
}
@AfterTest
public void tearDown() throws Exception {
super.tearDown();
}
@Test
public void testHMACSHA1WithNumericFlags() throws Exception { | byte flags = YSM_HMAC_SHA1_RESET | YSM_HMAC_SHA1_FINAL; |
UnitedID/YubiHSM-java-api | src/test/java/org/unitedid/yhsm/internal/HMACCmdTest.java | // Path: src/test/java/org/unitedid/yhsm/SetupCommon.java
// public class SetupCommon {
// public YubiHSM hsm;
// public DeviceHandler deviceHandler;
// public int keyHandle = 8192;
// public final String configPassPhrase = "";
// public final String hsmPassPhrase = "badabada";
// public final String adminYubikey = "ftftftfteeee";
//
//
// @BeforeTest
// public void setUp() throws Exception {
// String deviceName = "/dev/ttyACM0";
// if (System.getProperty("hsm.test.deviceName") != null) {
// deviceName = System.getProperty("hsm.test.deviceName");
// }
// hsm = new YubiHSM(deviceName);
// deviceHandler = hsm.getRawDevice();
// }
//
// @AfterTest
// public void tearDown() throws Exception {
// hsm = null;
// deviceHandler = null;
// }
//
// }
//
// Path: src/main/java/org/unitedid/yhsm/internal/Defines.java
// final static public byte YSM_HMAC_SHA1_FINAL = 0x02;
//
// Path: src/main/java/org/unitedid/yhsm/internal/Defines.java
// final static public byte YSM_HMAC_SHA1_RESET = 0x01;
//
// Path: src/main/java/org/unitedid/yhsm/internal/Defines.java
// final static public int YSM_SHA1_HASH_SIZE = 20;
| import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.unitedid.yhsm.SetupCommon;
import java.util.Map;
import static org.testng.Assert.assertEquals;
import static org.unitedid.yhsm.internal.Defines.YSM_HMAC_SHA1_FINAL;
import static org.unitedid.yhsm.internal.Defines.YSM_HMAC_SHA1_RESET;
import static org.unitedid.yhsm.internal.Defines.YSM_SHA1_HASH_SIZE; | /*
* Copyright (c) 2011 - 2013 United ID.
*
* 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.unitedid.yhsm.internal;
public class HMACCmdTest extends SetupCommon {
private String data = "Sample #2";
private String expectedHash = "0922d3405faa3d194f82a45830737d5cc6c75d24";
private String expectedNextHash = "0000000000000000000000000000000000000000";
private int keyHandle = 12337;
@BeforeTest
public void setUp() throws Exception {
super.setUp();
}
@AfterTest
public void tearDown() throws Exception {
super.tearDown();
}
@Test
public void testHMACSHA1WithNumericFlags() throws Exception { | // Path: src/test/java/org/unitedid/yhsm/SetupCommon.java
// public class SetupCommon {
// public YubiHSM hsm;
// public DeviceHandler deviceHandler;
// public int keyHandle = 8192;
// public final String configPassPhrase = "";
// public final String hsmPassPhrase = "badabada";
// public final String adminYubikey = "ftftftfteeee";
//
//
// @BeforeTest
// public void setUp() throws Exception {
// String deviceName = "/dev/ttyACM0";
// if (System.getProperty("hsm.test.deviceName") != null) {
// deviceName = System.getProperty("hsm.test.deviceName");
// }
// hsm = new YubiHSM(deviceName);
// deviceHandler = hsm.getRawDevice();
// }
//
// @AfterTest
// public void tearDown() throws Exception {
// hsm = null;
// deviceHandler = null;
// }
//
// }
//
// Path: src/main/java/org/unitedid/yhsm/internal/Defines.java
// final static public byte YSM_HMAC_SHA1_FINAL = 0x02;
//
// Path: src/main/java/org/unitedid/yhsm/internal/Defines.java
// final static public byte YSM_HMAC_SHA1_RESET = 0x01;
//
// Path: src/main/java/org/unitedid/yhsm/internal/Defines.java
// final static public int YSM_SHA1_HASH_SIZE = 20;
// Path: src/test/java/org/unitedid/yhsm/internal/HMACCmdTest.java
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.unitedid.yhsm.SetupCommon;
import java.util.Map;
import static org.testng.Assert.assertEquals;
import static org.unitedid.yhsm.internal.Defines.YSM_HMAC_SHA1_FINAL;
import static org.unitedid.yhsm.internal.Defines.YSM_HMAC_SHA1_RESET;
import static org.unitedid.yhsm.internal.Defines.YSM_SHA1_HASH_SIZE;
/*
* Copyright (c) 2011 - 2013 United ID.
*
* 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.unitedid.yhsm.internal;
public class HMACCmdTest extends SetupCommon {
private String data = "Sample #2";
private String expectedHash = "0922d3405faa3d194f82a45830737d5cc6c75d24";
private String expectedNextHash = "0000000000000000000000000000000000000000";
private int keyHandle = 12337;
@BeforeTest
public void setUp() throws Exception {
super.setUp();
}
@AfterTest
public void tearDown() throws Exception {
super.tearDown();
}
@Test
public void testHMACSHA1WithNumericFlags() throws Exception { | byte flags = YSM_HMAC_SHA1_RESET | YSM_HMAC_SHA1_FINAL; |
UnitedID/YubiHSM-java-api | src/test/java/org/unitedid/yhsm/internal/HMACCmdTest.java | // Path: src/test/java/org/unitedid/yhsm/SetupCommon.java
// public class SetupCommon {
// public YubiHSM hsm;
// public DeviceHandler deviceHandler;
// public int keyHandle = 8192;
// public final String configPassPhrase = "";
// public final String hsmPassPhrase = "badabada";
// public final String adminYubikey = "ftftftfteeee";
//
//
// @BeforeTest
// public void setUp() throws Exception {
// String deviceName = "/dev/ttyACM0";
// if (System.getProperty("hsm.test.deviceName") != null) {
// deviceName = System.getProperty("hsm.test.deviceName");
// }
// hsm = new YubiHSM(deviceName);
// deviceHandler = hsm.getRawDevice();
// }
//
// @AfterTest
// public void tearDown() throws Exception {
// hsm = null;
// deviceHandler = null;
// }
//
// }
//
// Path: src/main/java/org/unitedid/yhsm/internal/Defines.java
// final static public byte YSM_HMAC_SHA1_FINAL = 0x02;
//
// Path: src/main/java/org/unitedid/yhsm/internal/Defines.java
// final static public byte YSM_HMAC_SHA1_RESET = 0x01;
//
// Path: src/main/java/org/unitedid/yhsm/internal/Defines.java
// final static public int YSM_SHA1_HASH_SIZE = 20;
| import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.unitedid.yhsm.SetupCommon;
import java.util.Map;
import static org.testng.Assert.assertEquals;
import static org.unitedid.yhsm.internal.Defines.YSM_HMAC_SHA1_FINAL;
import static org.unitedid.yhsm.internal.Defines.YSM_HMAC_SHA1_RESET;
import static org.unitedid.yhsm.internal.Defines.YSM_SHA1_HASH_SIZE; |
@Test
public void testHMACSHA1NextNext() throws Exception {
Map<String, String> result = hsm.generateHMACSHA1("", keyHandle, false, false);
assertEquals(result.get("hash"), expectedNextHash);
result = hsm.generateHMACSHA1Next(data.substring(0, 3), keyHandle, false, false);
assertEquals(result.get("hash"), expectedNextHash);
result = hsm.generateHMACSHA1Next(data.substring(3), keyHandle, true, false);
assertEquals(result.get("hash"), expectedHash);
}
@Test
public void testHMACSHA1Interupted() throws Exception {
Map<String, String> result = hsm.generateHMACSHA1(data.substring(0, 3), keyHandle, false, false);
assertEquals(result.get("hash"), expectedNextHash);
assertEquals(hsm.echo("123qwe"), "123qwe");
result = hsm.generateHMACSHA1Next(data.substring(3), keyHandle, true, false);
assertEquals(result.get("hash"), expectedHash);
}
@Test(expectedExceptions = YubiHSMCommandFailedException.class,
expectedExceptionsMessageRegExp = "Command YSM_HMAC_SHA1_GENERATE failed: YSM_FUNCTION_DISABLED")
public void testHMACSHA1InvalidKeyHandle() throws Exception {
hsm.generateHMACSHA1(data, 1, true, false);
}
@Test
public void testHMACSHA1ToBuffer() throws Exception {
assertEquals(hsm.loadRandomBufferData(0, 0), 0);
hsm.generateHMACSHA1(data, keyHandle, true, true); | // Path: src/test/java/org/unitedid/yhsm/SetupCommon.java
// public class SetupCommon {
// public YubiHSM hsm;
// public DeviceHandler deviceHandler;
// public int keyHandle = 8192;
// public final String configPassPhrase = "";
// public final String hsmPassPhrase = "badabada";
// public final String adminYubikey = "ftftftfteeee";
//
//
// @BeforeTest
// public void setUp() throws Exception {
// String deviceName = "/dev/ttyACM0";
// if (System.getProperty("hsm.test.deviceName") != null) {
// deviceName = System.getProperty("hsm.test.deviceName");
// }
// hsm = new YubiHSM(deviceName);
// deviceHandler = hsm.getRawDevice();
// }
//
// @AfterTest
// public void tearDown() throws Exception {
// hsm = null;
// deviceHandler = null;
// }
//
// }
//
// Path: src/main/java/org/unitedid/yhsm/internal/Defines.java
// final static public byte YSM_HMAC_SHA1_FINAL = 0x02;
//
// Path: src/main/java/org/unitedid/yhsm/internal/Defines.java
// final static public byte YSM_HMAC_SHA1_RESET = 0x01;
//
// Path: src/main/java/org/unitedid/yhsm/internal/Defines.java
// final static public int YSM_SHA1_HASH_SIZE = 20;
// Path: src/test/java/org/unitedid/yhsm/internal/HMACCmdTest.java
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.unitedid.yhsm.SetupCommon;
import java.util.Map;
import static org.testng.Assert.assertEquals;
import static org.unitedid.yhsm.internal.Defines.YSM_HMAC_SHA1_FINAL;
import static org.unitedid.yhsm.internal.Defines.YSM_HMAC_SHA1_RESET;
import static org.unitedid.yhsm.internal.Defines.YSM_SHA1_HASH_SIZE;
@Test
public void testHMACSHA1NextNext() throws Exception {
Map<String, String> result = hsm.generateHMACSHA1("", keyHandle, false, false);
assertEquals(result.get("hash"), expectedNextHash);
result = hsm.generateHMACSHA1Next(data.substring(0, 3), keyHandle, false, false);
assertEquals(result.get("hash"), expectedNextHash);
result = hsm.generateHMACSHA1Next(data.substring(3), keyHandle, true, false);
assertEquals(result.get("hash"), expectedHash);
}
@Test
public void testHMACSHA1Interupted() throws Exception {
Map<String, String> result = hsm.generateHMACSHA1(data.substring(0, 3), keyHandle, false, false);
assertEquals(result.get("hash"), expectedNextHash);
assertEquals(hsm.echo("123qwe"), "123qwe");
result = hsm.generateHMACSHA1Next(data.substring(3), keyHandle, true, false);
assertEquals(result.get("hash"), expectedHash);
}
@Test(expectedExceptions = YubiHSMCommandFailedException.class,
expectedExceptionsMessageRegExp = "Command YSM_HMAC_SHA1_GENERATE failed: YSM_FUNCTION_DISABLED")
public void testHMACSHA1InvalidKeyHandle() throws Exception {
hsm.generateHMACSHA1(data, 1, true, false);
}
@Test
public void testHMACSHA1ToBuffer() throws Exception {
assertEquals(hsm.loadRandomBufferData(0, 0), 0);
hsm.generateHMACSHA1(data, keyHandle, true, true); | assertEquals(hsm.loadRandomBufferData(0, 1), YSM_SHA1_HASH_SIZE); |
UnitedID/YubiHSM-java-api | src/main/java/org/unitedid/yhsm/internal/DeviceHandler.java | // Path: src/main/java/org/unitedid/yhsm/utility/Utils.java
// public static byte[] concatAllArrays(byte[] data1, byte[]... remaining) {
// int bufLength = data1.length;
//
// for (byte[] arr : remaining) {
// if (arr.length == 0) {
// return data1;
// }
//
// bufLength += arr.length;
// }
//
// int offset = data1.length;
// byte[] buffer = Arrays.copyOf(data1, bufLength);
//
// for (byte[] arr : remaining) {
// System.arraycopy(arr, 0, buffer, offset, arr.length);
// offset += arr.length;
// }
//
// return buffer;
// }
| import jssc.SerialPort;
import jssc.SerialPortException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import static org.unitedid.yhsm.utility.Utils.concatAllArrays; |
public byte[] read(int readNumBytes) {
byte[] data = new byte[readNumBytes];
try {
data = device.readBytes(readNumBytes);
readBytes += data.length;
} catch (SerialPortException e) {
e.printStackTrace();
}
return data;
}
public int available() {
try {
return device.getInputBufferBytesCount();
} catch (SerialPortException e) {
e.printStackTrace();
}
return 0;
}
public boolean drain() {
byte[] buffer = new byte[0];
while(available() > 0) {
byte[] b = read(1);
if ((char)b[0] == '\r') {
log.info("Drained: {}", new String(buffer, 0, buffer.length)); //TODO: Do we really need to log this? If not the loop can be simplified.
buffer = new byte[0];
} else { | // Path: src/main/java/org/unitedid/yhsm/utility/Utils.java
// public static byte[] concatAllArrays(byte[] data1, byte[]... remaining) {
// int bufLength = data1.length;
//
// for (byte[] arr : remaining) {
// if (arr.length == 0) {
// return data1;
// }
//
// bufLength += arr.length;
// }
//
// int offset = data1.length;
// byte[] buffer = Arrays.copyOf(data1, bufLength);
//
// for (byte[] arr : remaining) {
// System.arraycopy(arr, 0, buffer, offset, arr.length);
// offset += arr.length;
// }
//
// return buffer;
// }
// Path: src/main/java/org/unitedid/yhsm/internal/DeviceHandler.java
import jssc.SerialPort;
import jssc.SerialPortException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import static org.unitedid.yhsm.utility.Utils.concatAllArrays;
public byte[] read(int readNumBytes) {
byte[] data = new byte[readNumBytes];
try {
data = device.readBytes(readNumBytes);
readBytes += data.length;
} catch (SerialPortException e) {
e.printStackTrace();
}
return data;
}
public int available() {
try {
return device.getInputBufferBytesCount();
} catch (SerialPortException e) {
e.printStackTrace();
}
return 0;
}
public boolean drain() {
byte[] buffer = new byte[0];
while(available() > 0) {
byte[] b = read(1);
if ((char)b[0] == '\r') {
log.info("Drained: {}", new String(buffer, 0, buffer.length)); //TODO: Do we really need to log this? If not the loop can be simplified.
buffer = new byte[0];
} else { | buffer = concatAllArrays(buffer, b); |
UnitedID/YubiHSM-java-api | src/test/java/org/unitedid/yhsm/internal/KeyStorageUnlockTest.java | // Path: src/test/java/org/unitedid/yhsm/SetupCommon.java
// public class SetupCommon {
// public YubiHSM hsm;
// public DeviceHandler deviceHandler;
// public int keyHandle = 8192;
// public final String configPassPhrase = "";
// public final String hsmPassPhrase = "badabada";
// public final String adminYubikey = "ftftftfteeee";
//
//
// @BeforeTest
// public void setUp() throws Exception {
// String deviceName = "/dev/ttyACM0";
// if (System.getProperty("hsm.test.deviceName") != null) {
// deviceName = System.getProperty("hsm.test.deviceName");
// }
// hsm = new YubiHSM(deviceName);
// deviceHandler = hsm.getRawDevice();
// }
//
// @AfterTest
// public void tearDown() throws Exception {
// hsm = null;
// deviceHandler = null;
// }
//
// }
//
// Path: src/main/java/org/unitedid/yhsm/utility/ModHex.java
// public class ModHex {
// private static final String HEX = "0123456789abcdef";
// private static final String MODHEX = "cbdefghijklnrtuv";
//
// /**
// * Encode a hex string as modHex
// *
// * @param input a hex string
// * @return modHex string
// */
// public static String encode(String input) {
// return replaceEach(input, HEX, MODHEX);
// }
//
// /**
// * Decode modHex as hex
// *
// * @param input a modHex string
// * @return hex string
// */
// public static String decode(String input) {
// return replaceEach(input, MODHEX, HEX);
// }
//
// /**
// * Decode a modHex string as a decimal number
// *
// * @param input a modHex string
// * @return long number
// */
// public static Long toDecimal(String input) {
// return Long.decode("#" + decode(input));
// }
//
// /**
// * Replace characters in a string
// *
// * @param input String to replace characters in
// * @param searchList String of characters to search for
// * @param replacementList String of characters to replace with
// * @return modified string
// */
// private static String replaceEach(String input, String searchList, String replacementList) {
// StringBuilder buf = new StringBuilder(input.length());
//
// for (int i = 0; i < input.length(); i++) {
// char ch = input.charAt(i);
// int index = searchList.indexOf(ch);
// if (index == -1) {
// throw new IllegalArgumentException(input + " is not properly encoded");
// } else if (index >= 0) {
// buf.append(replacementList.charAt(index));
// } else {
// buf.append(ch);
// }
// }
//
// return buf.toString();
// }
// }
| import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.unitedid.yhsm.SetupCommon;
import org.unitedid.yhsm.utility.ModHex;
import static org.testng.Assert.*; | /*
* Copyright (c) 2011 - 2013 United ID.
*
* 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.unitedid.yhsm.internal;
public class KeyStorageUnlockTest extends SetupCommon {
@BeforeTest
public void setUp() throws Exception {
super.setUp();
}
@AfterTest
public void tearDown() throws Exception {
super.tearDown();
}
@Test(priority = 1)
public void failedUnlockHsm() throws YubiHSMCommandFailedException, YubiHSMErrorException, YubiHSMInputException {
assertFalse(hsm.unlock("1111"));
}
@Test(priority = 2)
public void unlockHsm() throws Exception {
assertTrue(hsm.unlock(hsmPassPhrase));
}
@Test(priority = 3)
public void otpUnlockHsm() throws Exception {
/* order is crucial here, that's why these are not made into separate tests */ | // Path: src/test/java/org/unitedid/yhsm/SetupCommon.java
// public class SetupCommon {
// public YubiHSM hsm;
// public DeviceHandler deviceHandler;
// public int keyHandle = 8192;
// public final String configPassPhrase = "";
// public final String hsmPassPhrase = "badabada";
// public final String adminYubikey = "ftftftfteeee";
//
//
// @BeforeTest
// public void setUp() throws Exception {
// String deviceName = "/dev/ttyACM0";
// if (System.getProperty("hsm.test.deviceName") != null) {
// deviceName = System.getProperty("hsm.test.deviceName");
// }
// hsm = new YubiHSM(deviceName);
// deviceHandler = hsm.getRawDevice();
// }
//
// @AfterTest
// public void tearDown() throws Exception {
// hsm = null;
// deviceHandler = null;
// }
//
// }
//
// Path: src/main/java/org/unitedid/yhsm/utility/ModHex.java
// public class ModHex {
// private static final String HEX = "0123456789abcdef";
// private static final String MODHEX = "cbdefghijklnrtuv";
//
// /**
// * Encode a hex string as modHex
// *
// * @param input a hex string
// * @return modHex string
// */
// public static String encode(String input) {
// return replaceEach(input, HEX, MODHEX);
// }
//
// /**
// * Decode modHex as hex
// *
// * @param input a modHex string
// * @return hex string
// */
// public static String decode(String input) {
// return replaceEach(input, MODHEX, HEX);
// }
//
// /**
// * Decode a modHex string as a decimal number
// *
// * @param input a modHex string
// * @return long number
// */
// public static Long toDecimal(String input) {
// return Long.decode("#" + decode(input));
// }
//
// /**
// * Replace characters in a string
// *
// * @param input String to replace characters in
// * @param searchList String of characters to search for
// * @param replacementList String of characters to replace with
// * @return modified string
// */
// private static String replaceEach(String input, String searchList, String replacementList) {
// StringBuilder buf = new StringBuilder(input.length());
//
// for (int i = 0; i < input.length(); i++) {
// char ch = input.charAt(i);
// int index = searchList.indexOf(ch);
// if (index == -1) {
// throw new IllegalArgumentException(input + " is not properly encoded");
// } else if (index >= 0) {
// buf.append(replacementList.charAt(index));
// } else {
// buf.append(ch);
// }
// }
//
// return buf.toString();
// }
// }
// Path: src/test/java/org/unitedid/yhsm/internal/KeyStorageUnlockTest.java
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.unitedid.yhsm.SetupCommon;
import org.unitedid.yhsm.utility.ModHex;
import static org.testng.Assert.*;
/*
* Copyright (c) 2011 - 2013 United ID.
*
* 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.unitedid.yhsm.internal;
public class KeyStorageUnlockTest extends SetupCommon {
@BeforeTest
public void setUp() throws Exception {
super.setUp();
}
@AfterTest
public void tearDown() throws Exception {
super.tearDown();
}
@Test(priority = 1)
public void failedUnlockHsm() throws YubiHSMCommandFailedException, YubiHSMErrorException, YubiHSMInputException {
assertFalse(hsm.unlock("1111"));
}
@Test(priority = 2)
public void unlockHsm() throws Exception {
assertTrue(hsm.unlock(hsmPassPhrase));
}
@Test(priority = 3)
public void otpUnlockHsm() throws Exception {
/* order is crucial here, that's why these are not made into separate tests */ | String yubiKeyPublicId = ModHex.decode(adminYubikey); |
UnitedID/YubiHSM-java-api | src/test/java/org/unitedid/yhsm/SetupCommon.java | // Path: src/main/java/org/unitedid/yhsm/internal/DeviceHandler.java
// public class DeviceHandler {
// /** Logger */
// private final Logger log = LoggerFactory.getLogger(DeviceHandler.class);
//
// /** The YubiHSM device */
// private SerialPort device;
//
// private int readBytes = 0;
// private int writtenBytes = 0;
//
// private float timeout = 0.5f;
//
// /**
// * Constructor
// *
// * @param deviceName the YubiHSM device name
// */
// DeviceHandler(String deviceName) throws YubiHSMErrorException {
// device = new SerialPort(deviceName);
// try {
// device.openPort();
// device.setParams(
// SerialPort.BAUDRATE_115200,
// SerialPort.DATABITS_8,
// SerialPort.STOPBITS_1,
// SerialPort.PARITY_NONE
// );
// device.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
// } catch (SerialPortException e) {
// throw new YubiHSMErrorException("Failed to open device " + deviceName, e);
// }
// }
//
// public void write(byte[] data) {
// try {
// writtenBytes += data.length;
// device.writeBytes(data);
// } catch (SerialPortException e) {
// e.printStackTrace();
// }
// }
//
// public byte[] read(int readNumBytes) {
// byte[] data = new byte[readNumBytes];
// try {
// data = device.readBytes(readNumBytes);
// readBytes += data.length;
// } catch (SerialPortException e) {
// e.printStackTrace();
// }
//
// return data;
// }
//
// public int available() {
// try {
// return device.getInputBufferBytesCount();
// } catch (SerialPortException e) {
// e.printStackTrace();
// }
// return 0;
// }
//
// public boolean drain() {
// byte[] buffer = new byte[0];
// while(available() > 0) {
// byte[] b = read(1);
// if ((char)b[0] == '\r') {
// log.info("Drained: {}", new String(buffer, 0, buffer.length)); //TODO: Do we really need to log this? If not the loop can be simplified.
// buffer = new byte[0];
// } else {
// buffer = concatAllArrays(buffer, b);
// }
// }
// return true;
// }
//
// public void flush() throws IOException {
// try {
// device.purgePort(SerialPort.PURGE_RXCLEAR | SerialPort.PURGE_TXCLEAR);
// } catch (SerialPortException e) {
// e.printStackTrace();
// }
// }
//
// public float getTimeout() {
// return timeout;
// }
//
// public void setTimeout(float timeout) {
// this.timeout = timeout;
// }
//
// public int getReadBytes() {
// return readBytes;
// }
//
// public int getWrittenBytes() {
// return writtenBytes;
// }
//
// public String getPortName() {
// return device.getPortName();
// }
//
// public Object clone() throws CloneNotSupportedException
// {
// throw new CloneNotSupportedException();
// }
//
// protected void finalize() throws Throwable {
// try {
// device.closePort();
// } finally {
// super.finalize();
// }
// }
// }
| import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.unitedid.yhsm.internal.DeviceHandler; | /*
* Copyright (c) 2011 - 2013 United ID.
*
* 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.unitedid.yhsm;
public class SetupCommon {
public YubiHSM hsm; | // Path: src/main/java/org/unitedid/yhsm/internal/DeviceHandler.java
// public class DeviceHandler {
// /** Logger */
// private final Logger log = LoggerFactory.getLogger(DeviceHandler.class);
//
// /** The YubiHSM device */
// private SerialPort device;
//
// private int readBytes = 0;
// private int writtenBytes = 0;
//
// private float timeout = 0.5f;
//
// /**
// * Constructor
// *
// * @param deviceName the YubiHSM device name
// */
// DeviceHandler(String deviceName) throws YubiHSMErrorException {
// device = new SerialPort(deviceName);
// try {
// device.openPort();
// device.setParams(
// SerialPort.BAUDRATE_115200,
// SerialPort.DATABITS_8,
// SerialPort.STOPBITS_1,
// SerialPort.PARITY_NONE
// );
// device.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
// } catch (SerialPortException e) {
// throw new YubiHSMErrorException("Failed to open device " + deviceName, e);
// }
// }
//
// public void write(byte[] data) {
// try {
// writtenBytes += data.length;
// device.writeBytes(data);
// } catch (SerialPortException e) {
// e.printStackTrace();
// }
// }
//
// public byte[] read(int readNumBytes) {
// byte[] data = new byte[readNumBytes];
// try {
// data = device.readBytes(readNumBytes);
// readBytes += data.length;
// } catch (SerialPortException e) {
// e.printStackTrace();
// }
//
// return data;
// }
//
// public int available() {
// try {
// return device.getInputBufferBytesCount();
// } catch (SerialPortException e) {
// e.printStackTrace();
// }
// return 0;
// }
//
// public boolean drain() {
// byte[] buffer = new byte[0];
// while(available() > 0) {
// byte[] b = read(1);
// if ((char)b[0] == '\r') {
// log.info("Drained: {}", new String(buffer, 0, buffer.length)); //TODO: Do we really need to log this? If not the loop can be simplified.
// buffer = new byte[0];
// } else {
// buffer = concatAllArrays(buffer, b);
// }
// }
// return true;
// }
//
// public void flush() throws IOException {
// try {
// device.purgePort(SerialPort.PURGE_RXCLEAR | SerialPort.PURGE_TXCLEAR);
// } catch (SerialPortException e) {
// e.printStackTrace();
// }
// }
//
// public float getTimeout() {
// return timeout;
// }
//
// public void setTimeout(float timeout) {
// this.timeout = timeout;
// }
//
// public int getReadBytes() {
// return readBytes;
// }
//
// public int getWrittenBytes() {
// return writtenBytes;
// }
//
// public String getPortName() {
// return device.getPortName();
// }
//
// public Object clone() throws CloneNotSupportedException
// {
// throw new CloneNotSupportedException();
// }
//
// protected void finalize() throws Throwable {
// try {
// device.closePort();
// } finally {
// super.finalize();
// }
// }
// }
// Path: src/test/java/org/unitedid/yhsm/SetupCommon.java
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.unitedid.yhsm.internal.DeviceHandler;
/*
* Copyright (c) 2011 - 2013 United ID.
*
* 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.unitedid.yhsm;
public class SetupCommon {
public YubiHSM hsm; | public DeviceHandler deviceHandler; |
conveyal/gtfs-validator | gtfs-validation-lib/src/main/java/com/conveyal/gtfs/service/impl/GtfsStatisticsService.java | // Path: gtfs-validation-lib/src/main/java/com/conveyal/gtfs/model/Statistic.java
// public class Statistic {
// private String agencyId;
// private Integer routeCount;
// private Integer tripCount;
// private Integer stopCount;
// private Integer stopTimeCount;
// private Date calendarServiceStart;
// private Date calendarServiceEnd;
// private Date calendarStartDate;
// private Date calendarEndDate;
// private Rectangle2D bounds;
//
// public String getAgencyId() {
// return agencyId;
// }
// public void setAgencyId(String agencyId) {
// this.agencyId = agencyId;
// }
// public Integer getRouteCount() {
// return routeCount;
// }
// public void setRouteCount(Integer routeCount) {
// this.routeCount = routeCount;
// }
// public Integer getTripCount() {
// return tripCount;
// }
// public void setTripCount(Integer tripCount) {
// this.tripCount = tripCount;
// }
// public Integer getStopCount() {
// return stopCount;
// }
// public void setStopCount(Integer stopCount) {
// this.stopCount = stopCount;
// }
// public Integer getStopTimeCount() {
// return stopTimeCount;
// }
// public void setStopTimeCount(Integer stopTimeCount) {
// this.stopTimeCount = stopTimeCount;
// }
// public Date getCalendarStartDate() {
// return calendarStartDate;
// }
// public void setCalendarStartDate(Date calendarStartDate) {
// this.calendarStartDate = calendarStartDate;
// }
// public Date getCalendarEndDate() {
// return calendarEndDate;
// }
// public void setCalendarEndDate(Date calendarEndDate) {
// this.calendarEndDate = calendarEndDate;
// }
// public Date getCalendarServiceStart() {
// return calendarServiceStart;
// }
// public void setCalendarServiceStart(Date calendarServiceStart) {
// this.calendarServiceStart = calendarServiceStart;
// }
// public Date getCalendarServiceEnd() {
// return calendarServiceEnd;
// }
// public void setCalendarServiceEnd(Date calendarServiceEnd) {
// this.calendarServiceEnd = calendarServiceEnd;
// }
// public Rectangle2D getBounds() {
// return bounds;
// }
// public void setBounds(Rectangle2D bounds) {
// this.bounds = bounds;
// }
// }
//
// Path: gtfs-validation-lib/src/main/java/com/conveyal/gtfs/service/StatisticsService.java
// public interface StatisticsService {
//
// Integer getAgencyCount();
//
// Integer getRouteCount();
//
// Integer getTripCount();
//
// Integer getStopCount();
//
// Integer getStopTimesCount();
// /*
// * As Calendar Dates are optional per the GTFS spec, this returns an Optional<Date>.
// * To retrieve a Date Object from this use the method, getCalendarDateStart().get()
// */
// Optional<Date> getCalendarDateStart();
//
// Optional<Date> getCalendarDateEnd();
//
// Date getCalendarServiceRangeStart();
//
// Date getCalendarServiceRangeEnd();
//
// Integer getNumberOfDays();
//
// Integer getRouteCount(String agencyId);
//
// Integer getTripCount(String agencyId);
//
// Integer getStopCount(String agencyId);
//
// Integer getStopTimesCount(String agencyId);
//
// Date getCalendarDateStart(String agencyId);
//
// Date getCalendarDateEnd(String agencyId);
//
// Date getCalendarServiceRangeStart(String agencyId);
//
// Date getCalendarServiceRangeEnd(String agencyId);
//
// Rectangle2D getBounds ();
//
// Statistic getStatistic(String agencyId);
// }
| import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.time.Duration;
import java.time.ZoneId;
import java.util.Collection;
import java.util.Date;
import java.util.Optional;
import java.util.TimeZone;
import org.onebusaway.gtfs.impl.GtfsRelationalDaoImpl;
import org.onebusaway.gtfs.impl.calendar.CalendarServiceDataFactoryImpl;
import org.onebusaway.gtfs.model.Agency;
import org.onebusaway.gtfs.model.AgencyAndId;
import org.onebusaway.gtfs.model.Route;
import org.onebusaway.gtfs.model.ServiceCalendar;
import org.onebusaway.gtfs.model.ServiceCalendarDate;
import org.onebusaway.gtfs.model.Stop;
import org.onebusaway.gtfs.model.StopTime;
import org.onebusaway.gtfs.model.Trip;
import org.onebusaway.gtfs.services.calendar.CalendarService;
import com.conveyal.gtfs.model.Statistic;
import com.conveyal.gtfs.service.StatisticsService; | if (agencyId.equals(serviceCalendarDate.getServiceId().getAgencyId())) {
if (endDate == null
|| serviceCalendarDate.getDate().getAsDate().after(endDate))
endDate = serviceCalendarDate.getDate().getAsDate();
}
}
return endDate;
}
/**
* Get the bounding box of this GTFS feed.
* We use a Rectangle2D rather than a Geotools envelope because GTFS is always in WGS 84.
* Note that stops do not have agencies in GTFS.
*/
public Rectangle2D getBounds () {
Rectangle2D ret = null;
for (Stop stop : gtfsDao.getAllStops()) {
if (ret == null) {
ret = new Rectangle2D.Double(stop.getLon(), stop.getLat(), 0, 0);
}
else {
ret.add(new Point2D.Double(stop.getLon(), stop.getLat()));
}
}
return ret;
}
| // Path: gtfs-validation-lib/src/main/java/com/conveyal/gtfs/model/Statistic.java
// public class Statistic {
// private String agencyId;
// private Integer routeCount;
// private Integer tripCount;
// private Integer stopCount;
// private Integer stopTimeCount;
// private Date calendarServiceStart;
// private Date calendarServiceEnd;
// private Date calendarStartDate;
// private Date calendarEndDate;
// private Rectangle2D bounds;
//
// public String getAgencyId() {
// return agencyId;
// }
// public void setAgencyId(String agencyId) {
// this.agencyId = agencyId;
// }
// public Integer getRouteCount() {
// return routeCount;
// }
// public void setRouteCount(Integer routeCount) {
// this.routeCount = routeCount;
// }
// public Integer getTripCount() {
// return tripCount;
// }
// public void setTripCount(Integer tripCount) {
// this.tripCount = tripCount;
// }
// public Integer getStopCount() {
// return stopCount;
// }
// public void setStopCount(Integer stopCount) {
// this.stopCount = stopCount;
// }
// public Integer getStopTimeCount() {
// return stopTimeCount;
// }
// public void setStopTimeCount(Integer stopTimeCount) {
// this.stopTimeCount = stopTimeCount;
// }
// public Date getCalendarStartDate() {
// return calendarStartDate;
// }
// public void setCalendarStartDate(Date calendarStartDate) {
// this.calendarStartDate = calendarStartDate;
// }
// public Date getCalendarEndDate() {
// return calendarEndDate;
// }
// public void setCalendarEndDate(Date calendarEndDate) {
// this.calendarEndDate = calendarEndDate;
// }
// public Date getCalendarServiceStart() {
// return calendarServiceStart;
// }
// public void setCalendarServiceStart(Date calendarServiceStart) {
// this.calendarServiceStart = calendarServiceStart;
// }
// public Date getCalendarServiceEnd() {
// return calendarServiceEnd;
// }
// public void setCalendarServiceEnd(Date calendarServiceEnd) {
// this.calendarServiceEnd = calendarServiceEnd;
// }
// public Rectangle2D getBounds() {
// return bounds;
// }
// public void setBounds(Rectangle2D bounds) {
// this.bounds = bounds;
// }
// }
//
// Path: gtfs-validation-lib/src/main/java/com/conveyal/gtfs/service/StatisticsService.java
// public interface StatisticsService {
//
// Integer getAgencyCount();
//
// Integer getRouteCount();
//
// Integer getTripCount();
//
// Integer getStopCount();
//
// Integer getStopTimesCount();
// /*
// * As Calendar Dates are optional per the GTFS spec, this returns an Optional<Date>.
// * To retrieve a Date Object from this use the method, getCalendarDateStart().get()
// */
// Optional<Date> getCalendarDateStart();
//
// Optional<Date> getCalendarDateEnd();
//
// Date getCalendarServiceRangeStart();
//
// Date getCalendarServiceRangeEnd();
//
// Integer getNumberOfDays();
//
// Integer getRouteCount(String agencyId);
//
// Integer getTripCount(String agencyId);
//
// Integer getStopCount(String agencyId);
//
// Integer getStopTimesCount(String agencyId);
//
// Date getCalendarDateStart(String agencyId);
//
// Date getCalendarDateEnd(String agencyId);
//
// Date getCalendarServiceRangeStart(String agencyId);
//
// Date getCalendarServiceRangeEnd(String agencyId);
//
// Rectangle2D getBounds ();
//
// Statistic getStatistic(String agencyId);
// }
// Path: gtfs-validation-lib/src/main/java/com/conveyal/gtfs/service/impl/GtfsStatisticsService.java
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.time.Duration;
import java.time.ZoneId;
import java.util.Collection;
import java.util.Date;
import java.util.Optional;
import java.util.TimeZone;
import org.onebusaway.gtfs.impl.GtfsRelationalDaoImpl;
import org.onebusaway.gtfs.impl.calendar.CalendarServiceDataFactoryImpl;
import org.onebusaway.gtfs.model.Agency;
import org.onebusaway.gtfs.model.AgencyAndId;
import org.onebusaway.gtfs.model.Route;
import org.onebusaway.gtfs.model.ServiceCalendar;
import org.onebusaway.gtfs.model.ServiceCalendarDate;
import org.onebusaway.gtfs.model.Stop;
import org.onebusaway.gtfs.model.StopTime;
import org.onebusaway.gtfs.model.Trip;
import org.onebusaway.gtfs.services.calendar.CalendarService;
import com.conveyal.gtfs.model.Statistic;
import com.conveyal.gtfs.service.StatisticsService;
if (agencyId.equals(serviceCalendarDate.getServiceId().getAgencyId())) {
if (endDate == null
|| serviceCalendarDate.getDate().getAsDate().after(endDate))
endDate = serviceCalendarDate.getDate().getAsDate();
}
}
return endDate;
}
/**
* Get the bounding box of this GTFS feed.
* We use a Rectangle2D rather than a Geotools envelope because GTFS is always in WGS 84.
* Note that stops do not have agencies in GTFS.
*/
public Rectangle2D getBounds () {
Rectangle2D ret = null;
for (Stop stop : gtfsDao.getAllStops()) {
if (ret == null) {
ret = new Rectangle2D.Double(stop.getLon(), stop.getLat(), 0, 0);
}
else {
ret.add(new Point2D.Double(stop.getLon(), stop.getLat()));
}
}
return ret;
}
| public Statistic getStatistic(String agencyId) { |
conveyal/gtfs-validator | gtfs-validator-json/src/main/java/com/conveyal/gtfs/validator/json/JsonValidatorMain.java | // Path: gtfs-validator-json/src/main/java/com/conveyal/gtfs/validator/json/backends/FileSystemFeedBackend.java
// public class FileSystemFeedBackend implements FeedBackend {
//
// /**
// * Get the feed at path feedId on the file system. This is trivial but allows for compatibility
// * with more complicated backends.
// * @param feedId The path the feed
// * @return a file object referring to the feed
// */
// public File getFeed(String feedId) {
// return new File(feedId);
// }
// }
//
// Path: gtfs-validator-json/src/main/java/com/conveyal/gtfs/validator/json/serialization/JsonSerializer.java
// public class JsonSerializer extends Serializer {
// private ObjectMapper mapper;
// private ObjectWriter writer;
//
//
// /**
// * Create a JSON serializer for these validation results.
// * @param results
// */
// public JsonSerializer (FeedValidationResultSet results) {
// super(results);
// mapper = new ObjectMapper();
// mapper.addMixInAnnotations(Rectangle2D.class, Rectangle2DMixIn.class);
// SimpleModule deser = new SimpleModule();
// deser.addDeserializer(Rectangle2D.class, new Rectangle2DDeserializer());
// mapper.registerModule(deser);
// SimpleFilterProvider filters = new SimpleFilterProvider();
// filters.addFilter("bbox", SimpleBeanPropertyFilter.filterOutAllExcept("west", "east", "south", "north"));
// writer = mapper.writer(filters);
// }
//
// /**
// * Serialize to JSON
// * @return a string containing the serialized JSON
// */
// public Object serialize() throws JsonProcessingException {
// return writer.writeValueAsString(results);
// }
//
// /**
// * Serialize to JSON and write to file.
// * @param file the file to write the JSON to
// */
// public void serializeToFile(File file) throws JsonGenerationException, JsonMappingException, IOException {
// writer.writeValue(file, results);
// }
// }
| import java.io.File;
import java.io.IOException;
import com.conveyal.gtfs.validator.json.backends.FileSystemFeedBackend;
import com.conveyal.gtfs.validator.json.serialization.JsonSerializer; | package com.conveyal.gtfs.validator.json;
public class JsonValidatorMain {
/**
* Take an input GTFS and an output file and write JSON to that output file summarizing validation of the GTFS.
* @param args
*/
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.err.println("usage: java -Xmx[several]G input_gtfs.zip [other_gtfs.zip third_gtfs.zip . . .] output_file.json");
return;
}
// We use a file system backend because we're not doing anything fancy, just reading local GTFS | // Path: gtfs-validator-json/src/main/java/com/conveyal/gtfs/validator/json/backends/FileSystemFeedBackend.java
// public class FileSystemFeedBackend implements FeedBackend {
//
// /**
// * Get the feed at path feedId on the file system. This is trivial but allows for compatibility
// * with more complicated backends.
// * @param feedId The path the feed
// * @return a file object referring to the feed
// */
// public File getFeed(String feedId) {
// return new File(feedId);
// }
// }
//
// Path: gtfs-validator-json/src/main/java/com/conveyal/gtfs/validator/json/serialization/JsonSerializer.java
// public class JsonSerializer extends Serializer {
// private ObjectMapper mapper;
// private ObjectWriter writer;
//
//
// /**
// * Create a JSON serializer for these validation results.
// * @param results
// */
// public JsonSerializer (FeedValidationResultSet results) {
// super(results);
// mapper = new ObjectMapper();
// mapper.addMixInAnnotations(Rectangle2D.class, Rectangle2DMixIn.class);
// SimpleModule deser = new SimpleModule();
// deser.addDeserializer(Rectangle2D.class, new Rectangle2DDeserializer());
// mapper.registerModule(deser);
// SimpleFilterProvider filters = new SimpleFilterProvider();
// filters.addFilter("bbox", SimpleBeanPropertyFilter.filterOutAllExcept("west", "east", "south", "north"));
// writer = mapper.writer(filters);
// }
//
// /**
// * Serialize to JSON
// * @return a string containing the serialized JSON
// */
// public Object serialize() throws JsonProcessingException {
// return writer.writeValueAsString(results);
// }
//
// /**
// * Serialize to JSON and write to file.
// * @param file the file to write the JSON to
// */
// public void serializeToFile(File file) throws JsonGenerationException, JsonMappingException, IOException {
// writer.writeValue(file, results);
// }
// }
// Path: gtfs-validator-json/src/main/java/com/conveyal/gtfs/validator/json/JsonValidatorMain.java
import java.io.File;
import java.io.IOException;
import com.conveyal.gtfs.validator.json.backends.FileSystemFeedBackend;
import com.conveyal.gtfs.validator.json.serialization.JsonSerializer;
package com.conveyal.gtfs.validator.json;
public class JsonValidatorMain {
/**
* Take an input GTFS and an output file and write JSON to that output file summarizing validation of the GTFS.
* @param args
*/
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.err.println("usage: java -Xmx[several]G input_gtfs.zip [other_gtfs.zip third_gtfs.zip . . .] output_file.json");
return;
}
// We use a file system backend because we're not doing anything fancy, just reading local GTFS | FileSystemFeedBackend backend = new FileSystemFeedBackend(); |
conveyal/gtfs-validator | gtfs-validator-json/src/main/java/com/conveyal/gtfs/validator/json/JsonValidatorMain.java | // Path: gtfs-validator-json/src/main/java/com/conveyal/gtfs/validator/json/backends/FileSystemFeedBackend.java
// public class FileSystemFeedBackend implements FeedBackend {
//
// /**
// * Get the feed at path feedId on the file system. This is trivial but allows for compatibility
// * with more complicated backends.
// * @param feedId The path the feed
// * @return a file object referring to the feed
// */
// public File getFeed(String feedId) {
// return new File(feedId);
// }
// }
//
// Path: gtfs-validator-json/src/main/java/com/conveyal/gtfs/validator/json/serialization/JsonSerializer.java
// public class JsonSerializer extends Serializer {
// private ObjectMapper mapper;
// private ObjectWriter writer;
//
//
// /**
// * Create a JSON serializer for these validation results.
// * @param results
// */
// public JsonSerializer (FeedValidationResultSet results) {
// super(results);
// mapper = new ObjectMapper();
// mapper.addMixInAnnotations(Rectangle2D.class, Rectangle2DMixIn.class);
// SimpleModule deser = new SimpleModule();
// deser.addDeserializer(Rectangle2D.class, new Rectangle2DDeserializer());
// mapper.registerModule(deser);
// SimpleFilterProvider filters = new SimpleFilterProvider();
// filters.addFilter("bbox", SimpleBeanPropertyFilter.filterOutAllExcept("west", "east", "south", "north"));
// writer = mapper.writer(filters);
// }
//
// /**
// * Serialize to JSON
// * @return a string containing the serialized JSON
// */
// public Object serialize() throws JsonProcessingException {
// return writer.writeValueAsString(results);
// }
//
// /**
// * Serialize to JSON and write to file.
// * @param file the file to write the JSON to
// */
// public void serializeToFile(File file) throws JsonGenerationException, JsonMappingException, IOException {
// writer.writeValue(file, results);
// }
// }
| import java.io.File;
import java.io.IOException;
import com.conveyal.gtfs.validator.json.backends.FileSystemFeedBackend;
import com.conveyal.gtfs.validator.json.serialization.JsonSerializer; | package com.conveyal.gtfs.validator.json;
public class JsonValidatorMain {
/**
* Take an input GTFS and an output file and write JSON to that output file summarizing validation of the GTFS.
* @param args
*/
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.err.println("usage: java -Xmx[several]G input_gtfs.zip [other_gtfs.zip third_gtfs.zip . . .] output_file.json");
return;
}
// We use a file system backend because we're not doing anything fancy, just reading local GTFS
FileSystemFeedBackend backend = new FileSystemFeedBackend();
// Since we're processing multiple feeds (potentially), use a FeedValidationResultSet to save the output
FeedValidationResultSet results = new FeedValidationResultSet();
// default name is directory name
results.name = new File(args[0]).getAbsoluteFile().getParentFile().getName();
// loop over all arguments except the last (which is the name of the JSON file)
// TODO: throw all feeds in a queue and run as many threads as we have cores to do the validation
// not exactly urgent, since for all of New York State this takes only a few minutes on my laptop
for (int i = 0; i < args.length - 1; i++) {
File input = backend.getFeed(args[i]);
System.err.println("Processing feed " + input.getName());
FeedProcessor processor = new FeedProcessor(input);
try {
processor.run();
} catch (IOException e) {
e.printStackTrace();
System.err.println("Unable to access input GTFS " + input.getPath() + ". Does the file exist and do I have permission to read it?");
return;
}
results.add(processor.getOutput());
}
| // Path: gtfs-validator-json/src/main/java/com/conveyal/gtfs/validator/json/backends/FileSystemFeedBackend.java
// public class FileSystemFeedBackend implements FeedBackend {
//
// /**
// * Get the feed at path feedId on the file system. This is trivial but allows for compatibility
// * with more complicated backends.
// * @param feedId The path the feed
// * @return a file object referring to the feed
// */
// public File getFeed(String feedId) {
// return new File(feedId);
// }
// }
//
// Path: gtfs-validator-json/src/main/java/com/conveyal/gtfs/validator/json/serialization/JsonSerializer.java
// public class JsonSerializer extends Serializer {
// private ObjectMapper mapper;
// private ObjectWriter writer;
//
//
// /**
// * Create a JSON serializer for these validation results.
// * @param results
// */
// public JsonSerializer (FeedValidationResultSet results) {
// super(results);
// mapper = new ObjectMapper();
// mapper.addMixInAnnotations(Rectangle2D.class, Rectangle2DMixIn.class);
// SimpleModule deser = new SimpleModule();
// deser.addDeserializer(Rectangle2D.class, new Rectangle2DDeserializer());
// mapper.registerModule(deser);
// SimpleFilterProvider filters = new SimpleFilterProvider();
// filters.addFilter("bbox", SimpleBeanPropertyFilter.filterOutAllExcept("west", "east", "south", "north"));
// writer = mapper.writer(filters);
// }
//
// /**
// * Serialize to JSON
// * @return a string containing the serialized JSON
// */
// public Object serialize() throws JsonProcessingException {
// return writer.writeValueAsString(results);
// }
//
// /**
// * Serialize to JSON and write to file.
// * @param file the file to write the JSON to
// */
// public void serializeToFile(File file) throws JsonGenerationException, JsonMappingException, IOException {
// writer.writeValue(file, results);
// }
// }
// Path: gtfs-validator-json/src/main/java/com/conveyal/gtfs/validator/json/JsonValidatorMain.java
import java.io.File;
import java.io.IOException;
import com.conveyal.gtfs.validator.json.backends.FileSystemFeedBackend;
import com.conveyal.gtfs.validator.json.serialization.JsonSerializer;
package com.conveyal.gtfs.validator.json;
public class JsonValidatorMain {
/**
* Take an input GTFS and an output file and write JSON to that output file summarizing validation of the GTFS.
* @param args
*/
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.err.println("usage: java -Xmx[several]G input_gtfs.zip [other_gtfs.zip third_gtfs.zip . . .] output_file.json");
return;
}
// We use a file system backend because we're not doing anything fancy, just reading local GTFS
FileSystemFeedBackend backend = new FileSystemFeedBackend();
// Since we're processing multiple feeds (potentially), use a FeedValidationResultSet to save the output
FeedValidationResultSet results = new FeedValidationResultSet();
// default name is directory name
results.name = new File(args[0]).getAbsoluteFile().getParentFile().getName();
// loop over all arguments except the last (which is the name of the JSON file)
// TODO: throw all feeds in a queue and run as many threads as we have cores to do the validation
// not exactly urgent, since for all of New York State this takes only a few minutes on my laptop
for (int i = 0; i < args.length - 1; i++) {
File input = backend.getFeed(args[i]);
System.err.println("Processing feed " + input.getName());
FeedProcessor processor = new FeedProcessor(input);
try {
processor.run();
} catch (IOException e) {
e.printStackTrace();
System.err.println("Unable to access input GTFS " + input.getPath() + ". Does the file exist and do I have permission to read it?");
return;
}
results.add(processor.getOutput());
}
| JsonSerializer serializer = new JsonSerializer(results); |
conveyal/gtfs-validator | gtfs-validator-json/src/main/java/com/conveyal/gtfs/validator/json/serialization/JsonSerializer.java | // Path: gtfs-validator-json/src/main/java/com/conveyal/gtfs/validator/json/FeedValidationResultSet.java
// public class FeedValidationResultSet {
// /** The name of this feedset. In the simplest case this is the name of the directory
// * containing the first feed.
// */
// public String name;
//
// /**
// * The date of this run
// */
// public Date date;
//
// // note: the following three fields are private because applications should not manipulate them
// // directly, as they track internal state. We add a JsonProperty annotation to each so that it
// // is exported in the JSON. While this theoretically embeds one format into code that is generally
// // intended to be format-generic, it shouldn't be an issue because the annotation should simply have
// // no effect outside of Jackson.
//
// /**
// * The number of feeds validated.
// */
// @JsonProperty
// private int feedCount;
//
// /**
// * The number of feeds that were able to be loaded (they may have had validation errors,
// * but nothing that makes them unusable, at least not from a technical standpoint).
// */
// @JsonProperty
// private int loadCount;
//
// /**
// * The validation results of all of the feeds.
// */
// @JsonProperty
// private Set<FeedValidationResult> results;
//
// /**
// * Add a feed validation result to this result set.
// */
// public void add(FeedValidationResult results) {
// this.results.add(results);
// feedCount++;
// if (LoadStatus.SUCCESS.equals(results.loadStatus))
// loadCount++;
// }
//
// /**
// * Create a new FeedValidationResultSet with the given initial capacity.
// * @param capacity initial capacity
// */
// public FeedValidationResultSet (int capacity) {
// this.results = new HashSet<FeedValidationResult>(capacity);
// this.date = new Date();
// }
//
// /**
// * Create a new FeedValidationResultSet with a reasonable default initial capacity.
// */
// public FeedValidationResultSet () {
// this(16);
// }
// }
| import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.IOException;
import com.conveyal.gtfs.validator.json.FeedValidationResultSet;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; | package com.conveyal.gtfs.validator.json.serialization;
/**
* Serialize validation results to JSON, using Jackson
* @author mattwigway
*/
public class JsonSerializer extends Serializer {
private ObjectMapper mapper;
private ObjectWriter writer;
/**
* Create a JSON serializer for these validation results.
* @param results
*/ | // Path: gtfs-validator-json/src/main/java/com/conveyal/gtfs/validator/json/FeedValidationResultSet.java
// public class FeedValidationResultSet {
// /** The name of this feedset. In the simplest case this is the name of the directory
// * containing the first feed.
// */
// public String name;
//
// /**
// * The date of this run
// */
// public Date date;
//
// // note: the following three fields are private because applications should not manipulate them
// // directly, as they track internal state. We add a JsonProperty annotation to each so that it
// // is exported in the JSON. While this theoretically embeds one format into code that is generally
// // intended to be format-generic, it shouldn't be an issue because the annotation should simply have
// // no effect outside of Jackson.
//
// /**
// * The number of feeds validated.
// */
// @JsonProperty
// private int feedCount;
//
// /**
// * The number of feeds that were able to be loaded (they may have had validation errors,
// * but nothing that makes them unusable, at least not from a technical standpoint).
// */
// @JsonProperty
// private int loadCount;
//
// /**
// * The validation results of all of the feeds.
// */
// @JsonProperty
// private Set<FeedValidationResult> results;
//
// /**
// * Add a feed validation result to this result set.
// */
// public void add(FeedValidationResult results) {
// this.results.add(results);
// feedCount++;
// if (LoadStatus.SUCCESS.equals(results.loadStatus))
// loadCount++;
// }
//
// /**
// * Create a new FeedValidationResultSet with the given initial capacity.
// * @param capacity initial capacity
// */
// public FeedValidationResultSet (int capacity) {
// this.results = new HashSet<FeedValidationResult>(capacity);
// this.date = new Date();
// }
//
// /**
// * Create a new FeedValidationResultSet with a reasonable default initial capacity.
// */
// public FeedValidationResultSet () {
// this(16);
// }
// }
// Path: gtfs-validator-json/src/main/java/com/conveyal/gtfs/validator/json/serialization/JsonSerializer.java
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.IOException;
import com.conveyal.gtfs.validator.json.FeedValidationResultSet;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
package com.conveyal.gtfs.validator.json.serialization;
/**
* Serialize validation results to JSON, using Jackson
* @author mattwigway
*/
public class JsonSerializer extends Serializer {
private ObjectMapper mapper;
private ObjectWriter writer;
/**
* Create a JSON serializer for these validation results.
* @param results
*/ | public JsonSerializer (FeedValidationResultSet results) { |
conveyal/gtfs-validator | gtfs-validator-json/src/main/java/com/conveyal/gtfs/validator/json/FeedValidationResult.java | // Path: gtfs-validation-lib/src/main/java/com/conveyal/gtfs/model/ValidationResult.java
// public class ValidationResult implements Serializable {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private static Logger _log = Logger.getLogger(ValidationResult.class.getName());
//
// public Set<InvalidValue> invalidValues = new TreeSet<InvalidValue>();
//
// public void add(InvalidValue iv) {
// // _log.info(iv.toString());
// invalidValues.add(iv);
// }
//
// public void append(ValidationResult vr) {
// invalidValues.addAll(vr.invalidValues);
// }
//
// public String toString(){
// StringBuilder sb = new StringBuilder();
// for (InvalidValue iv: invalidValues){
// sb.append(iv);
// }
// return sb.toString();
// }
//
//
// public boolean containsBoth(String one, String two, String type){
// for (InvalidValue iv: invalidValues){
// if (iv.problemDescription.contains(one)
// && iv.problemDescription.contains(two)
// && iv.affectedEntity == type) {
// return true;
// }
// }
// return false;
// }
// }
| import java.awt.geom.Rectangle2D;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import com.conveyal.gtfs.model.ValidationResult;
import com.fasterxml.jackson.annotation.JsonProperty; | package com.conveyal.gtfs.validator.json;
/**
* A class to hold all of the results of a validation on a single feed.
* Not to be confused with {@link com.conveyal.gtfs.model.ValidationResult}, which holds all instances of
* a particular type of error.
* @author mattwigway
*
*/
public class FeedValidationResult implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/** Were we able to load the GTFS at all (note that this should only indicate corrupted files,
* not missing ones; that should raise an exception instead.)
*/
@JsonProperty
public LoadStatus loadStatus;
/**
* Additional description of why the feed failed to load.
*/
public String loadFailureReason;
/**
* The name of the feed on the file system
*/
public String feedFileName;
/**
* All of the agencies in the feed
*/
public Collection<String> agencies;
| // Path: gtfs-validation-lib/src/main/java/com/conveyal/gtfs/model/ValidationResult.java
// public class ValidationResult implements Serializable {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private static Logger _log = Logger.getLogger(ValidationResult.class.getName());
//
// public Set<InvalidValue> invalidValues = new TreeSet<InvalidValue>();
//
// public void add(InvalidValue iv) {
// // _log.info(iv.toString());
// invalidValues.add(iv);
// }
//
// public void append(ValidationResult vr) {
// invalidValues.addAll(vr.invalidValues);
// }
//
// public String toString(){
// StringBuilder sb = new StringBuilder();
// for (InvalidValue iv: invalidValues){
// sb.append(iv);
// }
// return sb.toString();
// }
//
//
// public boolean containsBoth(String one, String two, String type){
// for (InvalidValue iv: invalidValues){
// if (iv.problemDescription.contains(one)
// && iv.problemDescription.contains(two)
// && iv.affectedEntity == type) {
// return true;
// }
// }
// return false;
// }
// }
// Path: gtfs-validator-json/src/main/java/com/conveyal/gtfs/validator/json/FeedValidationResult.java
import java.awt.geom.Rectangle2D;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import com.conveyal.gtfs.model.ValidationResult;
import com.fasterxml.jackson.annotation.JsonProperty;
package com.conveyal.gtfs.validator.json;
/**
* A class to hold all of the results of a validation on a single feed.
* Not to be confused with {@link com.conveyal.gtfs.model.ValidationResult}, which holds all instances of
* a particular type of error.
* @author mattwigway
*
*/
public class FeedValidationResult implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/** Were we able to load the GTFS at all (note that this should only indicate corrupted files,
* not missing ones; that should raise an exception instead.)
*/
@JsonProperty
public LoadStatus loadStatus;
/**
* Additional description of why the feed failed to load.
*/
public String loadFailureReason;
/**
* The name of the feed on the file system
*/
public String feedFileName;
/**
* All of the agencies in the feed
*/
public Collection<String> agencies;
| public ValidationResult routes; |
conveyal/gtfs-validator | gtfs-validation-lib/src/main/java/com/conveyal/gtfs/service/StatisticsService.java | // Path: gtfs-validation-lib/src/main/java/com/conveyal/gtfs/model/Statistic.java
// public class Statistic {
// private String agencyId;
// private Integer routeCount;
// private Integer tripCount;
// private Integer stopCount;
// private Integer stopTimeCount;
// private Date calendarServiceStart;
// private Date calendarServiceEnd;
// private Date calendarStartDate;
// private Date calendarEndDate;
// private Rectangle2D bounds;
//
// public String getAgencyId() {
// return agencyId;
// }
// public void setAgencyId(String agencyId) {
// this.agencyId = agencyId;
// }
// public Integer getRouteCount() {
// return routeCount;
// }
// public void setRouteCount(Integer routeCount) {
// this.routeCount = routeCount;
// }
// public Integer getTripCount() {
// return tripCount;
// }
// public void setTripCount(Integer tripCount) {
// this.tripCount = tripCount;
// }
// public Integer getStopCount() {
// return stopCount;
// }
// public void setStopCount(Integer stopCount) {
// this.stopCount = stopCount;
// }
// public Integer getStopTimeCount() {
// return stopTimeCount;
// }
// public void setStopTimeCount(Integer stopTimeCount) {
// this.stopTimeCount = stopTimeCount;
// }
// public Date getCalendarStartDate() {
// return calendarStartDate;
// }
// public void setCalendarStartDate(Date calendarStartDate) {
// this.calendarStartDate = calendarStartDate;
// }
// public Date getCalendarEndDate() {
// return calendarEndDate;
// }
// public void setCalendarEndDate(Date calendarEndDate) {
// this.calendarEndDate = calendarEndDate;
// }
// public Date getCalendarServiceStart() {
// return calendarServiceStart;
// }
// public void setCalendarServiceStart(Date calendarServiceStart) {
// this.calendarServiceStart = calendarServiceStart;
// }
// public Date getCalendarServiceEnd() {
// return calendarServiceEnd;
// }
// public void setCalendarServiceEnd(Date calendarServiceEnd) {
// this.calendarServiceEnd = calendarServiceEnd;
// }
// public Rectangle2D getBounds() {
// return bounds;
// }
// public void setBounds(Rectangle2D bounds) {
// this.bounds = bounds;
// }
// }
| import java.awt.geom.Rectangle2D;
import java.util.Date;
import java.util.Optional;
import com.conveyal.gtfs.model.Statistic; | package com.conveyal.gtfs.service;
/**
* Provides statistics for:
* <or>
* <li>Agencies
* <li>Routes
* <li>Trips
* <li>Stops
* <li>Stop Times
* <li>Calendar Date ranges
* <li>Calendar Service exceptions
* </or>
* @author dev
*
*/
public interface StatisticsService {
Integer getAgencyCount();
Integer getRouteCount();
Integer getTripCount();
Integer getStopCount();
Integer getStopTimesCount();
/*
* As Calendar Dates are optional per the GTFS spec, this returns an Optional<Date>.
* To retrieve a Date Object from this use the method, getCalendarDateStart().get()
*/
Optional<Date> getCalendarDateStart();
Optional<Date> getCalendarDateEnd();
Date getCalendarServiceRangeStart();
Date getCalendarServiceRangeEnd();
Integer getNumberOfDays();
Integer getRouteCount(String agencyId);
Integer getTripCount(String agencyId);
Integer getStopCount(String agencyId);
Integer getStopTimesCount(String agencyId);
Date getCalendarDateStart(String agencyId);
Date getCalendarDateEnd(String agencyId);
Date getCalendarServiceRangeStart(String agencyId);
Date getCalendarServiceRangeEnd(String agencyId);
Rectangle2D getBounds ();
| // Path: gtfs-validation-lib/src/main/java/com/conveyal/gtfs/model/Statistic.java
// public class Statistic {
// private String agencyId;
// private Integer routeCount;
// private Integer tripCount;
// private Integer stopCount;
// private Integer stopTimeCount;
// private Date calendarServiceStart;
// private Date calendarServiceEnd;
// private Date calendarStartDate;
// private Date calendarEndDate;
// private Rectangle2D bounds;
//
// public String getAgencyId() {
// return agencyId;
// }
// public void setAgencyId(String agencyId) {
// this.agencyId = agencyId;
// }
// public Integer getRouteCount() {
// return routeCount;
// }
// public void setRouteCount(Integer routeCount) {
// this.routeCount = routeCount;
// }
// public Integer getTripCount() {
// return tripCount;
// }
// public void setTripCount(Integer tripCount) {
// this.tripCount = tripCount;
// }
// public Integer getStopCount() {
// return stopCount;
// }
// public void setStopCount(Integer stopCount) {
// this.stopCount = stopCount;
// }
// public Integer getStopTimeCount() {
// return stopTimeCount;
// }
// public void setStopTimeCount(Integer stopTimeCount) {
// this.stopTimeCount = stopTimeCount;
// }
// public Date getCalendarStartDate() {
// return calendarStartDate;
// }
// public void setCalendarStartDate(Date calendarStartDate) {
// this.calendarStartDate = calendarStartDate;
// }
// public Date getCalendarEndDate() {
// return calendarEndDate;
// }
// public void setCalendarEndDate(Date calendarEndDate) {
// this.calendarEndDate = calendarEndDate;
// }
// public Date getCalendarServiceStart() {
// return calendarServiceStart;
// }
// public void setCalendarServiceStart(Date calendarServiceStart) {
// this.calendarServiceStart = calendarServiceStart;
// }
// public Date getCalendarServiceEnd() {
// return calendarServiceEnd;
// }
// public void setCalendarServiceEnd(Date calendarServiceEnd) {
// this.calendarServiceEnd = calendarServiceEnd;
// }
// public Rectangle2D getBounds() {
// return bounds;
// }
// public void setBounds(Rectangle2D bounds) {
// this.bounds = bounds;
// }
// }
// Path: gtfs-validation-lib/src/main/java/com/conveyal/gtfs/service/StatisticsService.java
import java.awt.geom.Rectangle2D;
import java.util.Date;
import java.util.Optional;
import com.conveyal.gtfs.model.Statistic;
package com.conveyal.gtfs.service;
/**
* Provides statistics for:
* <or>
* <li>Agencies
* <li>Routes
* <li>Trips
* <li>Stops
* <li>Stop Times
* <li>Calendar Date ranges
* <li>Calendar Service exceptions
* </or>
* @author dev
*
*/
public interface StatisticsService {
Integer getAgencyCount();
Integer getRouteCount();
Integer getTripCount();
Integer getStopCount();
Integer getStopTimesCount();
/*
* As Calendar Dates are optional per the GTFS spec, this returns an Optional<Date>.
* To retrieve a Date Object from this use the method, getCalendarDateStart().get()
*/
Optional<Date> getCalendarDateStart();
Optional<Date> getCalendarDateEnd();
Date getCalendarServiceRangeStart();
Date getCalendarServiceRangeEnd();
Integer getNumberOfDays();
Integer getRouteCount(String agencyId);
Integer getTripCount(String agencyId);
Integer getStopCount(String agencyId);
Integer getStopTimesCount(String agencyId);
Date getCalendarDateStart(String agencyId);
Date getCalendarDateEnd(String agencyId);
Date getCalendarServiceRangeStart(String agencyId);
Date getCalendarServiceRangeEnd(String agencyId);
Rectangle2D getBounds ();
| Statistic getStatistic(String agencyId); |
conveyal/gtfs-validator | gtfs-validation-lib/src/main/java/com/conveyal/gtfs/service/GeoUtils.java | // Path: gtfs-validation-lib/src/main/java/com/conveyal/gtfs/model/ProjectedCoordinate.java
// public class ProjectedCoordinate extends Coordinate {
//
// private static final long serialVersionUID = 2905131060296578237L;
//
// final private MathTransform transform;
// final private Coordinate refLatLon;
//
// public ProjectedCoordinate(MathTransform mathTransform,
// Coordinate to, Coordinate refLatLon) {
// this.transform = mathTransform;
// this.x = to.x;
// this.y = to.y;
// this.refLatLon = refLatLon;
// }
//
// public String epsgCode() {
// final String epsgCode =
// "EPSG:" + GeoUtils.getEPSGCodefromUTS(refLatLon);
// return epsgCode;
// }
//
// public Coordinate getReferenceLatLon() {
// return refLatLon;
// }
//
// public MathTransform getTransform() {
// return transform;
// }
//
// public double getX() {
// return this.x;
// }
//
// public double getY() {
// return this.y;
// }
//
//
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
import org.geotools.geometry.GeometryBuilder;
import org.geotools.geometry.jts.JTS;
import org.geotools.referencing.CRS;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.onebusaway.gtfs.model.ShapePoint;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.NoSuchIdentifierException;
import org.opengis.referencing.crs.CRSAuthorityFactory;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.crs.GeographicCRS;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.TransformException;
import com.conveyal.gtfs.model.ProjectedCoordinate;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.PrecisionModel; | package com.conveyal.gtfs.service;
public class GeoUtils {
public static double RADIANS = 2 * Math.PI;
public static MathTransform recentMathTransform = null;
public static GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(),4326);
public static GeometryFactory projectedGeometryFactory = new GeometryFactory(new PrecisionModel());
public static GeometryBuilder builder = new GeometryBuilder(DefaultGeographicCRS.WGS84);
/**
* Converts from a coordinate to The appropriate UTM zone.
*
* @param latlon THE ORDER OF THE COORDINATE MUST BE LAT, LON!
* @return
*/ | // Path: gtfs-validation-lib/src/main/java/com/conveyal/gtfs/model/ProjectedCoordinate.java
// public class ProjectedCoordinate extends Coordinate {
//
// private static final long serialVersionUID = 2905131060296578237L;
//
// final private MathTransform transform;
// final private Coordinate refLatLon;
//
// public ProjectedCoordinate(MathTransform mathTransform,
// Coordinate to, Coordinate refLatLon) {
// this.transform = mathTransform;
// this.x = to.x;
// this.y = to.y;
// this.refLatLon = refLatLon;
// }
//
// public String epsgCode() {
// final String epsgCode =
// "EPSG:" + GeoUtils.getEPSGCodefromUTS(refLatLon);
// return epsgCode;
// }
//
// public Coordinate getReferenceLatLon() {
// return refLatLon;
// }
//
// public MathTransform getTransform() {
// return transform;
// }
//
// public double getX() {
// return this.x;
// }
//
// public double getY() {
// return this.y;
// }
//
//
// }
// Path: gtfs-validation-lib/src/main/java/com/conveyal/gtfs/service/GeoUtils.java
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
import org.geotools.geometry.GeometryBuilder;
import org.geotools.geometry.jts.JTS;
import org.geotools.referencing.CRS;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.onebusaway.gtfs.model.ShapePoint;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.NoSuchIdentifierException;
import org.opengis.referencing.crs.CRSAuthorityFactory;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.crs.GeographicCRS;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.TransformException;
import com.conveyal.gtfs.model.ProjectedCoordinate;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.PrecisionModel;
package com.conveyal.gtfs.service;
public class GeoUtils {
public static double RADIANS = 2 * Math.PI;
public static MathTransform recentMathTransform = null;
public static GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(),4326);
public static GeometryFactory projectedGeometryFactory = new GeometryFactory(new PrecisionModel());
public static GeometryBuilder builder = new GeometryBuilder(DefaultGeographicCRS.WGS84);
/**
* Converts from a coordinate to The appropriate UTM zone.
*
* @param latlon THE ORDER OF THE COORDINATE MUST BE LAT, LON!
* @return
*/ | public static ProjectedCoordinate convertLatLonToEuclidean( |
dianping/polestar | src/test/java/com/dianping/polestar/store/mysql/dao/impl/QueryDAOImpTest.java | // Path: src/main/java/com/dianping/polestar/store/mysql/dao/QueryDAO.java
// public interface QueryDAO {
//
// public void insertQueryInfo(QueryInfo queryInfo);
//
// public List<QueryInfo> findQueryInfoByUsername(String username);
//
// public void insertQueryProgress(QueryProgress queryProgress);
//
// public QueryProgress findQueryProgressById(String id);
//
// public void insertQueryCancel(QueryCancel qc);
//
// public List<QueryCancel> findQueryCancelWithouHost(String host);
//
// public void deleteQueryCancelById(String id);
// }
//
// Path: src/main/java/com/dianping/polestar/store/mysql/domain/QueryInfo.java
// public class QueryInfo {
// private String sql;
// private String mode;
// private String username;
// private String resultFilePath;
// private long execTime;
// private String addtime;
//
// public QueryInfo() {
// }
//
// public QueryInfo(Query q, QueryResult rs, long starttime) {
// setSql(q.getSql());
// setMode(q.getMode());
// setUsername(q.getUsername());
// setResultFilePath(rs.getResultFilePath());
// setExecTime(rs.getExecTime());
// setAddtime(EnvironmentConstants.DATE_FORMAT.format(new Date(starttime)));
// }
//
// public String getSql() {
// return sql;
// }
//
// public void setSql(String sql) {
// this.sql = sql;
// }
//
// public String getMode() {
// return mode;
// }
//
// public void setMode(String mode) {
// this.mode = mode;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getResultFilePath() {
// return resultFilePath;
// }
//
// public void setResultFilePath(String resultFilePath) {
// this.resultFilePath = resultFilePath;
// }
//
// public long getExecTime() {
// return execTime;
// }
//
// public void setExecTime(long execTime) {
// this.execTime = execTime;
// }
//
// public String getAddtime() {
// return addtime;
// }
//
// public void setAddtime(String addtime) {
// this.addtime = addtime;
// }
//
// @Override
// public String toString() {
// return "QueryInfo [sql=" + sql + ", mode=" + mode + ", username="
// + username + ", resultFilePath=" + resultFilePath
// + ", execTime=" + execTime + ", addtime=" + addtime + "]";
// }
// }
//
// Path: src/main/java/com/dianping/polestar/store/mysql/domain/QueryProgress.java
// public class QueryProgress {
// private String id;
// private String progressInfo;
//
// public QueryProgress() {
// }
//
// public QueryProgress(String id, String progressInfo) {
// this.id = id;
// this.progressInfo = progressInfo;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getProgressInfo() {
// return progressInfo;
// }
//
// public void setProgressInfo(String progressInfo) {
// this.progressInfo = progressInfo;
// }
//
// @Override
// public String toString() {
// return "QueryProgress [id=" + id + ", progressInfo=" + progressInfo
// + "]";
// }
// }
| import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.dianping.polestar.store.mysql.dao.QueryDAO;
import com.dianping.polestar.store.mysql.domain.QueryInfo;
import com.dianping.polestar.store.mysql.domain.QueryProgress; | package com.dianping.polestar.store.mysql.dao.impl;
public class QueryDAOImpTest {
static QueryDAO queryDAOImp;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
AbstractApplicationContext cxt = new ClassPathXmlApplicationContext(
"applicationContext.xml");
queryDAOImp = (QueryDAO) cxt.getBean("queryDaoImpl");
}
@Test
public void testInsertQueryInfo() { | // Path: src/main/java/com/dianping/polestar/store/mysql/dao/QueryDAO.java
// public interface QueryDAO {
//
// public void insertQueryInfo(QueryInfo queryInfo);
//
// public List<QueryInfo> findQueryInfoByUsername(String username);
//
// public void insertQueryProgress(QueryProgress queryProgress);
//
// public QueryProgress findQueryProgressById(String id);
//
// public void insertQueryCancel(QueryCancel qc);
//
// public List<QueryCancel> findQueryCancelWithouHost(String host);
//
// public void deleteQueryCancelById(String id);
// }
//
// Path: src/main/java/com/dianping/polestar/store/mysql/domain/QueryInfo.java
// public class QueryInfo {
// private String sql;
// private String mode;
// private String username;
// private String resultFilePath;
// private long execTime;
// private String addtime;
//
// public QueryInfo() {
// }
//
// public QueryInfo(Query q, QueryResult rs, long starttime) {
// setSql(q.getSql());
// setMode(q.getMode());
// setUsername(q.getUsername());
// setResultFilePath(rs.getResultFilePath());
// setExecTime(rs.getExecTime());
// setAddtime(EnvironmentConstants.DATE_FORMAT.format(new Date(starttime)));
// }
//
// public String getSql() {
// return sql;
// }
//
// public void setSql(String sql) {
// this.sql = sql;
// }
//
// public String getMode() {
// return mode;
// }
//
// public void setMode(String mode) {
// this.mode = mode;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getResultFilePath() {
// return resultFilePath;
// }
//
// public void setResultFilePath(String resultFilePath) {
// this.resultFilePath = resultFilePath;
// }
//
// public long getExecTime() {
// return execTime;
// }
//
// public void setExecTime(long execTime) {
// this.execTime = execTime;
// }
//
// public String getAddtime() {
// return addtime;
// }
//
// public void setAddtime(String addtime) {
// this.addtime = addtime;
// }
//
// @Override
// public String toString() {
// return "QueryInfo [sql=" + sql + ", mode=" + mode + ", username="
// + username + ", resultFilePath=" + resultFilePath
// + ", execTime=" + execTime + ", addtime=" + addtime + "]";
// }
// }
//
// Path: src/main/java/com/dianping/polestar/store/mysql/domain/QueryProgress.java
// public class QueryProgress {
// private String id;
// private String progressInfo;
//
// public QueryProgress() {
// }
//
// public QueryProgress(String id, String progressInfo) {
// this.id = id;
// this.progressInfo = progressInfo;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getProgressInfo() {
// return progressInfo;
// }
//
// public void setProgressInfo(String progressInfo) {
// this.progressInfo = progressInfo;
// }
//
// @Override
// public String toString() {
// return "QueryProgress [id=" + id + ", progressInfo=" + progressInfo
// + "]";
// }
// }
// Path: src/test/java/com/dianping/polestar/store/mysql/dao/impl/QueryDAOImpTest.java
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.dianping.polestar.store.mysql.dao.QueryDAO;
import com.dianping.polestar.store.mysql.domain.QueryInfo;
import com.dianping.polestar.store.mysql.domain.QueryProgress;
package com.dianping.polestar.store.mysql.dao.impl;
public class QueryDAOImpTest {
static QueryDAO queryDAOImp;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
AbstractApplicationContext cxt = new ClassPathXmlApplicationContext(
"applicationContext.xml");
queryDAOImp = (QueryDAO) cxt.getBean("queryDaoImpl");
}
@Test
public void testInsertQueryInfo() { | QueryInfo q = new QueryInfo(); |
dianping/polestar | src/test/java/com/dianping/polestar/store/mysql/dao/impl/QueryDAOImpTest.java | // Path: src/main/java/com/dianping/polestar/store/mysql/dao/QueryDAO.java
// public interface QueryDAO {
//
// public void insertQueryInfo(QueryInfo queryInfo);
//
// public List<QueryInfo> findQueryInfoByUsername(String username);
//
// public void insertQueryProgress(QueryProgress queryProgress);
//
// public QueryProgress findQueryProgressById(String id);
//
// public void insertQueryCancel(QueryCancel qc);
//
// public List<QueryCancel> findQueryCancelWithouHost(String host);
//
// public void deleteQueryCancelById(String id);
// }
//
// Path: src/main/java/com/dianping/polestar/store/mysql/domain/QueryInfo.java
// public class QueryInfo {
// private String sql;
// private String mode;
// private String username;
// private String resultFilePath;
// private long execTime;
// private String addtime;
//
// public QueryInfo() {
// }
//
// public QueryInfo(Query q, QueryResult rs, long starttime) {
// setSql(q.getSql());
// setMode(q.getMode());
// setUsername(q.getUsername());
// setResultFilePath(rs.getResultFilePath());
// setExecTime(rs.getExecTime());
// setAddtime(EnvironmentConstants.DATE_FORMAT.format(new Date(starttime)));
// }
//
// public String getSql() {
// return sql;
// }
//
// public void setSql(String sql) {
// this.sql = sql;
// }
//
// public String getMode() {
// return mode;
// }
//
// public void setMode(String mode) {
// this.mode = mode;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getResultFilePath() {
// return resultFilePath;
// }
//
// public void setResultFilePath(String resultFilePath) {
// this.resultFilePath = resultFilePath;
// }
//
// public long getExecTime() {
// return execTime;
// }
//
// public void setExecTime(long execTime) {
// this.execTime = execTime;
// }
//
// public String getAddtime() {
// return addtime;
// }
//
// public void setAddtime(String addtime) {
// this.addtime = addtime;
// }
//
// @Override
// public String toString() {
// return "QueryInfo [sql=" + sql + ", mode=" + mode + ", username="
// + username + ", resultFilePath=" + resultFilePath
// + ", execTime=" + execTime + ", addtime=" + addtime + "]";
// }
// }
//
// Path: src/main/java/com/dianping/polestar/store/mysql/domain/QueryProgress.java
// public class QueryProgress {
// private String id;
// private String progressInfo;
//
// public QueryProgress() {
// }
//
// public QueryProgress(String id, String progressInfo) {
// this.id = id;
// this.progressInfo = progressInfo;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getProgressInfo() {
// return progressInfo;
// }
//
// public void setProgressInfo(String progressInfo) {
// this.progressInfo = progressInfo;
// }
//
// @Override
// public String toString() {
// return "QueryProgress [id=" + id + ", progressInfo=" + progressInfo
// + "]";
// }
// }
| import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.dianping.polestar.store.mysql.dao.QueryDAO;
import com.dianping.polestar.store.mysql.domain.QueryInfo;
import com.dianping.polestar.store.mysql.domain.QueryProgress; | AbstractApplicationContext cxt = new ClassPathXmlApplicationContext(
"applicationContext.xml");
queryDAOImp = (QueryDAO) cxt.getBean("queryDaoImpl");
}
@Test
public void testInsertQueryInfo() {
QueryInfo q = new QueryInfo();
Date addtime = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
q.setUsername("xxx");
q.setMode("hive");
q.setResultFilePath("hdfs:////test");
q.setSql("show tables;");
q.setExecTime(600L);
q.setAddtime(sdf.format(addtime));
queryDAOImp.insertQueryInfo(q);
}
@Test
public void testGetQueryByUsername() {
List<QueryInfo> qs = queryDAOImp.findQueryInfoByUsername("yukang.chen");
System.out.println(qs.size());
for (int i = 0; i < qs.size(); i++) {
System.out.println(qs.get(i));
}
}
@Test
public void testGetQueryProgress() { | // Path: src/main/java/com/dianping/polestar/store/mysql/dao/QueryDAO.java
// public interface QueryDAO {
//
// public void insertQueryInfo(QueryInfo queryInfo);
//
// public List<QueryInfo> findQueryInfoByUsername(String username);
//
// public void insertQueryProgress(QueryProgress queryProgress);
//
// public QueryProgress findQueryProgressById(String id);
//
// public void insertQueryCancel(QueryCancel qc);
//
// public List<QueryCancel> findQueryCancelWithouHost(String host);
//
// public void deleteQueryCancelById(String id);
// }
//
// Path: src/main/java/com/dianping/polestar/store/mysql/domain/QueryInfo.java
// public class QueryInfo {
// private String sql;
// private String mode;
// private String username;
// private String resultFilePath;
// private long execTime;
// private String addtime;
//
// public QueryInfo() {
// }
//
// public QueryInfo(Query q, QueryResult rs, long starttime) {
// setSql(q.getSql());
// setMode(q.getMode());
// setUsername(q.getUsername());
// setResultFilePath(rs.getResultFilePath());
// setExecTime(rs.getExecTime());
// setAddtime(EnvironmentConstants.DATE_FORMAT.format(new Date(starttime)));
// }
//
// public String getSql() {
// return sql;
// }
//
// public void setSql(String sql) {
// this.sql = sql;
// }
//
// public String getMode() {
// return mode;
// }
//
// public void setMode(String mode) {
// this.mode = mode;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getResultFilePath() {
// return resultFilePath;
// }
//
// public void setResultFilePath(String resultFilePath) {
// this.resultFilePath = resultFilePath;
// }
//
// public long getExecTime() {
// return execTime;
// }
//
// public void setExecTime(long execTime) {
// this.execTime = execTime;
// }
//
// public String getAddtime() {
// return addtime;
// }
//
// public void setAddtime(String addtime) {
// this.addtime = addtime;
// }
//
// @Override
// public String toString() {
// return "QueryInfo [sql=" + sql + ", mode=" + mode + ", username="
// + username + ", resultFilePath=" + resultFilePath
// + ", execTime=" + execTime + ", addtime=" + addtime + "]";
// }
// }
//
// Path: src/main/java/com/dianping/polestar/store/mysql/domain/QueryProgress.java
// public class QueryProgress {
// private String id;
// private String progressInfo;
//
// public QueryProgress() {
// }
//
// public QueryProgress(String id, String progressInfo) {
// this.id = id;
// this.progressInfo = progressInfo;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getProgressInfo() {
// return progressInfo;
// }
//
// public void setProgressInfo(String progressInfo) {
// this.progressInfo = progressInfo;
// }
//
// @Override
// public String toString() {
// return "QueryProgress [id=" + id + ", progressInfo=" + progressInfo
// + "]";
// }
// }
// Path: src/test/java/com/dianping/polestar/store/mysql/dao/impl/QueryDAOImpTest.java
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.dianping.polestar.store.mysql.dao.QueryDAO;
import com.dianping.polestar.store.mysql.domain.QueryInfo;
import com.dianping.polestar.store.mysql.domain.QueryProgress;
AbstractApplicationContext cxt = new ClassPathXmlApplicationContext(
"applicationContext.xml");
queryDAOImp = (QueryDAO) cxt.getBean("queryDaoImpl");
}
@Test
public void testInsertQueryInfo() {
QueryInfo q = new QueryInfo();
Date addtime = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
q.setUsername("xxx");
q.setMode("hive");
q.setResultFilePath("hdfs:////test");
q.setSql("show tables;");
q.setExecTime(600L);
q.setAddtime(sdf.format(addtime));
queryDAOImp.insertQueryInfo(q);
}
@Test
public void testGetQueryByUsername() {
List<QueryInfo> qs = queryDAOImp.findQueryInfoByUsername("yukang.chen");
System.out.println(qs.size());
for (int i = 0; i < qs.size(); i++) {
System.out.println(qs.get(i));
}
}
@Test
public void testGetQueryProgress() { | queryDAOImp.insertQueryProgress(new QueryProgress("11111", |
dianping/polestar | src/main/java/com/dianping/polestar/engine/DummyQueryEngine.java | // Path: src/main/java/com/dianping/polestar/entity/Query.java
// public class Query extends Entity {
// private String sql;
// private String mode;
// private String database;
// private String username;
// private String password;
// private boolean storeResult;
//
// public String getSql() {
// return sql;
// }
//
// public void setSql(String sql) {
// this.sql = sql;
// }
//
// public String getMode() {
// return mode;
// }
//
// public void setMode(String mode) {
// this.mode = mode;
// }
//
// public String getDatabase() {
// return database;
// }
//
// public void setDatabase(String database) {
// this.database = database;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public boolean isStoreResult() {
// return storeResult;
// }
//
// public void setStoreResult(boolean storeResult) {
// this.storeResult = storeResult;
// }
// }
//
// Path: src/main/java/com/dianping/polestar/entity/QueryResult.java
// public final class QueryResult extends Entity {
// private String[] columnNames = new String[]{};
// private List<String[]> data = new ArrayList<String[]>();
// private long execTime = -1L;
// private String errorMsg = "";
// private String resultFilePath = "";
// private Boolean success = false;
//
// public String[] getColumnNames() {
// return columnNames;
// }
// public void setColumnNames(String[] columnNames) {
// this.columnNames = columnNames;
// }
// public List<String[]> getData() {
// return data;
// }
// public void setData(List<String[]> data) {
// this.data = data;
// }
// public long getExecTime() {
// return execTime;
// }
// public void setExecTime(long execTime) {
// this.execTime = execTime;
// }
// public String getErrorMsg() {
// return errorMsg;
// }
// public void setErrorMsg(String errorMsg) {
// this.errorMsg = errorMsg;
// }
// public String getResultFilePath() {
// return resultFilePath;
// }
// public void setResultFilePath(String resultFilePath) {
// this.resultFilePath = resultFilePath;
// }
// public Boolean getSuccess() {
// return success;
// }
// public void setSuccess(Boolean success) {
// this.success = success;
// }
//
// @Override
// public String toString() {
// return "QueryResult [columnNames=" + Arrays.toString(columnNames)
// + ", data=" + data + ", execTime=" + execTime + ", errorMsg="
// + errorMsg + ", resultFilePath=" + resultFilePath
// + ", success=" + success + "]";
// }
// }
| import com.dianping.polestar.entity.Query;
import com.dianping.polestar.entity.QueryResult; | package com.dianping.polestar.engine;
public class DummyQueryEngine implements IQueryEngine {
@Override | // Path: src/main/java/com/dianping/polestar/entity/Query.java
// public class Query extends Entity {
// private String sql;
// private String mode;
// private String database;
// private String username;
// private String password;
// private boolean storeResult;
//
// public String getSql() {
// return sql;
// }
//
// public void setSql(String sql) {
// this.sql = sql;
// }
//
// public String getMode() {
// return mode;
// }
//
// public void setMode(String mode) {
// this.mode = mode;
// }
//
// public String getDatabase() {
// return database;
// }
//
// public void setDatabase(String database) {
// this.database = database;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public boolean isStoreResult() {
// return storeResult;
// }
//
// public void setStoreResult(boolean storeResult) {
// this.storeResult = storeResult;
// }
// }
//
// Path: src/main/java/com/dianping/polestar/entity/QueryResult.java
// public final class QueryResult extends Entity {
// private String[] columnNames = new String[]{};
// private List<String[]> data = new ArrayList<String[]>();
// private long execTime = -1L;
// private String errorMsg = "";
// private String resultFilePath = "";
// private Boolean success = false;
//
// public String[] getColumnNames() {
// return columnNames;
// }
// public void setColumnNames(String[] columnNames) {
// this.columnNames = columnNames;
// }
// public List<String[]> getData() {
// return data;
// }
// public void setData(List<String[]> data) {
// this.data = data;
// }
// public long getExecTime() {
// return execTime;
// }
// public void setExecTime(long execTime) {
// this.execTime = execTime;
// }
// public String getErrorMsg() {
// return errorMsg;
// }
// public void setErrorMsg(String errorMsg) {
// this.errorMsg = errorMsg;
// }
// public String getResultFilePath() {
// return resultFilePath;
// }
// public void setResultFilePath(String resultFilePath) {
// this.resultFilePath = resultFilePath;
// }
// public Boolean getSuccess() {
// return success;
// }
// public void setSuccess(Boolean success) {
// this.success = success;
// }
//
// @Override
// public String toString() {
// return "QueryResult [columnNames=" + Arrays.toString(columnNames)
// + ", data=" + data + ", execTime=" + execTime + ", errorMsg="
// + errorMsg + ", resultFilePath=" + resultFilePath
// + ", success=" + success + "]";
// }
// }
// Path: src/main/java/com/dianping/polestar/engine/DummyQueryEngine.java
import com.dianping.polestar.entity.Query;
import com.dianping.polestar.entity.QueryResult;
package com.dianping.polestar.engine;
public class DummyQueryEngine implements IQueryEngine {
@Override | public QueryResult postQuery(Query query) { |
dianping/polestar | src/main/java/com/dianping/polestar/engine/DummyQueryEngine.java | // Path: src/main/java/com/dianping/polestar/entity/Query.java
// public class Query extends Entity {
// private String sql;
// private String mode;
// private String database;
// private String username;
// private String password;
// private boolean storeResult;
//
// public String getSql() {
// return sql;
// }
//
// public void setSql(String sql) {
// this.sql = sql;
// }
//
// public String getMode() {
// return mode;
// }
//
// public void setMode(String mode) {
// this.mode = mode;
// }
//
// public String getDatabase() {
// return database;
// }
//
// public void setDatabase(String database) {
// this.database = database;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public boolean isStoreResult() {
// return storeResult;
// }
//
// public void setStoreResult(boolean storeResult) {
// this.storeResult = storeResult;
// }
// }
//
// Path: src/main/java/com/dianping/polestar/entity/QueryResult.java
// public final class QueryResult extends Entity {
// private String[] columnNames = new String[]{};
// private List<String[]> data = new ArrayList<String[]>();
// private long execTime = -1L;
// private String errorMsg = "";
// private String resultFilePath = "";
// private Boolean success = false;
//
// public String[] getColumnNames() {
// return columnNames;
// }
// public void setColumnNames(String[] columnNames) {
// this.columnNames = columnNames;
// }
// public List<String[]> getData() {
// return data;
// }
// public void setData(List<String[]> data) {
// this.data = data;
// }
// public long getExecTime() {
// return execTime;
// }
// public void setExecTime(long execTime) {
// this.execTime = execTime;
// }
// public String getErrorMsg() {
// return errorMsg;
// }
// public void setErrorMsg(String errorMsg) {
// this.errorMsg = errorMsg;
// }
// public String getResultFilePath() {
// return resultFilePath;
// }
// public void setResultFilePath(String resultFilePath) {
// this.resultFilePath = resultFilePath;
// }
// public Boolean getSuccess() {
// return success;
// }
// public void setSuccess(Boolean success) {
// this.success = success;
// }
//
// @Override
// public String toString() {
// return "QueryResult [columnNames=" + Arrays.toString(columnNames)
// + ", data=" + data + ", execTime=" + execTime + ", errorMsg="
// + errorMsg + ", resultFilePath=" + resultFilePath
// + ", success=" + success + "]";
// }
// }
| import com.dianping.polestar.entity.Query;
import com.dianping.polestar.entity.QueryResult; | package com.dianping.polestar.engine;
public class DummyQueryEngine implements IQueryEngine {
@Override | // Path: src/main/java/com/dianping/polestar/entity/Query.java
// public class Query extends Entity {
// private String sql;
// private String mode;
// private String database;
// private String username;
// private String password;
// private boolean storeResult;
//
// public String getSql() {
// return sql;
// }
//
// public void setSql(String sql) {
// this.sql = sql;
// }
//
// public String getMode() {
// return mode;
// }
//
// public void setMode(String mode) {
// this.mode = mode;
// }
//
// public String getDatabase() {
// return database;
// }
//
// public void setDatabase(String database) {
// this.database = database;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public boolean isStoreResult() {
// return storeResult;
// }
//
// public void setStoreResult(boolean storeResult) {
// this.storeResult = storeResult;
// }
// }
//
// Path: src/main/java/com/dianping/polestar/entity/QueryResult.java
// public final class QueryResult extends Entity {
// private String[] columnNames = new String[]{};
// private List<String[]> data = new ArrayList<String[]>();
// private long execTime = -1L;
// private String errorMsg = "";
// private String resultFilePath = "";
// private Boolean success = false;
//
// public String[] getColumnNames() {
// return columnNames;
// }
// public void setColumnNames(String[] columnNames) {
// this.columnNames = columnNames;
// }
// public List<String[]> getData() {
// return data;
// }
// public void setData(List<String[]> data) {
// this.data = data;
// }
// public long getExecTime() {
// return execTime;
// }
// public void setExecTime(long execTime) {
// this.execTime = execTime;
// }
// public String getErrorMsg() {
// return errorMsg;
// }
// public void setErrorMsg(String errorMsg) {
// this.errorMsg = errorMsg;
// }
// public String getResultFilePath() {
// return resultFilePath;
// }
// public void setResultFilePath(String resultFilePath) {
// this.resultFilePath = resultFilePath;
// }
// public Boolean getSuccess() {
// return success;
// }
// public void setSuccess(Boolean success) {
// this.success = success;
// }
//
// @Override
// public String toString() {
// return "QueryResult [columnNames=" + Arrays.toString(columnNames)
// + ", data=" + data + ", execTime=" + execTime + ", errorMsg="
// + errorMsg + ", resultFilePath=" + resultFilePath
// + ", success=" + success + "]";
// }
// }
// Path: src/main/java/com/dianping/polestar/engine/DummyQueryEngine.java
import com.dianping.polestar.entity.Query;
import com.dianping.polestar.entity.QueryResult;
package com.dianping.polestar.engine;
public class DummyQueryEngine implements IQueryEngine {
@Override | public QueryResult postQuery(Query query) { |
dianping/polestar | src/main/java/com/dianping/polestar/CancelQueryListener.java | // Path: src/main/java/com/dianping/polestar/jobs/Job.java
// public interface Job {
//
// Integer run() throws Exception;
//
// void cancel();
//
// boolean isCanceled();
//
// }
//
// Path: src/main/java/com/dianping/polestar/jobs/JobManager.java
// public class JobManager {
// private final static Map<String, Job> idToJob = new ConcurrentHashMap<String, Job>(
// 100);
// private final static Map<String, JobContext> idToJobContext = new ConcurrentHashMap<String, JobContext>(
// 100);
//
// public static Job getJobById(String id) {
// return idToJob.get(id);
// }
//
// public static JobContext getJobContextById(String id) {
// return idToJobContext.get(id);
// }
//
// public static void putJob(String id, Job job, JobContext jobctx) {
// synchronized (JobManager.class) {
// idToJob.put(id, job);
// idToJobContext.put(id, jobctx);
// }
// }
//
// public static void removeJob(String id) {
// synchronized (JobManager.class) {
// idToJob.remove(id);
// idToJobContext.remove(id);
// }
// }
// }
//
// Path: src/main/java/com/dianping/polestar/store/mysql/dao/QueryDAO.java
// public interface QueryDAO {
//
// public void insertQueryInfo(QueryInfo queryInfo);
//
// public List<QueryInfo> findQueryInfoByUsername(String username);
//
// public void insertQueryProgress(QueryProgress queryProgress);
//
// public QueryProgress findQueryProgressById(String id);
//
// public void insertQueryCancel(QueryCancel qc);
//
// public List<QueryCancel> findQueryCancelWithouHost(String host);
//
// public void deleteQueryCancelById(String id);
// }
//
// Path: src/main/java/com/dianping/polestar/store/mysql/dao/impl/QueryDAOFactory.java
// public final class QueryDAOFactory {
//
// public static QueryDAO queryDao;
//
// public static QueryDAO getInstance() {
// if (queryDao == null) {
// synchronized (QueryDAOFactory.class) {
// if (queryDao == null) {
// AbstractApplicationContext cxt = new ClassPathXmlApplicationContext(
// "applicationContext.xml");
// queryDao = (QueryDAO) cxt.getBean("queryDaoImpl");
// }
// }
// }
// return queryDao;
// }
// }
//
// Path: src/main/java/com/dianping/polestar/store/mysql/domain/QueryCancel.java
// public class QueryCancel {
// private String id;
// private String host;
//
// public QueryCancel() {
// }
//
// public QueryCancel(String id, String host) {
// this.id = id;
// this.host = host;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getHost() {
// return host;
// }
//
// public void setHost(String host) {
// this.host = host;
// }
// }
| import java.util.List;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.dianping.polestar.jobs.Job;
import com.dianping.polestar.jobs.JobManager;
import com.dianping.polestar.store.mysql.dao.QueryDAO;
import com.dianping.polestar.store.mysql.dao.impl.QueryDAOFactory;
import com.dianping.polestar.store.mysql.domain.QueryCancel; | package com.dianping.polestar;
public class CancelQueryListener implements ServletContextListener {
private final static Log LOG = LogFactory.getLog(CancelQueryListener.class);
private final static long CHECK_DB_INTERVAL_IN_MILLISECONDS = 3000L; | // Path: src/main/java/com/dianping/polestar/jobs/Job.java
// public interface Job {
//
// Integer run() throws Exception;
//
// void cancel();
//
// boolean isCanceled();
//
// }
//
// Path: src/main/java/com/dianping/polestar/jobs/JobManager.java
// public class JobManager {
// private final static Map<String, Job> idToJob = new ConcurrentHashMap<String, Job>(
// 100);
// private final static Map<String, JobContext> idToJobContext = new ConcurrentHashMap<String, JobContext>(
// 100);
//
// public static Job getJobById(String id) {
// return idToJob.get(id);
// }
//
// public static JobContext getJobContextById(String id) {
// return idToJobContext.get(id);
// }
//
// public static void putJob(String id, Job job, JobContext jobctx) {
// synchronized (JobManager.class) {
// idToJob.put(id, job);
// idToJobContext.put(id, jobctx);
// }
// }
//
// public static void removeJob(String id) {
// synchronized (JobManager.class) {
// idToJob.remove(id);
// idToJobContext.remove(id);
// }
// }
// }
//
// Path: src/main/java/com/dianping/polestar/store/mysql/dao/QueryDAO.java
// public interface QueryDAO {
//
// public void insertQueryInfo(QueryInfo queryInfo);
//
// public List<QueryInfo> findQueryInfoByUsername(String username);
//
// public void insertQueryProgress(QueryProgress queryProgress);
//
// public QueryProgress findQueryProgressById(String id);
//
// public void insertQueryCancel(QueryCancel qc);
//
// public List<QueryCancel> findQueryCancelWithouHost(String host);
//
// public void deleteQueryCancelById(String id);
// }
//
// Path: src/main/java/com/dianping/polestar/store/mysql/dao/impl/QueryDAOFactory.java
// public final class QueryDAOFactory {
//
// public static QueryDAO queryDao;
//
// public static QueryDAO getInstance() {
// if (queryDao == null) {
// synchronized (QueryDAOFactory.class) {
// if (queryDao == null) {
// AbstractApplicationContext cxt = new ClassPathXmlApplicationContext(
// "applicationContext.xml");
// queryDao = (QueryDAO) cxt.getBean("queryDaoImpl");
// }
// }
// }
// return queryDao;
// }
// }
//
// Path: src/main/java/com/dianping/polestar/store/mysql/domain/QueryCancel.java
// public class QueryCancel {
// private String id;
// private String host;
//
// public QueryCancel() {
// }
//
// public QueryCancel(String id, String host) {
// this.id = id;
// this.host = host;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getHost() {
// return host;
// }
//
// public void setHost(String host) {
// this.host = host;
// }
// }
// Path: src/main/java/com/dianping/polestar/CancelQueryListener.java
import java.util.List;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.dianping.polestar.jobs.Job;
import com.dianping.polestar.jobs.JobManager;
import com.dianping.polestar.store.mysql.dao.QueryDAO;
import com.dianping.polestar.store.mysql.dao.impl.QueryDAOFactory;
import com.dianping.polestar.store.mysql.domain.QueryCancel;
package com.dianping.polestar;
public class CancelQueryListener implements ServletContextListener {
private final static Log LOG = LogFactory.getLog(CancelQueryListener.class);
private final static long CHECK_DB_INTERVAL_IN_MILLISECONDS = 3000L; | private final QueryDAO queryDao = QueryDAOFactory.getInstance(); |
dianping/polestar | src/main/java/com/dianping/polestar/CancelQueryListener.java | // Path: src/main/java/com/dianping/polestar/jobs/Job.java
// public interface Job {
//
// Integer run() throws Exception;
//
// void cancel();
//
// boolean isCanceled();
//
// }
//
// Path: src/main/java/com/dianping/polestar/jobs/JobManager.java
// public class JobManager {
// private final static Map<String, Job> idToJob = new ConcurrentHashMap<String, Job>(
// 100);
// private final static Map<String, JobContext> idToJobContext = new ConcurrentHashMap<String, JobContext>(
// 100);
//
// public static Job getJobById(String id) {
// return idToJob.get(id);
// }
//
// public static JobContext getJobContextById(String id) {
// return idToJobContext.get(id);
// }
//
// public static void putJob(String id, Job job, JobContext jobctx) {
// synchronized (JobManager.class) {
// idToJob.put(id, job);
// idToJobContext.put(id, jobctx);
// }
// }
//
// public static void removeJob(String id) {
// synchronized (JobManager.class) {
// idToJob.remove(id);
// idToJobContext.remove(id);
// }
// }
// }
//
// Path: src/main/java/com/dianping/polestar/store/mysql/dao/QueryDAO.java
// public interface QueryDAO {
//
// public void insertQueryInfo(QueryInfo queryInfo);
//
// public List<QueryInfo> findQueryInfoByUsername(String username);
//
// public void insertQueryProgress(QueryProgress queryProgress);
//
// public QueryProgress findQueryProgressById(String id);
//
// public void insertQueryCancel(QueryCancel qc);
//
// public List<QueryCancel> findQueryCancelWithouHost(String host);
//
// public void deleteQueryCancelById(String id);
// }
//
// Path: src/main/java/com/dianping/polestar/store/mysql/dao/impl/QueryDAOFactory.java
// public final class QueryDAOFactory {
//
// public static QueryDAO queryDao;
//
// public static QueryDAO getInstance() {
// if (queryDao == null) {
// synchronized (QueryDAOFactory.class) {
// if (queryDao == null) {
// AbstractApplicationContext cxt = new ClassPathXmlApplicationContext(
// "applicationContext.xml");
// queryDao = (QueryDAO) cxt.getBean("queryDaoImpl");
// }
// }
// }
// return queryDao;
// }
// }
//
// Path: src/main/java/com/dianping/polestar/store/mysql/domain/QueryCancel.java
// public class QueryCancel {
// private String id;
// private String host;
//
// public QueryCancel() {
// }
//
// public QueryCancel(String id, String host) {
// this.id = id;
// this.host = host;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getHost() {
// return host;
// }
//
// public void setHost(String host) {
// this.host = host;
// }
// }
| import java.util.List;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.dianping.polestar.jobs.Job;
import com.dianping.polestar.jobs.JobManager;
import com.dianping.polestar.store.mysql.dao.QueryDAO;
import com.dianping.polestar.store.mysql.dao.impl.QueryDAOFactory;
import com.dianping.polestar.store.mysql.domain.QueryCancel; | package com.dianping.polestar;
public class CancelQueryListener implements ServletContextListener {
private final static Log LOG = LogFactory.getLog(CancelQueryListener.class);
private final static long CHECK_DB_INTERVAL_IN_MILLISECONDS = 3000L; | // Path: src/main/java/com/dianping/polestar/jobs/Job.java
// public interface Job {
//
// Integer run() throws Exception;
//
// void cancel();
//
// boolean isCanceled();
//
// }
//
// Path: src/main/java/com/dianping/polestar/jobs/JobManager.java
// public class JobManager {
// private final static Map<String, Job> idToJob = new ConcurrentHashMap<String, Job>(
// 100);
// private final static Map<String, JobContext> idToJobContext = new ConcurrentHashMap<String, JobContext>(
// 100);
//
// public static Job getJobById(String id) {
// return idToJob.get(id);
// }
//
// public static JobContext getJobContextById(String id) {
// return idToJobContext.get(id);
// }
//
// public static void putJob(String id, Job job, JobContext jobctx) {
// synchronized (JobManager.class) {
// idToJob.put(id, job);
// idToJobContext.put(id, jobctx);
// }
// }
//
// public static void removeJob(String id) {
// synchronized (JobManager.class) {
// idToJob.remove(id);
// idToJobContext.remove(id);
// }
// }
// }
//
// Path: src/main/java/com/dianping/polestar/store/mysql/dao/QueryDAO.java
// public interface QueryDAO {
//
// public void insertQueryInfo(QueryInfo queryInfo);
//
// public List<QueryInfo> findQueryInfoByUsername(String username);
//
// public void insertQueryProgress(QueryProgress queryProgress);
//
// public QueryProgress findQueryProgressById(String id);
//
// public void insertQueryCancel(QueryCancel qc);
//
// public List<QueryCancel> findQueryCancelWithouHost(String host);
//
// public void deleteQueryCancelById(String id);
// }
//
// Path: src/main/java/com/dianping/polestar/store/mysql/dao/impl/QueryDAOFactory.java
// public final class QueryDAOFactory {
//
// public static QueryDAO queryDao;
//
// public static QueryDAO getInstance() {
// if (queryDao == null) {
// synchronized (QueryDAOFactory.class) {
// if (queryDao == null) {
// AbstractApplicationContext cxt = new ClassPathXmlApplicationContext(
// "applicationContext.xml");
// queryDao = (QueryDAO) cxt.getBean("queryDaoImpl");
// }
// }
// }
// return queryDao;
// }
// }
//
// Path: src/main/java/com/dianping/polestar/store/mysql/domain/QueryCancel.java
// public class QueryCancel {
// private String id;
// private String host;
//
// public QueryCancel() {
// }
//
// public QueryCancel(String id, String host) {
// this.id = id;
// this.host = host;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getHost() {
// return host;
// }
//
// public void setHost(String host) {
// this.host = host;
// }
// }
// Path: src/main/java/com/dianping/polestar/CancelQueryListener.java
import java.util.List;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.dianping.polestar.jobs.Job;
import com.dianping.polestar.jobs.JobManager;
import com.dianping.polestar.store.mysql.dao.QueryDAO;
import com.dianping.polestar.store.mysql.dao.impl.QueryDAOFactory;
import com.dianping.polestar.store.mysql.domain.QueryCancel;
package com.dianping.polestar;
public class CancelQueryListener implements ServletContextListener {
private final static Log LOG = LogFactory.getLog(CancelQueryListener.class);
private final static long CHECK_DB_INTERVAL_IN_MILLISECONDS = 3000L; | private final QueryDAO queryDao = QueryDAOFactory.getInstance(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.