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
|
---|---|---|---|---|---|---|
doanduyhai/killrvideo-java | src/main/java/killrvideo/events/CassandraMutationError.java | // Path: src/main/java/killrvideo/utils/ExceptionUtils.java
// public class ExceptionUtils {
//
// public static final String mergeStackTrace(Throwable throwable) {
// StringJoiner joiner = new StringJoiner("\n\t", "\n", "\n");
// joiner.add(throwable.getMessage());
// Arrays.asList(throwable.getStackTrace())
// .forEach(stackTraceElement -> joiner.add(stackTraceElement.toString()));
//
// return joiner.toString();
// }
// }
| import com.google.protobuf.GeneratedMessageV3;
import killrvideo.utils.ExceptionUtils; | package killrvideo.events;
/**
* Error bean to be published in BUS.
*
* @author DataStax evangelist team.
*/
public class CassandraMutationError {
/**
* Failed Protobuf requests.
*/
public final GeneratedMessageV3 request;
/**
* Related exception in code.
*/
public final Throwable throwable;
/**
* Default constructor.
*/
public CassandraMutationError(GeneratedMessageV3 request, Throwable throwable) {
this.request = request;
this.throwable = throwable;
}
/**
* Display as an error message.
*/
public String buildErrorLog() {
StringBuilder builder = new StringBuilder();
builder.append(request.toString()).append("\n");
builder.append(throwable.getMessage()).append("\n"); | // Path: src/main/java/killrvideo/utils/ExceptionUtils.java
// public class ExceptionUtils {
//
// public static final String mergeStackTrace(Throwable throwable) {
// StringJoiner joiner = new StringJoiner("\n\t", "\n", "\n");
// joiner.add(throwable.getMessage());
// Arrays.asList(throwable.getStackTrace())
// .forEach(stackTraceElement -> joiner.add(stackTraceElement.toString()));
//
// return joiner.toString();
// }
// }
// Path: src/main/java/killrvideo/events/CassandraMutationError.java
import com.google.protobuf.GeneratedMessageV3;
import killrvideo.utils.ExceptionUtils;
package killrvideo.events;
/**
* Error bean to be published in BUS.
*
* @author DataStax evangelist team.
*/
public class CassandraMutationError {
/**
* Failed Protobuf requests.
*/
public final GeneratedMessageV3 request;
/**
* Related exception in code.
*/
public final Throwable throwable;
/**
* Default constructor.
*/
public CassandraMutationError(GeneratedMessageV3 request, Throwable throwable) {
this.request = request;
this.throwable = throwable;
}
/**
* Display as an error message.
*/
public String buildErrorLog() {
StringBuilder builder = new StringBuilder();
builder.append(request.toString()).append("\n");
builder.append(throwable.getMessage()).append("\n"); | builder.append(ExceptionUtils.mergeStackTrace(throwable)); |
doanduyhai/killrvideo-java | src/main/java/killrvideo/entity/CommentsByUser.java | // Path: src/main/java/killrvideo/utils/TypeConverter.java
// public class TypeConverter {
//
// public static Timestamp instantToTimeStamp(Instant instant) {
// return Timestamp.newBuilder()
// .setSeconds(instant.getEpochSecond())
// .setNanos(instant.getNano()).build();
// }
//
// public static Timestamp epochTimeToTimeStamp(long epoch) {
// return Timestamp.newBuilder().setSeconds(epoch).build();
// }
//
// public static Timestamp dateToTimestamp(Date date) {
// return instantToTimeStamp(date.toInstant());
// }
//
// public static Date dateFromTimestamp(Timestamp timestamp) {
// return Date.from(Instant.ofEpochSecond(timestamp.getSeconds()));
// }
//
// public static TimeUuid uuidToTimeUuid(UUID uuid) {
// return TimeUuid.newBuilder()
// .setValue(uuid.toString())
// .build();
// }
//
// public static Uuid uuidToUuid(UUID uuid) {
// return Uuid.newBuilder()
// .setValue(uuid.toString())
// .build();
// }
//
// /**
// * This method is useful when debugging as an easy way to get a traversal
// * string to use in gremlin or DSE Studio from bytecode.
// * @param traversal
// * @return
// */
// public static String bytecodeToTraversalString(KillrVideoTraversal<Vertex, Vertex> traversal) {
// return org.apache.tinkerpop.gremlin.groovy.jsr223.GroovyTranslator.of("g").translate(traversal.getBytecode());
// }
// }
| import static java.util.UUID.fromString;
import java.io.Serializable;
import java.util.Date;
import java.util.UUID;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;
import com.datastax.driver.mapping.annotations.ClusteringColumn;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.Computed;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import killrvideo.comments.CommentsServiceOuterClass;
import killrvideo.comments.CommentsServiceOuterClass.CommentOnVideoRequest;
import killrvideo.utils.TypeConverter; | package killrvideo.entity;
/**
* Pojo representing DTO for table 'comments_by_user'
*
* @author DataStax evangelist team.
*/
@Table(keyspace = Schema.KEYSPACE, name = Schema.TABLENAME_COMMENTS_BY_USER)
public class CommentsByUser implements Serializable, Schema {
/** Serial. */
private static final long serialVersionUID = -4443951809189156563L;
@PartitionKey
private UUID userid;
@ClusteringColumn
private UUID commentid;
@NotNull
@Column
private UUID videoid;
@Length(min = 1, message = "The comment must not be empty")
@Column
private String comment;
/**
* In order to properly use the @Computed annotation for dateOfComment
* you must execute a query using the mapper with this entity, NOT QueryBuilder.
* If QueryBuilder is used you must use a call to fcall() and pass the CQL function
* needed to it directly. Here is an example pulled from CommentsByVideo.getVideoComments().
* fcall("toTimestamp", QueryBuilder.column("commentid")).as("comment_timestamp")
* This will execute the toTimeStamp() function against the commentid column and return the
* result with an alias of comment_timestamp. Again, reference CommentService.getUserComments()
* or CommentService.getVideoComments() for examples of how to implement.
*/
@NotNull
@Computed("toTimestamp(commentid)")
private Date dateOfComment;
/**
* Default constructor (reflection)
*/
public CommentsByUser() {}
/**
* Constructor with all parameters.
*/
public CommentsByUser(UUID userid, UUID commentid, UUID videoid, String comment) {
this.userid = userid;
this.commentid = commentid;
this.videoid = videoid;
this.comment = comment;
}
/**
* Constructor from GRPC generated request.
*/
public CommentsByUser(CommentOnVideoRequest request) {
this.userid = fromString(request.getUserId().getValue());
this.commentid = fromString(request.getCommentId().getValue());
this.videoid = fromString(request.getVideoId().getValue());
this.comment = request.getComment();
}
/**
* Mapping to GRPC generated classes.
*/
public CommentsServiceOuterClass.UserComment toUserComment() {
return CommentsServiceOuterClass.UserComment
.newBuilder()
.setComment(comment) | // Path: src/main/java/killrvideo/utils/TypeConverter.java
// public class TypeConverter {
//
// public static Timestamp instantToTimeStamp(Instant instant) {
// return Timestamp.newBuilder()
// .setSeconds(instant.getEpochSecond())
// .setNanos(instant.getNano()).build();
// }
//
// public static Timestamp epochTimeToTimeStamp(long epoch) {
// return Timestamp.newBuilder().setSeconds(epoch).build();
// }
//
// public static Timestamp dateToTimestamp(Date date) {
// return instantToTimeStamp(date.toInstant());
// }
//
// public static Date dateFromTimestamp(Timestamp timestamp) {
// return Date.from(Instant.ofEpochSecond(timestamp.getSeconds()));
// }
//
// public static TimeUuid uuidToTimeUuid(UUID uuid) {
// return TimeUuid.newBuilder()
// .setValue(uuid.toString())
// .build();
// }
//
// public static Uuid uuidToUuid(UUID uuid) {
// return Uuid.newBuilder()
// .setValue(uuid.toString())
// .build();
// }
//
// /**
// * This method is useful when debugging as an easy way to get a traversal
// * string to use in gremlin or DSE Studio from bytecode.
// * @param traversal
// * @return
// */
// public static String bytecodeToTraversalString(KillrVideoTraversal<Vertex, Vertex> traversal) {
// return org.apache.tinkerpop.gremlin.groovy.jsr223.GroovyTranslator.of("g").translate(traversal.getBytecode());
// }
// }
// Path: src/main/java/killrvideo/entity/CommentsByUser.java
import static java.util.UUID.fromString;
import java.io.Serializable;
import java.util.Date;
import java.util.UUID;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;
import com.datastax.driver.mapping.annotations.ClusteringColumn;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.Computed;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import killrvideo.comments.CommentsServiceOuterClass;
import killrvideo.comments.CommentsServiceOuterClass.CommentOnVideoRequest;
import killrvideo.utils.TypeConverter;
package killrvideo.entity;
/**
* Pojo representing DTO for table 'comments_by_user'
*
* @author DataStax evangelist team.
*/
@Table(keyspace = Schema.KEYSPACE, name = Schema.TABLENAME_COMMENTS_BY_USER)
public class CommentsByUser implements Serializable, Schema {
/** Serial. */
private static final long serialVersionUID = -4443951809189156563L;
@PartitionKey
private UUID userid;
@ClusteringColumn
private UUID commentid;
@NotNull
@Column
private UUID videoid;
@Length(min = 1, message = "The comment must not be empty")
@Column
private String comment;
/**
* In order to properly use the @Computed annotation for dateOfComment
* you must execute a query using the mapper with this entity, NOT QueryBuilder.
* If QueryBuilder is used you must use a call to fcall() and pass the CQL function
* needed to it directly. Here is an example pulled from CommentsByVideo.getVideoComments().
* fcall("toTimestamp", QueryBuilder.column("commentid")).as("comment_timestamp")
* This will execute the toTimeStamp() function against the commentid column and return the
* result with an alias of comment_timestamp. Again, reference CommentService.getUserComments()
* or CommentService.getVideoComments() for examples of how to implement.
*/
@NotNull
@Computed("toTimestamp(commentid)")
private Date dateOfComment;
/**
* Default constructor (reflection)
*/
public CommentsByUser() {}
/**
* Constructor with all parameters.
*/
public CommentsByUser(UUID userid, UUID commentid, UUID videoid, String comment) {
this.userid = userid;
this.commentid = commentid;
this.videoid = videoid;
this.comment = comment;
}
/**
* Constructor from GRPC generated request.
*/
public CommentsByUser(CommentOnVideoRequest request) {
this.userid = fromString(request.getUserId().getValue());
this.commentid = fromString(request.getCommentId().getValue());
this.videoid = fromString(request.getVideoId().getValue());
this.comment = request.getComment();
}
/**
* Mapping to GRPC generated classes.
*/
public CommentsServiceOuterClass.UserComment toUserComment() {
return CommentsServiceOuterClass.UserComment
.newBuilder()
.setComment(comment) | .setCommentId(TypeConverter.uuidToTimeUuid(commentid)) |
doanduyhai/killrvideo-java | src/main/java/killrvideo/events/CassandraMutationErrorHandler.java | // Path: src/main/java/killrvideo/configuration/KillrVideoConfiguration.java
// @Configuration
// public class KillrVideoConfiguration {
//
// // --- Global Infos
//
// @Value("${killrvideo.application.name:KillrVideo}")
// private String applicationName;
//
// @Value("${killrvideo.application.instance.id: 0}")
// private int applicationInstanceId;
//
// @Value("${killrvideo.server.port: 8899}")
// private int applicationPort;
//
// @Value("#{environment.KILLRVIDEO_HOST_IP}")
// private String applicationHost;
//
// @Value("${killrvideo.cassandra.mutation-error-log: /tmp/killrvideo-mutation-errors.log}")
// private String mutationErrorLog;
//
// // --- ThreadPool Settings
//
// @Value("${killrvideo.threadpool.min.threads:5}")
// private int minThreads;
//
// @Value("${killrvideo.threadpool.max.threads:10}")
// private int maxThreads;
//
// @Value("${killrvideo.thread.ttl.seconds:60}")
// private int threadsTTLSeconds;
//
// @Value("${killrvideo.thread.queue.size:1000}")
// private int threadPoolQueueSize;
//
// // --- Bean definition
//
// @Bean
// public EventBus createEventBus() {
// return new EventBus("killrvideo_event_bus");
// }
//
// /**
// * Initialize the threadPool.
// *
// * @return
// * current executor for this
// */
// @Bean(destroyMethod = "shutdownNow")
// public ExecutorService threadPool() {
// return new ThreadPoolExecutor(getMinThreads(), getMaxThreads(),
// getThreadsTTLSeconds(), TimeUnit.SECONDS,
// new LinkedBlockingQueue<>(getThreadPoolQueueSize()),
// new KillrVideoThreadFactory());
// }
//
// @Bean
// public Validator getBeanValidator() {
// return Validation.buildDefaultValidatorFactory().getValidator();
// }
//
// /**
// * Getter for attribute 'applicationName'.
// *
// * @return
// * current value of 'applicationName'
// */
// public String getApplicationName() {
// return applicationName;
// }
//
// /**
// * Getter for attribute 'applicationInstanceId'.
// *
// * @return
// * current value of 'applicationInstanceId'
// */
// public int getApplicationInstanceId() {
// return applicationInstanceId;
// }
//
// /**
// * Getter for attribute 'applicationPort'.
// *
// * @return
// * current value of 'applicationPort'
// */
// public int getApplicationPort() {
// return applicationPort;
// }
//
// /**
// * Getter for attribute 'mutationErrorLog'.
// *
// * @return
// * current value of 'mutationErrorLog'
// */
// public String getMutationErrorLog() {
// return mutationErrorLog;
// }
//
// /**
// * Getter for attribute 'minThreads'.
// *
// * @return
// * current value of 'minThreads'
// */
// public int getMinThreads() {
// return minThreads;
// }
//
// /**
// * Getter for attribute 'maxThreads'.
// *
// * @return
// * current value of 'maxThreads'
// */
// public int getMaxThreads() {
// return maxThreads;
// }
//
// /**
// * Getter for attribute 'threadsTTLSeconds'.
// *
// * @return
// * current value of 'threadsTTLSeconds'
// */
// public int getThreadsTTLSeconds() {
// return threadsTTLSeconds;
// }
//
// /**
// * Getter for attribute 'threadPoolQueueSize'.
// *
// * @return
// * current value of 'threadPoolQueueSize'
// */
// public int getThreadPoolQueueSize() {
// return threadPoolQueueSize;
// }
//
// /**
// * Getter for attribute 'applicationHost'.
// *
// * @return
// * current value of 'applicationHost'
// */
// public String getApplicationHost() {
// return applicationHost;
// }
//
// }
| import java.io.FileNotFoundException;
import java.io.PrintWriter;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.google.common.eventbus.Subscribe;
import killrvideo.configuration.KillrVideoConfiguration; | package killrvideo.events;
/**
* Catch exceptions and create a {@link CassandraMutationError} in EventBus.
*
* @author DataStax evangelist team.
*/
@Component
public class CassandraMutationErrorHandler {
/** LOGGER for the class. */
private static Logger LOGGER = LoggerFactory.getLogger(CassandraMutationErrorHandler.class);
@Inject | // Path: src/main/java/killrvideo/configuration/KillrVideoConfiguration.java
// @Configuration
// public class KillrVideoConfiguration {
//
// // --- Global Infos
//
// @Value("${killrvideo.application.name:KillrVideo}")
// private String applicationName;
//
// @Value("${killrvideo.application.instance.id: 0}")
// private int applicationInstanceId;
//
// @Value("${killrvideo.server.port: 8899}")
// private int applicationPort;
//
// @Value("#{environment.KILLRVIDEO_HOST_IP}")
// private String applicationHost;
//
// @Value("${killrvideo.cassandra.mutation-error-log: /tmp/killrvideo-mutation-errors.log}")
// private String mutationErrorLog;
//
// // --- ThreadPool Settings
//
// @Value("${killrvideo.threadpool.min.threads:5}")
// private int minThreads;
//
// @Value("${killrvideo.threadpool.max.threads:10}")
// private int maxThreads;
//
// @Value("${killrvideo.thread.ttl.seconds:60}")
// private int threadsTTLSeconds;
//
// @Value("${killrvideo.thread.queue.size:1000}")
// private int threadPoolQueueSize;
//
// // --- Bean definition
//
// @Bean
// public EventBus createEventBus() {
// return new EventBus("killrvideo_event_bus");
// }
//
// /**
// * Initialize the threadPool.
// *
// * @return
// * current executor for this
// */
// @Bean(destroyMethod = "shutdownNow")
// public ExecutorService threadPool() {
// return new ThreadPoolExecutor(getMinThreads(), getMaxThreads(),
// getThreadsTTLSeconds(), TimeUnit.SECONDS,
// new LinkedBlockingQueue<>(getThreadPoolQueueSize()),
// new KillrVideoThreadFactory());
// }
//
// @Bean
// public Validator getBeanValidator() {
// return Validation.buildDefaultValidatorFactory().getValidator();
// }
//
// /**
// * Getter for attribute 'applicationName'.
// *
// * @return
// * current value of 'applicationName'
// */
// public String getApplicationName() {
// return applicationName;
// }
//
// /**
// * Getter for attribute 'applicationInstanceId'.
// *
// * @return
// * current value of 'applicationInstanceId'
// */
// public int getApplicationInstanceId() {
// return applicationInstanceId;
// }
//
// /**
// * Getter for attribute 'applicationPort'.
// *
// * @return
// * current value of 'applicationPort'
// */
// public int getApplicationPort() {
// return applicationPort;
// }
//
// /**
// * Getter for attribute 'mutationErrorLog'.
// *
// * @return
// * current value of 'mutationErrorLog'
// */
// public String getMutationErrorLog() {
// return mutationErrorLog;
// }
//
// /**
// * Getter for attribute 'minThreads'.
// *
// * @return
// * current value of 'minThreads'
// */
// public int getMinThreads() {
// return minThreads;
// }
//
// /**
// * Getter for attribute 'maxThreads'.
// *
// * @return
// * current value of 'maxThreads'
// */
// public int getMaxThreads() {
// return maxThreads;
// }
//
// /**
// * Getter for attribute 'threadsTTLSeconds'.
// *
// * @return
// * current value of 'threadsTTLSeconds'
// */
// public int getThreadsTTLSeconds() {
// return threadsTTLSeconds;
// }
//
// /**
// * Getter for attribute 'threadPoolQueueSize'.
// *
// * @return
// * current value of 'threadPoolQueueSize'
// */
// public int getThreadPoolQueueSize() {
// return threadPoolQueueSize;
// }
//
// /**
// * Getter for attribute 'applicationHost'.
// *
// * @return
// * current value of 'applicationHost'
// */
// public String getApplicationHost() {
// return applicationHost;
// }
//
// }
// Path: src/main/java/killrvideo/events/CassandraMutationErrorHandler.java
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.google.common.eventbus.Subscribe;
import killrvideo.configuration.KillrVideoConfiguration;
package killrvideo.events;
/**
* Catch exceptions and create a {@link CassandraMutationError} in EventBus.
*
* @author DataStax evangelist team.
*/
@Component
public class CassandraMutationErrorHandler {
/** LOGGER for the class. */
private static Logger LOGGER = LoggerFactory.getLogger(CassandraMutationErrorHandler.class);
@Inject | private KillrVideoConfiguration config; |
doanduyhai/killrvideo-java | src/main/java/killrvideo/entity/VideoPlaybackStats.java | // Path: src/main/java/killrvideo/utils/TypeConverter.java
// public class TypeConverter {
//
// public static Timestamp instantToTimeStamp(Instant instant) {
// return Timestamp.newBuilder()
// .setSeconds(instant.getEpochSecond())
// .setNanos(instant.getNano()).build();
// }
//
// public static Timestamp epochTimeToTimeStamp(long epoch) {
// return Timestamp.newBuilder().setSeconds(epoch).build();
// }
//
// public static Timestamp dateToTimestamp(Date date) {
// return instantToTimeStamp(date.toInstant());
// }
//
// public static Date dateFromTimestamp(Timestamp timestamp) {
// return Date.from(Instant.ofEpochSecond(timestamp.getSeconds()));
// }
//
// public static TimeUuid uuidToTimeUuid(UUID uuid) {
// return TimeUuid.newBuilder()
// .setValue(uuid.toString())
// .build();
// }
//
// public static Uuid uuidToUuid(UUID uuid) {
// return Uuid.newBuilder()
// .setValue(uuid.toString())
// .build();
// }
//
// /**
// * This method is useful when debugging as an easy way to get a traversal
// * string to use in gremlin or DSE Studio from bytecode.
// * @param traversal
// * @return
// */
// public static String bytecodeToTraversalString(KillrVideoTraversal<Vertex, Vertex> traversal) {
// return org.apache.tinkerpop.gremlin.groovy.jsr223.GroovyTranslator.of("g").translate(traversal.getBytecode());
// }
// }
| import java.io.Serializable;
import java.util.Optional;
import java.util.UUID;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import killrvideo.statistics.StatisticsServiceOuterClass.PlayStats;
import killrvideo.utils.TypeConverter; | package killrvideo.entity;
/**
* Pojo representing DTO for table 'video_playback_stats'.
*
* @author DataStax evangelist team.
*/
@Table(keyspace = Schema.KEYSPACE, name = Schema.TABLENAME_PLAYBACK_STATS)
public class VideoPlaybackStats implements Serializable {
/** Serial. */
private static final long serialVersionUID = -8636413035520458200L;
@PartitionKey
private UUID videoid;
/**
* "views" column is a counter type in the underlying DSE database. As of driver version 3.2 there
* is no "@Counter" annotation that I know of. No worries though, just use the incr() function
* while using the QueryBuilder. Something similar to with(QueryBuilder.incr("views")).
*/
@Column
private Long views;
/**
* Mapping to generated GPRC beans.
*/
public PlayStats toPlayStats() {
return PlayStats.newBuilder() | // Path: src/main/java/killrvideo/utils/TypeConverter.java
// public class TypeConverter {
//
// public static Timestamp instantToTimeStamp(Instant instant) {
// return Timestamp.newBuilder()
// .setSeconds(instant.getEpochSecond())
// .setNanos(instant.getNano()).build();
// }
//
// public static Timestamp epochTimeToTimeStamp(long epoch) {
// return Timestamp.newBuilder().setSeconds(epoch).build();
// }
//
// public static Timestamp dateToTimestamp(Date date) {
// return instantToTimeStamp(date.toInstant());
// }
//
// public static Date dateFromTimestamp(Timestamp timestamp) {
// return Date.from(Instant.ofEpochSecond(timestamp.getSeconds()));
// }
//
// public static TimeUuid uuidToTimeUuid(UUID uuid) {
// return TimeUuid.newBuilder()
// .setValue(uuid.toString())
// .build();
// }
//
// public static Uuid uuidToUuid(UUID uuid) {
// return Uuid.newBuilder()
// .setValue(uuid.toString())
// .build();
// }
//
// /**
// * This method is useful when debugging as an easy way to get a traversal
// * string to use in gremlin or DSE Studio from bytecode.
// * @param traversal
// * @return
// */
// public static String bytecodeToTraversalString(KillrVideoTraversal<Vertex, Vertex> traversal) {
// return org.apache.tinkerpop.gremlin.groovy.jsr223.GroovyTranslator.of("g").translate(traversal.getBytecode());
// }
// }
// Path: src/main/java/killrvideo/entity/VideoPlaybackStats.java
import java.io.Serializable;
import java.util.Optional;
import java.util.UUID;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import killrvideo.statistics.StatisticsServiceOuterClass.PlayStats;
import killrvideo.utils.TypeConverter;
package killrvideo.entity;
/**
* Pojo representing DTO for table 'video_playback_stats'.
*
* @author DataStax evangelist team.
*/
@Table(keyspace = Schema.KEYSPACE, name = Schema.TABLENAME_PLAYBACK_STATS)
public class VideoPlaybackStats implements Serializable {
/** Serial. */
private static final long serialVersionUID = -8636413035520458200L;
@PartitionKey
private UUID videoid;
/**
* "views" column is a counter type in the underlying DSE database. As of driver version 3.2 there
* is no "@Counter" annotation that I know of. No worries though, just use the incr() function
* while using the QueryBuilder. Something similar to with(QueryBuilder.incr("views")).
*/
@Column
private Long views;
/**
* Mapping to generated GPRC beans.
*/
public PlayStats toPlayStats() {
return PlayStats.newBuilder() | .setVideoId(TypeConverter.uuidToUuid(videoid)) |
Pedro12909/RexCord | src/test/java/utils/XmlParserTest.java | // Path: src/main/java/model/Configuration.java
// public final class Configuration {
//
// /**
// * token
// */
// private String token;
//
// /**
// * prefix
// */
// private String prefix;
//
// /**
// * banned commands
// */
// private String bannedCommands;
//
// /**
// * listen channels
// */
// private List<Long> listenChannels;
//
// /**
// * giphy api key
// */
// private String apiGiphyKey;
//
// /**
// * @return token
// */
// public String getToken() {
// return token;
// }
//
// /**
// * @param token
// * sets the token
// */
// public void setToken(String token) {
// this.token = token;
// }
//
// /**
// * @return prefix
// */
// public String getPrefix() {
// return prefix;
// }
//
// /**
// * @param prefix
// * sets the prefix
// */
// public void setPrefix(String prefix) {
// this.prefix = prefix;
// }
//
// /**
// * @return bannedCommands
// */
// public String getBannedCommands() {
// return bannedCommands;
// }
//
// /**
// * sets banned comments
// * @param bannedCommands the banned commands
// */
// public void setBannedCommands(String bannedCommands) {
// this.bannedCommands = bannedCommands;
// }
//
// /**
// * @return listenChannels
// */
// public List<Long> getListenChannels() {
// return listenChannels;
// }
//
// /**
// * @param listenChannels
// * sets listenChannels
// */
// public void setListenChannels(List<Long> listenChannels) {
// this.listenChannels = listenChannels;
// }
//
// /**
// * @return apiGiphyKey
// */
// public String getApiGiphyKey() {
// return apiGiphyKey;
// }
//
// /**
// * @param apiGiphyKey
// * sets giphyApiKey
// */
// public void setApiGiphyKey(String apiGiphyKey) {
// this.apiGiphyKey = apiGiphyKey;
// }
//
// /**
// * verifies if the token has already been set
// * @return true if the token has been set, false otherwise
// */
// public boolean isTokenSet() {
// return this.token != null && !this.token.isEmpty();
// }
//
// /**
// * verifies if the prefix has already been set
// * @return true if the prefix has been set, false otherwise
// */
// public boolean isPrefixSet() {
// return this.prefix != null && !this.prefix.isEmpty();
// }
//
// /**
// * verifies if bannedCommands has already been set
// * @return true if bannedCommands has been set, false otherwise
// */
// public boolean isBannedCommandsSet() {
// return this.bannedCommands != null && !this.bannedCommands.isEmpty();
// }
//
// /**
// * verifies if giphyApiKey has already been set
// * @return true if giphyApiKey has been set, false otherwise
// */
// public boolean isApiGiphyKeySet() {
// return this.apiGiphyKey != null && !this.apiGiphyKey.isEmpty();
// }
//
// /**
// * verifies if listenChannels have already been set
// * @return true if listenChannels has been set, false otherwise
// */
// public boolean isListenChannelsSet() {
// return this.listenChannels != null && !this.listenChannels.isEmpty();
// }
// }
| import model.Configuration;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.*; | package utils;
/**
* Created by thales minussi on 28/09/17.
* https://github.com/tminussi
*/
public class XmlParserTest {
@Test
public void parseXmlShouldReturnConfiguration() throws IOException { | // Path: src/main/java/model/Configuration.java
// public final class Configuration {
//
// /**
// * token
// */
// private String token;
//
// /**
// * prefix
// */
// private String prefix;
//
// /**
// * banned commands
// */
// private String bannedCommands;
//
// /**
// * listen channels
// */
// private List<Long> listenChannels;
//
// /**
// * giphy api key
// */
// private String apiGiphyKey;
//
// /**
// * @return token
// */
// public String getToken() {
// return token;
// }
//
// /**
// * @param token
// * sets the token
// */
// public void setToken(String token) {
// this.token = token;
// }
//
// /**
// * @return prefix
// */
// public String getPrefix() {
// return prefix;
// }
//
// /**
// * @param prefix
// * sets the prefix
// */
// public void setPrefix(String prefix) {
// this.prefix = prefix;
// }
//
// /**
// * @return bannedCommands
// */
// public String getBannedCommands() {
// return bannedCommands;
// }
//
// /**
// * sets banned comments
// * @param bannedCommands the banned commands
// */
// public void setBannedCommands(String bannedCommands) {
// this.bannedCommands = bannedCommands;
// }
//
// /**
// * @return listenChannels
// */
// public List<Long> getListenChannels() {
// return listenChannels;
// }
//
// /**
// * @param listenChannels
// * sets listenChannels
// */
// public void setListenChannels(List<Long> listenChannels) {
// this.listenChannels = listenChannels;
// }
//
// /**
// * @return apiGiphyKey
// */
// public String getApiGiphyKey() {
// return apiGiphyKey;
// }
//
// /**
// * @param apiGiphyKey
// * sets giphyApiKey
// */
// public void setApiGiphyKey(String apiGiphyKey) {
// this.apiGiphyKey = apiGiphyKey;
// }
//
// /**
// * verifies if the token has already been set
// * @return true if the token has been set, false otherwise
// */
// public boolean isTokenSet() {
// return this.token != null && !this.token.isEmpty();
// }
//
// /**
// * verifies if the prefix has already been set
// * @return true if the prefix has been set, false otherwise
// */
// public boolean isPrefixSet() {
// return this.prefix != null && !this.prefix.isEmpty();
// }
//
// /**
// * verifies if bannedCommands has already been set
// * @return true if bannedCommands has been set, false otherwise
// */
// public boolean isBannedCommandsSet() {
// return this.bannedCommands != null && !this.bannedCommands.isEmpty();
// }
//
// /**
// * verifies if giphyApiKey has already been set
// * @return true if giphyApiKey has been set, false otherwise
// */
// public boolean isApiGiphyKeySet() {
// return this.apiGiphyKey != null && !this.apiGiphyKey.isEmpty();
// }
//
// /**
// * verifies if listenChannels have already been set
// * @return true if listenChannels has been set, false otherwise
// */
// public boolean isListenChannelsSet() {
// return this.listenChannels != null && !this.listenChannels.isEmpty();
// }
// }
// Path: src/test/java/utils/XmlParserTest.java
import model.Configuration;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.*;
package utils;
/**
* Created by thales minussi on 28/09/17.
* https://github.com/tminussi
*/
public class XmlParserTest {
@Test
public void parseXmlShouldReturnConfiguration() throws IOException { | Configuration configuration = XmlParser.parseXml("config/example_config.xml", Configuration.class); |
skyscreamer/JSONassert | src/main/java/org/skyscreamer/jsonassert/JSONParser.java | // Path: src/main/java/org/json/JSONString.java
// public interface JSONString {
//
// /**
// * The toJSONString method allows a class to produce its own JSON
// * serialization.
// *
// * @return String representation of JSON object
// * */
// String toJSONString();
//
// }
| import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONString; | /*
* 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.skyscreamer.jsonassert;
/**
* Simple JSON parsing utility.
*/
public class JSONParser {
// regular expression to match a number in JSON format. see http://www.json.org/fatfree.html.
// "A number can be represented as integer, real, or floating point. JSON does not support octal or hex
// ... [or] NaN or Infinity".
private static final String NUMBER_REGEX = "-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?";
private JSONParser() {}
/**
* Takes a JSON string and returns either a {@link org.json.JSONObject} or {@link org.json.JSONArray},
* depending on whether the string represents an object or an array.
*
* @param s Raw JSON string to be parsed
* @return JSONObject or JSONArray
* @throws JSONException JSON parsing error
*/
public static Object parseJSON(final String s) throws JSONException {
if (s.trim().startsWith("{")) {
return new JSONObject(s);
}
else if (s.trim().startsWith("[")) {
return new JSONArray(s);
} else if (s.trim().startsWith("\"")
|| s.trim().matches(NUMBER_REGEX)) { | // Path: src/main/java/org/json/JSONString.java
// public interface JSONString {
//
// /**
// * The toJSONString method allows a class to produce its own JSON
// * serialization.
// *
// * @return String representation of JSON object
// * */
// String toJSONString();
//
// }
// Path: src/main/java/org/skyscreamer/jsonassert/JSONParser.java
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONString;
/*
* 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.skyscreamer.jsonassert;
/**
* Simple JSON parsing utility.
*/
public class JSONParser {
// regular expression to match a number in JSON format. see http://www.json.org/fatfree.html.
// "A number can be represented as integer, real, or floating point. JSON does not support octal or hex
// ... [or] NaN or Infinity".
private static final String NUMBER_REGEX = "-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?";
private JSONParser() {}
/**
* Takes a JSON string and returns either a {@link org.json.JSONObject} or {@link org.json.JSONArray},
* depending on whether the string represents an object or an array.
*
* @param s Raw JSON string to be parsed
* @return JSONObject or JSONArray
* @throws JSONException JSON parsing error
*/
public static Object parseJSON(final String s) throws JSONException {
if (s.trim().startsWith("{")) {
return new JSONObject(s);
}
else if (s.trim().startsWith("[")) {
return new JSONArray(s);
} else if (s.trim().startsWith("\"")
|| s.trim().matches(NUMBER_REGEX)) { | return new JSONString() { |
skyscreamer/JSONassert | src/test/java/org/skyscreamer/jsonassert/JSONCompareTest.java | // Path: src/main/java/org/skyscreamer/jsonassert/JSONCompare.java
// public static JSONCompareResult compareJSON(String expectedStr, String actualStr, JSONComparator comparator)
// throws JSONException {
// Object expected = JSONParser.parseJSON(expectedStr);
// Object actual = JSONParser.parseJSON(actualStr);
// if ((expected instanceof JSONObject) && (actual instanceof JSONObject)) {
// return compareJSON((JSONObject) expected, (JSONObject) actual, comparator);
// }
// else if ((expected instanceof JSONArray) && (actual instanceof JSONArray)) {
// return compareJSON((JSONArray)expected, (JSONArray)actual, comparator);
// }
// else if (expected instanceof JSONString && actual instanceof JSONString) {
// return compareJson((JSONString) expected, (JSONString) actual);
// }
// else if (expected instanceof JSONObject) {
// return new JSONCompareResult().fail("", expected, actual);
// }
// else {
// return new JSONCompareResult().fail("", expected, actual);
// }
// }
| import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.skyscreamer.jsonassert.JSONCompare.compareJSON;
import static org.skyscreamer.jsonassert.JSONCompareMode.LENIENT;
import static org.skyscreamer.jsonassert.JSONCompareMode.NON_EXTENSIBLE;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.json.JSONException;
import org.junit.Test;
import org.junit.internal.matchers.TypeSafeMatcher; | /*
* 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.skyscreamer.jsonassert;
/**
* Unit tests for {@code JSONCompare}.
*/
public class JSONCompareTest {
@Test
public void succeedsWithEmptyArrays() throws JSONException { | // Path: src/main/java/org/skyscreamer/jsonassert/JSONCompare.java
// public static JSONCompareResult compareJSON(String expectedStr, String actualStr, JSONComparator comparator)
// throws JSONException {
// Object expected = JSONParser.parseJSON(expectedStr);
// Object actual = JSONParser.parseJSON(actualStr);
// if ((expected instanceof JSONObject) && (actual instanceof JSONObject)) {
// return compareJSON((JSONObject) expected, (JSONObject) actual, comparator);
// }
// else if ((expected instanceof JSONArray) && (actual instanceof JSONArray)) {
// return compareJSON((JSONArray)expected, (JSONArray)actual, comparator);
// }
// else if (expected instanceof JSONString && actual instanceof JSONString) {
// return compareJson((JSONString) expected, (JSONString) actual);
// }
// else if (expected instanceof JSONObject) {
// return new JSONCompareResult().fail("", expected, actual);
// }
// else {
// return new JSONCompareResult().fail("", expected, actual);
// }
// }
// Path: src/test/java/org/skyscreamer/jsonassert/JSONCompareTest.java
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.skyscreamer.jsonassert.JSONCompare.compareJSON;
import static org.skyscreamer.jsonassert.JSONCompareMode.LENIENT;
import static org.skyscreamer.jsonassert.JSONCompareMode.NON_EXTENSIBLE;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.json.JSONException;
import org.junit.Test;
import org.junit.internal.matchers.TypeSafeMatcher;
/*
* 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.skyscreamer.jsonassert;
/**
* Unit tests for {@code JSONCompare}.
*/
public class JSONCompareTest {
@Test
public void succeedsWithEmptyArrays() throws JSONException { | assertTrue(compareJSON("[]", "[]", LENIENT).passed()); |
skyscreamer/JSONassert | src/test/java/org/skyscreamer/jsonassert/JSONAssertTest.java | // Path: src/main/java/org/skyscreamer/jsonassert/comparator/CustomComparator.java
// public class CustomComparator extends DefaultComparator {
//
// private final Collection<Customization> customizations;
//
// public CustomComparator(JSONCompareMode mode, Customization... customizations) {
// super(mode);
// this.customizations = Arrays.asList(customizations);
// }
//
// @Override
// public void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException {
// Customization customization = getCustomization(prefix);
// if (customization != null) {
// try {
// if (!customization.matches(prefix, actualValue, expectedValue, result)) {
// result.fail(prefix, expectedValue, actualValue);
// }
// }
// catch (ValueMatcherException e) {
// result.fail(prefix, e);
// }
// } else {
// super.compareValues(prefix, expectedValue, actualValue, result);
// }
// }
//
// private Customization getCustomization(String path) {
// for (Customization c : customizations)
// if (c.appliesToPath(path))
// return c;
// return null;
// }
// }
//
// Path: src/main/java/org/skyscreamer/jsonassert/comparator/JSONComparator.java
// public interface JSONComparator {
//
// /**
// * Compares two {@link JSONObject}s and returns the result of the comparison in a {@link JSONCompareResult} object.
// *
// * @param expected the expected JSON object
// * @param actual the actual JSON object
// * @return the result of the comparison
// * @throws JSONException JSON parsing error
// */
// JSONCompareResult compareJSON(JSONObject expected, JSONObject actual) throws JSONException;
//
// /**
// * Compares two {@link JSONArray}s and returns the result of the comparison in a {@link JSONCompareResult} object.
// *
// * @param expected the expected JSON array
// * @param actual the actual JSON array
// * @return the result of the comparison
// * @throws JSONException JSON parsing error
// */
// JSONCompareResult compareJSON(JSONArray expected, JSONArray actual) throws JSONException;
//
// /**
// * Compares two {@link JSONObject}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expected the expected JSON object
// * @param actual the actual JSON object
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareJSON(String prefix, JSONObject expected, JSONObject actual, JSONCompareResult result) throws JSONException;
//
// /**
// * Compares two {@link Object}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expectedValue the expected value
// * @param actualValue the actual value
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException;
//
// /**
// * Compares two {@link JSONArray}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expected the expected JSON array
// * @param actual the actual JSON array
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareJSONArray(String prefix, JSONArray expected, JSONArray actual, JSONCompareResult result) throws JSONException;
// }
| import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.skyscreamer.jsonassert.JSONCompareMode.LENIENT;
import static org.skyscreamer.jsonassert.JSONCompareMode.NON_EXTENSIBLE;
import static org.skyscreamer.jsonassert.JSONCompareMode.STRICT;
import static org.skyscreamer.jsonassert.JSONCompareMode.STRICT_ORDER;
import java.util.Arrays;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import org.skyscreamer.jsonassert.comparator.CustomComparator;
import org.skyscreamer.jsonassert.comparator.JSONComparator; |
expected = new JSONObject();
actual = new JSONObject();
expected.put("id", Integer.valueOf(12345));
actual.put("id", Double.valueOf(12346));
performAssertEqualsTestForMessageVerification(expected, actual, STRICT);
}
@Test
public void testAssertEqualsJSONObject2Boolean() throws JSONException {
JSONObject expected = new JSONObject();
JSONObject actual = new JSONObject();
expected.put("id", Integer.valueOf(12345));
actual.put("name", "Joe");
actual.put("id", Integer.valueOf(12345));
JSONAssert.assertEquals("Message", expected, actual, false);
expected.put("street", "St. Paul");
performAssertEqualsTestForMessageVerification(expected, actual, false);
expected = new JSONObject();
actual = new JSONObject();
expected.put("id", Integer.valueOf(12345));
actual.put("id", Double.valueOf(12346));
performAssertEqualsTestForMessageVerification(expected, actual, true);
}
@Test
public void testAssertEqualsString2JsonComparator() throws IllegalArgumentException, JSONException {
JSONAssert.assertEquals("Message", "{\"entry\":{\"id\":x}}", "{\"entry\":{\"id\":1, \"id\":2}}", | // Path: src/main/java/org/skyscreamer/jsonassert/comparator/CustomComparator.java
// public class CustomComparator extends DefaultComparator {
//
// private final Collection<Customization> customizations;
//
// public CustomComparator(JSONCompareMode mode, Customization... customizations) {
// super(mode);
// this.customizations = Arrays.asList(customizations);
// }
//
// @Override
// public void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException {
// Customization customization = getCustomization(prefix);
// if (customization != null) {
// try {
// if (!customization.matches(prefix, actualValue, expectedValue, result)) {
// result.fail(prefix, expectedValue, actualValue);
// }
// }
// catch (ValueMatcherException e) {
// result.fail(prefix, e);
// }
// } else {
// super.compareValues(prefix, expectedValue, actualValue, result);
// }
// }
//
// private Customization getCustomization(String path) {
// for (Customization c : customizations)
// if (c.appliesToPath(path))
// return c;
// return null;
// }
// }
//
// Path: src/main/java/org/skyscreamer/jsonassert/comparator/JSONComparator.java
// public interface JSONComparator {
//
// /**
// * Compares two {@link JSONObject}s and returns the result of the comparison in a {@link JSONCompareResult} object.
// *
// * @param expected the expected JSON object
// * @param actual the actual JSON object
// * @return the result of the comparison
// * @throws JSONException JSON parsing error
// */
// JSONCompareResult compareJSON(JSONObject expected, JSONObject actual) throws JSONException;
//
// /**
// * Compares two {@link JSONArray}s and returns the result of the comparison in a {@link JSONCompareResult} object.
// *
// * @param expected the expected JSON array
// * @param actual the actual JSON array
// * @return the result of the comparison
// * @throws JSONException JSON parsing error
// */
// JSONCompareResult compareJSON(JSONArray expected, JSONArray actual) throws JSONException;
//
// /**
// * Compares two {@link JSONObject}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expected the expected JSON object
// * @param actual the actual JSON object
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareJSON(String prefix, JSONObject expected, JSONObject actual, JSONCompareResult result) throws JSONException;
//
// /**
// * Compares two {@link Object}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expectedValue the expected value
// * @param actualValue the actual value
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException;
//
// /**
// * Compares two {@link JSONArray}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expected the expected JSON array
// * @param actual the actual JSON array
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareJSONArray(String prefix, JSONArray expected, JSONArray actual, JSONCompareResult result) throws JSONException;
// }
// Path: src/test/java/org/skyscreamer/jsonassert/JSONAssertTest.java
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.skyscreamer.jsonassert.JSONCompareMode.LENIENT;
import static org.skyscreamer.jsonassert.JSONCompareMode.NON_EXTENSIBLE;
import static org.skyscreamer.jsonassert.JSONCompareMode.STRICT;
import static org.skyscreamer.jsonassert.JSONCompareMode.STRICT_ORDER;
import java.util.Arrays;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import org.skyscreamer.jsonassert.comparator.CustomComparator;
import org.skyscreamer.jsonassert.comparator.JSONComparator;
expected = new JSONObject();
actual = new JSONObject();
expected.put("id", Integer.valueOf(12345));
actual.put("id", Double.valueOf(12346));
performAssertEqualsTestForMessageVerification(expected, actual, STRICT);
}
@Test
public void testAssertEqualsJSONObject2Boolean() throws JSONException {
JSONObject expected = new JSONObject();
JSONObject actual = new JSONObject();
expected.put("id", Integer.valueOf(12345));
actual.put("name", "Joe");
actual.put("id", Integer.valueOf(12345));
JSONAssert.assertEquals("Message", expected, actual, false);
expected.put("street", "St. Paul");
performAssertEqualsTestForMessageVerification(expected, actual, false);
expected = new JSONObject();
actual = new JSONObject();
expected.put("id", Integer.valueOf(12345));
actual.put("id", Double.valueOf(12346));
performAssertEqualsTestForMessageVerification(expected, actual, true);
}
@Test
public void testAssertEqualsString2JsonComparator() throws IllegalArgumentException, JSONException {
JSONAssert.assertEquals("Message", "{\"entry\":{\"id\":x}}", "{\"entry\":{\"id\":1, \"id\":2}}", | new CustomComparator( |
skyscreamer/JSONassert | src/test/java/org/skyscreamer/jsonassert/JSONAssertTest.java | // Path: src/main/java/org/skyscreamer/jsonassert/comparator/CustomComparator.java
// public class CustomComparator extends DefaultComparator {
//
// private final Collection<Customization> customizations;
//
// public CustomComparator(JSONCompareMode mode, Customization... customizations) {
// super(mode);
// this.customizations = Arrays.asList(customizations);
// }
//
// @Override
// public void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException {
// Customization customization = getCustomization(prefix);
// if (customization != null) {
// try {
// if (!customization.matches(prefix, actualValue, expectedValue, result)) {
// result.fail(prefix, expectedValue, actualValue);
// }
// }
// catch (ValueMatcherException e) {
// result.fail(prefix, e);
// }
// } else {
// super.compareValues(prefix, expectedValue, actualValue, result);
// }
// }
//
// private Customization getCustomization(String path) {
// for (Customization c : customizations)
// if (c.appliesToPath(path))
// return c;
// return null;
// }
// }
//
// Path: src/main/java/org/skyscreamer/jsonassert/comparator/JSONComparator.java
// public interface JSONComparator {
//
// /**
// * Compares two {@link JSONObject}s and returns the result of the comparison in a {@link JSONCompareResult} object.
// *
// * @param expected the expected JSON object
// * @param actual the actual JSON object
// * @return the result of the comparison
// * @throws JSONException JSON parsing error
// */
// JSONCompareResult compareJSON(JSONObject expected, JSONObject actual) throws JSONException;
//
// /**
// * Compares two {@link JSONArray}s and returns the result of the comparison in a {@link JSONCompareResult} object.
// *
// * @param expected the expected JSON array
// * @param actual the actual JSON array
// * @return the result of the comparison
// * @throws JSONException JSON parsing error
// */
// JSONCompareResult compareJSON(JSONArray expected, JSONArray actual) throws JSONException;
//
// /**
// * Compares two {@link JSONObject}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expected the expected JSON object
// * @param actual the actual JSON object
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareJSON(String prefix, JSONObject expected, JSONObject actual, JSONCompareResult result) throws JSONException;
//
// /**
// * Compares two {@link Object}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expectedValue the expected value
// * @param actualValue the actual value
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException;
//
// /**
// * Compares two {@link JSONArray}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expected the expected JSON array
// * @param actual the actual JSON array
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareJSONArray(String prefix, JSONArray expected, JSONArray actual, JSONCompareResult result) throws JSONException;
// }
| import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.skyscreamer.jsonassert.JSONCompareMode.LENIENT;
import static org.skyscreamer.jsonassert.JSONCompareMode.NON_EXTENSIBLE;
import static org.skyscreamer.jsonassert.JSONCompareMode.STRICT;
import static org.skyscreamer.jsonassert.JSONCompareMode.STRICT_ORDER;
import java.util.Arrays;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import org.skyscreamer.jsonassert.comparator.CustomComparator;
import org.skyscreamer.jsonassert.comparator.JSONComparator; | new Customization("entry.id",
new RegularExpressionValueMatcher<Object>("\\d"))
));
}
private void testPass(String expected, String actual, JSONCompareMode compareMode)
throws JSONException
{
String message = expected + " == " + actual + " (" + compareMode + ")";
JSONCompareResult result = JSONCompare.compareJSON(expected, actual, compareMode);
Assert.assertTrue(message + "\n " + result.getMessage(), result.passed());
}
private void testFail(String expected, String actual, JSONCompareMode compareMode)
throws JSONException
{
String message = expected + " != " + actual + " (" + compareMode + ")";
JSONCompareResult result = JSONCompare.compareJSON(expected, actual, compareMode);
Assert.assertTrue(message, result.failed());
}
private void performAssertEqualsTestForMessageVerification(
Object expected,
Object actual,
Object strictMode) throws JSONException {
String message = "Message";
String testShouldFailMessage = "The test should fail so that the message in AssertionError could be verified.";
String strictModeMessage = "strictMode must be an instance of JSONCompareMode or Boolean";
boolean assertEqualsFailed = true; | // Path: src/main/java/org/skyscreamer/jsonassert/comparator/CustomComparator.java
// public class CustomComparator extends DefaultComparator {
//
// private final Collection<Customization> customizations;
//
// public CustomComparator(JSONCompareMode mode, Customization... customizations) {
// super(mode);
// this.customizations = Arrays.asList(customizations);
// }
//
// @Override
// public void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException {
// Customization customization = getCustomization(prefix);
// if (customization != null) {
// try {
// if (!customization.matches(prefix, actualValue, expectedValue, result)) {
// result.fail(prefix, expectedValue, actualValue);
// }
// }
// catch (ValueMatcherException e) {
// result.fail(prefix, e);
// }
// } else {
// super.compareValues(prefix, expectedValue, actualValue, result);
// }
// }
//
// private Customization getCustomization(String path) {
// for (Customization c : customizations)
// if (c.appliesToPath(path))
// return c;
// return null;
// }
// }
//
// Path: src/main/java/org/skyscreamer/jsonassert/comparator/JSONComparator.java
// public interface JSONComparator {
//
// /**
// * Compares two {@link JSONObject}s and returns the result of the comparison in a {@link JSONCompareResult} object.
// *
// * @param expected the expected JSON object
// * @param actual the actual JSON object
// * @return the result of the comparison
// * @throws JSONException JSON parsing error
// */
// JSONCompareResult compareJSON(JSONObject expected, JSONObject actual) throws JSONException;
//
// /**
// * Compares two {@link JSONArray}s and returns the result of the comparison in a {@link JSONCompareResult} object.
// *
// * @param expected the expected JSON array
// * @param actual the actual JSON array
// * @return the result of the comparison
// * @throws JSONException JSON parsing error
// */
// JSONCompareResult compareJSON(JSONArray expected, JSONArray actual) throws JSONException;
//
// /**
// * Compares two {@link JSONObject}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expected the expected JSON object
// * @param actual the actual JSON object
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareJSON(String prefix, JSONObject expected, JSONObject actual, JSONCompareResult result) throws JSONException;
//
// /**
// * Compares two {@link Object}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expectedValue the expected value
// * @param actualValue the actual value
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException;
//
// /**
// * Compares two {@link JSONArray}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expected the expected JSON array
// * @param actual the actual JSON array
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareJSONArray(String prefix, JSONArray expected, JSONArray actual, JSONCompareResult result) throws JSONException;
// }
// Path: src/test/java/org/skyscreamer/jsonassert/JSONAssertTest.java
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.skyscreamer.jsonassert.JSONCompareMode.LENIENT;
import static org.skyscreamer.jsonassert.JSONCompareMode.NON_EXTENSIBLE;
import static org.skyscreamer.jsonassert.JSONCompareMode.STRICT;
import static org.skyscreamer.jsonassert.JSONCompareMode.STRICT_ORDER;
import java.util.Arrays;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import org.skyscreamer.jsonassert.comparator.CustomComparator;
import org.skyscreamer.jsonassert.comparator.JSONComparator;
new Customization("entry.id",
new RegularExpressionValueMatcher<Object>("\\d"))
));
}
private void testPass(String expected, String actual, JSONCompareMode compareMode)
throws JSONException
{
String message = expected + " == " + actual + " (" + compareMode + ")";
JSONCompareResult result = JSONCompare.compareJSON(expected, actual, compareMode);
Assert.assertTrue(message + "\n " + result.getMessage(), result.passed());
}
private void testFail(String expected, String actual, JSONCompareMode compareMode)
throws JSONException
{
String message = expected + " != " + actual + " (" + compareMode + ")";
JSONCompareResult result = JSONCompare.compareJSON(expected, actual, compareMode);
Assert.assertTrue(message, result.failed());
}
private void performAssertEqualsTestForMessageVerification(
Object expected,
Object actual,
Object strictMode) throws JSONException {
String message = "Message";
String testShouldFailMessage = "The test should fail so that the message in AssertionError could be verified.";
String strictModeMessage = "strictMode must be an instance of JSONCompareMode or Boolean";
boolean assertEqualsFailed = true; | if(expected instanceof String && actual instanceof String && strictMode instanceof JSONComparator) { |
skyscreamer/JSONassert | src/test/java/org/skyscreamer/jsonassert/JSONCustomComparatorTest.java | // Path: src/main/java/org/skyscreamer/jsonassert/comparator/CustomComparator.java
// public class CustomComparator extends DefaultComparator {
//
// private final Collection<Customization> customizations;
//
// public CustomComparator(JSONCompareMode mode, Customization... customizations) {
// super(mode);
// this.customizations = Arrays.asList(customizations);
// }
//
// @Override
// public void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException {
// Customization customization = getCustomization(prefix);
// if (customization != null) {
// try {
// if (!customization.matches(prefix, actualValue, expectedValue, result)) {
// result.fail(prefix, expectedValue, actualValue);
// }
// }
// catch (ValueMatcherException e) {
// result.fail(prefix, e);
// }
// } else {
// super.compareValues(prefix, expectedValue, actualValue, result);
// }
// }
//
// private Customization getCustomization(String path) {
// for (Customization c : customizations)
// if (c.appliesToPath(path))
// return c;
// return null;
// }
// }
//
// Path: src/main/java/org/skyscreamer/jsonassert/comparator/JSONComparator.java
// public interface JSONComparator {
//
// /**
// * Compares two {@link JSONObject}s and returns the result of the comparison in a {@link JSONCompareResult} object.
// *
// * @param expected the expected JSON object
// * @param actual the actual JSON object
// * @return the result of the comparison
// * @throws JSONException JSON parsing error
// */
// JSONCompareResult compareJSON(JSONObject expected, JSONObject actual) throws JSONException;
//
// /**
// * Compares two {@link JSONArray}s and returns the result of the comparison in a {@link JSONCompareResult} object.
// *
// * @param expected the expected JSON array
// * @param actual the actual JSON array
// * @return the result of the comparison
// * @throws JSONException JSON parsing error
// */
// JSONCompareResult compareJSON(JSONArray expected, JSONArray actual) throws JSONException;
//
// /**
// * Compares two {@link JSONObject}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expected the expected JSON object
// * @param actual the actual JSON object
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareJSON(String prefix, JSONObject expected, JSONObject actual, JSONCompareResult result) throws JSONException;
//
// /**
// * Compares two {@link Object}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expectedValue the expected value
// * @param actualValue the actual value
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException;
//
// /**
// * Compares two {@link JSONArray}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expected the expected JSON array
// * @param actual the actual JSON array
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareJSONArray(String prefix, JSONArray expected, JSONArray actual, JSONCompareResult result) throws JSONException;
// }
//
// Path: src/main/java/org/skyscreamer/jsonassert/JSONCompare.java
// public static JSONCompareResult compareJSON(String expectedStr, String actualStr, JSONComparator comparator)
// throws JSONException {
// Object expected = JSONParser.parseJSON(expectedStr);
// Object actual = JSONParser.parseJSON(actualStr);
// if ((expected instanceof JSONObject) && (actual instanceof JSONObject)) {
// return compareJSON((JSONObject) expected, (JSONObject) actual, comparator);
// }
// else if ((expected instanceof JSONArray) && (actual instanceof JSONArray)) {
// return compareJSON((JSONArray)expected, (JSONArray)actual, comparator);
// }
// else if (expected instanceof JSONString && actual instanceof JSONString) {
// return compareJson((JSONString) expected, (JSONString) actual);
// }
// else if (expected instanceof JSONObject) {
// return new JSONCompareResult().fail("", expected, actual);
// }
// else {
// return new JSONCompareResult().fail("", expected, actual);
// }
// }
| import org.json.JSONException;
import org.junit.Test;
import org.skyscreamer.jsonassert.comparator.CustomComparator;
import org.skyscreamer.jsonassert.comparator.JSONComparator;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.skyscreamer.jsonassert.JSONCompare.compareJSON; | " \"bar\": {\n" +
" \"baz\": \"actual\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
String rootDeepWildcardExpected = "{\n" +
" \"baz\": \"expected\",\n" +
" \"root\": {\n" +
" \"baz\": \"expected\",\n" +
" \"foo\": {\n" +
" \"baz\": \"expected\",\n" +
" \"bar\": {\n" +
" \"baz\": \"expected\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
int comparatorCallCount = 0;
ValueMatcher<Object> comparator = new ValueMatcher<Object>() {
@Override
public boolean equal(Object o1, Object o2) {
comparatorCallCount++;
return o1.toString().equals("actual") && o2.toString().equals("expected");
}
};
@Test
public void whenPathMatchesInCustomizationThenCallCustomMatcher() throws JSONException { | // Path: src/main/java/org/skyscreamer/jsonassert/comparator/CustomComparator.java
// public class CustomComparator extends DefaultComparator {
//
// private final Collection<Customization> customizations;
//
// public CustomComparator(JSONCompareMode mode, Customization... customizations) {
// super(mode);
// this.customizations = Arrays.asList(customizations);
// }
//
// @Override
// public void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException {
// Customization customization = getCustomization(prefix);
// if (customization != null) {
// try {
// if (!customization.matches(prefix, actualValue, expectedValue, result)) {
// result.fail(prefix, expectedValue, actualValue);
// }
// }
// catch (ValueMatcherException e) {
// result.fail(prefix, e);
// }
// } else {
// super.compareValues(prefix, expectedValue, actualValue, result);
// }
// }
//
// private Customization getCustomization(String path) {
// for (Customization c : customizations)
// if (c.appliesToPath(path))
// return c;
// return null;
// }
// }
//
// Path: src/main/java/org/skyscreamer/jsonassert/comparator/JSONComparator.java
// public interface JSONComparator {
//
// /**
// * Compares two {@link JSONObject}s and returns the result of the comparison in a {@link JSONCompareResult} object.
// *
// * @param expected the expected JSON object
// * @param actual the actual JSON object
// * @return the result of the comparison
// * @throws JSONException JSON parsing error
// */
// JSONCompareResult compareJSON(JSONObject expected, JSONObject actual) throws JSONException;
//
// /**
// * Compares two {@link JSONArray}s and returns the result of the comparison in a {@link JSONCompareResult} object.
// *
// * @param expected the expected JSON array
// * @param actual the actual JSON array
// * @return the result of the comparison
// * @throws JSONException JSON parsing error
// */
// JSONCompareResult compareJSON(JSONArray expected, JSONArray actual) throws JSONException;
//
// /**
// * Compares two {@link JSONObject}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expected the expected JSON object
// * @param actual the actual JSON object
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareJSON(String prefix, JSONObject expected, JSONObject actual, JSONCompareResult result) throws JSONException;
//
// /**
// * Compares two {@link Object}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expectedValue the expected value
// * @param actualValue the actual value
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException;
//
// /**
// * Compares two {@link JSONArray}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expected the expected JSON array
// * @param actual the actual JSON array
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareJSONArray(String prefix, JSONArray expected, JSONArray actual, JSONCompareResult result) throws JSONException;
// }
//
// Path: src/main/java/org/skyscreamer/jsonassert/JSONCompare.java
// public static JSONCompareResult compareJSON(String expectedStr, String actualStr, JSONComparator comparator)
// throws JSONException {
// Object expected = JSONParser.parseJSON(expectedStr);
// Object actual = JSONParser.parseJSON(actualStr);
// if ((expected instanceof JSONObject) && (actual instanceof JSONObject)) {
// return compareJSON((JSONObject) expected, (JSONObject) actual, comparator);
// }
// else if ((expected instanceof JSONArray) && (actual instanceof JSONArray)) {
// return compareJSON((JSONArray)expected, (JSONArray)actual, comparator);
// }
// else if (expected instanceof JSONString && actual instanceof JSONString) {
// return compareJson((JSONString) expected, (JSONString) actual);
// }
// else if (expected instanceof JSONObject) {
// return new JSONCompareResult().fail("", expected, actual);
// }
// else {
// return new JSONCompareResult().fail("", expected, actual);
// }
// }
// Path: src/test/java/org/skyscreamer/jsonassert/JSONCustomComparatorTest.java
import org.json.JSONException;
import org.junit.Test;
import org.skyscreamer.jsonassert.comparator.CustomComparator;
import org.skyscreamer.jsonassert.comparator.JSONComparator;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.skyscreamer.jsonassert.JSONCompare.compareJSON;
" \"bar\": {\n" +
" \"baz\": \"actual\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
String rootDeepWildcardExpected = "{\n" +
" \"baz\": \"expected\",\n" +
" \"root\": {\n" +
" \"baz\": \"expected\",\n" +
" \"foo\": {\n" +
" \"baz\": \"expected\",\n" +
" \"bar\": {\n" +
" \"baz\": \"expected\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
int comparatorCallCount = 0;
ValueMatcher<Object> comparator = new ValueMatcher<Object>() {
@Override
public boolean equal(Object o1, Object o2) {
comparatorCallCount++;
return o1.toString().equals("actual") && o2.toString().equals("expected");
}
};
@Test
public void whenPathMatchesInCustomizationThenCallCustomMatcher() throws JSONException { | JSONComparator jsonCmp = new CustomComparator(JSONCompareMode.STRICT, new Customization("first", comparator)); |
skyscreamer/JSONassert | src/test/java/org/skyscreamer/jsonassert/JSONCustomComparatorTest.java | // Path: src/main/java/org/skyscreamer/jsonassert/comparator/CustomComparator.java
// public class CustomComparator extends DefaultComparator {
//
// private final Collection<Customization> customizations;
//
// public CustomComparator(JSONCompareMode mode, Customization... customizations) {
// super(mode);
// this.customizations = Arrays.asList(customizations);
// }
//
// @Override
// public void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException {
// Customization customization = getCustomization(prefix);
// if (customization != null) {
// try {
// if (!customization.matches(prefix, actualValue, expectedValue, result)) {
// result.fail(prefix, expectedValue, actualValue);
// }
// }
// catch (ValueMatcherException e) {
// result.fail(prefix, e);
// }
// } else {
// super.compareValues(prefix, expectedValue, actualValue, result);
// }
// }
//
// private Customization getCustomization(String path) {
// for (Customization c : customizations)
// if (c.appliesToPath(path))
// return c;
// return null;
// }
// }
//
// Path: src/main/java/org/skyscreamer/jsonassert/comparator/JSONComparator.java
// public interface JSONComparator {
//
// /**
// * Compares two {@link JSONObject}s and returns the result of the comparison in a {@link JSONCompareResult} object.
// *
// * @param expected the expected JSON object
// * @param actual the actual JSON object
// * @return the result of the comparison
// * @throws JSONException JSON parsing error
// */
// JSONCompareResult compareJSON(JSONObject expected, JSONObject actual) throws JSONException;
//
// /**
// * Compares two {@link JSONArray}s and returns the result of the comparison in a {@link JSONCompareResult} object.
// *
// * @param expected the expected JSON array
// * @param actual the actual JSON array
// * @return the result of the comparison
// * @throws JSONException JSON parsing error
// */
// JSONCompareResult compareJSON(JSONArray expected, JSONArray actual) throws JSONException;
//
// /**
// * Compares two {@link JSONObject}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expected the expected JSON object
// * @param actual the actual JSON object
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareJSON(String prefix, JSONObject expected, JSONObject actual, JSONCompareResult result) throws JSONException;
//
// /**
// * Compares two {@link Object}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expectedValue the expected value
// * @param actualValue the actual value
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException;
//
// /**
// * Compares two {@link JSONArray}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expected the expected JSON array
// * @param actual the actual JSON array
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareJSONArray(String prefix, JSONArray expected, JSONArray actual, JSONCompareResult result) throws JSONException;
// }
//
// Path: src/main/java/org/skyscreamer/jsonassert/JSONCompare.java
// public static JSONCompareResult compareJSON(String expectedStr, String actualStr, JSONComparator comparator)
// throws JSONException {
// Object expected = JSONParser.parseJSON(expectedStr);
// Object actual = JSONParser.parseJSON(actualStr);
// if ((expected instanceof JSONObject) && (actual instanceof JSONObject)) {
// return compareJSON((JSONObject) expected, (JSONObject) actual, comparator);
// }
// else if ((expected instanceof JSONArray) && (actual instanceof JSONArray)) {
// return compareJSON((JSONArray)expected, (JSONArray)actual, comparator);
// }
// else if (expected instanceof JSONString && actual instanceof JSONString) {
// return compareJson((JSONString) expected, (JSONString) actual);
// }
// else if (expected instanceof JSONObject) {
// return new JSONCompareResult().fail("", expected, actual);
// }
// else {
// return new JSONCompareResult().fail("", expected, actual);
// }
// }
| import org.json.JSONException;
import org.junit.Test;
import org.skyscreamer.jsonassert.comparator.CustomComparator;
import org.skyscreamer.jsonassert.comparator.JSONComparator;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.skyscreamer.jsonassert.JSONCompare.compareJSON; | " \"bar\": {\n" +
" \"baz\": \"actual\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
String rootDeepWildcardExpected = "{\n" +
" \"baz\": \"expected\",\n" +
" \"root\": {\n" +
" \"baz\": \"expected\",\n" +
" \"foo\": {\n" +
" \"baz\": \"expected\",\n" +
" \"bar\": {\n" +
" \"baz\": \"expected\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
int comparatorCallCount = 0;
ValueMatcher<Object> comparator = new ValueMatcher<Object>() {
@Override
public boolean equal(Object o1, Object o2) {
comparatorCallCount++;
return o1.toString().equals("actual") && o2.toString().equals("expected");
}
};
@Test
public void whenPathMatchesInCustomizationThenCallCustomMatcher() throws JSONException { | // Path: src/main/java/org/skyscreamer/jsonassert/comparator/CustomComparator.java
// public class CustomComparator extends DefaultComparator {
//
// private final Collection<Customization> customizations;
//
// public CustomComparator(JSONCompareMode mode, Customization... customizations) {
// super(mode);
// this.customizations = Arrays.asList(customizations);
// }
//
// @Override
// public void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException {
// Customization customization = getCustomization(prefix);
// if (customization != null) {
// try {
// if (!customization.matches(prefix, actualValue, expectedValue, result)) {
// result.fail(prefix, expectedValue, actualValue);
// }
// }
// catch (ValueMatcherException e) {
// result.fail(prefix, e);
// }
// } else {
// super.compareValues(prefix, expectedValue, actualValue, result);
// }
// }
//
// private Customization getCustomization(String path) {
// for (Customization c : customizations)
// if (c.appliesToPath(path))
// return c;
// return null;
// }
// }
//
// Path: src/main/java/org/skyscreamer/jsonassert/comparator/JSONComparator.java
// public interface JSONComparator {
//
// /**
// * Compares two {@link JSONObject}s and returns the result of the comparison in a {@link JSONCompareResult} object.
// *
// * @param expected the expected JSON object
// * @param actual the actual JSON object
// * @return the result of the comparison
// * @throws JSONException JSON parsing error
// */
// JSONCompareResult compareJSON(JSONObject expected, JSONObject actual) throws JSONException;
//
// /**
// * Compares two {@link JSONArray}s and returns the result of the comparison in a {@link JSONCompareResult} object.
// *
// * @param expected the expected JSON array
// * @param actual the actual JSON array
// * @return the result of the comparison
// * @throws JSONException JSON parsing error
// */
// JSONCompareResult compareJSON(JSONArray expected, JSONArray actual) throws JSONException;
//
// /**
// * Compares two {@link JSONObject}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expected the expected JSON object
// * @param actual the actual JSON object
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareJSON(String prefix, JSONObject expected, JSONObject actual, JSONCompareResult result) throws JSONException;
//
// /**
// * Compares two {@link Object}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expectedValue the expected value
// * @param actualValue the actual value
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException;
//
// /**
// * Compares two {@link JSONArray}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expected the expected JSON array
// * @param actual the actual JSON array
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareJSONArray(String prefix, JSONArray expected, JSONArray actual, JSONCompareResult result) throws JSONException;
// }
//
// Path: src/main/java/org/skyscreamer/jsonassert/JSONCompare.java
// public static JSONCompareResult compareJSON(String expectedStr, String actualStr, JSONComparator comparator)
// throws JSONException {
// Object expected = JSONParser.parseJSON(expectedStr);
// Object actual = JSONParser.parseJSON(actualStr);
// if ((expected instanceof JSONObject) && (actual instanceof JSONObject)) {
// return compareJSON((JSONObject) expected, (JSONObject) actual, comparator);
// }
// else if ((expected instanceof JSONArray) && (actual instanceof JSONArray)) {
// return compareJSON((JSONArray)expected, (JSONArray)actual, comparator);
// }
// else if (expected instanceof JSONString && actual instanceof JSONString) {
// return compareJson((JSONString) expected, (JSONString) actual);
// }
// else if (expected instanceof JSONObject) {
// return new JSONCompareResult().fail("", expected, actual);
// }
// else {
// return new JSONCompareResult().fail("", expected, actual);
// }
// }
// Path: src/test/java/org/skyscreamer/jsonassert/JSONCustomComparatorTest.java
import org.json.JSONException;
import org.junit.Test;
import org.skyscreamer.jsonassert.comparator.CustomComparator;
import org.skyscreamer.jsonassert.comparator.JSONComparator;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.skyscreamer.jsonassert.JSONCompare.compareJSON;
" \"bar\": {\n" +
" \"baz\": \"actual\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
String rootDeepWildcardExpected = "{\n" +
" \"baz\": \"expected\",\n" +
" \"root\": {\n" +
" \"baz\": \"expected\",\n" +
" \"foo\": {\n" +
" \"baz\": \"expected\",\n" +
" \"bar\": {\n" +
" \"baz\": \"expected\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
int comparatorCallCount = 0;
ValueMatcher<Object> comparator = new ValueMatcher<Object>() {
@Override
public boolean equal(Object o1, Object o2) {
comparatorCallCount++;
return o1.toString().equals("actual") && o2.toString().equals("expected");
}
};
@Test
public void whenPathMatchesInCustomizationThenCallCustomMatcher() throws JSONException { | JSONComparator jsonCmp = new CustomComparator(JSONCompareMode.STRICT, new Customization("first", comparator)); |
skyscreamer/JSONassert | src/test/java/org/skyscreamer/jsonassert/JSONCustomComparatorTest.java | // Path: src/main/java/org/skyscreamer/jsonassert/comparator/CustomComparator.java
// public class CustomComparator extends DefaultComparator {
//
// private final Collection<Customization> customizations;
//
// public CustomComparator(JSONCompareMode mode, Customization... customizations) {
// super(mode);
// this.customizations = Arrays.asList(customizations);
// }
//
// @Override
// public void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException {
// Customization customization = getCustomization(prefix);
// if (customization != null) {
// try {
// if (!customization.matches(prefix, actualValue, expectedValue, result)) {
// result.fail(prefix, expectedValue, actualValue);
// }
// }
// catch (ValueMatcherException e) {
// result.fail(prefix, e);
// }
// } else {
// super.compareValues(prefix, expectedValue, actualValue, result);
// }
// }
//
// private Customization getCustomization(String path) {
// for (Customization c : customizations)
// if (c.appliesToPath(path))
// return c;
// return null;
// }
// }
//
// Path: src/main/java/org/skyscreamer/jsonassert/comparator/JSONComparator.java
// public interface JSONComparator {
//
// /**
// * Compares two {@link JSONObject}s and returns the result of the comparison in a {@link JSONCompareResult} object.
// *
// * @param expected the expected JSON object
// * @param actual the actual JSON object
// * @return the result of the comparison
// * @throws JSONException JSON parsing error
// */
// JSONCompareResult compareJSON(JSONObject expected, JSONObject actual) throws JSONException;
//
// /**
// * Compares two {@link JSONArray}s and returns the result of the comparison in a {@link JSONCompareResult} object.
// *
// * @param expected the expected JSON array
// * @param actual the actual JSON array
// * @return the result of the comparison
// * @throws JSONException JSON parsing error
// */
// JSONCompareResult compareJSON(JSONArray expected, JSONArray actual) throws JSONException;
//
// /**
// * Compares two {@link JSONObject}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expected the expected JSON object
// * @param actual the actual JSON object
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareJSON(String prefix, JSONObject expected, JSONObject actual, JSONCompareResult result) throws JSONException;
//
// /**
// * Compares two {@link Object}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expectedValue the expected value
// * @param actualValue the actual value
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException;
//
// /**
// * Compares two {@link JSONArray}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expected the expected JSON array
// * @param actual the actual JSON array
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareJSONArray(String prefix, JSONArray expected, JSONArray actual, JSONCompareResult result) throws JSONException;
// }
//
// Path: src/main/java/org/skyscreamer/jsonassert/JSONCompare.java
// public static JSONCompareResult compareJSON(String expectedStr, String actualStr, JSONComparator comparator)
// throws JSONException {
// Object expected = JSONParser.parseJSON(expectedStr);
// Object actual = JSONParser.parseJSON(actualStr);
// if ((expected instanceof JSONObject) && (actual instanceof JSONObject)) {
// return compareJSON((JSONObject) expected, (JSONObject) actual, comparator);
// }
// else if ((expected instanceof JSONArray) && (actual instanceof JSONArray)) {
// return compareJSON((JSONArray)expected, (JSONArray)actual, comparator);
// }
// else if (expected instanceof JSONString && actual instanceof JSONString) {
// return compareJson((JSONString) expected, (JSONString) actual);
// }
// else if (expected instanceof JSONObject) {
// return new JSONCompareResult().fail("", expected, actual);
// }
// else {
// return new JSONCompareResult().fail("", expected, actual);
// }
// }
| import org.json.JSONException;
import org.junit.Test;
import org.skyscreamer.jsonassert.comparator.CustomComparator;
import org.skyscreamer.jsonassert.comparator.JSONComparator;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.skyscreamer.jsonassert.JSONCompare.compareJSON; | " \"baz\": \"actual\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
String rootDeepWildcardExpected = "{\n" +
" \"baz\": \"expected\",\n" +
" \"root\": {\n" +
" \"baz\": \"expected\",\n" +
" \"foo\": {\n" +
" \"baz\": \"expected\",\n" +
" \"bar\": {\n" +
" \"baz\": \"expected\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
int comparatorCallCount = 0;
ValueMatcher<Object> comparator = new ValueMatcher<Object>() {
@Override
public boolean equal(Object o1, Object o2) {
comparatorCallCount++;
return o1.toString().equals("actual") && o2.toString().equals("expected");
}
};
@Test
public void whenPathMatchesInCustomizationThenCallCustomMatcher() throws JSONException {
JSONComparator jsonCmp = new CustomComparator(JSONCompareMode.STRICT, new Customization("first", comparator)); | // Path: src/main/java/org/skyscreamer/jsonassert/comparator/CustomComparator.java
// public class CustomComparator extends DefaultComparator {
//
// private final Collection<Customization> customizations;
//
// public CustomComparator(JSONCompareMode mode, Customization... customizations) {
// super(mode);
// this.customizations = Arrays.asList(customizations);
// }
//
// @Override
// public void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException {
// Customization customization = getCustomization(prefix);
// if (customization != null) {
// try {
// if (!customization.matches(prefix, actualValue, expectedValue, result)) {
// result.fail(prefix, expectedValue, actualValue);
// }
// }
// catch (ValueMatcherException e) {
// result.fail(prefix, e);
// }
// } else {
// super.compareValues(prefix, expectedValue, actualValue, result);
// }
// }
//
// private Customization getCustomization(String path) {
// for (Customization c : customizations)
// if (c.appliesToPath(path))
// return c;
// return null;
// }
// }
//
// Path: src/main/java/org/skyscreamer/jsonassert/comparator/JSONComparator.java
// public interface JSONComparator {
//
// /**
// * Compares two {@link JSONObject}s and returns the result of the comparison in a {@link JSONCompareResult} object.
// *
// * @param expected the expected JSON object
// * @param actual the actual JSON object
// * @return the result of the comparison
// * @throws JSONException JSON parsing error
// */
// JSONCompareResult compareJSON(JSONObject expected, JSONObject actual) throws JSONException;
//
// /**
// * Compares two {@link JSONArray}s and returns the result of the comparison in a {@link JSONCompareResult} object.
// *
// * @param expected the expected JSON array
// * @param actual the actual JSON array
// * @return the result of the comparison
// * @throws JSONException JSON parsing error
// */
// JSONCompareResult compareJSON(JSONArray expected, JSONArray actual) throws JSONException;
//
// /**
// * Compares two {@link JSONObject}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expected the expected JSON object
// * @param actual the actual JSON object
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareJSON(String prefix, JSONObject expected, JSONObject actual, JSONCompareResult result) throws JSONException;
//
// /**
// * Compares two {@link Object}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expectedValue the expected value
// * @param actualValue the actual value
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException;
//
// /**
// * Compares two {@link JSONArray}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expected the expected JSON array
// * @param actual the actual JSON array
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareJSONArray(String prefix, JSONArray expected, JSONArray actual, JSONCompareResult result) throws JSONException;
// }
//
// Path: src/main/java/org/skyscreamer/jsonassert/JSONCompare.java
// public static JSONCompareResult compareJSON(String expectedStr, String actualStr, JSONComparator comparator)
// throws JSONException {
// Object expected = JSONParser.parseJSON(expectedStr);
// Object actual = JSONParser.parseJSON(actualStr);
// if ((expected instanceof JSONObject) && (actual instanceof JSONObject)) {
// return compareJSON((JSONObject) expected, (JSONObject) actual, comparator);
// }
// else if ((expected instanceof JSONArray) && (actual instanceof JSONArray)) {
// return compareJSON((JSONArray)expected, (JSONArray)actual, comparator);
// }
// else if (expected instanceof JSONString && actual instanceof JSONString) {
// return compareJson((JSONString) expected, (JSONString) actual);
// }
// else if (expected instanceof JSONObject) {
// return new JSONCompareResult().fail("", expected, actual);
// }
// else {
// return new JSONCompareResult().fail("", expected, actual);
// }
// }
// Path: src/test/java/org/skyscreamer/jsonassert/JSONCustomComparatorTest.java
import org.json.JSONException;
import org.junit.Test;
import org.skyscreamer.jsonassert.comparator.CustomComparator;
import org.skyscreamer.jsonassert.comparator.JSONComparator;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.skyscreamer.jsonassert.JSONCompare.compareJSON;
" \"baz\": \"actual\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
String rootDeepWildcardExpected = "{\n" +
" \"baz\": \"expected\",\n" +
" \"root\": {\n" +
" \"baz\": \"expected\",\n" +
" \"foo\": {\n" +
" \"baz\": \"expected\",\n" +
" \"bar\": {\n" +
" \"baz\": \"expected\"\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
int comparatorCallCount = 0;
ValueMatcher<Object> comparator = new ValueMatcher<Object>() {
@Override
public boolean equal(Object o1, Object o2) {
comparatorCallCount++;
return o1.toString().equals("actual") && o2.toString().equals("expected");
}
};
@Test
public void whenPathMatchesInCustomizationThenCallCustomMatcher() throws JSONException {
JSONComparator jsonCmp = new CustomComparator(JSONCompareMode.STRICT, new Customization("first", comparator)); | JSONCompareResult result = compareJSON(expected, actual, jsonCmp); |
skyscreamer/JSONassert | src/main/java/org/skyscreamer/jsonassert/JSONAssert.java | // Path: src/main/java/org/skyscreamer/jsonassert/comparator/JSONComparator.java
// public interface JSONComparator {
//
// /**
// * Compares two {@link JSONObject}s and returns the result of the comparison in a {@link JSONCompareResult} object.
// *
// * @param expected the expected JSON object
// * @param actual the actual JSON object
// * @return the result of the comparison
// * @throws JSONException JSON parsing error
// */
// JSONCompareResult compareJSON(JSONObject expected, JSONObject actual) throws JSONException;
//
// /**
// * Compares two {@link JSONArray}s and returns the result of the comparison in a {@link JSONCompareResult} object.
// *
// * @param expected the expected JSON array
// * @param actual the actual JSON array
// * @return the result of the comparison
// * @throws JSONException JSON parsing error
// */
// JSONCompareResult compareJSON(JSONArray expected, JSONArray actual) throws JSONException;
//
// /**
// * Compares two {@link JSONObject}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expected the expected JSON object
// * @param actual the actual JSON object
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareJSON(String prefix, JSONObject expected, JSONObject actual, JSONCompareResult result) throws JSONException;
//
// /**
// * Compares two {@link Object}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expectedValue the expected value
// * @param actualValue the actual value
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException;
//
// /**
// * Compares two {@link JSONArray}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expected the expected JSON array
// * @param actual the actual JSON array
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareJSONArray(String prefix, JSONArray expected, JSONArray actual, JSONCompareResult result) throws JSONException;
// }
| import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.skyscreamer.jsonassert.comparator.JSONComparator; | assertNotEquals("", expectedStr, actualStr, compareMode);
}
/**
* Asserts that the JSONArray provided does not match the expected string. If it is it throws an
* {@link AssertionError}.
*
* @param message Error message to be displayed in case of assertion failure
* @param expectedStr Expected JSON string
* @param actualStr String to compare
* @param compareMode Specifies which comparison mode to use
* @throws JSONException JSON parsing error
*/
public static void assertNotEquals(String message, String expectedStr, String actualStr, JSONCompareMode compareMode)
throws JSONException {
JSONCompareResult result = JSONCompare.compareJSON(expectedStr, actualStr, compareMode);
if (result.passed()) {
throw new AssertionError(getCombinedMessage(message, result.getMessage()));
}
}
/**
* Asserts that the json string provided matches the expected string. If it isn't it throws an
* {@link AssertionError}.
*
* @param expectedStr Expected JSON string
* @param actualStr String to compare
* @param comparator Comparator
* @throws JSONException JSON parsing error
*/ | // Path: src/main/java/org/skyscreamer/jsonassert/comparator/JSONComparator.java
// public interface JSONComparator {
//
// /**
// * Compares two {@link JSONObject}s and returns the result of the comparison in a {@link JSONCompareResult} object.
// *
// * @param expected the expected JSON object
// * @param actual the actual JSON object
// * @return the result of the comparison
// * @throws JSONException JSON parsing error
// */
// JSONCompareResult compareJSON(JSONObject expected, JSONObject actual) throws JSONException;
//
// /**
// * Compares two {@link JSONArray}s and returns the result of the comparison in a {@link JSONCompareResult} object.
// *
// * @param expected the expected JSON array
// * @param actual the actual JSON array
// * @return the result of the comparison
// * @throws JSONException JSON parsing error
// */
// JSONCompareResult compareJSON(JSONArray expected, JSONArray actual) throws JSONException;
//
// /**
// * Compares two {@link JSONObject}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expected the expected JSON object
// * @param actual the actual JSON object
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareJSON(String prefix, JSONObject expected, JSONObject actual, JSONCompareResult result) throws JSONException;
//
// /**
// * Compares two {@link Object}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expectedValue the expected value
// * @param actualValue the actual value
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException;
//
// /**
// * Compares two {@link JSONArray}s on the provided path represented by {@code prefix} and
// * updates the result of the comparison in the {@code result} {@link JSONCompareResult} object.
// *
// * @param prefix the path in the json where the comparison happens
// * @param expected the expected JSON array
// * @param actual the actual JSON array
// * @param result stores the actual state of the comparison result
// * @throws JSONException JSON parsing error
// */
// void compareJSONArray(String prefix, JSONArray expected, JSONArray actual, JSONCompareResult result) throws JSONException;
// }
// Path: src/main/java/org/skyscreamer/jsonassert/JSONAssert.java
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.skyscreamer.jsonassert.comparator.JSONComparator;
assertNotEquals("", expectedStr, actualStr, compareMode);
}
/**
* Asserts that the JSONArray provided does not match the expected string. If it is it throws an
* {@link AssertionError}.
*
* @param message Error message to be displayed in case of assertion failure
* @param expectedStr Expected JSON string
* @param actualStr String to compare
* @param compareMode Specifies which comparison mode to use
* @throws JSONException JSON parsing error
*/
public static void assertNotEquals(String message, String expectedStr, String actualStr, JSONCompareMode compareMode)
throws JSONException {
JSONCompareResult result = JSONCompare.compareJSON(expectedStr, actualStr, compareMode);
if (result.passed()) {
throw new AssertionError(getCombinedMessage(message, result.getMessage()));
}
}
/**
* Asserts that the json string provided matches the expected string. If it isn't it throws an
* {@link AssertionError}.
*
* @param expectedStr Expected JSON string
* @param actualStr String to compare
* @param comparator Comparator
* @throws JSONException JSON parsing error
*/ | public static void assertEquals(String expectedStr, String actualStr, JSONComparator comparator) |
stalk-io/stalk-server | src/main/java/io/stalk/common/server/RedisNodeManager.java | // Path: src/main/java/io/stalk/common/server/ServerNodeManager.java
// interface SERVER {
//
// String NODE = "server:node";
// String NODE_BY_CHANNEL = "server:nodeByChannel";
// String OK = "server:Ok";
//
// }
//
// Path: src/main/java/io/stalk/common/server/map/NodeMap.java
// public interface NodeMap<T> {
//
// public void add(String key, T node);
//
// public void remove(String key);
//
// public T get(String key);
//
// public boolean isExist(String key);
//
// public Set<String> getKeys();
//
// }
//
// Path: src/main/java/io/stalk/common/server/map/NodeRegistry.java
// public class NodeRegistry<T> implements NodeMap<T> {
//
// private final HashMap<String, T> keyMap = new HashMap<String, T>();
//
// public NodeRegistry() {
// }
//
// @Override
// public void add(String key, T node) {
// keyMap.put(key, node);
//
// }
//
// @Override
// public void remove(String key) {
// keyMap.remove(key);
// }
//
// @Override
// public T get(String key) {
// return keyMap.get(key);
// }
//
// @Override
// public boolean isExist(String key) {
// return keyMap.containsKey(key);
// }
//
// @Override
// public Set<String> getKeys() {
// return keyMap.keySet();
// }
//
// }
//
// Path: src/main/java/io/stalk/common/server/node/RedisPoolNode.java
// public class RedisPoolNode extends AbstractNode {
//
// private String channel;
// private JedisPool jedisPool;
//
// public RedisPoolNode(JsonObject jsonObject, Logger log, String prefix) {
//
// super(log, prefix);
//
// this.channel = jsonObject.getString("channel");
//
// JedisPoolConfig config = new JedisPoolConfig();
// config.testOnBorrow = true;
//
// JedisPool jedisPool;
//
// if (StringUtils.isEmpty(jsonObject.getString("host"))) {
// jedisPool = new JedisPool(config, "localhost");
// } else {
// jedisPool = new JedisPool(config,
// jsonObject.getString("host"),
// jsonObject.getInteger("port").intValue());
// }
//
// this.jedisPool = jedisPool;
//
//
// Jedis jedis = this.jedisPool.getResource();
// DEBUG("connected <%s!!> %s", jedis.ping(), jsonObject);
// this.jedisPool.returnResource(jedis);
// }
//
// public String getChannel() {
// return channel;
// }
//
// public void setChannel(String channel) {
// this.channel = channel;
// }
//
// public JedisPool getJedisPool() {
// return jedisPool;
// }
//
// public void setJedisPool(JedisPool jedisPool) {
// this.jedisPool = jedisPool;
// }
//
// public Long hset(String key, String field, String value) {
// Jedis jedis = jedisPool.getResource();
// Long status = jedis.hset(key, field, value);
// jedisPool.returnResource(jedis);
//
// return status;
// }
//
// public String hget(String key, String field) {
// Jedis jedis = jedisPool.getResource();
// String value = jedis.hget(key, field);
// jedisPool.returnResource(jedis);
//
// return value;
// }
//
// public Set<String> hkeys(String key) {
// Jedis jedis = jedisPool.getResource();
// Set<String> keys = jedis.hkeys(key);
// jedisPool.returnResource(jedis);
//
// return keys;
// }
//
// public Long hdel(String key, String... field) {
// Jedis jedis = jedisPool.getResource();
// Long status = jedis.hdel(key, field);
// jedisPool.returnResource(jedis);
//
// return status;
// }
//
// public String set(String key, String value) {
// Jedis jedis = jedisPool.getResource();
// String returnVal = jedis.set(key, value);
// jedisPool.returnResource(jedis);
//
// return returnVal;
// }
//
// public String get(String key) {
// Jedis jedis = jedisPool.getResource();
// String value = jedis.get(key);
// jedisPool.returnResource(jedis);
//
// return value;
// }
//
// public Long publish(String channel, String message) {
// Jedis jedis = jedisPool.getResource();
// Long status = jedis.publish(channel, message);
// jedisPool.returnResource(jedis);
//
// return status;
// }
//
// }
| import io.stalk.common.server.ServerNodeManager.SERVER;
import io.stalk.common.server.map.NodeMap;
import io.stalk.common.server.map.NodeRegistry;
import io.stalk.common.server.node.RedisPoolNode;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.core.logging.Logger;
import java.util.HashMap; | package io.stalk.common.server;
public class RedisNodeManager extends AbstractNodeManager<RedisPoolNode> {
private boolean isOk = false;
public RedisNodeManager() {
super();
}
public RedisNodeManager(Logger logger) {
super();
if (logger != null) activeLogger(logger);
}
public RedisNodeManager(Logger logger, String prefix) {
super();
if (logger != null) activeLogger(logger, prefix);
}
@Override | // Path: src/main/java/io/stalk/common/server/ServerNodeManager.java
// interface SERVER {
//
// String NODE = "server:node";
// String NODE_BY_CHANNEL = "server:nodeByChannel";
// String OK = "server:Ok";
//
// }
//
// Path: src/main/java/io/stalk/common/server/map/NodeMap.java
// public interface NodeMap<T> {
//
// public void add(String key, T node);
//
// public void remove(String key);
//
// public T get(String key);
//
// public boolean isExist(String key);
//
// public Set<String> getKeys();
//
// }
//
// Path: src/main/java/io/stalk/common/server/map/NodeRegistry.java
// public class NodeRegistry<T> implements NodeMap<T> {
//
// private final HashMap<String, T> keyMap = new HashMap<String, T>();
//
// public NodeRegistry() {
// }
//
// @Override
// public void add(String key, T node) {
// keyMap.put(key, node);
//
// }
//
// @Override
// public void remove(String key) {
// keyMap.remove(key);
// }
//
// @Override
// public T get(String key) {
// return keyMap.get(key);
// }
//
// @Override
// public boolean isExist(String key) {
// return keyMap.containsKey(key);
// }
//
// @Override
// public Set<String> getKeys() {
// return keyMap.keySet();
// }
//
// }
//
// Path: src/main/java/io/stalk/common/server/node/RedisPoolNode.java
// public class RedisPoolNode extends AbstractNode {
//
// private String channel;
// private JedisPool jedisPool;
//
// public RedisPoolNode(JsonObject jsonObject, Logger log, String prefix) {
//
// super(log, prefix);
//
// this.channel = jsonObject.getString("channel");
//
// JedisPoolConfig config = new JedisPoolConfig();
// config.testOnBorrow = true;
//
// JedisPool jedisPool;
//
// if (StringUtils.isEmpty(jsonObject.getString("host"))) {
// jedisPool = new JedisPool(config, "localhost");
// } else {
// jedisPool = new JedisPool(config,
// jsonObject.getString("host"),
// jsonObject.getInteger("port").intValue());
// }
//
// this.jedisPool = jedisPool;
//
//
// Jedis jedis = this.jedisPool.getResource();
// DEBUG("connected <%s!!> %s", jedis.ping(), jsonObject);
// this.jedisPool.returnResource(jedis);
// }
//
// public String getChannel() {
// return channel;
// }
//
// public void setChannel(String channel) {
// this.channel = channel;
// }
//
// public JedisPool getJedisPool() {
// return jedisPool;
// }
//
// public void setJedisPool(JedisPool jedisPool) {
// this.jedisPool = jedisPool;
// }
//
// public Long hset(String key, String field, String value) {
// Jedis jedis = jedisPool.getResource();
// Long status = jedis.hset(key, field, value);
// jedisPool.returnResource(jedis);
//
// return status;
// }
//
// public String hget(String key, String field) {
// Jedis jedis = jedisPool.getResource();
// String value = jedis.hget(key, field);
// jedisPool.returnResource(jedis);
//
// return value;
// }
//
// public Set<String> hkeys(String key) {
// Jedis jedis = jedisPool.getResource();
// Set<String> keys = jedis.hkeys(key);
// jedisPool.returnResource(jedis);
//
// return keys;
// }
//
// public Long hdel(String key, String... field) {
// Jedis jedis = jedisPool.getResource();
// Long status = jedis.hdel(key, field);
// jedisPool.returnResource(jedis);
//
// return status;
// }
//
// public String set(String key, String value) {
// Jedis jedis = jedisPool.getResource();
// String returnVal = jedis.set(key, value);
// jedisPool.returnResource(jedis);
//
// return returnVal;
// }
//
// public String get(String key) {
// Jedis jedis = jedisPool.getResource();
// String value = jedis.get(key);
// jedisPool.returnResource(jedis);
//
// return value;
// }
//
// public Long publish(String channel, String message) {
// Jedis jedis = jedisPool.getResource();
// Long status = jedis.publish(channel, message);
// jedisPool.returnResource(jedis);
//
// return status;
// }
//
// }
// Path: src/main/java/io/stalk/common/server/RedisNodeManager.java
import io.stalk.common.server.ServerNodeManager.SERVER;
import io.stalk.common.server.map.NodeMap;
import io.stalk.common.server.map.NodeRegistry;
import io.stalk.common.server.node.RedisPoolNode;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.core.logging.Logger;
import java.util.HashMap;
package io.stalk.common.server;
public class RedisNodeManager extends AbstractNodeManager<RedisPoolNode> {
private boolean isOk = false;
public RedisNodeManager() {
super();
}
public RedisNodeManager(Logger logger) {
super();
if (logger != null) activeLogger(logger);
}
public RedisNodeManager(Logger logger, String prefix) {
super();
if (logger != null) activeLogger(logger, prefix);
}
@Override | protected NodeMap<RedisPoolNode> initNodeMap() { |
stalk-io/stalk-server | src/main/java/io/stalk/common/server/RedisNodeManager.java | // Path: src/main/java/io/stalk/common/server/ServerNodeManager.java
// interface SERVER {
//
// String NODE = "server:node";
// String NODE_BY_CHANNEL = "server:nodeByChannel";
// String OK = "server:Ok";
//
// }
//
// Path: src/main/java/io/stalk/common/server/map/NodeMap.java
// public interface NodeMap<T> {
//
// public void add(String key, T node);
//
// public void remove(String key);
//
// public T get(String key);
//
// public boolean isExist(String key);
//
// public Set<String> getKeys();
//
// }
//
// Path: src/main/java/io/stalk/common/server/map/NodeRegistry.java
// public class NodeRegistry<T> implements NodeMap<T> {
//
// private final HashMap<String, T> keyMap = new HashMap<String, T>();
//
// public NodeRegistry() {
// }
//
// @Override
// public void add(String key, T node) {
// keyMap.put(key, node);
//
// }
//
// @Override
// public void remove(String key) {
// keyMap.remove(key);
// }
//
// @Override
// public T get(String key) {
// return keyMap.get(key);
// }
//
// @Override
// public boolean isExist(String key) {
// return keyMap.containsKey(key);
// }
//
// @Override
// public Set<String> getKeys() {
// return keyMap.keySet();
// }
//
// }
//
// Path: src/main/java/io/stalk/common/server/node/RedisPoolNode.java
// public class RedisPoolNode extends AbstractNode {
//
// private String channel;
// private JedisPool jedisPool;
//
// public RedisPoolNode(JsonObject jsonObject, Logger log, String prefix) {
//
// super(log, prefix);
//
// this.channel = jsonObject.getString("channel");
//
// JedisPoolConfig config = new JedisPoolConfig();
// config.testOnBorrow = true;
//
// JedisPool jedisPool;
//
// if (StringUtils.isEmpty(jsonObject.getString("host"))) {
// jedisPool = new JedisPool(config, "localhost");
// } else {
// jedisPool = new JedisPool(config,
// jsonObject.getString("host"),
// jsonObject.getInteger("port").intValue());
// }
//
// this.jedisPool = jedisPool;
//
//
// Jedis jedis = this.jedisPool.getResource();
// DEBUG("connected <%s!!> %s", jedis.ping(), jsonObject);
// this.jedisPool.returnResource(jedis);
// }
//
// public String getChannel() {
// return channel;
// }
//
// public void setChannel(String channel) {
// this.channel = channel;
// }
//
// public JedisPool getJedisPool() {
// return jedisPool;
// }
//
// public void setJedisPool(JedisPool jedisPool) {
// this.jedisPool = jedisPool;
// }
//
// public Long hset(String key, String field, String value) {
// Jedis jedis = jedisPool.getResource();
// Long status = jedis.hset(key, field, value);
// jedisPool.returnResource(jedis);
//
// return status;
// }
//
// public String hget(String key, String field) {
// Jedis jedis = jedisPool.getResource();
// String value = jedis.hget(key, field);
// jedisPool.returnResource(jedis);
//
// return value;
// }
//
// public Set<String> hkeys(String key) {
// Jedis jedis = jedisPool.getResource();
// Set<String> keys = jedis.hkeys(key);
// jedisPool.returnResource(jedis);
//
// return keys;
// }
//
// public Long hdel(String key, String... field) {
// Jedis jedis = jedisPool.getResource();
// Long status = jedis.hdel(key, field);
// jedisPool.returnResource(jedis);
//
// return status;
// }
//
// public String set(String key, String value) {
// Jedis jedis = jedisPool.getResource();
// String returnVal = jedis.set(key, value);
// jedisPool.returnResource(jedis);
//
// return returnVal;
// }
//
// public String get(String key) {
// Jedis jedis = jedisPool.getResource();
// String value = jedis.get(key);
// jedisPool.returnResource(jedis);
//
// return value;
// }
//
// public Long publish(String channel, String message) {
// Jedis jedis = jedisPool.getResource();
// Long status = jedis.publish(channel, message);
// jedisPool.returnResource(jedis);
//
// return status;
// }
//
// }
| import io.stalk.common.server.ServerNodeManager.SERVER;
import io.stalk.common.server.map.NodeMap;
import io.stalk.common.server.map.NodeRegistry;
import io.stalk.common.server.node.RedisPoolNode;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.core.logging.Logger;
import java.util.HashMap; | package io.stalk.common.server;
public class RedisNodeManager extends AbstractNodeManager<RedisPoolNode> {
private boolean isOk = false;
public RedisNodeManager() {
super();
}
public RedisNodeManager(Logger logger) {
super();
if (logger != null) activeLogger(logger);
}
public RedisNodeManager(Logger logger, String prefix) {
super();
if (logger != null) activeLogger(logger, prefix);
}
@Override
protected NodeMap<RedisPoolNode> initNodeMap() { | // Path: src/main/java/io/stalk/common/server/ServerNodeManager.java
// interface SERVER {
//
// String NODE = "server:node";
// String NODE_BY_CHANNEL = "server:nodeByChannel";
// String OK = "server:Ok";
//
// }
//
// Path: src/main/java/io/stalk/common/server/map/NodeMap.java
// public interface NodeMap<T> {
//
// public void add(String key, T node);
//
// public void remove(String key);
//
// public T get(String key);
//
// public boolean isExist(String key);
//
// public Set<String> getKeys();
//
// }
//
// Path: src/main/java/io/stalk/common/server/map/NodeRegistry.java
// public class NodeRegistry<T> implements NodeMap<T> {
//
// private final HashMap<String, T> keyMap = new HashMap<String, T>();
//
// public NodeRegistry() {
// }
//
// @Override
// public void add(String key, T node) {
// keyMap.put(key, node);
//
// }
//
// @Override
// public void remove(String key) {
// keyMap.remove(key);
// }
//
// @Override
// public T get(String key) {
// return keyMap.get(key);
// }
//
// @Override
// public boolean isExist(String key) {
// return keyMap.containsKey(key);
// }
//
// @Override
// public Set<String> getKeys() {
// return keyMap.keySet();
// }
//
// }
//
// Path: src/main/java/io/stalk/common/server/node/RedisPoolNode.java
// public class RedisPoolNode extends AbstractNode {
//
// private String channel;
// private JedisPool jedisPool;
//
// public RedisPoolNode(JsonObject jsonObject, Logger log, String prefix) {
//
// super(log, prefix);
//
// this.channel = jsonObject.getString("channel");
//
// JedisPoolConfig config = new JedisPoolConfig();
// config.testOnBorrow = true;
//
// JedisPool jedisPool;
//
// if (StringUtils.isEmpty(jsonObject.getString("host"))) {
// jedisPool = new JedisPool(config, "localhost");
// } else {
// jedisPool = new JedisPool(config,
// jsonObject.getString("host"),
// jsonObject.getInteger("port").intValue());
// }
//
// this.jedisPool = jedisPool;
//
//
// Jedis jedis = this.jedisPool.getResource();
// DEBUG("connected <%s!!> %s", jedis.ping(), jsonObject);
// this.jedisPool.returnResource(jedis);
// }
//
// public String getChannel() {
// return channel;
// }
//
// public void setChannel(String channel) {
// this.channel = channel;
// }
//
// public JedisPool getJedisPool() {
// return jedisPool;
// }
//
// public void setJedisPool(JedisPool jedisPool) {
// this.jedisPool = jedisPool;
// }
//
// public Long hset(String key, String field, String value) {
// Jedis jedis = jedisPool.getResource();
// Long status = jedis.hset(key, field, value);
// jedisPool.returnResource(jedis);
//
// return status;
// }
//
// public String hget(String key, String field) {
// Jedis jedis = jedisPool.getResource();
// String value = jedis.hget(key, field);
// jedisPool.returnResource(jedis);
//
// return value;
// }
//
// public Set<String> hkeys(String key) {
// Jedis jedis = jedisPool.getResource();
// Set<String> keys = jedis.hkeys(key);
// jedisPool.returnResource(jedis);
//
// return keys;
// }
//
// public Long hdel(String key, String... field) {
// Jedis jedis = jedisPool.getResource();
// Long status = jedis.hdel(key, field);
// jedisPool.returnResource(jedis);
//
// return status;
// }
//
// public String set(String key, String value) {
// Jedis jedis = jedisPool.getResource();
// String returnVal = jedis.set(key, value);
// jedisPool.returnResource(jedis);
//
// return returnVal;
// }
//
// public String get(String key) {
// Jedis jedis = jedisPool.getResource();
// String value = jedis.get(key);
// jedisPool.returnResource(jedis);
//
// return value;
// }
//
// public Long publish(String channel, String message) {
// Jedis jedis = jedisPool.getResource();
// Long status = jedis.publish(channel, message);
// jedisPool.returnResource(jedis);
//
// return status;
// }
//
// }
// Path: src/main/java/io/stalk/common/server/RedisNodeManager.java
import io.stalk.common.server.ServerNodeManager.SERVER;
import io.stalk.common.server.map.NodeMap;
import io.stalk.common.server.map.NodeRegistry;
import io.stalk.common.server.node.RedisPoolNode;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.core.logging.Logger;
import java.util.HashMap;
package io.stalk.common.server;
public class RedisNodeManager extends AbstractNodeManager<RedisPoolNode> {
private boolean isOk = false;
public RedisNodeManager() {
super();
}
public RedisNodeManager(Logger logger) {
super();
if (logger != null) activeLogger(logger);
}
public RedisNodeManager(Logger logger, String prefix) {
super();
if (logger != null) activeLogger(logger, prefix);
}
@Override
protected NodeMap<RedisPoolNode> initNodeMap() { | return new NodeRegistry<RedisPoolNode>(); |
stalk-io/stalk-server | src/main/java/io/stalk/common/server/RedisNodeManager.java | // Path: src/main/java/io/stalk/common/server/ServerNodeManager.java
// interface SERVER {
//
// String NODE = "server:node";
// String NODE_BY_CHANNEL = "server:nodeByChannel";
// String OK = "server:Ok";
//
// }
//
// Path: src/main/java/io/stalk/common/server/map/NodeMap.java
// public interface NodeMap<T> {
//
// public void add(String key, T node);
//
// public void remove(String key);
//
// public T get(String key);
//
// public boolean isExist(String key);
//
// public Set<String> getKeys();
//
// }
//
// Path: src/main/java/io/stalk/common/server/map/NodeRegistry.java
// public class NodeRegistry<T> implements NodeMap<T> {
//
// private final HashMap<String, T> keyMap = new HashMap<String, T>();
//
// public NodeRegistry() {
// }
//
// @Override
// public void add(String key, T node) {
// keyMap.put(key, node);
//
// }
//
// @Override
// public void remove(String key) {
// keyMap.remove(key);
// }
//
// @Override
// public T get(String key) {
// return keyMap.get(key);
// }
//
// @Override
// public boolean isExist(String key) {
// return keyMap.containsKey(key);
// }
//
// @Override
// public Set<String> getKeys() {
// return keyMap.keySet();
// }
//
// }
//
// Path: src/main/java/io/stalk/common/server/node/RedisPoolNode.java
// public class RedisPoolNode extends AbstractNode {
//
// private String channel;
// private JedisPool jedisPool;
//
// public RedisPoolNode(JsonObject jsonObject, Logger log, String prefix) {
//
// super(log, prefix);
//
// this.channel = jsonObject.getString("channel");
//
// JedisPoolConfig config = new JedisPoolConfig();
// config.testOnBorrow = true;
//
// JedisPool jedisPool;
//
// if (StringUtils.isEmpty(jsonObject.getString("host"))) {
// jedisPool = new JedisPool(config, "localhost");
// } else {
// jedisPool = new JedisPool(config,
// jsonObject.getString("host"),
// jsonObject.getInteger("port").intValue());
// }
//
// this.jedisPool = jedisPool;
//
//
// Jedis jedis = this.jedisPool.getResource();
// DEBUG("connected <%s!!> %s", jedis.ping(), jsonObject);
// this.jedisPool.returnResource(jedis);
// }
//
// public String getChannel() {
// return channel;
// }
//
// public void setChannel(String channel) {
// this.channel = channel;
// }
//
// public JedisPool getJedisPool() {
// return jedisPool;
// }
//
// public void setJedisPool(JedisPool jedisPool) {
// this.jedisPool = jedisPool;
// }
//
// public Long hset(String key, String field, String value) {
// Jedis jedis = jedisPool.getResource();
// Long status = jedis.hset(key, field, value);
// jedisPool.returnResource(jedis);
//
// return status;
// }
//
// public String hget(String key, String field) {
// Jedis jedis = jedisPool.getResource();
// String value = jedis.hget(key, field);
// jedisPool.returnResource(jedis);
//
// return value;
// }
//
// public Set<String> hkeys(String key) {
// Jedis jedis = jedisPool.getResource();
// Set<String> keys = jedis.hkeys(key);
// jedisPool.returnResource(jedis);
//
// return keys;
// }
//
// public Long hdel(String key, String... field) {
// Jedis jedis = jedisPool.getResource();
// Long status = jedis.hdel(key, field);
// jedisPool.returnResource(jedis);
//
// return status;
// }
//
// public String set(String key, String value) {
// Jedis jedis = jedisPool.getResource();
// String returnVal = jedis.set(key, value);
// jedisPool.returnResource(jedis);
//
// return returnVal;
// }
//
// public String get(String key) {
// Jedis jedis = jedisPool.getResource();
// String value = jedis.get(key);
// jedisPool.returnResource(jedis);
//
// return value;
// }
//
// public Long publish(String channel, String message) {
// Jedis jedis = jedisPool.getResource();
// Long status = jedis.publish(channel, message);
// jedisPool.returnResource(jedis);
//
// return status;
// }
//
// }
| import io.stalk.common.server.ServerNodeManager.SERVER;
import io.stalk.common.server.map.NodeMap;
import io.stalk.common.server.map.NodeRegistry;
import io.stalk.common.server.node.RedisPoolNode;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.core.logging.Logger;
import java.util.HashMap; | }
}
DEBUG("refreshNode - size : %d ", nodes.getKeys().size());
if (nodes.getKeys().size() > 0) {
isOk = true;
} else {
isOk = false;
}
}
@Override
public void messageHandle(Message<JsonObject> message) {
String action = message.body().getString("action");
DEBUG("messageHandle : %s ", message.body());
// to be deleted!!!
switch (action) {
case "message:publish":
sendOK(message, publish(
message.body().getString("channel"),
message.body()
));
break;
| // Path: src/main/java/io/stalk/common/server/ServerNodeManager.java
// interface SERVER {
//
// String NODE = "server:node";
// String NODE_BY_CHANNEL = "server:nodeByChannel";
// String OK = "server:Ok";
//
// }
//
// Path: src/main/java/io/stalk/common/server/map/NodeMap.java
// public interface NodeMap<T> {
//
// public void add(String key, T node);
//
// public void remove(String key);
//
// public T get(String key);
//
// public boolean isExist(String key);
//
// public Set<String> getKeys();
//
// }
//
// Path: src/main/java/io/stalk/common/server/map/NodeRegistry.java
// public class NodeRegistry<T> implements NodeMap<T> {
//
// private final HashMap<String, T> keyMap = new HashMap<String, T>();
//
// public NodeRegistry() {
// }
//
// @Override
// public void add(String key, T node) {
// keyMap.put(key, node);
//
// }
//
// @Override
// public void remove(String key) {
// keyMap.remove(key);
// }
//
// @Override
// public T get(String key) {
// return keyMap.get(key);
// }
//
// @Override
// public boolean isExist(String key) {
// return keyMap.containsKey(key);
// }
//
// @Override
// public Set<String> getKeys() {
// return keyMap.keySet();
// }
//
// }
//
// Path: src/main/java/io/stalk/common/server/node/RedisPoolNode.java
// public class RedisPoolNode extends AbstractNode {
//
// private String channel;
// private JedisPool jedisPool;
//
// public RedisPoolNode(JsonObject jsonObject, Logger log, String prefix) {
//
// super(log, prefix);
//
// this.channel = jsonObject.getString("channel");
//
// JedisPoolConfig config = new JedisPoolConfig();
// config.testOnBorrow = true;
//
// JedisPool jedisPool;
//
// if (StringUtils.isEmpty(jsonObject.getString("host"))) {
// jedisPool = new JedisPool(config, "localhost");
// } else {
// jedisPool = new JedisPool(config,
// jsonObject.getString("host"),
// jsonObject.getInteger("port").intValue());
// }
//
// this.jedisPool = jedisPool;
//
//
// Jedis jedis = this.jedisPool.getResource();
// DEBUG("connected <%s!!> %s", jedis.ping(), jsonObject);
// this.jedisPool.returnResource(jedis);
// }
//
// public String getChannel() {
// return channel;
// }
//
// public void setChannel(String channel) {
// this.channel = channel;
// }
//
// public JedisPool getJedisPool() {
// return jedisPool;
// }
//
// public void setJedisPool(JedisPool jedisPool) {
// this.jedisPool = jedisPool;
// }
//
// public Long hset(String key, String field, String value) {
// Jedis jedis = jedisPool.getResource();
// Long status = jedis.hset(key, field, value);
// jedisPool.returnResource(jedis);
//
// return status;
// }
//
// public String hget(String key, String field) {
// Jedis jedis = jedisPool.getResource();
// String value = jedis.hget(key, field);
// jedisPool.returnResource(jedis);
//
// return value;
// }
//
// public Set<String> hkeys(String key) {
// Jedis jedis = jedisPool.getResource();
// Set<String> keys = jedis.hkeys(key);
// jedisPool.returnResource(jedis);
//
// return keys;
// }
//
// public Long hdel(String key, String... field) {
// Jedis jedis = jedisPool.getResource();
// Long status = jedis.hdel(key, field);
// jedisPool.returnResource(jedis);
//
// return status;
// }
//
// public String set(String key, String value) {
// Jedis jedis = jedisPool.getResource();
// String returnVal = jedis.set(key, value);
// jedisPool.returnResource(jedis);
//
// return returnVal;
// }
//
// public String get(String key) {
// Jedis jedis = jedisPool.getResource();
// String value = jedis.get(key);
// jedisPool.returnResource(jedis);
//
// return value;
// }
//
// public Long publish(String channel, String message) {
// Jedis jedis = jedisPool.getResource();
// Long status = jedis.publish(channel, message);
// jedisPool.returnResource(jedis);
//
// return status;
// }
//
// }
// Path: src/main/java/io/stalk/common/server/RedisNodeManager.java
import io.stalk.common.server.ServerNodeManager.SERVER;
import io.stalk.common.server.map.NodeMap;
import io.stalk.common.server.map.NodeRegistry;
import io.stalk.common.server.node.RedisPoolNode;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.core.logging.Logger;
import java.util.HashMap;
}
}
DEBUG("refreshNode - size : %d ", nodes.getKeys().size());
if (nodes.getKeys().size() > 0) {
isOk = true;
} else {
isOk = false;
}
}
@Override
public void messageHandle(Message<JsonObject> message) {
String action = message.body().getString("action");
DEBUG("messageHandle : %s ", message.body());
// to be deleted!!!
switch (action) {
case "message:publish":
sendOK(message, publish(
message.body().getString("channel"),
message.body()
));
break;
| case SERVER.OK: |
stalk-io/stalk-server | src/main/java/io/stalk/common/oauth/utils/OpenIdConsumer.java | // Path: src/main/java/io/stalk/common/oauth/Profile.java
// public class Profile {
//
// private String name;
// private String link;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getLink() {
// return link;
// }
//
// public void setLink(String link) {
// this.link = link;
// }
//
//
// }
| import io.stalk.common.oauth.Profile;
import java.util.HashMap;
import java.util.Map;
| * @param scope
* @return Generated Request Token URL
* @throws Exception
*/
public static String getRequestTokenURL(final String requestTokenUrl,
final String returnTo, final String realm,
final String assocHandle, final String consumerURL,
final String scope) throws Exception {
Map<String, String> params = new HashMap<String, String>();
params.putAll(requestTokenMap);
params.put("openid.return_to", returnTo);
params.put("openid.realm", realm);
params.put("openid.assoc_handle", assocHandle);
params.put("openid.ext2.consumer", consumerURL);
if (scope != null) {
params.put("openid.ext2.scope", scope);
}
String paramStr = HttpUtil.buildParams(params);
char separator = requestTokenUrl.indexOf('?') == -1 ? '?' : '&';
String url = requestTokenUrl + separator + paramStr;
System.out.println("Request Token URL : " + url);
return url;
}
/**
* Parses the user info from request
*
* @param requestParams request parameters map
* @return User Profile
*/
| // Path: src/main/java/io/stalk/common/oauth/Profile.java
// public class Profile {
//
// private String name;
// private String link;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getLink() {
// return link;
// }
//
// public void setLink(String link) {
// this.link = link;
// }
//
//
// }
// Path: src/main/java/io/stalk/common/oauth/utils/OpenIdConsumer.java
import io.stalk.common.oauth.Profile;
import java.util.HashMap;
import java.util.Map;
* @param scope
* @return Generated Request Token URL
* @throws Exception
*/
public static String getRequestTokenURL(final String requestTokenUrl,
final String returnTo, final String realm,
final String assocHandle, final String consumerURL,
final String scope) throws Exception {
Map<String, String> params = new HashMap<String, String>();
params.putAll(requestTokenMap);
params.put("openid.return_to", returnTo);
params.put("openid.realm", realm);
params.put("openid.assoc_handle", assocHandle);
params.put("openid.ext2.consumer", consumerURL);
if (scope != null) {
params.put("openid.ext2.scope", scope);
}
String paramStr = HttpUtil.buildParams(params);
char separator = requestTokenUrl.indexOf('?') == -1 ? '?' : '&';
String url = requestTokenUrl + separator + paramStr;
System.out.println("Request Token URL : " + url);
return url;
}
/**
* Parses the user info from request
*
* @param requestParams request parameters map
* @return User Profile
*/
| public static Profile getUserInfo(final Map<String, String> requestParams) {
|
stalk-io/stalk-server | src/main/java/io/stalk/common/server/ServerNodeManager.java | // Path: src/main/java/io/stalk/common/server/map/ConsistentHash.java
// public class ConsistentHash<T> implements NodeMap<T> {
//
// public static final int NUMBER_OF_REPLICAS = 100;
//
// private final HashMap<String, Long[]> keyMap = new HashMap<String, Long[]>();
//
// private final HashFunction hashFunction;
// private final int numberOfReplicas;
// private final SortedMap<Long, T> circle = new TreeMap<Long, T>();
//
// public ConsistentHash() {
// this(Hashing.md5(), NUMBER_OF_REPLICAS);
// }
//
// public ConsistentHash(int numberOfReplicas) {
// this(Hashing.md5(), numberOfReplicas);
// }
//
// public ConsistentHash(HashFunction hashFunction, int numberOfReplicas) {
// this.hashFunction = hashFunction;
// this.numberOfReplicas = numberOfReplicas;
// }
//
// public void add(String key, T node) {
// Long keyArray[] = new Long[numberOfReplicas];
// for (int i = 0; i < numberOfReplicas; i++) {
// circle.put(hashFunction.hashString(key + i).asLong(),
// node);
// keyArray[i] = hashFunction.hashString(key + i).asLong();
// }
// keyMap.put(key, keyArray);
// }
//
// public void remove(String key) {
//
// for (int i = 0; i < numberOfReplicas; i++) {
// circle.remove(hashFunction.hashString(key + i).asLong());
// }
// keyMap.remove(key);
// }
//
// public boolean isExist(String key) {
// return keyMap.containsKey(key);
// }
//
// public Set<String> getKeys() {
// return keyMap.keySet();
// }
//
// public T get(String key) {
// if (circle.isEmpty()) {
// return null;
// }
// long hash = hashFunction.hashString(key).asLong();
// if (!circle.containsKey(hash)) {
// SortedMap<Long, T> tailMap = circle.tailMap(hash);
// hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();
// }
// return circle.get(hash);
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/server/map/NodeMap.java
// public interface NodeMap<T> {
//
// public void add(String key, T node);
//
// public void remove(String key);
//
// public T get(String key);
//
// public boolean isExist(String key);
//
// public Set<String> getKeys();
//
// }
//
// Path: src/main/java/io/stalk/common/server/node/ServerNode.java
// public class ServerNode extends AbstractNode {
//
// // @ TODO to Map!!!
// private String channel;
//
// private String host;
// private int port;
//
// public ServerNode(String host, int port, String channel, Logger log) {
// super(log, "SERVER");
// this.host = host;
// this.port = port;
// this.channel = channel;
// }
//
// public ServerNode(JsonObject jsonObject, Logger log) {
// super(log, "SERVER");
// this.channel = jsonObject.getString("channel");
// this.host = jsonObject.getString("host");
// this.port = jsonObject.getNumber("port").intValue();
//
// DEBUG("created %s", jsonObject);
// }
//
// public String getHost() {
// return host;
// }
//
//
// public void setHost(String host) {
// this.host = host;
// }
//
// public String getChannel() {
// return channel;
// }
//
// public void setChannel(String channel) {
// this.channel = channel;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
//
// }
| import io.stalk.common.server.map.ConsistentHash;
import io.stalk.common.server.map.NodeMap;
import io.stalk.common.server.node.ServerNode;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.core.logging.Logger;
import java.util.HashMap; | package io.stalk.common.server;
public class ServerNodeManager extends AbstractNodeManager<ServerNode> {
interface SERVER {
String NODE = "server:node";
String NODE_BY_CHANNEL = "server:nodeByChannel";
String OK = "server:Ok";
}
private boolean isOk = false;
private HashMap<String, ServerNode> serverList = new HashMap<String, ServerNode>();
public ServerNodeManager() {
super();
}
public ServerNodeManager(Logger logger) {
super();
if (logger != null) activeLogger(logger, "SERVER");
}
@Override | // Path: src/main/java/io/stalk/common/server/map/ConsistentHash.java
// public class ConsistentHash<T> implements NodeMap<T> {
//
// public static final int NUMBER_OF_REPLICAS = 100;
//
// private final HashMap<String, Long[]> keyMap = new HashMap<String, Long[]>();
//
// private final HashFunction hashFunction;
// private final int numberOfReplicas;
// private final SortedMap<Long, T> circle = new TreeMap<Long, T>();
//
// public ConsistentHash() {
// this(Hashing.md5(), NUMBER_OF_REPLICAS);
// }
//
// public ConsistentHash(int numberOfReplicas) {
// this(Hashing.md5(), numberOfReplicas);
// }
//
// public ConsistentHash(HashFunction hashFunction, int numberOfReplicas) {
// this.hashFunction = hashFunction;
// this.numberOfReplicas = numberOfReplicas;
// }
//
// public void add(String key, T node) {
// Long keyArray[] = new Long[numberOfReplicas];
// for (int i = 0; i < numberOfReplicas; i++) {
// circle.put(hashFunction.hashString(key + i).asLong(),
// node);
// keyArray[i] = hashFunction.hashString(key + i).asLong();
// }
// keyMap.put(key, keyArray);
// }
//
// public void remove(String key) {
//
// for (int i = 0; i < numberOfReplicas; i++) {
// circle.remove(hashFunction.hashString(key + i).asLong());
// }
// keyMap.remove(key);
// }
//
// public boolean isExist(String key) {
// return keyMap.containsKey(key);
// }
//
// public Set<String> getKeys() {
// return keyMap.keySet();
// }
//
// public T get(String key) {
// if (circle.isEmpty()) {
// return null;
// }
// long hash = hashFunction.hashString(key).asLong();
// if (!circle.containsKey(hash)) {
// SortedMap<Long, T> tailMap = circle.tailMap(hash);
// hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();
// }
// return circle.get(hash);
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/server/map/NodeMap.java
// public interface NodeMap<T> {
//
// public void add(String key, T node);
//
// public void remove(String key);
//
// public T get(String key);
//
// public boolean isExist(String key);
//
// public Set<String> getKeys();
//
// }
//
// Path: src/main/java/io/stalk/common/server/node/ServerNode.java
// public class ServerNode extends AbstractNode {
//
// // @ TODO to Map!!!
// private String channel;
//
// private String host;
// private int port;
//
// public ServerNode(String host, int port, String channel, Logger log) {
// super(log, "SERVER");
// this.host = host;
// this.port = port;
// this.channel = channel;
// }
//
// public ServerNode(JsonObject jsonObject, Logger log) {
// super(log, "SERVER");
// this.channel = jsonObject.getString("channel");
// this.host = jsonObject.getString("host");
// this.port = jsonObject.getNumber("port").intValue();
//
// DEBUG("created %s", jsonObject);
// }
//
// public String getHost() {
// return host;
// }
//
//
// public void setHost(String host) {
// this.host = host;
// }
//
// public String getChannel() {
// return channel;
// }
//
// public void setChannel(String channel) {
// this.channel = channel;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
//
// }
// Path: src/main/java/io/stalk/common/server/ServerNodeManager.java
import io.stalk.common.server.map.ConsistentHash;
import io.stalk.common.server.map.NodeMap;
import io.stalk.common.server.node.ServerNode;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.core.logging.Logger;
import java.util.HashMap;
package io.stalk.common.server;
public class ServerNodeManager extends AbstractNodeManager<ServerNode> {
interface SERVER {
String NODE = "server:node";
String NODE_BY_CHANNEL = "server:nodeByChannel";
String OK = "server:Ok";
}
private boolean isOk = false;
private HashMap<String, ServerNode> serverList = new HashMap<String, ServerNode>();
public ServerNodeManager() {
super();
}
public ServerNodeManager(Logger logger) {
super();
if (logger != null) activeLogger(logger, "SERVER");
}
@Override | protected NodeMap<ServerNode> initNodeMap() { |
stalk-io/stalk-server | src/main/java/io/stalk/common/server/ServerNodeManager.java | // Path: src/main/java/io/stalk/common/server/map/ConsistentHash.java
// public class ConsistentHash<T> implements NodeMap<T> {
//
// public static final int NUMBER_OF_REPLICAS = 100;
//
// private final HashMap<String, Long[]> keyMap = new HashMap<String, Long[]>();
//
// private final HashFunction hashFunction;
// private final int numberOfReplicas;
// private final SortedMap<Long, T> circle = new TreeMap<Long, T>();
//
// public ConsistentHash() {
// this(Hashing.md5(), NUMBER_OF_REPLICAS);
// }
//
// public ConsistentHash(int numberOfReplicas) {
// this(Hashing.md5(), numberOfReplicas);
// }
//
// public ConsistentHash(HashFunction hashFunction, int numberOfReplicas) {
// this.hashFunction = hashFunction;
// this.numberOfReplicas = numberOfReplicas;
// }
//
// public void add(String key, T node) {
// Long keyArray[] = new Long[numberOfReplicas];
// for (int i = 0; i < numberOfReplicas; i++) {
// circle.put(hashFunction.hashString(key + i).asLong(),
// node);
// keyArray[i] = hashFunction.hashString(key + i).asLong();
// }
// keyMap.put(key, keyArray);
// }
//
// public void remove(String key) {
//
// for (int i = 0; i < numberOfReplicas; i++) {
// circle.remove(hashFunction.hashString(key + i).asLong());
// }
// keyMap.remove(key);
// }
//
// public boolean isExist(String key) {
// return keyMap.containsKey(key);
// }
//
// public Set<String> getKeys() {
// return keyMap.keySet();
// }
//
// public T get(String key) {
// if (circle.isEmpty()) {
// return null;
// }
// long hash = hashFunction.hashString(key).asLong();
// if (!circle.containsKey(hash)) {
// SortedMap<Long, T> tailMap = circle.tailMap(hash);
// hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();
// }
// return circle.get(hash);
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/server/map/NodeMap.java
// public interface NodeMap<T> {
//
// public void add(String key, T node);
//
// public void remove(String key);
//
// public T get(String key);
//
// public boolean isExist(String key);
//
// public Set<String> getKeys();
//
// }
//
// Path: src/main/java/io/stalk/common/server/node/ServerNode.java
// public class ServerNode extends AbstractNode {
//
// // @ TODO to Map!!!
// private String channel;
//
// private String host;
// private int port;
//
// public ServerNode(String host, int port, String channel, Logger log) {
// super(log, "SERVER");
// this.host = host;
// this.port = port;
// this.channel = channel;
// }
//
// public ServerNode(JsonObject jsonObject, Logger log) {
// super(log, "SERVER");
// this.channel = jsonObject.getString("channel");
// this.host = jsonObject.getString("host");
// this.port = jsonObject.getNumber("port").intValue();
//
// DEBUG("created %s", jsonObject);
// }
//
// public String getHost() {
// return host;
// }
//
//
// public void setHost(String host) {
// this.host = host;
// }
//
// public String getChannel() {
// return channel;
// }
//
// public void setChannel(String channel) {
// this.channel = channel;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
//
// }
| import io.stalk.common.server.map.ConsistentHash;
import io.stalk.common.server.map.NodeMap;
import io.stalk.common.server.node.ServerNode;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.core.logging.Logger;
import java.util.HashMap; | package io.stalk.common.server;
public class ServerNodeManager extends AbstractNodeManager<ServerNode> {
interface SERVER {
String NODE = "server:node";
String NODE_BY_CHANNEL = "server:nodeByChannel";
String OK = "server:Ok";
}
private boolean isOk = false;
private HashMap<String, ServerNode> serverList = new HashMap<String, ServerNode>();
public ServerNodeManager() {
super();
}
public ServerNodeManager(Logger logger) {
super();
if (logger != null) activeLogger(logger, "SERVER");
}
@Override
protected NodeMap<ServerNode> initNodeMap() { | // Path: src/main/java/io/stalk/common/server/map/ConsistentHash.java
// public class ConsistentHash<T> implements NodeMap<T> {
//
// public static final int NUMBER_OF_REPLICAS = 100;
//
// private final HashMap<String, Long[]> keyMap = new HashMap<String, Long[]>();
//
// private final HashFunction hashFunction;
// private final int numberOfReplicas;
// private final SortedMap<Long, T> circle = new TreeMap<Long, T>();
//
// public ConsistentHash() {
// this(Hashing.md5(), NUMBER_OF_REPLICAS);
// }
//
// public ConsistentHash(int numberOfReplicas) {
// this(Hashing.md5(), numberOfReplicas);
// }
//
// public ConsistentHash(HashFunction hashFunction, int numberOfReplicas) {
// this.hashFunction = hashFunction;
// this.numberOfReplicas = numberOfReplicas;
// }
//
// public void add(String key, T node) {
// Long keyArray[] = new Long[numberOfReplicas];
// for (int i = 0; i < numberOfReplicas; i++) {
// circle.put(hashFunction.hashString(key + i).asLong(),
// node);
// keyArray[i] = hashFunction.hashString(key + i).asLong();
// }
// keyMap.put(key, keyArray);
// }
//
// public void remove(String key) {
//
// for (int i = 0; i < numberOfReplicas; i++) {
// circle.remove(hashFunction.hashString(key + i).asLong());
// }
// keyMap.remove(key);
// }
//
// public boolean isExist(String key) {
// return keyMap.containsKey(key);
// }
//
// public Set<String> getKeys() {
// return keyMap.keySet();
// }
//
// public T get(String key) {
// if (circle.isEmpty()) {
// return null;
// }
// long hash = hashFunction.hashString(key).asLong();
// if (!circle.containsKey(hash)) {
// SortedMap<Long, T> tailMap = circle.tailMap(hash);
// hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();
// }
// return circle.get(hash);
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/server/map/NodeMap.java
// public interface NodeMap<T> {
//
// public void add(String key, T node);
//
// public void remove(String key);
//
// public T get(String key);
//
// public boolean isExist(String key);
//
// public Set<String> getKeys();
//
// }
//
// Path: src/main/java/io/stalk/common/server/node/ServerNode.java
// public class ServerNode extends AbstractNode {
//
// // @ TODO to Map!!!
// private String channel;
//
// private String host;
// private int port;
//
// public ServerNode(String host, int port, String channel, Logger log) {
// super(log, "SERVER");
// this.host = host;
// this.port = port;
// this.channel = channel;
// }
//
// public ServerNode(JsonObject jsonObject, Logger log) {
// super(log, "SERVER");
// this.channel = jsonObject.getString("channel");
// this.host = jsonObject.getString("host");
// this.port = jsonObject.getNumber("port").intValue();
//
// DEBUG("created %s", jsonObject);
// }
//
// public String getHost() {
// return host;
// }
//
//
// public void setHost(String host) {
// this.host = host;
// }
//
// public String getChannel() {
// return channel;
// }
//
// public void setChannel(String channel) {
// this.channel = channel;
// }
//
// public int getPort() {
// return port;
// }
//
// public void setPort(int port) {
// this.port = port;
// }
//
//
// }
// Path: src/main/java/io/stalk/common/server/ServerNodeManager.java
import io.stalk.common.server.map.ConsistentHash;
import io.stalk.common.server.map.NodeMap;
import io.stalk.common.server.node.ServerNode;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.core.logging.Logger;
import java.util.HashMap;
package io.stalk.common.server;
public class ServerNodeManager extends AbstractNodeManager<ServerNode> {
interface SERVER {
String NODE = "server:node";
String NODE_BY_CHANNEL = "server:nodeByChannel";
String OK = "server:Ok";
}
private boolean isOk = false;
private HashMap<String, ServerNode> serverList = new HashMap<String, ServerNode>();
public ServerNodeManager() {
super();
}
public ServerNodeManager(Logger logger) {
super();
if (logger != null) activeLogger(logger, "SERVER");
}
@Override
protected NodeMap<ServerNode> initNodeMap() { | return new ConsistentHash<ServerNode>(); |
stalk-io/stalk-server | src/main/java/io/stalk/common/oauth/strategy/Hybrid.java | // Path: src/main/java/io/stalk/common/oauth/OAuthConfig.java
// public class OAuthConfig {
//
// private final String _consumerKey;
// private final String _consumerSecret;
// private final String _callbackUrl;
// private final String _signatureMethod;
// private final String _transportName;
// private String id;
// private Class<?> providerImplClass;
//
//
// public OAuthConfig(final String consumerKey, final String consumerSecret, final String callbackUrl,
// final String signatureMethod, final String transportName) {
// _consumerKey = consumerKey;
// _consumerSecret = consumerSecret;
// if (signatureMethod == null || signatureMethod.length() == 0) {
// _signatureMethod = Constants.HMACSHA1_SIGNATURE;
// } else {
// _signatureMethod = signatureMethod;
// }
// if (transportName == null || transportName.length() == 0) {
// _transportName = MethodType.GET.toString();
// } else {
// _transportName = transportName;
// }
// if (callbackUrl == null || callbackUrl.length() == 0) {
// _callbackUrl = "";
// } else {
// _callbackUrl = callbackUrl;
// }
//
// }
//
// public OAuthConfig(final String consumerKey, final String consumerSecret, final String callbackUrl) {
// _consumerKey = consumerKey;
// _consumerSecret = consumerSecret;
// _transportName = MethodType.GET.toString();
// _signatureMethod = Constants.HMACSHA1_SIGNATURE;
//
//
// if (callbackUrl == null || callbackUrl.length() == 0) {
// _callbackUrl = "";
// } else {
// _callbackUrl = callbackUrl;
// }
// }
//
// public String get_consumerKey() {
// return _consumerKey;
// }
//
// public String get_consumerSecret() {
// return _consumerSecret;
// }
//
// public String get_callbackUrl() {
// return _callbackUrl;
// }
//
// public String get_signatureMethod() {
// return _signatureMethod;
// }
//
// public String get_transportName() {
// return _transportName;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(final String id) {
// this.id = id;
// }
//
// public Class<?> getProviderImplClass() {
// return providerImplClass;
// }
//
// public void setProviderImplClass(final Class<?> providerImplClass) {
// this.providerImplClass = providerImplClass;
// }
//
// @Override
// public String toString() {
// StringBuilder result = new StringBuilder();
// String NEW_LINE = System.getProperty("line.separator");
// result.append(this.getClass().getName() + " Object {" + NEW_LINE);
// result.append(" consumerKey: " + _consumerKey + NEW_LINE);
// result.append(" consumerSecret: " + _consumerSecret + NEW_LINE);
// result.append(" signatureMethod: " + _signatureMethod + NEW_LINE);
// result.append(" transportName: " + _transportName + NEW_LINE);
// result.append(" id: " + id + NEW_LINE);
// result.append(" providerImplClass: " + providerImplClass + NEW_LINE);
// result.append("}");
// return result.toString();
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/oauth/exception/SocialAuthConfigurationException.java
// public class SocialAuthConfigurationException extends Exception {
//
// private static final long serialVersionUID = 477153534655510364L;
//
// public SocialAuthConfigurationException() {
// super();
// }
//
// /**
// * @param message
// */
// public SocialAuthConfigurationException(final String message) {
// super(message);
// }
//
// /**
// * @param cause
// */
// public SocialAuthConfigurationException(final Throwable cause) {
// super(cause);
// }
//
// /**
// * @param message
// * @param cause
// */
// public SocialAuthConfigurationException(final String message,
// final Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/io/stalk/common/oauth/exception/SocialAuthException.java
// public class SocialAuthException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -6856436294292027306L;
//
// public SocialAuthException() {
// super();
// }
//
// public SocialAuthException(final String message) {
// super(message);
// }
//
// public SocialAuthException(final Throwable cause) {
// super(cause);
// }
//
// public SocialAuthException(final String message, final Throwable cause) {
// super(message, cause);
// }
// }
| import io.stalk.common.oauth.OAuthConfig;
import io.stalk.common.oauth.exception.SocialAuthConfigurationException;
import io.stalk.common.oauth.exception.SocialAuthException;
import io.stalk.common.oauth.utils.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;
| package io.stalk.common.oauth.strategy;
public class Hybrid implements OAuthStrategyBase {
private Map<String, String> endpoints;
private String scope;
private String providerId;
private OAuthConsumer oauth;
private String successUrl;
| // Path: src/main/java/io/stalk/common/oauth/OAuthConfig.java
// public class OAuthConfig {
//
// private final String _consumerKey;
// private final String _consumerSecret;
// private final String _callbackUrl;
// private final String _signatureMethod;
// private final String _transportName;
// private String id;
// private Class<?> providerImplClass;
//
//
// public OAuthConfig(final String consumerKey, final String consumerSecret, final String callbackUrl,
// final String signatureMethod, final String transportName) {
// _consumerKey = consumerKey;
// _consumerSecret = consumerSecret;
// if (signatureMethod == null || signatureMethod.length() == 0) {
// _signatureMethod = Constants.HMACSHA1_SIGNATURE;
// } else {
// _signatureMethod = signatureMethod;
// }
// if (transportName == null || transportName.length() == 0) {
// _transportName = MethodType.GET.toString();
// } else {
// _transportName = transportName;
// }
// if (callbackUrl == null || callbackUrl.length() == 0) {
// _callbackUrl = "";
// } else {
// _callbackUrl = callbackUrl;
// }
//
// }
//
// public OAuthConfig(final String consumerKey, final String consumerSecret, final String callbackUrl) {
// _consumerKey = consumerKey;
// _consumerSecret = consumerSecret;
// _transportName = MethodType.GET.toString();
// _signatureMethod = Constants.HMACSHA1_SIGNATURE;
//
//
// if (callbackUrl == null || callbackUrl.length() == 0) {
// _callbackUrl = "";
// } else {
// _callbackUrl = callbackUrl;
// }
// }
//
// public String get_consumerKey() {
// return _consumerKey;
// }
//
// public String get_consumerSecret() {
// return _consumerSecret;
// }
//
// public String get_callbackUrl() {
// return _callbackUrl;
// }
//
// public String get_signatureMethod() {
// return _signatureMethod;
// }
//
// public String get_transportName() {
// return _transportName;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(final String id) {
// this.id = id;
// }
//
// public Class<?> getProviderImplClass() {
// return providerImplClass;
// }
//
// public void setProviderImplClass(final Class<?> providerImplClass) {
// this.providerImplClass = providerImplClass;
// }
//
// @Override
// public String toString() {
// StringBuilder result = new StringBuilder();
// String NEW_LINE = System.getProperty("line.separator");
// result.append(this.getClass().getName() + " Object {" + NEW_LINE);
// result.append(" consumerKey: " + _consumerKey + NEW_LINE);
// result.append(" consumerSecret: " + _consumerSecret + NEW_LINE);
// result.append(" signatureMethod: " + _signatureMethod + NEW_LINE);
// result.append(" transportName: " + _transportName + NEW_LINE);
// result.append(" id: " + id + NEW_LINE);
// result.append(" providerImplClass: " + providerImplClass + NEW_LINE);
// result.append("}");
// return result.toString();
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/oauth/exception/SocialAuthConfigurationException.java
// public class SocialAuthConfigurationException extends Exception {
//
// private static final long serialVersionUID = 477153534655510364L;
//
// public SocialAuthConfigurationException() {
// super();
// }
//
// /**
// * @param message
// */
// public SocialAuthConfigurationException(final String message) {
// super(message);
// }
//
// /**
// * @param cause
// */
// public SocialAuthConfigurationException(final Throwable cause) {
// super(cause);
// }
//
// /**
// * @param message
// * @param cause
// */
// public SocialAuthConfigurationException(final String message,
// final Throwable cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/io/stalk/common/oauth/exception/SocialAuthException.java
// public class SocialAuthException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -6856436294292027306L;
//
// public SocialAuthException() {
// super();
// }
//
// public SocialAuthException(final String message) {
// super(message);
// }
//
// public SocialAuthException(final Throwable cause) {
// super(cause);
// }
//
// public SocialAuthException(final String message, final Throwable cause) {
// super(message, cause);
// }
// }
// Path: src/main/java/io/stalk/common/oauth/strategy/Hybrid.java
import io.stalk.common.oauth.OAuthConfig;
import io.stalk.common.oauth.exception.SocialAuthConfigurationException;
import io.stalk.common.oauth.exception.SocialAuthException;
import io.stalk.common.oauth.utils.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;
package io.stalk.common.oauth.strategy;
public class Hybrid implements OAuthStrategyBase {
private Map<String, String> endpoints;
private String scope;
private String providerId;
private OAuthConsumer oauth;
private String successUrl;
| public Hybrid(final OAuthConfig config, final Map<String, String> endpoints) {
|
stalk-io/stalk-server | src/main/java/io/stalk/common/oauth/strategy/OAuth1.java | // Path: src/main/java/io/stalk/common/oauth/OAuthConfig.java
// public class OAuthConfig {
//
// private final String _consumerKey;
// private final String _consumerSecret;
// private final String _callbackUrl;
// private final String _signatureMethod;
// private final String _transportName;
// private String id;
// private Class<?> providerImplClass;
//
//
// public OAuthConfig(final String consumerKey, final String consumerSecret, final String callbackUrl,
// final String signatureMethod, final String transportName) {
// _consumerKey = consumerKey;
// _consumerSecret = consumerSecret;
// if (signatureMethod == null || signatureMethod.length() == 0) {
// _signatureMethod = Constants.HMACSHA1_SIGNATURE;
// } else {
// _signatureMethod = signatureMethod;
// }
// if (transportName == null || transportName.length() == 0) {
// _transportName = MethodType.GET.toString();
// } else {
// _transportName = transportName;
// }
// if (callbackUrl == null || callbackUrl.length() == 0) {
// _callbackUrl = "";
// } else {
// _callbackUrl = callbackUrl;
// }
//
// }
//
// public OAuthConfig(final String consumerKey, final String consumerSecret, final String callbackUrl) {
// _consumerKey = consumerKey;
// _consumerSecret = consumerSecret;
// _transportName = MethodType.GET.toString();
// _signatureMethod = Constants.HMACSHA1_SIGNATURE;
//
//
// if (callbackUrl == null || callbackUrl.length() == 0) {
// _callbackUrl = "";
// } else {
// _callbackUrl = callbackUrl;
// }
// }
//
// public String get_consumerKey() {
// return _consumerKey;
// }
//
// public String get_consumerSecret() {
// return _consumerSecret;
// }
//
// public String get_callbackUrl() {
// return _callbackUrl;
// }
//
// public String get_signatureMethod() {
// return _signatureMethod;
// }
//
// public String get_transportName() {
// return _transportName;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(final String id) {
// this.id = id;
// }
//
// public Class<?> getProviderImplClass() {
// return providerImplClass;
// }
//
// public void setProviderImplClass(final Class<?> providerImplClass) {
// this.providerImplClass = providerImplClass;
// }
//
// @Override
// public String toString() {
// StringBuilder result = new StringBuilder();
// String NEW_LINE = System.getProperty("line.separator");
// result.append(this.getClass().getName() + " Object {" + NEW_LINE);
// result.append(" consumerKey: " + _consumerKey + NEW_LINE);
// result.append(" consumerSecret: " + _consumerSecret + NEW_LINE);
// result.append(" signatureMethod: " + _signatureMethod + NEW_LINE);
// result.append(" transportName: " + _transportName + NEW_LINE);
// result.append(" id: " + id + NEW_LINE);
// result.append(" providerImplClass: " + providerImplClass + NEW_LINE);
// result.append("}");
// return result.toString();
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/oauth/exception/SocialAuthException.java
// public class SocialAuthException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -6856436294292027306L;
//
// public SocialAuthException() {
// super();
// }
//
// public SocialAuthException(final String message) {
// super(message);
// }
//
// public SocialAuthException(final Throwable cause) {
// super(cause);
// }
//
// public SocialAuthException(final String message, final Throwable cause) {
// super(message, cause);
// }
// }
| import io.stalk.common.oauth.OAuthConfig;
import io.stalk.common.oauth.exception.SocialAuthException;
import io.stalk.common.oauth.utils.*;
import java.util.Map;
| package io.stalk.common.oauth.strategy;
public class OAuth1 implements OAuthStrategyBase {
private OAuthConsumer oauth;
private Map<String, String> endpoints;
private String scope;
private String providerId;
private String successUrl;
| // Path: src/main/java/io/stalk/common/oauth/OAuthConfig.java
// public class OAuthConfig {
//
// private final String _consumerKey;
// private final String _consumerSecret;
// private final String _callbackUrl;
// private final String _signatureMethod;
// private final String _transportName;
// private String id;
// private Class<?> providerImplClass;
//
//
// public OAuthConfig(final String consumerKey, final String consumerSecret, final String callbackUrl,
// final String signatureMethod, final String transportName) {
// _consumerKey = consumerKey;
// _consumerSecret = consumerSecret;
// if (signatureMethod == null || signatureMethod.length() == 0) {
// _signatureMethod = Constants.HMACSHA1_SIGNATURE;
// } else {
// _signatureMethod = signatureMethod;
// }
// if (transportName == null || transportName.length() == 0) {
// _transportName = MethodType.GET.toString();
// } else {
// _transportName = transportName;
// }
// if (callbackUrl == null || callbackUrl.length() == 0) {
// _callbackUrl = "";
// } else {
// _callbackUrl = callbackUrl;
// }
//
// }
//
// public OAuthConfig(final String consumerKey, final String consumerSecret, final String callbackUrl) {
// _consumerKey = consumerKey;
// _consumerSecret = consumerSecret;
// _transportName = MethodType.GET.toString();
// _signatureMethod = Constants.HMACSHA1_SIGNATURE;
//
//
// if (callbackUrl == null || callbackUrl.length() == 0) {
// _callbackUrl = "";
// } else {
// _callbackUrl = callbackUrl;
// }
// }
//
// public String get_consumerKey() {
// return _consumerKey;
// }
//
// public String get_consumerSecret() {
// return _consumerSecret;
// }
//
// public String get_callbackUrl() {
// return _callbackUrl;
// }
//
// public String get_signatureMethod() {
// return _signatureMethod;
// }
//
// public String get_transportName() {
// return _transportName;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(final String id) {
// this.id = id;
// }
//
// public Class<?> getProviderImplClass() {
// return providerImplClass;
// }
//
// public void setProviderImplClass(final Class<?> providerImplClass) {
// this.providerImplClass = providerImplClass;
// }
//
// @Override
// public String toString() {
// StringBuilder result = new StringBuilder();
// String NEW_LINE = System.getProperty("line.separator");
// result.append(this.getClass().getName() + " Object {" + NEW_LINE);
// result.append(" consumerKey: " + _consumerKey + NEW_LINE);
// result.append(" consumerSecret: " + _consumerSecret + NEW_LINE);
// result.append(" signatureMethod: " + _signatureMethod + NEW_LINE);
// result.append(" transportName: " + _transportName + NEW_LINE);
// result.append(" id: " + id + NEW_LINE);
// result.append(" providerImplClass: " + providerImplClass + NEW_LINE);
// result.append("}");
// return result.toString();
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/oauth/exception/SocialAuthException.java
// public class SocialAuthException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -6856436294292027306L;
//
// public SocialAuthException() {
// super();
// }
//
// public SocialAuthException(final String message) {
// super(message);
// }
//
// public SocialAuthException(final Throwable cause) {
// super(cause);
// }
//
// public SocialAuthException(final String message, final Throwable cause) {
// super(message, cause);
// }
// }
// Path: src/main/java/io/stalk/common/oauth/strategy/OAuth1.java
import io.stalk.common.oauth.OAuthConfig;
import io.stalk.common.oauth.exception.SocialAuthException;
import io.stalk.common.oauth.utils.*;
import java.util.Map;
package io.stalk.common.oauth.strategy;
public class OAuth1 implements OAuthStrategyBase {
private OAuthConsumer oauth;
private Map<String, String> endpoints;
private String scope;
private String providerId;
private String successUrl;
| public OAuth1(final OAuthConfig config, final Map<String, String> endpoints) {
|
stalk-io/stalk-server | src/main/java/io/stalk/common/oauth/strategy/OAuth1.java | // Path: src/main/java/io/stalk/common/oauth/OAuthConfig.java
// public class OAuthConfig {
//
// private final String _consumerKey;
// private final String _consumerSecret;
// private final String _callbackUrl;
// private final String _signatureMethod;
// private final String _transportName;
// private String id;
// private Class<?> providerImplClass;
//
//
// public OAuthConfig(final String consumerKey, final String consumerSecret, final String callbackUrl,
// final String signatureMethod, final String transportName) {
// _consumerKey = consumerKey;
// _consumerSecret = consumerSecret;
// if (signatureMethod == null || signatureMethod.length() == 0) {
// _signatureMethod = Constants.HMACSHA1_SIGNATURE;
// } else {
// _signatureMethod = signatureMethod;
// }
// if (transportName == null || transportName.length() == 0) {
// _transportName = MethodType.GET.toString();
// } else {
// _transportName = transportName;
// }
// if (callbackUrl == null || callbackUrl.length() == 0) {
// _callbackUrl = "";
// } else {
// _callbackUrl = callbackUrl;
// }
//
// }
//
// public OAuthConfig(final String consumerKey, final String consumerSecret, final String callbackUrl) {
// _consumerKey = consumerKey;
// _consumerSecret = consumerSecret;
// _transportName = MethodType.GET.toString();
// _signatureMethod = Constants.HMACSHA1_SIGNATURE;
//
//
// if (callbackUrl == null || callbackUrl.length() == 0) {
// _callbackUrl = "";
// } else {
// _callbackUrl = callbackUrl;
// }
// }
//
// public String get_consumerKey() {
// return _consumerKey;
// }
//
// public String get_consumerSecret() {
// return _consumerSecret;
// }
//
// public String get_callbackUrl() {
// return _callbackUrl;
// }
//
// public String get_signatureMethod() {
// return _signatureMethod;
// }
//
// public String get_transportName() {
// return _transportName;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(final String id) {
// this.id = id;
// }
//
// public Class<?> getProviderImplClass() {
// return providerImplClass;
// }
//
// public void setProviderImplClass(final Class<?> providerImplClass) {
// this.providerImplClass = providerImplClass;
// }
//
// @Override
// public String toString() {
// StringBuilder result = new StringBuilder();
// String NEW_LINE = System.getProperty("line.separator");
// result.append(this.getClass().getName() + " Object {" + NEW_LINE);
// result.append(" consumerKey: " + _consumerKey + NEW_LINE);
// result.append(" consumerSecret: " + _consumerSecret + NEW_LINE);
// result.append(" signatureMethod: " + _signatureMethod + NEW_LINE);
// result.append(" transportName: " + _transportName + NEW_LINE);
// result.append(" id: " + id + NEW_LINE);
// result.append(" providerImplClass: " + providerImplClass + NEW_LINE);
// result.append("}");
// return result.toString();
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/oauth/exception/SocialAuthException.java
// public class SocialAuthException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -6856436294292027306L;
//
// public SocialAuthException() {
// super();
// }
//
// public SocialAuthException(final String message) {
// super(message);
// }
//
// public SocialAuthException(final Throwable cause) {
// super(cause);
// }
//
// public SocialAuthException(final String message, final Throwable cause) {
// super(message, cause);
// }
// }
| import io.stalk.common.oauth.OAuthConfig;
import io.stalk.common.oauth.exception.SocialAuthException;
import io.stalk.common.oauth.utils.*;
import java.util.Map;
| this.providerId = config.getId();
this.successUrl = config.get_callbackUrl();
}
@Override
public RequestToken getLoginRedirectURL() throws Exception {
AccessGrant requestToken = oauth.getRequestToken(
endpoints.get(Constants.OAUTH_REQUEST_TOKEN_URL), successUrl);
String authUrl = endpoints.get(Constants.OAUTH_AUTHORIZATION_URL);
if (scope != null) {
authUrl += scope;
}
StringBuilder urlBuffer = oauth.buildAuthUrl(authUrl, requestToken, successUrl);
System.out.println("Redirection to following URL should happen : " + urlBuffer.toString());
return new RequestToken(urlBuffer.toString(), requestToken);
}
@Override
public AccessGrant verifyResponse(AccessGrant requestToken,
Map<String, String> requestParams) throws Exception {
return verifyResponse(requestToken, requestParams, MethodType.GET.toString());
}
@Override
public AccessGrant verifyResponse(
AccessGrant requestToken,
Map<String, String> requestParams, String methodType)
throws Exception {
if (requestToken == null) {
| // Path: src/main/java/io/stalk/common/oauth/OAuthConfig.java
// public class OAuthConfig {
//
// private final String _consumerKey;
// private final String _consumerSecret;
// private final String _callbackUrl;
// private final String _signatureMethod;
// private final String _transportName;
// private String id;
// private Class<?> providerImplClass;
//
//
// public OAuthConfig(final String consumerKey, final String consumerSecret, final String callbackUrl,
// final String signatureMethod, final String transportName) {
// _consumerKey = consumerKey;
// _consumerSecret = consumerSecret;
// if (signatureMethod == null || signatureMethod.length() == 0) {
// _signatureMethod = Constants.HMACSHA1_SIGNATURE;
// } else {
// _signatureMethod = signatureMethod;
// }
// if (transportName == null || transportName.length() == 0) {
// _transportName = MethodType.GET.toString();
// } else {
// _transportName = transportName;
// }
// if (callbackUrl == null || callbackUrl.length() == 0) {
// _callbackUrl = "";
// } else {
// _callbackUrl = callbackUrl;
// }
//
// }
//
// public OAuthConfig(final String consumerKey, final String consumerSecret, final String callbackUrl) {
// _consumerKey = consumerKey;
// _consumerSecret = consumerSecret;
// _transportName = MethodType.GET.toString();
// _signatureMethod = Constants.HMACSHA1_SIGNATURE;
//
//
// if (callbackUrl == null || callbackUrl.length() == 0) {
// _callbackUrl = "";
// } else {
// _callbackUrl = callbackUrl;
// }
// }
//
// public String get_consumerKey() {
// return _consumerKey;
// }
//
// public String get_consumerSecret() {
// return _consumerSecret;
// }
//
// public String get_callbackUrl() {
// return _callbackUrl;
// }
//
// public String get_signatureMethod() {
// return _signatureMethod;
// }
//
// public String get_transportName() {
// return _transportName;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(final String id) {
// this.id = id;
// }
//
// public Class<?> getProviderImplClass() {
// return providerImplClass;
// }
//
// public void setProviderImplClass(final Class<?> providerImplClass) {
// this.providerImplClass = providerImplClass;
// }
//
// @Override
// public String toString() {
// StringBuilder result = new StringBuilder();
// String NEW_LINE = System.getProperty("line.separator");
// result.append(this.getClass().getName() + " Object {" + NEW_LINE);
// result.append(" consumerKey: " + _consumerKey + NEW_LINE);
// result.append(" consumerSecret: " + _consumerSecret + NEW_LINE);
// result.append(" signatureMethod: " + _signatureMethod + NEW_LINE);
// result.append(" transportName: " + _transportName + NEW_LINE);
// result.append(" id: " + id + NEW_LINE);
// result.append(" providerImplClass: " + providerImplClass + NEW_LINE);
// result.append("}");
// return result.toString();
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/oauth/exception/SocialAuthException.java
// public class SocialAuthException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -6856436294292027306L;
//
// public SocialAuthException() {
// super();
// }
//
// public SocialAuthException(final String message) {
// super(message);
// }
//
// public SocialAuthException(final Throwable cause) {
// super(cause);
// }
//
// public SocialAuthException(final String message, final Throwable cause) {
// super(message, cause);
// }
// }
// Path: src/main/java/io/stalk/common/oauth/strategy/OAuth1.java
import io.stalk.common.oauth.OAuthConfig;
import io.stalk.common.oauth.exception.SocialAuthException;
import io.stalk.common.oauth.utils.*;
import java.util.Map;
this.providerId = config.getId();
this.successUrl = config.get_callbackUrl();
}
@Override
public RequestToken getLoginRedirectURL() throws Exception {
AccessGrant requestToken = oauth.getRequestToken(
endpoints.get(Constants.OAUTH_REQUEST_TOKEN_URL), successUrl);
String authUrl = endpoints.get(Constants.OAUTH_AUTHORIZATION_URL);
if (scope != null) {
authUrl += scope;
}
StringBuilder urlBuffer = oauth.buildAuthUrl(authUrl, requestToken, successUrl);
System.out.println("Redirection to following URL should happen : " + urlBuffer.toString());
return new RequestToken(urlBuffer.toString(), requestToken);
}
@Override
public AccessGrant verifyResponse(AccessGrant requestToken,
Map<String, String> requestParams) throws Exception {
return verifyResponse(requestToken, requestParams, MethodType.GET.toString());
}
@Override
public AccessGrant verifyResponse(
AccessGrant requestToken,
Map<String, String> requestParams, String methodType)
throws Exception {
if (requestToken == null) {
| throw new SocialAuthException("Request token is null");
|
stalk-io/stalk-server | src/main/java/io/stalk/server/MonitorServer.java | // Path: src/main/java/io/stalk/server/verticle/SampleVerticle.java
// public class SampleVerticle extends AbstractVerticle{
// @Override
// void start(JsonObject appConfig) {
// System.out.println("ABCDE --------------------------------") ;
// }
//
// @Override
// public void handle(Message<JsonObject> jsonObjectMessage) {
// //To change body of implemented methods use File | Settings | File Templates.
// }
// }
| import io.stalk.server.verticle.SampleVerticle;
import org.vertx.java.core.Handler;
import org.vertx.java.core.buffer.Buffer;
import org.vertx.java.core.eventbus.EventBus;
import org.vertx.java.core.http.HttpClient;
import org.vertx.java.core.http.HttpClientResponse;
import org.vertx.java.core.http.HttpServer;
import org.vertx.java.core.http.HttpServerRequest;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.core.logging.Logger; | package io.stalk.server;
/**
* Simple sample Verticle Application for dev.
*/
public class MonitorServer extends Server{
private HttpClient client;
private EventBus eb;
private Logger logger;
@Override
void start(JsonObject appConfig, HttpServer server) {
| // Path: src/main/java/io/stalk/server/verticle/SampleVerticle.java
// public class SampleVerticle extends AbstractVerticle{
// @Override
// void start(JsonObject appConfig) {
// System.out.println("ABCDE --------------------------------") ;
// }
//
// @Override
// public void handle(Message<JsonObject> jsonObjectMessage) {
// //To change body of implemented methods use File | Settings | File Templates.
// }
// }
// Path: src/main/java/io/stalk/server/MonitorServer.java
import io.stalk.server.verticle.SampleVerticle;
import org.vertx.java.core.Handler;
import org.vertx.java.core.buffer.Buffer;
import org.vertx.java.core.eventbus.EventBus;
import org.vertx.java.core.http.HttpClient;
import org.vertx.java.core.http.HttpClientResponse;
import org.vertx.java.core.http.HttpServer;
import org.vertx.java.core.http.HttpServerRequest;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.core.logging.Logger;
package io.stalk.server;
/**
* Simple sample Verticle Application for dev.
*/
public class MonitorServer extends Server{
private HttpClient client;
private EventBus eb;
private Logger logger;
@Override
void start(JsonObject appConfig, HttpServer server) {
| container.deployWorkerVerticle(SampleVerticle.class.getName(),new JsonObject(),1,false); |
stalk-io/stalk-server | src/main/java/io/stalk/common/oauth/provider/AuthProvider.java | // Path: src/main/java/io/stalk/common/oauth/Profile.java
// public class Profile {
//
// private String name;
// private String link;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getLink() {
// return link;
// }
//
// public void setLink(String link) {
// this.link = link;
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/oauth/strategy/RequestToken.java
// public class RequestToken {
//
// private String url;
// private AccessGrant accessGrant;
//
// public RequestToken(String url, AccessGrant accessGrant) {
// this.url = url;
// this.accessGrant = accessGrant;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public AccessGrant getAccessGrant() {
// return accessGrant;
// }
//
// public void setAccessGrant(AccessGrant accessGrant) {
// this.accessGrant = accessGrant;
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/oauth/utils/AccessGrant.java
// public class AccessGrant implements Serializable {
//
// private static final long serialVersionUID = -7120362372191191930L;
// private String key;
// private String secret;
// private String providerId;
// private Map<String, Object> _attributes;
//
// /**
// * @param key the Key
// * @param secret the Secret
// */
// public AccessGrant(final String key, final String secret) {
// this.key = key;
// this.secret = secret;
// }
//
// public AccessGrant() {
// }
//
// /**
// * Retrieves the Token Key
// *
// * @return the Token Key
// */
// public String getKey() {
// return key;
// }
//
// /**
// * Updates the Token Key
// *
// * @param key the Token Key
// */
// public void setKey(final String key) {
// this.key = key;
// }
//
// /**
// * Retrieves the Token Secret
// *
// * @return the Token Secret
// */
// public String getSecret() {
// return secret;
// }
//
// /**
// * Updates the Token Secret
// *
// * @param secret the Token Secret
// */
// public void setSecret(final String secret) {
// this.secret = secret;
// }
//
// /**
// * Gets the attributes of this token.
// */
// public Map<String, Object> getAttributes() {
// return _attributes;
// }
//
// /**
// * Gets an attribute based from the given key.
// */
// public Object getAttribute(final String key) {
// return _attributes == null ? null : _attributes.get(key);
// }
//
// /**
// * Sets an attribute based from the given key and value.
// */
// public void setAttribute(final String key, final Object value) {
// if (_attributes == null) {
// _attributes = new HashMap<String, Object>();
// }
//
// _attributes.put(key, value);
// }
//
// /**
// * Sets an attributes from given attributes map.
// */
// public void setAttributes(final Map<String, Object> attributes) {
// if (_attributes == null) {
// _attributes = new HashMap<String, Object>();
// }
//
// _attributes.putAll(attributes);
// }
//
// /**
// * Retrieves the provider id.
// *
// * @return the provider id.
// */
// public String getProviderId() {
// return providerId;
// }
//
// /**
// * Updates the provider id.
// *
// * @param providerId the provider id.
// */
// public void setProviderId(final String providerId) {
// this.providerId = providerId;
// }
//
// @Override
// public String toString() {
// StringBuilder result = new StringBuilder();
// String NEW_LINE = System.getProperty("line.separator");
// result.append(this.getClass().getName() + " Object {" + NEW_LINE);
// result.append(" token key : " + key + NEW_LINE);
// result.append(" token secret : " + secret + NEW_LINE);
// result.append("provider id : " + providerId + NEW_LINE);
// if (_attributes != null) {
// result.append(_attributes.toString());
// }
// result.append("}");
//
// return result.toString();
// }
//
// }
| import io.stalk.common.oauth.Profile;
import io.stalk.common.oauth.strategy.RequestToken;
import io.stalk.common.oauth.utils.AccessGrant;
import java.util.Map;
| package io.stalk.common.oauth.provider;
public interface AuthProvider {
String EXT_NAMESPACE = "http://specs.openid.net/extensions/oauth/1.0";
String EMAIL = "email";
String COUNTRY = "country";
String LANGUAGE = "language";
String FULL_NAME = "fullname";
String NICK_NAME = "nickname";
String DOB = "dob";
String GENDER = "gender";
String POSTCODE = "postcode";
String FIRST_NAME = "firstname";
String LAST_NAME = "lastname";
| // Path: src/main/java/io/stalk/common/oauth/Profile.java
// public class Profile {
//
// private String name;
// private String link;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getLink() {
// return link;
// }
//
// public void setLink(String link) {
// this.link = link;
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/oauth/strategy/RequestToken.java
// public class RequestToken {
//
// private String url;
// private AccessGrant accessGrant;
//
// public RequestToken(String url, AccessGrant accessGrant) {
// this.url = url;
// this.accessGrant = accessGrant;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public AccessGrant getAccessGrant() {
// return accessGrant;
// }
//
// public void setAccessGrant(AccessGrant accessGrant) {
// this.accessGrant = accessGrant;
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/oauth/utils/AccessGrant.java
// public class AccessGrant implements Serializable {
//
// private static final long serialVersionUID = -7120362372191191930L;
// private String key;
// private String secret;
// private String providerId;
// private Map<String, Object> _attributes;
//
// /**
// * @param key the Key
// * @param secret the Secret
// */
// public AccessGrant(final String key, final String secret) {
// this.key = key;
// this.secret = secret;
// }
//
// public AccessGrant() {
// }
//
// /**
// * Retrieves the Token Key
// *
// * @return the Token Key
// */
// public String getKey() {
// return key;
// }
//
// /**
// * Updates the Token Key
// *
// * @param key the Token Key
// */
// public void setKey(final String key) {
// this.key = key;
// }
//
// /**
// * Retrieves the Token Secret
// *
// * @return the Token Secret
// */
// public String getSecret() {
// return secret;
// }
//
// /**
// * Updates the Token Secret
// *
// * @param secret the Token Secret
// */
// public void setSecret(final String secret) {
// this.secret = secret;
// }
//
// /**
// * Gets the attributes of this token.
// */
// public Map<String, Object> getAttributes() {
// return _attributes;
// }
//
// /**
// * Gets an attribute based from the given key.
// */
// public Object getAttribute(final String key) {
// return _attributes == null ? null : _attributes.get(key);
// }
//
// /**
// * Sets an attribute based from the given key and value.
// */
// public void setAttribute(final String key, final Object value) {
// if (_attributes == null) {
// _attributes = new HashMap<String, Object>();
// }
//
// _attributes.put(key, value);
// }
//
// /**
// * Sets an attributes from given attributes map.
// */
// public void setAttributes(final Map<String, Object> attributes) {
// if (_attributes == null) {
// _attributes = new HashMap<String, Object>();
// }
//
// _attributes.putAll(attributes);
// }
//
// /**
// * Retrieves the provider id.
// *
// * @return the provider id.
// */
// public String getProviderId() {
// return providerId;
// }
//
// /**
// * Updates the provider id.
// *
// * @param providerId the provider id.
// */
// public void setProviderId(final String providerId) {
// this.providerId = providerId;
// }
//
// @Override
// public String toString() {
// StringBuilder result = new StringBuilder();
// String NEW_LINE = System.getProperty("line.separator");
// result.append(this.getClass().getName() + " Object {" + NEW_LINE);
// result.append(" token key : " + key + NEW_LINE);
// result.append(" token secret : " + secret + NEW_LINE);
// result.append("provider id : " + providerId + NEW_LINE);
// if (_attributes != null) {
// result.append(_attributes.toString());
// }
// result.append("}");
//
// return result.toString();
// }
//
// }
// Path: src/main/java/io/stalk/common/oauth/provider/AuthProvider.java
import io.stalk.common.oauth.Profile;
import io.stalk.common.oauth.strategy.RequestToken;
import io.stalk.common.oauth.utils.AccessGrant;
import java.util.Map;
package io.stalk.common.oauth.provider;
public interface AuthProvider {
String EXT_NAMESPACE = "http://specs.openid.net/extensions/oauth/1.0";
String EMAIL = "email";
String COUNTRY = "country";
String LANGUAGE = "language";
String FULL_NAME = "fullname";
String NICK_NAME = "nickname";
String DOB = "dob";
String GENDER = "gender";
String POSTCODE = "postcode";
String FIRST_NAME = "firstname";
String LAST_NAME = "lastname";
| public RequestToken getLoginRedirectURL() throws Exception;
|
stalk-io/stalk-server | src/main/java/io/stalk/common/oauth/provider/AuthProvider.java | // Path: src/main/java/io/stalk/common/oauth/Profile.java
// public class Profile {
//
// private String name;
// private String link;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getLink() {
// return link;
// }
//
// public void setLink(String link) {
// this.link = link;
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/oauth/strategy/RequestToken.java
// public class RequestToken {
//
// private String url;
// private AccessGrant accessGrant;
//
// public RequestToken(String url, AccessGrant accessGrant) {
// this.url = url;
// this.accessGrant = accessGrant;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public AccessGrant getAccessGrant() {
// return accessGrant;
// }
//
// public void setAccessGrant(AccessGrant accessGrant) {
// this.accessGrant = accessGrant;
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/oauth/utils/AccessGrant.java
// public class AccessGrant implements Serializable {
//
// private static final long serialVersionUID = -7120362372191191930L;
// private String key;
// private String secret;
// private String providerId;
// private Map<String, Object> _attributes;
//
// /**
// * @param key the Key
// * @param secret the Secret
// */
// public AccessGrant(final String key, final String secret) {
// this.key = key;
// this.secret = secret;
// }
//
// public AccessGrant() {
// }
//
// /**
// * Retrieves the Token Key
// *
// * @return the Token Key
// */
// public String getKey() {
// return key;
// }
//
// /**
// * Updates the Token Key
// *
// * @param key the Token Key
// */
// public void setKey(final String key) {
// this.key = key;
// }
//
// /**
// * Retrieves the Token Secret
// *
// * @return the Token Secret
// */
// public String getSecret() {
// return secret;
// }
//
// /**
// * Updates the Token Secret
// *
// * @param secret the Token Secret
// */
// public void setSecret(final String secret) {
// this.secret = secret;
// }
//
// /**
// * Gets the attributes of this token.
// */
// public Map<String, Object> getAttributes() {
// return _attributes;
// }
//
// /**
// * Gets an attribute based from the given key.
// */
// public Object getAttribute(final String key) {
// return _attributes == null ? null : _attributes.get(key);
// }
//
// /**
// * Sets an attribute based from the given key and value.
// */
// public void setAttribute(final String key, final Object value) {
// if (_attributes == null) {
// _attributes = new HashMap<String, Object>();
// }
//
// _attributes.put(key, value);
// }
//
// /**
// * Sets an attributes from given attributes map.
// */
// public void setAttributes(final Map<String, Object> attributes) {
// if (_attributes == null) {
// _attributes = new HashMap<String, Object>();
// }
//
// _attributes.putAll(attributes);
// }
//
// /**
// * Retrieves the provider id.
// *
// * @return the provider id.
// */
// public String getProviderId() {
// return providerId;
// }
//
// /**
// * Updates the provider id.
// *
// * @param providerId the provider id.
// */
// public void setProviderId(final String providerId) {
// this.providerId = providerId;
// }
//
// @Override
// public String toString() {
// StringBuilder result = new StringBuilder();
// String NEW_LINE = System.getProperty("line.separator");
// result.append(this.getClass().getName() + " Object {" + NEW_LINE);
// result.append(" token key : " + key + NEW_LINE);
// result.append(" token secret : " + secret + NEW_LINE);
// result.append("provider id : " + providerId + NEW_LINE);
// if (_attributes != null) {
// result.append(_attributes.toString());
// }
// result.append("}");
//
// return result.toString();
// }
//
// }
| import io.stalk.common.oauth.Profile;
import io.stalk.common.oauth.strategy.RequestToken;
import io.stalk.common.oauth.utils.AccessGrant;
import java.util.Map;
| package io.stalk.common.oauth.provider;
public interface AuthProvider {
String EXT_NAMESPACE = "http://specs.openid.net/extensions/oauth/1.0";
String EMAIL = "email";
String COUNTRY = "country";
String LANGUAGE = "language";
String FULL_NAME = "fullname";
String NICK_NAME = "nickname";
String DOB = "dob";
String GENDER = "gender";
String POSTCODE = "postcode";
String FIRST_NAME = "firstname";
String LAST_NAME = "lastname";
public RequestToken getLoginRedirectURL() throws Exception;
| // Path: src/main/java/io/stalk/common/oauth/Profile.java
// public class Profile {
//
// private String name;
// private String link;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getLink() {
// return link;
// }
//
// public void setLink(String link) {
// this.link = link;
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/oauth/strategy/RequestToken.java
// public class RequestToken {
//
// private String url;
// private AccessGrant accessGrant;
//
// public RequestToken(String url, AccessGrant accessGrant) {
// this.url = url;
// this.accessGrant = accessGrant;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public AccessGrant getAccessGrant() {
// return accessGrant;
// }
//
// public void setAccessGrant(AccessGrant accessGrant) {
// this.accessGrant = accessGrant;
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/oauth/utils/AccessGrant.java
// public class AccessGrant implements Serializable {
//
// private static final long serialVersionUID = -7120362372191191930L;
// private String key;
// private String secret;
// private String providerId;
// private Map<String, Object> _attributes;
//
// /**
// * @param key the Key
// * @param secret the Secret
// */
// public AccessGrant(final String key, final String secret) {
// this.key = key;
// this.secret = secret;
// }
//
// public AccessGrant() {
// }
//
// /**
// * Retrieves the Token Key
// *
// * @return the Token Key
// */
// public String getKey() {
// return key;
// }
//
// /**
// * Updates the Token Key
// *
// * @param key the Token Key
// */
// public void setKey(final String key) {
// this.key = key;
// }
//
// /**
// * Retrieves the Token Secret
// *
// * @return the Token Secret
// */
// public String getSecret() {
// return secret;
// }
//
// /**
// * Updates the Token Secret
// *
// * @param secret the Token Secret
// */
// public void setSecret(final String secret) {
// this.secret = secret;
// }
//
// /**
// * Gets the attributes of this token.
// */
// public Map<String, Object> getAttributes() {
// return _attributes;
// }
//
// /**
// * Gets an attribute based from the given key.
// */
// public Object getAttribute(final String key) {
// return _attributes == null ? null : _attributes.get(key);
// }
//
// /**
// * Sets an attribute based from the given key and value.
// */
// public void setAttribute(final String key, final Object value) {
// if (_attributes == null) {
// _attributes = new HashMap<String, Object>();
// }
//
// _attributes.put(key, value);
// }
//
// /**
// * Sets an attributes from given attributes map.
// */
// public void setAttributes(final Map<String, Object> attributes) {
// if (_attributes == null) {
// _attributes = new HashMap<String, Object>();
// }
//
// _attributes.putAll(attributes);
// }
//
// /**
// * Retrieves the provider id.
// *
// * @return the provider id.
// */
// public String getProviderId() {
// return providerId;
// }
//
// /**
// * Updates the provider id.
// *
// * @param providerId the provider id.
// */
// public void setProviderId(final String providerId) {
// this.providerId = providerId;
// }
//
// @Override
// public String toString() {
// StringBuilder result = new StringBuilder();
// String NEW_LINE = System.getProperty("line.separator");
// result.append(this.getClass().getName() + " Object {" + NEW_LINE);
// result.append(" token key : " + key + NEW_LINE);
// result.append(" token secret : " + secret + NEW_LINE);
// result.append("provider id : " + providerId + NEW_LINE);
// if (_attributes != null) {
// result.append(_attributes.toString());
// }
// result.append("}");
//
// return result.toString();
// }
//
// }
// Path: src/main/java/io/stalk/common/oauth/provider/AuthProvider.java
import io.stalk.common.oauth.Profile;
import io.stalk.common.oauth.strategy.RequestToken;
import io.stalk.common.oauth.utils.AccessGrant;
import java.util.Map;
package io.stalk.common.oauth.provider;
public interface AuthProvider {
String EXT_NAMESPACE = "http://specs.openid.net/extensions/oauth/1.0";
String EMAIL = "email";
String COUNTRY = "country";
String LANGUAGE = "language";
String FULL_NAME = "fullname";
String NICK_NAME = "nickname";
String DOB = "dob";
String GENDER = "gender";
String POSTCODE = "postcode";
String FIRST_NAME = "firstname";
String LAST_NAME = "lastname";
public RequestToken getLoginRedirectURL() throws Exception;
| public Profile connect(AccessGrant requestToken, Map<String, String> requestParams) throws Exception;
|
stalk-io/stalk-server | src/main/java/io/stalk/common/oauth/provider/AuthProvider.java | // Path: src/main/java/io/stalk/common/oauth/Profile.java
// public class Profile {
//
// private String name;
// private String link;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getLink() {
// return link;
// }
//
// public void setLink(String link) {
// this.link = link;
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/oauth/strategy/RequestToken.java
// public class RequestToken {
//
// private String url;
// private AccessGrant accessGrant;
//
// public RequestToken(String url, AccessGrant accessGrant) {
// this.url = url;
// this.accessGrant = accessGrant;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public AccessGrant getAccessGrant() {
// return accessGrant;
// }
//
// public void setAccessGrant(AccessGrant accessGrant) {
// this.accessGrant = accessGrant;
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/oauth/utils/AccessGrant.java
// public class AccessGrant implements Serializable {
//
// private static final long serialVersionUID = -7120362372191191930L;
// private String key;
// private String secret;
// private String providerId;
// private Map<String, Object> _attributes;
//
// /**
// * @param key the Key
// * @param secret the Secret
// */
// public AccessGrant(final String key, final String secret) {
// this.key = key;
// this.secret = secret;
// }
//
// public AccessGrant() {
// }
//
// /**
// * Retrieves the Token Key
// *
// * @return the Token Key
// */
// public String getKey() {
// return key;
// }
//
// /**
// * Updates the Token Key
// *
// * @param key the Token Key
// */
// public void setKey(final String key) {
// this.key = key;
// }
//
// /**
// * Retrieves the Token Secret
// *
// * @return the Token Secret
// */
// public String getSecret() {
// return secret;
// }
//
// /**
// * Updates the Token Secret
// *
// * @param secret the Token Secret
// */
// public void setSecret(final String secret) {
// this.secret = secret;
// }
//
// /**
// * Gets the attributes of this token.
// */
// public Map<String, Object> getAttributes() {
// return _attributes;
// }
//
// /**
// * Gets an attribute based from the given key.
// */
// public Object getAttribute(final String key) {
// return _attributes == null ? null : _attributes.get(key);
// }
//
// /**
// * Sets an attribute based from the given key and value.
// */
// public void setAttribute(final String key, final Object value) {
// if (_attributes == null) {
// _attributes = new HashMap<String, Object>();
// }
//
// _attributes.put(key, value);
// }
//
// /**
// * Sets an attributes from given attributes map.
// */
// public void setAttributes(final Map<String, Object> attributes) {
// if (_attributes == null) {
// _attributes = new HashMap<String, Object>();
// }
//
// _attributes.putAll(attributes);
// }
//
// /**
// * Retrieves the provider id.
// *
// * @return the provider id.
// */
// public String getProviderId() {
// return providerId;
// }
//
// /**
// * Updates the provider id.
// *
// * @param providerId the provider id.
// */
// public void setProviderId(final String providerId) {
// this.providerId = providerId;
// }
//
// @Override
// public String toString() {
// StringBuilder result = new StringBuilder();
// String NEW_LINE = System.getProperty("line.separator");
// result.append(this.getClass().getName() + " Object {" + NEW_LINE);
// result.append(" token key : " + key + NEW_LINE);
// result.append(" token secret : " + secret + NEW_LINE);
// result.append("provider id : " + providerId + NEW_LINE);
// if (_attributes != null) {
// result.append(_attributes.toString());
// }
// result.append("}");
//
// return result.toString();
// }
//
// }
| import io.stalk.common.oauth.Profile;
import io.stalk.common.oauth.strategy.RequestToken;
import io.stalk.common.oauth.utils.AccessGrant;
import java.util.Map;
| package io.stalk.common.oauth.provider;
public interface AuthProvider {
String EXT_NAMESPACE = "http://specs.openid.net/extensions/oauth/1.0";
String EMAIL = "email";
String COUNTRY = "country";
String LANGUAGE = "language";
String FULL_NAME = "fullname";
String NICK_NAME = "nickname";
String DOB = "dob";
String GENDER = "gender";
String POSTCODE = "postcode";
String FIRST_NAME = "firstname";
String LAST_NAME = "lastname";
public RequestToken getLoginRedirectURL() throws Exception;
| // Path: src/main/java/io/stalk/common/oauth/Profile.java
// public class Profile {
//
// private String name;
// private String link;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getLink() {
// return link;
// }
//
// public void setLink(String link) {
// this.link = link;
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/oauth/strategy/RequestToken.java
// public class RequestToken {
//
// private String url;
// private AccessGrant accessGrant;
//
// public RequestToken(String url, AccessGrant accessGrant) {
// this.url = url;
// this.accessGrant = accessGrant;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
//
// public AccessGrant getAccessGrant() {
// return accessGrant;
// }
//
// public void setAccessGrant(AccessGrant accessGrant) {
// this.accessGrant = accessGrant;
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/oauth/utils/AccessGrant.java
// public class AccessGrant implements Serializable {
//
// private static final long serialVersionUID = -7120362372191191930L;
// private String key;
// private String secret;
// private String providerId;
// private Map<String, Object> _attributes;
//
// /**
// * @param key the Key
// * @param secret the Secret
// */
// public AccessGrant(final String key, final String secret) {
// this.key = key;
// this.secret = secret;
// }
//
// public AccessGrant() {
// }
//
// /**
// * Retrieves the Token Key
// *
// * @return the Token Key
// */
// public String getKey() {
// return key;
// }
//
// /**
// * Updates the Token Key
// *
// * @param key the Token Key
// */
// public void setKey(final String key) {
// this.key = key;
// }
//
// /**
// * Retrieves the Token Secret
// *
// * @return the Token Secret
// */
// public String getSecret() {
// return secret;
// }
//
// /**
// * Updates the Token Secret
// *
// * @param secret the Token Secret
// */
// public void setSecret(final String secret) {
// this.secret = secret;
// }
//
// /**
// * Gets the attributes of this token.
// */
// public Map<String, Object> getAttributes() {
// return _attributes;
// }
//
// /**
// * Gets an attribute based from the given key.
// */
// public Object getAttribute(final String key) {
// return _attributes == null ? null : _attributes.get(key);
// }
//
// /**
// * Sets an attribute based from the given key and value.
// */
// public void setAttribute(final String key, final Object value) {
// if (_attributes == null) {
// _attributes = new HashMap<String, Object>();
// }
//
// _attributes.put(key, value);
// }
//
// /**
// * Sets an attributes from given attributes map.
// */
// public void setAttributes(final Map<String, Object> attributes) {
// if (_attributes == null) {
// _attributes = new HashMap<String, Object>();
// }
//
// _attributes.putAll(attributes);
// }
//
// /**
// * Retrieves the provider id.
// *
// * @return the provider id.
// */
// public String getProviderId() {
// return providerId;
// }
//
// /**
// * Updates the provider id.
// *
// * @param providerId the provider id.
// */
// public void setProviderId(final String providerId) {
// this.providerId = providerId;
// }
//
// @Override
// public String toString() {
// StringBuilder result = new StringBuilder();
// String NEW_LINE = System.getProperty("line.separator");
// result.append(this.getClass().getName() + " Object {" + NEW_LINE);
// result.append(" token key : " + key + NEW_LINE);
// result.append(" token secret : " + secret + NEW_LINE);
// result.append("provider id : " + providerId + NEW_LINE);
// if (_attributes != null) {
// result.append(_attributes.toString());
// }
// result.append("}");
//
// return result.toString();
// }
//
// }
// Path: src/main/java/io/stalk/common/oauth/provider/AuthProvider.java
import io.stalk.common.oauth.Profile;
import io.stalk.common.oauth.strategy.RequestToken;
import io.stalk.common.oauth.utils.AccessGrant;
import java.util.Map;
package io.stalk.common.oauth.provider;
public interface AuthProvider {
String EXT_NAMESPACE = "http://specs.openid.net/extensions/oauth/1.0";
String EMAIL = "email";
String COUNTRY = "country";
String LANGUAGE = "language";
String FULL_NAME = "fullname";
String NICK_NAME = "nickname";
String DOB = "dob";
String GENDER = "gender";
String POSTCODE = "postcode";
String FIRST_NAME = "firstname";
String LAST_NAME = "lastname";
public RequestToken getLoginRedirectURL() throws Exception;
| public Profile connect(AccessGrant requestToken, Map<String, String> requestParams) throws Exception;
|
stalk-io/stalk-server | src/main/java/io/stalk/server/verticle/SubscribeManager.java | // Path: src/main/java/io/stalk/server/MessageServer.java
// public class MessageServer extends Server{
//
// private EventBus eb;
// private ConcurrentMap<String, String> sessionStore;
// private String channel;
//
// @Override
// void start(final JsonObject appConfig, HttpServer server) {
//
// eb = vertx.eventBus();
// channel = appConfig.getString("channel");
// sessionStore = vertx.sharedData().getMap("_REFER_STORAGE");
//
// List<Module> deployments = new ArrayList<Module>();
// deployments.add(new Module(SubscribeManager.class.getName() , appConfig, 1, false ));
// deployments.add(new Module(NodeWatchManager.class.getName() , appConfig, 1, false ));
// deployments.add(new Module(PublishManager.class.getName() ));
// deployments.add(new Module(SessionManager.class.getName() , appConfig ));
//
// deployWorkerVerticles(deployments, new Handler<Void>() {
// public void handle(Void event) {
// INFO(" *** modules are deployed. *** ");
//
// JsonObject createNodeAction = new JsonObject();
// createNodeAction.putString("action", "create");
// createNodeAction.putString("channel", channel);
// createNodeAction.putObject("data",
// new JsonObject()
// .putObject("server" , new JsonObject()
// .putString("host", appConfig.getString("host"))
// .putNumber("port", appConfig.getNumber("port")))
// .putObject("redis", appConfig.getObject("redis-address"))
// );
//
// eb.send(NodeWatchManager.class.getName(), createNodeAction, new Handler<Message<JsonObject>>() {
// public void handle(Message<JsonObject> message) {
// if("ok".equals(message.body().getString("status"))){
// eb.send(NodeWatchManager.class.getName(), new JsonObject().putString("action", "watch"));
// }
// }
// });
//
// }
// });
//
//
//
//
//
// SockJSServer sockServer = vertx.createSockJSServer(server);
// sockServer.installApp(
// new JsonObject().putString("prefix", "/message"),
// new SocketMessageHandler(vertx, channel)
// );
//
// }
//
// @Override
// protected void postStart(JsonObject appConfig, HttpServer server) {
//
// Handler<Message<JsonObject>> myHandler = new Handler<Message<JsonObject>>() {
// public void handle(Message<JsonObject> message) {
//
// String action = message.body().getString("action");
// String socketId = message.body().getString("socketId");
//
// if("message".equals(action)){
// message.body().putString("action", "LOGIN");
// eb.send(socketId, new Buffer(message.body().encode()));
// }
// }
// };
//
// eb.registerHandler(MessageServer.class.getName(), myHandler, new AsyncResultHandler<Void>() {
// public void handle(AsyncResult<Void> asyncResult) {
// System.out.println("["+this.getClass().getName()+"] has been registered across the cluster ok? " + asyncResult.succeeded());
// }
// });
//
// }
//
// @Override
// public void stop() {
// try {
// super.stop();
//
// JsonObject delNode = new JsonObject();
// delNode.putString("action", "delete");
// delNode.putString("channel", channel);
// eb.send(NodeWatchManager.class.getName(), delNode);
//
// INFO(channel+" is closed !!! ");
//
// } catch (Exception e) {
// }
// }
//
// @Override
// public void handle(HttpServerRequest req) {
//
// if("/status/ping".equals(req.path())){
//
//
// }else if("/status/session/count".equals(req.path())){
// StringBuffer returnStr = new StringBuffer("");
// if(StringUtils.isEmpty(req.params().get("callback"))){
// returnStr.append("{\"count\":").append(sessionStore.size()).append("}");
// }else{
// returnStr
// .append(req.params().get("callback"))
// .append("(")
// .append("{\"count\":").append(sessionStore.size()).append("}")
// .append(");");
// }
// sendResponse(req, returnStr.toString());
//
// }else if (!req.path().startsWith("/message")){
// System.out.println(" *** bad request path *** "+req.path());
// req.response().setStatusCode(404).setStatusMessage("WTF ?").end();
// }
// }
//
//
// private void sendResponse(HttpServerRequest req, String message){
// req.response().putHeader(HttpHeaders.Names.CONTENT_TYPE , "application/json; charset=UTF-8").end(message);
// }
//
// }
| import io.stalk.server.MessageServer;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.JsonObject; | package io.stalk.server.verticle;
public class SubscribeManager extends AbstractVerticle{
@Override
void start(JsonObject appConfig) {
JsonObject redisConf = appConfig.getObject("redis-address");
new Thread(
new SubscribeThread(
vertx.eventBus(),
redisConf.getString("host"),
redisConf.getInteger("port"),
appConfig.getString("channel"), | // Path: src/main/java/io/stalk/server/MessageServer.java
// public class MessageServer extends Server{
//
// private EventBus eb;
// private ConcurrentMap<String, String> sessionStore;
// private String channel;
//
// @Override
// void start(final JsonObject appConfig, HttpServer server) {
//
// eb = vertx.eventBus();
// channel = appConfig.getString("channel");
// sessionStore = vertx.sharedData().getMap("_REFER_STORAGE");
//
// List<Module> deployments = new ArrayList<Module>();
// deployments.add(new Module(SubscribeManager.class.getName() , appConfig, 1, false ));
// deployments.add(new Module(NodeWatchManager.class.getName() , appConfig, 1, false ));
// deployments.add(new Module(PublishManager.class.getName() ));
// deployments.add(new Module(SessionManager.class.getName() , appConfig ));
//
// deployWorkerVerticles(deployments, new Handler<Void>() {
// public void handle(Void event) {
// INFO(" *** modules are deployed. *** ");
//
// JsonObject createNodeAction = new JsonObject();
// createNodeAction.putString("action", "create");
// createNodeAction.putString("channel", channel);
// createNodeAction.putObject("data",
// new JsonObject()
// .putObject("server" , new JsonObject()
// .putString("host", appConfig.getString("host"))
// .putNumber("port", appConfig.getNumber("port")))
// .putObject("redis", appConfig.getObject("redis-address"))
// );
//
// eb.send(NodeWatchManager.class.getName(), createNodeAction, new Handler<Message<JsonObject>>() {
// public void handle(Message<JsonObject> message) {
// if("ok".equals(message.body().getString("status"))){
// eb.send(NodeWatchManager.class.getName(), new JsonObject().putString("action", "watch"));
// }
// }
// });
//
// }
// });
//
//
//
//
//
// SockJSServer sockServer = vertx.createSockJSServer(server);
// sockServer.installApp(
// new JsonObject().putString("prefix", "/message"),
// new SocketMessageHandler(vertx, channel)
// );
//
// }
//
// @Override
// protected void postStart(JsonObject appConfig, HttpServer server) {
//
// Handler<Message<JsonObject>> myHandler = new Handler<Message<JsonObject>>() {
// public void handle(Message<JsonObject> message) {
//
// String action = message.body().getString("action");
// String socketId = message.body().getString("socketId");
//
// if("message".equals(action)){
// message.body().putString("action", "LOGIN");
// eb.send(socketId, new Buffer(message.body().encode()));
// }
// }
// };
//
// eb.registerHandler(MessageServer.class.getName(), myHandler, new AsyncResultHandler<Void>() {
// public void handle(AsyncResult<Void> asyncResult) {
// System.out.println("["+this.getClass().getName()+"] has been registered across the cluster ok? " + asyncResult.succeeded());
// }
// });
//
// }
//
// @Override
// public void stop() {
// try {
// super.stop();
//
// JsonObject delNode = new JsonObject();
// delNode.putString("action", "delete");
// delNode.putString("channel", channel);
// eb.send(NodeWatchManager.class.getName(), delNode);
//
// INFO(channel+" is closed !!! ");
//
// } catch (Exception e) {
// }
// }
//
// @Override
// public void handle(HttpServerRequest req) {
//
// if("/status/ping".equals(req.path())){
//
//
// }else if("/status/session/count".equals(req.path())){
// StringBuffer returnStr = new StringBuffer("");
// if(StringUtils.isEmpty(req.params().get("callback"))){
// returnStr.append("{\"count\":").append(sessionStore.size()).append("}");
// }else{
// returnStr
// .append(req.params().get("callback"))
// .append("(")
// .append("{\"count\":").append(sessionStore.size()).append("}")
// .append(");");
// }
// sendResponse(req, returnStr.toString());
//
// }else if (!req.path().startsWith("/message")){
// System.out.println(" *** bad request path *** "+req.path());
// req.response().setStatusCode(404).setStatusMessage("WTF ?").end();
// }
// }
//
//
// private void sendResponse(HttpServerRequest req, String message){
// req.response().putHeader(HttpHeaders.Names.CONTENT_TYPE , "application/json; charset=UTF-8").end(message);
// }
//
// }
// Path: src/main/java/io/stalk/server/verticle/SubscribeManager.java
import io.stalk.server.MessageServer;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.json.JsonObject;
package io.stalk.server.verticle;
public class SubscribeManager extends AbstractVerticle{
@Override
void start(JsonObject appConfig) {
JsonObject redisConf = appConfig.getObject("redis-address");
new Thread(
new SubscribeThread(
vertx.eventBus(),
redisConf.getString("host"),
redisConf.getInteger("port"),
appConfig.getString("channel"), | MessageServer.class.getName() |
stalk-io/stalk-server | src/main/java/io/stalk/common/oauth/utils/HttpUtil.java | // Path: src/main/java/io/stalk/common/oauth/exception/SocialAuthException.java
// public class SocialAuthException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -6856436294292027306L;
//
// public SocialAuthException() {
// super();
// }
//
// public SocialAuthException(final String message) {
// super(message);
// }
//
// public SocialAuthException(final Throwable cause) {
// super(cause);
// }
//
// public SocialAuthException(final String message, final Throwable cause) {
// super(message, cause);
// }
// }
| import io.stalk.common.oauth.exception.SocialAuthException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map; | package io.stalk.common.oauth.utils;
public class HttpUtil {
private static int timeoutValue = 0;
public static void setConnectionTimeout(final int timeout) {
timeoutValue = timeout;
}
public static String encodeURIComponent(final String value)
throws Exception {
if (value == null) {
return "";
}
try {
return URLEncoder.encode(value, "utf-8")
// OAuth encodes some characters differently:
.replace("+", "%20").replace("*", "%2A")
.replace("%7E", "~");
// This could be done faster with more hand-crafted code.
} catch (UnsupportedEncodingException wow) { | // Path: src/main/java/io/stalk/common/oauth/exception/SocialAuthException.java
// public class SocialAuthException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -6856436294292027306L;
//
// public SocialAuthException() {
// super();
// }
//
// public SocialAuthException(final String message) {
// super(message);
// }
//
// public SocialAuthException(final Throwable cause) {
// super(cause);
// }
//
// public SocialAuthException(final String message, final Throwable cause) {
// super(message, cause);
// }
// }
// Path: src/main/java/io/stalk/common/oauth/utils/HttpUtil.java
import io.stalk.common.oauth.exception.SocialAuthException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
package io.stalk.common.oauth.utils;
public class HttpUtil {
private static int timeoutValue = 0;
public static void setConnectionTimeout(final int timeout) {
timeoutValue = timeout;
}
public static String encodeURIComponent(final String value)
throws Exception {
if (value == null) {
return "";
}
try {
return URLEncoder.encode(value, "utf-8")
// OAuth encodes some characters differently:
.replace("+", "%20").replace("*", "%2A")
.replace("%7E", "~");
// This could be done faster with more hand-crafted code.
} catch (UnsupportedEncodingException wow) { | throw new SocialAuthException(wow.getMessage(), wow); |
stalk-io/stalk-server | src/main/java/io/stalk/common/oauth/strategy/RequestToken.java | // Path: src/main/java/io/stalk/common/oauth/utils/AccessGrant.java
// public class AccessGrant implements Serializable {
//
// private static final long serialVersionUID = -7120362372191191930L;
// private String key;
// private String secret;
// private String providerId;
// private Map<String, Object> _attributes;
//
// /**
// * @param key the Key
// * @param secret the Secret
// */
// public AccessGrant(final String key, final String secret) {
// this.key = key;
// this.secret = secret;
// }
//
// public AccessGrant() {
// }
//
// /**
// * Retrieves the Token Key
// *
// * @return the Token Key
// */
// public String getKey() {
// return key;
// }
//
// /**
// * Updates the Token Key
// *
// * @param key the Token Key
// */
// public void setKey(final String key) {
// this.key = key;
// }
//
// /**
// * Retrieves the Token Secret
// *
// * @return the Token Secret
// */
// public String getSecret() {
// return secret;
// }
//
// /**
// * Updates the Token Secret
// *
// * @param secret the Token Secret
// */
// public void setSecret(final String secret) {
// this.secret = secret;
// }
//
// /**
// * Gets the attributes of this token.
// */
// public Map<String, Object> getAttributes() {
// return _attributes;
// }
//
// /**
// * Gets an attribute based from the given key.
// */
// public Object getAttribute(final String key) {
// return _attributes == null ? null : _attributes.get(key);
// }
//
// /**
// * Sets an attribute based from the given key and value.
// */
// public void setAttribute(final String key, final Object value) {
// if (_attributes == null) {
// _attributes = new HashMap<String, Object>();
// }
//
// _attributes.put(key, value);
// }
//
// /**
// * Sets an attributes from given attributes map.
// */
// public void setAttributes(final Map<String, Object> attributes) {
// if (_attributes == null) {
// _attributes = new HashMap<String, Object>();
// }
//
// _attributes.putAll(attributes);
// }
//
// /**
// * Retrieves the provider id.
// *
// * @return the provider id.
// */
// public String getProviderId() {
// return providerId;
// }
//
// /**
// * Updates the provider id.
// *
// * @param providerId the provider id.
// */
// public void setProviderId(final String providerId) {
// this.providerId = providerId;
// }
//
// @Override
// public String toString() {
// StringBuilder result = new StringBuilder();
// String NEW_LINE = System.getProperty("line.separator");
// result.append(this.getClass().getName() + " Object {" + NEW_LINE);
// result.append(" token key : " + key + NEW_LINE);
// result.append(" token secret : " + secret + NEW_LINE);
// result.append("provider id : " + providerId + NEW_LINE);
// if (_attributes != null) {
// result.append(_attributes.toString());
// }
// result.append("}");
//
// return result.toString();
// }
//
// }
| import io.stalk.common.oauth.utils.AccessGrant; | package io.stalk.common.oauth.strategy;
public class RequestToken {
private String url; | // Path: src/main/java/io/stalk/common/oauth/utils/AccessGrant.java
// public class AccessGrant implements Serializable {
//
// private static final long serialVersionUID = -7120362372191191930L;
// private String key;
// private String secret;
// private String providerId;
// private Map<String, Object> _attributes;
//
// /**
// * @param key the Key
// * @param secret the Secret
// */
// public AccessGrant(final String key, final String secret) {
// this.key = key;
// this.secret = secret;
// }
//
// public AccessGrant() {
// }
//
// /**
// * Retrieves the Token Key
// *
// * @return the Token Key
// */
// public String getKey() {
// return key;
// }
//
// /**
// * Updates the Token Key
// *
// * @param key the Token Key
// */
// public void setKey(final String key) {
// this.key = key;
// }
//
// /**
// * Retrieves the Token Secret
// *
// * @return the Token Secret
// */
// public String getSecret() {
// return secret;
// }
//
// /**
// * Updates the Token Secret
// *
// * @param secret the Token Secret
// */
// public void setSecret(final String secret) {
// this.secret = secret;
// }
//
// /**
// * Gets the attributes of this token.
// */
// public Map<String, Object> getAttributes() {
// return _attributes;
// }
//
// /**
// * Gets an attribute based from the given key.
// */
// public Object getAttribute(final String key) {
// return _attributes == null ? null : _attributes.get(key);
// }
//
// /**
// * Sets an attribute based from the given key and value.
// */
// public void setAttribute(final String key, final Object value) {
// if (_attributes == null) {
// _attributes = new HashMap<String, Object>();
// }
//
// _attributes.put(key, value);
// }
//
// /**
// * Sets an attributes from given attributes map.
// */
// public void setAttributes(final Map<String, Object> attributes) {
// if (_attributes == null) {
// _attributes = new HashMap<String, Object>();
// }
//
// _attributes.putAll(attributes);
// }
//
// /**
// * Retrieves the provider id.
// *
// * @return the provider id.
// */
// public String getProviderId() {
// return providerId;
// }
//
// /**
// * Updates the provider id.
// *
// * @param providerId the provider id.
// */
// public void setProviderId(final String providerId) {
// this.providerId = providerId;
// }
//
// @Override
// public String toString() {
// StringBuilder result = new StringBuilder();
// String NEW_LINE = System.getProperty("line.separator");
// result.append(this.getClass().getName() + " Object {" + NEW_LINE);
// result.append(" token key : " + key + NEW_LINE);
// result.append(" token secret : " + secret + NEW_LINE);
// result.append("provider id : " + providerId + NEW_LINE);
// if (_attributes != null) {
// result.append(_attributes.toString());
// }
// result.append("}");
//
// return result.toString();
// }
//
// }
// Path: src/main/java/io/stalk/common/oauth/strategy/RequestToken.java
import io.stalk.common.oauth.utils.AccessGrant;
package io.stalk.common.oauth.strategy;
public class RequestToken {
private String url; | private AccessGrant accessGrant; |
stalk-io/stalk-server | src/main/java/io/stalk/common/oauth/strategy/OAuth2.java | // Path: src/main/java/io/stalk/common/oauth/OAuthConfig.java
// public class OAuthConfig {
//
// private final String _consumerKey;
// private final String _consumerSecret;
// private final String _callbackUrl;
// private final String _signatureMethod;
// private final String _transportName;
// private String id;
// private Class<?> providerImplClass;
//
//
// public OAuthConfig(final String consumerKey, final String consumerSecret, final String callbackUrl,
// final String signatureMethod, final String transportName) {
// _consumerKey = consumerKey;
// _consumerSecret = consumerSecret;
// if (signatureMethod == null || signatureMethod.length() == 0) {
// _signatureMethod = Constants.HMACSHA1_SIGNATURE;
// } else {
// _signatureMethod = signatureMethod;
// }
// if (transportName == null || transportName.length() == 0) {
// _transportName = MethodType.GET.toString();
// } else {
// _transportName = transportName;
// }
// if (callbackUrl == null || callbackUrl.length() == 0) {
// _callbackUrl = "";
// } else {
// _callbackUrl = callbackUrl;
// }
//
// }
//
// public OAuthConfig(final String consumerKey, final String consumerSecret, final String callbackUrl) {
// _consumerKey = consumerKey;
// _consumerSecret = consumerSecret;
// _transportName = MethodType.GET.toString();
// _signatureMethod = Constants.HMACSHA1_SIGNATURE;
//
//
// if (callbackUrl == null || callbackUrl.length() == 0) {
// _callbackUrl = "";
// } else {
// _callbackUrl = callbackUrl;
// }
// }
//
// public String get_consumerKey() {
// return _consumerKey;
// }
//
// public String get_consumerSecret() {
// return _consumerSecret;
// }
//
// public String get_callbackUrl() {
// return _callbackUrl;
// }
//
// public String get_signatureMethod() {
// return _signatureMethod;
// }
//
// public String get_transportName() {
// return _transportName;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(final String id) {
// this.id = id;
// }
//
// public Class<?> getProviderImplClass() {
// return providerImplClass;
// }
//
// public void setProviderImplClass(final Class<?> providerImplClass) {
// this.providerImplClass = providerImplClass;
// }
//
// @Override
// public String toString() {
// StringBuilder result = new StringBuilder();
// String NEW_LINE = System.getProperty("line.separator");
// result.append(this.getClass().getName() + " Object {" + NEW_LINE);
// result.append(" consumerKey: " + _consumerKey + NEW_LINE);
// result.append(" consumerSecret: " + _consumerSecret + NEW_LINE);
// result.append(" signatureMethod: " + _signatureMethod + NEW_LINE);
// result.append(" transportName: " + _transportName + NEW_LINE);
// result.append(" id: " + id + NEW_LINE);
// result.append(" providerImplClass: " + providerImplClass + NEW_LINE);
// result.append("}");
// return result.toString();
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/oauth/exception/SocialAuthException.java
// public class SocialAuthException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -6856436294292027306L;
//
// public SocialAuthException() {
// super();
// }
//
// public SocialAuthException(final String message) {
// super(message);
// }
//
// public SocialAuthException(final Throwable cause) {
// super(cause);
// }
//
// public SocialAuthException(final String message, final Throwable cause) {
// super(message, cause);
// }
// }
| import io.stalk.common.oauth.OAuthConfig;
import io.stalk.common.oauth.exception.SocialAuthException;
import io.stalk.common.oauth.utils.*;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
| package io.stalk.common.oauth.strategy;
public class OAuth2 implements OAuthStrategyBase {
private OAuthConsumer oauth;
private Map<String, String> endpoints;
private String scope;
private String providerId;
private String successUrl;
private String accessTokenParameterName;
| // Path: src/main/java/io/stalk/common/oauth/OAuthConfig.java
// public class OAuthConfig {
//
// private final String _consumerKey;
// private final String _consumerSecret;
// private final String _callbackUrl;
// private final String _signatureMethod;
// private final String _transportName;
// private String id;
// private Class<?> providerImplClass;
//
//
// public OAuthConfig(final String consumerKey, final String consumerSecret, final String callbackUrl,
// final String signatureMethod, final String transportName) {
// _consumerKey = consumerKey;
// _consumerSecret = consumerSecret;
// if (signatureMethod == null || signatureMethod.length() == 0) {
// _signatureMethod = Constants.HMACSHA1_SIGNATURE;
// } else {
// _signatureMethod = signatureMethod;
// }
// if (transportName == null || transportName.length() == 0) {
// _transportName = MethodType.GET.toString();
// } else {
// _transportName = transportName;
// }
// if (callbackUrl == null || callbackUrl.length() == 0) {
// _callbackUrl = "";
// } else {
// _callbackUrl = callbackUrl;
// }
//
// }
//
// public OAuthConfig(final String consumerKey, final String consumerSecret, final String callbackUrl) {
// _consumerKey = consumerKey;
// _consumerSecret = consumerSecret;
// _transportName = MethodType.GET.toString();
// _signatureMethod = Constants.HMACSHA1_SIGNATURE;
//
//
// if (callbackUrl == null || callbackUrl.length() == 0) {
// _callbackUrl = "";
// } else {
// _callbackUrl = callbackUrl;
// }
// }
//
// public String get_consumerKey() {
// return _consumerKey;
// }
//
// public String get_consumerSecret() {
// return _consumerSecret;
// }
//
// public String get_callbackUrl() {
// return _callbackUrl;
// }
//
// public String get_signatureMethod() {
// return _signatureMethod;
// }
//
// public String get_transportName() {
// return _transportName;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(final String id) {
// this.id = id;
// }
//
// public Class<?> getProviderImplClass() {
// return providerImplClass;
// }
//
// public void setProviderImplClass(final Class<?> providerImplClass) {
// this.providerImplClass = providerImplClass;
// }
//
// @Override
// public String toString() {
// StringBuilder result = new StringBuilder();
// String NEW_LINE = System.getProperty("line.separator");
// result.append(this.getClass().getName() + " Object {" + NEW_LINE);
// result.append(" consumerKey: " + _consumerKey + NEW_LINE);
// result.append(" consumerSecret: " + _consumerSecret + NEW_LINE);
// result.append(" signatureMethod: " + _signatureMethod + NEW_LINE);
// result.append(" transportName: " + _transportName + NEW_LINE);
// result.append(" id: " + id + NEW_LINE);
// result.append(" providerImplClass: " + providerImplClass + NEW_LINE);
// result.append("}");
// return result.toString();
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/oauth/exception/SocialAuthException.java
// public class SocialAuthException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -6856436294292027306L;
//
// public SocialAuthException() {
// super();
// }
//
// public SocialAuthException(final String message) {
// super(message);
// }
//
// public SocialAuthException(final Throwable cause) {
// super(cause);
// }
//
// public SocialAuthException(final String message, final Throwable cause) {
// super(message, cause);
// }
// }
// Path: src/main/java/io/stalk/common/oauth/strategy/OAuth2.java
import io.stalk.common.oauth.OAuthConfig;
import io.stalk.common.oauth.exception.SocialAuthException;
import io.stalk.common.oauth.utils.*;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
package io.stalk.common.oauth.strategy;
public class OAuth2 implements OAuthStrategyBase {
private OAuthConsumer oauth;
private Map<String, String> endpoints;
private String scope;
private String providerId;
private String successUrl;
private String accessTokenParameterName;
| public OAuth2(final OAuthConfig config, final Map<String, String> endpoints) {
|
stalk-io/stalk-server | src/main/java/io/stalk/common/oauth/strategy/OAuth2.java | // Path: src/main/java/io/stalk/common/oauth/OAuthConfig.java
// public class OAuthConfig {
//
// private final String _consumerKey;
// private final String _consumerSecret;
// private final String _callbackUrl;
// private final String _signatureMethod;
// private final String _transportName;
// private String id;
// private Class<?> providerImplClass;
//
//
// public OAuthConfig(final String consumerKey, final String consumerSecret, final String callbackUrl,
// final String signatureMethod, final String transportName) {
// _consumerKey = consumerKey;
// _consumerSecret = consumerSecret;
// if (signatureMethod == null || signatureMethod.length() == 0) {
// _signatureMethod = Constants.HMACSHA1_SIGNATURE;
// } else {
// _signatureMethod = signatureMethod;
// }
// if (transportName == null || transportName.length() == 0) {
// _transportName = MethodType.GET.toString();
// } else {
// _transportName = transportName;
// }
// if (callbackUrl == null || callbackUrl.length() == 0) {
// _callbackUrl = "";
// } else {
// _callbackUrl = callbackUrl;
// }
//
// }
//
// public OAuthConfig(final String consumerKey, final String consumerSecret, final String callbackUrl) {
// _consumerKey = consumerKey;
// _consumerSecret = consumerSecret;
// _transportName = MethodType.GET.toString();
// _signatureMethod = Constants.HMACSHA1_SIGNATURE;
//
//
// if (callbackUrl == null || callbackUrl.length() == 0) {
// _callbackUrl = "";
// } else {
// _callbackUrl = callbackUrl;
// }
// }
//
// public String get_consumerKey() {
// return _consumerKey;
// }
//
// public String get_consumerSecret() {
// return _consumerSecret;
// }
//
// public String get_callbackUrl() {
// return _callbackUrl;
// }
//
// public String get_signatureMethod() {
// return _signatureMethod;
// }
//
// public String get_transportName() {
// return _transportName;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(final String id) {
// this.id = id;
// }
//
// public Class<?> getProviderImplClass() {
// return providerImplClass;
// }
//
// public void setProviderImplClass(final Class<?> providerImplClass) {
// this.providerImplClass = providerImplClass;
// }
//
// @Override
// public String toString() {
// StringBuilder result = new StringBuilder();
// String NEW_LINE = System.getProperty("line.separator");
// result.append(this.getClass().getName() + " Object {" + NEW_LINE);
// result.append(" consumerKey: " + _consumerKey + NEW_LINE);
// result.append(" consumerSecret: " + _consumerSecret + NEW_LINE);
// result.append(" signatureMethod: " + _signatureMethod + NEW_LINE);
// result.append(" transportName: " + _transportName + NEW_LINE);
// result.append(" id: " + id + NEW_LINE);
// result.append(" providerImplClass: " + providerImplClass + NEW_LINE);
// result.append("}");
// return result.toString();
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/oauth/exception/SocialAuthException.java
// public class SocialAuthException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -6856436294292027306L;
//
// public SocialAuthException() {
// super();
// }
//
// public SocialAuthException(final String message) {
// super(message);
// }
//
// public SocialAuthException(final Throwable cause) {
// super(cause);
// }
//
// public SocialAuthException(final String message, final Throwable cause) {
// super(message, cause);
// }
// }
| import io.stalk.common.oauth.OAuthConfig;
import io.stalk.common.oauth.exception.SocialAuthException;
import io.stalk.common.oauth.utils.*;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
| sb.append("&display=popup");
sb.append("&redirect_uri=").append(this.successUrl);
if (scope != null) {
sb.append("&scope=").append(scope);
}
String url = sb.toString();
System.out.println("Redirection to following URL should happen : " + url);
AccessGrant requestToken = new AccessGrant();
requestToken.setProviderId(providerId);
RequestToken token = new RequestToken(url, requestToken);
return token;
}
@Override
public AccessGrant verifyResponse(AccessGrant requestToken,
Map<String, String> requestParams) throws Exception {
return verifyResponse(null, requestParams, MethodType.GET.toString());
}
@Override
public AccessGrant verifyResponse(AccessGrant requestToken,
Map<String, String> requestParams, String methodType)
throws Exception {
String code = requestParams.get("code");
if (code == null || code.length() == 0) {
| // Path: src/main/java/io/stalk/common/oauth/OAuthConfig.java
// public class OAuthConfig {
//
// private final String _consumerKey;
// private final String _consumerSecret;
// private final String _callbackUrl;
// private final String _signatureMethod;
// private final String _transportName;
// private String id;
// private Class<?> providerImplClass;
//
//
// public OAuthConfig(final String consumerKey, final String consumerSecret, final String callbackUrl,
// final String signatureMethod, final String transportName) {
// _consumerKey = consumerKey;
// _consumerSecret = consumerSecret;
// if (signatureMethod == null || signatureMethod.length() == 0) {
// _signatureMethod = Constants.HMACSHA1_SIGNATURE;
// } else {
// _signatureMethod = signatureMethod;
// }
// if (transportName == null || transportName.length() == 0) {
// _transportName = MethodType.GET.toString();
// } else {
// _transportName = transportName;
// }
// if (callbackUrl == null || callbackUrl.length() == 0) {
// _callbackUrl = "";
// } else {
// _callbackUrl = callbackUrl;
// }
//
// }
//
// public OAuthConfig(final String consumerKey, final String consumerSecret, final String callbackUrl) {
// _consumerKey = consumerKey;
// _consumerSecret = consumerSecret;
// _transportName = MethodType.GET.toString();
// _signatureMethod = Constants.HMACSHA1_SIGNATURE;
//
//
// if (callbackUrl == null || callbackUrl.length() == 0) {
// _callbackUrl = "";
// } else {
// _callbackUrl = callbackUrl;
// }
// }
//
// public String get_consumerKey() {
// return _consumerKey;
// }
//
// public String get_consumerSecret() {
// return _consumerSecret;
// }
//
// public String get_callbackUrl() {
// return _callbackUrl;
// }
//
// public String get_signatureMethod() {
// return _signatureMethod;
// }
//
// public String get_transportName() {
// return _transportName;
// }
//
// public String getId() {
// return id;
// }
//
// public void setId(final String id) {
// this.id = id;
// }
//
// public Class<?> getProviderImplClass() {
// return providerImplClass;
// }
//
// public void setProviderImplClass(final Class<?> providerImplClass) {
// this.providerImplClass = providerImplClass;
// }
//
// @Override
// public String toString() {
// StringBuilder result = new StringBuilder();
// String NEW_LINE = System.getProperty("line.separator");
// result.append(this.getClass().getName() + " Object {" + NEW_LINE);
// result.append(" consumerKey: " + _consumerKey + NEW_LINE);
// result.append(" consumerSecret: " + _consumerSecret + NEW_LINE);
// result.append(" signatureMethod: " + _signatureMethod + NEW_LINE);
// result.append(" transportName: " + _transportName + NEW_LINE);
// result.append(" id: " + id + NEW_LINE);
// result.append(" providerImplClass: " + providerImplClass + NEW_LINE);
// result.append("}");
// return result.toString();
// }
//
//
// }
//
// Path: src/main/java/io/stalk/common/oauth/exception/SocialAuthException.java
// public class SocialAuthException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = -6856436294292027306L;
//
// public SocialAuthException() {
// super();
// }
//
// public SocialAuthException(final String message) {
// super(message);
// }
//
// public SocialAuthException(final Throwable cause) {
// super(cause);
// }
//
// public SocialAuthException(final String message, final Throwable cause) {
// super(message, cause);
// }
// }
// Path: src/main/java/io/stalk/common/oauth/strategy/OAuth2.java
import io.stalk.common.oauth.OAuthConfig;
import io.stalk.common.oauth.exception.SocialAuthException;
import io.stalk.common.oauth.utils.*;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
sb.append("&display=popup");
sb.append("&redirect_uri=").append(this.successUrl);
if (scope != null) {
sb.append("&scope=").append(scope);
}
String url = sb.toString();
System.out.println("Redirection to following URL should happen : " + url);
AccessGrant requestToken = new AccessGrant();
requestToken.setProviderId(providerId);
RequestToken token = new RequestToken(url, requestToken);
return token;
}
@Override
public AccessGrant verifyResponse(AccessGrant requestToken,
Map<String, String> requestParams) throws Exception {
return verifyResponse(null, requestParams, MethodType.GET.toString());
}
@Override
public AccessGrant verifyResponse(AccessGrant requestToken,
Map<String, String> requestParams, String methodType)
throws Exception {
String code = requestParams.get("code");
if (code == null || code.length() == 0) {
| throw new SocialAuthException("Verification code is null");
|
biointec/halvade | halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/BaseFileReader.java | // Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/Logger.java
// public class Logger {
// /*
// * levels of debugging
// * 0: INFO
// * 1: DEBUG
// * 2: EXCEPTION
// * 3:ALL
// */
// private static int LEVEL = 0;
// private static final int EXCEPTION = 2;
// private static final int DEBUG = 1;
// private static final int INFO = 0;
//
//
// // TODO use configuration set LEVEL
// public static void SETLEVEL(int NEWLEVEL) {
// LEVEL = NEWLEVEL;
// }
//
// public static void EXCEPTION(Exception ex){
// System.err.println("[EXCEPTION] " + ex.getLocalizedMessage());
// ex.printStackTrace();
// }
//
// public static void THROWABLE(Throwable ex){
// System.err.println("[EXCEPTION] " + ex.getLocalizedMessage());
// ex.printStackTrace();
// }
//
// public static void DEBUG(String message) {
// if(LEVEL >= DEBUG)
// System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message);
// }
//
// public static void INFO(String message) {
// if(LEVEL >= INFO)
// System.err.println("[INFO] " + message);
// }
//
// public static void DEBUG(String message, int level) {
// if(LEVEL >= level)
// System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message);
// }
// }
| import be.ugent.intec.halvade.uploader.Logger;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.tools.bzip2.CBZip2InputStream; | return new BufferedReader(new InputStreamReader(hdfsIn));
} else {
if(file.endsWith(".gz")) {
GZIPInputStream gzip = new GZIPInputStream(new FileInputStream(file), BUFFERSIZE);
return new BufferedReader(new InputStreamReader(gzip));
} else if(file.endsWith(".bz2")) {
CBZip2InputStream bzip2 = new CBZip2InputStream(new FileInputStream(file));
return new BufferedReader(new InputStreamReader(bzip2));
} else if(file.equals("-")) {
return new BufferedReader(new InputStreamReader(System.in));
}else
return new BufferedReader(new FileReader(file));
}
}
@Override
protected void finalize() throws Throwable {
super.finalize(); //To change body of generated methods, choose Tools | Templates.
// Logger.INFO("Finished: " + toStr);
}
public synchronized boolean getNextBlock(ReadBlock block) {
block.reset();
try {
while(addNextRead(block) == 0) {
}
// if addnext is -1 then close this!
count += block.size / LINES_PER_READ;
} catch (IOException ex) { | // Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/Logger.java
// public class Logger {
// /*
// * levels of debugging
// * 0: INFO
// * 1: DEBUG
// * 2: EXCEPTION
// * 3:ALL
// */
// private static int LEVEL = 0;
// private static final int EXCEPTION = 2;
// private static final int DEBUG = 1;
// private static final int INFO = 0;
//
//
// // TODO use configuration set LEVEL
// public static void SETLEVEL(int NEWLEVEL) {
// LEVEL = NEWLEVEL;
// }
//
// public static void EXCEPTION(Exception ex){
// System.err.println("[EXCEPTION] " + ex.getLocalizedMessage());
// ex.printStackTrace();
// }
//
// public static void THROWABLE(Throwable ex){
// System.err.println("[EXCEPTION] " + ex.getLocalizedMessage());
// ex.printStackTrace();
// }
//
// public static void DEBUG(String message) {
// if(LEVEL >= DEBUG)
// System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message);
// }
//
// public static void INFO(String message) {
// if(LEVEL >= INFO)
// System.err.println("[INFO] " + message);
// }
//
// public static void DEBUG(String message, int level) {
// if(LEVEL >= level)
// System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message);
// }
// }
// Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/BaseFileReader.java
import be.ugent.intec.halvade.uploader.Logger;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.tools.bzip2.CBZip2InputStream;
return new BufferedReader(new InputStreamReader(hdfsIn));
} else {
if(file.endsWith(".gz")) {
GZIPInputStream gzip = new GZIPInputStream(new FileInputStream(file), BUFFERSIZE);
return new BufferedReader(new InputStreamReader(gzip));
} else if(file.endsWith(".bz2")) {
CBZip2InputStream bzip2 = new CBZip2InputStream(new FileInputStream(file));
return new BufferedReader(new InputStreamReader(bzip2));
} else if(file.equals("-")) {
return new BufferedReader(new InputStreamReader(System.in));
}else
return new BufferedReader(new FileReader(file));
}
}
@Override
protected void finalize() throws Throwable {
super.finalize(); //To change body of generated methods, choose Tools | Templates.
// Logger.INFO("Finished: " + toStr);
}
public synchronized boolean getNextBlock(ReadBlock block) {
block.reset();
try {
while(addNextRead(block) == 0) {
}
// if addnext is -1 then close this!
count += block.size / LINES_PER_READ;
} catch (IOException ex) { | Logger.INFO("error occured: " + ex.getMessage()); |
biointec/halvade | halvade/src/be/ugent/intec/halvade/tools/BWAMemInstance.java | // Path: halvade/src/be/ugent/intec/halvade/hadoop/mapreduce/HalvadeCounters.java
// public enum HalvadeCounters {
// TIME_BWA_ALN,
// TIME_BWA_MEM,
// TIME_BOWTIE2,
// TIME_CUSHAW2,
// TIME_BWA_SAMPE,
// TIME_STAR,
// TIME_STAR_REF,
// TIME_STAR_BUILD,
// TIME_ELPREP,
// TIME_BEDTOOLS,
// TIME_SAMTOBAM,
// TIME_SAMPLESAM,
// TIME_HADOOP_SAMTOBAM,
// TIME_PICARD_CLEANSAM,
// TIME_PICARD_MARKDUP,
// TIME_PICARD_ADDGRP,
// TIME_FEATURECOUNTS,
// TIME_PICARD_BAI,
// TIME_GATK_RECAL,
// TIME_GATK_TARGET_CREATOR,
// TIME_GATK_INDEL_REALN,
// TIME_GATK_PRINT_READS,
// TIME_GATK_COMBINE_VCF,
// TIME_GATK_VARIANT_CALLER,
//
// IN_BWA_READS,
// IN_PREP_READS,
//
// OUT_BWA_READS,
// OUT_VCF_FILES,
// OUT_UNMAPPED_READS,
// OUT_DIFF_CHR_READS,
// OUT_OVERLAPPING_READS,
//
// FOUT_BWA_TMP,
// FOUT_STAR_TMP,
// FOUT_GATK_TMP,
// FOUT_GATK_VCF,
// FOUT_TO_HDFS,
//
// FIN_FROM_HDFS,
//
// TOOLS_GATK,
//
// STILL_RUNNING_HEARTBEAT
// }
| import be.ugent.intec.halvade.hadoop.mapreduce.HalvadeCounters;
import java.io.IOException;
import java.io.InputStream;
import org.apache.hadoop.mapreduce.Mapper;
import be.ugent.intec.halvade.utils.*;
import java.net.URISyntaxException;
import org.apache.hadoop.mapreduce.Mapper.Context; | pbw.startProcess(null, System.err);
// check if alive.
if(!pbw.isAlive())
throw new ProcessException("BWA mem", pbw.getExitState());
pbw.getSTDINWriter();
// make a SAMstream handler
ssh = new SAMStreamHandler(instance, context, false);
ssh.start();
}
/**
*
* @return 1 is running, 0 is completed, -1 is error
*/
@Override
public int getState() {
return pbw.getState();
}
@Override
public void closeAligner() throws InterruptedException {
try {
// close the input stream
pbw.getSTDINWriter().flush();
pbw.getSTDINWriter().close();
} catch (IOException ex) {
Logger.EXCEPTION(ex);
}
int error = pbw.waitForCompletion(); | // Path: halvade/src/be/ugent/intec/halvade/hadoop/mapreduce/HalvadeCounters.java
// public enum HalvadeCounters {
// TIME_BWA_ALN,
// TIME_BWA_MEM,
// TIME_BOWTIE2,
// TIME_CUSHAW2,
// TIME_BWA_SAMPE,
// TIME_STAR,
// TIME_STAR_REF,
// TIME_STAR_BUILD,
// TIME_ELPREP,
// TIME_BEDTOOLS,
// TIME_SAMTOBAM,
// TIME_SAMPLESAM,
// TIME_HADOOP_SAMTOBAM,
// TIME_PICARD_CLEANSAM,
// TIME_PICARD_MARKDUP,
// TIME_PICARD_ADDGRP,
// TIME_FEATURECOUNTS,
// TIME_PICARD_BAI,
// TIME_GATK_RECAL,
// TIME_GATK_TARGET_CREATOR,
// TIME_GATK_INDEL_REALN,
// TIME_GATK_PRINT_READS,
// TIME_GATK_COMBINE_VCF,
// TIME_GATK_VARIANT_CALLER,
//
// IN_BWA_READS,
// IN_PREP_READS,
//
// OUT_BWA_READS,
// OUT_VCF_FILES,
// OUT_UNMAPPED_READS,
// OUT_DIFF_CHR_READS,
// OUT_OVERLAPPING_READS,
//
// FOUT_BWA_TMP,
// FOUT_STAR_TMP,
// FOUT_GATK_TMP,
// FOUT_GATK_VCF,
// FOUT_TO_HDFS,
//
// FIN_FROM_HDFS,
//
// TOOLS_GATK,
//
// STILL_RUNNING_HEARTBEAT
// }
// Path: halvade/src/be/ugent/intec/halvade/tools/BWAMemInstance.java
import be.ugent.intec.halvade.hadoop.mapreduce.HalvadeCounters;
import java.io.IOException;
import java.io.InputStream;
import org.apache.hadoop.mapreduce.Mapper;
import be.ugent.intec.halvade.utils.*;
import java.net.URISyntaxException;
import org.apache.hadoop.mapreduce.Mapper.Context;
pbw.startProcess(null, System.err);
// check if alive.
if(!pbw.isAlive())
throw new ProcessException("BWA mem", pbw.getExitState());
pbw.getSTDINWriter();
// make a SAMstream handler
ssh = new SAMStreamHandler(instance, context, false);
ssh.start();
}
/**
*
* @return 1 is running, 0 is completed, -1 is error
*/
@Override
public int getState() {
return pbw.getState();
}
@Override
public void closeAligner() throws InterruptedException {
try {
// close the input stream
pbw.getSTDINWriter().flush();
pbw.getSTDINWriter().close();
} catch (IOException ex) {
Logger.EXCEPTION(ex);
}
int error = pbw.waitForCompletion(); | context.getCounter(HalvadeCounters.TIME_BWA_MEM).increment(pbw.getExecutionTime()); |
biointec/halvade | halvade/src/be/ugent/intec/halvade/utils/HalvadeFileUtils.java | // Path: halvade/src/be/ugent/intec/halvade/hadoop/mapreduce/HalvadeCounters.java
// public enum HalvadeCounters {
// TIME_BWA_ALN,
// TIME_BWA_MEM,
// TIME_BOWTIE2,
// TIME_CUSHAW2,
// TIME_BWA_SAMPE,
// TIME_STAR,
// TIME_STAR_REF,
// TIME_STAR_BUILD,
// TIME_ELPREP,
// TIME_BEDTOOLS,
// TIME_SAMTOBAM,
// TIME_SAMPLESAM,
// TIME_HADOOP_SAMTOBAM,
// TIME_PICARD_CLEANSAM,
// TIME_PICARD_MARKDUP,
// TIME_PICARD_ADDGRP,
// TIME_FEATURECOUNTS,
// TIME_PICARD_BAI,
// TIME_GATK_RECAL,
// TIME_GATK_TARGET_CREATOR,
// TIME_GATK_INDEL_REALN,
// TIME_GATK_PRINT_READS,
// TIME_GATK_COMBINE_VCF,
// TIME_GATK_VARIANT_CALLER,
//
// IN_BWA_READS,
// IN_PREP_READS,
//
// OUT_BWA_READS,
// OUT_VCF_FILES,
// OUT_UNMAPPED_READS,
// OUT_DIFF_CHR_READS,
// OUT_OVERLAPPING_READS,
//
// FOUT_BWA_TMP,
// FOUT_STAR_TMP,
// FOUT_GATK_TMP,
// FOUT_GATK_VCF,
// FOUT_TO_HDFS,
//
// FIN_FROM_HDFS,
//
// TOOLS_GATK,
//
// STILL_RUNNING_HEARTBEAT
// }
| import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.TaskInputOutputContext;
import be.ugent.intec.halvade.hadoop.mapreduce.HalvadeCounters;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.zip.GZIPInputStream;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.ChecksumException;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem; | // attempt to download .idx file
if(fs.exists(new Path(hdfssite + ".idx")))
downloadFileWithLock(fs, lock, hdfssite + ".idx", refDir + name + ".idx", context.getConfiguration());
}
} catch (InterruptedException ex) {
Logger.EXCEPTION(ex);
} finally {
lock.removeAndReleaseLock();
}
Logger.DEBUG("local sires:");
for (String site: localSites) {
Logger.DEBUG(site);
}
return localSites;
}
public static boolean removeLocalFile(String filename) {
return removeLocalFile(false, filename);
}
public static boolean removeLocalFile(boolean keep, String filename) {
if(keep) return false;
File f = new File(filename);
long size = f.length();
boolean res = f.exists() && f.delete();
Logger.DEBUG((res ? "successfully deleted ": "failed to delete ") + "\"" + filename + "\" [" + (size / 1024 / 1024)+ "Mb]");
return res;
}
| // Path: halvade/src/be/ugent/intec/halvade/hadoop/mapreduce/HalvadeCounters.java
// public enum HalvadeCounters {
// TIME_BWA_ALN,
// TIME_BWA_MEM,
// TIME_BOWTIE2,
// TIME_CUSHAW2,
// TIME_BWA_SAMPE,
// TIME_STAR,
// TIME_STAR_REF,
// TIME_STAR_BUILD,
// TIME_ELPREP,
// TIME_BEDTOOLS,
// TIME_SAMTOBAM,
// TIME_SAMPLESAM,
// TIME_HADOOP_SAMTOBAM,
// TIME_PICARD_CLEANSAM,
// TIME_PICARD_MARKDUP,
// TIME_PICARD_ADDGRP,
// TIME_FEATURECOUNTS,
// TIME_PICARD_BAI,
// TIME_GATK_RECAL,
// TIME_GATK_TARGET_CREATOR,
// TIME_GATK_INDEL_REALN,
// TIME_GATK_PRINT_READS,
// TIME_GATK_COMBINE_VCF,
// TIME_GATK_VARIANT_CALLER,
//
// IN_BWA_READS,
// IN_PREP_READS,
//
// OUT_BWA_READS,
// OUT_VCF_FILES,
// OUT_UNMAPPED_READS,
// OUT_DIFF_CHR_READS,
// OUT_OVERLAPPING_READS,
//
// FOUT_BWA_TMP,
// FOUT_STAR_TMP,
// FOUT_GATK_TMP,
// FOUT_GATK_VCF,
// FOUT_TO_HDFS,
//
// FIN_FROM_HDFS,
//
// TOOLS_GATK,
//
// STILL_RUNNING_HEARTBEAT
// }
// Path: halvade/src/be/ugent/intec/halvade/utils/HalvadeFileUtils.java
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.TaskInputOutputContext;
import be.ugent.intec.halvade.hadoop.mapreduce.HalvadeCounters;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.zip.GZIPInputStream;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.ChecksumException;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
// attempt to download .idx file
if(fs.exists(new Path(hdfssite + ".idx")))
downloadFileWithLock(fs, lock, hdfssite + ".idx", refDir + name + ".idx", context.getConfiguration());
}
} catch (InterruptedException ex) {
Logger.EXCEPTION(ex);
} finally {
lock.removeAndReleaseLock();
}
Logger.DEBUG("local sires:");
for (String site: localSites) {
Logger.DEBUG(site);
}
return localSites;
}
public static boolean removeLocalFile(String filename) {
return removeLocalFile(false, filename);
}
public static boolean removeLocalFile(boolean keep, String filename) {
if(keep) return false;
File f = new File(filename);
long size = f.length();
boolean res = f.exists() && f.delete();
Logger.DEBUG((res ? "successfully deleted ": "failed to delete ") + "\"" + filename + "\" [" + (size / 1024 / 1024)+ "Mb]");
return res;
}
| public static boolean removeLocalFile(String filename, TaskInputOutputContext context, HalvadeCounters counter) { |
biointec/halvade | halvade/src/be/ugent/intec/halvade/hadoop/partitioners/GenomeSJSortComparator.java | // Path: halvade/src/be/ugent/intec/halvade/hadoop/datatypes/GenomeSJ.java
// public class GenomeSJ implements WritableComparable<GenomeSJ> {
// protected int type; // -2 = overhang length, -1 = sj string, 2 = count per key region
// protected int secondary_key;
//
// public void setOverhang(int overhang) {
// this.type = -2;
// this.secondary_key = overhang;
// }
//
// public void parseSJString(String sjString, SAMSequenceDictionary dict) {
// String columns[] = sjString.split("\t");
// this.type = -1;
// this.secondary_key = dict.getSequenceIndex(columns[0]);
// }
//
// public void setRegion(int key, int pos) {
// this.type = key;
// this.secondary_key = pos;
// }
//
// public int getType() {
// return type;
// }
// public int getSecKey() {
// return secondary_key;
// }
//
// public GenomeSJ() {
// this.type = 0;
// this.secondary_key = -1;
// }
//
// @Override
// public void write(DataOutput d) throws IOException {
// d.writeInt(type);
// d.writeInt(secondary_key);
// }
//
// @Override
// public String toString() {
// return "GenomeSJ{" + "1=" + type + ", 2=" + secondary_key + '}';
// }
//
//
// @Override
// public void readFields(DataInput di) throws IOException {
// type = di.readInt();
// secondary_key = di.readInt();
// }
//
// @Override
// public int compareTo(GenomeSJ o) {
// if(type == o.type) {
// return secondary_key - o.secondary_key;
// } else
// return type - o.type;
// }
//
// }
| import be.ugent.intec.halvade.hadoop.datatypes.GenomeSJ;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator; | /*
* Copyright (C) 2014 ddecap
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package be.ugent.intec.halvade.hadoop.partitioners;
/**
*
* @author ddecap
*/
public class GenomeSJSortComparator extends WritableComparator {
protected GenomeSJSortComparator() { | // Path: halvade/src/be/ugent/intec/halvade/hadoop/datatypes/GenomeSJ.java
// public class GenomeSJ implements WritableComparable<GenomeSJ> {
// protected int type; // -2 = overhang length, -1 = sj string, 2 = count per key region
// protected int secondary_key;
//
// public void setOverhang(int overhang) {
// this.type = -2;
// this.secondary_key = overhang;
// }
//
// public void parseSJString(String sjString, SAMSequenceDictionary dict) {
// String columns[] = sjString.split("\t");
// this.type = -1;
// this.secondary_key = dict.getSequenceIndex(columns[0]);
// }
//
// public void setRegion(int key, int pos) {
// this.type = key;
// this.secondary_key = pos;
// }
//
// public int getType() {
// return type;
// }
// public int getSecKey() {
// return secondary_key;
// }
//
// public GenomeSJ() {
// this.type = 0;
// this.secondary_key = -1;
// }
//
// @Override
// public void write(DataOutput d) throws IOException {
// d.writeInt(type);
// d.writeInt(secondary_key);
// }
//
// @Override
// public String toString() {
// return "GenomeSJ{" + "1=" + type + ", 2=" + secondary_key + '}';
// }
//
//
// @Override
// public void readFields(DataInput di) throws IOException {
// type = di.readInt();
// secondary_key = di.readInt();
// }
//
// @Override
// public int compareTo(GenomeSJ o) {
// if(type == o.type) {
// return secondary_key - o.secondary_key;
// } else
// return type - o.type;
// }
//
// }
// Path: halvade/src/be/ugent/intec/halvade/hadoop/partitioners/GenomeSJSortComparator.java
import be.ugent.intec.halvade.hadoop.datatypes.GenomeSJ;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;
/*
* Copyright (C) 2014 ddecap
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package be.ugent.intec.halvade.hadoop.partitioners;
/**
*
* @author ddecap
*/
public class GenomeSJSortComparator extends WritableComparator {
protected GenomeSJSortComparator() { | super(GenomeSJ.class, true); |
biointec/halvade | halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/FileReaderFactory.java | // Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/Logger.java
// public class Logger {
// /*
// * levels of debugging
// * 0: INFO
// * 1: DEBUG
// * 2: EXCEPTION
// * 3:ALL
// */
// private static int LEVEL = 0;
// private static final int EXCEPTION = 2;
// private static final int DEBUG = 1;
// private static final int INFO = 0;
//
//
// // TODO use configuration set LEVEL
// public static void SETLEVEL(int NEWLEVEL) {
// LEVEL = NEWLEVEL;
// }
//
// public static void EXCEPTION(Exception ex){
// System.err.println("[EXCEPTION] " + ex.getLocalizedMessage());
// ex.printStackTrace();
// }
//
// public static void THROWABLE(Throwable ex){
// System.err.println("[EXCEPTION] " + ex.getLocalizedMessage());
// ex.printStackTrace();
// }
//
// public static void DEBUG(String message) {
// if(LEVEL >= DEBUG)
// System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message);
// }
//
// public static void INFO(String message) {
// if(LEVEL >= INFO)
// System.err.println("[INFO] " + message);
// }
//
// public static void DEBUG(String message, int level) {
// if(LEVEL >= level)
// System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message);
// }
// }
| import be.ugent.intec.halvade.uploader.Logger;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit; | }
return allReaders;
}
public static BaseFileReader createFileReader(boolean fromHDFS, String fileA, String fileB, boolean interleaved) throws IOException {
if (fileB == null) {
return new SingleFastQReader(fromHDFS, fileA, interleaved);
} else {
return new PairedFastQReader(fromHDFS, fileA, fileB);
}
}
public void addReader(String fileA, String fileB, boolean interleaved) throws IOException {
readers.add(createFileReader(fromHDFS, fileA, fileB, interleaved));
}
public void addReader(BaseFileReader reader) {
readers.add(reader);
}
public ReadBlock retrieveBlock() {
try {
ReadBlock block = null;
while((check || blocks.size() > 0) && block == null) {
// Logger.INFO("get block" + blocks.size());
block = blocks.poll(1000, TimeUnit.MILLISECONDS);
}
return block;
} catch (InterruptedException ex) { | // Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/Logger.java
// public class Logger {
// /*
// * levels of debugging
// * 0: INFO
// * 1: DEBUG
// * 2: EXCEPTION
// * 3:ALL
// */
// private static int LEVEL = 0;
// private static final int EXCEPTION = 2;
// private static final int DEBUG = 1;
// private static final int INFO = 0;
//
//
// // TODO use configuration set LEVEL
// public static void SETLEVEL(int NEWLEVEL) {
// LEVEL = NEWLEVEL;
// }
//
// public static void EXCEPTION(Exception ex){
// System.err.println("[EXCEPTION] " + ex.getLocalizedMessage());
// ex.printStackTrace();
// }
//
// public static void THROWABLE(Throwable ex){
// System.err.println("[EXCEPTION] " + ex.getLocalizedMessage());
// ex.printStackTrace();
// }
//
// public static void DEBUG(String message) {
// if(LEVEL >= DEBUG)
// System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message);
// }
//
// public static void INFO(String message) {
// if(LEVEL >= INFO)
// System.err.println("[INFO] " + message);
// }
//
// public static void DEBUG(String message, int level) {
// if(LEVEL >= level)
// System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message);
// }
// }
// Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/FileReaderFactory.java
import be.ugent.intec.halvade.uploader.Logger;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
}
return allReaders;
}
public static BaseFileReader createFileReader(boolean fromHDFS, String fileA, String fileB, boolean interleaved) throws IOException {
if (fileB == null) {
return new SingleFastQReader(fromHDFS, fileA, interleaved);
} else {
return new PairedFastQReader(fromHDFS, fileA, fileB);
}
}
public void addReader(String fileA, String fileB, boolean interleaved) throws IOException {
readers.add(createFileReader(fromHDFS, fileA, fileB, interleaved));
}
public void addReader(BaseFileReader reader) {
readers.add(reader);
}
public ReadBlock retrieveBlock() {
try {
ReadBlock block = null;
while((check || blocks.size() > 0) && block == null) {
// Logger.INFO("get block" + blocks.size());
block = blocks.poll(1000, TimeUnit.MILLISECONDS);
}
return block;
} catch (InterruptedException ex) { | Logger.EXCEPTION(ex); |
biointec/halvade | halvade/src/be/ugent/intec/halvade/hadoop/partitioners/GenomeSJGroupingComparator.java | // Path: halvade/src/be/ugent/intec/halvade/hadoop/datatypes/GenomeSJ.java
// public class GenomeSJ implements WritableComparable<GenomeSJ> {
// protected int type; // -2 = overhang length, -1 = sj string, 2 = count per key region
// protected int secondary_key;
//
// public void setOverhang(int overhang) {
// this.type = -2;
// this.secondary_key = overhang;
// }
//
// public void parseSJString(String sjString, SAMSequenceDictionary dict) {
// String columns[] = sjString.split("\t");
// this.type = -1;
// this.secondary_key = dict.getSequenceIndex(columns[0]);
// }
//
// public void setRegion(int key, int pos) {
// this.type = key;
// this.secondary_key = pos;
// }
//
// public int getType() {
// return type;
// }
// public int getSecKey() {
// return secondary_key;
// }
//
// public GenomeSJ() {
// this.type = 0;
// this.secondary_key = -1;
// }
//
// @Override
// public void write(DataOutput d) throws IOException {
// d.writeInt(type);
// d.writeInt(secondary_key);
// }
//
// @Override
// public String toString() {
// return "GenomeSJ{" + "1=" + type + ", 2=" + secondary_key + '}';
// }
//
//
// @Override
// public void readFields(DataInput di) throws IOException {
// type = di.readInt();
// secondary_key = di.readInt();
// }
//
// @Override
// public int compareTo(GenomeSJ o) {
// if(type == o.type) {
// return secondary_key - o.secondary_key;
// } else
// return type - o.type;
// }
//
// }
| import be.ugent.intec.halvade.hadoop.datatypes.GenomeSJ;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator; | /*
* Copyright (C) 2014 ddecap
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package be.ugent.intec.halvade.hadoop.partitioners;
/**
*
* @author ddecap
*/
public class GenomeSJGroupingComparator extends WritableComparator {
protected GenomeSJGroupingComparator() { | // Path: halvade/src/be/ugent/intec/halvade/hadoop/datatypes/GenomeSJ.java
// public class GenomeSJ implements WritableComparable<GenomeSJ> {
// protected int type; // -2 = overhang length, -1 = sj string, 2 = count per key region
// protected int secondary_key;
//
// public void setOverhang(int overhang) {
// this.type = -2;
// this.secondary_key = overhang;
// }
//
// public void parseSJString(String sjString, SAMSequenceDictionary dict) {
// String columns[] = sjString.split("\t");
// this.type = -1;
// this.secondary_key = dict.getSequenceIndex(columns[0]);
// }
//
// public void setRegion(int key, int pos) {
// this.type = key;
// this.secondary_key = pos;
// }
//
// public int getType() {
// return type;
// }
// public int getSecKey() {
// return secondary_key;
// }
//
// public GenomeSJ() {
// this.type = 0;
// this.secondary_key = -1;
// }
//
// @Override
// public void write(DataOutput d) throws IOException {
// d.writeInt(type);
// d.writeInt(secondary_key);
// }
//
// @Override
// public String toString() {
// return "GenomeSJ{" + "1=" + type + ", 2=" + secondary_key + '}';
// }
//
//
// @Override
// public void readFields(DataInput di) throws IOException {
// type = di.readInt();
// secondary_key = di.readInt();
// }
//
// @Override
// public int compareTo(GenomeSJ o) {
// if(type == o.type) {
// return secondary_key - o.secondary_key;
// } else
// return type - o.type;
// }
//
// }
// Path: halvade/src/be/ugent/intec/halvade/hadoop/partitioners/GenomeSJGroupingComparator.java
import be.ugent.intec.halvade.hadoop.datatypes.GenomeSJ;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;
/*
* Copyright (C) 2014 ddecap
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package be.ugent.intec.halvade.hadoop.partitioners;
/**
*
* @author ddecap
*/
public class GenomeSJGroupingComparator extends WritableComparator {
protected GenomeSJGroupingComparator() { | super(GenomeSJ.class, true); |
biointec/halvade | halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/SingleFastQReader.java | // Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/Logger.java
// public class Logger {
// /*
// * levels of debugging
// * 0: INFO
// * 1: DEBUG
// * 2: EXCEPTION
// * 3:ALL
// */
// private static int LEVEL = 0;
// private static final int EXCEPTION = 2;
// private static final int DEBUG = 1;
// private static final int INFO = 0;
//
//
// // TODO use configuration set LEVEL
// public static void SETLEVEL(int NEWLEVEL) {
// LEVEL = NEWLEVEL;
// }
//
// public static void EXCEPTION(Exception ex){
// System.err.println("[EXCEPTION] " + ex.getLocalizedMessage());
// ex.printStackTrace();
// }
//
// public static void THROWABLE(Throwable ex){
// System.err.println("[EXCEPTION] " + ex.getLocalizedMessage());
// ex.printStackTrace();
// }
//
// public static void DEBUG(String message) {
// if(LEVEL >= DEBUG)
// System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message);
// }
//
// public static void INFO(String message) {
// if(LEVEL >= INFO)
// System.err.println("[INFO] " + message);
// }
//
// public static void DEBUG(String message, int level) {
// if(LEVEL >= level)
// System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message);
// }
// }
//
// Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/BaseFileReader.java
// protected static BufferedReader getReader(boolean readFromDistributedStorage, String file) throws FileNotFoundException, IOException {
// InputStream hdfsIn;
// if(readFromDistributedStorage) {
// Path pt =new Path(file);
// FileSystem fs = FileSystem.get(pt.toUri(), new Configuration());
// hdfsIn = fs.open(pt);
// // read the stream in the correct format!
// if(file.endsWith(".gz")) {
// GZIPInputStream gzip = new GZIPInputStream(hdfsIn, BUFFERSIZE);
// return new BufferedReader(new InputStreamReader(gzip));
// } else if(file.endsWith(".bz2")) {
// CBZip2InputStream bzip2 = new CBZip2InputStream(hdfsIn);
// return new BufferedReader(new InputStreamReader(bzip2));
// } else
// return new BufferedReader(new InputStreamReader(hdfsIn));
//
// } else {
// if(file.endsWith(".gz")) {
// GZIPInputStream gzip = new GZIPInputStream(new FileInputStream(file), BUFFERSIZE);
// return new BufferedReader(new InputStreamReader(gzip));
// } else if(file.endsWith(".bz2")) {
// CBZip2InputStream bzip2 = new CBZip2InputStream(new FileInputStream(file));
// return new BufferedReader(new InputStreamReader(bzip2));
// } else if(file.equals("-")) {
// return new BufferedReader(new InputStreamReader(System.in));
// }else
// return new BufferedReader(new FileReader(file));
// }
// }
| import be.ugent.intec.halvade.uploader.Logger;
import static be.ugent.intec.halvade.uploader.input.BaseFileReader.getReader;
import java.io.BufferedReader;
import java.io.IOException; | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package be.ugent.intec.halvade.uploader.input;
/**
*
* @author ddecap
*/
public class SingleFastQReader extends BaseFileReader {
protected BufferedReader readerA;
protected ReadBlock block;
protected int readsFactor;
public SingleFastQReader(boolean fromHDFS, String fileA, boolean interleaved) throws IOException {
super(true); | // Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/Logger.java
// public class Logger {
// /*
// * levels of debugging
// * 0: INFO
// * 1: DEBUG
// * 2: EXCEPTION
// * 3:ALL
// */
// private static int LEVEL = 0;
// private static final int EXCEPTION = 2;
// private static final int DEBUG = 1;
// private static final int INFO = 0;
//
//
// // TODO use configuration set LEVEL
// public static void SETLEVEL(int NEWLEVEL) {
// LEVEL = NEWLEVEL;
// }
//
// public static void EXCEPTION(Exception ex){
// System.err.println("[EXCEPTION] " + ex.getLocalizedMessage());
// ex.printStackTrace();
// }
//
// public static void THROWABLE(Throwable ex){
// System.err.println("[EXCEPTION] " + ex.getLocalizedMessage());
// ex.printStackTrace();
// }
//
// public static void DEBUG(String message) {
// if(LEVEL >= DEBUG)
// System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message);
// }
//
// public static void INFO(String message) {
// if(LEVEL >= INFO)
// System.err.println("[INFO] " + message);
// }
//
// public static void DEBUG(String message, int level) {
// if(LEVEL >= level)
// System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message);
// }
// }
//
// Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/BaseFileReader.java
// protected static BufferedReader getReader(boolean readFromDistributedStorage, String file) throws FileNotFoundException, IOException {
// InputStream hdfsIn;
// if(readFromDistributedStorage) {
// Path pt =new Path(file);
// FileSystem fs = FileSystem.get(pt.toUri(), new Configuration());
// hdfsIn = fs.open(pt);
// // read the stream in the correct format!
// if(file.endsWith(".gz")) {
// GZIPInputStream gzip = new GZIPInputStream(hdfsIn, BUFFERSIZE);
// return new BufferedReader(new InputStreamReader(gzip));
// } else if(file.endsWith(".bz2")) {
// CBZip2InputStream bzip2 = new CBZip2InputStream(hdfsIn);
// return new BufferedReader(new InputStreamReader(bzip2));
// } else
// return new BufferedReader(new InputStreamReader(hdfsIn));
//
// } else {
// if(file.endsWith(".gz")) {
// GZIPInputStream gzip = new GZIPInputStream(new FileInputStream(file), BUFFERSIZE);
// return new BufferedReader(new InputStreamReader(gzip));
// } else if(file.endsWith(".bz2")) {
// CBZip2InputStream bzip2 = new CBZip2InputStream(new FileInputStream(file));
// return new BufferedReader(new InputStreamReader(bzip2));
// } else if(file.equals("-")) {
// return new BufferedReader(new InputStreamReader(System.in));
// }else
// return new BufferedReader(new FileReader(file));
// }
// }
// Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/SingleFastQReader.java
import be.ugent.intec.halvade.uploader.Logger;
import static be.ugent.intec.halvade.uploader.input.BaseFileReader.getReader;
import java.io.BufferedReader;
import java.io.IOException;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package be.ugent.intec.halvade.uploader.input;
/**
*
* @author ddecap
*/
public class SingleFastQReader extends BaseFileReader {
protected BufferedReader readerA;
protected ReadBlock block;
protected int readsFactor;
public SingleFastQReader(boolean fromHDFS, String fileA, boolean interleaved) throws IOException {
super(true); | readerA = getReader(fromHDFS, fileA); |
biointec/halvade | halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/SingleFastQReader.java | // Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/Logger.java
// public class Logger {
// /*
// * levels of debugging
// * 0: INFO
// * 1: DEBUG
// * 2: EXCEPTION
// * 3:ALL
// */
// private static int LEVEL = 0;
// private static final int EXCEPTION = 2;
// private static final int DEBUG = 1;
// private static final int INFO = 0;
//
//
// // TODO use configuration set LEVEL
// public static void SETLEVEL(int NEWLEVEL) {
// LEVEL = NEWLEVEL;
// }
//
// public static void EXCEPTION(Exception ex){
// System.err.println("[EXCEPTION] " + ex.getLocalizedMessage());
// ex.printStackTrace();
// }
//
// public static void THROWABLE(Throwable ex){
// System.err.println("[EXCEPTION] " + ex.getLocalizedMessage());
// ex.printStackTrace();
// }
//
// public static void DEBUG(String message) {
// if(LEVEL >= DEBUG)
// System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message);
// }
//
// public static void INFO(String message) {
// if(LEVEL >= INFO)
// System.err.println("[INFO] " + message);
// }
//
// public static void DEBUG(String message, int level) {
// if(LEVEL >= level)
// System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message);
// }
// }
//
// Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/BaseFileReader.java
// protected static BufferedReader getReader(boolean readFromDistributedStorage, String file) throws FileNotFoundException, IOException {
// InputStream hdfsIn;
// if(readFromDistributedStorage) {
// Path pt =new Path(file);
// FileSystem fs = FileSystem.get(pt.toUri(), new Configuration());
// hdfsIn = fs.open(pt);
// // read the stream in the correct format!
// if(file.endsWith(".gz")) {
// GZIPInputStream gzip = new GZIPInputStream(hdfsIn, BUFFERSIZE);
// return new BufferedReader(new InputStreamReader(gzip));
// } else if(file.endsWith(".bz2")) {
// CBZip2InputStream bzip2 = new CBZip2InputStream(hdfsIn);
// return new BufferedReader(new InputStreamReader(bzip2));
// } else
// return new BufferedReader(new InputStreamReader(hdfsIn));
//
// } else {
// if(file.endsWith(".gz")) {
// GZIPInputStream gzip = new GZIPInputStream(new FileInputStream(file), BUFFERSIZE);
// return new BufferedReader(new InputStreamReader(gzip));
// } else if(file.endsWith(".bz2")) {
// CBZip2InputStream bzip2 = new CBZip2InputStream(new FileInputStream(file));
// return new BufferedReader(new InputStreamReader(bzip2));
// } else if(file.equals("-")) {
// return new BufferedReader(new InputStreamReader(System.in));
// }else
// return new BufferedReader(new FileReader(file));
// }
// }
| import be.ugent.intec.halvade.uploader.Logger;
import static be.ugent.intec.halvade.uploader.input.BaseFileReader.getReader;
import java.io.BufferedReader;
import java.io.IOException; | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package be.ugent.intec.halvade.uploader.input;
/**
*
* @author ddecap
*/
public class SingleFastQReader extends BaseFileReader {
protected BufferedReader readerA;
protected ReadBlock block;
protected int readsFactor;
public SingleFastQReader(boolean fromHDFS, String fileA, boolean interleaved) throws IOException {
super(true);
readerA = getReader(fromHDFS, fileA);
this.isInterleaved = interleaved;
if(isInterleaved)
readsFactor = 2;
else
readsFactor = 1;
toStr = fileA; | // Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/Logger.java
// public class Logger {
// /*
// * levels of debugging
// * 0: INFO
// * 1: DEBUG
// * 2: EXCEPTION
// * 3:ALL
// */
// private static int LEVEL = 0;
// private static final int EXCEPTION = 2;
// private static final int DEBUG = 1;
// private static final int INFO = 0;
//
//
// // TODO use configuration set LEVEL
// public static void SETLEVEL(int NEWLEVEL) {
// LEVEL = NEWLEVEL;
// }
//
// public static void EXCEPTION(Exception ex){
// System.err.println("[EXCEPTION] " + ex.getLocalizedMessage());
// ex.printStackTrace();
// }
//
// public static void THROWABLE(Throwable ex){
// System.err.println("[EXCEPTION] " + ex.getLocalizedMessage());
// ex.printStackTrace();
// }
//
// public static void DEBUG(String message) {
// if(LEVEL >= DEBUG)
// System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message);
// }
//
// public static void INFO(String message) {
// if(LEVEL >= INFO)
// System.err.println("[INFO] " + message);
// }
//
// public static void DEBUG(String message, int level) {
// if(LEVEL >= level)
// System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message);
// }
// }
//
// Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/BaseFileReader.java
// protected static BufferedReader getReader(boolean readFromDistributedStorage, String file) throws FileNotFoundException, IOException {
// InputStream hdfsIn;
// if(readFromDistributedStorage) {
// Path pt =new Path(file);
// FileSystem fs = FileSystem.get(pt.toUri(), new Configuration());
// hdfsIn = fs.open(pt);
// // read the stream in the correct format!
// if(file.endsWith(".gz")) {
// GZIPInputStream gzip = new GZIPInputStream(hdfsIn, BUFFERSIZE);
// return new BufferedReader(new InputStreamReader(gzip));
// } else if(file.endsWith(".bz2")) {
// CBZip2InputStream bzip2 = new CBZip2InputStream(hdfsIn);
// return new BufferedReader(new InputStreamReader(bzip2));
// } else
// return new BufferedReader(new InputStreamReader(hdfsIn));
//
// } else {
// if(file.endsWith(".gz")) {
// GZIPInputStream gzip = new GZIPInputStream(new FileInputStream(file), BUFFERSIZE);
// return new BufferedReader(new InputStreamReader(gzip));
// } else if(file.endsWith(".bz2")) {
// CBZip2InputStream bzip2 = new CBZip2InputStream(new FileInputStream(file));
// return new BufferedReader(new InputStreamReader(bzip2));
// } else if(file.equals("-")) {
// return new BufferedReader(new InputStreamReader(System.in));
// }else
// return new BufferedReader(new FileReader(file));
// }
// }
// Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/SingleFastQReader.java
import be.ugent.intec.halvade.uploader.Logger;
import static be.ugent.intec.halvade.uploader.input.BaseFileReader.getReader;
import java.io.BufferedReader;
import java.io.IOException;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package be.ugent.intec.halvade.uploader.input;
/**
*
* @author ddecap
*/
public class SingleFastQReader extends BaseFileReader {
protected BufferedReader readerA;
protected ReadBlock block;
protected int readsFactor;
public SingleFastQReader(boolean fromHDFS, String fileA, boolean interleaved) throws IOException {
super(true);
readerA = getReader(fromHDFS, fileA);
this.isInterleaved = interleaved;
if(isInterleaved)
readsFactor = 2;
else
readsFactor = 1;
toStr = fileA; | Logger.DEBUG("Single: " + toStr + (isInterleaved ? " interleaved" : "")); |
biointec/halvade | halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/PairedFastQReader.java | // Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/Logger.java
// public class Logger {
// /*
// * levels of debugging
// * 0: INFO
// * 1: DEBUG
// * 2: EXCEPTION
// * 3:ALL
// */
// private static int LEVEL = 0;
// private static final int EXCEPTION = 2;
// private static final int DEBUG = 1;
// private static final int INFO = 0;
//
//
// // TODO use configuration set LEVEL
// public static void SETLEVEL(int NEWLEVEL) {
// LEVEL = NEWLEVEL;
// }
//
// public static void EXCEPTION(Exception ex){
// System.err.println("[EXCEPTION] " + ex.getLocalizedMessage());
// ex.printStackTrace();
// }
//
// public static void THROWABLE(Throwable ex){
// System.err.println("[EXCEPTION] " + ex.getLocalizedMessage());
// ex.printStackTrace();
// }
//
// public static void DEBUG(String message) {
// if(LEVEL >= DEBUG)
// System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message);
// }
//
// public static void INFO(String message) {
// if(LEVEL >= INFO)
// System.err.println("[INFO] " + message);
// }
//
// public static void DEBUG(String message, int level) {
// if(LEVEL >= level)
// System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message);
// }
// }
| import be.ugent.intec.halvade.uploader.Logger;
import java.io.BufferedReader;
import java.io.IOException; | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package be.ugent.intec.halvade.uploader.input;
/**
*
* @author ddecap
*/
public class PairedFastQReader extends BaseFileReader {
protected BufferedReader readerA, readerB;
protected ReadBlock block;
public PairedFastQReader(boolean fromHDFS, String fileA, String fileB) throws IOException {
super(true);
readerA = getReader(fromHDFS, fileA);
readerB = getReader(fromHDFS, fileB);
toStr = fileA.substring(fileA.lastIndexOf("/")+1) + " & " + fileB.substring(fileB.lastIndexOf("/")+1); | // Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/Logger.java
// public class Logger {
// /*
// * levels of debugging
// * 0: INFO
// * 1: DEBUG
// * 2: EXCEPTION
// * 3:ALL
// */
// private static int LEVEL = 0;
// private static final int EXCEPTION = 2;
// private static final int DEBUG = 1;
// private static final int INFO = 0;
//
//
// // TODO use configuration set LEVEL
// public static void SETLEVEL(int NEWLEVEL) {
// LEVEL = NEWLEVEL;
// }
//
// public static void EXCEPTION(Exception ex){
// System.err.println("[EXCEPTION] " + ex.getLocalizedMessage());
// ex.printStackTrace();
// }
//
// public static void THROWABLE(Throwable ex){
// System.err.println("[EXCEPTION] " + ex.getLocalizedMessage());
// ex.printStackTrace();
// }
//
// public static void DEBUG(String message) {
// if(LEVEL >= DEBUG)
// System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message);
// }
//
// public static void INFO(String message) {
// if(LEVEL >= INFO)
// System.err.println("[INFO] " + message);
// }
//
// public static void DEBUG(String message, int level) {
// if(LEVEL >= level)
// System.err.println("[" + Timer.getGlobalTime() + " - DEBUG] " + message);
// }
// }
// Path: halvade_upload_tool/src/be/ugent/intec/halvade/uploader/input/PairedFastQReader.java
import be.ugent.intec.halvade.uploader.Logger;
import java.io.BufferedReader;
import java.io.IOException;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package be.ugent.intec.halvade.uploader.input;
/**
*
* @author ddecap
*/
public class PairedFastQReader extends BaseFileReader {
protected BufferedReader readerA, readerB;
protected ReadBlock block;
public PairedFastQReader(boolean fromHDFS, String fileA, String fileB) throws IOException {
super(true);
readerA = getReader(fromHDFS, fileA);
readerB = getReader(fromHDFS, fileB);
toStr = fileA.substring(fileA.lastIndexOf("/")+1) + " & " + fileB.substring(fileB.lastIndexOf("/")+1); | Logger.DEBUG("Paired: " + toStr); |
biointec/halvade | halvade/src/be/ugent/intec/halvade/hadoop/mapreduce/BWAMemMapper.java | // Path: halvade/src/be/ugent/intec/halvade/tools/BWAMemInstance.java
// public class BWAMemInstance extends AlignerInstance {
//
// private static BWAMemInstance instance;
// private ProcessBuilderWrapper pbw;
// private SAMStreamHandler ssh;
// private String taskId;
// /**
// *
// * This BWA instance runs BWA from stdin (custom provided BWA is needed)
// */
// private BWAMemInstance(Context context, String bin, int task) throws IOException, URISyntaxException {
// super(context, bin, task);
// taskId = context.getTaskAttemptID().toString();
// taskId = taskId.substring(taskId.indexOf("m_"));
// ref = HalvadeFileUtils.downloadBWAIndex(context);
// System.out.println("reference: " + ref);
// }
//
// public int feedLine(String line) throws IOException {
// return feedLine(line, pbw);
// }
//
// @Override
// protected void startAligner(Mapper.Context context) throws IOException, InterruptedException {
// // make command
// String customArgs = HalvadeConf.getCustomArgs(context.getConfiguration(), "bwa", "mem");
// String[] command = CommandGenerator.bwaMem(bin, ref, null, null, isPaired, true, threads, customArgs);
// pbw = new ProcessBuilderWrapper(command, bin);
// // run command
// // needs to be streamed to output otherwise the process blocks ...
// pbw.startProcess(null, System.err);
// // check if alive.
// if(!pbw.isAlive())
// throw new ProcessException("BWA mem", pbw.getExitState());
// pbw.getSTDINWriter();
// // make a SAMstream handler
// ssh = new SAMStreamHandler(instance, context, false);
// ssh.start();
// }
//
// /**
// *
// * @return 1 is running, 0 is completed, -1 is error
// */
// @Override
// public int getState() {
// return pbw.getState();
// }
//
// @Override
// public void closeAligner() throws InterruptedException {
// try {
// // close the input stream
// pbw.getSTDINWriter().flush();
// pbw.getSTDINWriter().close();
// } catch (IOException ex) {
// Logger.EXCEPTION(ex);
// }
//
// int error = pbw.waitForCompletion();
// context.getCounter(HalvadeCounters.TIME_BWA_MEM).increment(pbw.getExecutionTime());
// if(error != 0)
// throw new ProcessException("BWA mem", error);
// ssh.join();
// instance = null;
// }
//
// static public BWAMemInstance getBWAInstance(Mapper.Context context, String bin, int task) throws IOException, InterruptedException, URISyntaxException {
// if(instance == null) {
// instance = new BWAMemInstance(context, bin, task);
// instance.startAligner(context);
// }
// BWAMemInstance.context = context;
// return instance;
// }
//
//
// @Override
// public InputStream getSTDOUTStream() {
// return pbw.getSTDOUTStream();
// }
//
// @Override
// public void flushStream() {
// try {
// // close the input stream
// pbw.getSTDINWriter().flush();
// } catch (IOException ex) {
// Logger.EXCEPTION(ex);
// }
// }
// }
| import be.ugent.intec.halvade.hadoop.datatypes.ChromosomeRegion;
import java.io.IOException;
import org.apache.hadoop.io.Text;
import be.ugent.intec.halvade.tools.BWAMemInstance;
import be.ugent.intec.halvade.utils.Logger;
import org.seqdoop.hadoop_bam.SAMRecordWritable;
import java.net.URISyntaxException;
import org.apache.hadoop.io.LongWritable; | /*
* Copyright (C) 2014 ddecap
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package be.ugent.intec.halvade.hadoop.mapreduce;
/**
*
* @author ddecap
*/
public class BWAMemMapper extends HalvadeMapper<ChromosomeRegion, SAMRecordWritable> {
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
super.map(key, value, context); | // Path: halvade/src/be/ugent/intec/halvade/tools/BWAMemInstance.java
// public class BWAMemInstance extends AlignerInstance {
//
// private static BWAMemInstance instance;
// private ProcessBuilderWrapper pbw;
// private SAMStreamHandler ssh;
// private String taskId;
// /**
// *
// * This BWA instance runs BWA from stdin (custom provided BWA is needed)
// */
// private BWAMemInstance(Context context, String bin, int task) throws IOException, URISyntaxException {
// super(context, bin, task);
// taskId = context.getTaskAttemptID().toString();
// taskId = taskId.substring(taskId.indexOf("m_"));
// ref = HalvadeFileUtils.downloadBWAIndex(context);
// System.out.println("reference: " + ref);
// }
//
// public int feedLine(String line) throws IOException {
// return feedLine(line, pbw);
// }
//
// @Override
// protected void startAligner(Mapper.Context context) throws IOException, InterruptedException {
// // make command
// String customArgs = HalvadeConf.getCustomArgs(context.getConfiguration(), "bwa", "mem");
// String[] command = CommandGenerator.bwaMem(bin, ref, null, null, isPaired, true, threads, customArgs);
// pbw = new ProcessBuilderWrapper(command, bin);
// // run command
// // needs to be streamed to output otherwise the process blocks ...
// pbw.startProcess(null, System.err);
// // check if alive.
// if(!pbw.isAlive())
// throw new ProcessException("BWA mem", pbw.getExitState());
// pbw.getSTDINWriter();
// // make a SAMstream handler
// ssh = new SAMStreamHandler(instance, context, false);
// ssh.start();
// }
//
// /**
// *
// * @return 1 is running, 0 is completed, -1 is error
// */
// @Override
// public int getState() {
// return pbw.getState();
// }
//
// @Override
// public void closeAligner() throws InterruptedException {
// try {
// // close the input stream
// pbw.getSTDINWriter().flush();
// pbw.getSTDINWriter().close();
// } catch (IOException ex) {
// Logger.EXCEPTION(ex);
// }
//
// int error = pbw.waitForCompletion();
// context.getCounter(HalvadeCounters.TIME_BWA_MEM).increment(pbw.getExecutionTime());
// if(error != 0)
// throw new ProcessException("BWA mem", error);
// ssh.join();
// instance = null;
// }
//
// static public BWAMemInstance getBWAInstance(Mapper.Context context, String bin, int task) throws IOException, InterruptedException, URISyntaxException {
// if(instance == null) {
// instance = new BWAMemInstance(context, bin, task);
// instance.startAligner(context);
// }
// BWAMemInstance.context = context;
// return instance;
// }
//
//
// @Override
// public InputStream getSTDOUTStream() {
// return pbw.getSTDOUTStream();
// }
//
// @Override
// public void flushStream() {
// try {
// // close the input stream
// pbw.getSTDINWriter().flush();
// } catch (IOException ex) {
// Logger.EXCEPTION(ex);
// }
// }
// }
// Path: halvade/src/be/ugent/intec/halvade/hadoop/mapreduce/BWAMemMapper.java
import be.ugent.intec.halvade.hadoop.datatypes.ChromosomeRegion;
import java.io.IOException;
import org.apache.hadoop.io.Text;
import be.ugent.intec.halvade.tools.BWAMemInstance;
import be.ugent.intec.halvade.utils.Logger;
import org.seqdoop.hadoop_bam.SAMRecordWritable;
import java.net.URISyntaxException;
import org.apache.hadoop.io.LongWritable;
/*
* Copyright (C) 2014 ddecap
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package be.ugent.intec.halvade.hadoop.mapreduce;
/**
*
* @author ddecap
*/
public class BWAMemMapper extends HalvadeMapper<ChromosomeRegion, SAMRecordWritable> {
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
super.map(key, value, context); | ((BWAMemInstance)instance).feedLine(value.toString()); |
danisola/restify | url/src/main/java/com/danisola/restify/url/ParsedUrl.java | // Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkState(boolean expression, String errorMessageFormat, Object ... args) {
// if (!expression) {
// throw new IllegalStateException(String.format(errorMessageFormat, args));
// }
// }
| import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static com.danisola.restify.url.preconditions.Preconditions.checkState; |
List<NameValuePair> getParameters() {
return parameters;
}
static ParsedUrl parseUrl(String url) {
String path, queryString;
int questionIndex = url.indexOf("?");
if (questionIndex >= 0) {
path = url.substring(0, questionIndex);
queryString = url.substring(questionIndex + 1);
} else {
path = url;
queryString = null;
}
return new ParsedUrl(path, parseParams(queryString));
}
static List<NameValuePair> parseParams(String query) {
if (query == null || query.isEmpty()) {
return Collections.emptyList();
}
List<NameValuePair> pairs = new ArrayList<>();
int startIndex = 0;
int queryLength = query.length();
while (startIndex < queryLength) {
int equalsIndex = query.indexOf("=", startIndex); | // Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkState(boolean expression, String errorMessageFormat, Object ... args) {
// if (!expression) {
// throw new IllegalStateException(String.format(errorMessageFormat, args));
// }
// }
// Path: url/src/main/java/com/danisola/restify/url/ParsedUrl.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static com.danisola.restify.url.preconditions.Preconditions.checkState;
List<NameValuePair> getParameters() {
return parameters;
}
static ParsedUrl parseUrl(String url) {
String path, queryString;
int questionIndex = url.indexOf("?");
if (questionIndex >= 0) {
path = url.substring(0, questionIndex);
queryString = url.substring(questionIndex + 1);
} else {
path = url;
queryString = null;
}
return new ParsedUrl(path, parseParams(queryString));
}
static List<NameValuePair> parseParams(String query) {
if (query == null || query.isEmpty()) {
return Collections.emptyList();
}
List<NameValuePair> pairs = new ArrayList<>();
int startIndex = 0;
int queryLength = query.length();
while (startIndex < queryLength) {
int equalsIndex = query.indexOf("=", startIndex); | checkState(equalsIndex > 0, "Parameters are not well formatted: %s", query); |
danisola/restify | servlet/src/test/java/com/danisola/restify/servlet/utils/TestCallback.java | // Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// public class RestUrl {
//
// final String errorMessage;
// final VarType[] types;
// final Object[] values;
//
// static RestUrl invalidRestUrl(String errorMsg) {
// return new RestUrl(null, null, errorMsg);
// }
//
// static RestUrl restUrl(VarType[] types, Object[] values) {
// return new RestUrl(types, values, null);
// }
//
// private RestUrl(VarType[] types, Object[] values, String errorMsg) {
// this.types = types;
// this.values = values;
// this.errorMessage = errorMsg;
// }
//
// /**
// * Returns true if it matches the pattern and variable types of the {@link RestParser} that has generated this
// * {@link RestUrl}.
// */
// public boolean isValid() {
// return errorMessage == null;
// }
//
// /**
// * <p>If {@link #isValid()} is false, returns a message explaining why the parsed URL did not match the pattern
// * and variables of the {@link RestParser} that has generated this {@link RestUrl}.</p>
// *
// * <p>If {@link #isValid()} is true, returns null</p>
// */
// public String errorMessage() {
// return errorMessage;
// }
//
// /**
// * Returns the given variable with the specified return type. The variable id and type must match the declared
// * ones in the {@link RestParser} that has generated this {@link RestUrl}.
// *
// * <p>This method throws exceptions to enforce a correct usage of the API.</p>
// *
// * @throws IllegalArgumentException if variableId is null, empty or not defined in the {@link RestParser}
// * @throws IllegalStateException if the URL is invalid ({@link #isValid()} is false)
// * @throws ClassCastException if the returned variable has not the same type as the declared variable in {@link RestParser}
// */
// public <T> T variable(String variableId) {
// checkArgumentNotNullOrEmpty(variableId);
// checkState(isValid(), "Variables are not accessible for invalid URLs");
//
// for (int i = 0; i < types.length; i++) {
// if (types[i].getId().equals(variableId)) {
// return (T) values[i];
// }
// }
// throw new IllegalArgumentException("Variable id '" + variableId + "' is not declared in the pattern");
// }
// }
| import com.danisola.restify.url.RestUrl; | package com.danisola.restify.servlet.utils;
public interface TestCallback {
void onMethodCalled(Method method);
| // Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// public class RestUrl {
//
// final String errorMessage;
// final VarType[] types;
// final Object[] values;
//
// static RestUrl invalidRestUrl(String errorMsg) {
// return new RestUrl(null, null, errorMsg);
// }
//
// static RestUrl restUrl(VarType[] types, Object[] values) {
// return new RestUrl(types, values, null);
// }
//
// private RestUrl(VarType[] types, Object[] values, String errorMsg) {
// this.types = types;
// this.values = values;
// this.errorMessage = errorMsg;
// }
//
// /**
// * Returns true if it matches the pattern and variable types of the {@link RestParser} that has generated this
// * {@link RestUrl}.
// */
// public boolean isValid() {
// return errorMessage == null;
// }
//
// /**
// * <p>If {@link #isValid()} is false, returns a message explaining why the parsed URL did not match the pattern
// * and variables of the {@link RestParser} that has generated this {@link RestUrl}.</p>
// *
// * <p>If {@link #isValid()} is true, returns null</p>
// */
// public String errorMessage() {
// return errorMessage;
// }
//
// /**
// * Returns the given variable with the specified return type. The variable id and type must match the declared
// * ones in the {@link RestParser} that has generated this {@link RestUrl}.
// *
// * <p>This method throws exceptions to enforce a correct usage of the API.</p>
// *
// * @throws IllegalArgumentException if variableId is null, empty or not defined in the {@link RestParser}
// * @throws IllegalStateException if the URL is invalid ({@link #isValid()} is false)
// * @throws ClassCastException if the returned variable has not the same type as the declared variable in {@link RestParser}
// */
// public <T> T variable(String variableId) {
// checkArgumentNotNullOrEmpty(variableId);
// checkState(isValid(), "Variables are not accessible for invalid URLs");
//
// for (int i = 0; i < types.length; i++) {
// if (types[i].getId().equals(variableId)) {
// return (T) values[i];
// }
// }
// throw new IllegalArgumentException("Variable id '" + variableId + "' is not declared in the pattern");
// }
// }
// Path: servlet/src/test/java/com/danisola/restify/servlet/utils/TestCallback.java
import com.danisola.restify.url.RestUrl;
package com.danisola.restify.servlet.utils;
public interface TestCallback {
void onMethodCalled(Method method);
| void onInvalidUrl(RestUrl url); |
danisola/restify | url/src/main/java/com/danisola/restify/url/RestParser.java | // Path: url/src/main/java/com/danisola/restify/url/types/Opt.java
// public class Opt<T> implements VarType<T> {
//
// public static <T> Opt<T> opt(VarType<T> varType) {
// return new Opt<>(varType);
// }
//
// private final VarType<T> varType;
//
// private Opt(VarType<T> varType) {
// this.varType = varType;
// }
//
// @Override
// public String getId() {
// return varType.getId();
// }
//
// @Override
// public String getVarPattern() {
// return varType.getVarPattern();
// }
//
// @Override
// public T convert(String value) throws Exception {
// if ("".equals(value)) {
// return null;
// }
// return varType.convert(value);
// }
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/ParsedUrl.java
// static List<NameValuePair> parseParams(String query) {
// if (query == null || query.isEmpty()) {
// return Collections.emptyList();
// }
//
// List<NameValuePair> pairs = new ArrayList<>();
// int startIndex = 0;
// int queryLength = query.length();
// while (startIndex < queryLength) {
// int equalsIndex = query.indexOf("=", startIndex);
// checkState(equalsIndex > 0, "Parameters are not well formatted: %s", query);
// String paramName = query.substring(startIndex, equalsIndex);
// String paramValue;
// int andIndex = query.indexOf("&", equalsIndex);
// if (andIndex > equalsIndex) {
// paramValue = query.substring(equalsIndex + 1, andIndex);
// startIndex = andIndex + 1;
// } else {
// paramValue = query.substring(equalsIndex + 1);
// startIndex = queryLength;
// }
// pairs.add(new NameValuePair(paramName, paramValue));
// }
// return pairs;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// static RestUrl invalidRestUrl(String errorMsg) {
// return new RestUrl(null, null, errorMsg);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// static RestUrl restUrl(VarType[] types, Object[] values) {
// return new RestUrl(types, values, null);
// }
| import com.danisola.restify.url.types.Opt;
import com.danisola.restify.url.types.VarType;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.danisola.restify.url.ParsedUrl.parseParams;
import static com.danisola.restify.url.RestUrl.invalidRestUrl;
import static com.danisola.restify.url.RestUrl.restUrl; | package com.danisola.restify.url;
/**
* A URL parser that produces {@link ParsedUrl}. It does not throw any exceptions in case the parsed URLs are found to
* be incorrect, but the resulting {@link RestUrl} will be invalid.
*
* <p>Instances of this class are immutable and thus thread-safe.</p>
*/
public class RestParser {
private final Pattern pathPattern; | // Path: url/src/main/java/com/danisola/restify/url/types/Opt.java
// public class Opt<T> implements VarType<T> {
//
// public static <T> Opt<T> opt(VarType<T> varType) {
// return new Opt<>(varType);
// }
//
// private final VarType<T> varType;
//
// private Opt(VarType<T> varType) {
// this.varType = varType;
// }
//
// @Override
// public String getId() {
// return varType.getId();
// }
//
// @Override
// public String getVarPattern() {
// return varType.getVarPattern();
// }
//
// @Override
// public T convert(String value) throws Exception {
// if ("".equals(value)) {
// return null;
// }
// return varType.convert(value);
// }
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/ParsedUrl.java
// static List<NameValuePair> parseParams(String query) {
// if (query == null || query.isEmpty()) {
// return Collections.emptyList();
// }
//
// List<NameValuePair> pairs = new ArrayList<>();
// int startIndex = 0;
// int queryLength = query.length();
// while (startIndex < queryLength) {
// int equalsIndex = query.indexOf("=", startIndex);
// checkState(equalsIndex > 0, "Parameters are not well formatted: %s", query);
// String paramName = query.substring(startIndex, equalsIndex);
// String paramValue;
// int andIndex = query.indexOf("&", equalsIndex);
// if (andIndex > equalsIndex) {
// paramValue = query.substring(equalsIndex + 1, andIndex);
// startIndex = andIndex + 1;
// } else {
// paramValue = query.substring(equalsIndex + 1);
// startIndex = queryLength;
// }
// pairs.add(new NameValuePair(paramName, paramValue));
// }
// return pairs;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// static RestUrl invalidRestUrl(String errorMsg) {
// return new RestUrl(null, null, errorMsg);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// static RestUrl restUrl(VarType[] types, Object[] values) {
// return new RestUrl(types, values, null);
// }
// Path: url/src/main/java/com/danisola/restify/url/RestParser.java
import com.danisola.restify.url.types.Opt;
import com.danisola.restify.url.types.VarType;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.danisola.restify.url.ParsedUrl.parseParams;
import static com.danisola.restify.url.RestUrl.invalidRestUrl;
import static com.danisola.restify.url.RestUrl.restUrl;
package com.danisola.restify.url;
/**
* A URL parser that produces {@link ParsedUrl}. It does not throw any exceptions in case the parsed URLs are found to
* be incorrect, but the resulting {@link RestUrl} will be invalid.
*
* <p>Instances of this class are immutable and thus thread-safe.</p>
*/
public class RestParser {
private final Pattern pathPattern; | private final VarType[] pathTypes; |
danisola/restify | url/src/main/java/com/danisola/restify/url/RestParser.java | // Path: url/src/main/java/com/danisola/restify/url/types/Opt.java
// public class Opt<T> implements VarType<T> {
//
// public static <T> Opt<T> opt(VarType<T> varType) {
// return new Opt<>(varType);
// }
//
// private final VarType<T> varType;
//
// private Opt(VarType<T> varType) {
// this.varType = varType;
// }
//
// @Override
// public String getId() {
// return varType.getId();
// }
//
// @Override
// public String getVarPattern() {
// return varType.getVarPattern();
// }
//
// @Override
// public T convert(String value) throws Exception {
// if ("".equals(value)) {
// return null;
// }
// return varType.convert(value);
// }
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/ParsedUrl.java
// static List<NameValuePair> parseParams(String query) {
// if (query == null || query.isEmpty()) {
// return Collections.emptyList();
// }
//
// List<NameValuePair> pairs = new ArrayList<>();
// int startIndex = 0;
// int queryLength = query.length();
// while (startIndex < queryLength) {
// int equalsIndex = query.indexOf("=", startIndex);
// checkState(equalsIndex > 0, "Parameters are not well formatted: %s", query);
// String paramName = query.substring(startIndex, equalsIndex);
// String paramValue;
// int andIndex = query.indexOf("&", equalsIndex);
// if (andIndex > equalsIndex) {
// paramValue = query.substring(equalsIndex + 1, andIndex);
// startIndex = andIndex + 1;
// } else {
// paramValue = query.substring(equalsIndex + 1);
// startIndex = queryLength;
// }
// pairs.add(new NameValuePair(paramName, paramValue));
// }
// return pairs;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// static RestUrl invalidRestUrl(String errorMsg) {
// return new RestUrl(null, null, errorMsg);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// static RestUrl restUrl(VarType[] types, Object[] values) {
// return new RestUrl(types, values, null);
// }
| import com.danisola.restify.url.types.Opt;
import com.danisola.restify.url.types.VarType;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.danisola.restify.url.ParsedUrl.parseParams;
import static com.danisola.restify.url.RestUrl.invalidRestUrl;
import static com.danisola.restify.url.RestUrl.restUrl; | package com.danisola.restify.url;
/**
* A URL parser that produces {@link ParsedUrl}. It does not throw any exceptions in case the parsed URLs are found to
* be incorrect, but the resulting {@link RestUrl} will be invalid.
*
* <p>Instances of this class are immutable and thus thread-safe.</p>
*/
public class RestParser {
private final Pattern pathPattern;
private final VarType[] pathTypes;
private final ParamVar[] paramVars;
private final int numVars;
RestParser(Pattern pathPattern, VarType[] pathTypes, ParamVar[] paramVars, int numVars) {
this.pathPattern = pathPattern;
this.pathTypes = pathTypes;
this.paramVars = paramVars;
this.numVars = numVars;
}
/**
* Parses the given fully qualified URL.
*
* @return the {@link RestUrl} that represents the given URL.
*/
public RestUrl parse(String url) {
if (url == null) { | // Path: url/src/main/java/com/danisola/restify/url/types/Opt.java
// public class Opt<T> implements VarType<T> {
//
// public static <T> Opt<T> opt(VarType<T> varType) {
// return new Opt<>(varType);
// }
//
// private final VarType<T> varType;
//
// private Opt(VarType<T> varType) {
// this.varType = varType;
// }
//
// @Override
// public String getId() {
// return varType.getId();
// }
//
// @Override
// public String getVarPattern() {
// return varType.getVarPattern();
// }
//
// @Override
// public T convert(String value) throws Exception {
// if ("".equals(value)) {
// return null;
// }
// return varType.convert(value);
// }
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/ParsedUrl.java
// static List<NameValuePair> parseParams(String query) {
// if (query == null || query.isEmpty()) {
// return Collections.emptyList();
// }
//
// List<NameValuePair> pairs = new ArrayList<>();
// int startIndex = 0;
// int queryLength = query.length();
// while (startIndex < queryLength) {
// int equalsIndex = query.indexOf("=", startIndex);
// checkState(equalsIndex > 0, "Parameters are not well formatted: %s", query);
// String paramName = query.substring(startIndex, equalsIndex);
// String paramValue;
// int andIndex = query.indexOf("&", equalsIndex);
// if (andIndex > equalsIndex) {
// paramValue = query.substring(equalsIndex + 1, andIndex);
// startIndex = andIndex + 1;
// } else {
// paramValue = query.substring(equalsIndex + 1);
// startIndex = queryLength;
// }
// pairs.add(new NameValuePair(paramName, paramValue));
// }
// return pairs;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// static RestUrl invalidRestUrl(String errorMsg) {
// return new RestUrl(null, null, errorMsg);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// static RestUrl restUrl(VarType[] types, Object[] values) {
// return new RestUrl(types, values, null);
// }
// Path: url/src/main/java/com/danisola/restify/url/RestParser.java
import com.danisola.restify.url.types.Opt;
import com.danisola.restify.url.types.VarType;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.danisola.restify.url.ParsedUrl.parseParams;
import static com.danisola.restify.url.RestUrl.invalidRestUrl;
import static com.danisola.restify.url.RestUrl.restUrl;
package com.danisola.restify.url;
/**
* A URL parser that produces {@link ParsedUrl}. It does not throw any exceptions in case the parsed URLs are found to
* be incorrect, but the resulting {@link RestUrl} will be invalid.
*
* <p>Instances of this class are immutable and thus thread-safe.</p>
*/
public class RestParser {
private final Pattern pathPattern;
private final VarType[] pathTypes;
private final ParamVar[] paramVars;
private final int numVars;
RestParser(Pattern pathPattern, VarType[] pathTypes, ParamVar[] paramVars, int numVars) {
this.pathPattern = pathPattern;
this.pathTypes = pathTypes;
this.paramVars = paramVars;
this.numVars = numVars;
}
/**
* Parses the given fully qualified URL.
*
* @return the {@link RestUrl} that represents the given URL.
*/
public RestUrl parse(String url) {
if (url == null) { | return RestUrl.invalidRestUrl("Url is null"); |
danisola/restify | url/src/main/java/com/danisola/restify/url/RestParser.java | // Path: url/src/main/java/com/danisola/restify/url/types/Opt.java
// public class Opt<T> implements VarType<T> {
//
// public static <T> Opt<T> opt(VarType<T> varType) {
// return new Opt<>(varType);
// }
//
// private final VarType<T> varType;
//
// private Opt(VarType<T> varType) {
// this.varType = varType;
// }
//
// @Override
// public String getId() {
// return varType.getId();
// }
//
// @Override
// public String getVarPattern() {
// return varType.getVarPattern();
// }
//
// @Override
// public T convert(String value) throws Exception {
// if ("".equals(value)) {
// return null;
// }
// return varType.convert(value);
// }
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/ParsedUrl.java
// static List<NameValuePair> parseParams(String query) {
// if (query == null || query.isEmpty()) {
// return Collections.emptyList();
// }
//
// List<NameValuePair> pairs = new ArrayList<>();
// int startIndex = 0;
// int queryLength = query.length();
// while (startIndex < queryLength) {
// int equalsIndex = query.indexOf("=", startIndex);
// checkState(equalsIndex > 0, "Parameters are not well formatted: %s", query);
// String paramName = query.substring(startIndex, equalsIndex);
// String paramValue;
// int andIndex = query.indexOf("&", equalsIndex);
// if (andIndex > equalsIndex) {
// paramValue = query.substring(equalsIndex + 1, andIndex);
// startIndex = andIndex + 1;
// } else {
// paramValue = query.substring(equalsIndex + 1);
// startIndex = queryLength;
// }
// pairs.add(new NameValuePair(paramName, paramValue));
// }
// return pairs;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// static RestUrl invalidRestUrl(String errorMsg) {
// return new RestUrl(null, null, errorMsg);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// static RestUrl restUrl(VarType[] types, Object[] values) {
// return new RestUrl(types, values, null);
// }
| import com.danisola.restify.url.types.Opt;
import com.danisola.restify.url.types.VarType;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.danisola.restify.url.ParsedUrl.parseParams;
import static com.danisola.restify.url.RestUrl.invalidRestUrl;
import static com.danisola.restify.url.RestUrl.restUrl; |
try {
return parse(new URL(url));
} catch (MalformedURLException e) {
return RestUrl.invalidRestUrl("Url is malformed");
}
}
/**
* Parses the given URL.
*
* @return the {@link RestUrl} that represents the given URL.
*/
public RestUrl parse(URL url) {
if (url == null) {
return RestUrl.invalidRestUrl("Url is null");
}
return parse(url.getPath(), url.getQuery());
}
/**
* Parses the given path and query.
*
* @return the {@link RestUrl} that represents the given URL.
*/
public RestUrl parse(String path, String queryString) {
if (path == null) {
return RestUrl.invalidRestUrl("Url is null");
}
| // Path: url/src/main/java/com/danisola/restify/url/types/Opt.java
// public class Opt<T> implements VarType<T> {
//
// public static <T> Opt<T> opt(VarType<T> varType) {
// return new Opt<>(varType);
// }
//
// private final VarType<T> varType;
//
// private Opt(VarType<T> varType) {
// this.varType = varType;
// }
//
// @Override
// public String getId() {
// return varType.getId();
// }
//
// @Override
// public String getVarPattern() {
// return varType.getVarPattern();
// }
//
// @Override
// public T convert(String value) throws Exception {
// if ("".equals(value)) {
// return null;
// }
// return varType.convert(value);
// }
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/ParsedUrl.java
// static List<NameValuePair> parseParams(String query) {
// if (query == null || query.isEmpty()) {
// return Collections.emptyList();
// }
//
// List<NameValuePair> pairs = new ArrayList<>();
// int startIndex = 0;
// int queryLength = query.length();
// while (startIndex < queryLength) {
// int equalsIndex = query.indexOf("=", startIndex);
// checkState(equalsIndex > 0, "Parameters are not well formatted: %s", query);
// String paramName = query.substring(startIndex, equalsIndex);
// String paramValue;
// int andIndex = query.indexOf("&", equalsIndex);
// if (andIndex > equalsIndex) {
// paramValue = query.substring(equalsIndex + 1, andIndex);
// startIndex = andIndex + 1;
// } else {
// paramValue = query.substring(equalsIndex + 1);
// startIndex = queryLength;
// }
// pairs.add(new NameValuePair(paramName, paramValue));
// }
// return pairs;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// static RestUrl invalidRestUrl(String errorMsg) {
// return new RestUrl(null, null, errorMsg);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// static RestUrl restUrl(VarType[] types, Object[] values) {
// return new RestUrl(types, values, null);
// }
// Path: url/src/main/java/com/danisola/restify/url/RestParser.java
import com.danisola.restify.url.types.Opt;
import com.danisola.restify.url.types.VarType;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.danisola.restify.url.ParsedUrl.parseParams;
import static com.danisola.restify.url.RestUrl.invalidRestUrl;
import static com.danisola.restify.url.RestUrl.restUrl;
try {
return parse(new URL(url));
} catch (MalformedURLException e) {
return RestUrl.invalidRestUrl("Url is malformed");
}
}
/**
* Parses the given URL.
*
* @return the {@link RestUrl} that represents the given URL.
*/
public RestUrl parse(URL url) {
if (url == null) {
return RestUrl.invalidRestUrl("Url is null");
}
return parse(url.getPath(), url.getQuery());
}
/**
* Parses the given path and query.
*
* @return the {@link RestUrl} that represents the given URL.
*/
public RestUrl parse(String path, String queryString) {
if (path == null) {
return RestUrl.invalidRestUrl("Url is null");
}
| RestUrl restUrl = RestUrl.restUrl(new VarType[numVars], new Object[numVars]); |
danisola/restify | url/src/main/java/com/danisola/restify/url/RestParser.java | // Path: url/src/main/java/com/danisola/restify/url/types/Opt.java
// public class Opt<T> implements VarType<T> {
//
// public static <T> Opt<T> opt(VarType<T> varType) {
// return new Opt<>(varType);
// }
//
// private final VarType<T> varType;
//
// private Opt(VarType<T> varType) {
// this.varType = varType;
// }
//
// @Override
// public String getId() {
// return varType.getId();
// }
//
// @Override
// public String getVarPattern() {
// return varType.getVarPattern();
// }
//
// @Override
// public T convert(String value) throws Exception {
// if ("".equals(value)) {
// return null;
// }
// return varType.convert(value);
// }
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/ParsedUrl.java
// static List<NameValuePair> parseParams(String query) {
// if (query == null || query.isEmpty()) {
// return Collections.emptyList();
// }
//
// List<NameValuePair> pairs = new ArrayList<>();
// int startIndex = 0;
// int queryLength = query.length();
// while (startIndex < queryLength) {
// int equalsIndex = query.indexOf("=", startIndex);
// checkState(equalsIndex > 0, "Parameters are not well formatted: %s", query);
// String paramName = query.substring(startIndex, equalsIndex);
// String paramValue;
// int andIndex = query.indexOf("&", equalsIndex);
// if (andIndex > equalsIndex) {
// paramValue = query.substring(equalsIndex + 1, andIndex);
// startIndex = andIndex + 1;
// } else {
// paramValue = query.substring(equalsIndex + 1);
// startIndex = queryLength;
// }
// pairs.add(new NameValuePair(paramName, paramValue));
// }
// return pairs;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// static RestUrl invalidRestUrl(String errorMsg) {
// return new RestUrl(null, null, errorMsg);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// static RestUrl restUrl(VarType[] types, Object[] values) {
// return new RestUrl(types, values, null);
// }
| import com.danisola.restify.url.types.Opt;
import com.danisola.restify.url.types.VarType;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.danisola.restify.url.ParsedUrl.parseParams;
import static com.danisola.restify.url.RestUrl.invalidRestUrl;
import static com.danisola.restify.url.RestUrl.restUrl; | }
/**
* Parses the given path and query.
*
* @return the {@link RestUrl} that represents the given URL.
*/
public RestUrl parse(String path, String queryString) {
if (path == null) {
return RestUrl.invalidRestUrl("Url is null");
}
RestUrl restUrl = RestUrl.restUrl(new VarType[numVars], new Object[numVars]);
int varIndex = 0;
// Processing path variables
Matcher pathMatcher = pathPattern.matcher(path);
if (!pathMatcher.matches()) {
return RestUrl.invalidRestUrl("Path '" + path + "' does not match the pattern '" + pathPattern + "'");
}
for (VarType type : pathTypes) {
try {
varIndex = extract(pathMatcher, type, varIndex, restUrl);
} catch (Exception ex) {
return RestUrl.invalidRestUrl("Invalid value for variable '" + type.getId() + "': " + pathMatcher.group(type.getId()));
}
}
// Processing param variables | // Path: url/src/main/java/com/danisola/restify/url/types/Opt.java
// public class Opt<T> implements VarType<T> {
//
// public static <T> Opt<T> opt(VarType<T> varType) {
// return new Opt<>(varType);
// }
//
// private final VarType<T> varType;
//
// private Opt(VarType<T> varType) {
// this.varType = varType;
// }
//
// @Override
// public String getId() {
// return varType.getId();
// }
//
// @Override
// public String getVarPattern() {
// return varType.getVarPattern();
// }
//
// @Override
// public T convert(String value) throws Exception {
// if ("".equals(value)) {
// return null;
// }
// return varType.convert(value);
// }
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/ParsedUrl.java
// static List<NameValuePair> parseParams(String query) {
// if (query == null || query.isEmpty()) {
// return Collections.emptyList();
// }
//
// List<NameValuePair> pairs = new ArrayList<>();
// int startIndex = 0;
// int queryLength = query.length();
// while (startIndex < queryLength) {
// int equalsIndex = query.indexOf("=", startIndex);
// checkState(equalsIndex > 0, "Parameters are not well formatted: %s", query);
// String paramName = query.substring(startIndex, equalsIndex);
// String paramValue;
// int andIndex = query.indexOf("&", equalsIndex);
// if (andIndex > equalsIndex) {
// paramValue = query.substring(equalsIndex + 1, andIndex);
// startIndex = andIndex + 1;
// } else {
// paramValue = query.substring(equalsIndex + 1);
// startIndex = queryLength;
// }
// pairs.add(new NameValuePair(paramName, paramValue));
// }
// return pairs;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// static RestUrl invalidRestUrl(String errorMsg) {
// return new RestUrl(null, null, errorMsg);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// static RestUrl restUrl(VarType[] types, Object[] values) {
// return new RestUrl(types, values, null);
// }
// Path: url/src/main/java/com/danisola/restify/url/RestParser.java
import com.danisola.restify.url.types.Opt;
import com.danisola.restify.url.types.VarType;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.danisola.restify.url.ParsedUrl.parseParams;
import static com.danisola.restify.url.RestUrl.invalidRestUrl;
import static com.danisola.restify.url.RestUrl.restUrl;
}
/**
* Parses the given path and query.
*
* @return the {@link RestUrl} that represents the given URL.
*/
public RestUrl parse(String path, String queryString) {
if (path == null) {
return RestUrl.invalidRestUrl("Url is null");
}
RestUrl restUrl = RestUrl.restUrl(new VarType[numVars], new Object[numVars]);
int varIndex = 0;
// Processing path variables
Matcher pathMatcher = pathPattern.matcher(path);
if (!pathMatcher.matches()) {
return RestUrl.invalidRestUrl("Path '" + path + "' does not match the pattern '" + pathPattern + "'");
}
for (VarType type : pathTypes) {
try {
varIndex = extract(pathMatcher, type, varIndex, restUrl);
} catch (Exception ex) {
return RestUrl.invalidRestUrl("Invalid value for variable '" + type.getId() + "': " + pathMatcher.group(type.getId()));
}
}
// Processing param variables | List<NameValuePair> valuePairs = parseParams(queryString); |
danisola/restify | url/src/main/java/com/danisola/restify/url/RestParser.java | // Path: url/src/main/java/com/danisola/restify/url/types/Opt.java
// public class Opt<T> implements VarType<T> {
//
// public static <T> Opt<T> opt(VarType<T> varType) {
// return new Opt<>(varType);
// }
//
// private final VarType<T> varType;
//
// private Opt(VarType<T> varType) {
// this.varType = varType;
// }
//
// @Override
// public String getId() {
// return varType.getId();
// }
//
// @Override
// public String getVarPattern() {
// return varType.getVarPattern();
// }
//
// @Override
// public T convert(String value) throws Exception {
// if ("".equals(value)) {
// return null;
// }
// return varType.convert(value);
// }
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/ParsedUrl.java
// static List<NameValuePair> parseParams(String query) {
// if (query == null || query.isEmpty()) {
// return Collections.emptyList();
// }
//
// List<NameValuePair> pairs = new ArrayList<>();
// int startIndex = 0;
// int queryLength = query.length();
// while (startIndex < queryLength) {
// int equalsIndex = query.indexOf("=", startIndex);
// checkState(equalsIndex > 0, "Parameters are not well formatted: %s", query);
// String paramName = query.substring(startIndex, equalsIndex);
// String paramValue;
// int andIndex = query.indexOf("&", equalsIndex);
// if (andIndex > equalsIndex) {
// paramValue = query.substring(equalsIndex + 1, andIndex);
// startIndex = andIndex + 1;
// } else {
// paramValue = query.substring(equalsIndex + 1);
// startIndex = queryLength;
// }
// pairs.add(new NameValuePair(paramName, paramValue));
// }
// return pairs;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// static RestUrl invalidRestUrl(String errorMsg) {
// return new RestUrl(null, null, errorMsg);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// static RestUrl restUrl(VarType[] types, Object[] values) {
// return new RestUrl(types, values, null);
// }
| import com.danisola.restify.url.types.Opt;
import com.danisola.restify.url.types.VarType;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.danisola.restify.url.ParsedUrl.parseParams;
import static com.danisola.restify.url.RestUrl.invalidRestUrl;
import static com.danisola.restify.url.RestUrl.restUrl; | }
String paramValue = valuePair.getValue();
Matcher paramMatcher = paramVar.getValuePattern().matcher(paramValue);
if (!paramMatcher.matches()) {
return RestUrl.invalidRestUrl("Parameter '" + paramName + "=" + paramValue + "' does not match pattern");
}
for (VarType paramType : paramVar.getTypes()) {
try {
varIndex = extract(paramMatcher, paramType, varIndex, restUrl);
} catch (Exception ex) {
return RestUrl.invalidRestUrl("Invalid value for variable '" + paramName + "': " + paramValue);
}
}
}
return restUrl;
}
private NameValuePair getValuePairWithName(String name, List<NameValuePair> params) {
for (NameValuePair valuePair : params) {
if (name.equals(valuePair.getName())) {
return valuePair;
}
}
return null;
}
private boolean areOptional(VarType[] varTypes) {
for (VarType varType : varTypes) { | // Path: url/src/main/java/com/danisola/restify/url/types/Opt.java
// public class Opt<T> implements VarType<T> {
//
// public static <T> Opt<T> opt(VarType<T> varType) {
// return new Opt<>(varType);
// }
//
// private final VarType<T> varType;
//
// private Opt(VarType<T> varType) {
// this.varType = varType;
// }
//
// @Override
// public String getId() {
// return varType.getId();
// }
//
// @Override
// public String getVarPattern() {
// return varType.getVarPattern();
// }
//
// @Override
// public T convert(String value) throws Exception {
// if ("".equals(value)) {
// return null;
// }
// return varType.convert(value);
// }
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/ParsedUrl.java
// static List<NameValuePair> parseParams(String query) {
// if (query == null || query.isEmpty()) {
// return Collections.emptyList();
// }
//
// List<NameValuePair> pairs = new ArrayList<>();
// int startIndex = 0;
// int queryLength = query.length();
// while (startIndex < queryLength) {
// int equalsIndex = query.indexOf("=", startIndex);
// checkState(equalsIndex > 0, "Parameters are not well formatted: %s", query);
// String paramName = query.substring(startIndex, equalsIndex);
// String paramValue;
// int andIndex = query.indexOf("&", equalsIndex);
// if (andIndex > equalsIndex) {
// paramValue = query.substring(equalsIndex + 1, andIndex);
// startIndex = andIndex + 1;
// } else {
// paramValue = query.substring(equalsIndex + 1);
// startIndex = queryLength;
// }
// pairs.add(new NameValuePair(paramName, paramValue));
// }
// return pairs;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// static RestUrl invalidRestUrl(String errorMsg) {
// return new RestUrl(null, null, errorMsg);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// static RestUrl restUrl(VarType[] types, Object[] values) {
// return new RestUrl(types, values, null);
// }
// Path: url/src/main/java/com/danisola/restify/url/RestParser.java
import com.danisola.restify.url.types.Opt;
import com.danisola.restify.url.types.VarType;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.danisola.restify.url.ParsedUrl.parseParams;
import static com.danisola.restify.url.RestUrl.invalidRestUrl;
import static com.danisola.restify.url.RestUrl.restUrl;
}
String paramValue = valuePair.getValue();
Matcher paramMatcher = paramVar.getValuePattern().matcher(paramValue);
if (!paramMatcher.matches()) {
return RestUrl.invalidRestUrl("Parameter '" + paramName + "=" + paramValue + "' does not match pattern");
}
for (VarType paramType : paramVar.getTypes()) {
try {
varIndex = extract(paramMatcher, paramType, varIndex, restUrl);
} catch (Exception ex) {
return RestUrl.invalidRestUrl("Invalid value for variable '" + paramName + "': " + paramValue);
}
}
}
return restUrl;
}
private NameValuePair getValuePairWithName(String name, List<NameValuePair> params) {
for (NameValuePair valuePair : params) {
if (name.equals(valuePair.getName())) {
return valuePair;
}
}
return null;
}
private boolean areOptional(VarType[] varTypes) {
for (VarType varType : varTypes) { | if (!(varType instanceof Opt)) { |
danisola/restify | url/src/main/java/com/danisola/restify/url/RestUrl.java | // Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static String checkArgumentNotNullOrEmpty(String string) {
// if (string == null || string.isEmpty()) {
// throw new IllegalArgumentException("Argument cannot be null or empty");
// }
// return string;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkState(boolean expression, String errorMessageFormat, Object ... args) {
// if (!expression) {
// throw new IllegalStateException(String.format(errorMessageFormat, args));
// }
// }
| import com.danisola.restify.url.types.VarType;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgumentNotNullOrEmpty;
import static com.danisola.restify.url.preconditions.Preconditions.checkState; | package com.danisola.restify.url;
/**
* A REST representation of an URL. Allows to get access to the variables defined in the {@link RestParser} that has
* generated it.
*
* <p>Instances of this class are immutable and thus thread-safe.</p>
*/
public class RestUrl {
final String errorMessage; | // Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static String checkArgumentNotNullOrEmpty(String string) {
// if (string == null || string.isEmpty()) {
// throw new IllegalArgumentException("Argument cannot be null or empty");
// }
// return string;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkState(boolean expression, String errorMessageFormat, Object ... args) {
// if (!expression) {
// throw new IllegalStateException(String.format(errorMessageFormat, args));
// }
// }
// Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
import com.danisola.restify.url.types.VarType;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgumentNotNullOrEmpty;
import static com.danisola.restify.url.preconditions.Preconditions.checkState;
package com.danisola.restify.url;
/**
* A REST representation of an URL. Allows to get access to the variables defined in the {@link RestParser} that has
* generated it.
*
* <p>Instances of this class are immutable and thus thread-safe.</p>
*/
public class RestUrl {
final String errorMessage; | final VarType[] types; |
danisola/restify | url/src/main/java/com/danisola/restify/url/RestUrl.java | // Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static String checkArgumentNotNullOrEmpty(String string) {
// if (string == null || string.isEmpty()) {
// throw new IllegalArgumentException("Argument cannot be null or empty");
// }
// return string;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkState(boolean expression, String errorMessageFormat, Object ... args) {
// if (!expression) {
// throw new IllegalStateException(String.format(errorMessageFormat, args));
// }
// }
| import com.danisola.restify.url.types.VarType;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgumentNotNullOrEmpty;
import static com.danisola.restify.url.preconditions.Preconditions.checkState; | package com.danisola.restify.url;
/**
* A REST representation of an URL. Allows to get access to the variables defined in the {@link RestParser} that has
* generated it.
*
* <p>Instances of this class are immutable and thus thread-safe.</p>
*/
public class RestUrl {
final String errorMessage;
final VarType[] types;
final Object[] values;
static RestUrl invalidRestUrl(String errorMsg) {
return new RestUrl(null, null, errorMsg);
}
static RestUrl restUrl(VarType[] types, Object[] values) {
return new RestUrl(types, values, null);
}
private RestUrl(VarType[] types, Object[] values, String errorMsg) {
this.types = types;
this.values = values;
this.errorMessage = errorMsg;
}
/**
* Returns true if it matches the pattern and variable types of the {@link RestParser} that has generated this
* {@link RestUrl}.
*/
public boolean isValid() {
return errorMessage == null;
}
/**
* <p>If {@link #isValid()} is false, returns a message explaining why the parsed URL did not match the pattern
* and variables of the {@link RestParser} that has generated this {@link RestUrl}.</p>
*
* <p>If {@link #isValid()} is true, returns null</p>
*/
public String errorMessage() {
return errorMessage;
}
/**
* Returns the given variable with the specified return type. The variable id and type must match the declared
* ones in the {@link RestParser} that has generated this {@link RestUrl}.
*
* <p>This method throws exceptions to enforce a correct usage of the API.</p>
*
* @throws IllegalArgumentException if variableId is null, empty or not defined in the {@link RestParser}
* @throws IllegalStateException if the URL is invalid ({@link #isValid()} is false)
* @throws ClassCastException if the returned variable has not the same type as the declared variable in {@link RestParser}
*/
public <T> T variable(String variableId) { | // Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static String checkArgumentNotNullOrEmpty(String string) {
// if (string == null || string.isEmpty()) {
// throw new IllegalArgumentException("Argument cannot be null or empty");
// }
// return string;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkState(boolean expression, String errorMessageFormat, Object ... args) {
// if (!expression) {
// throw new IllegalStateException(String.format(errorMessageFormat, args));
// }
// }
// Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
import com.danisola.restify.url.types.VarType;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgumentNotNullOrEmpty;
import static com.danisola.restify.url.preconditions.Preconditions.checkState;
package com.danisola.restify.url;
/**
* A REST representation of an URL. Allows to get access to the variables defined in the {@link RestParser} that has
* generated it.
*
* <p>Instances of this class are immutable and thus thread-safe.</p>
*/
public class RestUrl {
final String errorMessage;
final VarType[] types;
final Object[] values;
static RestUrl invalidRestUrl(String errorMsg) {
return new RestUrl(null, null, errorMsg);
}
static RestUrl restUrl(VarType[] types, Object[] values) {
return new RestUrl(types, values, null);
}
private RestUrl(VarType[] types, Object[] values, String errorMsg) {
this.types = types;
this.values = values;
this.errorMessage = errorMsg;
}
/**
* Returns true if it matches the pattern and variable types of the {@link RestParser} that has generated this
* {@link RestUrl}.
*/
public boolean isValid() {
return errorMessage == null;
}
/**
* <p>If {@link #isValid()} is false, returns a message explaining why the parsed URL did not match the pattern
* and variables of the {@link RestParser} that has generated this {@link RestUrl}.</p>
*
* <p>If {@link #isValid()} is true, returns null</p>
*/
public String errorMessage() {
return errorMessage;
}
/**
* Returns the given variable with the specified return type. The variable id and type must match the declared
* ones in the {@link RestParser} that has generated this {@link RestUrl}.
*
* <p>This method throws exceptions to enforce a correct usage of the API.</p>
*
* @throws IllegalArgumentException if variableId is null, empty or not defined in the {@link RestParser}
* @throws IllegalStateException if the URL is invalid ({@link #isValid()} is false)
* @throws ClassCastException if the returned variable has not the same type as the declared variable in {@link RestParser}
*/
public <T> T variable(String variableId) { | checkArgumentNotNullOrEmpty(variableId); |
danisola/restify | url/src/main/java/com/danisola/restify/url/RestUrl.java | // Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static String checkArgumentNotNullOrEmpty(String string) {
// if (string == null || string.isEmpty()) {
// throw new IllegalArgumentException("Argument cannot be null or empty");
// }
// return string;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkState(boolean expression, String errorMessageFormat, Object ... args) {
// if (!expression) {
// throw new IllegalStateException(String.format(errorMessageFormat, args));
// }
// }
| import com.danisola.restify.url.types.VarType;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgumentNotNullOrEmpty;
import static com.danisola.restify.url.preconditions.Preconditions.checkState; | package com.danisola.restify.url;
/**
* A REST representation of an URL. Allows to get access to the variables defined in the {@link RestParser} that has
* generated it.
*
* <p>Instances of this class are immutable and thus thread-safe.</p>
*/
public class RestUrl {
final String errorMessage;
final VarType[] types;
final Object[] values;
static RestUrl invalidRestUrl(String errorMsg) {
return new RestUrl(null, null, errorMsg);
}
static RestUrl restUrl(VarType[] types, Object[] values) {
return new RestUrl(types, values, null);
}
private RestUrl(VarType[] types, Object[] values, String errorMsg) {
this.types = types;
this.values = values;
this.errorMessage = errorMsg;
}
/**
* Returns true if it matches the pattern and variable types of the {@link RestParser} that has generated this
* {@link RestUrl}.
*/
public boolean isValid() {
return errorMessage == null;
}
/**
* <p>If {@link #isValid()} is false, returns a message explaining why the parsed URL did not match the pattern
* and variables of the {@link RestParser} that has generated this {@link RestUrl}.</p>
*
* <p>If {@link #isValid()} is true, returns null</p>
*/
public String errorMessage() {
return errorMessage;
}
/**
* Returns the given variable with the specified return type. The variable id and type must match the declared
* ones in the {@link RestParser} that has generated this {@link RestUrl}.
*
* <p>This method throws exceptions to enforce a correct usage of the API.</p>
*
* @throws IllegalArgumentException if variableId is null, empty or not defined in the {@link RestParser}
* @throws IllegalStateException if the URL is invalid ({@link #isValid()} is false)
* @throws ClassCastException if the returned variable has not the same type as the declared variable in {@link RestParser}
*/
public <T> T variable(String variableId) {
checkArgumentNotNullOrEmpty(variableId); | // Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static String checkArgumentNotNullOrEmpty(String string) {
// if (string == null || string.isEmpty()) {
// throw new IllegalArgumentException("Argument cannot be null or empty");
// }
// return string;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkState(boolean expression, String errorMessageFormat, Object ... args) {
// if (!expression) {
// throw new IllegalStateException(String.format(errorMessageFormat, args));
// }
// }
// Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
import com.danisola.restify.url.types.VarType;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgumentNotNullOrEmpty;
import static com.danisola.restify.url.preconditions.Preconditions.checkState;
package com.danisola.restify.url;
/**
* A REST representation of an URL. Allows to get access to the variables defined in the {@link RestParser} that has
* generated it.
*
* <p>Instances of this class are immutable and thus thread-safe.</p>
*/
public class RestUrl {
final String errorMessage;
final VarType[] types;
final Object[] values;
static RestUrl invalidRestUrl(String errorMsg) {
return new RestUrl(null, null, errorMsg);
}
static RestUrl restUrl(VarType[] types, Object[] values) {
return new RestUrl(types, values, null);
}
private RestUrl(VarType[] types, Object[] values, String errorMsg) {
this.types = types;
this.values = values;
this.errorMessage = errorMsg;
}
/**
* Returns true if it matches the pattern and variable types of the {@link RestParser} that has generated this
* {@link RestUrl}.
*/
public boolean isValid() {
return errorMessage == null;
}
/**
* <p>If {@link #isValid()} is false, returns a message explaining why the parsed URL did not match the pattern
* and variables of the {@link RestParser} that has generated this {@link RestUrl}.</p>
*
* <p>If {@link #isValid()} is true, returns null</p>
*/
public String errorMessage() {
return errorMessage;
}
/**
* Returns the given variable with the specified return type. The variable id and type must match the declared
* ones in the {@link RestParser} that has generated this {@link RestUrl}.
*
* <p>This method throws exceptions to enforce a correct usage of the API.</p>
*
* @throws IllegalArgumentException if variableId is null, empty or not defined in the {@link RestParser}
* @throws IllegalStateException if the URL is invalid ({@link #isValid()} is false)
* @throws ClassCastException if the returned variable has not the same type as the declared variable in {@link RestParser}
*/
public <T> T variable(String variableId) {
checkArgumentNotNullOrEmpty(variableId); | checkState(isValid(), "Variables are not accessible for invalid URLs"); |
danisola/restify | url/src/main/java/com/danisola/restify/url/types/AbstractVarType.java | // Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static String checkArgumentNotNullOrEmpty(String string) {
// if (string == null || string.isEmpty()) {
// throw new IllegalArgumentException("Argument cannot be null or empty");
// }
// return string;
// }
| import static com.danisola.restify.url.preconditions.Preconditions.checkArgumentNotNullOrEmpty; | package com.danisola.restify.url.types;
public abstract class AbstractVarType<T> implements VarType<T> {
private final String id;
private final String varPatternStr;
protected AbstractVarType(String id) {
this(id, ".*?");
}
protected AbstractVarType(String id, String pattern) { | // Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static String checkArgumentNotNullOrEmpty(String string) {
// if (string == null || string.isEmpty()) {
// throw new IllegalArgumentException("Argument cannot be null or empty");
// }
// return string;
// }
// Path: url/src/main/java/com/danisola/restify/url/types/AbstractVarType.java
import static com.danisola.restify.url.preconditions.Preconditions.checkArgumentNotNullOrEmpty;
package com.danisola.restify.url.types;
public abstract class AbstractVarType<T> implements VarType<T> {
private final String id;
private final String varPatternStr;
protected AbstractVarType(String id) {
this(id, ".*?");
}
protected AbstractVarType(String id, String pattern) { | this.id = checkArgumentNotNullOrEmpty(id); |
danisola/restify | url/src/main/java/com/danisola/restify/url/types/StrVar.java | // Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkArgument(boolean expression, String errorMessage) {
// if (!expression) {
// throw new IllegalArgumentException(errorMessage);
// }
// }
| import static com.danisola.restify.url.preconditions.Preconditions.checkArgument; | package com.danisola.restify.url.types;
public class StrVar extends AbstractVarType<String> {
public static StrVar strVar(String id) {
return new StrVar(id);
}
public static StrVar strVar(String id, String regex) {
return new StrVar(id, regex);
}
private StrVar(String id) {
super(id);
}
private StrVar(String id, String pattern) {
super(id, pattern);
}
@Override
public String convert(String value) { | // Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkArgument(boolean expression, String errorMessage) {
// if (!expression) {
// throw new IllegalArgumentException(errorMessage);
// }
// }
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
import static com.danisola.restify.url.preconditions.Preconditions.checkArgument;
package com.danisola.restify.url.types;
public class StrVar extends AbstractVarType<String> {
public static StrVar strVar(String id) {
return new StrVar(id);
}
public static StrVar strVar(String id, String regex) {
return new StrVar(id, regex);
}
private StrVar(String id) {
super(id);
}
private StrVar(String id, String pattern) {
super(id, pattern);
}
@Override
public String convert(String value) { | checkArgument(value != null, "Argument cannot be null"); |
danisola/restify | servlet/src/test/java/com/danisola/restify/servlet/utils/TestServlet.java | // Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// public class RestUrl {
//
// final String errorMessage;
// final VarType[] types;
// final Object[] values;
//
// static RestUrl invalidRestUrl(String errorMsg) {
// return new RestUrl(null, null, errorMsg);
// }
//
// static RestUrl restUrl(VarType[] types, Object[] values) {
// return new RestUrl(types, values, null);
// }
//
// private RestUrl(VarType[] types, Object[] values, String errorMsg) {
// this.types = types;
// this.values = values;
// this.errorMessage = errorMsg;
// }
//
// /**
// * Returns true if it matches the pattern and variable types of the {@link RestParser} that has generated this
// * {@link RestUrl}.
// */
// public boolean isValid() {
// return errorMessage == null;
// }
//
// /**
// * <p>If {@link #isValid()} is false, returns a message explaining why the parsed URL did not match the pattern
// * and variables of the {@link RestParser} that has generated this {@link RestUrl}.</p>
// *
// * <p>If {@link #isValid()} is true, returns null</p>
// */
// public String errorMessage() {
// return errorMessage;
// }
//
// /**
// * Returns the given variable with the specified return type. The variable id and type must match the declared
// * ones in the {@link RestParser} that has generated this {@link RestUrl}.
// *
// * <p>This method throws exceptions to enforce a correct usage of the API.</p>
// *
// * @throws IllegalArgumentException if variableId is null, empty or not defined in the {@link RestParser}
// * @throws IllegalStateException if the URL is invalid ({@link #isValid()} is false)
// * @throws ClassCastException if the returned variable has not the same type as the declared variable in {@link RestParser}
// */
// public <T> T variable(String variableId) {
// checkArgumentNotNullOrEmpty(variableId);
// checkState(isValid(), "Variables are not accessible for invalid URLs");
//
// for (int i = 0; i < types.length; i++) {
// if (types[i].getId().equals(variableId)) {
// return (T) values[i];
// }
// }
// throw new IllegalArgumentException("Variable id '" + variableId + "' is not declared in the pattern");
// }
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
| import com.danisola.restify.servlet.*;
import com.danisola.restify.url.RestUrl;
import com.danisola.restify.url.types.VarType;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; | package com.danisola.restify.servlet.utils;
public class TestServlet extends RestServlet implements Delete, Get, Head, Options, Post, Put, Trace {
private final TestCallback callback;
| // Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// public class RestUrl {
//
// final String errorMessage;
// final VarType[] types;
// final Object[] values;
//
// static RestUrl invalidRestUrl(String errorMsg) {
// return new RestUrl(null, null, errorMsg);
// }
//
// static RestUrl restUrl(VarType[] types, Object[] values) {
// return new RestUrl(types, values, null);
// }
//
// private RestUrl(VarType[] types, Object[] values, String errorMsg) {
// this.types = types;
// this.values = values;
// this.errorMessage = errorMsg;
// }
//
// /**
// * Returns true if it matches the pattern and variable types of the {@link RestParser} that has generated this
// * {@link RestUrl}.
// */
// public boolean isValid() {
// return errorMessage == null;
// }
//
// /**
// * <p>If {@link #isValid()} is false, returns a message explaining why the parsed URL did not match the pattern
// * and variables of the {@link RestParser} that has generated this {@link RestUrl}.</p>
// *
// * <p>If {@link #isValid()} is true, returns null</p>
// */
// public String errorMessage() {
// return errorMessage;
// }
//
// /**
// * Returns the given variable with the specified return type. The variable id and type must match the declared
// * ones in the {@link RestParser} that has generated this {@link RestUrl}.
// *
// * <p>This method throws exceptions to enforce a correct usage of the API.</p>
// *
// * @throws IllegalArgumentException if variableId is null, empty or not defined in the {@link RestParser}
// * @throws IllegalStateException if the URL is invalid ({@link #isValid()} is false)
// * @throws ClassCastException if the returned variable has not the same type as the declared variable in {@link RestParser}
// */
// public <T> T variable(String variableId) {
// checkArgumentNotNullOrEmpty(variableId);
// checkState(isValid(), "Variables are not accessible for invalid URLs");
//
// for (int i = 0; i < types.length; i++) {
// if (types[i].getId().equals(variableId)) {
// return (T) values[i];
// }
// }
// throw new IllegalArgumentException("Variable id '" + variableId + "' is not declared in the pattern");
// }
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
// Path: servlet/src/test/java/com/danisola/restify/servlet/utils/TestServlet.java
import com.danisola.restify.servlet.*;
import com.danisola.restify.url.RestUrl;
import com.danisola.restify.url.types.VarType;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
package com.danisola.restify.servlet.utils;
public class TestServlet extends RestServlet implements Delete, Get, Head, Options, Post, Put, Trace {
private final TestCallback callback;
| public TestServlet(TestCallback callback, String pattern, VarType... types) { |
danisola/restify | servlet/src/test/java/com/danisola/restify/servlet/utils/TestServlet.java | // Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// public class RestUrl {
//
// final String errorMessage;
// final VarType[] types;
// final Object[] values;
//
// static RestUrl invalidRestUrl(String errorMsg) {
// return new RestUrl(null, null, errorMsg);
// }
//
// static RestUrl restUrl(VarType[] types, Object[] values) {
// return new RestUrl(types, values, null);
// }
//
// private RestUrl(VarType[] types, Object[] values, String errorMsg) {
// this.types = types;
// this.values = values;
// this.errorMessage = errorMsg;
// }
//
// /**
// * Returns true if it matches the pattern and variable types of the {@link RestParser} that has generated this
// * {@link RestUrl}.
// */
// public boolean isValid() {
// return errorMessage == null;
// }
//
// /**
// * <p>If {@link #isValid()} is false, returns a message explaining why the parsed URL did not match the pattern
// * and variables of the {@link RestParser} that has generated this {@link RestUrl}.</p>
// *
// * <p>If {@link #isValid()} is true, returns null</p>
// */
// public String errorMessage() {
// return errorMessage;
// }
//
// /**
// * Returns the given variable with the specified return type. The variable id and type must match the declared
// * ones in the {@link RestParser} that has generated this {@link RestUrl}.
// *
// * <p>This method throws exceptions to enforce a correct usage of the API.</p>
// *
// * @throws IllegalArgumentException if variableId is null, empty or not defined in the {@link RestParser}
// * @throws IllegalStateException if the URL is invalid ({@link #isValid()} is false)
// * @throws ClassCastException if the returned variable has not the same type as the declared variable in {@link RestParser}
// */
// public <T> T variable(String variableId) {
// checkArgumentNotNullOrEmpty(variableId);
// checkState(isValid(), "Variables are not accessible for invalid URLs");
//
// for (int i = 0; i < types.length; i++) {
// if (types[i].getId().equals(variableId)) {
// return (T) values[i];
// }
// }
// throw new IllegalArgumentException("Variable id '" + variableId + "' is not declared in the pattern");
// }
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
| import com.danisola.restify.servlet.*;
import com.danisola.restify.url.RestUrl;
import com.danisola.restify.url.types.VarType;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; | package com.danisola.restify.servlet.utils;
public class TestServlet extends RestServlet implements Delete, Get, Head, Options, Post, Put, Trace {
private final TestCallback callback;
public TestServlet(TestCallback callback, String pattern, VarType... types) {
super(pattern, types);
this.callback = callback;
}
@Override | // Path: url/src/main/java/com/danisola/restify/url/RestUrl.java
// public class RestUrl {
//
// final String errorMessage;
// final VarType[] types;
// final Object[] values;
//
// static RestUrl invalidRestUrl(String errorMsg) {
// return new RestUrl(null, null, errorMsg);
// }
//
// static RestUrl restUrl(VarType[] types, Object[] values) {
// return new RestUrl(types, values, null);
// }
//
// private RestUrl(VarType[] types, Object[] values, String errorMsg) {
// this.types = types;
// this.values = values;
// this.errorMessage = errorMsg;
// }
//
// /**
// * Returns true if it matches the pattern and variable types of the {@link RestParser} that has generated this
// * {@link RestUrl}.
// */
// public boolean isValid() {
// return errorMessage == null;
// }
//
// /**
// * <p>If {@link #isValid()} is false, returns a message explaining why the parsed URL did not match the pattern
// * and variables of the {@link RestParser} that has generated this {@link RestUrl}.</p>
// *
// * <p>If {@link #isValid()} is true, returns null</p>
// */
// public String errorMessage() {
// return errorMessage;
// }
//
// /**
// * Returns the given variable with the specified return type. The variable id and type must match the declared
// * ones in the {@link RestParser} that has generated this {@link RestUrl}.
// *
// * <p>This method throws exceptions to enforce a correct usage of the API.</p>
// *
// * @throws IllegalArgumentException if variableId is null, empty or not defined in the {@link RestParser}
// * @throws IllegalStateException if the URL is invalid ({@link #isValid()} is false)
// * @throws ClassCastException if the returned variable has not the same type as the declared variable in {@link RestParser}
// */
// public <T> T variable(String variableId) {
// checkArgumentNotNullOrEmpty(variableId);
// checkState(isValid(), "Variables are not accessible for invalid URLs");
//
// for (int i = 0; i < types.length; i++) {
// if (types[i].getId().equals(variableId)) {
// return (T) values[i];
// }
// }
// throw new IllegalArgumentException("Variable id '" + variableId + "' is not declared in the pattern");
// }
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
// Path: servlet/src/test/java/com/danisola/restify/servlet/utils/TestServlet.java
import com.danisola.restify.servlet.*;
import com.danisola.restify.url.RestUrl;
import com.danisola.restify.url.types.VarType;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
package com.danisola.restify.servlet.utils;
public class TestServlet extends RestServlet implements Delete, Get, Head, Options, Post, Put, Trace {
private final TestCallback callback;
public TestServlet(TestCallback callback, String pattern, VarType... types) {
super(pattern, types);
this.callback = callback;
}
@Override | public void delete(HttpServletRequest req, HttpServletResponse res, RestUrl url) throws ServletException, IOException { |
danisola/restify | url/src/main/java/com/danisola/restify/url/ParamVar.java | // Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
| import com.danisola.restify.url.types.VarType;
import java.util.regex.Pattern; | package com.danisola.restify.url;
class ParamVar {
private final String name; | // Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
// Path: url/src/main/java/com/danisola/restify/url/ParamVar.java
import com.danisola.restify.url.types.VarType;
import java.util.regex.Pattern;
package com.danisola.restify.url;
class ParamVar {
private final String name; | private final VarType[] types; |
danisola/restify | url/src/main/java/com/danisola/restify/url/types/StrArrayVar.java | // Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static String checkArgumentNotNullOrEmpty(String string) {
// if (string == null || string.isEmpty()) {
// throw new IllegalArgumentException("Argument cannot be null or empty");
// }
// return string;
// }
| import static com.danisola.restify.url.preconditions.Preconditions.checkArgumentNotNullOrEmpty; | package com.danisola.restify.url.types;
public class StrArrayVar extends AbstractVarType<String[]> {
public static StrArrayVar strArrayVar(String id) {
return new StrArrayVar(id);
}
public static StrArrayVar strArrayVar(String id, String regex) {
return new StrArrayVar(id, regex);
}
private StrArrayVar(String id) {
super(id);
}
private StrArrayVar(String id, String regex) {
super(id);
}
@Override
public String[] convert(String value) { | // Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static String checkArgumentNotNullOrEmpty(String string) {
// if (string == null || string.isEmpty()) {
// throw new IllegalArgumentException("Argument cannot be null or empty");
// }
// return string;
// }
// Path: url/src/main/java/com/danisola/restify/url/types/StrArrayVar.java
import static com.danisola.restify.url.preconditions.Preconditions.checkArgumentNotNullOrEmpty;
package com.danisola.restify.url.types;
public class StrArrayVar extends AbstractVarType<String[]> {
public static StrArrayVar strArrayVar(String id) {
return new StrArrayVar(id);
}
public static StrArrayVar strArrayVar(String id, String regex) {
return new StrArrayVar(id, regex);
}
private StrArrayVar(String id) {
super(id);
}
private StrArrayVar(String id, String regex) {
super(id);
}
@Override
public String[] convert(String value) { | return checkArgumentNotNullOrEmpty(value).split(","); |
danisola/restify | url/src/test/java/com/danisola/restify/url/UrlRestifyBenchmark.java | // Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
// public static RestParser parser(String pattern, VarType... types) {
// checkPattern(pattern);
//
// final int numTypes = types.length;
// ParsedUrl parsedUrl = parseUrl(pattern);
// StringBuilder sb = new StringBuilder();
//
// // Processing path
// int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
// Pattern pathPattern = Pattern.compile(sb.toString());
// VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
//
// // Processing parameters
// List<NameValuePair> params = parsedUrl.getParameters();
// ParamVar[] paramVars = new ParamVar[params.size()];
// int paramVarCounter = 0;
// for (int i = 0; i < paramVars.length; i++) {
// NameValuePair pair = params.get(i);
//
// int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue());
// checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName());
//
// VarType[] paramTypes = Arrays.copyOfRange(types, typesIndex, newTypesIndex);
// Pattern paramValuePattern = Pattern.compile(sb.toString());
// paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
// paramVarCounter += newTypesIndex - typesIndex;
// typesIndex = newTypesIndex;
// }
//
// final int numVars = pathTypes.length + paramVarCounter;
// checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
// return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/IntVar.java
// public static IntVar intVar(String id) {
// return new IntVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
// public static StrVar strVar(String id) {
// return new StrVar(id);
// }
| import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import static com.danisola.restify.url.RestParserFactory.parser;
import static com.danisola.restify.url.types.IntVar.intVar;
import static com.danisola.restify.url.types.StrVar.strVar; | package com.danisola.restify.url;
public class UrlRestifyBenchmark extends SimpleBenchmark {
public RestParser timeCreatingParser(int reps) { | // Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
// public static RestParser parser(String pattern, VarType... types) {
// checkPattern(pattern);
//
// final int numTypes = types.length;
// ParsedUrl parsedUrl = parseUrl(pattern);
// StringBuilder sb = new StringBuilder();
//
// // Processing path
// int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
// Pattern pathPattern = Pattern.compile(sb.toString());
// VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
//
// // Processing parameters
// List<NameValuePair> params = parsedUrl.getParameters();
// ParamVar[] paramVars = new ParamVar[params.size()];
// int paramVarCounter = 0;
// for (int i = 0; i < paramVars.length; i++) {
// NameValuePair pair = params.get(i);
//
// int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue());
// checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName());
//
// VarType[] paramTypes = Arrays.copyOfRange(types, typesIndex, newTypesIndex);
// Pattern paramValuePattern = Pattern.compile(sb.toString());
// paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
// paramVarCounter += newTypesIndex - typesIndex;
// typesIndex = newTypesIndex;
// }
//
// final int numVars = pathTypes.length + paramVarCounter;
// checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
// return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/IntVar.java
// public static IntVar intVar(String id) {
// return new IntVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
// public static StrVar strVar(String id) {
// return new StrVar(id);
// }
// Path: url/src/test/java/com/danisola/restify/url/UrlRestifyBenchmark.java
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import static com.danisola.restify.url.RestParserFactory.parser;
import static com.danisola.restify.url.types.IntVar.intVar;
import static com.danisola.restify.url.types.StrVar.strVar;
package com.danisola.restify.url;
public class UrlRestifyBenchmark extends SimpleBenchmark {
public RestParser timeCreatingParser(int reps) { | RestParser parser = null; |
danisola/restify | url/src/test/java/com/danisola/restify/url/UrlRestifyBenchmark.java | // Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
// public static RestParser parser(String pattern, VarType... types) {
// checkPattern(pattern);
//
// final int numTypes = types.length;
// ParsedUrl parsedUrl = parseUrl(pattern);
// StringBuilder sb = new StringBuilder();
//
// // Processing path
// int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
// Pattern pathPattern = Pattern.compile(sb.toString());
// VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
//
// // Processing parameters
// List<NameValuePair> params = parsedUrl.getParameters();
// ParamVar[] paramVars = new ParamVar[params.size()];
// int paramVarCounter = 0;
// for (int i = 0; i < paramVars.length; i++) {
// NameValuePair pair = params.get(i);
//
// int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue());
// checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName());
//
// VarType[] paramTypes = Arrays.copyOfRange(types, typesIndex, newTypesIndex);
// Pattern paramValuePattern = Pattern.compile(sb.toString());
// paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
// paramVarCounter += newTypesIndex - typesIndex;
// typesIndex = newTypesIndex;
// }
//
// final int numVars = pathTypes.length + paramVarCounter;
// checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
// return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/IntVar.java
// public static IntVar intVar(String id) {
// return new IntVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
// public static StrVar strVar(String id) {
// return new StrVar(id);
// }
| import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import static com.danisola.restify.url.RestParserFactory.parser;
import static com.danisola.restify.url.types.IntVar.intVar;
import static com.danisola.restify.url.types.StrVar.strVar; | package com.danisola.restify.url;
public class UrlRestifyBenchmark extends SimpleBenchmark {
public RestParser timeCreatingParser(int reps) {
RestParser parser = null;
for (int i = 0; i < reps; i++) { | // Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
// public static RestParser parser(String pattern, VarType... types) {
// checkPattern(pattern);
//
// final int numTypes = types.length;
// ParsedUrl parsedUrl = parseUrl(pattern);
// StringBuilder sb = new StringBuilder();
//
// // Processing path
// int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
// Pattern pathPattern = Pattern.compile(sb.toString());
// VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
//
// // Processing parameters
// List<NameValuePair> params = parsedUrl.getParameters();
// ParamVar[] paramVars = new ParamVar[params.size()];
// int paramVarCounter = 0;
// for (int i = 0; i < paramVars.length; i++) {
// NameValuePair pair = params.get(i);
//
// int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue());
// checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName());
//
// VarType[] paramTypes = Arrays.copyOfRange(types, typesIndex, newTypesIndex);
// Pattern paramValuePattern = Pattern.compile(sb.toString());
// paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
// paramVarCounter += newTypesIndex - typesIndex;
// typesIndex = newTypesIndex;
// }
//
// final int numVars = pathTypes.length + paramVarCounter;
// checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
// return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/IntVar.java
// public static IntVar intVar(String id) {
// return new IntVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
// public static StrVar strVar(String id) {
// return new StrVar(id);
// }
// Path: url/src/test/java/com/danisola/restify/url/UrlRestifyBenchmark.java
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import static com.danisola.restify.url.RestParserFactory.parser;
import static com.danisola.restify.url.types.IntVar.intVar;
import static com.danisola.restify.url.types.StrVar.strVar;
package com.danisola.restify.url;
public class UrlRestifyBenchmark extends SimpleBenchmark {
public RestParser timeCreatingParser(int reps) {
RestParser parser = null;
for (int i = 0; i < reps; i++) { | parser = parser("/leagues/{}/teams/{}/players?age={}", strVar("leagueId"), strVar("teamId"), |
danisola/restify | url/src/test/java/com/danisola/restify/url/UrlRestifyBenchmark.java | // Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
// public static RestParser parser(String pattern, VarType... types) {
// checkPattern(pattern);
//
// final int numTypes = types.length;
// ParsedUrl parsedUrl = parseUrl(pattern);
// StringBuilder sb = new StringBuilder();
//
// // Processing path
// int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
// Pattern pathPattern = Pattern.compile(sb.toString());
// VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
//
// // Processing parameters
// List<NameValuePair> params = parsedUrl.getParameters();
// ParamVar[] paramVars = new ParamVar[params.size()];
// int paramVarCounter = 0;
// for (int i = 0; i < paramVars.length; i++) {
// NameValuePair pair = params.get(i);
//
// int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue());
// checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName());
//
// VarType[] paramTypes = Arrays.copyOfRange(types, typesIndex, newTypesIndex);
// Pattern paramValuePattern = Pattern.compile(sb.toString());
// paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
// paramVarCounter += newTypesIndex - typesIndex;
// typesIndex = newTypesIndex;
// }
//
// final int numVars = pathTypes.length + paramVarCounter;
// checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
// return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/IntVar.java
// public static IntVar intVar(String id) {
// return new IntVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
// public static StrVar strVar(String id) {
// return new StrVar(id);
// }
| import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import static com.danisola.restify.url.RestParserFactory.parser;
import static com.danisola.restify.url.types.IntVar.intVar;
import static com.danisola.restify.url.types.StrVar.strVar; | package com.danisola.restify.url;
public class UrlRestifyBenchmark extends SimpleBenchmark {
public RestParser timeCreatingParser(int reps) {
RestParser parser = null;
for (int i = 0; i < reps; i++) {
parser = parser("/leagues/{}/teams/{}/players?age={}", strVar("leagueId"), strVar("teamId"), | // Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
// public static RestParser parser(String pattern, VarType... types) {
// checkPattern(pattern);
//
// final int numTypes = types.length;
// ParsedUrl parsedUrl = parseUrl(pattern);
// StringBuilder sb = new StringBuilder();
//
// // Processing path
// int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
// Pattern pathPattern = Pattern.compile(sb.toString());
// VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
//
// // Processing parameters
// List<NameValuePair> params = parsedUrl.getParameters();
// ParamVar[] paramVars = new ParamVar[params.size()];
// int paramVarCounter = 0;
// for (int i = 0; i < paramVars.length; i++) {
// NameValuePair pair = params.get(i);
//
// int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue());
// checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName());
//
// VarType[] paramTypes = Arrays.copyOfRange(types, typesIndex, newTypesIndex);
// Pattern paramValuePattern = Pattern.compile(sb.toString());
// paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
// paramVarCounter += newTypesIndex - typesIndex;
// typesIndex = newTypesIndex;
// }
//
// final int numVars = pathTypes.length + paramVarCounter;
// checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
// return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/IntVar.java
// public static IntVar intVar(String id) {
// return new IntVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
// public static StrVar strVar(String id) {
// return new StrVar(id);
// }
// Path: url/src/test/java/com/danisola/restify/url/UrlRestifyBenchmark.java
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import static com.danisola.restify.url.RestParserFactory.parser;
import static com.danisola.restify.url.types.IntVar.intVar;
import static com.danisola.restify.url.types.StrVar.strVar;
package com.danisola.restify.url;
public class UrlRestifyBenchmark extends SimpleBenchmark {
public RestParser timeCreatingParser(int reps) {
RestParser parser = null;
for (int i = 0; i < reps; i++) {
parser = parser("/leagues/{}/teams/{}/players?age={}", strVar("leagueId"), strVar("teamId"), | intVar("playerAge")); |
danisola/restify | url/src/test/java/com/danisola/restify/url/RestParserTest.java | // Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
// public static RestParser parser(String pattern, VarType... types) {
// checkPattern(pattern);
//
// final int numTypes = types.length;
// ParsedUrl parsedUrl = parseUrl(pattern);
// StringBuilder sb = new StringBuilder();
//
// // Processing path
// int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
// Pattern pathPattern = Pattern.compile(sb.toString());
// VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
//
// // Processing parameters
// List<NameValuePair> params = parsedUrl.getParameters();
// ParamVar[] paramVars = new ParamVar[params.size()];
// int paramVarCounter = 0;
// for (int i = 0; i < paramVars.length; i++) {
// NameValuePair pair = params.get(i);
//
// int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue());
// checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName());
//
// VarType[] paramTypes = Arrays.copyOfRange(types, typesIndex, newTypesIndex);
// Pattern paramValuePattern = Pattern.compile(sb.toString());
// paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
// paramVarCounter += newTypesIndex - typesIndex;
// typesIndex = newTypesIndex;
// }
//
// final int numVars = pathTypes.length + paramVarCounter;
// checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
// return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/IntVar.java
// public static IntVar intVar(String id) {
// return new IntVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
// public static StrVar strVar(String id) {
// return new StrVar(id);
// }
| import org.junit.Test;
import static com.danisola.restify.url.RestParserFactory.parser;
import static com.danisola.restify.url.types.IntVar.intVar;
import static com.danisola.restify.url.types.StrVar.strVar; | package com.danisola.restify.url;
public class RestParserTest {
@Test(expected = IllegalStateException.class)
public void whenParameterValueHasNoVariableThenExceptionIsThrown() { | // Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
// public static RestParser parser(String pattern, VarType... types) {
// checkPattern(pattern);
//
// final int numTypes = types.length;
// ParsedUrl parsedUrl = parseUrl(pattern);
// StringBuilder sb = new StringBuilder();
//
// // Processing path
// int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
// Pattern pathPattern = Pattern.compile(sb.toString());
// VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
//
// // Processing parameters
// List<NameValuePair> params = parsedUrl.getParameters();
// ParamVar[] paramVars = new ParamVar[params.size()];
// int paramVarCounter = 0;
// for (int i = 0; i < paramVars.length; i++) {
// NameValuePair pair = params.get(i);
//
// int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue());
// checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName());
//
// VarType[] paramTypes = Arrays.copyOfRange(types, typesIndex, newTypesIndex);
// Pattern paramValuePattern = Pattern.compile(sb.toString());
// paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
// paramVarCounter += newTypesIndex - typesIndex;
// typesIndex = newTypesIndex;
// }
//
// final int numVars = pathTypes.length + paramVarCounter;
// checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
// return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/IntVar.java
// public static IntVar intVar(String id) {
// return new IntVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
// public static StrVar strVar(String id) {
// return new StrVar(id);
// }
// Path: url/src/test/java/com/danisola/restify/url/RestParserTest.java
import org.junit.Test;
import static com.danisola.restify.url.RestParserFactory.parser;
import static com.danisola.restify.url.types.IntVar.intVar;
import static com.danisola.restify.url.types.StrVar.strVar;
package com.danisola.restify.url;
public class RestParserTest {
@Test(expected = IllegalStateException.class)
public void whenParameterValueHasNoVariableThenExceptionIsThrown() { | parser("/countries/{}?city=lon", strVar("GB")); |
danisola/restify | url/src/test/java/com/danisola/restify/url/RestParserTest.java | // Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
// public static RestParser parser(String pattern, VarType... types) {
// checkPattern(pattern);
//
// final int numTypes = types.length;
// ParsedUrl parsedUrl = parseUrl(pattern);
// StringBuilder sb = new StringBuilder();
//
// // Processing path
// int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
// Pattern pathPattern = Pattern.compile(sb.toString());
// VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
//
// // Processing parameters
// List<NameValuePair> params = parsedUrl.getParameters();
// ParamVar[] paramVars = new ParamVar[params.size()];
// int paramVarCounter = 0;
// for (int i = 0; i < paramVars.length; i++) {
// NameValuePair pair = params.get(i);
//
// int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue());
// checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName());
//
// VarType[] paramTypes = Arrays.copyOfRange(types, typesIndex, newTypesIndex);
// Pattern paramValuePattern = Pattern.compile(sb.toString());
// paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
// paramVarCounter += newTypesIndex - typesIndex;
// typesIndex = newTypesIndex;
// }
//
// final int numVars = pathTypes.length + paramVarCounter;
// checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
// return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/IntVar.java
// public static IntVar intVar(String id) {
// return new IntVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
// public static StrVar strVar(String id) {
// return new StrVar(id);
// }
| import org.junit.Test;
import static com.danisola.restify.url.RestParserFactory.parser;
import static com.danisola.restify.url.types.IntVar.intVar;
import static com.danisola.restify.url.types.StrVar.strVar; | package com.danisola.restify.url;
public class RestParserTest {
@Test(expected = IllegalStateException.class)
public void whenParameterValueHasNoVariableThenExceptionIsThrown() { | // Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
// public static RestParser parser(String pattern, VarType... types) {
// checkPattern(pattern);
//
// final int numTypes = types.length;
// ParsedUrl parsedUrl = parseUrl(pattern);
// StringBuilder sb = new StringBuilder();
//
// // Processing path
// int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
// Pattern pathPattern = Pattern.compile(sb.toString());
// VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
//
// // Processing parameters
// List<NameValuePair> params = parsedUrl.getParameters();
// ParamVar[] paramVars = new ParamVar[params.size()];
// int paramVarCounter = 0;
// for (int i = 0; i < paramVars.length; i++) {
// NameValuePair pair = params.get(i);
//
// int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue());
// checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName());
//
// VarType[] paramTypes = Arrays.copyOfRange(types, typesIndex, newTypesIndex);
// Pattern paramValuePattern = Pattern.compile(sb.toString());
// paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
// paramVarCounter += newTypesIndex - typesIndex;
// typesIndex = newTypesIndex;
// }
//
// final int numVars = pathTypes.length + paramVarCounter;
// checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
// return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/IntVar.java
// public static IntVar intVar(String id) {
// return new IntVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
// public static StrVar strVar(String id) {
// return new StrVar(id);
// }
// Path: url/src/test/java/com/danisola/restify/url/RestParserTest.java
import org.junit.Test;
import static com.danisola.restify.url.RestParserFactory.parser;
import static com.danisola.restify.url.types.IntVar.intVar;
import static com.danisola.restify.url.types.StrVar.strVar;
package com.danisola.restify.url;
public class RestParserTest {
@Test(expected = IllegalStateException.class)
public void whenParameterValueHasNoVariableThenExceptionIsThrown() { | parser("/countries/{}?city=lon", strVar("GB")); |
danisola/restify | url/src/test/java/com/danisola/restify/url/RestParserTest.java | // Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
// public static RestParser parser(String pattern, VarType... types) {
// checkPattern(pattern);
//
// final int numTypes = types.length;
// ParsedUrl parsedUrl = parseUrl(pattern);
// StringBuilder sb = new StringBuilder();
//
// // Processing path
// int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
// Pattern pathPattern = Pattern.compile(sb.toString());
// VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
//
// // Processing parameters
// List<NameValuePair> params = parsedUrl.getParameters();
// ParamVar[] paramVars = new ParamVar[params.size()];
// int paramVarCounter = 0;
// for (int i = 0; i < paramVars.length; i++) {
// NameValuePair pair = params.get(i);
//
// int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue());
// checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName());
//
// VarType[] paramTypes = Arrays.copyOfRange(types, typesIndex, newTypesIndex);
// Pattern paramValuePattern = Pattern.compile(sb.toString());
// paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
// paramVarCounter += newTypesIndex - typesIndex;
// typesIndex = newTypesIndex;
// }
//
// final int numVars = pathTypes.length + paramVarCounter;
// checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
// return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/IntVar.java
// public static IntVar intVar(String id) {
// return new IntVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
// public static StrVar strVar(String id) {
// return new StrVar(id);
// }
| import org.junit.Test;
import static com.danisola.restify.url.RestParserFactory.parser;
import static com.danisola.restify.url.types.IntVar.intVar;
import static com.danisola.restify.url.types.StrVar.strVar; | parser("/country/{}#economy", strVar("countryId"));
}
@Test(expected = IllegalStateException.class)
public void whenMoreVariablesThanTypesThenExceptionIsThrown() {
parser("/country/{}/city/{}", strVar("countryId"));
}
@Test(expected = IllegalStateException.class)
public void whenMoreTypesThanVariablesThenExceptionIsThrown() {
parser("/country/{}", strVar("countryId"), strVar("cityId"));
}
@Test(expected = IllegalArgumentException.class)
public void whenPatternEndsInSlashThenExceptionIsThrown() {
parser("/country/{}/", strVar("countryId"));
}
@Test(expected = IllegalArgumentException.class)
public void whenBracesAreNotClosedInPathThenExceptionIsThrown() {
parser("/country/{/city", strVar("countryId"));
}
@Test(expected = IllegalArgumentException.class)
public void whenBracesAreNotOpenedInPathThenExceptionIsThrown() {
parser("/country/}city", strVar("countryId"));
}
@Test(expected = IllegalArgumentException.class)
public void whenBracesAreNotClosedInParamsThenExceptionIsThrown() { | // Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
// public static RestParser parser(String pattern, VarType... types) {
// checkPattern(pattern);
//
// final int numTypes = types.length;
// ParsedUrl parsedUrl = parseUrl(pattern);
// StringBuilder sb = new StringBuilder();
//
// // Processing path
// int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
// Pattern pathPattern = Pattern.compile(sb.toString());
// VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
//
// // Processing parameters
// List<NameValuePair> params = parsedUrl.getParameters();
// ParamVar[] paramVars = new ParamVar[params.size()];
// int paramVarCounter = 0;
// for (int i = 0; i < paramVars.length; i++) {
// NameValuePair pair = params.get(i);
//
// int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue());
// checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName());
//
// VarType[] paramTypes = Arrays.copyOfRange(types, typesIndex, newTypesIndex);
// Pattern paramValuePattern = Pattern.compile(sb.toString());
// paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
// paramVarCounter += newTypesIndex - typesIndex;
// typesIndex = newTypesIndex;
// }
//
// final int numVars = pathTypes.length + paramVarCounter;
// checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
// return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/IntVar.java
// public static IntVar intVar(String id) {
// return new IntVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
// public static StrVar strVar(String id) {
// return new StrVar(id);
// }
// Path: url/src/test/java/com/danisola/restify/url/RestParserTest.java
import org.junit.Test;
import static com.danisola.restify.url.RestParserFactory.parser;
import static com.danisola.restify.url.types.IntVar.intVar;
import static com.danisola.restify.url.types.StrVar.strVar;
parser("/country/{}#economy", strVar("countryId"));
}
@Test(expected = IllegalStateException.class)
public void whenMoreVariablesThanTypesThenExceptionIsThrown() {
parser("/country/{}/city/{}", strVar("countryId"));
}
@Test(expected = IllegalStateException.class)
public void whenMoreTypesThanVariablesThenExceptionIsThrown() {
parser("/country/{}", strVar("countryId"), strVar("cityId"));
}
@Test(expected = IllegalArgumentException.class)
public void whenPatternEndsInSlashThenExceptionIsThrown() {
parser("/country/{}/", strVar("countryId"));
}
@Test(expected = IllegalArgumentException.class)
public void whenBracesAreNotClosedInPathThenExceptionIsThrown() {
parser("/country/{/city", strVar("countryId"));
}
@Test(expected = IllegalArgumentException.class)
public void whenBracesAreNotOpenedInPathThenExceptionIsThrown() {
parser("/country/}city", strVar("countryId"));
}
@Test(expected = IllegalArgumentException.class)
public void whenBracesAreNotClosedInParamsThenExceptionIsThrown() { | parser("/country?countryId=}&population={}", strVar("countryId"), intVar("population")); |
danisola/restify | url/src/main/java/com/danisola/restify/url/NameValuePair.java | // Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static String checkArgumentNotNullOrEmpty(String string) {
// if (string == null || string.isEmpty()) {
// throw new IllegalArgumentException("Argument cannot be null or empty");
// }
// return string;
// }
| import static com.danisola.restify.url.preconditions.Preconditions.checkArgumentNotNullOrEmpty; | package com.danisola.restify.url;
class NameValuePair {
private final String name;
private final String value;
public NameValuePair(String name, String value) { | // Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static String checkArgumentNotNullOrEmpty(String string) {
// if (string == null || string.isEmpty()) {
// throw new IllegalArgumentException("Argument cannot be null or empty");
// }
// return string;
// }
// Path: url/src/main/java/com/danisola/restify/url/NameValuePair.java
import static com.danisola.restify.url.preconditions.Preconditions.checkArgumentNotNullOrEmpty;
package com.danisola.restify.url;
class NameValuePair {
private final String name;
private final String value;
public NameValuePair(String name, String value) { | this.name = checkArgumentNotNullOrEmpty(name); |
danisola/restify | url/src/main/java/com/danisola/restify/url/RestParserFactory.java | // Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/ParsedUrl.java
// static ParsedUrl parseUrl(String url) {
// String path, queryString;
//
// int questionIndex = url.indexOf("?");
// if (questionIndex >= 0) {
// path = url.substring(0, questionIndex);
// queryString = url.substring(questionIndex + 1);
// } else {
// path = url;
// queryString = null;
// }
//
// return new ParsedUrl(path, parseParams(queryString));
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkArgument(boolean expression, String errorMessage) {
// if (!expression) {
// throw new IllegalArgumentException(errorMessage);
// }
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static String checkArgumentNotNullOrEmpty(String string) {
// if (string == null || string.isEmpty()) {
// throw new IllegalArgumentException("Argument cannot be null or empty");
// }
// return string;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkState(boolean expression, String errorMessageFormat, Object ... args) {
// if (!expression) {
// throw new IllegalStateException(String.format(errorMessageFormat, args));
// }
// }
| import com.danisola.restify.url.types.VarType;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import static com.danisola.restify.url.ParsedUrl.parseUrl;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgument;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgumentNotNullOrEmpty;
import static com.danisola.restify.url.preconditions.Preconditions.checkState; | package com.danisola.restify.url;
/**
* Generates instances of {@link RestParser}.
*/
public class RestParserFactory {
private static final String VAR_MARKER = "{}";
private static final int VAR_MARKER_LENGTH = VAR_MARKER.length();
private static final Pattern MARKER_VALIDATOR = Pattern.compile(".*?(\\{[^\\}]|[^\\{]\\}).*?");
/**
* Generates a {@link RestParser} given a pattern and variable types. See usage examples in <a
* href="https://bitbucket.org/danisola/url-restify/">https://bitbucket.org/danisola/url-restify/</a>.
*
* <p>This method throws exceptions when the pattern or the variables are not correctly defined to enforce a
* correct usage of the API. However, cannot protect from all possible malformed patterns,
* make sure to test them.</p>
*
* @throws IllegalArgumentException if the pattern is malformed or if the pattern and types do not match
* @throws NullPointerException if the pattern or types are null
*/ | // Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/ParsedUrl.java
// static ParsedUrl parseUrl(String url) {
// String path, queryString;
//
// int questionIndex = url.indexOf("?");
// if (questionIndex >= 0) {
// path = url.substring(0, questionIndex);
// queryString = url.substring(questionIndex + 1);
// } else {
// path = url;
// queryString = null;
// }
//
// return new ParsedUrl(path, parseParams(queryString));
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkArgument(boolean expression, String errorMessage) {
// if (!expression) {
// throw new IllegalArgumentException(errorMessage);
// }
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static String checkArgumentNotNullOrEmpty(String string) {
// if (string == null || string.isEmpty()) {
// throw new IllegalArgumentException("Argument cannot be null or empty");
// }
// return string;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkState(boolean expression, String errorMessageFormat, Object ... args) {
// if (!expression) {
// throw new IllegalStateException(String.format(errorMessageFormat, args));
// }
// }
// Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
import com.danisola.restify.url.types.VarType;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import static com.danisola.restify.url.ParsedUrl.parseUrl;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgument;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgumentNotNullOrEmpty;
import static com.danisola.restify.url.preconditions.Preconditions.checkState;
package com.danisola.restify.url;
/**
* Generates instances of {@link RestParser}.
*/
public class RestParserFactory {
private static final String VAR_MARKER = "{}";
private static final int VAR_MARKER_LENGTH = VAR_MARKER.length();
private static final Pattern MARKER_VALIDATOR = Pattern.compile(".*?(\\{[^\\}]|[^\\{]\\}).*?");
/**
* Generates a {@link RestParser} given a pattern and variable types. See usage examples in <a
* href="https://bitbucket.org/danisola/url-restify/">https://bitbucket.org/danisola/url-restify/</a>.
*
* <p>This method throws exceptions when the pattern or the variables are not correctly defined to enforce a
* correct usage of the API. However, cannot protect from all possible malformed patterns,
* make sure to test them.</p>
*
* @throws IllegalArgumentException if the pattern is malformed or if the pattern and types do not match
* @throws NullPointerException if the pattern or types are null
*/ | public static RestParser parser(String pattern, VarType... types) { |
danisola/restify | url/src/main/java/com/danisola/restify/url/RestParserFactory.java | // Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/ParsedUrl.java
// static ParsedUrl parseUrl(String url) {
// String path, queryString;
//
// int questionIndex = url.indexOf("?");
// if (questionIndex >= 0) {
// path = url.substring(0, questionIndex);
// queryString = url.substring(questionIndex + 1);
// } else {
// path = url;
// queryString = null;
// }
//
// return new ParsedUrl(path, parseParams(queryString));
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkArgument(boolean expression, String errorMessage) {
// if (!expression) {
// throw new IllegalArgumentException(errorMessage);
// }
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static String checkArgumentNotNullOrEmpty(String string) {
// if (string == null || string.isEmpty()) {
// throw new IllegalArgumentException("Argument cannot be null or empty");
// }
// return string;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkState(boolean expression, String errorMessageFormat, Object ... args) {
// if (!expression) {
// throw new IllegalStateException(String.format(errorMessageFormat, args));
// }
// }
| import com.danisola.restify.url.types.VarType;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import static com.danisola.restify.url.ParsedUrl.parseUrl;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgument;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgumentNotNullOrEmpty;
import static com.danisola.restify.url.preconditions.Preconditions.checkState; | package com.danisola.restify.url;
/**
* Generates instances of {@link RestParser}.
*/
public class RestParserFactory {
private static final String VAR_MARKER = "{}";
private static final int VAR_MARKER_LENGTH = VAR_MARKER.length();
private static final Pattern MARKER_VALIDATOR = Pattern.compile(".*?(\\{[^\\}]|[^\\{]\\}).*?");
/**
* Generates a {@link RestParser} given a pattern and variable types. See usage examples in <a
* href="https://bitbucket.org/danisola/url-restify/">https://bitbucket.org/danisola/url-restify/</a>.
*
* <p>This method throws exceptions when the pattern or the variables are not correctly defined to enforce a
* correct usage of the API. However, cannot protect from all possible malformed patterns,
* make sure to test them.</p>
*
* @throws IllegalArgumentException if the pattern is malformed or if the pattern and types do not match
* @throws NullPointerException if the pattern or types are null
*/
public static RestParser parser(String pattern, VarType... types) {
checkPattern(pattern);
final int numTypes = types.length; | // Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/ParsedUrl.java
// static ParsedUrl parseUrl(String url) {
// String path, queryString;
//
// int questionIndex = url.indexOf("?");
// if (questionIndex >= 0) {
// path = url.substring(0, questionIndex);
// queryString = url.substring(questionIndex + 1);
// } else {
// path = url;
// queryString = null;
// }
//
// return new ParsedUrl(path, parseParams(queryString));
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkArgument(boolean expression, String errorMessage) {
// if (!expression) {
// throw new IllegalArgumentException(errorMessage);
// }
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static String checkArgumentNotNullOrEmpty(String string) {
// if (string == null || string.isEmpty()) {
// throw new IllegalArgumentException("Argument cannot be null or empty");
// }
// return string;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkState(boolean expression, String errorMessageFormat, Object ... args) {
// if (!expression) {
// throw new IllegalStateException(String.format(errorMessageFormat, args));
// }
// }
// Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
import com.danisola.restify.url.types.VarType;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import static com.danisola.restify.url.ParsedUrl.parseUrl;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgument;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgumentNotNullOrEmpty;
import static com.danisola.restify.url.preconditions.Preconditions.checkState;
package com.danisola.restify.url;
/**
* Generates instances of {@link RestParser}.
*/
public class RestParserFactory {
private static final String VAR_MARKER = "{}";
private static final int VAR_MARKER_LENGTH = VAR_MARKER.length();
private static final Pattern MARKER_VALIDATOR = Pattern.compile(".*?(\\{[^\\}]|[^\\{]\\}).*?");
/**
* Generates a {@link RestParser} given a pattern and variable types. See usage examples in <a
* href="https://bitbucket.org/danisola/url-restify/">https://bitbucket.org/danisola/url-restify/</a>.
*
* <p>This method throws exceptions when the pattern or the variables are not correctly defined to enforce a
* correct usage of the API. However, cannot protect from all possible malformed patterns,
* make sure to test them.</p>
*
* @throws IllegalArgumentException if the pattern is malformed or if the pattern and types do not match
* @throws NullPointerException if the pattern or types are null
*/
public static RestParser parser(String pattern, VarType... types) {
checkPattern(pattern);
final int numTypes = types.length; | ParsedUrl parsedUrl = parseUrl(pattern); |
danisola/restify | url/src/main/java/com/danisola/restify/url/RestParserFactory.java | // Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/ParsedUrl.java
// static ParsedUrl parseUrl(String url) {
// String path, queryString;
//
// int questionIndex = url.indexOf("?");
// if (questionIndex >= 0) {
// path = url.substring(0, questionIndex);
// queryString = url.substring(questionIndex + 1);
// } else {
// path = url;
// queryString = null;
// }
//
// return new ParsedUrl(path, parseParams(queryString));
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkArgument(boolean expression, String errorMessage) {
// if (!expression) {
// throw new IllegalArgumentException(errorMessage);
// }
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static String checkArgumentNotNullOrEmpty(String string) {
// if (string == null || string.isEmpty()) {
// throw new IllegalArgumentException("Argument cannot be null or empty");
// }
// return string;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkState(boolean expression, String errorMessageFormat, Object ... args) {
// if (!expression) {
// throw new IllegalStateException(String.format(errorMessageFormat, args));
// }
// }
| import com.danisola.restify.url.types.VarType;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import static com.danisola.restify.url.ParsedUrl.parseUrl;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgument;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgumentNotNullOrEmpty;
import static com.danisola.restify.url.preconditions.Preconditions.checkState; | package com.danisola.restify.url;
/**
* Generates instances of {@link RestParser}.
*/
public class RestParserFactory {
private static final String VAR_MARKER = "{}";
private static final int VAR_MARKER_LENGTH = VAR_MARKER.length();
private static final Pattern MARKER_VALIDATOR = Pattern.compile(".*?(\\{[^\\}]|[^\\{]\\}).*?");
/**
* Generates a {@link RestParser} given a pattern and variable types. See usage examples in <a
* href="https://bitbucket.org/danisola/url-restify/">https://bitbucket.org/danisola/url-restify/</a>.
*
* <p>This method throws exceptions when the pattern or the variables are not correctly defined to enforce a
* correct usage of the API. However, cannot protect from all possible malformed patterns,
* make sure to test them.</p>
*
* @throws IllegalArgumentException if the pattern is malformed or if the pattern and types do not match
* @throws NullPointerException if the pattern or types are null
*/
public static RestParser parser(String pattern, VarType... types) {
checkPattern(pattern);
final int numTypes = types.length;
ParsedUrl parsedUrl = parseUrl(pattern);
StringBuilder sb = new StringBuilder();
// Processing path
int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
Pattern pathPattern = Pattern.compile(sb.toString());
VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
// Processing parameters
List<NameValuePair> params = parsedUrl.getParameters();
ParamVar[] paramVars = new ParamVar[params.size()];
int paramVarCounter = 0;
for (int i = 0; i < paramVars.length; i++) {
NameValuePair pair = params.get(i);
int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue()); | // Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/ParsedUrl.java
// static ParsedUrl parseUrl(String url) {
// String path, queryString;
//
// int questionIndex = url.indexOf("?");
// if (questionIndex >= 0) {
// path = url.substring(0, questionIndex);
// queryString = url.substring(questionIndex + 1);
// } else {
// path = url;
// queryString = null;
// }
//
// return new ParsedUrl(path, parseParams(queryString));
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkArgument(boolean expression, String errorMessage) {
// if (!expression) {
// throw new IllegalArgumentException(errorMessage);
// }
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static String checkArgumentNotNullOrEmpty(String string) {
// if (string == null || string.isEmpty()) {
// throw new IllegalArgumentException("Argument cannot be null or empty");
// }
// return string;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkState(boolean expression, String errorMessageFormat, Object ... args) {
// if (!expression) {
// throw new IllegalStateException(String.format(errorMessageFormat, args));
// }
// }
// Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
import com.danisola.restify.url.types.VarType;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import static com.danisola.restify.url.ParsedUrl.parseUrl;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgument;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgumentNotNullOrEmpty;
import static com.danisola.restify.url.preconditions.Preconditions.checkState;
package com.danisola.restify.url;
/**
* Generates instances of {@link RestParser}.
*/
public class RestParserFactory {
private static final String VAR_MARKER = "{}";
private static final int VAR_MARKER_LENGTH = VAR_MARKER.length();
private static final Pattern MARKER_VALIDATOR = Pattern.compile(".*?(\\{[^\\}]|[^\\{]\\}).*?");
/**
* Generates a {@link RestParser} given a pattern and variable types. See usage examples in <a
* href="https://bitbucket.org/danisola/url-restify/">https://bitbucket.org/danisola/url-restify/</a>.
*
* <p>This method throws exceptions when the pattern or the variables are not correctly defined to enforce a
* correct usage of the API. However, cannot protect from all possible malformed patterns,
* make sure to test them.</p>
*
* @throws IllegalArgumentException if the pattern is malformed or if the pattern and types do not match
* @throws NullPointerException if the pattern or types are null
*/
public static RestParser parser(String pattern, VarType... types) {
checkPattern(pattern);
final int numTypes = types.length;
ParsedUrl parsedUrl = parseUrl(pattern);
StringBuilder sb = new StringBuilder();
// Processing path
int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
Pattern pathPattern = Pattern.compile(sb.toString());
VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
// Processing parameters
List<NameValuePair> params = parsedUrl.getParameters();
ParamVar[] paramVars = new ParamVar[params.size()];
int paramVarCounter = 0;
for (int i = 0; i < paramVars.length; i++) {
NameValuePair pair = params.get(i);
int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue()); | checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName()); |
danisola/restify | url/src/main/java/com/danisola/restify/url/RestParserFactory.java | // Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/ParsedUrl.java
// static ParsedUrl parseUrl(String url) {
// String path, queryString;
//
// int questionIndex = url.indexOf("?");
// if (questionIndex >= 0) {
// path = url.substring(0, questionIndex);
// queryString = url.substring(questionIndex + 1);
// } else {
// path = url;
// queryString = null;
// }
//
// return new ParsedUrl(path, parseParams(queryString));
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkArgument(boolean expression, String errorMessage) {
// if (!expression) {
// throw new IllegalArgumentException(errorMessage);
// }
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static String checkArgumentNotNullOrEmpty(String string) {
// if (string == null || string.isEmpty()) {
// throw new IllegalArgumentException("Argument cannot be null or empty");
// }
// return string;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkState(boolean expression, String errorMessageFormat, Object ... args) {
// if (!expression) {
// throw new IllegalStateException(String.format(errorMessageFormat, args));
// }
// }
| import com.danisola.restify.url.types.VarType;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import static com.danisola.restify.url.ParsedUrl.parseUrl;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgument;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgumentNotNullOrEmpty;
import static com.danisola.restify.url.preconditions.Preconditions.checkState; | Pattern paramValuePattern = Pattern.compile(sb.toString());
paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
paramVarCounter += newTypesIndex - typesIndex;
typesIndex = newTypesIndex;
}
final int numVars = pathTypes.length + paramVarCounter;
checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
}
private static int processMarkers(VarType[] types, int typesIndex, StringBuilder sb, String values) {
sb.setLength(0);
sb.append("^").append(values);
int pathVarsIndex = sb.indexOf(VAR_MARKER);
while (pathVarsIndex >= 0) {
checkState(typesIndex < types.length, "There are more variables in the pattern than types");
String varPattern = types[typesIndex].getVarPattern();
sb.replace(pathVarsIndex, pathVarsIndex + VAR_MARKER_LENGTH, varPattern);
pathVarsIndex = sb.indexOf(VAR_MARKER, pathVarsIndex + varPattern.length());
typesIndex++;
}
sb.append("$");
return typesIndex;
}
private static void checkPattern(String pattern) { | // Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/ParsedUrl.java
// static ParsedUrl parseUrl(String url) {
// String path, queryString;
//
// int questionIndex = url.indexOf("?");
// if (questionIndex >= 0) {
// path = url.substring(0, questionIndex);
// queryString = url.substring(questionIndex + 1);
// } else {
// path = url;
// queryString = null;
// }
//
// return new ParsedUrl(path, parseParams(queryString));
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkArgument(boolean expression, String errorMessage) {
// if (!expression) {
// throw new IllegalArgumentException(errorMessage);
// }
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static String checkArgumentNotNullOrEmpty(String string) {
// if (string == null || string.isEmpty()) {
// throw new IllegalArgumentException("Argument cannot be null or empty");
// }
// return string;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkState(boolean expression, String errorMessageFormat, Object ... args) {
// if (!expression) {
// throw new IllegalStateException(String.format(errorMessageFormat, args));
// }
// }
// Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
import com.danisola.restify.url.types.VarType;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import static com.danisola.restify.url.ParsedUrl.parseUrl;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgument;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgumentNotNullOrEmpty;
import static com.danisola.restify.url.preconditions.Preconditions.checkState;
Pattern paramValuePattern = Pattern.compile(sb.toString());
paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
paramVarCounter += newTypesIndex - typesIndex;
typesIndex = newTypesIndex;
}
final int numVars = pathTypes.length + paramVarCounter;
checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
}
private static int processMarkers(VarType[] types, int typesIndex, StringBuilder sb, String values) {
sb.setLength(0);
sb.append("^").append(values);
int pathVarsIndex = sb.indexOf(VAR_MARKER);
while (pathVarsIndex >= 0) {
checkState(typesIndex < types.length, "There are more variables in the pattern than types");
String varPattern = types[typesIndex].getVarPattern();
sb.replace(pathVarsIndex, pathVarsIndex + VAR_MARKER_LENGTH, varPattern);
pathVarsIndex = sb.indexOf(VAR_MARKER, pathVarsIndex + varPattern.length());
typesIndex++;
}
sb.append("$");
return typesIndex;
}
private static void checkPattern(String pattern) { | checkArgumentNotNullOrEmpty(pattern); |
danisola/restify | url/src/main/java/com/danisola/restify/url/RestParserFactory.java | // Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/ParsedUrl.java
// static ParsedUrl parseUrl(String url) {
// String path, queryString;
//
// int questionIndex = url.indexOf("?");
// if (questionIndex >= 0) {
// path = url.substring(0, questionIndex);
// queryString = url.substring(questionIndex + 1);
// } else {
// path = url;
// queryString = null;
// }
//
// return new ParsedUrl(path, parseParams(queryString));
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkArgument(boolean expression, String errorMessage) {
// if (!expression) {
// throw new IllegalArgumentException(errorMessage);
// }
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static String checkArgumentNotNullOrEmpty(String string) {
// if (string == null || string.isEmpty()) {
// throw new IllegalArgumentException("Argument cannot be null or empty");
// }
// return string;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkState(boolean expression, String errorMessageFormat, Object ... args) {
// if (!expression) {
// throw new IllegalStateException(String.format(errorMessageFormat, args));
// }
// }
| import com.danisola.restify.url.types.VarType;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import static com.danisola.restify.url.ParsedUrl.parseUrl;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgument;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgumentNotNullOrEmpty;
import static com.danisola.restify.url.preconditions.Preconditions.checkState; | paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
paramVarCounter += newTypesIndex - typesIndex;
typesIndex = newTypesIndex;
}
final int numVars = pathTypes.length + paramVarCounter;
checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
}
private static int processMarkers(VarType[] types, int typesIndex, StringBuilder sb, String values) {
sb.setLength(0);
sb.append("^").append(values);
int pathVarsIndex = sb.indexOf(VAR_MARKER);
while (pathVarsIndex >= 0) {
checkState(typesIndex < types.length, "There are more variables in the pattern than types");
String varPattern = types[typesIndex].getVarPattern();
sb.replace(pathVarsIndex, pathVarsIndex + VAR_MARKER_LENGTH, varPattern);
pathVarsIndex = sb.indexOf(VAR_MARKER, pathVarsIndex + varPattern.length());
typesIndex++;
}
sb.append("$");
return typesIndex;
}
private static void checkPattern(String pattern) {
checkArgumentNotNullOrEmpty(pattern); | // Path: url/src/main/java/com/danisola/restify/url/types/VarType.java
// public interface VarType<T> {
//
// public String getId();
//
// public String getVarPattern();
//
// public T convert(String value) throws Exception;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/ParsedUrl.java
// static ParsedUrl parseUrl(String url) {
// String path, queryString;
//
// int questionIndex = url.indexOf("?");
// if (questionIndex >= 0) {
// path = url.substring(0, questionIndex);
// queryString = url.substring(questionIndex + 1);
// } else {
// path = url;
// queryString = null;
// }
//
// return new ParsedUrl(path, parseParams(queryString));
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkArgument(boolean expression, String errorMessage) {
// if (!expression) {
// throw new IllegalArgumentException(errorMessage);
// }
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static String checkArgumentNotNullOrEmpty(String string) {
// if (string == null || string.isEmpty()) {
// throw new IllegalArgumentException("Argument cannot be null or empty");
// }
// return string;
// }
//
// Path: url/src/main/java/com/danisola/restify/url/preconditions/Preconditions.java
// public static void checkState(boolean expression, String errorMessageFormat, Object ... args) {
// if (!expression) {
// throw new IllegalStateException(String.format(errorMessageFormat, args));
// }
// }
// Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
import com.danisola.restify.url.types.VarType;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import static com.danisola.restify.url.ParsedUrl.parseUrl;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgument;
import static com.danisola.restify.url.preconditions.Preconditions.checkArgumentNotNullOrEmpty;
import static com.danisola.restify.url.preconditions.Preconditions.checkState;
paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
paramVarCounter += newTypesIndex - typesIndex;
typesIndex = newTypesIndex;
}
final int numVars = pathTypes.length + paramVarCounter;
checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
}
private static int processMarkers(VarType[] types, int typesIndex, StringBuilder sb, String values) {
sb.setLength(0);
sb.append("^").append(values);
int pathVarsIndex = sb.indexOf(VAR_MARKER);
while (pathVarsIndex >= 0) {
checkState(typesIndex < types.length, "There are more variables in the pattern than types");
String varPattern = types[typesIndex].getVarPattern();
sb.replace(pathVarsIndex, pathVarsIndex + VAR_MARKER_LENGTH, varPattern);
pathVarsIndex = sb.indexOf(VAR_MARKER, pathVarsIndex + varPattern.length());
typesIndex++;
}
sb.append("$");
return typesIndex;
}
private static void checkPattern(String pattern) {
checkArgumentNotNullOrEmpty(pattern); | checkArgument(!pattern.endsWith("/"), "Patterns must not end with /"); |
danisola/restify | url/src/test/java/com/danisola/restify/url/RestUrlTest.java | // Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
// public static RestParser parser(String pattern, VarType... types) {
// checkPattern(pattern);
//
// final int numTypes = types.length;
// ParsedUrl parsedUrl = parseUrl(pattern);
// StringBuilder sb = new StringBuilder();
//
// // Processing path
// int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
// Pattern pathPattern = Pattern.compile(sb.toString());
// VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
//
// // Processing parameters
// List<NameValuePair> params = parsedUrl.getParameters();
// ParamVar[] paramVars = new ParamVar[params.size()];
// int paramVarCounter = 0;
// for (int i = 0; i < paramVars.length; i++) {
// NameValuePair pair = params.get(i);
//
// int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue());
// checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName());
//
// VarType[] paramTypes = Arrays.copyOfRange(types, typesIndex, newTypesIndex);
// Pattern paramValuePattern = Pattern.compile(sb.toString());
// paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
// paramVarCounter += newTypesIndex - typesIndex;
// typesIndex = newTypesIndex;
// }
//
// final int numVars = pathTypes.length + paramVarCounter;
// checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
// return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
// }
//
// Path: url/src/test/java/com/danisola/restify/url/matchers/IsInvalid.java
// public static IsInvalid isInvalid() {
// return new IsInvalid();
// }
//
// Path: url/src/test/java/com/danisola/restify/url/matchers/IsValid.java
// public static IsValid isValid() {
// return new IsValid();
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/FloatVar.java
// public static FloatVar floatVar(String id) {
// return new FloatVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/IntVar.java
// public static IntVar intVar(String id) {
// return new IntVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
// public static StrVar strVar(String id) {
// return new StrVar(id);
// }
| import org.junit.Test;
import java.net.URL;
import static com.danisola.restify.url.RestParserFactory.parser;
import static com.danisola.restify.url.matchers.IsInvalid.isInvalid;
import static com.danisola.restify.url.matchers.IsValid.isValid;
import static com.danisola.restify.url.types.FloatVar.floatVar;
import static com.danisola.restify.url.types.IntVar.intVar;
import static com.danisola.restify.url.types.StrVar.strVar;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertTrue; | package com.danisola.restify.url;
public class RestUrlTest {
@Test
public void whenMultipleParametersAreRequestedThenItsValuesAreCorrect() { | // Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
// public static RestParser parser(String pattern, VarType... types) {
// checkPattern(pattern);
//
// final int numTypes = types.length;
// ParsedUrl parsedUrl = parseUrl(pattern);
// StringBuilder sb = new StringBuilder();
//
// // Processing path
// int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
// Pattern pathPattern = Pattern.compile(sb.toString());
// VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
//
// // Processing parameters
// List<NameValuePair> params = parsedUrl.getParameters();
// ParamVar[] paramVars = new ParamVar[params.size()];
// int paramVarCounter = 0;
// for (int i = 0; i < paramVars.length; i++) {
// NameValuePair pair = params.get(i);
//
// int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue());
// checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName());
//
// VarType[] paramTypes = Arrays.copyOfRange(types, typesIndex, newTypesIndex);
// Pattern paramValuePattern = Pattern.compile(sb.toString());
// paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
// paramVarCounter += newTypesIndex - typesIndex;
// typesIndex = newTypesIndex;
// }
//
// final int numVars = pathTypes.length + paramVarCounter;
// checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
// return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
// }
//
// Path: url/src/test/java/com/danisola/restify/url/matchers/IsInvalid.java
// public static IsInvalid isInvalid() {
// return new IsInvalid();
// }
//
// Path: url/src/test/java/com/danisola/restify/url/matchers/IsValid.java
// public static IsValid isValid() {
// return new IsValid();
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/FloatVar.java
// public static FloatVar floatVar(String id) {
// return new FloatVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/IntVar.java
// public static IntVar intVar(String id) {
// return new IntVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
// public static StrVar strVar(String id) {
// return new StrVar(id);
// }
// Path: url/src/test/java/com/danisola/restify/url/RestUrlTest.java
import org.junit.Test;
import java.net.URL;
import static com.danisola.restify.url.RestParserFactory.parser;
import static com.danisola.restify.url.matchers.IsInvalid.isInvalid;
import static com.danisola.restify.url.matchers.IsValid.isValid;
import static com.danisola.restify.url.types.FloatVar.floatVar;
import static com.danisola.restify.url.types.IntVar.intVar;
import static com.danisola.restify.url.types.StrVar.strVar;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertTrue;
package com.danisola.restify.url;
public class RestUrlTest {
@Test
public void whenMultipleParametersAreRequestedThenItsValuesAreCorrect() { | RestParser parser = parser("/{}/{}?float={}&str={}&int={}", |
danisola/restify | url/src/test/java/com/danisola/restify/url/RestUrlTest.java | // Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
// public static RestParser parser(String pattern, VarType... types) {
// checkPattern(pattern);
//
// final int numTypes = types.length;
// ParsedUrl parsedUrl = parseUrl(pattern);
// StringBuilder sb = new StringBuilder();
//
// // Processing path
// int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
// Pattern pathPattern = Pattern.compile(sb.toString());
// VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
//
// // Processing parameters
// List<NameValuePair> params = parsedUrl.getParameters();
// ParamVar[] paramVars = new ParamVar[params.size()];
// int paramVarCounter = 0;
// for (int i = 0; i < paramVars.length; i++) {
// NameValuePair pair = params.get(i);
//
// int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue());
// checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName());
//
// VarType[] paramTypes = Arrays.copyOfRange(types, typesIndex, newTypesIndex);
// Pattern paramValuePattern = Pattern.compile(sb.toString());
// paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
// paramVarCounter += newTypesIndex - typesIndex;
// typesIndex = newTypesIndex;
// }
//
// final int numVars = pathTypes.length + paramVarCounter;
// checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
// return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
// }
//
// Path: url/src/test/java/com/danisola/restify/url/matchers/IsInvalid.java
// public static IsInvalid isInvalid() {
// return new IsInvalid();
// }
//
// Path: url/src/test/java/com/danisola/restify/url/matchers/IsValid.java
// public static IsValid isValid() {
// return new IsValid();
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/FloatVar.java
// public static FloatVar floatVar(String id) {
// return new FloatVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/IntVar.java
// public static IntVar intVar(String id) {
// return new IntVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
// public static StrVar strVar(String id) {
// return new StrVar(id);
// }
| import org.junit.Test;
import java.net.URL;
import static com.danisola.restify.url.RestParserFactory.parser;
import static com.danisola.restify.url.matchers.IsInvalid.isInvalid;
import static com.danisola.restify.url.matchers.IsValid.isValid;
import static com.danisola.restify.url.types.FloatVar.floatVar;
import static com.danisola.restify.url.types.IntVar.intVar;
import static com.danisola.restify.url.types.StrVar.strVar;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertTrue; | package com.danisola.restify.url;
public class RestUrlTest {
@Test
public void whenMultipleParametersAreRequestedThenItsValuesAreCorrect() {
RestParser parser = parser("/{}/{}?float={}&str={}&int={}", | // Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
// public static RestParser parser(String pattern, VarType... types) {
// checkPattern(pattern);
//
// final int numTypes = types.length;
// ParsedUrl parsedUrl = parseUrl(pattern);
// StringBuilder sb = new StringBuilder();
//
// // Processing path
// int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
// Pattern pathPattern = Pattern.compile(sb.toString());
// VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
//
// // Processing parameters
// List<NameValuePair> params = parsedUrl.getParameters();
// ParamVar[] paramVars = new ParamVar[params.size()];
// int paramVarCounter = 0;
// for (int i = 0; i < paramVars.length; i++) {
// NameValuePair pair = params.get(i);
//
// int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue());
// checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName());
//
// VarType[] paramTypes = Arrays.copyOfRange(types, typesIndex, newTypesIndex);
// Pattern paramValuePattern = Pattern.compile(sb.toString());
// paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
// paramVarCounter += newTypesIndex - typesIndex;
// typesIndex = newTypesIndex;
// }
//
// final int numVars = pathTypes.length + paramVarCounter;
// checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
// return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
// }
//
// Path: url/src/test/java/com/danisola/restify/url/matchers/IsInvalid.java
// public static IsInvalid isInvalid() {
// return new IsInvalid();
// }
//
// Path: url/src/test/java/com/danisola/restify/url/matchers/IsValid.java
// public static IsValid isValid() {
// return new IsValid();
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/FloatVar.java
// public static FloatVar floatVar(String id) {
// return new FloatVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/IntVar.java
// public static IntVar intVar(String id) {
// return new IntVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
// public static StrVar strVar(String id) {
// return new StrVar(id);
// }
// Path: url/src/test/java/com/danisola/restify/url/RestUrlTest.java
import org.junit.Test;
import java.net.URL;
import static com.danisola.restify.url.RestParserFactory.parser;
import static com.danisola.restify.url.matchers.IsInvalid.isInvalid;
import static com.danisola.restify.url.matchers.IsValid.isValid;
import static com.danisola.restify.url.types.FloatVar.floatVar;
import static com.danisola.restify.url.types.IntVar.intVar;
import static com.danisola.restify.url.types.StrVar.strVar;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertTrue;
package com.danisola.restify.url;
public class RestUrlTest {
@Test
public void whenMultipleParametersAreRequestedThenItsValuesAreCorrect() {
RestParser parser = parser("/{}/{}?float={}&str={}&int={}", | strVar("first"), strVar("second"), floatVar("float"), strVar("str"), intVar("int")); |
danisola/restify | url/src/test/java/com/danisola/restify/url/RestUrlTest.java | // Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
// public static RestParser parser(String pattern, VarType... types) {
// checkPattern(pattern);
//
// final int numTypes = types.length;
// ParsedUrl parsedUrl = parseUrl(pattern);
// StringBuilder sb = new StringBuilder();
//
// // Processing path
// int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
// Pattern pathPattern = Pattern.compile(sb.toString());
// VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
//
// // Processing parameters
// List<NameValuePair> params = parsedUrl.getParameters();
// ParamVar[] paramVars = new ParamVar[params.size()];
// int paramVarCounter = 0;
// for (int i = 0; i < paramVars.length; i++) {
// NameValuePair pair = params.get(i);
//
// int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue());
// checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName());
//
// VarType[] paramTypes = Arrays.copyOfRange(types, typesIndex, newTypesIndex);
// Pattern paramValuePattern = Pattern.compile(sb.toString());
// paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
// paramVarCounter += newTypesIndex - typesIndex;
// typesIndex = newTypesIndex;
// }
//
// final int numVars = pathTypes.length + paramVarCounter;
// checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
// return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
// }
//
// Path: url/src/test/java/com/danisola/restify/url/matchers/IsInvalid.java
// public static IsInvalid isInvalid() {
// return new IsInvalid();
// }
//
// Path: url/src/test/java/com/danisola/restify/url/matchers/IsValid.java
// public static IsValid isValid() {
// return new IsValid();
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/FloatVar.java
// public static FloatVar floatVar(String id) {
// return new FloatVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/IntVar.java
// public static IntVar intVar(String id) {
// return new IntVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
// public static StrVar strVar(String id) {
// return new StrVar(id);
// }
| import org.junit.Test;
import java.net.URL;
import static com.danisola.restify.url.RestParserFactory.parser;
import static com.danisola.restify.url.matchers.IsInvalid.isInvalid;
import static com.danisola.restify.url.matchers.IsValid.isValid;
import static com.danisola.restify.url.types.FloatVar.floatVar;
import static com.danisola.restify.url.types.IntVar.intVar;
import static com.danisola.restify.url.types.StrVar.strVar;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertTrue; | package com.danisola.restify.url;
public class RestUrlTest {
@Test
public void whenMultipleParametersAreRequestedThenItsValuesAreCorrect() {
RestParser parser = parser("/{}/{}?float={}&str={}&int={}", | // Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
// public static RestParser parser(String pattern, VarType... types) {
// checkPattern(pattern);
//
// final int numTypes = types.length;
// ParsedUrl parsedUrl = parseUrl(pattern);
// StringBuilder sb = new StringBuilder();
//
// // Processing path
// int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
// Pattern pathPattern = Pattern.compile(sb.toString());
// VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
//
// // Processing parameters
// List<NameValuePair> params = parsedUrl.getParameters();
// ParamVar[] paramVars = new ParamVar[params.size()];
// int paramVarCounter = 0;
// for (int i = 0; i < paramVars.length; i++) {
// NameValuePair pair = params.get(i);
//
// int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue());
// checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName());
//
// VarType[] paramTypes = Arrays.copyOfRange(types, typesIndex, newTypesIndex);
// Pattern paramValuePattern = Pattern.compile(sb.toString());
// paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
// paramVarCounter += newTypesIndex - typesIndex;
// typesIndex = newTypesIndex;
// }
//
// final int numVars = pathTypes.length + paramVarCounter;
// checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
// return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
// }
//
// Path: url/src/test/java/com/danisola/restify/url/matchers/IsInvalid.java
// public static IsInvalid isInvalid() {
// return new IsInvalid();
// }
//
// Path: url/src/test/java/com/danisola/restify/url/matchers/IsValid.java
// public static IsValid isValid() {
// return new IsValid();
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/FloatVar.java
// public static FloatVar floatVar(String id) {
// return new FloatVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/IntVar.java
// public static IntVar intVar(String id) {
// return new IntVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
// public static StrVar strVar(String id) {
// return new StrVar(id);
// }
// Path: url/src/test/java/com/danisola/restify/url/RestUrlTest.java
import org.junit.Test;
import java.net.URL;
import static com.danisola.restify.url.RestParserFactory.parser;
import static com.danisola.restify.url.matchers.IsInvalid.isInvalid;
import static com.danisola.restify.url.matchers.IsValid.isValid;
import static com.danisola.restify.url.types.FloatVar.floatVar;
import static com.danisola.restify.url.types.IntVar.intVar;
import static com.danisola.restify.url.types.StrVar.strVar;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertTrue;
package com.danisola.restify.url;
public class RestUrlTest {
@Test
public void whenMultipleParametersAreRequestedThenItsValuesAreCorrect() {
RestParser parser = parser("/{}/{}?float={}&str={}&int={}", | strVar("first"), strVar("second"), floatVar("float"), strVar("str"), intVar("int")); |
danisola/restify | url/src/test/java/com/danisola/restify/url/RestUrlTest.java | // Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
// public static RestParser parser(String pattern, VarType... types) {
// checkPattern(pattern);
//
// final int numTypes = types.length;
// ParsedUrl parsedUrl = parseUrl(pattern);
// StringBuilder sb = new StringBuilder();
//
// // Processing path
// int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
// Pattern pathPattern = Pattern.compile(sb.toString());
// VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
//
// // Processing parameters
// List<NameValuePair> params = parsedUrl.getParameters();
// ParamVar[] paramVars = new ParamVar[params.size()];
// int paramVarCounter = 0;
// for (int i = 0; i < paramVars.length; i++) {
// NameValuePair pair = params.get(i);
//
// int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue());
// checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName());
//
// VarType[] paramTypes = Arrays.copyOfRange(types, typesIndex, newTypesIndex);
// Pattern paramValuePattern = Pattern.compile(sb.toString());
// paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
// paramVarCounter += newTypesIndex - typesIndex;
// typesIndex = newTypesIndex;
// }
//
// final int numVars = pathTypes.length + paramVarCounter;
// checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
// return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
// }
//
// Path: url/src/test/java/com/danisola/restify/url/matchers/IsInvalid.java
// public static IsInvalid isInvalid() {
// return new IsInvalid();
// }
//
// Path: url/src/test/java/com/danisola/restify/url/matchers/IsValid.java
// public static IsValid isValid() {
// return new IsValid();
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/FloatVar.java
// public static FloatVar floatVar(String id) {
// return new FloatVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/IntVar.java
// public static IntVar intVar(String id) {
// return new IntVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
// public static StrVar strVar(String id) {
// return new StrVar(id);
// }
| import org.junit.Test;
import java.net.URL;
import static com.danisola.restify.url.RestParserFactory.parser;
import static com.danisola.restify.url.matchers.IsInvalid.isInvalid;
import static com.danisola.restify.url.matchers.IsValid.isValid;
import static com.danisola.restify.url.types.FloatVar.floatVar;
import static com.danisola.restify.url.types.IntVar.intVar;
import static com.danisola.restify.url.types.StrVar.strVar;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertTrue; | package com.danisola.restify.url;
public class RestUrlTest {
@Test
public void whenMultipleParametersAreRequestedThenItsValuesAreCorrect() {
RestParser parser = parser("/{}/{}?float={}&str={}&int={}", | // Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
// public static RestParser parser(String pattern, VarType... types) {
// checkPattern(pattern);
//
// final int numTypes = types.length;
// ParsedUrl parsedUrl = parseUrl(pattern);
// StringBuilder sb = new StringBuilder();
//
// // Processing path
// int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
// Pattern pathPattern = Pattern.compile(sb.toString());
// VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
//
// // Processing parameters
// List<NameValuePair> params = parsedUrl.getParameters();
// ParamVar[] paramVars = new ParamVar[params.size()];
// int paramVarCounter = 0;
// for (int i = 0; i < paramVars.length; i++) {
// NameValuePair pair = params.get(i);
//
// int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue());
// checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName());
//
// VarType[] paramTypes = Arrays.copyOfRange(types, typesIndex, newTypesIndex);
// Pattern paramValuePattern = Pattern.compile(sb.toString());
// paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
// paramVarCounter += newTypesIndex - typesIndex;
// typesIndex = newTypesIndex;
// }
//
// final int numVars = pathTypes.length + paramVarCounter;
// checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
// return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
// }
//
// Path: url/src/test/java/com/danisola/restify/url/matchers/IsInvalid.java
// public static IsInvalid isInvalid() {
// return new IsInvalid();
// }
//
// Path: url/src/test/java/com/danisola/restify/url/matchers/IsValid.java
// public static IsValid isValid() {
// return new IsValid();
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/FloatVar.java
// public static FloatVar floatVar(String id) {
// return new FloatVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/IntVar.java
// public static IntVar intVar(String id) {
// return new IntVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
// public static StrVar strVar(String id) {
// return new StrVar(id);
// }
// Path: url/src/test/java/com/danisola/restify/url/RestUrlTest.java
import org.junit.Test;
import java.net.URL;
import static com.danisola.restify.url.RestParserFactory.parser;
import static com.danisola.restify.url.matchers.IsInvalid.isInvalid;
import static com.danisola.restify.url.matchers.IsValid.isValid;
import static com.danisola.restify.url.types.FloatVar.floatVar;
import static com.danisola.restify.url.types.IntVar.intVar;
import static com.danisola.restify.url.types.StrVar.strVar;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertTrue;
package com.danisola.restify.url;
public class RestUrlTest {
@Test
public void whenMultipleParametersAreRequestedThenItsValuesAreCorrect() {
RestParser parser = parser("/{}/{}?float={}&str={}&int={}", | strVar("first"), strVar("second"), floatVar("float"), strVar("str"), intVar("int")); |
danisola/restify | url/src/test/java/com/danisola/restify/url/RestUrlTest.java | // Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
// public static RestParser parser(String pattern, VarType... types) {
// checkPattern(pattern);
//
// final int numTypes = types.length;
// ParsedUrl parsedUrl = parseUrl(pattern);
// StringBuilder sb = new StringBuilder();
//
// // Processing path
// int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
// Pattern pathPattern = Pattern.compile(sb.toString());
// VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
//
// // Processing parameters
// List<NameValuePair> params = parsedUrl.getParameters();
// ParamVar[] paramVars = new ParamVar[params.size()];
// int paramVarCounter = 0;
// for (int i = 0; i < paramVars.length; i++) {
// NameValuePair pair = params.get(i);
//
// int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue());
// checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName());
//
// VarType[] paramTypes = Arrays.copyOfRange(types, typesIndex, newTypesIndex);
// Pattern paramValuePattern = Pattern.compile(sb.toString());
// paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
// paramVarCounter += newTypesIndex - typesIndex;
// typesIndex = newTypesIndex;
// }
//
// final int numVars = pathTypes.length + paramVarCounter;
// checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
// return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
// }
//
// Path: url/src/test/java/com/danisola/restify/url/matchers/IsInvalid.java
// public static IsInvalid isInvalid() {
// return new IsInvalid();
// }
//
// Path: url/src/test/java/com/danisola/restify/url/matchers/IsValid.java
// public static IsValid isValid() {
// return new IsValid();
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/FloatVar.java
// public static FloatVar floatVar(String id) {
// return new FloatVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/IntVar.java
// public static IntVar intVar(String id) {
// return new IntVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
// public static StrVar strVar(String id) {
// return new StrVar(id);
// }
| import org.junit.Test;
import java.net.URL;
import static com.danisola.restify.url.RestParserFactory.parser;
import static com.danisola.restify.url.matchers.IsInvalid.isInvalid;
import static com.danisola.restify.url.matchers.IsValid.isValid;
import static com.danisola.restify.url.types.FloatVar.floatVar;
import static com.danisola.restify.url.types.IntVar.intVar;
import static com.danisola.restify.url.types.StrVar.strVar;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertTrue; | package com.danisola.restify.url;
public class RestUrlTest {
@Test
public void whenMultipleParametersAreRequestedThenItsValuesAreCorrect() {
RestParser parser = parser("/{}/{}?float={}&str={}&int={}",
strVar("first"), strVar("second"), floatVar("float"), strVar("str"), intVar("int"));
RestUrl url = parser.parse("http://www.example.com/a/b?float=3.14&str=pi&int=3"); | // Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
// public static RestParser parser(String pattern, VarType... types) {
// checkPattern(pattern);
//
// final int numTypes = types.length;
// ParsedUrl parsedUrl = parseUrl(pattern);
// StringBuilder sb = new StringBuilder();
//
// // Processing path
// int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
// Pattern pathPattern = Pattern.compile(sb.toString());
// VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
//
// // Processing parameters
// List<NameValuePair> params = parsedUrl.getParameters();
// ParamVar[] paramVars = new ParamVar[params.size()];
// int paramVarCounter = 0;
// for (int i = 0; i < paramVars.length; i++) {
// NameValuePair pair = params.get(i);
//
// int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue());
// checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName());
//
// VarType[] paramTypes = Arrays.copyOfRange(types, typesIndex, newTypesIndex);
// Pattern paramValuePattern = Pattern.compile(sb.toString());
// paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
// paramVarCounter += newTypesIndex - typesIndex;
// typesIndex = newTypesIndex;
// }
//
// final int numVars = pathTypes.length + paramVarCounter;
// checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
// return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
// }
//
// Path: url/src/test/java/com/danisola/restify/url/matchers/IsInvalid.java
// public static IsInvalid isInvalid() {
// return new IsInvalid();
// }
//
// Path: url/src/test/java/com/danisola/restify/url/matchers/IsValid.java
// public static IsValid isValid() {
// return new IsValid();
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/FloatVar.java
// public static FloatVar floatVar(String id) {
// return new FloatVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/IntVar.java
// public static IntVar intVar(String id) {
// return new IntVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
// public static StrVar strVar(String id) {
// return new StrVar(id);
// }
// Path: url/src/test/java/com/danisola/restify/url/RestUrlTest.java
import org.junit.Test;
import java.net.URL;
import static com.danisola.restify.url.RestParserFactory.parser;
import static com.danisola.restify.url.matchers.IsInvalid.isInvalid;
import static com.danisola.restify.url.matchers.IsValid.isValid;
import static com.danisola.restify.url.types.FloatVar.floatVar;
import static com.danisola.restify.url.types.IntVar.intVar;
import static com.danisola.restify.url.types.StrVar.strVar;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertTrue;
package com.danisola.restify.url;
public class RestUrlTest {
@Test
public void whenMultipleParametersAreRequestedThenItsValuesAreCorrect() {
RestParser parser = parser("/{}/{}?float={}&str={}&int={}",
strVar("first"), strVar("second"), floatVar("float"), strVar("str"), intVar("int"));
RestUrl url = parser.parse("http://www.example.com/a/b?float=3.14&str=pi&int=3"); | assertThat(url, isValid()); |
danisola/restify | url/src/test/java/com/danisola/restify/url/RestUrlTest.java | // Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
// public static RestParser parser(String pattern, VarType... types) {
// checkPattern(pattern);
//
// final int numTypes = types.length;
// ParsedUrl parsedUrl = parseUrl(pattern);
// StringBuilder sb = new StringBuilder();
//
// // Processing path
// int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
// Pattern pathPattern = Pattern.compile(sb.toString());
// VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
//
// // Processing parameters
// List<NameValuePair> params = parsedUrl.getParameters();
// ParamVar[] paramVars = new ParamVar[params.size()];
// int paramVarCounter = 0;
// for (int i = 0; i < paramVars.length; i++) {
// NameValuePair pair = params.get(i);
//
// int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue());
// checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName());
//
// VarType[] paramTypes = Arrays.copyOfRange(types, typesIndex, newTypesIndex);
// Pattern paramValuePattern = Pattern.compile(sb.toString());
// paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
// paramVarCounter += newTypesIndex - typesIndex;
// typesIndex = newTypesIndex;
// }
//
// final int numVars = pathTypes.length + paramVarCounter;
// checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
// return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
// }
//
// Path: url/src/test/java/com/danisola/restify/url/matchers/IsInvalid.java
// public static IsInvalid isInvalid() {
// return new IsInvalid();
// }
//
// Path: url/src/test/java/com/danisola/restify/url/matchers/IsValid.java
// public static IsValid isValid() {
// return new IsValid();
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/FloatVar.java
// public static FloatVar floatVar(String id) {
// return new FloatVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/IntVar.java
// public static IntVar intVar(String id) {
// return new IntVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
// public static StrVar strVar(String id) {
// return new StrVar(id);
// }
| import org.junit.Test;
import java.net.URL;
import static com.danisola.restify.url.RestParserFactory.parser;
import static com.danisola.restify.url.matchers.IsInvalid.isInvalid;
import static com.danisola.restify.url.matchers.IsValid.isValid;
import static com.danisola.restify.url.types.FloatVar.floatVar;
import static com.danisola.restify.url.types.IntVar.intVar;
import static com.danisola.restify.url.types.StrVar.strVar;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertTrue; | @Test
public void whenCompositeParamsAreDefinedThenItsValuesAreCorrect() {
RestParser parser = parser("/battleship/shoot?square={}{}",
strVar("char", "[A-L]"), intVar("num", "[0-9]"));
RestUrl url = parser.parse("http://www.games.com/battleship/shoot?square=B7");
assertThat(url, isValid());
assertThat((String) url.variable("char"), is("B"));
assertThat((Integer) url.variable("num"), is(7));
}
@Test
public void whenNoVariablesAreProvidedThenOnlyThePathIsConsidered() {
RestParser parser = parser("/users");
RestUrl url = parser.parse("http://www.social-network.com/users");
assertThat(url, isValid());
assertTrue(url.isValid());
}
@Test
public void whenThereAreExtraParametersThenSpecifiedOnesAreCorrect() {
RestParser parser = parser("/users?id={}", strVar("userId"));
RestUrl url = parser.parse("http://www.mail.com/users?cache_buster=4f0ce72&id=ben");
assertThat(url, isValid());
assertThat((String) url.variable("userId"), is("ben"));
}
@Test
public void whenVariablesDoNotMatchTheWholeValueThenUrlIsInvalid() {
RestParser parser = parser("/friends?within={}", intVar("kms"));
RestUrl url = parser.parse("http://www.network.com/friends?within=4K"); | // Path: url/src/main/java/com/danisola/restify/url/RestParserFactory.java
// public static RestParser parser(String pattern, VarType... types) {
// checkPattern(pattern);
//
// final int numTypes = types.length;
// ParsedUrl parsedUrl = parseUrl(pattern);
// StringBuilder sb = new StringBuilder();
//
// // Processing path
// int typesIndex = processMarkers(types, 0, sb, parsedUrl.getPath());
// Pattern pathPattern = Pattern.compile(sb.toString());
// VarType[] pathTypes = Arrays.copyOfRange(types, 0, typesIndex);
//
// // Processing parameters
// List<NameValuePair> params = parsedUrl.getParameters();
// ParamVar[] paramVars = new ParamVar[params.size()];
// int paramVarCounter = 0;
// for (int i = 0; i < paramVars.length; i++) {
// NameValuePair pair = params.get(i);
//
// int newTypesIndex = processMarkers(types, typesIndex, sb, pair.getValue());
// checkState(newTypesIndex > typesIndex, "Parameter '%s' has no variables in its value", pair.getName());
//
// VarType[] paramTypes = Arrays.copyOfRange(types, typesIndex, newTypesIndex);
// Pattern paramValuePattern = Pattern.compile(sb.toString());
// paramVars[i] = new ParamVar(pair.getName(), paramTypes, paramValuePattern);
// paramVarCounter += newTypesIndex - typesIndex;
// typesIndex = newTypesIndex;
// }
//
// final int numVars = pathTypes.length + paramVarCounter;
// checkState(numVars == numTypes, "The number of variables (%d) and types (%d) do not match", numVars, numTypes);
// return new RestParser(pathPattern, pathTypes, paramVars, numTypes);
// }
//
// Path: url/src/test/java/com/danisola/restify/url/matchers/IsInvalid.java
// public static IsInvalid isInvalid() {
// return new IsInvalid();
// }
//
// Path: url/src/test/java/com/danisola/restify/url/matchers/IsValid.java
// public static IsValid isValid() {
// return new IsValid();
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/FloatVar.java
// public static FloatVar floatVar(String id) {
// return new FloatVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/IntVar.java
// public static IntVar intVar(String id) {
// return new IntVar(id);
// }
//
// Path: url/src/main/java/com/danisola/restify/url/types/StrVar.java
// public static StrVar strVar(String id) {
// return new StrVar(id);
// }
// Path: url/src/test/java/com/danisola/restify/url/RestUrlTest.java
import org.junit.Test;
import java.net.URL;
import static com.danisola.restify.url.RestParserFactory.parser;
import static com.danisola.restify.url.matchers.IsInvalid.isInvalid;
import static com.danisola.restify.url.matchers.IsValid.isValid;
import static com.danisola.restify.url.types.FloatVar.floatVar;
import static com.danisola.restify.url.types.IntVar.intVar;
import static com.danisola.restify.url.types.StrVar.strVar;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertTrue;
@Test
public void whenCompositeParamsAreDefinedThenItsValuesAreCorrect() {
RestParser parser = parser("/battleship/shoot?square={}{}",
strVar("char", "[A-L]"), intVar("num", "[0-9]"));
RestUrl url = parser.parse("http://www.games.com/battleship/shoot?square=B7");
assertThat(url, isValid());
assertThat((String) url.variable("char"), is("B"));
assertThat((Integer) url.variable("num"), is(7));
}
@Test
public void whenNoVariablesAreProvidedThenOnlyThePathIsConsidered() {
RestParser parser = parser("/users");
RestUrl url = parser.parse("http://www.social-network.com/users");
assertThat(url, isValid());
assertTrue(url.isValid());
}
@Test
public void whenThereAreExtraParametersThenSpecifiedOnesAreCorrect() {
RestParser parser = parser("/users?id={}", strVar("userId"));
RestUrl url = parser.parse("http://www.mail.com/users?cache_buster=4f0ce72&id=ben");
assertThat(url, isValid());
assertThat((String) url.variable("userId"), is("ben"));
}
@Test
public void whenVariablesDoNotMatchTheWholeValueThenUrlIsInvalid() {
RestParser parser = parser("/friends?within={}", intVar("kms"));
RestUrl url = parser.parse("http://www.network.com/friends?within=4K"); | assertThat(url, isInvalid()); |
theblindr/blindr | app/src/com/lesgens/blindr/controllers/Controller.java | // Path: app/src/com/lesgens/blindr/models/City.java
// public class City implements IDestination{
//
// private String name;
//
// public City(String name) {
// this.name = name;
// }
//
// public String getName(){
// return name;
// }
//
// public String getId(){
// return name;
// }
// }
//
// Path: app/src/com/lesgens/blindr/models/Match.java
// public class Match extends Event{
//
// private Boolean isMutual;
// private String fakeName;
//
// public Match(UUID id, Timestamp timestamp, IDestination destination, User user) {
// this(id, timestamp, destination, user, false, null, null);
// }
//
// public Match(UUID id, Timestamp timestamp, IDestination destination, User user, Boolean isMutual, String realName, String fakeName) {
// super(id, timestamp, destination, user, realName, fakeName);
// this.isMutual = isMutual;
// this.fakeName = fakeName;
// }
//
// public User[] getMatchUsers() {
// return new User[]{this.getUser(), (User)this.getDestination()};
// }
//
// public User getMatchedUser(){
// if(!getUser().getId().equals(Controller.getInstance().getMyself().getId())){
// return getUser();
// }
//
// return (User) getDestination();
// }
//
// public Boolean isMutual() {
// return isMutual;
// }
//
// public String getFakeName(){
// return fakeName;
// }
//
// }
//
// Path: app/src/com/lesgens/blindr/models/User.java
// public class User implements IDestination{
// private Bitmap avatar;
// private String name;
// private String tokenId;
//
// public User(String name, Bitmap avatar, String tokenId){
// this.name = name;
// this.avatar = avatar;
// this.tokenId = tokenId;
// }
//
// public Bitmap getAvatar(){
// return avatar;
// }
//
// public String getName(){
// return name;
// }
//
// public String getId() {
// return tokenId;
// }
// }
//
// Path: app/src/com/lesgens/blindr/utils/Utils.java
// public class Utils {
//
// public static final String BLINDR_IMAGE_BASE = "BLINDR_IMAGE_BASE:";
//
// public static int dpInPixels(Context context, int dp) {
// return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources()
// .getDisplayMetrics());
// }
//
// public static Bitmap scaleDown(Bitmap realImage, float maxImageSize,
// boolean filter) {
// float ratio = Math.min(
// (float) maxImageSize / realImage.getWidth(),
// (float) maxImageSize / realImage.getHeight());
// int width = Math.round((float) ratio * realImage.getWidth());
// int height = Math.round((float) ratio * realImage.getHeight());
//
// Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width,
// height, filter);
// return newBitmap;
// }
//
// public static byte[] getByteArrayFromString(String str){
// String[] splitted = str.split(",");
//
// byte[] byteArray = new byte[splitted.length];
//
// for(int i = 0; i < splitted.length; i++){
// byteArray[i] = Byte.valueOf(splitted[i]);
// }
//
// return byteArray;
// }
//
// }
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import com.checkin.avatargenerator.AvatarGenerator;
import com.facebook.Session;
import com.lesgens.blindr.models.City;
import com.lesgens.blindr.models.Match;
import com.lesgens.blindr.models.User;
import com.lesgens.blindr.utils.Utils; | package com.lesgens.blindr.controllers;
public class Controller {
private City city; | // Path: app/src/com/lesgens/blindr/models/City.java
// public class City implements IDestination{
//
// private String name;
//
// public City(String name) {
// this.name = name;
// }
//
// public String getName(){
// return name;
// }
//
// public String getId(){
// return name;
// }
// }
//
// Path: app/src/com/lesgens/blindr/models/Match.java
// public class Match extends Event{
//
// private Boolean isMutual;
// private String fakeName;
//
// public Match(UUID id, Timestamp timestamp, IDestination destination, User user) {
// this(id, timestamp, destination, user, false, null, null);
// }
//
// public Match(UUID id, Timestamp timestamp, IDestination destination, User user, Boolean isMutual, String realName, String fakeName) {
// super(id, timestamp, destination, user, realName, fakeName);
// this.isMutual = isMutual;
// this.fakeName = fakeName;
// }
//
// public User[] getMatchUsers() {
// return new User[]{this.getUser(), (User)this.getDestination()};
// }
//
// public User getMatchedUser(){
// if(!getUser().getId().equals(Controller.getInstance().getMyself().getId())){
// return getUser();
// }
//
// return (User) getDestination();
// }
//
// public Boolean isMutual() {
// return isMutual;
// }
//
// public String getFakeName(){
// return fakeName;
// }
//
// }
//
// Path: app/src/com/lesgens/blindr/models/User.java
// public class User implements IDestination{
// private Bitmap avatar;
// private String name;
// private String tokenId;
//
// public User(String name, Bitmap avatar, String tokenId){
// this.name = name;
// this.avatar = avatar;
// this.tokenId = tokenId;
// }
//
// public Bitmap getAvatar(){
// return avatar;
// }
//
// public String getName(){
// return name;
// }
//
// public String getId() {
// return tokenId;
// }
// }
//
// Path: app/src/com/lesgens/blindr/utils/Utils.java
// public class Utils {
//
// public static final String BLINDR_IMAGE_BASE = "BLINDR_IMAGE_BASE:";
//
// public static int dpInPixels(Context context, int dp) {
// return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources()
// .getDisplayMetrics());
// }
//
// public static Bitmap scaleDown(Bitmap realImage, float maxImageSize,
// boolean filter) {
// float ratio = Math.min(
// (float) maxImageSize / realImage.getWidth(),
// (float) maxImageSize / realImage.getHeight());
// int width = Math.round((float) ratio * realImage.getWidth());
// int height = Math.round((float) ratio * realImage.getHeight());
//
// Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width,
// height, filter);
// return newBitmap;
// }
//
// public static byte[] getByteArrayFromString(String str){
// String[] splitted = str.split(",");
//
// byte[] byteArray = new byte[splitted.length];
//
// for(int i = 0; i < splitted.length; i++){
// byteArray[i] = Byte.valueOf(splitted[i]);
// }
//
// return byteArray;
// }
//
// }
// Path: app/src/com/lesgens/blindr/controllers/Controller.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import com.checkin.avatargenerator.AvatarGenerator;
import com.facebook.Session;
import com.lesgens.blindr.models.City;
import com.lesgens.blindr.models.Match;
import com.lesgens.blindr.models.User;
import com.lesgens.blindr.utils.Utils;
package com.lesgens.blindr.controllers;
public class Controller {
private City city; | private HashMap<String, User> users; |
theblindr/blindr | app/src/com/lesgens/blindr/controllers/Controller.java | // Path: app/src/com/lesgens/blindr/models/City.java
// public class City implements IDestination{
//
// private String name;
//
// public City(String name) {
// this.name = name;
// }
//
// public String getName(){
// return name;
// }
//
// public String getId(){
// return name;
// }
// }
//
// Path: app/src/com/lesgens/blindr/models/Match.java
// public class Match extends Event{
//
// private Boolean isMutual;
// private String fakeName;
//
// public Match(UUID id, Timestamp timestamp, IDestination destination, User user) {
// this(id, timestamp, destination, user, false, null, null);
// }
//
// public Match(UUID id, Timestamp timestamp, IDestination destination, User user, Boolean isMutual, String realName, String fakeName) {
// super(id, timestamp, destination, user, realName, fakeName);
// this.isMutual = isMutual;
// this.fakeName = fakeName;
// }
//
// public User[] getMatchUsers() {
// return new User[]{this.getUser(), (User)this.getDestination()};
// }
//
// public User getMatchedUser(){
// if(!getUser().getId().equals(Controller.getInstance().getMyself().getId())){
// return getUser();
// }
//
// return (User) getDestination();
// }
//
// public Boolean isMutual() {
// return isMutual;
// }
//
// public String getFakeName(){
// return fakeName;
// }
//
// }
//
// Path: app/src/com/lesgens/blindr/models/User.java
// public class User implements IDestination{
// private Bitmap avatar;
// private String name;
// private String tokenId;
//
// public User(String name, Bitmap avatar, String tokenId){
// this.name = name;
// this.avatar = avatar;
// this.tokenId = tokenId;
// }
//
// public Bitmap getAvatar(){
// return avatar;
// }
//
// public String getName(){
// return name;
// }
//
// public String getId() {
// return tokenId;
// }
// }
//
// Path: app/src/com/lesgens/blindr/utils/Utils.java
// public class Utils {
//
// public static final String BLINDR_IMAGE_BASE = "BLINDR_IMAGE_BASE:";
//
// public static int dpInPixels(Context context, int dp) {
// return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources()
// .getDisplayMetrics());
// }
//
// public static Bitmap scaleDown(Bitmap realImage, float maxImageSize,
// boolean filter) {
// float ratio = Math.min(
// (float) maxImageSize / realImage.getWidth(),
// (float) maxImageSize / realImage.getHeight());
// int width = Math.round((float) ratio * realImage.getWidth());
// int height = Math.round((float) ratio * realImage.getHeight());
//
// Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width,
// height, filter);
// return newBitmap;
// }
//
// public static byte[] getByteArrayFromString(String str){
// String[] splitted = str.split(",");
//
// byte[] byteArray = new byte[splitted.length];
//
// for(int i = 0; i < splitted.length; i++){
// byteArray[i] = Byte.valueOf(splitted[i]);
// }
//
// return byteArray;
// }
//
// }
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import com.checkin.avatargenerator.AvatarGenerator;
import com.facebook.Session;
import com.lesgens.blindr.models.City;
import com.lesgens.blindr.models.Match;
import com.lesgens.blindr.models.User;
import com.lesgens.blindr.utils.Utils; | package com.lesgens.blindr.controllers;
public class Controller {
private City city;
private HashMap<String, User> users;
private Session session;
private User myselfUser; | // Path: app/src/com/lesgens/blindr/models/City.java
// public class City implements IDestination{
//
// private String name;
//
// public City(String name) {
// this.name = name;
// }
//
// public String getName(){
// return name;
// }
//
// public String getId(){
// return name;
// }
// }
//
// Path: app/src/com/lesgens/blindr/models/Match.java
// public class Match extends Event{
//
// private Boolean isMutual;
// private String fakeName;
//
// public Match(UUID id, Timestamp timestamp, IDestination destination, User user) {
// this(id, timestamp, destination, user, false, null, null);
// }
//
// public Match(UUID id, Timestamp timestamp, IDestination destination, User user, Boolean isMutual, String realName, String fakeName) {
// super(id, timestamp, destination, user, realName, fakeName);
// this.isMutual = isMutual;
// this.fakeName = fakeName;
// }
//
// public User[] getMatchUsers() {
// return new User[]{this.getUser(), (User)this.getDestination()};
// }
//
// public User getMatchedUser(){
// if(!getUser().getId().equals(Controller.getInstance().getMyself().getId())){
// return getUser();
// }
//
// return (User) getDestination();
// }
//
// public Boolean isMutual() {
// return isMutual;
// }
//
// public String getFakeName(){
// return fakeName;
// }
//
// }
//
// Path: app/src/com/lesgens/blindr/models/User.java
// public class User implements IDestination{
// private Bitmap avatar;
// private String name;
// private String tokenId;
//
// public User(String name, Bitmap avatar, String tokenId){
// this.name = name;
// this.avatar = avatar;
// this.tokenId = tokenId;
// }
//
// public Bitmap getAvatar(){
// return avatar;
// }
//
// public String getName(){
// return name;
// }
//
// public String getId() {
// return tokenId;
// }
// }
//
// Path: app/src/com/lesgens/blindr/utils/Utils.java
// public class Utils {
//
// public static final String BLINDR_IMAGE_BASE = "BLINDR_IMAGE_BASE:";
//
// public static int dpInPixels(Context context, int dp) {
// return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources()
// .getDisplayMetrics());
// }
//
// public static Bitmap scaleDown(Bitmap realImage, float maxImageSize,
// boolean filter) {
// float ratio = Math.min(
// (float) maxImageSize / realImage.getWidth(),
// (float) maxImageSize / realImage.getHeight());
// int width = Math.round((float) ratio * realImage.getWidth());
// int height = Math.round((float) ratio * realImage.getHeight());
//
// Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width,
// height, filter);
// return newBitmap;
// }
//
// public static byte[] getByteArrayFromString(String str){
// String[] splitted = str.split(",");
//
// byte[] byteArray = new byte[splitted.length];
//
// for(int i = 0; i < splitted.length; i++){
// byteArray[i] = Byte.valueOf(splitted[i]);
// }
//
// return byteArray;
// }
//
// }
// Path: app/src/com/lesgens/blindr/controllers/Controller.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import com.checkin.avatargenerator.AvatarGenerator;
import com.facebook.Session;
import com.lesgens.blindr.models.City;
import com.lesgens.blindr.models.Match;
import com.lesgens.blindr.models.User;
import com.lesgens.blindr.utils.Utils;
package com.lesgens.blindr.controllers;
public class Controller {
private City city;
private HashMap<String, User> users;
private Session session;
private User myselfUser; | private ArrayList<Match> matches; |
theblindr/blindr | app/src/com/lesgens/blindr/controllers/Controller.java | // Path: app/src/com/lesgens/blindr/models/City.java
// public class City implements IDestination{
//
// private String name;
//
// public City(String name) {
// this.name = name;
// }
//
// public String getName(){
// return name;
// }
//
// public String getId(){
// return name;
// }
// }
//
// Path: app/src/com/lesgens/blindr/models/Match.java
// public class Match extends Event{
//
// private Boolean isMutual;
// private String fakeName;
//
// public Match(UUID id, Timestamp timestamp, IDestination destination, User user) {
// this(id, timestamp, destination, user, false, null, null);
// }
//
// public Match(UUID id, Timestamp timestamp, IDestination destination, User user, Boolean isMutual, String realName, String fakeName) {
// super(id, timestamp, destination, user, realName, fakeName);
// this.isMutual = isMutual;
// this.fakeName = fakeName;
// }
//
// public User[] getMatchUsers() {
// return new User[]{this.getUser(), (User)this.getDestination()};
// }
//
// public User getMatchedUser(){
// if(!getUser().getId().equals(Controller.getInstance().getMyself().getId())){
// return getUser();
// }
//
// return (User) getDestination();
// }
//
// public Boolean isMutual() {
// return isMutual;
// }
//
// public String getFakeName(){
// return fakeName;
// }
//
// }
//
// Path: app/src/com/lesgens/blindr/models/User.java
// public class User implements IDestination{
// private Bitmap avatar;
// private String name;
// private String tokenId;
//
// public User(String name, Bitmap avatar, String tokenId){
// this.name = name;
// this.avatar = avatar;
// this.tokenId = tokenId;
// }
//
// public Bitmap getAvatar(){
// return avatar;
// }
//
// public String getName(){
// return name;
// }
//
// public String getId() {
// return tokenId;
// }
// }
//
// Path: app/src/com/lesgens/blindr/utils/Utils.java
// public class Utils {
//
// public static final String BLINDR_IMAGE_BASE = "BLINDR_IMAGE_BASE:";
//
// public static int dpInPixels(Context context, int dp) {
// return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources()
// .getDisplayMetrics());
// }
//
// public static Bitmap scaleDown(Bitmap realImage, float maxImageSize,
// boolean filter) {
// float ratio = Math.min(
// (float) maxImageSize / realImage.getWidth(),
// (float) maxImageSize / realImage.getHeight());
// int width = Math.round((float) ratio * realImage.getWidth());
// int height = Math.round((float) ratio * realImage.getHeight());
//
// Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width,
// height, filter);
// return newBitmap;
// }
//
// public static byte[] getByteArrayFromString(String str){
// String[] splitted = str.split(",");
//
// byte[] byteArray = new byte[splitted.length];
//
// for(int i = 0; i < splitted.length; i++){
// byteArray[i] = Byte.valueOf(splitted[i]);
// }
//
// return byteArray;
// }
//
// }
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import com.checkin.avatargenerator.AvatarGenerator;
import com.facebook.Session;
import com.lesgens.blindr.models.City;
import com.lesgens.blindr.models.Match;
import com.lesgens.blindr.models.User;
import com.lesgens.blindr.utils.Utils; | public void setSession(Session session) {
this.session = session;
}
public void setMyOwnUser(User user){
this.myselfUser = user;
}
public User getMyself(){
return myselfUser;
}
public String getMyId(){
return myselfUser.getId().substring(0, myselfUser.getId().indexOf("."));
}
public void setMatches(List<Match> matches){
this.matches.clear();
this.matches.addAll(matches);
}
public void addMatch(Match match){
this.matches.add(match);
}
public ArrayList<Match> getMatches(){
return matches;
}
public void setDimensionAvatar(Context context) { | // Path: app/src/com/lesgens/blindr/models/City.java
// public class City implements IDestination{
//
// private String name;
//
// public City(String name) {
// this.name = name;
// }
//
// public String getName(){
// return name;
// }
//
// public String getId(){
// return name;
// }
// }
//
// Path: app/src/com/lesgens/blindr/models/Match.java
// public class Match extends Event{
//
// private Boolean isMutual;
// private String fakeName;
//
// public Match(UUID id, Timestamp timestamp, IDestination destination, User user) {
// this(id, timestamp, destination, user, false, null, null);
// }
//
// public Match(UUID id, Timestamp timestamp, IDestination destination, User user, Boolean isMutual, String realName, String fakeName) {
// super(id, timestamp, destination, user, realName, fakeName);
// this.isMutual = isMutual;
// this.fakeName = fakeName;
// }
//
// public User[] getMatchUsers() {
// return new User[]{this.getUser(), (User)this.getDestination()};
// }
//
// public User getMatchedUser(){
// if(!getUser().getId().equals(Controller.getInstance().getMyself().getId())){
// return getUser();
// }
//
// return (User) getDestination();
// }
//
// public Boolean isMutual() {
// return isMutual;
// }
//
// public String getFakeName(){
// return fakeName;
// }
//
// }
//
// Path: app/src/com/lesgens/blindr/models/User.java
// public class User implements IDestination{
// private Bitmap avatar;
// private String name;
// private String tokenId;
//
// public User(String name, Bitmap avatar, String tokenId){
// this.name = name;
// this.avatar = avatar;
// this.tokenId = tokenId;
// }
//
// public Bitmap getAvatar(){
// return avatar;
// }
//
// public String getName(){
// return name;
// }
//
// public String getId() {
// return tokenId;
// }
// }
//
// Path: app/src/com/lesgens/blindr/utils/Utils.java
// public class Utils {
//
// public static final String BLINDR_IMAGE_BASE = "BLINDR_IMAGE_BASE:";
//
// public static int dpInPixels(Context context, int dp) {
// return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources()
// .getDisplayMetrics());
// }
//
// public static Bitmap scaleDown(Bitmap realImage, float maxImageSize,
// boolean filter) {
// float ratio = Math.min(
// (float) maxImageSize / realImage.getWidth(),
// (float) maxImageSize / realImage.getHeight());
// int width = Math.round((float) ratio * realImage.getWidth());
// int height = Math.round((float) ratio * realImage.getHeight());
//
// Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width,
// height, filter);
// return newBitmap;
// }
//
// public static byte[] getByteArrayFromString(String str){
// String[] splitted = str.split(",");
//
// byte[] byteArray = new byte[splitted.length];
//
// for(int i = 0; i < splitted.length; i++){
// byteArray[i] = Byte.valueOf(splitted[i]);
// }
//
// return byteArray;
// }
//
// }
// Path: app/src/com/lesgens/blindr/controllers/Controller.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import com.checkin.avatargenerator.AvatarGenerator;
import com.facebook.Session;
import com.lesgens.blindr.models.City;
import com.lesgens.blindr.models.Match;
import com.lesgens.blindr.models.User;
import com.lesgens.blindr.utils.Utils;
public void setSession(Session session) {
this.session = session;
}
public void setMyOwnUser(User user){
this.myselfUser = user;
}
public User getMyself(){
return myselfUser;
}
public String getMyId(){
return myselfUser.getId().substring(0, myselfUser.getId().indexOf("."));
}
public void setMatches(List<Match> matches){
this.matches.clear();
this.matches.addAll(matches);
}
public void addMatch(Match match){
this.matches.add(match);
}
public ArrayList<Match> getMatches(){
return matches;
}
public void setDimensionAvatar(Context context) { | dimensionAvatar = Utils.dpInPixels(context, 50); |
theblindr/blindr | app/src/com/lesgens/blindr/listeners/EventsListener.java | // Path: app/src/com/lesgens/blindr/models/Event.java
// public abstract class Event {
//
//
// private UUID id;
// private Timestamp timestamp;
// private IDestination destination;
// private User sourceUser;
// private String realName;
// private String fakeName;
//
// public Event(UUID id, Timestamp timestamp, IDestination destination, User user, String realName, String fakeName) {
// this.id = id;
// this.timestamp = timestamp;
// this.destination = destination;
// this.sourceUser = user;
// this.realName = realName;
// this.fakeName = fakeName;
// }
//
// public UUID getId(){
// return id;
// }
//
// public Timestamp getTimestamp(){
// return timestamp;
// }
//
// public IDestination getDestination(){
// return destination;
// }
//
// public User getUser(){
// return sourceUser;
// }
//
// public String getRealName() {
// return realName;
// }
//
// public String getFakeName() {
// return fakeName;
// }
//
// }
//
// Path: app/src/com/lesgens/blindr/models/Match.java
// public class Match extends Event{
//
// private Boolean isMutual;
// private String fakeName;
//
// public Match(UUID id, Timestamp timestamp, IDestination destination, User user) {
// this(id, timestamp, destination, user, false, null, null);
// }
//
// public Match(UUID id, Timestamp timestamp, IDestination destination, User user, Boolean isMutual, String realName, String fakeName) {
// super(id, timestamp, destination, user, realName, fakeName);
// this.isMutual = isMutual;
// this.fakeName = fakeName;
// }
//
// public User[] getMatchUsers() {
// return new User[]{this.getUser(), (User)this.getDestination()};
// }
//
// public User getMatchedUser(){
// if(!getUser().getId().equals(Controller.getInstance().getMyself().getId())){
// return getUser();
// }
//
// return (User) getDestination();
// }
//
// public Boolean isMutual() {
// return isMutual;
// }
//
// public String getFakeName(){
// return fakeName;
// }
//
// }
//
// Path: app/src/com/lesgens/blindr/models/User.java
// public class User implements IDestination{
// private Bitmap avatar;
// private String name;
// private String tokenId;
//
// public User(String name, Bitmap avatar, String tokenId){
// this.name = name;
// this.avatar = avatar;
// this.tokenId = tokenId;
// }
//
// public Bitmap getAvatar(){
// return avatar;
// }
//
// public String getName(){
// return name;
// }
//
// public String getId() {
// return tokenId;
// }
// }
| import java.util.List;
import com.lesgens.blindr.models.Event;
import com.lesgens.blindr.models.Match;
import com.lesgens.blindr.models.User; | package com.lesgens.blindr.listeners;
public interface EventsListener {
public void onEventsReceived(List<Event> events);
| // Path: app/src/com/lesgens/blindr/models/Event.java
// public abstract class Event {
//
//
// private UUID id;
// private Timestamp timestamp;
// private IDestination destination;
// private User sourceUser;
// private String realName;
// private String fakeName;
//
// public Event(UUID id, Timestamp timestamp, IDestination destination, User user, String realName, String fakeName) {
// this.id = id;
// this.timestamp = timestamp;
// this.destination = destination;
// this.sourceUser = user;
// this.realName = realName;
// this.fakeName = fakeName;
// }
//
// public UUID getId(){
// return id;
// }
//
// public Timestamp getTimestamp(){
// return timestamp;
// }
//
// public IDestination getDestination(){
// return destination;
// }
//
// public User getUser(){
// return sourceUser;
// }
//
// public String getRealName() {
// return realName;
// }
//
// public String getFakeName() {
// return fakeName;
// }
//
// }
//
// Path: app/src/com/lesgens/blindr/models/Match.java
// public class Match extends Event{
//
// private Boolean isMutual;
// private String fakeName;
//
// public Match(UUID id, Timestamp timestamp, IDestination destination, User user) {
// this(id, timestamp, destination, user, false, null, null);
// }
//
// public Match(UUID id, Timestamp timestamp, IDestination destination, User user, Boolean isMutual, String realName, String fakeName) {
// super(id, timestamp, destination, user, realName, fakeName);
// this.isMutual = isMutual;
// this.fakeName = fakeName;
// }
//
// public User[] getMatchUsers() {
// return new User[]{this.getUser(), (User)this.getDestination()};
// }
//
// public User getMatchedUser(){
// if(!getUser().getId().equals(Controller.getInstance().getMyself().getId())){
// return getUser();
// }
//
// return (User) getDestination();
// }
//
// public Boolean isMutual() {
// return isMutual;
// }
//
// public String getFakeName(){
// return fakeName;
// }
//
// }
//
// Path: app/src/com/lesgens/blindr/models/User.java
// public class User implements IDestination{
// private Bitmap avatar;
// private String name;
// private String tokenId;
//
// public User(String name, Bitmap avatar, String tokenId){
// this.name = name;
// this.avatar = avatar;
// this.tokenId = tokenId;
// }
//
// public Bitmap getAvatar(){
// return avatar;
// }
//
// public String getName(){
// return name;
// }
//
// public String getId() {
// return tokenId;
// }
// }
// Path: app/src/com/lesgens/blindr/listeners/EventsListener.java
import java.util.List;
import com.lesgens.blindr.models.Event;
import com.lesgens.blindr.models.Match;
import com.lesgens.blindr.models.User;
package com.lesgens.blindr.listeners;
public interface EventsListener {
public void onEventsReceived(List<Event> events);
| public void onOldMatchesReceives(List<Match> matches); |
theblindr/blindr | app/src/com/lesgens/blindr/listeners/EventsListener.java | // Path: app/src/com/lesgens/blindr/models/Event.java
// public abstract class Event {
//
//
// private UUID id;
// private Timestamp timestamp;
// private IDestination destination;
// private User sourceUser;
// private String realName;
// private String fakeName;
//
// public Event(UUID id, Timestamp timestamp, IDestination destination, User user, String realName, String fakeName) {
// this.id = id;
// this.timestamp = timestamp;
// this.destination = destination;
// this.sourceUser = user;
// this.realName = realName;
// this.fakeName = fakeName;
// }
//
// public UUID getId(){
// return id;
// }
//
// public Timestamp getTimestamp(){
// return timestamp;
// }
//
// public IDestination getDestination(){
// return destination;
// }
//
// public User getUser(){
// return sourceUser;
// }
//
// public String getRealName() {
// return realName;
// }
//
// public String getFakeName() {
// return fakeName;
// }
//
// }
//
// Path: app/src/com/lesgens/blindr/models/Match.java
// public class Match extends Event{
//
// private Boolean isMutual;
// private String fakeName;
//
// public Match(UUID id, Timestamp timestamp, IDestination destination, User user) {
// this(id, timestamp, destination, user, false, null, null);
// }
//
// public Match(UUID id, Timestamp timestamp, IDestination destination, User user, Boolean isMutual, String realName, String fakeName) {
// super(id, timestamp, destination, user, realName, fakeName);
// this.isMutual = isMutual;
// this.fakeName = fakeName;
// }
//
// public User[] getMatchUsers() {
// return new User[]{this.getUser(), (User)this.getDestination()};
// }
//
// public User getMatchedUser(){
// if(!getUser().getId().equals(Controller.getInstance().getMyself().getId())){
// return getUser();
// }
//
// return (User) getDestination();
// }
//
// public Boolean isMutual() {
// return isMutual;
// }
//
// public String getFakeName(){
// return fakeName;
// }
//
// }
//
// Path: app/src/com/lesgens/blindr/models/User.java
// public class User implements IDestination{
// private Bitmap avatar;
// private String name;
// private String tokenId;
//
// public User(String name, Bitmap avatar, String tokenId){
// this.name = name;
// this.avatar = avatar;
// this.tokenId = tokenId;
// }
//
// public Bitmap getAvatar(){
// return avatar;
// }
//
// public String getName(){
// return name;
// }
//
// public String getId() {
// return tokenId;
// }
// }
| import java.util.List;
import com.lesgens.blindr.models.Event;
import com.lesgens.blindr.models.Match;
import com.lesgens.blindr.models.User; | package com.lesgens.blindr.listeners;
public interface EventsListener {
public void onEventsReceived(List<Event> events);
public void onOldMatchesReceives(List<Match> matches);
public void onUserHistoryReceived(List<Event> events);
| // Path: app/src/com/lesgens/blindr/models/Event.java
// public abstract class Event {
//
//
// private UUID id;
// private Timestamp timestamp;
// private IDestination destination;
// private User sourceUser;
// private String realName;
// private String fakeName;
//
// public Event(UUID id, Timestamp timestamp, IDestination destination, User user, String realName, String fakeName) {
// this.id = id;
// this.timestamp = timestamp;
// this.destination = destination;
// this.sourceUser = user;
// this.realName = realName;
// this.fakeName = fakeName;
// }
//
// public UUID getId(){
// return id;
// }
//
// public Timestamp getTimestamp(){
// return timestamp;
// }
//
// public IDestination getDestination(){
// return destination;
// }
//
// public User getUser(){
// return sourceUser;
// }
//
// public String getRealName() {
// return realName;
// }
//
// public String getFakeName() {
// return fakeName;
// }
//
// }
//
// Path: app/src/com/lesgens/blindr/models/Match.java
// public class Match extends Event{
//
// private Boolean isMutual;
// private String fakeName;
//
// public Match(UUID id, Timestamp timestamp, IDestination destination, User user) {
// this(id, timestamp, destination, user, false, null, null);
// }
//
// public Match(UUID id, Timestamp timestamp, IDestination destination, User user, Boolean isMutual, String realName, String fakeName) {
// super(id, timestamp, destination, user, realName, fakeName);
// this.isMutual = isMutual;
// this.fakeName = fakeName;
// }
//
// public User[] getMatchUsers() {
// return new User[]{this.getUser(), (User)this.getDestination()};
// }
//
// public User getMatchedUser(){
// if(!getUser().getId().equals(Controller.getInstance().getMyself().getId())){
// return getUser();
// }
//
// return (User) getDestination();
// }
//
// public Boolean isMutual() {
// return isMutual;
// }
//
// public String getFakeName(){
// return fakeName;
// }
//
// }
//
// Path: app/src/com/lesgens/blindr/models/User.java
// public class User implements IDestination{
// private Bitmap avatar;
// private String name;
// private String tokenId;
//
// public User(String name, Bitmap avatar, String tokenId){
// this.name = name;
// this.avatar = avatar;
// this.tokenId = tokenId;
// }
//
// public Bitmap getAvatar(){
// return avatar;
// }
//
// public String getName(){
// return name;
// }
//
// public String getId() {
// return tokenId;
// }
// }
// Path: app/src/com/lesgens/blindr/listeners/EventsListener.java
import java.util.List;
import com.lesgens.blindr.models.Event;
import com.lesgens.blindr.models.Match;
import com.lesgens.blindr.models.User;
package com.lesgens.blindr.listeners;
public interface EventsListener {
public void onEventsReceived(List<Event> events);
public void onOldMatchesReceives(List<Match> matches);
public void onUserHistoryReceived(List<Event> events);
| public void onUserLiked(User user, String userFakeName); |
theblindr/blindr | app/src/com/grio/fbphotopicker/FBPhotoPickerActivity.java | // Path: app/src/com/lesgens/blindr/views/CustomYesNoDialog.java
// public class CustomYesNoDialog extends Dialog implements
// android.view.View.OnClickListener {
//
// public Button yes, no;
//
// public CustomYesNoDialog(Context context) {
// super(context);
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// requestWindowFeature(Window.FEATURE_NO_TITLE);
//
// setContentView(R.layout.dialog_yes_no);
//
// setCancelable(false);
// setCanceledOnTouchOutside(false);
//
// yes = (Button) findViewById(R.id.btn_yes);
// no = (Button) findViewById(R.id.btn_no);
//
// yes.setOnClickListener(this);
// no.setOnClickListener(this);
//
// getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
// }
//
// public void setDialogText(String text){
// if(findViewById(R.id.txt_dia) != null){
// ((TextView) findViewById(R.id.txt_dia)).setText(text);
// }
// }
//
// public void setDialogText(int resourceId){
// if(findViewById(R.id.txt_dia) != null){
// ((TextView) findViewById(R.id.txt_dia)).setText(resourceId);
// }
// }
//
// public void setYesText(int resourceId){
// if(findViewById(R.id.btn_yes) != null){
// ((TextView) findViewById(R.id.btn_yes)).setText(resourceId);
// }
// }
//
// public void setYesText(String text){
// if(findViewById(R.id.btn_yes) != null){
// ((TextView) findViewById(R.id.btn_yes)).setText(text);
// }
// }
//
// public void setNoText(int resourceId){
// if(findViewById(R.id.btn_no) != null){
// ((TextView) findViewById(R.id.btn_no)).setText(resourceId);
// }
// }
//
// public void setNoText(String text){
// if(findViewById(R.id.btn_no) != null){
// ((TextView) findViewById(R.id.btn_no)).setText(text);
// }
// }
//
// public void transformAsOkDialog(){
// ((TextView) findViewById(R.id.btn_yes)).setText(getContext().getString(R.string.ok));
// findViewById(R.id.btn_no).setVisibility(View.GONE);
// }
//
// public void onPositiveClick(){}
// public void onNegativeClick(){}
//
// @Override
// public void onClick(View v) {
// switch (v.getId()) {
// case R.id.btn_yes:
// onPositiveClick();
// dismiss();
// break;
// case R.id.btn_no:
// onNegativeClick();
// dismiss();
// break;
// default:
// break;
// }
// dismiss();
// }
// }
| import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Request.Callback;
import com.facebook.Response;
import com.facebook.Session;
import com.lesgens.blindr.R;
import com.lesgens.blindr.views.CustomYesNoDialog; | }
mAlbumsList.setAdapter(new FBAlbumArrayAdapter(mContext, 0, fbAlbums));
mAlbumsList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
mPhotos = fbAlbums.get(position).getPhotos();
mPhotosGrid
.setAdapter(new FBPhotoArrayAdapter(mContext, 0, mPhotos));
// TODO: check for API Level before animating
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1)
mAlbumsList.animate().x(-mAlbumsList.getWidth());
else
mAlbumsList.setVisibility(View.GONE);
mPhotoGridVisible = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
if (getActionBar() != null)
getActionBar().setTitle(fbAlbums.get(position).getName());
}
});
mPhotosGrid.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, final int position,
long id) { | // Path: app/src/com/lesgens/blindr/views/CustomYesNoDialog.java
// public class CustomYesNoDialog extends Dialog implements
// android.view.View.OnClickListener {
//
// public Button yes, no;
//
// public CustomYesNoDialog(Context context) {
// super(context);
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// requestWindowFeature(Window.FEATURE_NO_TITLE);
//
// setContentView(R.layout.dialog_yes_no);
//
// setCancelable(false);
// setCanceledOnTouchOutside(false);
//
// yes = (Button) findViewById(R.id.btn_yes);
// no = (Button) findViewById(R.id.btn_no);
//
// yes.setOnClickListener(this);
// no.setOnClickListener(this);
//
// getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
// }
//
// public void setDialogText(String text){
// if(findViewById(R.id.txt_dia) != null){
// ((TextView) findViewById(R.id.txt_dia)).setText(text);
// }
// }
//
// public void setDialogText(int resourceId){
// if(findViewById(R.id.txt_dia) != null){
// ((TextView) findViewById(R.id.txt_dia)).setText(resourceId);
// }
// }
//
// public void setYesText(int resourceId){
// if(findViewById(R.id.btn_yes) != null){
// ((TextView) findViewById(R.id.btn_yes)).setText(resourceId);
// }
// }
//
// public void setYesText(String text){
// if(findViewById(R.id.btn_yes) != null){
// ((TextView) findViewById(R.id.btn_yes)).setText(text);
// }
// }
//
// public void setNoText(int resourceId){
// if(findViewById(R.id.btn_no) != null){
// ((TextView) findViewById(R.id.btn_no)).setText(resourceId);
// }
// }
//
// public void setNoText(String text){
// if(findViewById(R.id.btn_no) != null){
// ((TextView) findViewById(R.id.btn_no)).setText(text);
// }
// }
//
// public void transformAsOkDialog(){
// ((TextView) findViewById(R.id.btn_yes)).setText(getContext().getString(R.string.ok));
// findViewById(R.id.btn_no).setVisibility(View.GONE);
// }
//
// public void onPositiveClick(){}
// public void onNegativeClick(){}
//
// @Override
// public void onClick(View v) {
// switch (v.getId()) {
// case R.id.btn_yes:
// onPositiveClick();
// dismiss();
// break;
// case R.id.btn_no:
// onNegativeClick();
// dismiss();
// break;
// default:
// break;
// }
// dismiss();
// }
// }
// Path: app/src/com/grio/fbphotopicker/FBPhotoPickerActivity.java
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Request.Callback;
import com.facebook.Response;
import com.facebook.Session;
import com.lesgens.blindr.R;
import com.lesgens.blindr.views.CustomYesNoDialog;
}
mAlbumsList.setAdapter(new FBAlbumArrayAdapter(mContext, 0, fbAlbums));
mAlbumsList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
mPhotos = fbAlbums.get(position).getPhotos();
mPhotosGrid
.setAdapter(new FBPhotoArrayAdapter(mContext, 0, mPhotos));
// TODO: check for API Level before animating
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1)
mAlbumsList.animate().x(-mAlbumsList.getWidth());
else
mAlbumsList.setVisibility(View.GONE);
mPhotoGridVisible = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
if (getActionBar() != null)
getActionBar().setTitle(fbAlbums.get(position).getName());
}
});
mPhotosGrid.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, final int position,
long id) { | CustomYesNoDialog dialog = new CustomYesNoDialog(FBPhotoPickerActivity.this){ |
theblindr/blindr | app/src/com/lesgens/blindr/models/Match.java | // Path: app/src/com/lesgens/blindr/controllers/Controller.java
// public class Controller {
// private City city;
// private HashMap<String, User> users;
// private Session session;
// private User myselfUser;
// private ArrayList<Match> matches;
// private int dimensionAvatar;
//
// private static Controller controller;
//
// private Controller(){
// city = new City("");
// users = new HashMap<String, User>();
// matches = new ArrayList<Match>();
// }
//
// public static Controller getInstance(){
// if(controller == null){
// controller = new Controller();
// }
//
// return controller;
// }
//
// public void setCity(City city){
// this.city = city;
// }
//
// public City getCity(){
// return city;
// }
//
// public void addUser(User user){
// users.put(user.getId(), user);
// }
//
// public User getUser(String tokenId){
// if(users.get(tokenId) == null){
// users.put(tokenId, new User("user" + tokenId, AvatarGenerator.generate(dimensionAvatar, dimensionAvatar), tokenId));
// }
// return users.get(tokenId);
// }
//
// public Session getSession() {
// return session;
// }
//
// public void setSession(Session session) {
// this.session = session;
// }
//
// public void setMyOwnUser(User user){
// this.myselfUser = user;
// }
//
// public User getMyself(){
// return myselfUser;
// }
//
// public String getMyId(){
// return myselfUser.getId().substring(0, myselfUser.getId().indexOf("."));
// }
//
// public void setMatches(List<Match> matches){
// this.matches.clear();
// this.matches.addAll(matches);
// }
//
// public void addMatch(Match match){
// this.matches.add(match);
// }
//
// public ArrayList<Match> getMatches(){
// return matches;
// }
//
// public void setDimensionAvatar(Context context) {
// dimensionAvatar = Utils.dpInPixels(context, 50);
// }
//
// public int getDimensionAvatar() {
// return dimensionAvatar;
// }
//
// public void addBlockPerson(Activity activity, String id){
// SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = sharedPref.edit();
// String blocked = getBlockedPeopleString(activity);
// if(blocked.isEmpty()){
// blocked = id;
// } else{
// blocked += "," + id;
// }
// editor.putString("blockedList", blocked);
// editor.commit();
// }
//
// private String getBlockedPeopleString(Activity activity){
// SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE);
// String blocked = sharedPref.getString("blockedList", "");
//
// return blocked;
//
// }
//
// public ArrayList<String> getBlockedPeople(Activity activity){
// SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE);
// String blocked = sharedPref.getString("blockedList", "");
//
// ArrayList<String> blockedPeople = new ArrayList<String>();
// for(String b : blocked.split(",")){
// blockedPeople.add(b);
// }
//
// return blockedPeople;
//
// }
//
// public boolean containsMatch(Match match) {
// for(Match m : matches){
// if(m.getId() != null){
// if(m.getId().equals(match.getId())){
// return true;
// }
// }
// }
// return false;
// }
//
// public Match removeOldIfPendingMatch(Match match) {
// for(Match m : matches){
// if(!m.isMutual() && m.getMatchedUser().getId().equals(match.getMatchedUser().getId())){
// matches.remove(m);
// return m;
// }
// }
// return null;
// }
//
// public boolean checkIfMutualWith(String fakeName){
// if(fakeName != null){
// for(Match m : matches){
// if(m.isMutual() && fakeName.equals(m.getFakeName())){
// return true;
// }
// }
// }
// return false;
// }
//
// }
| import java.sql.Timestamp;
import java.util.UUID;
import com.lesgens.blindr.controllers.Controller; | package com.lesgens.blindr.models;
public class Match extends Event{
private Boolean isMutual;
private String fakeName;
public Match(UUID id, Timestamp timestamp, IDestination destination, User user) {
this(id, timestamp, destination, user, false, null, null);
}
public Match(UUID id, Timestamp timestamp, IDestination destination, User user, Boolean isMutual, String realName, String fakeName) {
super(id, timestamp, destination, user, realName, fakeName);
this.isMutual = isMutual;
this.fakeName = fakeName;
}
public User[] getMatchUsers() {
return new User[]{this.getUser(), (User)this.getDestination()};
}
public User getMatchedUser(){ | // Path: app/src/com/lesgens/blindr/controllers/Controller.java
// public class Controller {
// private City city;
// private HashMap<String, User> users;
// private Session session;
// private User myselfUser;
// private ArrayList<Match> matches;
// private int dimensionAvatar;
//
// private static Controller controller;
//
// private Controller(){
// city = new City("");
// users = new HashMap<String, User>();
// matches = new ArrayList<Match>();
// }
//
// public static Controller getInstance(){
// if(controller == null){
// controller = new Controller();
// }
//
// return controller;
// }
//
// public void setCity(City city){
// this.city = city;
// }
//
// public City getCity(){
// return city;
// }
//
// public void addUser(User user){
// users.put(user.getId(), user);
// }
//
// public User getUser(String tokenId){
// if(users.get(tokenId) == null){
// users.put(tokenId, new User("user" + tokenId, AvatarGenerator.generate(dimensionAvatar, dimensionAvatar), tokenId));
// }
// return users.get(tokenId);
// }
//
// public Session getSession() {
// return session;
// }
//
// public void setSession(Session session) {
// this.session = session;
// }
//
// public void setMyOwnUser(User user){
// this.myselfUser = user;
// }
//
// public User getMyself(){
// return myselfUser;
// }
//
// public String getMyId(){
// return myselfUser.getId().substring(0, myselfUser.getId().indexOf("."));
// }
//
// public void setMatches(List<Match> matches){
// this.matches.clear();
// this.matches.addAll(matches);
// }
//
// public void addMatch(Match match){
// this.matches.add(match);
// }
//
// public ArrayList<Match> getMatches(){
// return matches;
// }
//
// public void setDimensionAvatar(Context context) {
// dimensionAvatar = Utils.dpInPixels(context, 50);
// }
//
// public int getDimensionAvatar() {
// return dimensionAvatar;
// }
//
// public void addBlockPerson(Activity activity, String id){
// SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = sharedPref.edit();
// String blocked = getBlockedPeopleString(activity);
// if(blocked.isEmpty()){
// blocked = id;
// } else{
// blocked += "," + id;
// }
// editor.putString("blockedList", blocked);
// editor.commit();
// }
//
// private String getBlockedPeopleString(Activity activity){
// SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE);
// String blocked = sharedPref.getString("blockedList", "");
//
// return blocked;
//
// }
//
// public ArrayList<String> getBlockedPeople(Activity activity){
// SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE);
// String blocked = sharedPref.getString("blockedList", "");
//
// ArrayList<String> blockedPeople = new ArrayList<String>();
// for(String b : blocked.split(",")){
// blockedPeople.add(b);
// }
//
// return blockedPeople;
//
// }
//
// public boolean containsMatch(Match match) {
// for(Match m : matches){
// if(m.getId() != null){
// if(m.getId().equals(match.getId())){
// return true;
// }
// }
// }
// return false;
// }
//
// public Match removeOldIfPendingMatch(Match match) {
// for(Match m : matches){
// if(!m.isMutual() && m.getMatchedUser().getId().equals(match.getMatchedUser().getId())){
// matches.remove(m);
// return m;
// }
// }
// return null;
// }
//
// public boolean checkIfMutualWith(String fakeName){
// if(fakeName != null){
// for(Match m : matches){
// if(m.isMutual() && fakeName.equals(m.getFakeName())){
// return true;
// }
// }
// }
// return false;
// }
//
// }
// Path: app/src/com/lesgens/blindr/models/Match.java
import java.sql.Timestamp;
import java.util.UUID;
import com.lesgens.blindr.controllers.Controller;
package com.lesgens.blindr.models;
public class Match extends Event{
private Boolean isMutual;
private String fakeName;
public Match(UUID id, Timestamp timestamp, IDestination destination, User user) {
this(id, timestamp, destination, user, false, null, null);
}
public Match(UUID id, Timestamp timestamp, IDestination destination, User user, Boolean isMutual, String realName, String fakeName) {
super(id, timestamp, destination, user, realName, fakeName);
this.isMutual = isMutual;
this.fakeName = fakeName;
}
public User[] getMatchUsers() {
return new User[]{this.getUser(), (User)this.getDestination()};
}
public User getMatchedUser(){ | if(!getUser().getId().equals(Controller.getInstance().getMyself().getId())){ |
theblindr/blindr | app/src/com/jeremyfeinstein/slidingmenu/lib/CustomViewBehind.java | // Path: app/src/com/jeremyfeinstein/slidingmenu/lib/SlidingMenu.java
// public interface CanvasTransformer {
//
// /**
// * Transform canvas.
// *
// * @param canvas the canvas
// * @param percentOpen the percent open
// */
// public void transformCanvas(Canvas canvas, float percentOpen);
// }
| import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu.CanvasTransformer;
import com.lesgens.blindr.R; | package com.jeremyfeinstein.slidingmenu.lib;
public class CustomViewBehind extends ViewGroup {
private static final String TAG = "CustomViewBehind";
private static final int MARGIN_THRESHOLD = 48; // dips
private int mTouchMode = SlidingMenu.TOUCHMODE_MARGIN;
private CustomViewAbove mViewAbove;
private View mContent;
private View mSecondaryContent;
private int mMarginThreshold;
private int mWidthOffset; | // Path: app/src/com/jeremyfeinstein/slidingmenu/lib/SlidingMenu.java
// public interface CanvasTransformer {
//
// /**
// * Transform canvas.
// *
// * @param canvas the canvas
// * @param percentOpen the percent open
// */
// public void transformCanvas(Canvas canvas, float percentOpen);
// }
// Path: app/src/com/jeremyfeinstein/slidingmenu/lib/CustomViewBehind.java
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu.CanvasTransformer;
import com.lesgens.blindr.R;
package com.jeremyfeinstein.slidingmenu.lib;
public class CustomViewBehind extends ViewGroup {
private static final String TAG = "CustomViewBehind";
private static final int MARGIN_THRESHOLD = 48; // dips
private int mTouchMode = SlidingMenu.TOUCHMODE_MARGIN;
private CustomViewAbove mViewAbove;
private View mContent;
private View mSecondaryContent;
private int mMarginThreshold;
private int mWidthOffset; | private CanvasTransformer mTransformer; |
theblindr/blindr | app/src/com/lesgens/blindr/views/SlideshowView.java | // Path: app/src/com/lesgens/blindr/ImageViewerActivity.java
// public class ImageViewerActivity extends Activity implements OnClickListener{
//
// public static void show(Context context, Bitmap bitmap) {
// Intent i = new Intent(context, ImageViewerActivity.class);
// FileOutputStream out = null;
// try {
// File file = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
// out = new FileOutputStream(file);
// bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
// i.putExtra("photoUri", Uri.fromFile(file));
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// try {
// if (out != null) {
// out.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// context.startActivity(i);
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// //Remove title bar
// this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//
// setContentView(R.layout.image_viewer);
//
// Uri photoUri = getIntent().getParcelableExtra("photoUri");
//
//
// if(photoUri == null){
// finish();
// }
//
//
// try{
// Bitmap bitmap = android.provider.MediaStore.Images.Media
// .getBitmap(getContentResolver(), photoUri);
// ImageView imageView = (ImageView) findViewById(R.id.image);
// imageView.setImageBitmap(bitmap);
// } catch(Exception e){
// e.printStackTrace();
// finish();
// }
//
// findViewById(R.id.container).setOnClickListener(this);
// }
//
// @Override
// public void onClick(View v) {
// if(v.getId() == R.id.container){
// finish();
// }
// }
//
//
// }
| import java.util.ArrayList;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.lesgens.blindr.ImageViewerActivity;
import com.lesgens.blindr.R; | mPicturesContainer = (LinearLayout) view.findViewById(R.id.pictures_container);
mDotsContainer = (LinearLayout) view.findViewById(R.id.dots_container);
mDotsContainer.setPadding(0, -mDotsSize*2, 0, 0);
mImages = new ArrayList<Bitmap>();
mSelectedItem = -1;
}
private void initAttrs(AttributeSet attrs){
TypedArray a = getContext().getTheme().obtainStyledAttributes(
attrs,
R.styleable.SlideshowView,
0, 0);
try {
mSelectedColor = a.getColor(R.styleable.SlideshowView_selectedColor, Color.BLACK);
mUnselectedColor = a.getColor(R.styleable.SlideshowView_unselectedColor, Color.WHITE);
mCurrentColor = a.getColor(R.styleable.SlideshowView_currentColor, Color.GRAY);
mPicturesWidth = a.getDimensionPixelSize(R.styleable.SlideshowView_picturesWidth, LayoutParams.WRAP_CONTENT);
mPicturesHeight= a.getDimensionPixelSize(R.styleable.SlideshowView_picturesHeight, LayoutParams.WRAP_CONTENT);
mDotsSize = a.getDimensionPixelSize(R.styleable.SlideshowView_dotsSize, 72);
} finally {
a.recycle();
}
}
@Override
public void onClick(View v) {
if(v instanceof ImageView){
select((Integer) v.getTag()); | // Path: app/src/com/lesgens/blindr/ImageViewerActivity.java
// public class ImageViewerActivity extends Activity implements OnClickListener{
//
// public static void show(Context context, Bitmap bitmap) {
// Intent i = new Intent(context, ImageViewerActivity.class);
// FileOutputStream out = null;
// try {
// File file = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
// out = new FileOutputStream(file);
// bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
// i.putExtra("photoUri", Uri.fromFile(file));
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// try {
// if (out != null) {
// out.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// context.startActivity(i);
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// //Remove title bar
// this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//
// setContentView(R.layout.image_viewer);
//
// Uri photoUri = getIntent().getParcelableExtra("photoUri");
//
//
// if(photoUri == null){
// finish();
// }
//
//
// try{
// Bitmap bitmap = android.provider.MediaStore.Images.Media
// .getBitmap(getContentResolver(), photoUri);
// ImageView imageView = (ImageView) findViewById(R.id.image);
// imageView.setImageBitmap(bitmap);
// } catch(Exception e){
// e.printStackTrace();
// finish();
// }
//
// findViewById(R.id.container).setOnClickListener(this);
// }
//
// @Override
// public void onClick(View v) {
// if(v.getId() == R.id.container){
// finish();
// }
// }
//
//
// }
// Path: app/src/com/lesgens/blindr/views/SlideshowView.java
import java.util.ArrayList;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.lesgens.blindr.ImageViewerActivity;
import com.lesgens.blindr.R;
mPicturesContainer = (LinearLayout) view.findViewById(R.id.pictures_container);
mDotsContainer = (LinearLayout) view.findViewById(R.id.dots_container);
mDotsContainer.setPadding(0, -mDotsSize*2, 0, 0);
mImages = new ArrayList<Bitmap>();
mSelectedItem = -1;
}
private void initAttrs(AttributeSet attrs){
TypedArray a = getContext().getTheme().obtainStyledAttributes(
attrs,
R.styleable.SlideshowView,
0, 0);
try {
mSelectedColor = a.getColor(R.styleable.SlideshowView_selectedColor, Color.BLACK);
mUnselectedColor = a.getColor(R.styleable.SlideshowView_unselectedColor, Color.WHITE);
mCurrentColor = a.getColor(R.styleable.SlideshowView_currentColor, Color.GRAY);
mPicturesWidth = a.getDimensionPixelSize(R.styleable.SlideshowView_picturesWidth, LayoutParams.WRAP_CONTENT);
mPicturesHeight= a.getDimensionPixelSize(R.styleable.SlideshowView_picturesHeight, LayoutParams.WRAP_CONTENT);
mDotsSize = a.getDimensionPixelSize(R.styleable.SlideshowView_dotsSize, 72);
} finally {
a.recycle();
}
}
@Override
public void onClick(View v) {
if(v instanceof ImageView){
select((Integer) v.getTag()); | ImageViewerActivity.show(getContext(), getSelectedImage()); |
theblindr/blindr | app/src/com/lesgens/blindr/WelcomeToBlindrPageFragment.java | // Path: app/src/com/lesgens/blindr/controllers/Controller.java
// public class Controller {
// private City city;
// private HashMap<String, User> users;
// private Session session;
// private User myselfUser;
// private ArrayList<Match> matches;
// private int dimensionAvatar;
//
// private static Controller controller;
//
// private Controller(){
// city = new City("");
// users = new HashMap<String, User>();
// matches = new ArrayList<Match>();
// }
//
// public static Controller getInstance(){
// if(controller == null){
// controller = new Controller();
// }
//
// return controller;
// }
//
// public void setCity(City city){
// this.city = city;
// }
//
// public City getCity(){
// return city;
// }
//
// public void addUser(User user){
// users.put(user.getId(), user);
// }
//
// public User getUser(String tokenId){
// if(users.get(tokenId) == null){
// users.put(tokenId, new User("user" + tokenId, AvatarGenerator.generate(dimensionAvatar, dimensionAvatar), tokenId));
// }
// return users.get(tokenId);
// }
//
// public Session getSession() {
// return session;
// }
//
// public void setSession(Session session) {
// this.session = session;
// }
//
// public void setMyOwnUser(User user){
// this.myselfUser = user;
// }
//
// public User getMyself(){
// return myselfUser;
// }
//
// public String getMyId(){
// return myselfUser.getId().substring(0, myselfUser.getId().indexOf("."));
// }
//
// public void setMatches(List<Match> matches){
// this.matches.clear();
// this.matches.addAll(matches);
// }
//
// public void addMatch(Match match){
// this.matches.add(match);
// }
//
// public ArrayList<Match> getMatches(){
// return matches;
// }
//
// public void setDimensionAvatar(Context context) {
// dimensionAvatar = Utils.dpInPixels(context, 50);
// }
//
// public int getDimensionAvatar() {
// return dimensionAvatar;
// }
//
// public void addBlockPerson(Activity activity, String id){
// SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = sharedPref.edit();
// String blocked = getBlockedPeopleString(activity);
// if(blocked.isEmpty()){
// blocked = id;
// } else{
// blocked += "," + id;
// }
// editor.putString("blockedList", blocked);
// editor.commit();
// }
//
// private String getBlockedPeopleString(Activity activity){
// SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE);
// String blocked = sharedPref.getString("blockedList", "");
//
// return blocked;
//
// }
//
// public ArrayList<String> getBlockedPeople(Activity activity){
// SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE);
// String blocked = sharedPref.getString("blockedList", "");
//
// ArrayList<String> blockedPeople = new ArrayList<String>();
// for(String b : blocked.split(",")){
// blockedPeople.add(b);
// }
//
// return blockedPeople;
//
// }
//
// public boolean containsMatch(Match match) {
// for(Match m : matches){
// if(m.getId() != null){
// if(m.getId().equals(match.getId())){
// return true;
// }
// }
// }
// return false;
// }
//
// public Match removeOldIfPendingMatch(Match match) {
// for(Match m : matches){
// if(!m.isMutual() && m.getMatchedUser().getId().equals(match.getMatchedUser().getId())){
// matches.remove(m);
// return m;
// }
// }
// return null;
// }
//
// public boolean checkIfMutualWith(String fakeName){
// if(fakeName != null){
// for(Match m : matches){
// if(m.isMutual() && fakeName.equals(m.getFakeName())){
// return true;
// }
// }
// }
// return false;
// }
//
// }
| import com.lesgens.blindr.controllers.Controller;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView; | package com.lesgens.blindr;
public class WelcomeToBlindrPageFragment extends Fragment implements OnClickListener {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup v = (ViewGroup) inflater.inflate(
R.layout.welcome_to_blindr, container, false);
((TextView) v.findViewById(R.id.splash_text)).setTypeface(((FirstTimeExperienceActivity) getActivity()).typeFace);
| // Path: app/src/com/lesgens/blindr/controllers/Controller.java
// public class Controller {
// private City city;
// private HashMap<String, User> users;
// private Session session;
// private User myselfUser;
// private ArrayList<Match> matches;
// private int dimensionAvatar;
//
// private static Controller controller;
//
// private Controller(){
// city = new City("");
// users = new HashMap<String, User>();
// matches = new ArrayList<Match>();
// }
//
// public static Controller getInstance(){
// if(controller == null){
// controller = new Controller();
// }
//
// return controller;
// }
//
// public void setCity(City city){
// this.city = city;
// }
//
// public City getCity(){
// return city;
// }
//
// public void addUser(User user){
// users.put(user.getId(), user);
// }
//
// public User getUser(String tokenId){
// if(users.get(tokenId) == null){
// users.put(tokenId, new User("user" + tokenId, AvatarGenerator.generate(dimensionAvatar, dimensionAvatar), tokenId));
// }
// return users.get(tokenId);
// }
//
// public Session getSession() {
// return session;
// }
//
// public void setSession(Session session) {
// this.session = session;
// }
//
// public void setMyOwnUser(User user){
// this.myselfUser = user;
// }
//
// public User getMyself(){
// return myselfUser;
// }
//
// public String getMyId(){
// return myselfUser.getId().substring(0, myselfUser.getId().indexOf("."));
// }
//
// public void setMatches(List<Match> matches){
// this.matches.clear();
// this.matches.addAll(matches);
// }
//
// public void addMatch(Match match){
// this.matches.add(match);
// }
//
// public ArrayList<Match> getMatches(){
// return matches;
// }
//
// public void setDimensionAvatar(Context context) {
// dimensionAvatar = Utils.dpInPixels(context, 50);
// }
//
// public int getDimensionAvatar() {
// return dimensionAvatar;
// }
//
// public void addBlockPerson(Activity activity, String id){
// SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = sharedPref.edit();
// String blocked = getBlockedPeopleString(activity);
// if(blocked.isEmpty()){
// blocked = id;
// } else{
// blocked += "," + id;
// }
// editor.putString("blockedList", blocked);
// editor.commit();
// }
//
// private String getBlockedPeopleString(Activity activity){
// SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE);
// String blocked = sharedPref.getString("blockedList", "");
//
// return blocked;
//
// }
//
// public ArrayList<String> getBlockedPeople(Activity activity){
// SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE);
// String blocked = sharedPref.getString("blockedList", "");
//
// ArrayList<String> blockedPeople = new ArrayList<String>();
// for(String b : blocked.split(",")){
// blockedPeople.add(b);
// }
//
// return blockedPeople;
//
// }
//
// public boolean containsMatch(Match match) {
// for(Match m : matches){
// if(m.getId() != null){
// if(m.getId().equals(match.getId())){
// return true;
// }
// }
// }
// return false;
// }
//
// public Match removeOldIfPendingMatch(Match match) {
// for(Match m : matches){
// if(!m.isMutual() && m.getMatchedUser().getId().equals(match.getMatchedUser().getId())){
// matches.remove(m);
// return m;
// }
// }
// return null;
// }
//
// public boolean checkIfMutualWith(String fakeName){
// if(fakeName != null){
// for(Match m : matches){
// if(m.isMutual() && fakeName.equals(m.getFakeName())){
// return true;
// }
// }
// }
// return false;
// }
//
// }
// Path: app/src/com/lesgens/blindr/WelcomeToBlindrPageFragment.java
import com.lesgens.blindr.controllers.Controller;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
package com.lesgens.blindr;
public class WelcomeToBlindrPageFragment extends Fragment implements OnClickListener {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup v = (ViewGroup) inflater.inflate(
R.layout.welcome_to_blindr, container, false);
((TextView) v.findViewById(R.id.splash_text)).setTypeface(((FirstTimeExperienceActivity) getActivity()).typeFace);
| ((ImageView) v.findViewById(R.id.avatar)).setImageBitmap(Controller.getInstance().getMyself().getAvatar()); |
darrenfoong/candc | src/lexicon/Categories.java | // Path: src/io/Preface.java
// public class Preface {
// public static void readPreface(BufferedReader in) throws IOException {
// String line = in.readLine();
//
// if (line == null || line.charAt(0) != '#') {
// throw new IllegalArgumentException("File does not start with the mandatory preface.");
// }
//
// while ((line = in.readLine()) != null) {
// if (line.isEmpty()) {
// break;
// }
// if (line.charAt(0) != '#') {
// throw new IllegalArgumentException("Uncommented line within preface.");
// }
// }
// }
//
// public static void printPreface(PrintWriter out) {
// out.println("# mandatory preface");
// out.println("# mandatory preface");
// out.println();
// }
// }
//
// Path: src/utils/ByteWrapper.java
// public class ByteWrapper {
// public byte value;
//
// public ByteWrapper(byte value) {
// this.value = value;
// }
// }
//
// Path: src/utils/ShortWrapper.java
// public class ShortWrapper {
// public short value;
//
// public ShortWrapper(short value) {
// this.value = value;
// }
// }
| import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import io.Preface;
import utils.ByteWrapper;
import utils.ShortWrapper; |
public String getString(String plainCategoryString) {
return markedupStrings.get(plainCategoryString);
}
public String getPlainString(String markedupString) {
return plainCategoryStrings.get(markedupString);
}
public Category getCategory(String plainCategoryString) {
return markedupCategories.get(plainCategoryString);
}
// 3 constants only used when reading the markedup file:
private enum States {
CAT, MARKEDUP, GRS
}
private void readMarkedupFile(String grammarDir, boolean ALT_MARKEDUP) throws IOException {
markedupStrings = new HashMap<String, String>();
plainCategoryStrings = new HashMap<String, String>();
markedupCategories = new HashMap<String, Category>();
// not sure when the sentinel is used for categories, but retaining from C&C:
markedupStrings.put("+", "+");
markedupCategories.put("+", null);
String markedupFile = grammarDir + "/markedup";
try ( BufferedReader in = new BufferedReader(new FileReader(markedupFile)) ) { | // Path: src/io/Preface.java
// public class Preface {
// public static void readPreface(BufferedReader in) throws IOException {
// String line = in.readLine();
//
// if (line == null || line.charAt(0) != '#') {
// throw new IllegalArgumentException("File does not start with the mandatory preface.");
// }
//
// while ((line = in.readLine()) != null) {
// if (line.isEmpty()) {
// break;
// }
// if (line.charAt(0) != '#') {
// throw new IllegalArgumentException("Uncommented line within preface.");
// }
// }
// }
//
// public static void printPreface(PrintWriter out) {
// out.println("# mandatory preface");
// out.println("# mandatory preface");
// out.println();
// }
// }
//
// Path: src/utils/ByteWrapper.java
// public class ByteWrapper {
// public byte value;
//
// public ByteWrapper(byte value) {
// this.value = value;
// }
// }
//
// Path: src/utils/ShortWrapper.java
// public class ShortWrapper {
// public short value;
//
// public ShortWrapper(short value) {
// this.value = value;
// }
// }
// Path: src/lexicon/Categories.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import io.Preface;
import utils.ByteWrapper;
import utils.ShortWrapper;
public String getString(String plainCategoryString) {
return markedupStrings.get(plainCategoryString);
}
public String getPlainString(String markedupString) {
return plainCategoryStrings.get(markedupString);
}
public Category getCategory(String plainCategoryString) {
return markedupCategories.get(plainCategoryString);
}
// 3 constants only used when reading the markedup file:
private enum States {
CAT, MARKEDUP, GRS
}
private void readMarkedupFile(String grammarDir, boolean ALT_MARKEDUP) throws IOException {
markedupStrings = new HashMap<String, String>();
plainCategoryStrings = new HashMap<String, String>();
markedupCategories = new HashMap<String, Category>();
// not sure when the sentinel is used for categories, but retaining from C&C:
markedupStrings.put("+", "+");
markedupCategories.put("+", null);
String markedupFile = grammarDir + "/markedup";
try ( BufferedReader in = new BufferedReader(new FileReader(markedupFile)) ) { | Preface.readPreface(in); |
darrenfoong/candc | src/lexicon/Categories.java | // Path: src/io/Preface.java
// public class Preface {
// public static void readPreface(BufferedReader in) throws IOException {
// String line = in.readLine();
//
// if (line == null || line.charAt(0) != '#') {
// throw new IllegalArgumentException("File does not start with the mandatory preface.");
// }
//
// while ((line = in.readLine()) != null) {
// if (line.isEmpty()) {
// break;
// }
// if (line.charAt(0) != '#') {
// throw new IllegalArgumentException("Uncommented line within preface.");
// }
// }
// }
//
// public static void printPreface(PrintWriter out) {
// out.println("# mandatory preface");
// out.println("# mandatory preface");
// out.println();
// }
// }
//
// Path: src/utils/ByteWrapper.java
// public class ByteWrapper {
// public byte value;
//
// public ByteWrapper(byte value) {
// this.value = value;
// }
// }
//
// Path: src/utils/ShortWrapper.java
// public class ShortWrapper {
// public short value;
//
// public ShortWrapper(short value) {
// this.value = value;
// }
// }
| import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import io.Preface;
import utils.ByteWrapper;
import utils.ShortWrapper; | if ( tokens.length != 1 ) {
throw new Error("error parsing plain cat line in markedup");
}
plainCatString = tokens[0];
state = States.MARKEDUP;
break;
case MARKEDUP:
tokens = (line.trim()).split("\\s+");
if ( tokens.length != 2 ) {
throw new Error("error parsing markedup cat line in markedup");
}
markedupCatString = tokens[1];
cat = parse(markedupCatString);
/*
* call reorder since C&C does, although this Java class
* does now check the variable ordering in the
* consumeSlot method
*
* ensures categories have vars ordered according to the
* ordering in the VarID class:
*/
byte[] seenVariables = new byte[VarID.NUM_VARS];
Arrays.fill(seenVariables, VarID.NONE); // not necessary
// since VarID.NONE
// is 0, but let's
// be explicit
| // Path: src/io/Preface.java
// public class Preface {
// public static void readPreface(BufferedReader in) throws IOException {
// String line = in.readLine();
//
// if (line == null || line.charAt(0) != '#') {
// throw new IllegalArgumentException("File does not start with the mandatory preface.");
// }
//
// while ((line = in.readLine()) != null) {
// if (line.isEmpty()) {
// break;
// }
// if (line.charAt(0) != '#') {
// throw new IllegalArgumentException("Uncommented line within preface.");
// }
// }
// }
//
// public static void printPreface(PrintWriter out) {
// out.println("# mandatory preface");
// out.println("# mandatory preface");
// out.println();
// }
// }
//
// Path: src/utils/ByteWrapper.java
// public class ByteWrapper {
// public byte value;
//
// public ByteWrapper(byte value) {
// this.value = value;
// }
// }
//
// Path: src/utils/ShortWrapper.java
// public class ShortWrapper {
// public short value;
//
// public ShortWrapper(short value) {
// this.value = value;
// }
// }
// Path: src/lexicon/Categories.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import io.Preface;
import utils.ByteWrapper;
import utils.ShortWrapper;
if ( tokens.length != 1 ) {
throw new Error("error parsing plain cat line in markedup");
}
plainCatString = tokens[0];
state = States.MARKEDUP;
break;
case MARKEDUP:
tokens = (line.trim()).split("\\s+");
if ( tokens.length != 2 ) {
throw new Error("error parsing markedup cat line in markedup");
}
markedupCatString = tokens[1];
cat = parse(markedupCatString);
/*
* call reorder since C&C does, although this Java class
* does now check the variable ordering in the
* consumeSlot method
*
* ensures categories have vars ordered according to the
* ordering in the VarID class:
*/
byte[] seenVariables = new byte[VarID.NUM_VARS];
Arrays.fill(seenVariables, VarID.NONE); // not necessary
// since VarID.NONE
// is 0, but let's
// be explicit
| cat.reorderVariables(seenVariables, new ByteWrapper((byte) (0))); |
darrenfoong/candc | src/lexicon/Categories.java | // Path: src/io/Preface.java
// public class Preface {
// public static void readPreface(BufferedReader in) throws IOException {
// String line = in.readLine();
//
// if (line == null || line.charAt(0) != '#') {
// throw new IllegalArgumentException("File does not start with the mandatory preface.");
// }
//
// while ((line = in.readLine()) != null) {
// if (line.isEmpty()) {
// break;
// }
// if (line.charAt(0) != '#') {
// throw new IllegalArgumentException("Uncommented line within preface.");
// }
// }
// }
//
// public static void printPreface(PrintWriter out) {
// out.println("# mandatory preface");
// out.println("# mandatory preface");
// out.println();
// }
// }
//
// Path: src/utils/ByteWrapper.java
// public class ByteWrapper {
// public byte value;
//
// public ByteWrapper(byte value) {
// this.value = value;
// }
// }
//
// Path: src/utils/ShortWrapper.java
// public class ShortWrapper {
// public short value;
//
// public ShortWrapper(short value) {
// this.value = value;
// }
// }
| import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import io.Preface;
import utils.ByteWrapper;
import utils.ShortWrapper; | }
markedupCatString = tokens[1];
cat = parse(markedupCatString);
seenVariables = new byte[VarID.NUM_VARS];
Arrays.fill(seenVariables, VarID.NONE);
cat.reorderVariables(seenVariables, new ByteWrapper((byte) (0)));
markedupStrings.put(plainCatString, markedupCatString);
plainCategoryStrings.put(markedupCatString, plainCatString);
markedupCategories.put(plainCatString, cat);
continue;
}
break;
}
}
} catch ( IOException e ) {
throw e;
}
}
/*
* when parsing a markedup string, this will add new relations to
* dependencyRelations (so be careful when using this outside of parsing the
* markedup file)
*/
public Category parse(String catString) { | // Path: src/io/Preface.java
// public class Preface {
// public static void readPreface(BufferedReader in) throws IOException {
// String line = in.readLine();
//
// if (line == null || line.charAt(0) != '#') {
// throw new IllegalArgumentException("File does not start with the mandatory preface.");
// }
//
// while ((line = in.readLine()) != null) {
// if (line.isEmpty()) {
// break;
// }
// if (line.charAt(0) != '#') {
// throw new IllegalArgumentException("Uncommented line within preface.");
// }
// }
// }
//
// public static void printPreface(PrintWriter out) {
// out.println("# mandatory preface");
// out.println("# mandatory preface");
// out.println();
// }
// }
//
// Path: src/utils/ByteWrapper.java
// public class ByteWrapper {
// public byte value;
//
// public ByteWrapper(byte value) {
// this.value = value;
// }
// }
//
// Path: src/utils/ShortWrapper.java
// public class ShortWrapper {
// public short value;
//
// public ShortWrapper(short value) {
// this.value = value;
// }
// }
// Path: src/lexicon/Categories.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import io.Preface;
import utils.ByteWrapper;
import utils.ShortWrapper;
}
markedupCatString = tokens[1];
cat = parse(markedupCatString);
seenVariables = new byte[VarID.NUM_VARS];
Arrays.fill(seenVariables, VarID.NONE);
cat.reorderVariables(seenVariables, new ByteWrapper((byte) (0)));
markedupStrings.put(plainCatString, markedupCatString);
plainCategoryStrings.put(markedupCatString, plainCatString);
markedupCategories.put(plainCatString, cat);
continue;
}
break;
}
}
} catch ( IOException e ) {
throw e;
}
}
/*
* when parsing a markedup string, this will add new relations to
* dependencyRelations (so be careful when using this outside of parsing the
* markedup file)
*/
public Category parse(String catString) { | ShortWrapper numJuliaSlots = new ShortWrapper((short) (0)); |
darrenfoong/candc | src/chart_parser/Candidate.java | // Path: src/utils/Hash.java
// public class Hash {
// /*
// * comment from C&C: shift value to multiply by with each additional
// * component of the hash function; this number is normally selected to be
// * a smallish prime; 31 and 37 seem to work well
// */
// private final static long INC = 92821;
// private long hash;
//
// public Hash(Hash other) {
// hash = other.value();
// }
//
// public Hash(long hash) {
// this.hash = hash;
// }
//
// public Hash(byte hash) {
// this.hash = (hash);
// }
//
// public long value() {
// return hash;
// }
//
// public void plusEqual(long value) {
// // += in the C&C code
// hash *= INC;
// hash += value;
// }
//
// public void barEqual(long value) {
// // |= in the C&C code
// hash += value;
// }
//
// public void timesEqual(long value) {
// // *= in the C&C code
// hash *= value;
// }
// }
| import utils.Hash; | package chart_parser;
public class Candidate implements Comparable<Candidate> {
int k; // choice point
int leftIndex; // index into left k-best array
int rightIndex; // index into right k-best array
double score; // sum of the scores of the two children
public Candidate(int k, int leftIndex, int rightIndex, double score) {
this.k = k;
this.leftIndex = leftIndex;
this.rightIndex = rightIndex;
this.score = score;
}
@Override
public int compareTo(Candidate other) {
return Double.compare(other.score, this.score);
}
@Override
public int hashCode() { | // Path: src/utils/Hash.java
// public class Hash {
// /*
// * comment from C&C: shift value to multiply by with each additional
// * component of the hash function; this number is normally selected to be
// * a smallish prime; 31 and 37 seem to work well
// */
// private final static long INC = 92821;
// private long hash;
//
// public Hash(Hash other) {
// hash = other.value();
// }
//
// public Hash(long hash) {
// this.hash = hash;
// }
//
// public Hash(byte hash) {
// this.hash = (hash);
// }
//
// public long value() {
// return hash;
// }
//
// public void plusEqual(long value) {
// // += in the C&C code
// hash *= INC;
// hash += value;
// }
//
// public void barEqual(long value) {
// // |= in the C&C code
// hash += value;
// }
//
// public void timesEqual(long value) {
// // *= in the C&C code
// hash *= value;
// }
// }
// Path: src/chart_parser/Candidate.java
import utils.Hash;
package chart_parser;
public class Candidate implements Comparable<Candidate> {
int k; // choice point
int leftIndex; // index into left k-best array
int rightIndex; // index into right k-best array
double score; // sum of the scores of the two children
public Candidate(int k, int leftIndex, int rightIndex, double score) {
this.k = k;
this.leftIndex = leftIndex;
this.rightIndex = rightIndex;
this.score = score;
}
@Override
public int compareTo(Candidate other) {
return Double.compare(other.score, this.score);
}
@Override
public int hashCode() { | Hash h = new Hash(k); |
darrenfoong/candc | src/cat_combination/DependencyStringWords.java | // Path: src/utils/Hash.java
// public class Hash {
// /*
// * comment from C&C: shift value to multiply by with each additional
// * component of the hash function; this number is normally selected to be
// * a smallish prime; 31 and 37 seem to work well
// */
// private final static long INC = 92821;
// private long hash;
//
// public Hash(Hash other) {
// hash = other.value();
// }
//
// public Hash(long hash) {
// this.hash = hash;
// }
//
// public Hash(byte hash) {
// this.hash = (hash);
// }
//
// public long value() {
// return hash;
// }
//
// public void plusEqual(long value) {
// // += in the C&C code
// hash *= INC;
// hash += value;
// }
//
// public void barEqual(long value) {
// // |= in the C&C code
// hash += value;
// }
//
// public void timesEqual(long value) {
// // *= in the C&C code
// hash *= value;
// }
// }
| import utils.Hash; | package cat_combination;
// used by the oracle decoder and IgnoreDepsEval class which stores
// which dependencies are ignored by the evaluate script; we have to
// store heads and fillers as strings, not sentence indices
public class DependencyStringWords implements Comparable<DependencyStringWords> {
private final short relID;
private final String head;
private final String filler;
private final short unaryRuleID;
public DependencyStringWords(short relID, String head, String filler, short unaryRuleID) {
this.relID = relID;
this.head = head;
this.filler = filler;
this.unaryRuleID = unaryRuleID;
}
@Override
public int compareTo(DependencyStringWords other) {
int compare;
if ( (compare = Short.compare(this.relID, other.relID)) != 0 ) { return compare; }
if ( (compare = this.head.compareTo(other.head)) != 0 ) { return compare; }
if ( (compare = this.filler.compareTo(other.filler)) != 0 ) { return compare; }
if ( (compare = Short.compare(this.unaryRuleID, other.unaryRuleID)) != 0 ) { return compare; }
return 0;
}
@Override
public int hashCode() { | // Path: src/utils/Hash.java
// public class Hash {
// /*
// * comment from C&C: shift value to multiply by with each additional
// * component of the hash function; this number is normally selected to be
// * a smallish prime; 31 and 37 seem to work well
// */
// private final static long INC = 92821;
// private long hash;
//
// public Hash(Hash other) {
// hash = other.value();
// }
//
// public Hash(long hash) {
// this.hash = hash;
// }
//
// public Hash(byte hash) {
// this.hash = (hash);
// }
//
// public long value() {
// return hash;
// }
//
// public void plusEqual(long value) {
// // += in the C&C code
// hash *= INC;
// hash += value;
// }
//
// public void barEqual(long value) {
// // |= in the C&C code
// hash += value;
// }
//
// public void timesEqual(long value) {
// // *= in the C&C code
// hash *= value;
// }
// }
// Path: src/cat_combination/DependencyStringWords.java
import utils.Hash;
package cat_combination;
// used by the oracle decoder and IgnoreDepsEval class which stores
// which dependencies are ignored by the evaluate script; we have to
// store heads and fillers as strings, not sentence indices
public class DependencyStringWords implements Comparable<DependencyStringWords> {
private final short relID;
private final String head;
private final String filler;
private final short unaryRuleID;
public DependencyStringWords(short relID, String head, String filler, short unaryRuleID) {
this.relID = relID;
this.head = head;
this.filler = filler;
this.unaryRuleID = unaryRuleID;
}
@Override
public int compareTo(DependencyStringWords other) {
int compare;
if ( (compare = Short.compare(this.relID, other.relID)) != 0 ) { return compare; }
if ( (compare = this.head.compareTo(other.head)) != 0 ) { return compare; }
if ( (compare = this.filler.compareTo(other.filler)) != 0 ) { return compare; }
if ( (compare = Short.compare(this.unaryRuleID, other.unaryRuleID)) != 0 ) { return compare; }
return 0;
}
@Override
public int hashCode() { | Hash h = new Hash(relID); |
darrenfoong/candc | src/lexicon/Category.java | // Path: src/utils/ByteWrapper.java
// public class ByteWrapper {
// public byte value;
//
// public ByteWrapper(byte value) {
// this.value = value;
// }
// }
//
// Path: src/utils/Hash.java
// public class Hash {
// /*
// * comment from C&C: shift value to multiply by with each additional
// * component of the hash function; this number is normally selected to be
// * a smallish prime; 31 and 37 seem to work well
// */
// private final static long INC = 92821;
// private long hash;
//
// public Hash(Hash other) {
// hash = other.value();
// }
//
// public Hash(long hash) {
// this.hash = hash;
// }
//
// public Hash(byte hash) {
// this.hash = (hash);
// }
//
// public long value() {
// return hash;
// }
//
// public void plusEqual(long value) {
// // += in the C&C code
// hash *= INC;
// hash += value;
// }
//
// public void barEqual(long value) {
// // |= in the C&C code
// hash += value;
// }
//
// public void timesEqual(long value) {
// // *= in the C&C code
// hash *= value;
// }
// }
| import utils.ByteWrapper;
import utils.Hash; | package lexicon;
public class Category {
public static final byte BWD_SLASH = 0;
public static final byte FWD_SLASH = 1;
public byte var;
public final short relID;
public final short lrange;
| // Path: src/utils/ByteWrapper.java
// public class ByteWrapper {
// public byte value;
//
// public ByteWrapper(byte value) {
// this.value = value;
// }
// }
//
// Path: src/utils/Hash.java
// public class Hash {
// /*
// * comment from C&C: shift value to multiply by with each additional
// * component of the hash function; this number is normally selected to be
// * a smallish prime; 31 and 37 seem to work well
// */
// private final static long INC = 92821;
// private long hash;
//
// public Hash(Hash other) {
// hash = other.value();
// }
//
// public Hash(long hash) {
// this.hash = hash;
// }
//
// public Hash(byte hash) {
// this.hash = (hash);
// }
//
// public long value() {
// return hash;
// }
//
// public void plusEqual(long value) {
// // += in the C&C code
// hash *= INC;
// hash += value;
// }
//
// public void barEqual(long value) {
// // |= in the C&C code
// hash += value;
// }
//
// public void timesEqual(long value) {
// // *= in the C&C code
// hash *= value;
// }
// }
// Path: src/lexicon/Category.java
import utils.ByteWrapper;
import utils.Hash;
package lexicon;
public class Category {
public static final byte BWD_SLASH = 0;
public static final byte FWD_SLASH = 1;
public byte var;
public final short relID;
public final short lrange;
| private final Hash equivalenceHash; |
darrenfoong/candc | src/lexicon/Category.java | // Path: src/utils/ByteWrapper.java
// public class ByteWrapper {
// public byte value;
//
// public ByteWrapper(byte value) {
// this.value = value;
// }
// }
//
// Path: src/utils/Hash.java
// public class Hash {
// /*
// * comment from C&C: shift value to multiply by with each additional
// * component of the hash function; this number is normally selected to be
// * a smallish prime; 31 and 37 seem to work well
// */
// private final static long INC = 92821;
// private long hash;
//
// public Hash(Hash other) {
// hash = other.value();
// }
//
// public Hash(long hash) {
// this.hash = hash;
// }
//
// public Hash(byte hash) {
// this.hash = (hash);
// }
//
// public long value() {
// return hash;
// }
//
// public void plusEqual(long value) {
// // += in the C&C code
// hash *= INC;
// hash += value;
// }
//
// public void barEqual(long value) {
// // |= in the C&C code
// hash += value;
// }
//
// public void timesEqual(long value) {
// // *= in the C&C code
// hash *= value;
// }
// }
| import utils.ByteWrapper;
import utils.Hash; | this.unificationHash = new Hash(other.unificationHash);
this.equivalenceHash = isComplex() ? eHashComplex() : eHashBasic();
// need to call eHash method again since the feature may have changed from other
}
/*
* uses the constructor above; upper-case first letter since this is
* effectively a constructor; called TransVariable because it copies the
* other Category whilst translating its variables using the transTable
*/
public static Category TransVariable(Category other, byte[] transTable, GrammaticalFeature feat) {
return new Category(other, transTable, feat);
}
private byte countArgs() {
if ( isBasic() ) {
return (byte) 0;
} else {
return (byte) (result.countArgs() + 1);
}
}
/*
* gets the variables ordered according to the left-to-right category order
* e.g. (S{Z}\NP{Y})/NP{X} would get changed to: (S{X}\NP{Y})/NP{Z} (X=1,
* Y=2, Z=3 in VarID; 0 is reserved for the no variable case (NONE)) the "_"
* variable is treated like any other, eg: ((S{Z}\NP{Y})/NP{Z}){_} becomes:
* ((S{X}\NP{Y})/NP{Z}){W}
*/ | // Path: src/utils/ByteWrapper.java
// public class ByteWrapper {
// public byte value;
//
// public ByteWrapper(byte value) {
// this.value = value;
// }
// }
//
// Path: src/utils/Hash.java
// public class Hash {
// /*
// * comment from C&C: shift value to multiply by with each additional
// * component of the hash function; this number is normally selected to be
// * a smallish prime; 31 and 37 seem to work well
// */
// private final static long INC = 92821;
// private long hash;
//
// public Hash(Hash other) {
// hash = other.value();
// }
//
// public Hash(long hash) {
// this.hash = hash;
// }
//
// public Hash(byte hash) {
// this.hash = (hash);
// }
//
// public long value() {
// return hash;
// }
//
// public void plusEqual(long value) {
// // += in the C&C code
// hash *= INC;
// hash += value;
// }
//
// public void barEqual(long value) {
// // |= in the C&C code
// hash += value;
// }
//
// public void timesEqual(long value) {
// // *= in the C&C code
// hash *= value;
// }
// }
// Path: src/lexicon/Category.java
import utils.ByteWrapper;
import utils.Hash;
this.unificationHash = new Hash(other.unificationHash);
this.equivalenceHash = isComplex() ? eHashComplex() : eHashBasic();
// need to call eHash method again since the feature may have changed from other
}
/*
* uses the constructor above; upper-case first letter since this is
* effectively a constructor; called TransVariable because it copies the
* other Category whilst translating its variables using the transTable
*/
public static Category TransVariable(Category other, byte[] transTable, GrammaticalFeature feat) {
return new Category(other, transTable, feat);
}
private byte countArgs() {
if ( isBasic() ) {
return (byte) 0;
} else {
return (byte) (result.countArgs() + 1);
}
}
/*
* gets the variables ordered according to the left-to-right category order
* e.g. (S{Z}\NP{Y})/NP{X} would get changed to: (S{X}\NP{Y})/NP{Z} (X=1,
* Y=2, Z=3 in VarID; 0 is reserved for the no variable case (NONE)) the "_"
* variable is treated like any other, eg: ((S{Z}\NP{Y})/NP{Z}){_} becomes:
* ((S{X}\NP{Y})/NP{Z}){W}
*/ | public void reorderVariables(byte[] seenVariables, ByteWrapper nextVarID) { |
darrenfoong/candc | src/model/Weights.java | // Path: src/io/Preface.java
// public class Preface {
// public static void readPreface(BufferedReader in) throws IOException {
// String line = in.readLine();
//
// if (line == null || line.charAt(0) != '#') {
// throw new IllegalArgumentException("File does not start with the mandatory preface.");
// }
//
// while ((line = in.readLine()) != null) {
// if (line.isEmpty()) {
// break;
// }
// if (line.charAt(0) != '#') {
// throw new IllegalArgumentException("Uncommented line within preface.");
// }
// }
// }
//
// public static void printPreface(PrintWriter out) {
// out.println("# mandatory preface");
// out.println("# mandatory preface");
// out.println();
// }
// }
| import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import io.Preface; | package model;
public class Weights {
private double[] weights;
private double logp;
private double depnn;
public Weights() {
}
public Weights(String weightsFile, int numFeatures) throws IOException {
this.weights = new double[numFeatures];
if (!weightsFile.equals("zero")) {
readWeights(weightsFile);
}
}
public void setWeights(double[] weights) {
this.weights = weights.clone();
}
private void readWeights(String weightsFile) throws IOException {
int ID = 0;
try ( BufferedReader in = new BufferedReader(new FileReader(weightsFile)) ) {
| // Path: src/io/Preface.java
// public class Preface {
// public static void readPreface(BufferedReader in) throws IOException {
// String line = in.readLine();
//
// if (line == null || line.charAt(0) != '#') {
// throw new IllegalArgumentException("File does not start with the mandatory preface.");
// }
//
// while ((line = in.readLine()) != null) {
// if (line.isEmpty()) {
// break;
// }
// if (line.charAt(0) != '#') {
// throw new IllegalArgumentException("Uncommented line within preface.");
// }
// }
// }
//
// public static void printPreface(PrintWriter out) {
// out.println("# mandatory preface");
// out.println("# mandatory preface");
// out.println();
// }
// }
// Path: src/model/Weights.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import io.Preface;
package model;
public class Weights {
private double[] weights;
private double logp;
private double depnn;
public Weights() {
}
public Weights(String weightsFile, int numFeatures) throws IOException {
this.weights = new double[numFeatures];
if (!weightsFile.equals("zero")) {
readWeights(weightsFile);
}
}
public void setWeights(double[] weights) {
this.weights = weights.clone();
}
private void readWeights(String weightsFile) throws IOException {
int ID = 0;
try ( BufferedReader in = new BufferedReader(new FileReader(weightsFile)) ) {
| Preface.readPreface(in); |
darrenfoong/candc | src/training/ConjNode.java | // Path: src/utils/NumericalFunctions.java
// public class NumericalFunctions {
// public static double addLogs(double x, double y) {
// if (y <= x) {
// return x + Math.log1p(Math.exp(y - x));
// } else {
// return y + Math.log1p(Math.exp(x - y));
// }
// }
//
// /*
// * e^x + e^y = e^z - need to solve for z
// *
// * z = log(e^x + e^y) = log(e^x.(e^x + e^y)/e^x) = x + log(1 + e^(y-x))
// *
// * useful since e^(y-x) is presumably easier to calculate than either e^x or
// * e^y
// */
//
// public static double adaGradUpdate(double gradient, double sumGradSquared, double learningRate) {
// double eps = 0.001;
//
// return learningRate * gradient / (Math.sqrt(sumGradSquared) + eps);
// }
// }
| import utils.NumericalFunctions; | // and viterbi
// scores on
// disj nodes
} else {
inside = leftChild.score;
}
} else {
inside = 0.0;
}
for (int i = 0; i < features.length; i++) {
inside += features[i].getLambda();
}
return inside;
}
// also calculates the feature expectations
public void calcOutside(double outside, double invZ, boolean gold) {
double sum = 0.0;
for (int i = 0; i < features.length; i++) {
sum += features[i].getLambda();
}
sum += outside;
if (leftChild != null) {
if (rightChild != null) {
if (leftChild.outside != 0.0) {
// suggest this may not be
// completely correct | // Path: src/utils/NumericalFunctions.java
// public class NumericalFunctions {
// public static double addLogs(double x, double y) {
// if (y <= x) {
// return x + Math.log1p(Math.exp(y - x));
// } else {
// return y + Math.log1p(Math.exp(x - y));
// }
// }
//
// /*
// * e^x + e^y = e^z - need to solve for z
// *
// * z = log(e^x + e^y) = log(e^x.(e^x + e^y)/e^x) = x + log(1 + e^(y-x))
// *
// * useful since e^(y-x) is presumably easier to calculate than either e^x or
// * e^y
// */
//
// public static double adaGradUpdate(double gradient, double sumGradSquared, double learningRate) {
// double eps = 0.001;
//
// return learningRate * gradient / (Math.sqrt(sumGradSquared) + eps);
// }
// }
// Path: src/training/ConjNode.java
import utils.NumericalFunctions;
// and viterbi
// scores on
// disj nodes
} else {
inside = leftChild.score;
}
} else {
inside = 0.0;
}
for (int i = 0; i < features.length; i++) {
inside += features[i].getLambda();
}
return inside;
}
// also calculates the feature expectations
public void calcOutside(double outside, double invZ, boolean gold) {
double sum = 0.0;
for (int i = 0; i < features.length; i++) {
sum += features[i].getLambda();
}
sum += outside;
if (leftChild != null) {
if (rightChild != null) {
if (leftChild.outside != 0.0) {
// suggest this may not be
// completely correct | leftChild.outside = NumericalFunctions.addLogs( |
darrenfoong/candc | src/training/DisjNode.java | // Path: src/utils/NumericalFunctions.java
// public class NumericalFunctions {
// public static double addLogs(double x, double y) {
// if (y <= x) {
// return x + Math.log1p(Math.exp(y - x));
// } else {
// return y + Math.log1p(Math.exp(x - y));
// }
// }
//
// /*
// * e^x + e^y = e^z - need to solve for z
// *
// * z = log(e^x + e^y) = log(e^x.(e^x + e^y)/e^x) = x + log(1 + e^(y-x))
// *
// * useful since e^(y-x) is presumably easier to calculate than either e^x or
// * e^y
// */
//
// public static double adaGradUpdate(double gradient, double sumGradSquared, double learningRate) {
// double eps = 0.001;
//
// return learningRate * gradient / (Math.sqrt(sumGradSquared) + eps);
// }
// }
| import utils.NumericalFunctions; |
if (viterbiScore > maxScore) {
maxScore = viterbiScore;
maxNode = node;
}
}
}
if (maxNode != null) {
maxNode.viterbiMarker = true; // mark the conjNode as being in the
// highest scoring derivation
} else {
throw new Error("shld always have a maxNode!");
}
score = maxScore; // keep this in case we see this node again
marker = true; // record the fact we've been here
return maxScore;
}
public void calcInside(boolean gold) {
score = 0.0;
for (int i = 0; i < conjNodes.length; i++) {
ConjNode node = conjNodes[i];
if (!gold || node.goldMarker) {
if (score == 0.0) {
score = node.calcInside(); // need to get a non-zero score
// before passing to addLogs (?)
} else { | // Path: src/utils/NumericalFunctions.java
// public class NumericalFunctions {
// public static double addLogs(double x, double y) {
// if (y <= x) {
// return x + Math.log1p(Math.exp(y - x));
// } else {
// return y + Math.log1p(Math.exp(x - y));
// }
// }
//
// /*
// * e^x + e^y = e^z - need to solve for z
// *
// * z = log(e^x + e^y) = log(e^x.(e^x + e^y)/e^x) = x + log(1 + e^(y-x))
// *
// * useful since e^(y-x) is presumably easier to calculate than either e^x or
// * e^y
// */
//
// public static double adaGradUpdate(double gradient, double sumGradSquared, double learningRate) {
// double eps = 0.001;
//
// return learningRate * gradient / (Math.sqrt(sumGradSquared) + eps);
// }
// }
// Path: src/training/DisjNode.java
import utils.NumericalFunctions;
if (viterbiScore > maxScore) {
maxScore = viterbiScore;
maxNode = node;
}
}
}
if (maxNode != null) {
maxNode.viterbiMarker = true; // mark the conjNode as being in the
// highest scoring derivation
} else {
throw new Error("shld always have a maxNode!");
}
score = maxScore; // keep this in case we see this node again
marker = true; // record the fact we've been here
return maxScore;
}
public void calcInside(boolean gold) {
score = 0.0;
for (int i = 0; i < conjNodes.length; i++) {
ConjNode node = conjNodes[i];
if (!gold || node.goldMarker) {
if (score == 0.0) {
score = node.calcInside(); // need to get a non-zero score
// before passing to addLogs (?)
} else { | score = NumericalFunctions |
darrenfoong/candc | src/cat_combination/IgnoreDepsEval.java | // Path: src/io/Sentence.java
// public class Sentence {
// public ArrayList<String> words;
// public ArrayList<String> postags;
// public ArrayList<ArrayList<Supertag>> multiSupertags;
// public ArrayList<Integer> wordIDs;
// public ArrayList<Integer> postagIDs;
// public ArrayList<Category> outputSupertags;
// // stored before printing dependency structures
//
// public Sentence(int MAX_WORDS) {
// words = new ArrayList<String>(MAX_WORDS);
// postags = new ArrayList<String>(MAX_WORDS);
// multiSupertags = new ArrayList<ArrayList<Supertag>>(MAX_WORDS);
// wordIDs = new ArrayList<Integer>(MAX_WORDS);
// postagIDs = new ArrayList<Integer>(MAX_WORDS);
// outputSupertags = new ArrayList<Category>(MAX_WORDS);
// }
//
// public void addWord(String word) {
// words.add(word);
// }
//
// public void addPostag(String postag) {
// postags.add(postag);
// }
//
// public void addSupertags(ArrayList<Supertag> supertags) {
// multiSupertags.add(supertags);
// }
//
// public void addOutputSupertag(Category supertag) {
// outputSupertags.add(supertag);
// }
//
// /**
// * Fills wordIDs and postagIDs with integer IDs obtained from lexicon.
// *
// * @param lexicon lexicon
// */
// public void addIDs(Lexicon lexicon) {
// for (int i = 0; i < words.size(); i++) {
// wordIDs.add(lexicon.getID(words.get(i)));
// postagIDs.add(lexicon.getID(postags.get(i)));
// }
// }
//
// public void clear() {
// words.clear();
// postags.clear();
// multiSupertags.clear();
// wordIDs.clear();
// postagIDs.clear();
// outputSupertags.clear();
// }
//
// public void printC_line(PrintWriter out) {
// out.print("<c>");
//
// for (int i = 0; i < words.size(); i++) {
// out.print(" " + words.get(i) + "|" + postags.get(i) + "|");
// out.print(outputSupertags.get(i).toStringNoOuterBracketsNoVars());
// }
//
// out.println();
// }
//
// public void printSupertags(PrintWriter out) {
// for (int i = 0; i < words.size(); i++) {
// if (i > 0) {
// out.print(" ");
// }
//
// out.print(outputSupertags.get(i).toStringNoOuterBracketsNoVars());
// }
//
// out.println();
// }
// }
//
// Path: src/lexicon/Relations.java
// public class Relations {
// private ArrayList<Relation> relations;
// private HashMap<String, Short> relIDs;
// private HashMap<CategoryJSlotPair, Short> relIDsII;
// // from pairs of Category strings and Julia slots to RelIDs used in the oracle deps decoder
// public static short conj1 = 0;
// // the special conj relation for dealing with coordination
//
// public Relations() {
// relations = new ArrayList<Relation>();
// relIDs = new HashMap<String, Short>();
// relIDsII = new HashMap<CategoryJSlotPair, Short>();
// addRelation("", (short) (0), (short) (0));
// // first index of a relation needs to be 1
// initConj();
// }
//
// public Relation getRelation(short relID) {
// return relations.get(relID);
// }
//
// public short getRelID(String category, short slot) {
// return (short) (relIDs.get(category) + slot - 1);
// }
//
// /*
// * note that we may get cases where the category, slot pair is not in the
// * hashMap, eg if the slot is a Julia slot and it doesn't correspond to any
// * of the relations in the markedup file
// */
// public short getRelID_II(String category, short slot) {
// CategoryJSlotPair pair = new CategoryJSlotPair(category, slot);
// if ( relIDsII.containsKey(pair) ) {
// // if (relIDsII.get(pair) != null) {
// return relIDsII.get(pair);
// } else {
// return (short) (0); // not a relation in markedup
// }
// }
//
// public short addRelation(String categoryString, short slot, short juliaSlot) {
// Relation relation = new Relation(categoryString, slot, juliaSlot);
// short relID = (short) (relations.size());
// relations.add(relation);
//
// if ( slot == 1 ) {
// relIDs.put(categoryString, relID);
// // relID gets converted to an object thro' autoboxing
// }
//
// CategoryJSlotPair pair = new CategoryJSlotPair(categoryString, juliaSlot);
// relIDsII.put(pair, relID);
//
// return relID;
// }
//
// private void initConj() {
// conj1 = addRelation("conj", (short) (1), (short) (1));
// }
// }
| import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import io.Sentence;
import lexicon.Relations; | package cat_combination;
/*
* an object of this class is used by the max F-score oracle decoder;
* it takes a dependency as input and outputs 1 if the dependency is
* ignored by the evaluate script; the ignored dependencies are read
* in as separate text files depending on their type
*/
public class IgnoreDepsEval {
HashSet<Short> ruleIDs;
// deps ignored based on the ruleID alone
HashMap<Short, HashSet<Short>> relRuleIDs;
// deps ignored based on the relation and ruleID
HashSet<DependencyStringWords> unfilledDeps;
// deps ignored based on the relation and head
HashSet<DependencyStringWords> filledDeps;
// deps ignored based on the relation, head and filler
| // Path: src/io/Sentence.java
// public class Sentence {
// public ArrayList<String> words;
// public ArrayList<String> postags;
// public ArrayList<ArrayList<Supertag>> multiSupertags;
// public ArrayList<Integer> wordIDs;
// public ArrayList<Integer> postagIDs;
// public ArrayList<Category> outputSupertags;
// // stored before printing dependency structures
//
// public Sentence(int MAX_WORDS) {
// words = new ArrayList<String>(MAX_WORDS);
// postags = new ArrayList<String>(MAX_WORDS);
// multiSupertags = new ArrayList<ArrayList<Supertag>>(MAX_WORDS);
// wordIDs = new ArrayList<Integer>(MAX_WORDS);
// postagIDs = new ArrayList<Integer>(MAX_WORDS);
// outputSupertags = new ArrayList<Category>(MAX_WORDS);
// }
//
// public void addWord(String word) {
// words.add(word);
// }
//
// public void addPostag(String postag) {
// postags.add(postag);
// }
//
// public void addSupertags(ArrayList<Supertag> supertags) {
// multiSupertags.add(supertags);
// }
//
// public void addOutputSupertag(Category supertag) {
// outputSupertags.add(supertag);
// }
//
// /**
// * Fills wordIDs and postagIDs with integer IDs obtained from lexicon.
// *
// * @param lexicon lexicon
// */
// public void addIDs(Lexicon lexicon) {
// for (int i = 0; i < words.size(); i++) {
// wordIDs.add(lexicon.getID(words.get(i)));
// postagIDs.add(lexicon.getID(postags.get(i)));
// }
// }
//
// public void clear() {
// words.clear();
// postags.clear();
// multiSupertags.clear();
// wordIDs.clear();
// postagIDs.clear();
// outputSupertags.clear();
// }
//
// public void printC_line(PrintWriter out) {
// out.print("<c>");
//
// for (int i = 0; i < words.size(); i++) {
// out.print(" " + words.get(i) + "|" + postags.get(i) + "|");
// out.print(outputSupertags.get(i).toStringNoOuterBracketsNoVars());
// }
//
// out.println();
// }
//
// public void printSupertags(PrintWriter out) {
// for (int i = 0; i < words.size(); i++) {
// if (i > 0) {
// out.print(" ");
// }
//
// out.print(outputSupertags.get(i).toStringNoOuterBracketsNoVars());
// }
//
// out.println();
// }
// }
//
// Path: src/lexicon/Relations.java
// public class Relations {
// private ArrayList<Relation> relations;
// private HashMap<String, Short> relIDs;
// private HashMap<CategoryJSlotPair, Short> relIDsII;
// // from pairs of Category strings and Julia slots to RelIDs used in the oracle deps decoder
// public static short conj1 = 0;
// // the special conj relation for dealing with coordination
//
// public Relations() {
// relations = new ArrayList<Relation>();
// relIDs = new HashMap<String, Short>();
// relIDsII = new HashMap<CategoryJSlotPair, Short>();
// addRelation("", (short) (0), (short) (0));
// // first index of a relation needs to be 1
// initConj();
// }
//
// public Relation getRelation(short relID) {
// return relations.get(relID);
// }
//
// public short getRelID(String category, short slot) {
// return (short) (relIDs.get(category) + slot - 1);
// }
//
// /*
// * note that we may get cases where the category, slot pair is not in the
// * hashMap, eg if the slot is a Julia slot and it doesn't correspond to any
// * of the relations in the markedup file
// */
// public short getRelID_II(String category, short slot) {
// CategoryJSlotPair pair = new CategoryJSlotPair(category, slot);
// if ( relIDsII.containsKey(pair) ) {
// // if (relIDsII.get(pair) != null) {
// return relIDsII.get(pair);
// } else {
// return (short) (0); // not a relation in markedup
// }
// }
//
// public short addRelation(String categoryString, short slot, short juliaSlot) {
// Relation relation = new Relation(categoryString, slot, juliaSlot);
// short relID = (short) (relations.size());
// relations.add(relation);
//
// if ( slot == 1 ) {
// relIDs.put(categoryString, relID);
// // relID gets converted to an object thro' autoboxing
// }
//
// CategoryJSlotPair pair = new CategoryJSlotPair(categoryString, juliaSlot);
// relIDsII.put(pair, relID);
//
// return relID;
// }
//
// private void initConj() {
// conj1 = addRelation("conj", (short) (1), (short) (1));
// }
// }
// Path: src/cat_combination/IgnoreDepsEval.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import io.Sentence;
import lexicon.Relations;
package cat_combination;
/*
* an object of this class is used by the max F-score oracle decoder;
* it takes a dependency as input and outputs 1 if the dependency is
* ignored by the evaluate script; the ignored dependencies are read
* in as separate text files depending on their type
*/
public class IgnoreDepsEval {
HashSet<Short> ruleIDs;
// deps ignored based on the ruleID alone
HashMap<Short, HashSet<Short>> relRuleIDs;
// deps ignored based on the relation and ruleID
HashSet<DependencyStringWords> unfilledDeps;
// deps ignored based on the relation and head
HashSet<DependencyStringWords> filledDeps;
// deps ignored based on the relation, head and filler
| Relations relations; |
darrenfoong/candc | src/training/Forest.java | // Path: src/utils/NumericalFunctions.java
// public class NumericalFunctions {
// public static double addLogs(double x, double y) {
// if (y <= x) {
// return x + Math.log1p(Math.exp(y - x));
// } else {
// return y + Math.log1p(Math.exp(x - y));
// }
// }
//
// /*
// * e^x + e^y = e^z - need to solve for z
// *
// * z = log(e^x + e^y) = log(e^x.(e^x + e^y)/e^x) = x + log(1 + e^(y-x))
// *
// * useful since e^(y-x) is presumably easier to calculate than either e^x or
// * e^y
// */
//
// public static double adaGradUpdate(double gradient, double sumGradSquared, double learningRate) {
// double eps = 0.001;
//
// return learningRate * gradient / (Math.sqrt(sumGradSquared) + eps);
// }
// }
| import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import utils.NumericalFunctions; |
// System.out.println("root score: " + score + " gold: " +
// root.goldMarker());
if (score > maxScore) {
maxScore = score;
maxRoot = root;
}
}
}
// System.out.println("viterbi max value: " + maxScore);
return maxRoot;
}
public double calcInside(boolean gold) {
for (int i = 0; i < disjNodes.length; i++) {
disjNodes[i].calcInside(gold);
}
// sum up the values for the roots:
Iterator<DisjNode> it = rootNodes.iterator();
if (!gold) {
logZ = 0.0;
while (it.hasNext()) {
DisjNode root = it.next();
if (logZ == 0.0) {
logZ = root.score;
} else { | // Path: src/utils/NumericalFunctions.java
// public class NumericalFunctions {
// public static double addLogs(double x, double y) {
// if (y <= x) {
// return x + Math.log1p(Math.exp(y - x));
// } else {
// return y + Math.log1p(Math.exp(x - y));
// }
// }
//
// /*
// * e^x + e^y = e^z - need to solve for z
// *
// * z = log(e^x + e^y) = log(e^x.(e^x + e^y)/e^x) = x + log(1 + e^(y-x))
// *
// * useful since e^(y-x) is presumably easier to calculate than either e^x or
// * e^y
// */
//
// public static double adaGradUpdate(double gradient, double sumGradSquared, double learningRate) {
// double eps = 0.001;
//
// return learningRate * gradient / (Math.sqrt(sumGradSquared) + eps);
// }
// }
// Path: src/training/Forest.java
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import utils.NumericalFunctions;
// System.out.println("root score: " + score + " gold: " +
// root.goldMarker());
if (score > maxScore) {
maxScore = score;
maxRoot = root;
}
}
}
// System.out.println("viterbi max value: " + maxScore);
return maxRoot;
}
public double calcInside(boolean gold) {
for (int i = 0; i < disjNodes.length; i++) {
disjNodes[i].calcInside(gold);
}
// sum up the values for the roots:
Iterator<DisjNode> it = rootNodes.iterator();
if (!gold) {
logZ = 0.0;
while (it.hasNext()) {
DisjNode root = it.next();
if (logZ == 0.0) {
logZ = root.score;
} else { | logZ = NumericalFunctions.addLogs(logZ, root.score); |
darrenfoong/candc | src/model/Lexicon.java | // Path: src/io/Preface.java
// public class Preface {
// public static void readPreface(BufferedReader in) throws IOException {
// String line = in.readLine();
//
// if (line == null || line.charAt(0) != '#') {
// throw new IllegalArgumentException("File does not start with the mandatory preface.");
// }
//
// while ((line = in.readLine()) != null) {
// if (line.isEmpty()) {
// break;
// }
// if (line.charAt(0) != '#') {
// throw new IllegalArgumentException("Uncommented line within preface.");
// }
// }
// }
//
// public static void printPreface(PrintWriter out) {
// out.println("# mandatory preface");
// out.println("# mandatory preface");
// out.println();
// }
// }
| import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import io.Preface; | package model;
public class Lexicon {
private HashMap<String,Integer> lexicon;
// map from words and pos as strings to IDs
public Lexicon(String file) throws IOException {
this.lexicon = new HashMap<String,Integer>();
readWordPosFile(file);
}
public int getID(String word) {
// returns -1 if word not in lexicon
Integer ID = lexicon.get(word);
if (ID == null) {
return -1;
} else {
return ID;
}
}
/*
* not assuming an empty intersection between words and pos (ie word and pos
* can get the same id eg punctuation); this is fine since the feature types
* distinguish word and pos
*/
private void readWordPosFile(String file) throws IOException {
try ( BufferedReader in = new BufferedReader(new FileReader(file)) ) { | // Path: src/io/Preface.java
// public class Preface {
// public static void readPreface(BufferedReader in) throws IOException {
// String line = in.readLine();
//
// if (line == null || line.charAt(0) != '#') {
// throw new IllegalArgumentException("File does not start with the mandatory preface.");
// }
//
// while ((line = in.readLine()) != null) {
// if (line.isEmpty()) {
// break;
// }
// if (line.charAt(0) != '#') {
// throw new IllegalArgumentException("Uncommented line within preface.");
// }
// }
// }
//
// public static void printPreface(PrintWriter out) {
// out.println("# mandatory preface");
// out.println("# mandatory preface");
// out.println();
// }
// }
// Path: src/model/Lexicon.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import io.Preface;
package model;
public class Lexicon {
private HashMap<String,Integer> lexicon;
// map from words and pos as strings to IDs
public Lexicon(String file) throws IOException {
this.lexicon = new HashMap<String,Integer>();
readWordPosFile(file);
}
public int getID(String word) {
// returns -1 if word not in lexicon
Integer ID = lexicon.get(word);
if (ID == null) {
return -1;
} else {
return ID;
}
}
/*
* not assuming an empty intersection between words and pos (ie word and pos
* can get the same id eg punctuation); this is fine since the feature types
* distinguish word and pos
*/
private void readWordPosFile(String file) throws IOException {
try ( BufferedReader in = new BufferedReader(new FileReader(file)) ) { | Preface.readPreface(in); |
darrenfoong/candc | src/lexicon/CategoryJSlotPair.java | // Path: src/utils/Hash.java
// public class Hash {
// /*
// * comment from C&C: shift value to multiply by with each additional
// * component of the hash function; this number is normally selected to be
// * a smallish prime; 31 and 37 seem to work well
// */
// private final static long INC = 92821;
// private long hash;
//
// public Hash(Hash other) {
// hash = other.value();
// }
//
// public Hash(long hash) {
// this.hash = hash;
// }
//
// public Hash(byte hash) {
// this.hash = (hash);
// }
//
// public long value() {
// return hash;
// }
//
// public void plusEqual(long value) {
// // += in the C&C code
// hash *= INC;
// hash += value;
// }
//
// public void barEqual(long value) {
// // |= in the C&C code
// hash += value;
// }
//
// public void timesEqual(long value) {
// // *= in the C&C code
// hash *= value;
// }
// }
| import utils.Hash; | package lexicon;
/*
* keys for one of the hashMaps in Relations
*/
public class CategoryJSlotPair {
public String catString;
public short slot;
public CategoryJSlotPair(String catString, short slot) {
this.catString = catString;
this.slot = slot;
}
@Override
public int hashCode() { | // Path: src/utils/Hash.java
// public class Hash {
// /*
// * comment from C&C: shift value to multiply by with each additional
// * component of the hash function; this number is normally selected to be
// * a smallish prime; 31 and 37 seem to work well
// */
// private final static long INC = 92821;
// private long hash;
//
// public Hash(Hash other) {
// hash = other.value();
// }
//
// public Hash(long hash) {
// this.hash = hash;
// }
//
// public Hash(byte hash) {
// this.hash = (hash);
// }
//
// public long value() {
// return hash;
// }
//
// public void plusEqual(long value) {
// // += in the C&C code
// hash *= INC;
// hash += value;
// }
//
// public void barEqual(long value) {
// // |= in the C&C code
// hash += value;
// }
//
// public void timesEqual(long value) {
// // *= in the C&C code
// hash *= value;
// }
// }
// Path: src/lexicon/CategoryJSlotPair.java
import utils.Hash;
package lexicon;
/*
* keys for one of the hashMaps in Relations
*/
public class CategoryJSlotPair {
public String catString;
public short slot;
public CategoryJSlotPair(String catString, short slot) {
this.catString = catString;
this.slot = slot;
}
@Override
public int hashCode() { | Hash h = new Hash(catString.hashCode()); |
darrenfoong/candc | src/training/Feature.java | // Path: src/utils/NumericalFunctions.java
// public class NumericalFunctions {
// public static double addLogs(double x, double y) {
// if (y <= x) {
// return x + Math.log1p(Math.exp(y - x));
// } else {
// return y + Math.log1p(Math.exp(x - y));
// }
// }
//
// /*
// * e^x + e^y = e^z - need to solve for z
// *
// * z = log(e^x + e^y) = log(e^x.(e^x + e^y)/e^x) = x + log(1 + e^(y-x))
// *
// * useful since e^(y-x) is presumably easier to calculate than either e^x or
// * e^y
// */
//
// public static double adaGradUpdate(double gradient, double sumGradSquared, double learningRate) {
// double eps = 0.001;
//
// return learningRate * gradient / (Math.sqrt(sumGradSquared) + eps);
// }
// }
| import utils.NumericalFunctions; | this.empiricalValue = 0.0;
}
public void perceptronUpdate() {
lambda += lambdaUpdate;
lambdaUpdate = 0.0;
cumulativeLambda += lambda;
}
public void perceptronUpdateFast(int numTrainInstances) {
double oldLambda = lambda;
lambda += lambdaUpdate;
lambdaUpdate = 0.0;
cumulativeLambda += oldLambda * (numTrainInstances - lastNumTrainInstances - 1) + lambda;
lastNumTrainInstances = numTrainInstances;
}
public void decrementLambdaUpdate() {
this.lambdaUpdate--;
}
public void incrementLambdaUpdate() {
this.lambdaUpdate++;
}
public void adaGradUpdate(double learningRate) {
double gradient = empiricalValue - expectedValue;
sumGradSquared += gradient * gradient; | // Path: src/utils/NumericalFunctions.java
// public class NumericalFunctions {
// public static double addLogs(double x, double y) {
// if (y <= x) {
// return x + Math.log1p(Math.exp(y - x));
// } else {
// return y + Math.log1p(Math.exp(x - y));
// }
// }
//
// /*
// * e^x + e^y = e^z - need to solve for z
// *
// * z = log(e^x + e^y) = log(e^x.(e^x + e^y)/e^x) = x + log(1 + e^(y-x))
// *
// * useful since e^(y-x) is presumably easier to calculate than either e^x or
// * e^y
// */
//
// public static double adaGradUpdate(double gradient, double sumGradSquared, double learningRate) {
// double eps = 0.001;
//
// return learningRate * gradient / (Math.sqrt(sumGradSquared) + eps);
// }
// }
// Path: src/training/Feature.java
import utils.NumericalFunctions;
this.empiricalValue = 0.0;
}
public void perceptronUpdate() {
lambda += lambdaUpdate;
lambdaUpdate = 0.0;
cumulativeLambda += lambda;
}
public void perceptronUpdateFast(int numTrainInstances) {
double oldLambda = lambda;
lambda += lambdaUpdate;
lambdaUpdate = 0.0;
cumulativeLambda += oldLambda * (numTrainInstances - lastNumTrainInstances - 1) + lambda;
lastNumTrainInstances = numTrainInstances;
}
public void decrementLambdaUpdate() {
this.lambdaUpdate--;
}
public void incrementLambdaUpdate() {
this.lambdaUpdate++;
}
public void adaGradUpdate(double learningRate) {
double gradient = empiricalValue - expectedValue;
sumGradSquared += gradient * gradient; | lambda += NumericalFunctions.adaGradUpdate(gradient, sumGradSquared, learningRate); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.