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
Coreoz/Plume
plume-web-jersey/src/main/java/com/coreoz/plume/jersey/dagger/DaggerJacksonModule.java
// Path: plume-web-jersey/src/main/java/com/coreoz/plume/jersey/jackson/ObjectMapperProvider.java // @Singleton // public class ObjectMapperProvider implements Provider<ObjectMapper> { // // private final ObjectMapper objectMapper; // // @Inject // public ObjectMapperProvider() { // this.objectMapper = new ObjectMapper() // .registerModule(new JavaTimeModule()) // .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) // .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) // .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // } // // @Override // public ObjectMapper get() { // return objectMapper; // } // // }
import com.coreoz.plume.jersey.jackson.ObjectMapperProvider; import com.fasterxml.jackson.databind.ObjectMapper; import dagger.Module; import dagger.Provides; import javax.inject.Singleton;
package com.coreoz.plume.jersey.dagger; @Module public class DaggerJacksonModule { @Provides @Singleton
// Path: plume-web-jersey/src/main/java/com/coreoz/plume/jersey/jackson/ObjectMapperProvider.java // @Singleton // public class ObjectMapperProvider implements Provider<ObjectMapper> { // // private final ObjectMapper objectMapper; // // @Inject // public ObjectMapperProvider() { // this.objectMapper = new ObjectMapper() // .registerModule(new JavaTimeModule()) // .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) // .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) // .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // } // // @Override // public ObjectMapper get() { // return objectMapper; // } // // } // Path: plume-web-jersey/src/main/java/com/coreoz/plume/jersey/dagger/DaggerJacksonModule.java import com.coreoz.plume.jersey.jackson.ObjectMapperProvider; import com.fasterxml.jackson.databind.ObjectMapper; import dagger.Module; import dagger.Provides; import javax.inject.Singleton; package com.coreoz.plume.jersey.dagger; @Module public class DaggerJacksonModule { @Provides @Singleton
static ObjectMapper provideObjectMapper(ObjectMapperProvider objectMapperProvider) {
Coreoz/Plume
plume-db-querydsl-codegen/src/main/java/com/coreoz/plume/db/querydsl/generation/IdBeanSerializer.java
// Path: plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/crud/CrudEntityQuerydsl.java // public abstract class CrudEntityQuerydsl implements CrudEntity { // // }
import java.io.IOException; import java.lang.annotation.Annotation; import com.coreoz.plume.db.querydsl.crud.CrudEntityQuerydsl; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import com.fasterxml.jackson.databind.util.Converter; import com.querydsl.codegen.EntityType; import com.querydsl.codegen.Property; import com.querydsl.codegen.SerializerConfig; import com.querydsl.codegen.Supertype; import com.querydsl.codegen.utils.CodeWriter; import com.querydsl.codegen.utils.model.ClassType; import com.querydsl.sql.codegen.ExtendedBeanSerializer;
package com.coreoz.plume.db.querydsl.generation; public class IdBeanSerializer extends ExtendedBeanSerializer { private boolean useJacksonAnnotation; public IdBeanSerializer() { setPrintSupertype(true); this.useJacksonAnnotation = false; } @Override public void serialize(EntityType model, SerializerConfig serializerConfig, CodeWriter writer) throws IOException { injectIdInterface(model); if(useJacksonAnnotation) { injectJacksonAnnotation(model); } super.serialize(model, serializerConfig, writer); } protected void injectIdInterface(EntityType model) { for(Property property : model.getProperties()) { if("id".equals(property.getName()) && Long.class.equals(property.getType().getJavaClass())) {
// Path: plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/crud/CrudEntityQuerydsl.java // public abstract class CrudEntityQuerydsl implements CrudEntity { // // } // Path: plume-db-querydsl-codegen/src/main/java/com/coreoz/plume/db/querydsl/generation/IdBeanSerializer.java import java.io.IOException; import java.lang.annotation.Annotation; import com.coreoz.plume.db.querydsl.crud.CrudEntityQuerydsl; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import com.fasterxml.jackson.databind.util.Converter; import com.querydsl.codegen.EntityType; import com.querydsl.codegen.Property; import com.querydsl.codegen.SerializerConfig; import com.querydsl.codegen.Supertype; import com.querydsl.codegen.utils.CodeWriter; import com.querydsl.codegen.utils.model.ClassType; import com.querydsl.sql.codegen.ExtendedBeanSerializer; package com.coreoz.plume.db.querydsl.generation; public class IdBeanSerializer extends ExtendedBeanSerializer { private boolean useJacksonAnnotation; public IdBeanSerializer() { setPrintSupertype(true); this.useJacksonAnnotation = false; } @Override public void serialize(EntityType model, SerializerConfig serializerConfig, CodeWriter writer) throws IOException { injectIdInterface(model); if(useJacksonAnnotation) { injectJacksonAnnotation(model); } super.serialize(model, serializerConfig, writer); } protected void injectIdInterface(EntityType model) { for(Property property : model.getProperties()) { if("id".equals(property.getName()) && Long.class.equals(property.getType().getJavaClass())) {
model.addSupertype(new Supertype(new ClassType(CrudEntityQuerydsl.class)));
Coreoz/Plume
plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/UserDao.java
// Path: plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/crud/CrudDaoQuerydsl.java // public class CrudDaoQuerydsl<T extends CrudEntity> extends QueryDslDao<T> implements CrudDao<T> { // // private final NumberPath<Long> idPath; // // public CrudDaoQuerydsl(TransactionManagerQuerydsl transactionManager, // RelationalPath<T> table) { // this(transactionManager, table, null); // } // // public CrudDaoQuerydsl(TransactionManagerQuerydsl transactionManager, // RelationalPath<T> table, OrderSpecifier<?> defaultOrder) { // this(transactionManager, table, defaultOrder, new IdPath(table)); // } // // public CrudDaoQuerydsl(TransactionManagerQuerydsl transactionManager, // RelationalPath<T> table, OrderSpecifier<?> defaultOrder, NumberPath<Long> idPath) { // super(transactionManager, table, defaultOrder); // this.idPath = idPath; // } // // // API // // @Override // public T findById(Long id) { // return selectFrom() // .where(idPath.eq(id)) // .fetchFirst(); // } // // @Override // public T save(T entityToUpdate) { // return transactionManager.executeAndReturn(connection -> // save(entityToUpdate, connection) // ); // } // // public T save(T entityToUpdate, Connection connection) { // if(entityToUpdate.getId() == null) { // // insert // entityToUpdate.setId(generateIdentifier()); // transactionManager // .insert(table, connection) // .populate(entityToUpdate) // .execute(); // return entityToUpdate; // } // // update // transactionManager // .update(table, connection) // .populate(entityToUpdate, DefaultMapper.WITH_NULL_BINDINGS) // .where(idPath.eq(entityToUpdate.getId())) // .execute(); // return entityToUpdate; // } // // @Override // public long delete(Long id) { // return transactionManager.executeAndReturn(connection -> // delete(id, connection) // ); // } // // public long delete(Long id, Connection connection) { // return transactionManager // .delete(table, connection) // .where(idPath.eq(id)) // .execute(); // } // // // dao API // // protected long generateIdentifier() { // return IdGenerator.generate(); // } // // // internal // // private static class IdPath extends NumberPath<Long> { // private static final long serialVersionUID = -8749023770318917240L; // // IdPath(RelationalPath<?> base) { // super(Long.class, base, "id"); // } // } // // } // // Path: plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/transaction/TransactionManagerQuerydsl.java // @Singleton // public class TransactionManagerQuerydsl extends TransactionManager { // // private final Configuration querydslConfiguration; // // @Inject // public TransactionManagerQuerydsl(Config config) { // this(config, "db"); // } // // public TransactionManagerQuerydsl(Config config, String prefix) { // super(config, prefix); // // String dialect = config.getString(prefix + ".dialect"); // this.querydslConfiguration = new Configuration(QuerydslTemplates.valueOf(dialect).sqlTemplates()); // } // // public TransactionManagerQuerydsl(DataSource dataSource, Configuration querydslConfiguration) { // super(dataSource); // // this.querydslConfiguration = querydslConfiguration; // } // // // API // // public <Q> SQLQuery<Q> selectQuery() { // SQLQuery<Q> query = new SQLQuery<>(getConnectionProvider(), querydslConfiguration); // query.addListener(SQLCloseListener.DEFAULT); // return query; // } // // public <Q> SQLQuery<Q> selectQuery(Connection connection) { // return new SQLQuery<>(connection, querydslConfiguration); // } // // public SQLDeleteClause delete(RelationalPath<?> path) { // return autoCloseQuery(new SQLDeleteClause(getConnectionProvider(), querydslConfiguration, path)); // } // // public SQLDeleteClause delete(RelationalPath<?> path, Connection connection) { // return new SQLDeleteClause(connection, querydslConfiguration, path); // } // // public SQLInsertClause insert(RelationalPath<?> path) { // return autoCloseQuery(new SQLInsertClause(getConnectionProvider(), querydslConfiguration, path)); // } // // public SQLInsertClause insert(RelationalPath<?> path, Connection connection) { // return new SQLInsertClause(connection, querydslConfiguration, path); // } // // public SQLUpdateClause update(RelationalPath<?> path) { // return autoCloseQuery(new SQLUpdateClause(getConnectionProvider(), querydslConfiguration, path)); // } // // public SQLUpdateClause update(RelationalPath<?> path, Connection connection) { // return new SQLUpdateClause(connection, querydslConfiguration, path); // } // // // internal // // private <T extends AbstractSQLClause<?>> T autoCloseQuery(T query) { // query.addListener(SQLCloseListener.DEFAULT); // return query; // } // // private Supplier<Connection> getConnectionProvider() { // return () -> { // try { // return dataSource().getConnection(); // } catch (SQLException e) { // throw new RuntimeException(e); // } // }; // } // // }
import javax.inject.Inject; import javax.inject.Singleton; import com.coreoz.plume.db.querydsl.crud.CrudDaoQuerydsl; import com.coreoz.plume.db.querydsl.transaction.TransactionManagerQuerydsl;
package com.coreoz.plume.db.querydsl.db; @Singleton public class UserDao extends CrudDaoQuerydsl<User> { @Inject
// Path: plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/crud/CrudDaoQuerydsl.java // public class CrudDaoQuerydsl<T extends CrudEntity> extends QueryDslDao<T> implements CrudDao<T> { // // private final NumberPath<Long> idPath; // // public CrudDaoQuerydsl(TransactionManagerQuerydsl transactionManager, // RelationalPath<T> table) { // this(transactionManager, table, null); // } // // public CrudDaoQuerydsl(TransactionManagerQuerydsl transactionManager, // RelationalPath<T> table, OrderSpecifier<?> defaultOrder) { // this(transactionManager, table, defaultOrder, new IdPath(table)); // } // // public CrudDaoQuerydsl(TransactionManagerQuerydsl transactionManager, // RelationalPath<T> table, OrderSpecifier<?> defaultOrder, NumberPath<Long> idPath) { // super(transactionManager, table, defaultOrder); // this.idPath = idPath; // } // // // API // // @Override // public T findById(Long id) { // return selectFrom() // .where(idPath.eq(id)) // .fetchFirst(); // } // // @Override // public T save(T entityToUpdate) { // return transactionManager.executeAndReturn(connection -> // save(entityToUpdate, connection) // ); // } // // public T save(T entityToUpdate, Connection connection) { // if(entityToUpdate.getId() == null) { // // insert // entityToUpdate.setId(generateIdentifier()); // transactionManager // .insert(table, connection) // .populate(entityToUpdate) // .execute(); // return entityToUpdate; // } // // update // transactionManager // .update(table, connection) // .populate(entityToUpdate, DefaultMapper.WITH_NULL_BINDINGS) // .where(idPath.eq(entityToUpdate.getId())) // .execute(); // return entityToUpdate; // } // // @Override // public long delete(Long id) { // return transactionManager.executeAndReturn(connection -> // delete(id, connection) // ); // } // // public long delete(Long id, Connection connection) { // return transactionManager // .delete(table, connection) // .where(idPath.eq(id)) // .execute(); // } // // // dao API // // protected long generateIdentifier() { // return IdGenerator.generate(); // } // // // internal // // private static class IdPath extends NumberPath<Long> { // private static final long serialVersionUID = -8749023770318917240L; // // IdPath(RelationalPath<?> base) { // super(Long.class, base, "id"); // } // } // // } // // Path: plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/transaction/TransactionManagerQuerydsl.java // @Singleton // public class TransactionManagerQuerydsl extends TransactionManager { // // private final Configuration querydslConfiguration; // // @Inject // public TransactionManagerQuerydsl(Config config) { // this(config, "db"); // } // // public TransactionManagerQuerydsl(Config config, String prefix) { // super(config, prefix); // // String dialect = config.getString(prefix + ".dialect"); // this.querydslConfiguration = new Configuration(QuerydslTemplates.valueOf(dialect).sqlTemplates()); // } // // public TransactionManagerQuerydsl(DataSource dataSource, Configuration querydslConfiguration) { // super(dataSource); // // this.querydslConfiguration = querydslConfiguration; // } // // // API // // public <Q> SQLQuery<Q> selectQuery() { // SQLQuery<Q> query = new SQLQuery<>(getConnectionProvider(), querydslConfiguration); // query.addListener(SQLCloseListener.DEFAULT); // return query; // } // // public <Q> SQLQuery<Q> selectQuery(Connection connection) { // return new SQLQuery<>(connection, querydslConfiguration); // } // // public SQLDeleteClause delete(RelationalPath<?> path) { // return autoCloseQuery(new SQLDeleteClause(getConnectionProvider(), querydslConfiguration, path)); // } // // public SQLDeleteClause delete(RelationalPath<?> path, Connection connection) { // return new SQLDeleteClause(connection, querydslConfiguration, path); // } // // public SQLInsertClause insert(RelationalPath<?> path) { // return autoCloseQuery(new SQLInsertClause(getConnectionProvider(), querydslConfiguration, path)); // } // // public SQLInsertClause insert(RelationalPath<?> path, Connection connection) { // return new SQLInsertClause(connection, querydslConfiguration, path); // } // // public SQLUpdateClause update(RelationalPath<?> path) { // return autoCloseQuery(new SQLUpdateClause(getConnectionProvider(), querydslConfiguration, path)); // } // // public SQLUpdateClause update(RelationalPath<?> path, Connection connection) { // return new SQLUpdateClause(connection, querydslConfiguration, path); // } // // // internal // // private <T extends AbstractSQLClause<?>> T autoCloseQuery(T query) { // query.addListener(SQLCloseListener.DEFAULT); // return query; // } // // private Supplier<Connection> getConnectionProvider() { // return () -> { // try { // return dataSource().getConnection(); // } catch (SQLException e) { // throw new RuntimeException(e); // } // }; // } // // } // Path: plume-db-querydsl/src/test/java/com/coreoz/plume/db/querydsl/db/UserDao.java import javax.inject.Inject; import javax.inject.Singleton; import com.coreoz.plume.db.querydsl.crud.CrudDaoQuerydsl; import com.coreoz.plume.db.querydsl.transaction.TransactionManagerQuerydsl; package com.coreoz.plume.db.querydsl.db; @Singleton public class UserDao extends CrudDaoQuerydsl<User> { @Inject
public UserDao(TransactionManagerQuerydsl transactionManagerQuerydsl) {
Coreoz/Plume
plume-scheduler/src/main/java/com/coreoz/plume/scheduler/guice/GuiceSchedulerModule.java
// Path: plume-services/src/main/java/com/coreoz/plume/guice/GuiceServicesModule.java // public class GuiceServicesModule extends AbstractModule { // // @Override // protected void configure() { // bind(TimeProvider.class).to(SystemTimeProvider.class); // } // // } // // Path: plume-scheduler/src/main/java/com/coreoz/plume/scheduler/SchedulerProvider.java // @Singleton // public class SchedulerProvider implements Provider<Scheduler> { // // private final Scheduler scheduler; // // @Inject // public SchedulerProvider(TimeProvider timeProvider) { // this.scheduler = new Scheduler( // SchedulerConfig // .builder() // .timeProvider(new PlumeTimeProvider(timeProvider)) // .build() // ); // } // // @Override // public Scheduler get() { // return scheduler; // } // // }
import com.coreoz.plume.guice.GuiceServicesModule; import com.coreoz.plume.scheduler.SchedulerProvider; import com.coreoz.wisp.Scheduler; import com.google.inject.AbstractModule;
package com.coreoz.plume.scheduler.guice; public class GuiceSchedulerModule extends AbstractModule { @Override protected void configure() {
// Path: plume-services/src/main/java/com/coreoz/plume/guice/GuiceServicesModule.java // public class GuiceServicesModule extends AbstractModule { // // @Override // protected void configure() { // bind(TimeProvider.class).to(SystemTimeProvider.class); // } // // } // // Path: plume-scheduler/src/main/java/com/coreoz/plume/scheduler/SchedulerProvider.java // @Singleton // public class SchedulerProvider implements Provider<Scheduler> { // // private final Scheduler scheduler; // // @Inject // public SchedulerProvider(TimeProvider timeProvider) { // this.scheduler = new Scheduler( // SchedulerConfig // .builder() // .timeProvider(new PlumeTimeProvider(timeProvider)) // .build() // ); // } // // @Override // public Scheduler get() { // return scheduler; // } // // } // Path: plume-scheduler/src/main/java/com/coreoz/plume/scheduler/guice/GuiceSchedulerModule.java import com.coreoz.plume.guice.GuiceServicesModule; import com.coreoz.plume.scheduler.SchedulerProvider; import com.coreoz.wisp.Scheduler; import com.google.inject.AbstractModule; package com.coreoz.plume.scheduler.guice; public class GuiceSchedulerModule extends AbstractModule { @Override protected void configure() {
install(new GuiceServicesModule());
Coreoz/Plume
plume-scheduler/src/main/java/com/coreoz/plume/scheduler/guice/GuiceSchedulerModule.java
// Path: plume-services/src/main/java/com/coreoz/plume/guice/GuiceServicesModule.java // public class GuiceServicesModule extends AbstractModule { // // @Override // protected void configure() { // bind(TimeProvider.class).to(SystemTimeProvider.class); // } // // } // // Path: plume-scheduler/src/main/java/com/coreoz/plume/scheduler/SchedulerProvider.java // @Singleton // public class SchedulerProvider implements Provider<Scheduler> { // // private final Scheduler scheduler; // // @Inject // public SchedulerProvider(TimeProvider timeProvider) { // this.scheduler = new Scheduler( // SchedulerConfig // .builder() // .timeProvider(new PlumeTimeProvider(timeProvider)) // .build() // ); // } // // @Override // public Scheduler get() { // return scheduler; // } // // }
import com.coreoz.plume.guice.GuiceServicesModule; import com.coreoz.plume.scheduler.SchedulerProvider; import com.coreoz.wisp.Scheduler; import com.google.inject.AbstractModule;
package com.coreoz.plume.scheduler.guice; public class GuiceSchedulerModule extends AbstractModule { @Override protected void configure() { install(new GuiceServicesModule());
// Path: plume-services/src/main/java/com/coreoz/plume/guice/GuiceServicesModule.java // public class GuiceServicesModule extends AbstractModule { // // @Override // protected void configure() { // bind(TimeProvider.class).to(SystemTimeProvider.class); // } // // } // // Path: plume-scheduler/src/main/java/com/coreoz/plume/scheduler/SchedulerProvider.java // @Singleton // public class SchedulerProvider implements Provider<Scheduler> { // // private final Scheduler scheduler; // // @Inject // public SchedulerProvider(TimeProvider timeProvider) { // this.scheduler = new Scheduler( // SchedulerConfig // .builder() // .timeProvider(new PlumeTimeProvider(timeProvider)) // .build() // ); // } // // @Override // public Scheduler get() { // return scheduler; // } // // } // Path: plume-scheduler/src/main/java/com/coreoz/plume/scheduler/guice/GuiceSchedulerModule.java import com.coreoz.plume.guice.GuiceServicesModule; import com.coreoz.plume.scheduler.SchedulerProvider; import com.coreoz.wisp.Scheduler; import com.google.inject.AbstractModule; package com.coreoz.plume.scheduler.guice; public class GuiceSchedulerModule extends AbstractModule { @Override protected void configure() { install(new GuiceServicesModule());
bind(Scheduler.class).toProvider(SchedulerProvider.class);
Coreoz/Plume
plume-services/src/main/java/com/coreoz/plume/guice/GuiceServicesModule.java
// Path: plume-services/src/main/java/com/coreoz/plume/services/time/SystemTimeProvider.java // @Singleton // public class SystemTimeProvider implements TimeProvider { // // private final Clock clock; // // @Inject // public SystemTimeProvider() { // this.clock = Clock.systemDefaultZone(); // } // // @Override // public Clock clock() { // return clock; // } // // } // // Path: plume-services/src/main/java/com/coreoz/plume/services/time/TimeProvider.java // public interface TimeProvider { // // Clock clock(); // // /** // * Returns the current time in milliseconds // */ // default long currentTime() { // return clock().millis(); // } // // default Instant currentInstant() { // return Instant.now(clock()); // } // // default LocalDate currentLocalDate() { // return LocalDate.now(clock()); // } // // default LocalDateTime currentDateTime() { // return LocalDateTime.now(clock()); // } // // }
import com.coreoz.plume.services.time.SystemTimeProvider; import com.coreoz.plume.services.time.TimeProvider; import com.google.inject.AbstractModule;
package com.coreoz.plume.guice; public class GuiceServicesModule extends AbstractModule { @Override protected void configure() {
// Path: plume-services/src/main/java/com/coreoz/plume/services/time/SystemTimeProvider.java // @Singleton // public class SystemTimeProvider implements TimeProvider { // // private final Clock clock; // // @Inject // public SystemTimeProvider() { // this.clock = Clock.systemDefaultZone(); // } // // @Override // public Clock clock() { // return clock; // } // // } // // Path: plume-services/src/main/java/com/coreoz/plume/services/time/TimeProvider.java // public interface TimeProvider { // // Clock clock(); // // /** // * Returns the current time in milliseconds // */ // default long currentTime() { // return clock().millis(); // } // // default Instant currentInstant() { // return Instant.now(clock()); // } // // default LocalDate currentLocalDate() { // return LocalDate.now(clock()); // } // // default LocalDateTime currentDateTime() { // return LocalDateTime.now(clock()); // } // // } // Path: plume-services/src/main/java/com/coreoz/plume/guice/GuiceServicesModule.java import com.coreoz.plume.services.time.SystemTimeProvider; import com.coreoz.plume.services.time.TimeProvider; import com.google.inject.AbstractModule; package com.coreoz.plume.guice; public class GuiceServicesModule extends AbstractModule { @Override protected void configure() {
bind(TimeProvider.class).to(SystemTimeProvider.class);
Coreoz/Plume
plume-services/src/main/java/com/coreoz/plume/guice/GuiceServicesModule.java
// Path: plume-services/src/main/java/com/coreoz/plume/services/time/SystemTimeProvider.java // @Singleton // public class SystemTimeProvider implements TimeProvider { // // private final Clock clock; // // @Inject // public SystemTimeProvider() { // this.clock = Clock.systemDefaultZone(); // } // // @Override // public Clock clock() { // return clock; // } // // } // // Path: plume-services/src/main/java/com/coreoz/plume/services/time/TimeProvider.java // public interface TimeProvider { // // Clock clock(); // // /** // * Returns the current time in milliseconds // */ // default long currentTime() { // return clock().millis(); // } // // default Instant currentInstant() { // return Instant.now(clock()); // } // // default LocalDate currentLocalDate() { // return LocalDate.now(clock()); // } // // default LocalDateTime currentDateTime() { // return LocalDateTime.now(clock()); // } // // }
import com.coreoz.plume.services.time.SystemTimeProvider; import com.coreoz.plume.services.time.TimeProvider; import com.google.inject.AbstractModule;
package com.coreoz.plume.guice; public class GuiceServicesModule extends AbstractModule { @Override protected void configure() {
// Path: plume-services/src/main/java/com/coreoz/plume/services/time/SystemTimeProvider.java // @Singleton // public class SystemTimeProvider implements TimeProvider { // // private final Clock clock; // // @Inject // public SystemTimeProvider() { // this.clock = Clock.systemDefaultZone(); // } // // @Override // public Clock clock() { // return clock; // } // // } // // Path: plume-services/src/main/java/com/coreoz/plume/services/time/TimeProvider.java // public interface TimeProvider { // // Clock clock(); // // /** // * Returns the current time in milliseconds // */ // default long currentTime() { // return clock().millis(); // } // // default Instant currentInstant() { // return Instant.now(clock()); // } // // default LocalDate currentLocalDate() { // return LocalDate.now(clock()); // } // // default LocalDateTime currentDateTime() { // return LocalDateTime.now(clock()); // } // // } // Path: plume-services/src/main/java/com/coreoz/plume/guice/GuiceServicesModule.java import com.coreoz.plume.services.time.SystemTimeProvider; import com.coreoz.plume.services.time.TimeProvider; import com.google.inject.AbstractModule; package com.coreoz.plume.guice; public class GuiceServicesModule extends AbstractModule { @Override protected void configure() {
bind(TimeProvider.class).to(SystemTimeProvider.class);
Coreoz/Plume
plume-mail/src/main/java/com/coreoz/plume/mail/dagger/DaggerMailModule.java
// Path: plume-mail/src/main/java/com/coreoz/plume/mail/MailerProvider.java // @Singleton // public class MailerProvider implements Provider<Mailer> { // // private final Mailer mailer; // // @Inject // public MailerProvider(Config config) { // this.mailer = initializeMailer(config); // } // // @Override // public Mailer get() { // return mailer; // } // // private static Mailer initializeMailer(Config config) { // ConfigLoader.loadProperties( // // Properties are in ISO 8859 1 // new ByteArrayInputStream(readMailConfiguration(config).getBytes(StandardCharsets.ISO_8859_1)), // true // ); // // return MailerBuilder.buildMailer(); // } // // // visible for testing // static String readMailConfiguration(Config config) { // return config // .getObject("mail") // .entrySet() // .stream() // .map(entry -> "simplejavamail." + entry.getKey() + "=" + entry.getValue().unwrapped().toString()) // .collect(Collectors.joining("\n")); // } // // }
import javax.inject.Singleton; import org.simplejavamail.api.mailer.Mailer; import com.coreoz.plume.mail.MailerProvider; import dagger.Module; import dagger.Provides;
package com.coreoz.plume.mail.dagger; @Module public class DaggerMailModule { @Provides @Singleton
// Path: plume-mail/src/main/java/com/coreoz/plume/mail/MailerProvider.java // @Singleton // public class MailerProvider implements Provider<Mailer> { // // private final Mailer mailer; // // @Inject // public MailerProvider(Config config) { // this.mailer = initializeMailer(config); // } // // @Override // public Mailer get() { // return mailer; // } // // private static Mailer initializeMailer(Config config) { // ConfigLoader.loadProperties( // // Properties are in ISO 8859 1 // new ByteArrayInputStream(readMailConfiguration(config).getBytes(StandardCharsets.ISO_8859_1)), // true // ); // // return MailerBuilder.buildMailer(); // } // // // visible for testing // static String readMailConfiguration(Config config) { // return config // .getObject("mail") // .entrySet() // .stream() // .map(entry -> "simplejavamail." + entry.getKey() + "=" + entry.getValue().unwrapped().toString()) // .collect(Collectors.joining("\n")); // } // // } // Path: plume-mail/src/main/java/com/coreoz/plume/mail/dagger/DaggerMailModule.java import javax.inject.Singleton; import org.simplejavamail.api.mailer.Mailer; import com.coreoz.plume.mail.MailerProvider; import dagger.Module; import dagger.Provides; package com.coreoz.plume.mail.dagger; @Module public class DaggerMailModule { @Provides @Singleton
static Mailer provideMailer(MailerProvider mailerProvider) {
Coreoz/Plume
plume-web-jersey/src/main/java/com/coreoz/plume/jersey/guice/GuiceJacksonModule.java
// Path: plume-web-jersey/src/main/java/com/coreoz/plume/jersey/jackson/ObjectMapperProvider.java // @Singleton // public class ObjectMapperProvider implements Provider<ObjectMapper> { // // private final ObjectMapper objectMapper; // // @Inject // public ObjectMapperProvider() { // this.objectMapper = new ObjectMapper() // .registerModule(new JavaTimeModule()) // .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) // .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) // .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // } // // @Override // public ObjectMapper get() { // return objectMapper; // } // // }
import com.coreoz.plume.jersey.jackson.ObjectMapperProvider; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.inject.AbstractModule;
package com.coreoz.plume.jersey.guice; public class GuiceJacksonModule extends AbstractModule { @Override protected void configure() {
// Path: plume-web-jersey/src/main/java/com/coreoz/plume/jersey/jackson/ObjectMapperProvider.java // @Singleton // public class ObjectMapperProvider implements Provider<ObjectMapper> { // // private final ObjectMapper objectMapper; // // @Inject // public ObjectMapperProvider() { // this.objectMapper = new ObjectMapper() // .registerModule(new JavaTimeModule()) // .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) // .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) // .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); // } // // @Override // public ObjectMapper get() { // return objectMapper; // } // // } // Path: plume-web-jersey/src/main/java/com/coreoz/plume/jersey/guice/GuiceJacksonModule.java import com.coreoz.plume.jersey.jackson.ObjectMapperProvider; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.inject.AbstractModule; package com.coreoz.plume.jersey.guice; public class GuiceJacksonModule extends AbstractModule { @Override protected void configure() {
bind(ObjectMapper.class).toProvider(ObjectMapperProvider.class);
Coreoz/Plume
plume-mail/src/main/java/com/coreoz/plume/mail/guice/GuiceMailModule.java
// Path: plume-mail/src/main/java/com/coreoz/plume/mail/MailerProvider.java // @Singleton // public class MailerProvider implements Provider<Mailer> { // // private final Mailer mailer; // // @Inject // public MailerProvider(Config config) { // this.mailer = initializeMailer(config); // } // // @Override // public Mailer get() { // return mailer; // } // // private static Mailer initializeMailer(Config config) { // ConfigLoader.loadProperties( // // Properties are in ISO 8859 1 // new ByteArrayInputStream(readMailConfiguration(config).getBytes(StandardCharsets.ISO_8859_1)), // true // ); // // return MailerBuilder.buildMailer(); // } // // // visible for testing // static String readMailConfiguration(Config config) { // return config // .getObject("mail") // .entrySet() // .stream() // .map(entry -> "simplejavamail." + entry.getKey() + "=" + entry.getValue().unwrapped().toString()) // .collect(Collectors.joining("\n")); // } // // }
import org.simplejavamail.api.mailer.Mailer; import com.coreoz.plume.mail.MailerProvider; import com.google.inject.AbstractModule;
package com.coreoz.plume.mail.guice; public class GuiceMailModule extends AbstractModule { @Override protected void configure() {
// Path: plume-mail/src/main/java/com/coreoz/plume/mail/MailerProvider.java // @Singleton // public class MailerProvider implements Provider<Mailer> { // // private final Mailer mailer; // // @Inject // public MailerProvider(Config config) { // this.mailer = initializeMailer(config); // } // // @Override // public Mailer get() { // return mailer; // } // // private static Mailer initializeMailer(Config config) { // ConfigLoader.loadProperties( // // Properties are in ISO 8859 1 // new ByteArrayInputStream(readMailConfiguration(config).getBytes(StandardCharsets.ISO_8859_1)), // true // ); // // return MailerBuilder.buildMailer(); // } // // // visible for testing // static String readMailConfiguration(Config config) { // return config // .getObject("mail") // .entrySet() // .stream() // .map(entry -> "simplejavamail." + entry.getKey() + "=" + entry.getValue().unwrapped().toString()) // .collect(Collectors.joining("\n")); // } // // } // Path: plume-mail/src/main/java/com/coreoz/plume/mail/guice/GuiceMailModule.java import org.simplejavamail.api.mailer.Mailer; import com.coreoz.plume.mail.MailerProvider; import com.google.inject.AbstractModule; package com.coreoz.plume.mail.guice; public class GuiceMailModule extends AbstractModule { @Override protected void configure() {
bind(Mailer.class).toProvider(MailerProvider.class);
Coreoz/Plume
plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/guice/GuiceQuerydslModule.java
// Path: plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/transaction/TransactionManagerQuerydsl.java // @Singleton // public class TransactionManagerQuerydsl extends TransactionManager { // // private final Configuration querydslConfiguration; // // @Inject // public TransactionManagerQuerydsl(Config config) { // this(config, "db"); // } // // public TransactionManagerQuerydsl(Config config, String prefix) { // super(config, prefix); // // String dialect = config.getString(prefix + ".dialect"); // this.querydslConfiguration = new Configuration(QuerydslTemplates.valueOf(dialect).sqlTemplates()); // } // // public TransactionManagerQuerydsl(DataSource dataSource, Configuration querydslConfiguration) { // super(dataSource); // // this.querydslConfiguration = querydslConfiguration; // } // // // API // // public <Q> SQLQuery<Q> selectQuery() { // SQLQuery<Q> query = new SQLQuery<>(getConnectionProvider(), querydslConfiguration); // query.addListener(SQLCloseListener.DEFAULT); // return query; // } // // public <Q> SQLQuery<Q> selectQuery(Connection connection) { // return new SQLQuery<>(connection, querydslConfiguration); // } // // public SQLDeleteClause delete(RelationalPath<?> path) { // return autoCloseQuery(new SQLDeleteClause(getConnectionProvider(), querydslConfiguration, path)); // } // // public SQLDeleteClause delete(RelationalPath<?> path, Connection connection) { // return new SQLDeleteClause(connection, querydslConfiguration, path); // } // // public SQLInsertClause insert(RelationalPath<?> path) { // return autoCloseQuery(new SQLInsertClause(getConnectionProvider(), querydslConfiguration, path)); // } // // public SQLInsertClause insert(RelationalPath<?> path, Connection connection) { // return new SQLInsertClause(connection, querydslConfiguration, path); // } // // public SQLUpdateClause update(RelationalPath<?> path) { // return autoCloseQuery(new SQLUpdateClause(getConnectionProvider(), querydslConfiguration, path)); // } // // public SQLUpdateClause update(RelationalPath<?> path, Connection connection) { // return new SQLUpdateClause(connection, querydslConfiguration, path); // } // // // internal // // private <T extends AbstractSQLClause<?>> T autoCloseQuery(T query) { // query.addListener(SQLCloseListener.DEFAULT); // return query; // } // // private Supplier<Connection> getConnectionProvider() { // return () -> { // try { // return dataSource().getConnection(); // } catch (SQLException e) { // throw new RuntimeException(e); // } // }; // } // // } // // Path: plume-db/src/main/java/com/coreoz/plume/db/transaction/TransactionManager.java // @Singleton // public class TransactionManager { // // private final DataSource dataSource; // // @Inject // public TransactionManager(Config config) { // this(config, "db"); // } // // public TransactionManager(Config config, String prefix) { // this(HikariDataSources.fromConfig(config, prefix + ".hikari")); // } // // public TransactionManager(DataSource dataSource) { // this.dataSource = dataSource; // } // // // API // // public DataSource dataSource() { // return dataSource; // } // // public <T> T executeAndReturn(Function<Connection, T> toExecuteOnDb) { // Connection connection = null; // Boolean initialAutoCommit = null; // try { // connection = dataSource.getConnection(); // initialAutoCommit = connection.getAutoCommit(); // connection.setAutoCommit(false); // T result = toExecuteOnDb.apply(connection); // connection.commit(); // return result; // } catch(Throwable e) { // try { // if(connection != null) { // connection.rollback(); // } // } catch (Throwable e2) { // // never mind if the connection cannot be rolled back // } // Throwables.throwIfUnchecked(e); // throw new RuntimeException(e); // } finally { // if(connection != null) { // try { // if(initialAutoCommit != null) { // connection.setAutoCommit(initialAutoCommit); // } // connection.close(); // } catch (SQLException e) { // // never mind if the connection cannot be closed // } // } // } // } // // public void execute(Consumer<Connection> toExecuteOnDb) { // executeAndReturn(connection -> { // toExecuteOnDb.accept(connection); // return null; // }); // } // // }
import com.coreoz.plume.db.querydsl.transaction.TransactionManagerQuerydsl; import com.coreoz.plume.db.transaction.TransactionManager; import com.google.inject.AbstractModule;
package com.coreoz.plume.db.querydsl.guice; public class GuiceQuerydslModule extends AbstractModule { @Override protected void configure() {
// Path: plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/transaction/TransactionManagerQuerydsl.java // @Singleton // public class TransactionManagerQuerydsl extends TransactionManager { // // private final Configuration querydslConfiguration; // // @Inject // public TransactionManagerQuerydsl(Config config) { // this(config, "db"); // } // // public TransactionManagerQuerydsl(Config config, String prefix) { // super(config, prefix); // // String dialect = config.getString(prefix + ".dialect"); // this.querydslConfiguration = new Configuration(QuerydslTemplates.valueOf(dialect).sqlTemplates()); // } // // public TransactionManagerQuerydsl(DataSource dataSource, Configuration querydslConfiguration) { // super(dataSource); // // this.querydslConfiguration = querydslConfiguration; // } // // // API // // public <Q> SQLQuery<Q> selectQuery() { // SQLQuery<Q> query = new SQLQuery<>(getConnectionProvider(), querydslConfiguration); // query.addListener(SQLCloseListener.DEFAULT); // return query; // } // // public <Q> SQLQuery<Q> selectQuery(Connection connection) { // return new SQLQuery<>(connection, querydslConfiguration); // } // // public SQLDeleteClause delete(RelationalPath<?> path) { // return autoCloseQuery(new SQLDeleteClause(getConnectionProvider(), querydslConfiguration, path)); // } // // public SQLDeleteClause delete(RelationalPath<?> path, Connection connection) { // return new SQLDeleteClause(connection, querydslConfiguration, path); // } // // public SQLInsertClause insert(RelationalPath<?> path) { // return autoCloseQuery(new SQLInsertClause(getConnectionProvider(), querydslConfiguration, path)); // } // // public SQLInsertClause insert(RelationalPath<?> path, Connection connection) { // return new SQLInsertClause(connection, querydslConfiguration, path); // } // // public SQLUpdateClause update(RelationalPath<?> path) { // return autoCloseQuery(new SQLUpdateClause(getConnectionProvider(), querydslConfiguration, path)); // } // // public SQLUpdateClause update(RelationalPath<?> path, Connection connection) { // return new SQLUpdateClause(connection, querydslConfiguration, path); // } // // // internal // // private <T extends AbstractSQLClause<?>> T autoCloseQuery(T query) { // query.addListener(SQLCloseListener.DEFAULT); // return query; // } // // private Supplier<Connection> getConnectionProvider() { // return () -> { // try { // return dataSource().getConnection(); // } catch (SQLException e) { // throw new RuntimeException(e); // } // }; // } // // } // // Path: plume-db/src/main/java/com/coreoz/plume/db/transaction/TransactionManager.java // @Singleton // public class TransactionManager { // // private final DataSource dataSource; // // @Inject // public TransactionManager(Config config) { // this(config, "db"); // } // // public TransactionManager(Config config, String prefix) { // this(HikariDataSources.fromConfig(config, prefix + ".hikari")); // } // // public TransactionManager(DataSource dataSource) { // this.dataSource = dataSource; // } // // // API // // public DataSource dataSource() { // return dataSource; // } // // public <T> T executeAndReturn(Function<Connection, T> toExecuteOnDb) { // Connection connection = null; // Boolean initialAutoCommit = null; // try { // connection = dataSource.getConnection(); // initialAutoCommit = connection.getAutoCommit(); // connection.setAutoCommit(false); // T result = toExecuteOnDb.apply(connection); // connection.commit(); // return result; // } catch(Throwable e) { // try { // if(connection != null) { // connection.rollback(); // } // } catch (Throwable e2) { // // never mind if the connection cannot be rolled back // } // Throwables.throwIfUnchecked(e); // throw new RuntimeException(e); // } finally { // if(connection != null) { // try { // if(initialAutoCommit != null) { // connection.setAutoCommit(initialAutoCommit); // } // connection.close(); // } catch (SQLException e) { // // never mind if the connection cannot be closed // } // } // } // } // // public void execute(Consumer<Connection> toExecuteOnDb) { // executeAndReturn(connection -> { // toExecuteOnDb.accept(connection); // return null; // }); // } // // } // Path: plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/guice/GuiceQuerydslModule.java import com.coreoz.plume.db.querydsl.transaction.TransactionManagerQuerydsl; import com.coreoz.plume.db.transaction.TransactionManager; import com.google.inject.AbstractModule; package com.coreoz.plume.db.querydsl.guice; public class GuiceQuerydslModule extends AbstractModule { @Override protected void configure() {
bind(TransactionManager.class).to(TransactionManagerQuerydsl.class);
Coreoz/Plume
plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/guice/GuiceQuerydslModule.java
// Path: plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/transaction/TransactionManagerQuerydsl.java // @Singleton // public class TransactionManagerQuerydsl extends TransactionManager { // // private final Configuration querydslConfiguration; // // @Inject // public TransactionManagerQuerydsl(Config config) { // this(config, "db"); // } // // public TransactionManagerQuerydsl(Config config, String prefix) { // super(config, prefix); // // String dialect = config.getString(prefix + ".dialect"); // this.querydslConfiguration = new Configuration(QuerydslTemplates.valueOf(dialect).sqlTemplates()); // } // // public TransactionManagerQuerydsl(DataSource dataSource, Configuration querydslConfiguration) { // super(dataSource); // // this.querydslConfiguration = querydslConfiguration; // } // // // API // // public <Q> SQLQuery<Q> selectQuery() { // SQLQuery<Q> query = new SQLQuery<>(getConnectionProvider(), querydslConfiguration); // query.addListener(SQLCloseListener.DEFAULT); // return query; // } // // public <Q> SQLQuery<Q> selectQuery(Connection connection) { // return new SQLQuery<>(connection, querydslConfiguration); // } // // public SQLDeleteClause delete(RelationalPath<?> path) { // return autoCloseQuery(new SQLDeleteClause(getConnectionProvider(), querydslConfiguration, path)); // } // // public SQLDeleteClause delete(RelationalPath<?> path, Connection connection) { // return new SQLDeleteClause(connection, querydslConfiguration, path); // } // // public SQLInsertClause insert(RelationalPath<?> path) { // return autoCloseQuery(new SQLInsertClause(getConnectionProvider(), querydslConfiguration, path)); // } // // public SQLInsertClause insert(RelationalPath<?> path, Connection connection) { // return new SQLInsertClause(connection, querydslConfiguration, path); // } // // public SQLUpdateClause update(RelationalPath<?> path) { // return autoCloseQuery(new SQLUpdateClause(getConnectionProvider(), querydslConfiguration, path)); // } // // public SQLUpdateClause update(RelationalPath<?> path, Connection connection) { // return new SQLUpdateClause(connection, querydslConfiguration, path); // } // // // internal // // private <T extends AbstractSQLClause<?>> T autoCloseQuery(T query) { // query.addListener(SQLCloseListener.DEFAULT); // return query; // } // // private Supplier<Connection> getConnectionProvider() { // return () -> { // try { // return dataSource().getConnection(); // } catch (SQLException e) { // throw new RuntimeException(e); // } // }; // } // // } // // Path: plume-db/src/main/java/com/coreoz/plume/db/transaction/TransactionManager.java // @Singleton // public class TransactionManager { // // private final DataSource dataSource; // // @Inject // public TransactionManager(Config config) { // this(config, "db"); // } // // public TransactionManager(Config config, String prefix) { // this(HikariDataSources.fromConfig(config, prefix + ".hikari")); // } // // public TransactionManager(DataSource dataSource) { // this.dataSource = dataSource; // } // // // API // // public DataSource dataSource() { // return dataSource; // } // // public <T> T executeAndReturn(Function<Connection, T> toExecuteOnDb) { // Connection connection = null; // Boolean initialAutoCommit = null; // try { // connection = dataSource.getConnection(); // initialAutoCommit = connection.getAutoCommit(); // connection.setAutoCommit(false); // T result = toExecuteOnDb.apply(connection); // connection.commit(); // return result; // } catch(Throwable e) { // try { // if(connection != null) { // connection.rollback(); // } // } catch (Throwable e2) { // // never mind if the connection cannot be rolled back // } // Throwables.throwIfUnchecked(e); // throw new RuntimeException(e); // } finally { // if(connection != null) { // try { // if(initialAutoCommit != null) { // connection.setAutoCommit(initialAutoCommit); // } // connection.close(); // } catch (SQLException e) { // // never mind if the connection cannot be closed // } // } // } // } // // public void execute(Consumer<Connection> toExecuteOnDb) { // executeAndReturn(connection -> { // toExecuteOnDb.accept(connection); // return null; // }); // } // // }
import com.coreoz.plume.db.querydsl.transaction.TransactionManagerQuerydsl; import com.coreoz.plume.db.transaction.TransactionManager; import com.google.inject.AbstractModule;
package com.coreoz.plume.db.querydsl.guice; public class GuiceQuerydslModule extends AbstractModule { @Override protected void configure() {
// Path: plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/transaction/TransactionManagerQuerydsl.java // @Singleton // public class TransactionManagerQuerydsl extends TransactionManager { // // private final Configuration querydslConfiguration; // // @Inject // public TransactionManagerQuerydsl(Config config) { // this(config, "db"); // } // // public TransactionManagerQuerydsl(Config config, String prefix) { // super(config, prefix); // // String dialect = config.getString(prefix + ".dialect"); // this.querydslConfiguration = new Configuration(QuerydslTemplates.valueOf(dialect).sqlTemplates()); // } // // public TransactionManagerQuerydsl(DataSource dataSource, Configuration querydslConfiguration) { // super(dataSource); // // this.querydslConfiguration = querydslConfiguration; // } // // // API // // public <Q> SQLQuery<Q> selectQuery() { // SQLQuery<Q> query = new SQLQuery<>(getConnectionProvider(), querydslConfiguration); // query.addListener(SQLCloseListener.DEFAULT); // return query; // } // // public <Q> SQLQuery<Q> selectQuery(Connection connection) { // return new SQLQuery<>(connection, querydslConfiguration); // } // // public SQLDeleteClause delete(RelationalPath<?> path) { // return autoCloseQuery(new SQLDeleteClause(getConnectionProvider(), querydslConfiguration, path)); // } // // public SQLDeleteClause delete(RelationalPath<?> path, Connection connection) { // return new SQLDeleteClause(connection, querydslConfiguration, path); // } // // public SQLInsertClause insert(RelationalPath<?> path) { // return autoCloseQuery(new SQLInsertClause(getConnectionProvider(), querydslConfiguration, path)); // } // // public SQLInsertClause insert(RelationalPath<?> path, Connection connection) { // return new SQLInsertClause(connection, querydslConfiguration, path); // } // // public SQLUpdateClause update(RelationalPath<?> path) { // return autoCloseQuery(new SQLUpdateClause(getConnectionProvider(), querydslConfiguration, path)); // } // // public SQLUpdateClause update(RelationalPath<?> path, Connection connection) { // return new SQLUpdateClause(connection, querydslConfiguration, path); // } // // // internal // // private <T extends AbstractSQLClause<?>> T autoCloseQuery(T query) { // query.addListener(SQLCloseListener.DEFAULT); // return query; // } // // private Supplier<Connection> getConnectionProvider() { // return () -> { // try { // return dataSource().getConnection(); // } catch (SQLException e) { // throw new RuntimeException(e); // } // }; // } // // } // // Path: plume-db/src/main/java/com/coreoz/plume/db/transaction/TransactionManager.java // @Singleton // public class TransactionManager { // // private final DataSource dataSource; // // @Inject // public TransactionManager(Config config) { // this(config, "db"); // } // // public TransactionManager(Config config, String prefix) { // this(HikariDataSources.fromConfig(config, prefix + ".hikari")); // } // // public TransactionManager(DataSource dataSource) { // this.dataSource = dataSource; // } // // // API // // public DataSource dataSource() { // return dataSource; // } // // public <T> T executeAndReturn(Function<Connection, T> toExecuteOnDb) { // Connection connection = null; // Boolean initialAutoCommit = null; // try { // connection = dataSource.getConnection(); // initialAutoCommit = connection.getAutoCommit(); // connection.setAutoCommit(false); // T result = toExecuteOnDb.apply(connection); // connection.commit(); // return result; // } catch(Throwable e) { // try { // if(connection != null) { // connection.rollback(); // } // } catch (Throwable e2) { // // never mind if the connection cannot be rolled back // } // Throwables.throwIfUnchecked(e); // throw new RuntimeException(e); // } finally { // if(connection != null) { // try { // if(initialAutoCommit != null) { // connection.setAutoCommit(initialAutoCommit); // } // connection.close(); // } catch (SQLException e) { // // never mind if the connection cannot be closed // } // } // } // } // // public void execute(Consumer<Connection> toExecuteOnDb) { // executeAndReturn(connection -> { // toExecuteOnDb.accept(connection); // return null; // }); // } // // } // Path: plume-db-querydsl/src/main/java/com/coreoz/plume/db/querydsl/guice/GuiceQuerydslModule.java import com.coreoz.plume.db.querydsl.transaction.TransactionManagerQuerydsl; import com.coreoz.plume.db.transaction.TransactionManager; import com.google.inject.AbstractModule; package com.coreoz.plume.db.querydsl.guice; public class GuiceQuerydslModule extends AbstractModule { @Override protected void configure() {
bind(TransactionManager.class).to(TransactionManagerQuerydsl.class);
Coreoz/Plume
plume-scheduler/src/main/java/com/coreoz/plume/scheduler/SchedulerProvider.java
// Path: plume-services/src/main/java/com/coreoz/plume/services/time/TimeProvider.java // public interface TimeProvider { // // Clock clock(); // // /** // * Returns the current time in milliseconds // */ // default long currentTime() { // return clock().millis(); // } // // default Instant currentInstant() { // return Instant.now(clock()); // } // // default LocalDate currentLocalDate() { // return LocalDate.now(clock()); // } // // default LocalDateTime currentDateTime() { // return LocalDateTime.now(clock()); // } // // }
import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Singleton; import com.coreoz.plume.services.time.TimeProvider; import com.coreoz.wisp.Scheduler; import com.coreoz.wisp.SchedulerConfig;
package com.coreoz.plume.scheduler; @Singleton public class SchedulerProvider implements Provider<Scheduler> { private final Scheduler scheduler; @Inject
// Path: plume-services/src/main/java/com/coreoz/plume/services/time/TimeProvider.java // public interface TimeProvider { // // Clock clock(); // // /** // * Returns the current time in milliseconds // */ // default long currentTime() { // return clock().millis(); // } // // default Instant currentInstant() { // return Instant.now(clock()); // } // // default LocalDate currentLocalDate() { // return LocalDate.now(clock()); // } // // default LocalDateTime currentDateTime() { // return LocalDateTime.now(clock()); // } // // } // Path: plume-scheduler/src/main/java/com/coreoz/plume/scheduler/SchedulerProvider.java import javax.inject.Inject; import javax.inject.Provider; import javax.inject.Singleton; import com.coreoz.plume.services.time.TimeProvider; import com.coreoz.wisp.Scheduler; import com.coreoz.wisp.SchedulerConfig; package com.coreoz.plume.scheduler; @Singleton public class SchedulerProvider implements Provider<Scheduler> { private final Scheduler scheduler; @Inject
public SchedulerProvider(TimeProvider timeProvider) {
Coreoz/Plume
plume-db/src/main/java/com/coreoz/plume/db/guice/DataSourceModule.java
// Path: plume-db/src/main/java/com/coreoz/plume/db/transaction/DataSourceProvider.java // @Singleton // public class DataSourceProvider implements Provider<DataSource> { // // private final DataSource dataSource; // // @Inject // public DataSourceProvider(TransactionManager transactionManager) { // this.dataSource = transactionManager.dataSource(); // } // // @Override // public DataSource get() { // return dataSource; // } // // }
import javax.sql.DataSource; import com.coreoz.plume.db.transaction.DataSourceProvider; import com.google.inject.AbstractModule;
package com.coreoz.plume.db.guice; public class DataSourceModule extends AbstractModule { @Override protected void configure() {
// Path: plume-db/src/main/java/com/coreoz/plume/db/transaction/DataSourceProvider.java // @Singleton // public class DataSourceProvider implements Provider<DataSource> { // // private final DataSource dataSource; // // @Inject // public DataSourceProvider(TransactionManager transactionManager) { // this.dataSource = transactionManager.dataSource(); // } // // @Override // public DataSource get() { // return dataSource; // } // // } // Path: plume-db/src/main/java/com/coreoz/plume/db/guice/DataSourceModule.java import javax.sql.DataSource; import com.coreoz.plume.db.transaction.DataSourceProvider; import com.google.inject.AbstractModule; package com.coreoz.plume.db.guice; public class DataSourceModule extends AbstractModule { @Override protected void configure() {
bind(DataSource.class).toProvider(DataSourceProvider.class);
Coreoz/Plume
plume-scheduler/src/main/java/com/coreoz/plume/scheduler/dagger/DaggerSchedulerModule.java
// Path: plume-services/src/main/java/com/coreoz/plume/dagger/DaggerServicesModule.java // @Module // public class DaggerServicesModule { // // @Provides // @Singleton // static TimeProvider provideTimeProvider(SystemTimeProvider systemTimeProvider) { // return systemTimeProvider; // } // // } // // Path: plume-scheduler/src/main/java/com/coreoz/plume/scheduler/SchedulerProvider.java // @Singleton // public class SchedulerProvider implements Provider<Scheduler> { // // private final Scheduler scheduler; // // @Inject // public SchedulerProvider(TimeProvider timeProvider) { // this.scheduler = new Scheduler( // SchedulerConfig // .builder() // .timeProvider(new PlumeTimeProvider(timeProvider)) // .build() // ); // } // // @Override // public Scheduler get() { // return scheduler; // } // // }
import javax.inject.Singleton; import com.coreoz.plume.dagger.DaggerServicesModule; import com.coreoz.plume.scheduler.SchedulerProvider; import com.coreoz.wisp.Scheduler; import dagger.Module; import dagger.Provides;
package com.coreoz.plume.scheduler.dagger; @Module(includes = DaggerServicesModule.class) public class DaggerSchedulerModule { @Provides @Singleton
// Path: plume-services/src/main/java/com/coreoz/plume/dagger/DaggerServicesModule.java // @Module // public class DaggerServicesModule { // // @Provides // @Singleton // static TimeProvider provideTimeProvider(SystemTimeProvider systemTimeProvider) { // return systemTimeProvider; // } // // } // // Path: plume-scheduler/src/main/java/com/coreoz/plume/scheduler/SchedulerProvider.java // @Singleton // public class SchedulerProvider implements Provider<Scheduler> { // // private final Scheduler scheduler; // // @Inject // public SchedulerProvider(TimeProvider timeProvider) { // this.scheduler = new Scheduler( // SchedulerConfig // .builder() // .timeProvider(new PlumeTimeProvider(timeProvider)) // .build() // ); // } // // @Override // public Scheduler get() { // return scheduler; // } // // } // Path: plume-scheduler/src/main/java/com/coreoz/plume/scheduler/dagger/DaggerSchedulerModule.java import javax.inject.Singleton; import com.coreoz.plume.dagger.DaggerServicesModule; import com.coreoz.plume.scheduler.SchedulerProvider; import com.coreoz.wisp.Scheduler; import dagger.Module; import dagger.Provides; package com.coreoz.plume.scheduler.dagger; @Module(includes = DaggerServicesModule.class) public class DaggerSchedulerModule { @Provides @Singleton
static Scheduler provideScheduler(SchedulerProvider schedulerProvider) {
Coreoz/Plume
plume-services/src/main/java/com/coreoz/plume/dagger/DaggerServicesModule.java
// Path: plume-services/src/main/java/com/coreoz/plume/services/time/SystemTimeProvider.java // @Singleton // public class SystemTimeProvider implements TimeProvider { // // private final Clock clock; // // @Inject // public SystemTimeProvider() { // this.clock = Clock.systemDefaultZone(); // } // // @Override // public Clock clock() { // return clock; // } // // } // // Path: plume-services/src/main/java/com/coreoz/plume/services/time/TimeProvider.java // public interface TimeProvider { // // Clock clock(); // // /** // * Returns the current time in milliseconds // */ // default long currentTime() { // return clock().millis(); // } // // default Instant currentInstant() { // return Instant.now(clock()); // } // // default LocalDate currentLocalDate() { // return LocalDate.now(clock()); // } // // default LocalDateTime currentDateTime() { // return LocalDateTime.now(clock()); // } // // }
import javax.inject.Singleton; import com.coreoz.plume.services.time.SystemTimeProvider; import com.coreoz.plume.services.time.TimeProvider; import dagger.Module; import dagger.Provides;
package com.coreoz.plume.dagger; @Module public class DaggerServicesModule { @Provides @Singleton
// Path: plume-services/src/main/java/com/coreoz/plume/services/time/SystemTimeProvider.java // @Singleton // public class SystemTimeProvider implements TimeProvider { // // private final Clock clock; // // @Inject // public SystemTimeProvider() { // this.clock = Clock.systemDefaultZone(); // } // // @Override // public Clock clock() { // return clock; // } // // } // // Path: plume-services/src/main/java/com/coreoz/plume/services/time/TimeProvider.java // public interface TimeProvider { // // Clock clock(); // // /** // * Returns the current time in milliseconds // */ // default long currentTime() { // return clock().millis(); // } // // default Instant currentInstant() { // return Instant.now(clock()); // } // // default LocalDate currentLocalDate() { // return LocalDate.now(clock()); // } // // default LocalDateTime currentDateTime() { // return LocalDateTime.now(clock()); // } // // } // Path: plume-services/src/main/java/com/coreoz/plume/dagger/DaggerServicesModule.java import javax.inject.Singleton; import com.coreoz.plume.services.time.SystemTimeProvider; import com.coreoz.plume.services.time.TimeProvider; import dagger.Module; import dagger.Provides; package com.coreoz.plume.dagger; @Module public class DaggerServicesModule { @Provides @Singleton
static TimeProvider provideTimeProvider(SystemTimeProvider systemTimeProvider) {
Coreoz/Plume
plume-services/src/main/java/com/coreoz/plume/dagger/DaggerServicesModule.java
// Path: plume-services/src/main/java/com/coreoz/plume/services/time/SystemTimeProvider.java // @Singleton // public class SystemTimeProvider implements TimeProvider { // // private final Clock clock; // // @Inject // public SystemTimeProvider() { // this.clock = Clock.systemDefaultZone(); // } // // @Override // public Clock clock() { // return clock; // } // // } // // Path: plume-services/src/main/java/com/coreoz/plume/services/time/TimeProvider.java // public interface TimeProvider { // // Clock clock(); // // /** // * Returns the current time in milliseconds // */ // default long currentTime() { // return clock().millis(); // } // // default Instant currentInstant() { // return Instant.now(clock()); // } // // default LocalDate currentLocalDate() { // return LocalDate.now(clock()); // } // // default LocalDateTime currentDateTime() { // return LocalDateTime.now(clock()); // } // // }
import javax.inject.Singleton; import com.coreoz.plume.services.time.SystemTimeProvider; import com.coreoz.plume.services.time.TimeProvider; import dagger.Module; import dagger.Provides;
package com.coreoz.plume.dagger; @Module public class DaggerServicesModule { @Provides @Singleton
// Path: plume-services/src/main/java/com/coreoz/plume/services/time/SystemTimeProvider.java // @Singleton // public class SystemTimeProvider implements TimeProvider { // // private final Clock clock; // // @Inject // public SystemTimeProvider() { // this.clock = Clock.systemDefaultZone(); // } // // @Override // public Clock clock() { // return clock; // } // // } // // Path: plume-services/src/main/java/com/coreoz/plume/services/time/TimeProvider.java // public interface TimeProvider { // // Clock clock(); // // /** // * Returns the current time in milliseconds // */ // default long currentTime() { // return clock().millis(); // } // // default Instant currentInstant() { // return Instant.now(clock()); // } // // default LocalDate currentLocalDate() { // return LocalDate.now(clock()); // } // // default LocalDateTime currentDateTime() { // return LocalDateTime.now(clock()); // } // // } // Path: plume-services/src/main/java/com/coreoz/plume/dagger/DaggerServicesModule.java import javax.inject.Singleton; import com.coreoz.plume.services.time.SystemTimeProvider; import com.coreoz.plume.services.time.TimeProvider; import dagger.Module; import dagger.Provides; package com.coreoz.plume.dagger; @Module public class DaggerServicesModule { @Provides @Singleton
static TimeProvider provideTimeProvider(SystemTimeProvider systemTimeProvider) {
fashare2015/MVVM-JueJin
adapter/src/main/java/com/fashare/adapter/viewpager/loop/LoopPagerAdapterWrapper.java
// Path: adapter/src/main/java/com/fashare/adapter/viewpager/CommonPagerAdapter.java // public abstract class CommonPagerAdapter<T> extends PagerAdapter { // // protected final String TAG = this.getClass().getSimpleName(); // protected Context mContext; // protected List<T> mDataList; // private OnItemClickListener<T> mOnItemClickListener; // private int mLayoutId; // // public List<T> getDataList() { // return mDataList; // } // // public void setDataList(List<T> dataList) { // if(dataList != null) { // this.mDataList = dataList; // notifyDataSetChanged(); // }else{ // Log.e(TAG, "mDataList is null"); // } // } // // public void setDataListWithoutNotify(List<T> dataList) { // if(dataList != null) { // this.mDataList = dataList; // }else{ // Log.e(TAG, "mDataList is null"); // } // } // // // /** // * reutrn POSITION_NONE 使得 notifyDataSetChanged() 会触发 instantiateItem() -> onBindViewHolder() // * @param object // * @return // */ // @Override // public int getItemPosition(Object object) { // return POSITION_NONE; // } // // public void setOnItemClickListener(OnItemClickListener<T> onItemClickListener) { // this.mOnItemClickListener = onItemClickListener; // } // // public CommonPagerAdapter(final Context context, final int layoutId, List<T> dataList) { // mContext = context; // mLayoutId = layoutId; // mDataList = dataList; // } // // @Override // public int getCount() { // return mDataList == null? 0: mDataList.size(); // } // // @Override // public boolean isViewFromObject(View view, Object object) { // return view == object; // } // // @Override // public Object instantiateItem(ViewGroup container, int position) { // ViewHolder viewHolder = createViewHolder(container, position); // onBindViewHolder(viewHolder, position); // return viewHolder.itemView; // } // // protected final ViewHolder createViewHolder(ViewGroup container, int position) { // ViewHolder viewHolder; // viewHolder = onCreateViewHolder(container); // // if(viewHolder != null) { // container.addView(viewHolder.itemView); // }else { // Log.e(TAG, "viewHolder is null"); // } // // return viewHolder; // } // // protected ViewHolder onCreateViewHolder(ViewGroup parent){ // return ViewHolder.createViewHolder(mContext, parent, mLayoutId); // } // // public void onBindViewHolder(final ViewHolder holder, final int position) { // setListener(holder, position); // // T data = getDataList().get(position); // if(data != null) { // convert(holder, data, position); // }else{ // Log.e(TAG, String.format("mDataList.get(%d) is null", position)); // } // } // // protected void setListener(final ViewHolder viewHolder, final int position) { // viewHolder.getConvertView().setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // if (mOnItemClickListener != null) { // mOnItemClickListener.onItemClick(viewHolder, mDataList.get(position), position); // } // } // }); // // viewHolder.getConvertView().setOnLongClickListener(new View.OnLongClickListener() { // @Override // public boolean onLongClick(View v) { // if (mOnItemClickListener != null) { // return mOnItemClickListener.onItemLongClick(viewHolder, mDataList.get(position), position); // } // return false; // } // }); // } // // protected abstract void convert(ViewHolder holder, T t, int position); // // @Override // public void destroyItem(ViewGroup container, int position, Object object) { // container.removeView((View)object); // } // }
import android.os.Parcelable; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import com.fashare.adapter.viewpager.CommonPagerAdapter; import java.util.List;
/* * Copyright (C) 2013 Leszek Mzyk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fashare.adapter.viewpager.loop; /** * A PagerAdapter wrapper responsible for providing a proper page to * LoopViewPager * * This class shouldn't be used directly */ public class LoopPagerAdapterWrapper extends PagerAdapter { private PagerAdapter mAdapter; private SparseArray<ToDestroy> mToDestroy = new SparseArray<ToDestroy>(); private boolean mBoundaryCaching; ViewPager mViewPager; void setBoundaryCaching(boolean flag) { mBoundaryCaching = flag; } LoopPagerAdapterWrapper(PagerAdapter adapter) { this.mAdapter = adapter; } public void setDataList(List<?> dataList) {
// Path: adapter/src/main/java/com/fashare/adapter/viewpager/CommonPagerAdapter.java // public abstract class CommonPagerAdapter<T> extends PagerAdapter { // // protected final String TAG = this.getClass().getSimpleName(); // protected Context mContext; // protected List<T> mDataList; // private OnItemClickListener<T> mOnItemClickListener; // private int mLayoutId; // // public List<T> getDataList() { // return mDataList; // } // // public void setDataList(List<T> dataList) { // if(dataList != null) { // this.mDataList = dataList; // notifyDataSetChanged(); // }else{ // Log.e(TAG, "mDataList is null"); // } // } // // public void setDataListWithoutNotify(List<T> dataList) { // if(dataList != null) { // this.mDataList = dataList; // }else{ // Log.e(TAG, "mDataList is null"); // } // } // // // /** // * reutrn POSITION_NONE 使得 notifyDataSetChanged() 会触发 instantiateItem() -> onBindViewHolder() // * @param object // * @return // */ // @Override // public int getItemPosition(Object object) { // return POSITION_NONE; // } // // public void setOnItemClickListener(OnItemClickListener<T> onItemClickListener) { // this.mOnItemClickListener = onItemClickListener; // } // // public CommonPagerAdapter(final Context context, final int layoutId, List<T> dataList) { // mContext = context; // mLayoutId = layoutId; // mDataList = dataList; // } // // @Override // public int getCount() { // return mDataList == null? 0: mDataList.size(); // } // // @Override // public boolean isViewFromObject(View view, Object object) { // return view == object; // } // // @Override // public Object instantiateItem(ViewGroup container, int position) { // ViewHolder viewHolder = createViewHolder(container, position); // onBindViewHolder(viewHolder, position); // return viewHolder.itemView; // } // // protected final ViewHolder createViewHolder(ViewGroup container, int position) { // ViewHolder viewHolder; // viewHolder = onCreateViewHolder(container); // // if(viewHolder != null) { // container.addView(viewHolder.itemView); // }else { // Log.e(TAG, "viewHolder is null"); // } // // return viewHolder; // } // // protected ViewHolder onCreateViewHolder(ViewGroup parent){ // return ViewHolder.createViewHolder(mContext, parent, mLayoutId); // } // // public void onBindViewHolder(final ViewHolder holder, final int position) { // setListener(holder, position); // // T data = getDataList().get(position); // if(data != null) { // convert(holder, data, position); // }else{ // Log.e(TAG, String.format("mDataList.get(%d) is null", position)); // } // } // // protected void setListener(final ViewHolder viewHolder, final int position) { // viewHolder.getConvertView().setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // if (mOnItemClickListener != null) { // mOnItemClickListener.onItemClick(viewHolder, mDataList.get(position), position); // } // } // }); // // viewHolder.getConvertView().setOnLongClickListener(new View.OnLongClickListener() { // @Override // public boolean onLongClick(View v) { // if (mOnItemClickListener != null) { // return mOnItemClickListener.onItemLongClick(viewHolder, mDataList.get(position), position); // } // return false; // } // }); // } // // protected abstract void convert(ViewHolder holder, T t, int position); // // @Override // public void destroyItem(ViewGroup container, int position, Object object) { // container.removeView((View)object); // } // } // Path: adapter/src/main/java/com/fashare/adapter/viewpager/loop/LoopPagerAdapterWrapper.java import android.os.Parcelable; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import com.fashare.adapter.viewpager.CommonPagerAdapter; import java.util.List; /* * Copyright (C) 2013 Leszek Mzyk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fashare.adapter.viewpager.loop; /** * A PagerAdapter wrapper responsible for providing a proper page to * LoopViewPager * * This class shouldn't be used directly */ public class LoopPagerAdapterWrapper extends PagerAdapter { private PagerAdapter mAdapter; private SparseArray<ToDestroy> mToDestroy = new SparseArray<ToDestroy>(); private boolean mBoundaryCaching; ViewPager mViewPager; void setBoundaryCaching(boolean flag) { mBoundaryCaching = flag; } LoopPagerAdapterWrapper(PagerAdapter adapter) { this.mAdapter = adapter; } public void setDataList(List<?> dataList) {
if(mAdapter instanceof CommonPagerAdapter) {
fashare2015/MVVM-JueJin
app/src/main/kotlin/com/daimajia/gold/utils/d/b.java
// Path: app/src/main/kotlin/com/daimajia/gold/utils/z.java // public class z { // public static void a(TextView textView, String str) { // if (textView != null && !TextUtils.isEmpty(str)) { // textView.setText(str); // } // } // // public static boolean a(String str) { // if (str == null) { // return false; // } // Matcher matcher = Pattern.compile("^[a-zA-Z0-9_一-龥]+$").matcher(str); // if (str.length() > 20 || !matcher.find()) { // return false; // } // return true; // } // // public static boolean b(String str) { // if (str == null) { // return false; // } // return Pattern.compile("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?").matcher(str).find(); // } // // public static boolean c(String str) { // return str == null || str.length() == 0; // } // // public static String a(TextView textView) { // if (textView != null) { // return textView.getText().toString(); // } // return ""; // } // }
import android.net.Uri; import android.text.TextUtils; import com.daimajia.gold.utils.z;
} stringBuilder.append(String.format(" <link href=\"%s\" type=\"text/css\" rel=\"stylesheet\" />", new Object[]{"file:///android_asset/www/header-img.css"})); if (TextUtils.isEmpty(stringBuilder.toString())) { return ""; } return stringBuilder.toString(); } public static String b(String str) { StringBuilder stringBuilder = new StringBuilder(); if (!TextUtils.isEmpty(str)) { stringBuilder.append(String.format(" <script src=\"%s\"></script>", new Object[]{str})); } stringBuilder.append(String.format(" <script src=\"%s\"></script>", new Object[]{"file:///android_asset/www/img_replace.js"})); return stringBuilder.toString(); } public static String a(String str, String str2, String str3, String str4) { StringBuilder stringBuilder = new StringBuilder(); if (!TextUtils.isEmpty(str)) { stringBuilder.append(String.format(" <div id = \"gold-web-header-img\" style=\"background-image: linear-gradient(rgba(0, 0, 0, .1), rgba(0, 0, 0, 0)), url(%s)\" class=\"entry-hero\"></div>", new Object[]{str})); } stringBuilder.append(String.format("<h2 id=\"entry_title\" class=\"entry-title\">%s</h2>", new Object[]{str3})); String str5 = ""; if (!TextUtils.isEmpty(str2)) { str5 = Uri.parse(str2).getHost(); } if (c(str2)) { str5 = "<p class=\"entry-meta\"><span style=\"margin-right:0.8em; border:solid #909090 1px;border-radius: 2px;padding:.2em .7em 0.1em 0.7em;\">原创</span>%s</p>"; Object[] objArr = new Object[1];
// Path: app/src/main/kotlin/com/daimajia/gold/utils/z.java // public class z { // public static void a(TextView textView, String str) { // if (textView != null && !TextUtils.isEmpty(str)) { // textView.setText(str); // } // } // // public static boolean a(String str) { // if (str == null) { // return false; // } // Matcher matcher = Pattern.compile("^[a-zA-Z0-9_一-龥]+$").matcher(str); // if (str.length() > 20 || !matcher.find()) { // return false; // } // return true; // } // // public static boolean b(String str) { // if (str == null) { // return false; // } // return Pattern.compile("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?").matcher(str).find(); // } // // public static boolean c(String str) { // return str == null || str.length() == 0; // } // // public static String a(TextView textView) { // if (textView != null) { // return textView.getText().toString(); // } // return ""; // } // } // Path: app/src/main/kotlin/com/daimajia/gold/utils/d/b.java import android.net.Uri; import android.text.TextUtils; import com.daimajia.gold.utils.z; } stringBuilder.append(String.format(" <link href=\"%s\" type=\"text/css\" rel=\"stylesheet\" />", new Object[]{"file:///android_asset/www/header-img.css"})); if (TextUtils.isEmpty(stringBuilder.toString())) { return ""; } return stringBuilder.toString(); } public static String b(String str) { StringBuilder stringBuilder = new StringBuilder(); if (!TextUtils.isEmpty(str)) { stringBuilder.append(String.format(" <script src=\"%s\"></script>", new Object[]{str})); } stringBuilder.append(String.format(" <script src=\"%s\"></script>", new Object[]{"file:///android_asset/www/img_replace.js"})); return stringBuilder.toString(); } public static String a(String str, String str2, String str3, String str4) { StringBuilder stringBuilder = new StringBuilder(); if (!TextUtils.isEmpty(str)) { stringBuilder.append(String.format(" <div id = \"gold-web-header-img\" style=\"background-image: linear-gradient(rgba(0, 0, 0, .1), rgba(0, 0, 0, 0)), url(%s)\" class=\"entry-hero\"></div>", new Object[]{str})); } stringBuilder.append(String.format("<h2 id=\"entry_title\" class=\"entry-title\">%s</h2>", new Object[]{str3})); String str5 = ""; if (!TextUtils.isEmpty(str2)) { str5 = Uri.parse(str2).getHost(); } if (c(str2)) { str5 = "<p class=\"entry-meta\"><span style=\"margin-right:0.8em; border:solid #909090 1px;border-radius: 2px;padding:.2em .7em 0.1em 0.7em;\">原创</span>%s</p>"; Object[] objArr = new Object[1];
if (z.c(str4)) {
amrmagdy4/kite
kite-core/src/main/java/edu/umn/cs/kite/querying/metadata/CommandMetadataEntry.java
// Path: kite-core/src/main/java/edu/umn/cs/kite/util/serialization/ByteStream.java // public class ByteStream { // // private final int DELTA = 1024; // private int capacity ; // private ByteBuffer byteStream ; // // public ByteStream(int capacity) { // this.capacity = 2*capacity+4*DELTA; // byteStream = ByteBuffer.allocate(this.capacity); // } // // public ByteStream(byte [] bytes) { // byteStream = ByteBuffer.wrap(bytes); // } // // public int write(byte[] bytes) { // byteStream.put(bytes); // return Byte.BYTES*bytes.length; // } // // public int write(byte[] bytes, int length) { // byteStream.put(bytes,0,length); // return Byte.BYTES*length; // } // // public int write(byte oneByte) { // byteStream.put(oneByte); // return Byte.BYTES; // } // // public int write(int value) { // byteStream.putInt(value); // return Integer.BYTES; // } // // public int write(long value) { // byteStream.putLong(value); // return Long.BYTES; // } // // public int write(String str) { // int bytesLen = 0; // if(str == null) { // bytesLen += this.write(0); // } // else { // byte[] strBytes = str.getBytes(); // // bytesLen += this.write(strBytes.length); //key length // bytesLen += this.write(strBytes); // } // return bytesLen; // } // // public byte[] getBytes() { return byteStream.array(); } // // public int getWrittenBytes() { return byteStream.position(); } // // public int getReadBytes() { return byteStream.position(); } // // public boolean hasRemaining(){return byteStream.hasRemaining();} // // public int write(double dblVal) { // byteStream.putDouble(dblVal); // return Double.BYTES; // } // // public int readInt() { // return byteStream.getInt(); // } // // public byte[] readBytes(int bytesLen) { // byte [] bytes = new byte[bytesLen]; // byteStream.get(bytes,0,bytesLen); // return bytes; // } // // public boolean skipBytes(int bytesLen) { // try { // byteStream.position(byteStream.position()+bytesLen); // return true; // } catch (IllegalArgumentException e) { // return false; // } // } // // public long readLong() { // return byteStream.getLong(); // } // // public String readString() { // int keyBytesLen = readInt(); // if(keyBytesLen == 0) // return null; // byte [] keyStrBytes = readBytes(keyBytesLen); // return new String(keyStrBytes); // } // // public byte readByte() { // byte [] bytes = readBytes(1); // return bytes[0]; // } // // public double readDouble() { // return byteStream.getDouble(); // } // // public void clear() { // byteStream.clear(); // } // // public byte[] getBytesClone() { // int lenToCopy = getWrittenBytes(); // return Arrays.copyOfRange(byteStream.array(),0, lenToCopy); // } // // public int getCapacity() { // return capacity; // } // }
import edu.umn.cs.kite.util.serialization.ByteStream; import java.util.ArrayList; import java.util.List;
package edu.umn.cs.kite.querying.metadata; /** * Created by amr_000 on 12/28/2016. */ public class CommandMetadataEntry implements MetadataEntry { private String command; private List<Object> arguments; public CommandMetadataEntry(String command, String arg1) { this.command = command; arguments = new ArrayList<>(); arguments.add(arg1); } public CommandMetadataEntry(String command, String arg1, String arg2) { this(command, arg1); arguments.add(arg2); } public CommandMetadataEntry(String command, String arg1, String arg2, String arg3) { this(command, arg1, arg2); arguments.add(arg3); } @Override public boolean isStreamEntry() { return false; } @Override public boolean isIndexEntry() { return false; } @Override public boolean isCommandEntry() { return true; } @Override public boolean isQueryEntry() { return false; } @Override
// Path: kite-core/src/main/java/edu/umn/cs/kite/util/serialization/ByteStream.java // public class ByteStream { // // private final int DELTA = 1024; // private int capacity ; // private ByteBuffer byteStream ; // // public ByteStream(int capacity) { // this.capacity = 2*capacity+4*DELTA; // byteStream = ByteBuffer.allocate(this.capacity); // } // // public ByteStream(byte [] bytes) { // byteStream = ByteBuffer.wrap(bytes); // } // // public int write(byte[] bytes) { // byteStream.put(bytes); // return Byte.BYTES*bytes.length; // } // // public int write(byte[] bytes, int length) { // byteStream.put(bytes,0,length); // return Byte.BYTES*length; // } // // public int write(byte oneByte) { // byteStream.put(oneByte); // return Byte.BYTES; // } // // public int write(int value) { // byteStream.putInt(value); // return Integer.BYTES; // } // // public int write(long value) { // byteStream.putLong(value); // return Long.BYTES; // } // // public int write(String str) { // int bytesLen = 0; // if(str == null) { // bytesLen += this.write(0); // } // else { // byte[] strBytes = str.getBytes(); // // bytesLen += this.write(strBytes.length); //key length // bytesLen += this.write(strBytes); // } // return bytesLen; // } // // public byte[] getBytes() { return byteStream.array(); } // // public int getWrittenBytes() { return byteStream.position(); } // // public int getReadBytes() { return byteStream.position(); } // // public boolean hasRemaining(){return byteStream.hasRemaining();} // // public int write(double dblVal) { // byteStream.putDouble(dblVal); // return Double.BYTES; // } // // public int readInt() { // return byteStream.getInt(); // } // // public byte[] readBytes(int bytesLen) { // byte [] bytes = new byte[bytesLen]; // byteStream.get(bytes,0,bytesLen); // return bytes; // } // // public boolean skipBytes(int bytesLen) { // try { // byteStream.position(byteStream.position()+bytesLen); // return true; // } catch (IllegalArgumentException e) { // return false; // } // } // // public long readLong() { // return byteStream.getLong(); // } // // public String readString() { // int keyBytesLen = readInt(); // if(keyBytesLen == 0) // return null; // byte [] keyStrBytes = readBytes(keyBytesLen); // return new String(keyStrBytes); // } // // public byte readByte() { // byte [] bytes = readBytes(1); // return bytes[0]; // } // // public double readDouble() { // return byteStream.getDouble(); // } // // public void clear() { // byteStream.clear(); // } // // public byte[] getBytesClone() { // int lenToCopy = getWrittenBytes(); // return Arrays.copyOfRange(byteStream.array(),0, lenToCopy); // } // // public int getCapacity() { // return capacity; // } // } // Path: kite-core/src/main/java/edu/umn/cs/kite/querying/metadata/CommandMetadataEntry.java import edu.umn.cs.kite.util.serialization.ByteStream; import java.util.ArrayList; import java.util.List; package edu.umn.cs.kite.querying.metadata; /** * Created by amr_000 on 12/28/2016. */ public class CommandMetadataEntry implements MetadataEntry { private String command; private List<Object> arguments; public CommandMetadataEntry(String command, String arg1) { this.command = command; arguments = new ArrayList<>(); arguments.add(arg1); } public CommandMetadataEntry(String command, String arg1, String arg2) { this(command, arg1); arguments.add(arg2); } public CommandMetadataEntry(String command, String arg1, String arg2, String arg3) { this(command, arg1, arg2); arguments.add(arg3); } @Override public boolean isStreamEntry() { return false; } @Override public boolean isIndexEntry() { return false; } @Override public boolean isCommandEntry() { return true; } @Override public boolean isQueryEntry() { return false; } @Override
public void serialize(ByteStream byteStream) {
amrmagdy4/kite
kite-core/src/main/java/edu/umn/cs/kite/util/TemporalPeriod.java
// Path: kite-core/src/main/java/edu/umn/cs/kite/util/serialization/ByteStream.java // public class ByteStream { // // private final int DELTA = 1024; // private int capacity ; // private ByteBuffer byteStream ; // // public ByteStream(int capacity) { // this.capacity = 2*capacity+4*DELTA; // byteStream = ByteBuffer.allocate(this.capacity); // } // // public ByteStream(byte [] bytes) { // byteStream = ByteBuffer.wrap(bytes); // } // // public int write(byte[] bytes) { // byteStream.put(bytes); // return Byte.BYTES*bytes.length; // } // // public int write(byte[] bytes, int length) { // byteStream.put(bytes,0,length); // return Byte.BYTES*length; // } // // public int write(byte oneByte) { // byteStream.put(oneByte); // return Byte.BYTES; // } // // public int write(int value) { // byteStream.putInt(value); // return Integer.BYTES; // } // // public int write(long value) { // byteStream.putLong(value); // return Long.BYTES; // } // // public int write(String str) { // int bytesLen = 0; // if(str == null) { // bytesLen += this.write(0); // } // else { // byte[] strBytes = str.getBytes(); // // bytesLen += this.write(strBytes.length); //key length // bytesLen += this.write(strBytes); // } // return bytesLen; // } // // public byte[] getBytes() { return byteStream.array(); } // // public int getWrittenBytes() { return byteStream.position(); } // // public int getReadBytes() { return byteStream.position(); } // // public boolean hasRemaining(){return byteStream.hasRemaining();} // // public int write(double dblVal) { // byteStream.putDouble(dblVal); // return Double.BYTES; // } // // public int readInt() { // return byteStream.getInt(); // } // // public byte[] readBytes(int bytesLen) { // byte [] bytes = new byte[bytesLen]; // byteStream.get(bytes,0,bytesLen); // return bytes; // } // // public boolean skipBytes(int bytesLen) { // try { // byteStream.position(byteStream.position()+bytesLen); // return true; // } catch (IllegalArgumentException e) { // return false; // } // } // // public long readLong() { // return byteStream.getLong(); // } // // public String readString() { // int keyBytesLen = readInt(); // if(keyBytesLen == 0) // return null; // byte [] keyStrBytes = readBytes(keyBytesLen); // return new String(keyStrBytes); // } // // public byte readByte() { // byte [] bytes = readBytes(1); // return bytes[0]; // } // // public double readDouble() { // return byteStream.getDouble(); // } // // public void clear() { // byteStream.clear(); // } // // public byte[] getBytesClone() { // int lenToCopy = getWrittenBytes(); // return Arrays.copyOfRange(byteStream.array(),0, lenToCopy); // } // // public int getCapacity() { // return capacity; // } // }
import edu.umn.cs.kite.util.serialization.ByteStream; import java.sql.Timestamp;
public void setTo(long to) { this.to = new Timestamp(to); } public boolean overlap(Timestamp timestamp) { return (from()==null || timestamp.getTime() >= this.from().getTime()) && (to()==null || timestamp.getTime() <= this.to().getTime()); } public boolean overlap(long timestamp) { return timestamp >= this.from().getTime() && timestamp <= this.to().getTime(); } public boolean endsBefore(Timestamp timestamp) { if(timestamp == null) { if(this.to() != null) return true; else return false; } if(this.to() == null) return false; return this.to().getTime() < timestamp.getTime(); } public boolean startsAfter(Timestamp timestamp) { return this.from().getTime() > timestamp.getTime(); }
// Path: kite-core/src/main/java/edu/umn/cs/kite/util/serialization/ByteStream.java // public class ByteStream { // // private final int DELTA = 1024; // private int capacity ; // private ByteBuffer byteStream ; // // public ByteStream(int capacity) { // this.capacity = 2*capacity+4*DELTA; // byteStream = ByteBuffer.allocate(this.capacity); // } // // public ByteStream(byte [] bytes) { // byteStream = ByteBuffer.wrap(bytes); // } // // public int write(byte[] bytes) { // byteStream.put(bytes); // return Byte.BYTES*bytes.length; // } // // public int write(byte[] bytes, int length) { // byteStream.put(bytes,0,length); // return Byte.BYTES*length; // } // // public int write(byte oneByte) { // byteStream.put(oneByte); // return Byte.BYTES; // } // // public int write(int value) { // byteStream.putInt(value); // return Integer.BYTES; // } // // public int write(long value) { // byteStream.putLong(value); // return Long.BYTES; // } // // public int write(String str) { // int bytesLen = 0; // if(str == null) { // bytesLen += this.write(0); // } // else { // byte[] strBytes = str.getBytes(); // // bytesLen += this.write(strBytes.length); //key length // bytesLen += this.write(strBytes); // } // return bytesLen; // } // // public byte[] getBytes() { return byteStream.array(); } // // public int getWrittenBytes() { return byteStream.position(); } // // public int getReadBytes() { return byteStream.position(); } // // public boolean hasRemaining(){return byteStream.hasRemaining();} // // public int write(double dblVal) { // byteStream.putDouble(dblVal); // return Double.BYTES; // } // // public int readInt() { // return byteStream.getInt(); // } // // public byte[] readBytes(int bytesLen) { // byte [] bytes = new byte[bytesLen]; // byteStream.get(bytes,0,bytesLen); // return bytes; // } // // public boolean skipBytes(int bytesLen) { // try { // byteStream.position(byteStream.position()+bytesLen); // return true; // } catch (IllegalArgumentException e) { // return false; // } // } // // public long readLong() { // return byteStream.getLong(); // } // // public String readString() { // int keyBytesLen = readInt(); // if(keyBytesLen == 0) // return null; // byte [] keyStrBytes = readBytes(keyBytesLen); // return new String(keyStrBytes); // } // // public byte readByte() { // byte [] bytes = readBytes(1); // return bytes[0]; // } // // public double readDouble() { // return byteStream.getDouble(); // } // // public void clear() { // byteStream.clear(); // } // // public byte[] getBytesClone() { // int lenToCopy = getWrittenBytes(); // return Arrays.copyOfRange(byteStream.array(),0, lenToCopy); // } // // public int getCapacity() { // return capacity; // } // } // Path: kite-core/src/main/java/edu/umn/cs/kite/util/TemporalPeriod.java import edu.umn.cs.kite.util.serialization.ByteStream; import java.sql.Timestamp; public void setTo(long to) { this.to = new Timestamp(to); } public boolean overlap(Timestamp timestamp) { return (from()==null || timestamp.getTime() >= this.from().getTime()) && (to()==null || timestamp.getTime() <= this.to().getTime()); } public boolean overlap(long timestamp) { return timestamp >= this.from().getTime() && timestamp <= this.to().getTime(); } public boolean endsBefore(Timestamp timestamp) { if(timestamp == null) { if(this.to() != null) return true; else return false; } if(this.to() == null) return false; return this.to().getTime() < timestamp.getTime(); } public boolean startsAfter(Timestamp timestamp) { return this.from().getTime() > timestamp.getTime(); }
public void serialize(ByteStream byteStream) {
amrmagdy4/kite
kite-core/src/main/java/edu/umn/cs/kite/querying/metadata/MetadataEntry.java
// Path: kite-core/src/main/java/edu/umn/cs/kite/datamodel/Scheme.java // public class Scheme { // private ArrayList<Attribute> attributes; // // public Scheme (ArrayList<Attribute> attributesList) { // attributes = attributesList; // } // public int numAttributes() {return attributes.size();} // // public ArrayList<Attribute> getAttributes() { // return attributes; // } // // public boolean attributeExists(String attributeName) { // for(Attribute attribute: attributes) { // if(attribute.getName().compareTo(attributeName) == 0) // return true; // } // return false; // } // // public boolean spatialAttributeExists(String attributeName) { // for(Attribute attribute: attributes) { // if(attribute.getName().compareTo(attributeName) == 0 // && attribute.isSpatialAttribute()) // return true; // } // return false; // } // // public Attribute getAttribute(String attributeName) { // for(Attribute attribute: attributes) { // if(attribute.getName().compareTo(attributeName) == 0) // return attribute; // } // return null; // } // // public void serialize(ByteStream byteStream) { // Serializer.serializeAttributeList(this.getAttributes(), byteStream); // } // // public static Scheme deserialize(ByteStream byteStream) { // ArrayList<Attribute> attributes = Serializer.deserializeAttributeList // (byteStream); // return new Scheme(attributes); // } // // public String toString() { // String str = ""; // for(Attribute attribute: attributes) { // str += attribute.toString(); // } // return str; // } // } // // Path: kite-core/src/main/java/edu/umn/cs/kite/util/serialization/ByteStream.java // public class ByteStream { // // private final int DELTA = 1024; // private int capacity ; // private ByteBuffer byteStream ; // // public ByteStream(int capacity) { // this.capacity = 2*capacity+4*DELTA; // byteStream = ByteBuffer.allocate(this.capacity); // } // // public ByteStream(byte [] bytes) { // byteStream = ByteBuffer.wrap(bytes); // } // // public int write(byte[] bytes) { // byteStream.put(bytes); // return Byte.BYTES*bytes.length; // } // // public int write(byte[] bytes, int length) { // byteStream.put(bytes,0,length); // return Byte.BYTES*length; // } // // public int write(byte oneByte) { // byteStream.put(oneByte); // return Byte.BYTES; // } // // public int write(int value) { // byteStream.putInt(value); // return Integer.BYTES; // } // // public int write(long value) { // byteStream.putLong(value); // return Long.BYTES; // } // // public int write(String str) { // int bytesLen = 0; // if(str == null) { // bytesLen += this.write(0); // } // else { // byte[] strBytes = str.getBytes(); // // bytesLen += this.write(strBytes.length); //key length // bytesLen += this.write(strBytes); // } // return bytesLen; // } // // public byte[] getBytes() { return byteStream.array(); } // // public int getWrittenBytes() { return byteStream.position(); } // // public int getReadBytes() { return byteStream.position(); } // // public boolean hasRemaining(){return byteStream.hasRemaining();} // // public int write(double dblVal) { // byteStream.putDouble(dblVal); // return Double.BYTES; // } // // public int readInt() { // return byteStream.getInt(); // } // // public byte[] readBytes(int bytesLen) { // byte [] bytes = new byte[bytesLen]; // byteStream.get(bytes,0,bytesLen); // return bytes; // } // // public boolean skipBytes(int bytesLen) { // try { // byteStream.position(byteStream.position()+bytesLen); // return true; // } catch (IllegalArgumentException e) { // return false; // } // } // // public long readLong() { // return byteStream.getLong(); // } // // public String readString() { // int keyBytesLen = readInt(); // if(keyBytesLen == 0) // return null; // byte [] keyStrBytes = readBytes(keyBytesLen); // return new String(keyStrBytes); // } // // public byte readByte() { // byte [] bytes = readBytes(1); // return bytes[0]; // } // // public double readDouble() { // return byteStream.getDouble(); // } // // public void clear() { // byteStream.clear(); // } // // public byte[] getBytesClone() { // int lenToCopy = getWrittenBytes(); // return Arrays.copyOfRange(byteStream.array(),0, lenToCopy); // } // // public int getCapacity() { // return capacity; // } // }
import edu.umn.cs.kite.datamodel.Scheme; import edu.umn.cs.kite.util.serialization.ByteStream; import java.util.ArrayList;
package edu.umn.cs.kite.querying.metadata; /** * Created by amr_000 on 12/21/2016. */ public interface MetadataEntry { boolean isStreamEntry(); boolean isIndexEntry(); boolean isCommandEntry(); boolean isQueryEntry();
// Path: kite-core/src/main/java/edu/umn/cs/kite/datamodel/Scheme.java // public class Scheme { // private ArrayList<Attribute> attributes; // // public Scheme (ArrayList<Attribute> attributesList) { // attributes = attributesList; // } // public int numAttributes() {return attributes.size();} // // public ArrayList<Attribute> getAttributes() { // return attributes; // } // // public boolean attributeExists(String attributeName) { // for(Attribute attribute: attributes) { // if(attribute.getName().compareTo(attributeName) == 0) // return true; // } // return false; // } // // public boolean spatialAttributeExists(String attributeName) { // for(Attribute attribute: attributes) { // if(attribute.getName().compareTo(attributeName) == 0 // && attribute.isSpatialAttribute()) // return true; // } // return false; // } // // public Attribute getAttribute(String attributeName) { // for(Attribute attribute: attributes) { // if(attribute.getName().compareTo(attributeName) == 0) // return attribute; // } // return null; // } // // public void serialize(ByteStream byteStream) { // Serializer.serializeAttributeList(this.getAttributes(), byteStream); // } // // public static Scheme deserialize(ByteStream byteStream) { // ArrayList<Attribute> attributes = Serializer.deserializeAttributeList // (byteStream); // return new Scheme(attributes); // } // // public String toString() { // String str = ""; // for(Attribute attribute: attributes) { // str += attribute.toString(); // } // return str; // } // } // // Path: kite-core/src/main/java/edu/umn/cs/kite/util/serialization/ByteStream.java // public class ByteStream { // // private final int DELTA = 1024; // private int capacity ; // private ByteBuffer byteStream ; // // public ByteStream(int capacity) { // this.capacity = 2*capacity+4*DELTA; // byteStream = ByteBuffer.allocate(this.capacity); // } // // public ByteStream(byte [] bytes) { // byteStream = ByteBuffer.wrap(bytes); // } // // public int write(byte[] bytes) { // byteStream.put(bytes); // return Byte.BYTES*bytes.length; // } // // public int write(byte[] bytes, int length) { // byteStream.put(bytes,0,length); // return Byte.BYTES*length; // } // // public int write(byte oneByte) { // byteStream.put(oneByte); // return Byte.BYTES; // } // // public int write(int value) { // byteStream.putInt(value); // return Integer.BYTES; // } // // public int write(long value) { // byteStream.putLong(value); // return Long.BYTES; // } // // public int write(String str) { // int bytesLen = 0; // if(str == null) { // bytesLen += this.write(0); // } // else { // byte[] strBytes = str.getBytes(); // // bytesLen += this.write(strBytes.length); //key length // bytesLen += this.write(strBytes); // } // return bytesLen; // } // // public byte[] getBytes() { return byteStream.array(); } // // public int getWrittenBytes() { return byteStream.position(); } // // public int getReadBytes() { return byteStream.position(); } // // public boolean hasRemaining(){return byteStream.hasRemaining();} // // public int write(double dblVal) { // byteStream.putDouble(dblVal); // return Double.BYTES; // } // // public int readInt() { // return byteStream.getInt(); // } // // public byte[] readBytes(int bytesLen) { // byte [] bytes = new byte[bytesLen]; // byteStream.get(bytes,0,bytesLen); // return bytes; // } // // public boolean skipBytes(int bytesLen) { // try { // byteStream.position(byteStream.position()+bytesLen); // return true; // } catch (IllegalArgumentException e) { // return false; // } // } // // public long readLong() { // return byteStream.getLong(); // } // // public String readString() { // int keyBytesLen = readInt(); // if(keyBytesLen == 0) // return null; // byte [] keyStrBytes = readBytes(keyBytesLen); // return new String(keyStrBytes); // } // // public byte readByte() { // byte [] bytes = readBytes(1); // return bytes[0]; // } // // public double readDouble() { // return byteStream.getDouble(); // } // // public void clear() { // byteStream.clear(); // } // // public byte[] getBytesClone() { // int lenToCopy = getWrittenBytes(); // return Arrays.copyOfRange(byteStream.array(),0, lenToCopy); // } // // public int getCapacity() { // return capacity; // } // } // Path: kite-core/src/main/java/edu/umn/cs/kite/querying/metadata/MetadataEntry.java import edu.umn.cs.kite.datamodel.Scheme; import edu.umn.cs.kite.util.serialization.ByteStream; import java.util.ArrayList; package edu.umn.cs.kite.querying.metadata; /** * Created by amr_000 on 12/21/2016. */ public interface MetadataEntry { boolean isStreamEntry(); boolean isIndexEntry(); boolean isCommandEntry(); boolean isQueryEntry();
void serialize(ByteStream byteStream);
amrmagdy4/kite
kite-core/src/main/java/edu/umn/cs/kite/querying/metadata/MetadataEntry.java
// Path: kite-core/src/main/java/edu/umn/cs/kite/datamodel/Scheme.java // public class Scheme { // private ArrayList<Attribute> attributes; // // public Scheme (ArrayList<Attribute> attributesList) { // attributes = attributesList; // } // public int numAttributes() {return attributes.size();} // // public ArrayList<Attribute> getAttributes() { // return attributes; // } // // public boolean attributeExists(String attributeName) { // for(Attribute attribute: attributes) { // if(attribute.getName().compareTo(attributeName) == 0) // return true; // } // return false; // } // // public boolean spatialAttributeExists(String attributeName) { // for(Attribute attribute: attributes) { // if(attribute.getName().compareTo(attributeName) == 0 // && attribute.isSpatialAttribute()) // return true; // } // return false; // } // // public Attribute getAttribute(String attributeName) { // for(Attribute attribute: attributes) { // if(attribute.getName().compareTo(attributeName) == 0) // return attribute; // } // return null; // } // // public void serialize(ByteStream byteStream) { // Serializer.serializeAttributeList(this.getAttributes(), byteStream); // } // // public static Scheme deserialize(ByteStream byteStream) { // ArrayList<Attribute> attributes = Serializer.deserializeAttributeList // (byteStream); // return new Scheme(attributes); // } // // public String toString() { // String str = ""; // for(Attribute attribute: attributes) { // str += attribute.toString(); // } // return str; // } // } // // Path: kite-core/src/main/java/edu/umn/cs/kite/util/serialization/ByteStream.java // public class ByteStream { // // private final int DELTA = 1024; // private int capacity ; // private ByteBuffer byteStream ; // // public ByteStream(int capacity) { // this.capacity = 2*capacity+4*DELTA; // byteStream = ByteBuffer.allocate(this.capacity); // } // // public ByteStream(byte [] bytes) { // byteStream = ByteBuffer.wrap(bytes); // } // // public int write(byte[] bytes) { // byteStream.put(bytes); // return Byte.BYTES*bytes.length; // } // // public int write(byte[] bytes, int length) { // byteStream.put(bytes,0,length); // return Byte.BYTES*length; // } // // public int write(byte oneByte) { // byteStream.put(oneByte); // return Byte.BYTES; // } // // public int write(int value) { // byteStream.putInt(value); // return Integer.BYTES; // } // // public int write(long value) { // byteStream.putLong(value); // return Long.BYTES; // } // // public int write(String str) { // int bytesLen = 0; // if(str == null) { // bytesLen += this.write(0); // } // else { // byte[] strBytes = str.getBytes(); // // bytesLen += this.write(strBytes.length); //key length // bytesLen += this.write(strBytes); // } // return bytesLen; // } // // public byte[] getBytes() { return byteStream.array(); } // // public int getWrittenBytes() { return byteStream.position(); } // // public int getReadBytes() { return byteStream.position(); } // // public boolean hasRemaining(){return byteStream.hasRemaining();} // // public int write(double dblVal) { // byteStream.putDouble(dblVal); // return Double.BYTES; // } // // public int readInt() { // return byteStream.getInt(); // } // // public byte[] readBytes(int bytesLen) { // byte [] bytes = new byte[bytesLen]; // byteStream.get(bytes,0,bytesLen); // return bytes; // } // // public boolean skipBytes(int bytesLen) { // try { // byteStream.position(byteStream.position()+bytesLen); // return true; // } catch (IllegalArgumentException e) { // return false; // } // } // // public long readLong() { // return byteStream.getLong(); // } // // public String readString() { // int keyBytesLen = readInt(); // if(keyBytesLen == 0) // return null; // byte [] keyStrBytes = readBytes(keyBytesLen); // return new String(keyStrBytes); // } // // public byte readByte() { // byte [] bytes = readBytes(1); // return bytes[0]; // } // // public double readDouble() { // return byteStream.getDouble(); // } // // public void clear() { // byteStream.clear(); // } // // public byte[] getBytesClone() { // int lenToCopy = getWrittenBytes(); // return Arrays.copyOfRange(byteStream.array(),0, lenToCopy); // } // // public int getCapacity() { // return capacity; // } // }
import edu.umn.cs.kite.datamodel.Scheme; import edu.umn.cs.kite.util.serialization.ByteStream; import java.util.ArrayList;
package edu.umn.cs.kite.querying.metadata; /** * Created by amr_000 on 12/21/2016. */ public interface MetadataEntry { boolean isStreamEntry(); boolean isIndexEntry(); boolean isCommandEntry(); boolean isQueryEntry(); void serialize(ByteStream byteStream); static MetadataEntry deserialize(ByteStream byteStream) { if(!byteStream.hasRemaining()) return null; MetadataEntry entry = new CommandMetadataEntry("dummy", "dummy"); byte type = byteStream.readByte(); switch (type) { case 0: //stream String streamName = byteStream.readString();
// Path: kite-core/src/main/java/edu/umn/cs/kite/datamodel/Scheme.java // public class Scheme { // private ArrayList<Attribute> attributes; // // public Scheme (ArrayList<Attribute> attributesList) { // attributes = attributesList; // } // public int numAttributes() {return attributes.size();} // // public ArrayList<Attribute> getAttributes() { // return attributes; // } // // public boolean attributeExists(String attributeName) { // for(Attribute attribute: attributes) { // if(attribute.getName().compareTo(attributeName) == 0) // return true; // } // return false; // } // // public boolean spatialAttributeExists(String attributeName) { // for(Attribute attribute: attributes) { // if(attribute.getName().compareTo(attributeName) == 0 // && attribute.isSpatialAttribute()) // return true; // } // return false; // } // // public Attribute getAttribute(String attributeName) { // for(Attribute attribute: attributes) { // if(attribute.getName().compareTo(attributeName) == 0) // return attribute; // } // return null; // } // // public void serialize(ByteStream byteStream) { // Serializer.serializeAttributeList(this.getAttributes(), byteStream); // } // // public static Scheme deserialize(ByteStream byteStream) { // ArrayList<Attribute> attributes = Serializer.deserializeAttributeList // (byteStream); // return new Scheme(attributes); // } // // public String toString() { // String str = ""; // for(Attribute attribute: attributes) { // str += attribute.toString(); // } // return str; // } // } // // Path: kite-core/src/main/java/edu/umn/cs/kite/util/serialization/ByteStream.java // public class ByteStream { // // private final int DELTA = 1024; // private int capacity ; // private ByteBuffer byteStream ; // // public ByteStream(int capacity) { // this.capacity = 2*capacity+4*DELTA; // byteStream = ByteBuffer.allocate(this.capacity); // } // // public ByteStream(byte [] bytes) { // byteStream = ByteBuffer.wrap(bytes); // } // // public int write(byte[] bytes) { // byteStream.put(bytes); // return Byte.BYTES*bytes.length; // } // // public int write(byte[] bytes, int length) { // byteStream.put(bytes,0,length); // return Byte.BYTES*length; // } // // public int write(byte oneByte) { // byteStream.put(oneByte); // return Byte.BYTES; // } // // public int write(int value) { // byteStream.putInt(value); // return Integer.BYTES; // } // // public int write(long value) { // byteStream.putLong(value); // return Long.BYTES; // } // // public int write(String str) { // int bytesLen = 0; // if(str == null) { // bytesLen += this.write(0); // } // else { // byte[] strBytes = str.getBytes(); // // bytesLen += this.write(strBytes.length); //key length // bytesLen += this.write(strBytes); // } // return bytesLen; // } // // public byte[] getBytes() { return byteStream.array(); } // // public int getWrittenBytes() { return byteStream.position(); } // // public int getReadBytes() { return byteStream.position(); } // // public boolean hasRemaining(){return byteStream.hasRemaining();} // // public int write(double dblVal) { // byteStream.putDouble(dblVal); // return Double.BYTES; // } // // public int readInt() { // return byteStream.getInt(); // } // // public byte[] readBytes(int bytesLen) { // byte [] bytes = new byte[bytesLen]; // byteStream.get(bytes,0,bytesLen); // return bytes; // } // // public boolean skipBytes(int bytesLen) { // try { // byteStream.position(byteStream.position()+bytesLen); // return true; // } catch (IllegalArgumentException e) { // return false; // } // } // // public long readLong() { // return byteStream.getLong(); // } // // public String readString() { // int keyBytesLen = readInt(); // if(keyBytesLen == 0) // return null; // byte [] keyStrBytes = readBytes(keyBytesLen); // return new String(keyStrBytes); // } // // public byte readByte() { // byte [] bytes = readBytes(1); // return bytes[0]; // } // // public double readDouble() { // return byteStream.getDouble(); // } // // public void clear() { // byteStream.clear(); // } // // public byte[] getBytesClone() { // int lenToCopy = getWrittenBytes(); // return Arrays.copyOfRange(byteStream.array(),0, lenToCopy); // } // // public int getCapacity() { // return capacity; // } // } // Path: kite-core/src/main/java/edu/umn/cs/kite/querying/metadata/MetadataEntry.java import edu.umn.cs.kite.datamodel.Scheme; import edu.umn.cs.kite.util.serialization.ByteStream; import java.util.ArrayList; package edu.umn.cs.kite.querying.metadata; /** * Created by amr_000 on 12/21/2016. */ public interface MetadataEntry { boolean isStreamEntry(); boolean isIndexEntry(); boolean isCommandEntry(); boolean isQueryEntry(); void serialize(ByteStream byteStream); static MetadataEntry deserialize(ByteStream byteStream) { if(!byteStream.hasRemaining()) return null; MetadataEntry entry = new CommandMetadataEntry("dummy", "dummy"); byte type = byteStream.readByte(); switch (type) { case 0: //stream String streamName = byteStream.readString();
Scheme scheme = Scheme.deserialize(byteStream);
amrmagdy4/kite
kite-core/src/main/java/edu/umn/cs/kite/util/PointLocation.java
// Path: kite-core/src/main/java/edu/umn/cs/kite/util/serialization/ByteStream.java // public class ByteStream { // // private final int DELTA = 1024; // private int capacity ; // private ByteBuffer byteStream ; // // public ByteStream(int capacity) { // this.capacity = 2*capacity+4*DELTA; // byteStream = ByteBuffer.allocate(this.capacity); // } // // public ByteStream(byte [] bytes) { // byteStream = ByteBuffer.wrap(bytes); // } // // public int write(byte[] bytes) { // byteStream.put(bytes); // return Byte.BYTES*bytes.length; // } // // public int write(byte[] bytes, int length) { // byteStream.put(bytes,0,length); // return Byte.BYTES*length; // } // // public int write(byte oneByte) { // byteStream.put(oneByte); // return Byte.BYTES; // } // // public int write(int value) { // byteStream.putInt(value); // return Integer.BYTES; // } // // public int write(long value) { // byteStream.putLong(value); // return Long.BYTES; // } // // public int write(String str) { // int bytesLen = 0; // if(str == null) { // bytesLen += this.write(0); // } // else { // byte[] strBytes = str.getBytes(); // // bytesLen += this.write(strBytes.length); //key length // bytesLen += this.write(strBytes); // } // return bytesLen; // } // // public byte[] getBytes() { return byteStream.array(); } // // public int getWrittenBytes() { return byteStream.position(); } // // public int getReadBytes() { return byteStream.position(); } // // public boolean hasRemaining(){return byteStream.hasRemaining();} // // public int write(double dblVal) { // byteStream.putDouble(dblVal); // return Double.BYTES; // } // // public int readInt() { // return byteStream.getInt(); // } // // public byte[] readBytes(int bytesLen) { // byte [] bytes = new byte[bytesLen]; // byteStream.get(bytes,0,bytesLen); // return bytes; // } // // public boolean skipBytes(int bytesLen) { // try { // byteStream.position(byteStream.position()+bytesLen); // return true; // } catch (IllegalArgumentException e) { // return false; // } // } // // public long readLong() { // return byteStream.getLong(); // } // // public String readString() { // int keyBytesLen = readInt(); // if(keyBytesLen == 0) // return null; // byte [] keyStrBytes = readBytes(keyBytesLen); // return new String(keyStrBytes); // } // // public byte readByte() { // byte [] bytes = readBytes(1); // return bytes[0]; // } // // public double readDouble() { // return byteStream.getDouble(); // } // // public void clear() { // byteStream.clear(); // } // // public byte[] getBytesClone() { // int lenToCopy = getWrittenBytes(); // return Arrays.copyOfRange(byteStream.array(),0, lenToCopy); // } // // public int getCapacity() { // return capacity; // } // }
import edu.umn.cs.kite.util.serialization.ByteStream;
package edu.umn.cs.kite.util; /** * Created by amr_000 on 8/4/2016. */ public class PointLocation implements GeoLocation { private double latitude, longitude; public PointLocation (double lat, double lng) { latitude = lat; longitude = lng; } public PointLocation (double [] coords) { latitude = coords[0]; longitude = coords[1]; } public double getLatitude() { return latitude; } public double getLongitude() { return longitude; } @Override
// Path: kite-core/src/main/java/edu/umn/cs/kite/util/serialization/ByteStream.java // public class ByteStream { // // private final int DELTA = 1024; // private int capacity ; // private ByteBuffer byteStream ; // // public ByteStream(int capacity) { // this.capacity = 2*capacity+4*DELTA; // byteStream = ByteBuffer.allocate(this.capacity); // } // // public ByteStream(byte [] bytes) { // byteStream = ByteBuffer.wrap(bytes); // } // // public int write(byte[] bytes) { // byteStream.put(bytes); // return Byte.BYTES*bytes.length; // } // // public int write(byte[] bytes, int length) { // byteStream.put(bytes,0,length); // return Byte.BYTES*length; // } // // public int write(byte oneByte) { // byteStream.put(oneByte); // return Byte.BYTES; // } // // public int write(int value) { // byteStream.putInt(value); // return Integer.BYTES; // } // // public int write(long value) { // byteStream.putLong(value); // return Long.BYTES; // } // // public int write(String str) { // int bytesLen = 0; // if(str == null) { // bytesLen += this.write(0); // } // else { // byte[] strBytes = str.getBytes(); // // bytesLen += this.write(strBytes.length); //key length // bytesLen += this.write(strBytes); // } // return bytesLen; // } // // public byte[] getBytes() { return byteStream.array(); } // // public int getWrittenBytes() { return byteStream.position(); } // // public int getReadBytes() { return byteStream.position(); } // // public boolean hasRemaining(){return byteStream.hasRemaining();} // // public int write(double dblVal) { // byteStream.putDouble(dblVal); // return Double.BYTES; // } // // public int readInt() { // return byteStream.getInt(); // } // // public byte[] readBytes(int bytesLen) { // byte [] bytes = new byte[bytesLen]; // byteStream.get(bytes,0,bytesLen); // return bytes; // } // // public boolean skipBytes(int bytesLen) { // try { // byteStream.position(byteStream.position()+bytesLen); // return true; // } catch (IllegalArgumentException e) { // return false; // } // } // // public long readLong() { // return byteStream.getLong(); // } // // public String readString() { // int keyBytesLen = readInt(); // if(keyBytesLen == 0) // return null; // byte [] keyStrBytes = readBytes(keyBytesLen); // return new String(keyStrBytes); // } // // public byte readByte() { // byte [] bytes = readBytes(1); // return bytes[0]; // } // // public double readDouble() { // return byteStream.getDouble(); // } // // public void clear() { // byteStream.clear(); // } // // public byte[] getBytesClone() { // int lenToCopy = getWrittenBytes(); // return Arrays.copyOfRange(byteStream.array(),0, lenToCopy); // } // // public int getCapacity() { // return capacity; // } // } // Path: kite-core/src/main/java/edu/umn/cs/kite/util/PointLocation.java import edu.umn.cs.kite.util.serialization.ByteStream; package edu.umn.cs.kite.util; /** * Created by amr_000 on 8/4/2016. */ public class PointLocation implements GeoLocation { private double latitude, longitude; public PointLocation (double lat, double lng) { latitude = lat; longitude = lng; } public PointLocation (double [] coords) { latitude = coords[0]; longitude = coords[1]; } public double getLatitude() { return latitude; } public double getLongitude() { return longitude; } @Override
public int serialize(ByteStream byteStream) {
amrmagdy4/kite
kite-core/src/main/java/edu/umn/cs/kite/indexing/memory/MemoryIndexSegment.java
// Path: kite-core/src/main/java/edu/umn/cs/kite/querying/Query.java // public class Query { // private QueryType queryType; // private Condition condition = null; // private Attribute primaryAttribute = null; // private Object primaryAttributeValue = null; // // private Hashtable<String, Object> params; // private TemporalPeriod time = ConstantsAndDefaults.QUERY_TIME(); // private int k = ConstantsAndDefaults.QUERY_ANSWER_SIZE; // // public Query(QueryType queryType) { // this.queryType = queryType; // params = new Hashtable<>(); // } // // @Override public String toString() { // return "<"+queryType+","+condition+","+primaryAttribute+","+ // primaryAttributeValue+">"; // } // public Query(QueryType type, Condition condition) { // this.queryType = type; // this.condition = condition; // } // // public QueryType getQueryType() { return queryType; } // // public Rectangle getParam_Rectangle(String paramName) { // Rectangle spatialRect = (Rectangle)params.get(paramName); // return spatialRect; // } // // public void putParam_Rectangle(String paramName, Rectangle rect) { // params.put(paramName, rect); // } // // public boolean isHash() { // return queryType==QueryType.HASH_TEMPORAL; // } // // public boolean isSpatial() { // return queryType== QueryType.SPATIAL_RANGE_TEMPORAL || queryType== QueryType // .SPATIAL_KNN_TEMPORAL; // } // // public boolean isSpatialRange() { // return queryType== QueryType.SPATIAL_RANGE_TEMPORAL; // } // // public boolean isSpatialKNN() { // return queryType== QueryType.SPATIAL_KNN_TEMPORAL; // } // // public int getK() { // return k; // } // // public TemporalPeriod getTime() { // return time; // } // // public void setK(int k) { // this.k = k; // } // // public void setTime(TemporalPeriod time) { // this.time = time; // } // // public Condition getCondition() { // return condition; // } // // public void setQueryType(QueryType queryType) { // this.queryType = queryType; // } // // public void setPrimaryAttribute(Attribute primaryAttribute) { // this.primaryAttribute = primaryAttribute; // } // // public Attribute getPrimaryAttribute() { // return primaryAttribute; // } // // public boolean isSingleSearchAttribute() { // return getCondition().getSearchAttributes().size()==1; // } // // public void setPrimaryAttributeValue(Object primaryAttributeValue) { // this.primaryAttributeValue = primaryAttributeValue; // } // // public Object getPrimaryAttributeValue() { // return primaryAttributeValue; // } // }
import edu.umn.cs.kite.querying.Query; import java.util.ArrayList;
package edu.umn.cs.kite.indexing.memory; /** * Created by amr_000 on 8/1/2016. */ public interface MemoryIndexSegment<K,V> { public abstract int insert(K key, V value); public abstract int insert(K key, ArrayList<V> value);
// Path: kite-core/src/main/java/edu/umn/cs/kite/querying/Query.java // public class Query { // private QueryType queryType; // private Condition condition = null; // private Attribute primaryAttribute = null; // private Object primaryAttributeValue = null; // // private Hashtable<String, Object> params; // private TemporalPeriod time = ConstantsAndDefaults.QUERY_TIME(); // private int k = ConstantsAndDefaults.QUERY_ANSWER_SIZE; // // public Query(QueryType queryType) { // this.queryType = queryType; // params = new Hashtable<>(); // } // // @Override public String toString() { // return "<"+queryType+","+condition+","+primaryAttribute+","+ // primaryAttributeValue+">"; // } // public Query(QueryType type, Condition condition) { // this.queryType = type; // this.condition = condition; // } // // public QueryType getQueryType() { return queryType; } // // public Rectangle getParam_Rectangle(String paramName) { // Rectangle spatialRect = (Rectangle)params.get(paramName); // return spatialRect; // } // // public void putParam_Rectangle(String paramName, Rectangle rect) { // params.put(paramName, rect); // } // // public boolean isHash() { // return queryType==QueryType.HASH_TEMPORAL; // } // // public boolean isSpatial() { // return queryType== QueryType.SPATIAL_RANGE_TEMPORAL || queryType== QueryType // .SPATIAL_KNN_TEMPORAL; // } // // public boolean isSpatialRange() { // return queryType== QueryType.SPATIAL_RANGE_TEMPORAL; // } // // public boolean isSpatialKNN() { // return queryType== QueryType.SPATIAL_KNN_TEMPORAL; // } // // public int getK() { // return k; // } // // public TemporalPeriod getTime() { // return time; // } // // public void setK(int k) { // this.k = k; // } // // public void setTime(TemporalPeriod time) { // this.time = time; // } // // public Condition getCondition() { // return condition; // } // // public void setQueryType(QueryType queryType) { // this.queryType = queryType; // } // // public void setPrimaryAttribute(Attribute primaryAttribute) { // this.primaryAttribute = primaryAttribute; // } // // public Attribute getPrimaryAttribute() { // return primaryAttribute; // } // // public boolean isSingleSearchAttribute() { // return getCondition().getSearchAttributes().size()==1; // } // // public void setPrimaryAttributeValue(Object primaryAttributeValue) { // this.primaryAttributeValue = primaryAttributeValue; // } // // public Object getPrimaryAttributeValue() { // return primaryAttributeValue; // } // } // Path: kite-core/src/main/java/edu/umn/cs/kite/indexing/memory/MemoryIndexSegment.java import edu.umn.cs.kite.querying.Query; import java.util.ArrayList; package edu.umn.cs.kite.indexing.memory; /** * Created by amr_000 on 8/1/2016. */ public interface MemoryIndexSegment<K,V> { public abstract int insert(K key, V value); public abstract int insert(K key, ArrayList<V> value);
public abstract ArrayList<V> search(K key, Query query);
amrmagdy4/kite
kite-core/src/main/java/edu/umn/cs/kite/util/Rectangle.java
// Path: kite-core/src/main/java/edu/umn/cs/kite/util/serialization/ByteStream.java // public class ByteStream { // // private final int DELTA = 1024; // private int capacity ; // private ByteBuffer byteStream ; // // public ByteStream(int capacity) { // this.capacity = 2*capacity+4*DELTA; // byteStream = ByteBuffer.allocate(this.capacity); // } // // public ByteStream(byte [] bytes) { // byteStream = ByteBuffer.wrap(bytes); // } // // public int write(byte[] bytes) { // byteStream.put(bytes); // return Byte.BYTES*bytes.length; // } // // public int write(byte[] bytes, int length) { // byteStream.put(bytes,0,length); // return Byte.BYTES*length; // } // // public int write(byte oneByte) { // byteStream.put(oneByte); // return Byte.BYTES; // } // // public int write(int value) { // byteStream.putInt(value); // return Integer.BYTES; // } // // public int write(long value) { // byteStream.putLong(value); // return Long.BYTES; // } // // public int write(String str) { // int bytesLen = 0; // if(str == null) { // bytesLen += this.write(0); // } // else { // byte[] strBytes = str.getBytes(); // // bytesLen += this.write(strBytes.length); //key length // bytesLen += this.write(strBytes); // } // return bytesLen; // } // // public byte[] getBytes() { return byteStream.array(); } // // public int getWrittenBytes() { return byteStream.position(); } // // public int getReadBytes() { return byteStream.position(); } // // public boolean hasRemaining(){return byteStream.hasRemaining();} // // public int write(double dblVal) { // byteStream.putDouble(dblVal); // return Double.BYTES; // } // // public int readInt() { // return byteStream.getInt(); // } // // public byte[] readBytes(int bytesLen) { // byte [] bytes = new byte[bytesLen]; // byteStream.get(bytes,0,bytesLen); // return bytes; // } // // public boolean skipBytes(int bytesLen) { // try { // byteStream.position(byteStream.position()+bytesLen); // return true; // } catch (IllegalArgumentException e) { // return false; // } // } // // public long readLong() { // return byteStream.getLong(); // } // // public String readString() { // int keyBytesLen = readInt(); // if(keyBytesLen == 0) // return null; // byte [] keyStrBytes = readBytes(keyBytesLen); // return new String(keyStrBytes); // } // // public byte readByte() { // byte [] bytes = readBytes(1); // return bytes[0]; // } // // public double readDouble() { // return byteStream.getDouble(); // } // // public void clear() { // byteStream.clear(); // } // // public byte[] getBytesClone() { // int lenToCopy = getWrittenBytes(); // return Arrays.copyOfRange(byteStream.array(),0, lenToCopy); // } // // public int getCapacity() { // return capacity; // } // }
import edu.umn.cs.kite.util.serialization.ByteStream;
public double getNorth() { return north; } public double getSouth() { return south; } public double getEast() { return east; } public double getWest() { return west; } public boolean isValid() { return south <= north && west <= east; } public Rectangle merge(Rectangle other) { if(this.equals(other)) return other; Rectangle mergedRect = new Rectangle(Math.max(north,other.getNorth()), Math.min(south,other.getSouth()), Math.max(east,other.getEast ()), Math.min(west, other.getWest())); return mergedRect; } @Override
// Path: kite-core/src/main/java/edu/umn/cs/kite/util/serialization/ByteStream.java // public class ByteStream { // // private final int DELTA = 1024; // private int capacity ; // private ByteBuffer byteStream ; // // public ByteStream(int capacity) { // this.capacity = 2*capacity+4*DELTA; // byteStream = ByteBuffer.allocate(this.capacity); // } // // public ByteStream(byte [] bytes) { // byteStream = ByteBuffer.wrap(bytes); // } // // public int write(byte[] bytes) { // byteStream.put(bytes); // return Byte.BYTES*bytes.length; // } // // public int write(byte[] bytes, int length) { // byteStream.put(bytes,0,length); // return Byte.BYTES*length; // } // // public int write(byte oneByte) { // byteStream.put(oneByte); // return Byte.BYTES; // } // // public int write(int value) { // byteStream.putInt(value); // return Integer.BYTES; // } // // public int write(long value) { // byteStream.putLong(value); // return Long.BYTES; // } // // public int write(String str) { // int bytesLen = 0; // if(str == null) { // bytesLen += this.write(0); // } // else { // byte[] strBytes = str.getBytes(); // // bytesLen += this.write(strBytes.length); //key length // bytesLen += this.write(strBytes); // } // return bytesLen; // } // // public byte[] getBytes() { return byteStream.array(); } // // public int getWrittenBytes() { return byteStream.position(); } // // public int getReadBytes() { return byteStream.position(); } // // public boolean hasRemaining(){return byteStream.hasRemaining();} // // public int write(double dblVal) { // byteStream.putDouble(dblVal); // return Double.BYTES; // } // // public int readInt() { // return byteStream.getInt(); // } // // public byte[] readBytes(int bytesLen) { // byte [] bytes = new byte[bytesLen]; // byteStream.get(bytes,0,bytesLen); // return bytes; // } // // public boolean skipBytes(int bytesLen) { // try { // byteStream.position(byteStream.position()+bytesLen); // return true; // } catch (IllegalArgumentException e) { // return false; // } // } // // public long readLong() { // return byteStream.getLong(); // } // // public String readString() { // int keyBytesLen = readInt(); // if(keyBytesLen == 0) // return null; // byte [] keyStrBytes = readBytes(keyBytesLen); // return new String(keyStrBytes); // } // // public byte readByte() { // byte [] bytes = readBytes(1); // return bytes[0]; // } // // public double readDouble() { // return byteStream.getDouble(); // } // // public void clear() { // byteStream.clear(); // } // // public byte[] getBytesClone() { // int lenToCopy = getWrittenBytes(); // return Arrays.copyOfRange(byteStream.array(),0, lenToCopy); // } // // public int getCapacity() { // return capacity; // } // } // Path: kite-core/src/main/java/edu/umn/cs/kite/util/Rectangle.java import edu.umn.cs.kite.util.serialization.ByteStream; public double getNorth() { return north; } public double getSouth() { return south; } public double getEast() { return east; } public double getWest() { return west; } public boolean isValid() { return south <= north && west <= east; } public Rectangle merge(Rectangle other) { if(this.equals(other)) return other; Rectangle mergedRect = new Rectangle(Math.max(north,other.getNorth()), Math.min(south,other.getSouth()), Math.max(east,other.getEast ()), Math.min(west, other.getWest())); return mergedRect; } @Override
public int serialize(ByteStream byteStream) {
amrmagdy4/kite
kite-core/src/main/java/edu/umn/cs/kite/common/KiteLaunchTool.java
// Path: kite-core/src/main/java/edu/umn/cs/kite/util/ConstantsAndDefaults.java // public class ConstantsAndDefaults { // public static long GC_PERIOD_MILLISECONDS = 15*60*1000; // public static long LOG_PERIOD_MILLISECONDS = 2*60*1000; // public static int FILE_BLK_SIZE_BYTES = 128*1024*1024*1; // public static int BUFFER_SIZE_BYTES = 4096 * 1024; // public static int RECOVERY_BLK_SIZE_BYTES = 64*1024*1024*1; // // //Memory data constants // public final static int MAX_MEMORY_CHUNK_CAPACITY = 3000000; // public final static double MEMORY_DATA_FLUSH_THRESHOLD = 0.2; // // //Memory indexes // public static int MEMORY_INDEX_DEFAULT_SEGMENTS = 5; // public static final long BATCH_UPDATE_TIME_MILLISECONDS = 3000; // public static final int TEMPORAL_FLUSHING_PERIODIC_TIME_MINUTES = 360; // public static final int TEMPORAL_FLUSHING_PERIODIC_DATA_SIZE = 1000000; // // public static int MEMORY_INDEX_CAPACITY = // TEMPORAL_FLUSHING_PERIODIC_DATA_SIZE; // // //Disk indexes // public static String DISK_INDEXES_ROOT_DIRECTORY; // public static final int NUM_DISK_SEGMENTS_IN_MEMORY_DIRECTORY = 10; // // //Query default values // public static int QUERY_ANSWER_SIZE = 20; // public static long QUERY_TIME = 3*60*60*1000;//3 hours // public static TemporalPeriod QUERY_TIME() { // long to = new Date().getTime(); // long from = to - QUERY_TIME; // return new TemporalPeriod(from, to); // } // } // // Path: kite-core/src/main/java/edu/umn/cs/kite/util/GC.java // public class GC implements Runnable { // public static void invoke() { // Thread gcThread = new Thread(new GC()); // gcThread.start(); // } // // @Override // public void run() { // System.gc(); // } // }
import edu.umn.cs.kite.util.ConstantsAndDefaults; import edu.umn.cs.kite.util.GC; import org.apache.ignite.Ignite; import org.apache.ignite.Ignition; import org.apache.ignite.configuration.IgniteConfiguration; import java.util.Timer; import java.util.TimerTask;
package edu.umn.cs.kite.common; /** * Created by amr_000 on 8/1/2016. */ public class KiteLaunchTool { private Ignite cluster = null; private String configurationXMLFile = null; private Timer gcTimer; public Ignite getCluster() { return cluster; } public KiteLaunchTool(String configurationXML) { cluster = Ignition.start(configurationXML); init(); } public KiteLaunchTool() { boolean peerClassLoading = true; IgniteConfiguration config = new IgniteConfiguration(); config.setPeerClassLoadingEnabled(peerClassLoading); cluster = Ignition.start(config); init(); } private void init(){ printKiteName(); startGCTimer(); } private void startGCTimer() { gcTimer = new Timer(true);
// Path: kite-core/src/main/java/edu/umn/cs/kite/util/ConstantsAndDefaults.java // public class ConstantsAndDefaults { // public static long GC_PERIOD_MILLISECONDS = 15*60*1000; // public static long LOG_PERIOD_MILLISECONDS = 2*60*1000; // public static int FILE_BLK_SIZE_BYTES = 128*1024*1024*1; // public static int BUFFER_SIZE_BYTES = 4096 * 1024; // public static int RECOVERY_BLK_SIZE_BYTES = 64*1024*1024*1; // // //Memory data constants // public final static int MAX_MEMORY_CHUNK_CAPACITY = 3000000; // public final static double MEMORY_DATA_FLUSH_THRESHOLD = 0.2; // // //Memory indexes // public static int MEMORY_INDEX_DEFAULT_SEGMENTS = 5; // public static final long BATCH_UPDATE_TIME_MILLISECONDS = 3000; // public static final int TEMPORAL_FLUSHING_PERIODIC_TIME_MINUTES = 360; // public static final int TEMPORAL_FLUSHING_PERIODIC_DATA_SIZE = 1000000; // // public static int MEMORY_INDEX_CAPACITY = // TEMPORAL_FLUSHING_PERIODIC_DATA_SIZE; // // //Disk indexes // public static String DISK_INDEXES_ROOT_DIRECTORY; // public static final int NUM_DISK_SEGMENTS_IN_MEMORY_DIRECTORY = 10; // // //Query default values // public static int QUERY_ANSWER_SIZE = 20; // public static long QUERY_TIME = 3*60*60*1000;//3 hours // public static TemporalPeriod QUERY_TIME() { // long to = new Date().getTime(); // long from = to - QUERY_TIME; // return new TemporalPeriod(from, to); // } // } // // Path: kite-core/src/main/java/edu/umn/cs/kite/util/GC.java // public class GC implements Runnable { // public static void invoke() { // Thread gcThread = new Thread(new GC()); // gcThread.start(); // } // // @Override // public void run() { // System.gc(); // } // } // Path: kite-core/src/main/java/edu/umn/cs/kite/common/KiteLaunchTool.java import edu.umn.cs.kite.util.ConstantsAndDefaults; import edu.umn.cs.kite.util.GC; import org.apache.ignite.Ignite; import org.apache.ignite.Ignition; import org.apache.ignite.configuration.IgniteConfiguration; import java.util.Timer; import java.util.TimerTask; package edu.umn.cs.kite.common; /** * Created by amr_000 on 8/1/2016. */ public class KiteLaunchTool { private Ignite cluster = null; private String configurationXMLFile = null; private Timer gcTimer; public Ignite getCluster() { return cluster; } public KiteLaunchTool(String configurationXML) { cluster = Ignition.start(configurationXML); init(); } public KiteLaunchTool() { boolean peerClassLoading = true; IgniteConfiguration config = new IgniteConfiguration(); config.setPeerClassLoadingEnabled(peerClassLoading); cluster = Ignition.start(config); init(); } private void init(){ printKiteName(); startGCTimer(); } private void startGCTimer() { gcTimer = new Timer(true);
long timerPeriod = ConstantsAndDefaults.GC_PERIOD_MILLISECONDS;
amrmagdy4/kite
kite-core/src/main/java/edu/umn/cs/kite/common/KiteLaunchTool.java
// Path: kite-core/src/main/java/edu/umn/cs/kite/util/ConstantsAndDefaults.java // public class ConstantsAndDefaults { // public static long GC_PERIOD_MILLISECONDS = 15*60*1000; // public static long LOG_PERIOD_MILLISECONDS = 2*60*1000; // public static int FILE_BLK_SIZE_BYTES = 128*1024*1024*1; // public static int BUFFER_SIZE_BYTES = 4096 * 1024; // public static int RECOVERY_BLK_SIZE_BYTES = 64*1024*1024*1; // // //Memory data constants // public final static int MAX_MEMORY_CHUNK_CAPACITY = 3000000; // public final static double MEMORY_DATA_FLUSH_THRESHOLD = 0.2; // // //Memory indexes // public static int MEMORY_INDEX_DEFAULT_SEGMENTS = 5; // public static final long BATCH_UPDATE_TIME_MILLISECONDS = 3000; // public static final int TEMPORAL_FLUSHING_PERIODIC_TIME_MINUTES = 360; // public static final int TEMPORAL_FLUSHING_PERIODIC_DATA_SIZE = 1000000; // // public static int MEMORY_INDEX_CAPACITY = // TEMPORAL_FLUSHING_PERIODIC_DATA_SIZE; // // //Disk indexes // public static String DISK_INDEXES_ROOT_DIRECTORY; // public static final int NUM_DISK_SEGMENTS_IN_MEMORY_DIRECTORY = 10; // // //Query default values // public static int QUERY_ANSWER_SIZE = 20; // public static long QUERY_TIME = 3*60*60*1000;//3 hours // public static TemporalPeriod QUERY_TIME() { // long to = new Date().getTime(); // long from = to - QUERY_TIME; // return new TemporalPeriod(from, to); // } // } // // Path: kite-core/src/main/java/edu/umn/cs/kite/util/GC.java // public class GC implements Runnable { // public static void invoke() { // Thread gcThread = new Thread(new GC()); // gcThread.start(); // } // // @Override // public void run() { // System.gc(); // } // }
import edu.umn.cs.kite.util.ConstantsAndDefaults; import edu.umn.cs.kite.util.GC; import org.apache.ignite.Ignite; import org.apache.ignite.Ignition; import org.apache.ignite.configuration.IgniteConfiguration; import java.util.Timer; import java.util.TimerTask;
package edu.umn.cs.kite.common; /** * Created by amr_000 on 8/1/2016. */ public class KiteLaunchTool { private Ignite cluster = null; private String configurationXMLFile = null; private Timer gcTimer; public Ignite getCluster() { return cluster; } public KiteLaunchTool(String configurationXML) { cluster = Ignition.start(configurationXML); init(); } public KiteLaunchTool() { boolean peerClassLoading = true; IgniteConfiguration config = new IgniteConfiguration(); config.setPeerClassLoadingEnabled(peerClassLoading); cluster = Ignition.start(config); init(); } private void init(){ printKiteName(); startGCTimer(); } private void startGCTimer() { gcTimer = new Timer(true); long timerPeriod = ConstantsAndDefaults.GC_PERIOD_MILLISECONDS; gcTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() {
// Path: kite-core/src/main/java/edu/umn/cs/kite/util/ConstantsAndDefaults.java // public class ConstantsAndDefaults { // public static long GC_PERIOD_MILLISECONDS = 15*60*1000; // public static long LOG_PERIOD_MILLISECONDS = 2*60*1000; // public static int FILE_BLK_SIZE_BYTES = 128*1024*1024*1; // public static int BUFFER_SIZE_BYTES = 4096 * 1024; // public static int RECOVERY_BLK_SIZE_BYTES = 64*1024*1024*1; // // //Memory data constants // public final static int MAX_MEMORY_CHUNK_CAPACITY = 3000000; // public final static double MEMORY_DATA_FLUSH_THRESHOLD = 0.2; // // //Memory indexes // public static int MEMORY_INDEX_DEFAULT_SEGMENTS = 5; // public static final long BATCH_UPDATE_TIME_MILLISECONDS = 3000; // public static final int TEMPORAL_FLUSHING_PERIODIC_TIME_MINUTES = 360; // public static final int TEMPORAL_FLUSHING_PERIODIC_DATA_SIZE = 1000000; // // public static int MEMORY_INDEX_CAPACITY = // TEMPORAL_FLUSHING_PERIODIC_DATA_SIZE; // // //Disk indexes // public static String DISK_INDEXES_ROOT_DIRECTORY; // public static final int NUM_DISK_SEGMENTS_IN_MEMORY_DIRECTORY = 10; // // //Query default values // public static int QUERY_ANSWER_SIZE = 20; // public static long QUERY_TIME = 3*60*60*1000;//3 hours // public static TemporalPeriod QUERY_TIME() { // long to = new Date().getTime(); // long from = to - QUERY_TIME; // return new TemporalPeriod(from, to); // } // } // // Path: kite-core/src/main/java/edu/umn/cs/kite/util/GC.java // public class GC implements Runnable { // public static void invoke() { // Thread gcThread = new Thread(new GC()); // gcThread.start(); // } // // @Override // public void run() { // System.gc(); // } // } // Path: kite-core/src/main/java/edu/umn/cs/kite/common/KiteLaunchTool.java import edu.umn.cs.kite.util.ConstantsAndDefaults; import edu.umn.cs.kite.util.GC; import org.apache.ignite.Ignite; import org.apache.ignite.Ignition; import org.apache.ignite.configuration.IgniteConfiguration; import java.util.Timer; import java.util.TimerTask; package edu.umn.cs.kite.common; /** * Created by amr_000 on 8/1/2016. */ public class KiteLaunchTool { private Ignite cluster = null; private String configurationXMLFile = null; private Timer gcTimer; public Ignite getCluster() { return cluster; } public KiteLaunchTool(String configurationXML) { cluster = Ignition.start(configurationXML); init(); } public KiteLaunchTool() { boolean peerClassLoading = true; IgniteConfiguration config = new IgniteConfiguration(); config.setPeerClassLoadingEnabled(peerClassLoading); cluster = Ignition.start(config); init(); } private void init(){ printKiteName(); startGCTimer(); } private void startGCTimer() { gcTimer = new Timer(true); long timerPeriod = ConstantsAndDefaults.GC_PERIOD_MILLISECONDS; gcTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() {
GC.invoke();
amrmagdy4/kite
kite-core/src/main/java/edu/umn/cs/kite/querying/metadata/IndexMetadataEntry.java
// Path: kite-core/src/main/java/edu/umn/cs/kite/util/serialization/ByteStream.java // public class ByteStream { // // private final int DELTA = 1024; // private int capacity ; // private ByteBuffer byteStream ; // // public ByteStream(int capacity) { // this.capacity = 2*capacity+4*DELTA; // byteStream = ByteBuffer.allocate(this.capacity); // } // // public ByteStream(byte [] bytes) { // byteStream = ByteBuffer.wrap(bytes); // } // // public int write(byte[] bytes) { // byteStream.put(bytes); // return Byte.BYTES*bytes.length; // } // // public int write(byte[] bytes, int length) { // byteStream.put(bytes,0,length); // return Byte.BYTES*length; // } // // public int write(byte oneByte) { // byteStream.put(oneByte); // return Byte.BYTES; // } // // public int write(int value) { // byteStream.putInt(value); // return Integer.BYTES; // } // // public int write(long value) { // byteStream.putLong(value); // return Long.BYTES; // } // // public int write(String str) { // int bytesLen = 0; // if(str == null) { // bytesLen += this.write(0); // } // else { // byte[] strBytes = str.getBytes(); // // bytesLen += this.write(strBytes.length); //key length // bytesLen += this.write(strBytes); // } // return bytesLen; // } // // public byte[] getBytes() { return byteStream.array(); } // // public int getWrittenBytes() { return byteStream.position(); } // // public int getReadBytes() { return byteStream.position(); } // // public boolean hasRemaining(){return byteStream.hasRemaining();} // // public int write(double dblVal) { // byteStream.putDouble(dblVal); // return Double.BYTES; // } // // public int readInt() { // return byteStream.getInt(); // } // // public byte[] readBytes(int bytesLen) { // byte [] bytes = new byte[bytesLen]; // byteStream.get(bytes,0,bytesLen); // return bytes; // } // // public boolean skipBytes(int bytesLen) { // try { // byteStream.position(byteStream.position()+bytesLen); // return true; // } catch (IllegalArgumentException e) { // return false; // } // } // // public long readLong() { // return byteStream.getLong(); // } // // public String readString() { // int keyBytesLen = readInt(); // if(keyBytesLen == 0) // return null; // byte [] keyStrBytes = readBytes(keyBytesLen); // return new String(keyStrBytes); // } // // public byte readByte() { // byte [] bytes = readBytes(1); // return bytes[0]; // } // // public double readDouble() { // return byteStream.getDouble(); // } // // public void clear() { // byteStream.clear(); // } // // public byte[] getBytesClone() { // int lenToCopy = getWrittenBytes(); // return Arrays.copyOfRange(byteStream.array(),0, lenToCopy); // } // // public int getCapacity() { // return capacity; // } // }
import edu.umn.cs.kite.util.serialization.ByteStream; import java.util.List;
package edu.umn.cs.kite.querying.metadata; /** * Created by amr_000 on 12/27/2016. */ public class IndexMetadataEntry implements MetadataEntry { private String indexType; private String indexName; private String streamName; private String attributeName; private List<Object> options; public IndexMetadataEntry(String indexType, String indexName, String streamName, String attributeName, List<Object> options) { this.indexType = indexType; this.indexName = indexName; this.streamName = streamName; this.attributeName = attributeName; this.options = options; } @Override public boolean isStreamEntry() {return false;} @Override public boolean isIndexEntry() { return true;} @Override public boolean isCommandEntry() { return false; } @Override public boolean isQueryEntry() { return false; } @Override
// Path: kite-core/src/main/java/edu/umn/cs/kite/util/serialization/ByteStream.java // public class ByteStream { // // private final int DELTA = 1024; // private int capacity ; // private ByteBuffer byteStream ; // // public ByteStream(int capacity) { // this.capacity = 2*capacity+4*DELTA; // byteStream = ByteBuffer.allocate(this.capacity); // } // // public ByteStream(byte [] bytes) { // byteStream = ByteBuffer.wrap(bytes); // } // // public int write(byte[] bytes) { // byteStream.put(bytes); // return Byte.BYTES*bytes.length; // } // // public int write(byte[] bytes, int length) { // byteStream.put(bytes,0,length); // return Byte.BYTES*length; // } // // public int write(byte oneByte) { // byteStream.put(oneByte); // return Byte.BYTES; // } // // public int write(int value) { // byteStream.putInt(value); // return Integer.BYTES; // } // // public int write(long value) { // byteStream.putLong(value); // return Long.BYTES; // } // // public int write(String str) { // int bytesLen = 0; // if(str == null) { // bytesLen += this.write(0); // } // else { // byte[] strBytes = str.getBytes(); // // bytesLen += this.write(strBytes.length); //key length // bytesLen += this.write(strBytes); // } // return bytesLen; // } // // public byte[] getBytes() { return byteStream.array(); } // // public int getWrittenBytes() { return byteStream.position(); } // // public int getReadBytes() { return byteStream.position(); } // // public boolean hasRemaining(){return byteStream.hasRemaining();} // // public int write(double dblVal) { // byteStream.putDouble(dblVal); // return Double.BYTES; // } // // public int readInt() { // return byteStream.getInt(); // } // // public byte[] readBytes(int bytesLen) { // byte [] bytes = new byte[bytesLen]; // byteStream.get(bytes,0,bytesLen); // return bytes; // } // // public boolean skipBytes(int bytesLen) { // try { // byteStream.position(byteStream.position()+bytesLen); // return true; // } catch (IllegalArgumentException e) { // return false; // } // } // // public long readLong() { // return byteStream.getLong(); // } // // public String readString() { // int keyBytesLen = readInt(); // if(keyBytesLen == 0) // return null; // byte [] keyStrBytes = readBytes(keyBytesLen); // return new String(keyStrBytes); // } // // public byte readByte() { // byte [] bytes = readBytes(1); // return bytes[0]; // } // // public double readDouble() { // return byteStream.getDouble(); // } // // public void clear() { // byteStream.clear(); // } // // public byte[] getBytesClone() { // int lenToCopy = getWrittenBytes(); // return Arrays.copyOfRange(byteStream.array(),0, lenToCopy); // } // // public int getCapacity() { // return capacity; // } // } // Path: kite-core/src/main/java/edu/umn/cs/kite/querying/metadata/IndexMetadataEntry.java import edu.umn.cs.kite.util.serialization.ByteStream; import java.util.List; package edu.umn.cs.kite.querying.metadata; /** * Created by amr_000 on 12/27/2016. */ public class IndexMetadataEntry implements MetadataEntry { private String indexType; private String indexName; private String streamName; private String attributeName; private List<Object> options; public IndexMetadataEntry(String indexType, String indexName, String streamName, String attributeName, List<Object> options) { this.indexType = indexType; this.indexName = indexName; this.streamName = streamName; this.attributeName = attributeName; this.options = options; } @Override public boolean isStreamEntry() {return false;} @Override public boolean isIndexEntry() { return true;} @Override public boolean isCommandEntry() { return false; } @Override public boolean isQueryEntry() { return false; } @Override
public void serialize(ByteStream byteStream) {
PunchThrough/bean-sdk-android
sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/EnumParse.java
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/NoEnumFoundException.java // public class NoEnumFoundException extends Exception { // public NoEnumFoundException(String detailMessage) { // super(detailMessage); // } // }
import com.punchthrough.bean.sdk.internal.exception.NoEnumFoundException; import java.util.EnumSet;
package com.punchthrough.bean.sdk.internal.utility; /** * Utilities for parsing enums from raw values. */ public class EnumParse { /** * Denotes enums that provide a method "int getRawValue()" to get their unique int representation. */ public static interface ParsableEnum { public int getRawValue(); } /** * Retrieve the enum of a given type from a given raw value. Enums must implement the * {@link com.punchthrough.bean.sdk.internal.utility.EnumParse.ParsableEnum} interface to ensure they have * a {@link com.punchthrough.bean.sdk.internal.utility.EnumParse.ParsableEnum#getRawValue()} method. * <a href="http://stackoverflow.com/a/16406386/254187">Based on this StackOverflow answer.</a> * * @param enumClass The class of the enum type being parsed, e.g. <code>BeanState.class</code> * @param value The raw int value of the enum to be retrieved * @param <T> The enum type being parsed * @return The enum value with the given raw value * * @throws com.punchthrough.bean.sdk.internal.exception.NoEnumFoundException if the given enum type has no enum value with a raw value * matching the given value */ public static <T extends Enum & ParsableEnum> T enumWithRawValue(Class<T> enumClass, int value)
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/NoEnumFoundException.java // public class NoEnumFoundException extends Exception { // public NoEnumFoundException(String detailMessage) { // super(detailMessage); // } // } // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/EnumParse.java import com.punchthrough.bean.sdk.internal.exception.NoEnumFoundException; import java.util.EnumSet; package com.punchthrough.bean.sdk.internal.utility; /** * Utilities for parsing enums from raw values. */ public class EnumParse { /** * Denotes enums that provide a method "int getRawValue()" to get their unique int representation. */ public static interface ParsableEnum { public int getRawValue(); } /** * Retrieve the enum of a given type from a given raw value. Enums must implement the * {@link com.punchthrough.bean.sdk.internal.utility.EnumParse.ParsableEnum} interface to ensure they have * a {@link com.punchthrough.bean.sdk.internal.utility.EnumParse.ParsableEnum#getRawValue()} method. * <a href="http://stackoverflow.com/a/16406386/254187">Based on this StackOverflow answer.</a> * * @param enumClass The class of the enum type being parsed, e.g. <code>BeanState.class</code> * @param value The raw int value of the enum to be retrieved * @param <T> The enum type being parsed * @return The enum value with the given raw value * * @throws com.punchthrough.bean.sdk.internal.exception.NoEnumFoundException if the given enum type has no enum value with a raw value * matching the given value */ public static <T extends Enum & ParsableEnum> T enumWithRawValue(Class<T> enumClass, int value)
throws NoEnumFoundException {
PunchThrough/bean-sdk-android
sdk/src/main/java/com/punchthrough/bean/sdk/upload/FirmwareBundle.java
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/OADException.java // public class OADException extends Exception { // public OADException(String detailMessage) { // super(detailMessage); // } // }
import com.punchthrough.bean.sdk.internal.exception.OADException; import java.util.List;
package com.punchthrough.bean.sdk.upload; /** * Represents a bundle of firmware images */ public class FirmwareBundle { private List<FirmwareImage> images; private int imageCounter; public FirmwareBundle(List<FirmwareImage> images) { this.images = images; this.imageCounter = 0; } public long version() { return images.get(0).version(); }
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/OADException.java // public class OADException extends Exception { // public OADException(String detailMessage) { // super(detailMessage); // } // } // Path: sdk/src/main/java/com/punchthrough/bean/sdk/upload/FirmwareBundle.java import com.punchthrough.bean.sdk.internal.exception.OADException; import java.util.List; package com.punchthrough.bean.sdk.upload; /** * Represents a bundle of firmware images */ public class FirmwareBundle { private List<FirmwareImage> images; private int imageCounter; public FirmwareBundle(List<FirmwareImage> images) { this.images = images; this.imageCounter = 0; } public long version() { return images.get(0).version(); }
public FirmwareImage getNextImage() throws OADException {
PunchThrough/bean-sdk-android
sdk/src/main/java/com/punchthrough/bean/sdk/BeanListener.java
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/message/BeanError.java // public enum BeanError { // // GATT_SERIAL_TRANSPORT_ERROR, // // /** // * Bean is not connected // */ // NOT_CONNECTED, // // /** // * Bean's services have not yet been discovered // */ // SERVICES_NOT_DISCOVERED, // // /** // * OAD service was not found // */ // MISSING_OAD_SERVICE, // // /** // * OAD Identify characteristic was not found // */ // MISSING_OAD_IDENTIFY, // // /** // * OAD Block characteristic was not found // */ // MISSING_OAD_BLOCK, // // /** // * Notifications could not be enabled for either OAD Identify, Block, or both characteristics // */ // ENABLE_OAD_NOTIFY_FAILED, // // /** // * Timed out during sketch programming, before sending blocks: Bean took too long to update its // * current state // */ // STATE_TIMEOUT, // // /** // * Firmware version to send could not be parsed from OAD request header // */ // UNPARSABLE_FW_VERSION, // // /** // * Timed out during OAD // */ // OAD_TIMEOUT, // // /** // * Bean rejected firmware version for being older than the current version // */ // BEAN_REJECTED_FW, // // /** // * The client (user) rejected the OAD process // */ // CLIENT_REJECTED, // // /** // * Bean responded with a message with an ID we don't know anything about // */ // UNKNOWN_MESSAGE_ID, // // /** // * Bean did not provide a reason for the error // */ // UNKNOWN // // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/message/ScratchBank.java // public enum ScratchBank implements EnumParse.ParsableEnum { // BANK_1(1), BANK_2(2), BANK_3(3), BANK_4(4), BANK_5(5); // // private final int value; // // private ScratchBank(final int value) { // this.value = value; // } // // public int getRawValue() { // return value; // } // }
import com.punchthrough.bean.sdk.message.BeanError; import com.punchthrough.bean.sdk.message.ScratchBank;
/* * The MIT License (MIT) * * Copyright (c) 2014 Little Robots * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.punchthrough.bean.sdk; /** * A Listener interface for communicating with the Bean. */ public interface BeanListener { /** * Called when the Bean is connected. Connected means that a Bluetooth GATT connection is made * and the setup for the Bean serial protocol is complete. */ public void onConnected(); /** * Called when the connection could not be established. This could either be because the Bean * could not be connected, or the serial connection could not be established. */ public void onConnectionFailed(); /** * Called when the Bean has been disconnected. */ public void onDisconnected(); /** * Called when a serial message is received from the Bean, e.g. a <code>Serial.write()</code> * from Arduino code. * * @param data the data that was sent from th bean */ public void onSerialMessageReceived(byte[] data); /** * Called when one of the scratch characteristics of the Bean has updated its value. * * @param bank the {@link com.punchthrough.bean.sdk.message.ScratchBank} that was updated * @param value the bank's new value */
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/message/BeanError.java // public enum BeanError { // // GATT_SERIAL_TRANSPORT_ERROR, // // /** // * Bean is not connected // */ // NOT_CONNECTED, // // /** // * Bean's services have not yet been discovered // */ // SERVICES_NOT_DISCOVERED, // // /** // * OAD service was not found // */ // MISSING_OAD_SERVICE, // // /** // * OAD Identify characteristic was not found // */ // MISSING_OAD_IDENTIFY, // // /** // * OAD Block characteristic was not found // */ // MISSING_OAD_BLOCK, // // /** // * Notifications could not be enabled for either OAD Identify, Block, or both characteristics // */ // ENABLE_OAD_NOTIFY_FAILED, // // /** // * Timed out during sketch programming, before sending blocks: Bean took too long to update its // * current state // */ // STATE_TIMEOUT, // // /** // * Firmware version to send could not be parsed from OAD request header // */ // UNPARSABLE_FW_VERSION, // // /** // * Timed out during OAD // */ // OAD_TIMEOUT, // // /** // * Bean rejected firmware version for being older than the current version // */ // BEAN_REJECTED_FW, // // /** // * The client (user) rejected the OAD process // */ // CLIENT_REJECTED, // // /** // * Bean responded with a message with an ID we don't know anything about // */ // UNKNOWN_MESSAGE_ID, // // /** // * Bean did not provide a reason for the error // */ // UNKNOWN // // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/message/ScratchBank.java // public enum ScratchBank implements EnumParse.ParsableEnum { // BANK_1(1), BANK_2(2), BANK_3(3), BANK_4(4), BANK_5(5); // // private final int value; // // private ScratchBank(final int value) { // this.value = value; // } // // public int getRawValue() { // return value; // } // } // Path: sdk/src/main/java/com/punchthrough/bean/sdk/BeanListener.java import com.punchthrough.bean.sdk.message.BeanError; import com.punchthrough.bean.sdk.message.ScratchBank; /* * The MIT License (MIT) * * Copyright (c) 2014 Little Robots * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.punchthrough.bean.sdk; /** * A Listener interface for communicating with the Bean. */ public interface BeanListener { /** * Called when the Bean is connected. Connected means that a Bluetooth GATT connection is made * and the setup for the Bean serial protocol is complete. */ public void onConnected(); /** * Called when the connection could not be established. This could either be because the Bean * could not be connected, or the serial connection could not be established. */ public void onConnectionFailed(); /** * Called when the Bean has been disconnected. */ public void onDisconnected(); /** * Called when a serial message is received from the Bean, e.g. a <code>Serial.write()</code> * from Arduino code. * * @param data the data that was sent from th bean */ public void onSerialMessageReceived(byte[] data); /** * Called when one of the scratch characteristics of the Bean has updated its value. * * @param bank the {@link com.punchthrough.bean.sdk.message.ScratchBank} that was updated * @param value the bank's new value */
public void onScratchValueChanged(ScratchBank bank, byte[] value);
PunchThrough/bean-sdk-android
sdk/src/main/java/com/punchthrough/bean/sdk/BeanListener.java
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/message/BeanError.java // public enum BeanError { // // GATT_SERIAL_TRANSPORT_ERROR, // // /** // * Bean is not connected // */ // NOT_CONNECTED, // // /** // * Bean's services have not yet been discovered // */ // SERVICES_NOT_DISCOVERED, // // /** // * OAD service was not found // */ // MISSING_OAD_SERVICE, // // /** // * OAD Identify characteristic was not found // */ // MISSING_OAD_IDENTIFY, // // /** // * OAD Block characteristic was not found // */ // MISSING_OAD_BLOCK, // // /** // * Notifications could not be enabled for either OAD Identify, Block, or both characteristics // */ // ENABLE_OAD_NOTIFY_FAILED, // // /** // * Timed out during sketch programming, before sending blocks: Bean took too long to update its // * current state // */ // STATE_TIMEOUT, // // /** // * Firmware version to send could not be parsed from OAD request header // */ // UNPARSABLE_FW_VERSION, // // /** // * Timed out during OAD // */ // OAD_TIMEOUT, // // /** // * Bean rejected firmware version for being older than the current version // */ // BEAN_REJECTED_FW, // // /** // * The client (user) rejected the OAD process // */ // CLIENT_REJECTED, // // /** // * Bean responded with a message with an ID we don't know anything about // */ // UNKNOWN_MESSAGE_ID, // // /** // * Bean did not provide a reason for the error // */ // UNKNOWN // // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/message/ScratchBank.java // public enum ScratchBank implements EnumParse.ParsableEnum { // BANK_1(1), BANK_2(2), BANK_3(3), BANK_4(4), BANK_5(5); // // private final int value; // // private ScratchBank(final int value) { // this.value = value; // } // // public int getRawValue() { // return value; // } // }
import com.punchthrough.bean.sdk.message.BeanError; import com.punchthrough.bean.sdk.message.ScratchBank;
/* * The MIT License (MIT) * * Copyright (c) 2014 Little Robots * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.punchthrough.bean.sdk; /** * A Listener interface for communicating with the Bean. */ public interface BeanListener { /** * Called when the Bean is connected. Connected means that a Bluetooth GATT connection is made * and the setup for the Bean serial protocol is complete. */ public void onConnected(); /** * Called when the connection could not be established. This could either be because the Bean * could not be connected, or the serial connection could not be established. */ public void onConnectionFailed(); /** * Called when the Bean has been disconnected. */ public void onDisconnected(); /** * Called when a serial message is received from the Bean, e.g. a <code>Serial.write()</code> * from Arduino code. * * @param data the data that was sent from th bean */ public void onSerialMessageReceived(byte[] data); /** * Called when one of the scratch characteristics of the Bean has updated its value. * * @param bank the {@link com.punchthrough.bean.sdk.message.ScratchBank} that was updated * @param value the bank's new value */ public void onScratchValueChanged(ScratchBank bank, byte[] value); /** * Called when an error occurs during sketch or firmware upload. * * @param error The {@link com.punchthrough.bean.sdk.message.BeanError} that occurred */
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/message/BeanError.java // public enum BeanError { // // GATT_SERIAL_TRANSPORT_ERROR, // // /** // * Bean is not connected // */ // NOT_CONNECTED, // // /** // * Bean's services have not yet been discovered // */ // SERVICES_NOT_DISCOVERED, // // /** // * OAD service was not found // */ // MISSING_OAD_SERVICE, // // /** // * OAD Identify characteristic was not found // */ // MISSING_OAD_IDENTIFY, // // /** // * OAD Block characteristic was not found // */ // MISSING_OAD_BLOCK, // // /** // * Notifications could not be enabled for either OAD Identify, Block, or both characteristics // */ // ENABLE_OAD_NOTIFY_FAILED, // // /** // * Timed out during sketch programming, before sending blocks: Bean took too long to update its // * current state // */ // STATE_TIMEOUT, // // /** // * Firmware version to send could not be parsed from OAD request header // */ // UNPARSABLE_FW_VERSION, // // /** // * Timed out during OAD // */ // OAD_TIMEOUT, // // /** // * Bean rejected firmware version for being older than the current version // */ // BEAN_REJECTED_FW, // // /** // * The client (user) rejected the OAD process // */ // CLIENT_REJECTED, // // /** // * Bean responded with a message with an ID we don't know anything about // */ // UNKNOWN_MESSAGE_ID, // // /** // * Bean did not provide a reason for the error // */ // UNKNOWN // // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/message/ScratchBank.java // public enum ScratchBank implements EnumParse.ParsableEnum { // BANK_1(1), BANK_2(2), BANK_3(3), BANK_4(4), BANK_5(5); // // private final int value; // // private ScratchBank(final int value) { // this.value = value; // } // // public int getRawValue() { // return value; // } // } // Path: sdk/src/main/java/com/punchthrough/bean/sdk/BeanListener.java import com.punchthrough.bean.sdk.message.BeanError; import com.punchthrough.bean.sdk.message.ScratchBank; /* * The MIT License (MIT) * * Copyright (c) 2014 Little Robots * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.punchthrough.bean.sdk; /** * A Listener interface for communicating with the Bean. */ public interface BeanListener { /** * Called when the Bean is connected. Connected means that a Bluetooth GATT connection is made * and the setup for the Bean serial protocol is complete. */ public void onConnected(); /** * Called when the connection could not be established. This could either be because the Bean * could not be connected, or the serial connection could not be established. */ public void onConnectionFailed(); /** * Called when the Bean has been disconnected. */ public void onDisconnected(); /** * Called when a serial message is received from the Bean, e.g. a <code>Serial.write()</code> * from Arduino code. * * @param data the data that was sent from th bean */ public void onSerialMessageReceived(byte[] data); /** * Called when one of the scratch characteristics of the Bean has updated its value. * * @param bank the {@link com.punchthrough.bean.sdk.message.ScratchBank} that was updated * @param value the bank's new value */ public void onScratchValueChanged(ScratchBank bank, byte[] value); /** * Called when an error occurs during sketch or firmware upload. * * @param error The {@link com.punchthrough.bean.sdk.message.BeanError} that occurred */
public void onError(BeanError error);
PunchThrough/bean-sdk-android
sdk/src/main/java/com/punchthrough/bean/sdk/internal/serial/GattSerialPacket.java
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/serial/GattSerialTransportProfile.java // public static final int PACKET_TX_MAX_PAYLOAD_LENGTH = 19;
import java.io.IOException; import okio.Buffer; import static com.punchthrough.bean.sdk.internal.serial.GattSerialTransportProfile.PACKET_TX_MAX_PAYLOAD_LENGTH;
/* * The MIT License (MIT) * * Copyright (c) 2014 Little Robots * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.punchthrough.bean.sdk.internal.serial; public class GattSerialPacket { private final boolean mFirstPacket; private final int mMessageCount; private final int mPendingCount; private byte[] mPacket; public GattSerialPacket(boolean startBit, int outgoingMessageCount, int pendingPacketCount, Buffer message) { mFirstPacket = startBit; mMessageCount = outgoingMessageCount; mPendingCount = pendingPacketCount; Buffer buffer = new Buffer(); buffer.writeByte((startBit ? 0x80 : 0) | ((outgoingMessageCount << 5) & 0x60) | ((pendingPacketCount & 0x1f)));
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/serial/GattSerialTransportProfile.java // public static final int PACKET_TX_MAX_PAYLOAD_LENGTH = 19; // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/serial/GattSerialPacket.java import java.io.IOException; import okio.Buffer; import static com.punchthrough.bean.sdk.internal.serial.GattSerialTransportProfile.PACKET_TX_MAX_PAYLOAD_LENGTH; /* * The MIT License (MIT) * * Copyright (c) 2014 Little Robots * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.punchthrough.bean.sdk.internal.serial; public class GattSerialPacket { private final boolean mFirstPacket; private final int mMessageCount; private final int mPendingCount; private byte[] mPacket; public GattSerialPacket(boolean startBit, int outgoingMessageCount, int pendingPacketCount, Buffer message) { mFirstPacket = startBit; mMessageCount = outgoingMessageCount; mPendingCount = pendingPacketCount; Buffer buffer = new Buffer(); buffer.writeByte((startBit ? 0x80 : 0) | ((outgoingMessageCount << 5) & 0x60) | ((pendingPacketCount & 0x1f)));
int size = (int) Math.min(PACKET_TX_MAX_PAYLOAD_LENGTH, message.size());
PunchThrough/bean-sdk-android
sdk/src/test/java/com/punchthrough/bean/sdk/upload/SketchHexTest.java
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Convert.java // public static byte[] intArrayToByteArray(int[] intArray) { // // byte[] byteArray = new byte[intArray.length]; // // for (int i = 0; i < intArray.length; i++) { // byteArray[i] = intToByte(intArray[i]); // } // // return byteArray; // // }
import com.punchthrough.bean.sdk.internal.exception.HexParsingException; import com.punchthrough.bean.sdk.internal.utility.Chunk; import org.junit.Before; import org.junit.Test; import java.util.List; import static com.punchthrough.bean.sdk.internal.utility.Convert.intArrayToByteArray; import static org.assertj.core.api.Assertions.assertThat;
package com.punchthrough.bean.sdk.upload; public class SketchHexTest { // From http://en.wikipedia.org/wiki/Intel_HEX final String asciiHexData = // Bytes 1-8 Bytes 9-16 // |...............|............... ":10010000214601360121470136007EFE09D2190140\r\n" + ":100110002146017E17C20001FF5F16002148011928\r\n" + ":10012000194E79234623965778239EDA3F01B2CAA7\r\n" + ":100130003F0156702B5E712B722B732146013421C7\r\n" + ":00000001FF"; // Produced from the above hex by http://hex2bin.sourceforge.net/ final int[] rawHexDataInts = new int[]{ 0x21, 0x46, 0x01, 0x36, 0x01, 0x21, 0x47, 0x01, // 0-15 0x36, 0x00, 0x7E, 0xFE, 0x09, 0xD2, 0x19, 0x01, 0x21, 0x46, 0x01, 0x7E, 0x17, 0xC2, 0x00, 0x01, // 16-31 0xFF, 0x5F, 0x16, 0x00, 0x21, 0x48, 0x01, 0x19, 0x19, 0x4E, 0x79, 0x23, 0x46, 0x23, 0x96, 0x57, // 32-47 0x78, 0x23, 0x9E, 0xDA, 0x3F, 0x01, 0xB2, 0xCA, 0x3F, 0x01, 0x56, 0x70, 0x2B, 0x5E, 0x71, 0x2B, // 48-63 0x72, 0x2B, 0x73, 0x21, 0x46, 0x01, 0x34, 0x21 };
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Convert.java // public static byte[] intArrayToByteArray(int[] intArray) { // // byte[] byteArray = new byte[intArray.length]; // // for (int i = 0; i < intArray.length; i++) { // byteArray[i] = intToByte(intArray[i]); // } // // return byteArray; // // } // Path: sdk/src/test/java/com/punchthrough/bean/sdk/upload/SketchHexTest.java import com.punchthrough.bean.sdk.internal.exception.HexParsingException; import com.punchthrough.bean.sdk.internal.utility.Chunk; import org.junit.Before; import org.junit.Test; import java.util.List; import static com.punchthrough.bean.sdk.internal.utility.Convert.intArrayToByteArray; import static org.assertj.core.api.Assertions.assertThat; package com.punchthrough.bean.sdk.upload; public class SketchHexTest { // From http://en.wikipedia.org/wiki/Intel_HEX final String asciiHexData = // Bytes 1-8 Bytes 9-16 // |...............|............... ":10010000214601360121470136007EFE09D2190140\r\n" + ":100110002146017E17C20001FF5F16002148011928\r\n" + ":10012000194E79234623965778239EDA3F01B2CAA7\r\n" + ":100130003F0156702B5E712B722B732146013421C7\r\n" + ":00000001FF"; // Produced from the above hex by http://hex2bin.sourceforge.net/ final int[] rawHexDataInts = new int[]{ 0x21, 0x46, 0x01, 0x36, 0x01, 0x21, 0x47, 0x01, // 0-15 0x36, 0x00, 0x7E, 0xFE, 0x09, 0xD2, 0x19, 0x01, 0x21, 0x46, 0x01, 0x7E, 0x17, 0xC2, 0x00, 0x01, // 16-31 0xFF, 0x5F, 0x16, 0x00, 0x21, 0x48, 0x01, 0x19, 0x19, 0x4E, 0x79, 0x23, 0x46, 0x23, 0x96, 0x57, // 32-47 0x78, 0x23, 0x9E, 0xDA, 0x3F, 0x01, 0xB2, 0xCA, 0x3F, 0x01, 0x56, 0x70, 0x2B, 0x5E, 0x71, 0x2B, // 48-63 0x72, 0x2B, 0x73, 0x21, 0x46, 0x01, 0x34, 0x21 };
final byte[] rawHexData = intArrayToByteArray(rawHexDataInts);
PunchThrough/bean-sdk-android
sdk/src/androidTest/java/com/punchthrough/bean/sdk/TestBeanBLE.java
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Constants.java // public class Constants { // // private static UUID smallUUID(int hexBytes) { // return UUID.fromString(String.format("%08x-0000-1000-8000-00805f9b34fb", hexBytes)); // } // // /** // * Maximum allowed length for the name of a sketch being programmed to the Bean. // */ // public static final int MAX_SKETCH_NAME_LENGTH = 20; // // /** // * The byte order used by the CC2540 // */ // public static final ByteOrder CC2540_BYTE_ORDER = ByteOrder.LITTLE_ENDIAN; // // /** // * Device Profile UUIDs // */ // public static final UUID UUID_DEVICE_INFO_SERVICE = smallUUID(0x180A); // public static final UUID UUID_DEVICE_INFO_CHAR_HARDWARE_VERSION = smallUUID(0x2A27); // public static final UUID UUID_DEVICE_INFO_CHAR_FIRMWARE_VERSION = smallUUID(0x2A26); // public static final UUID UUID_DEVICE_INFO_CHAR_SOFTWARE_VERSION = smallUUID(0x2A28); // // /** // * Battery UUIDs // */ // public static final UUID UUID_BATTERY_SERVICE = smallUUID(0x180F); // public static final UUID UUID_BATTERY_CHARACTERISTIC = smallUUID(0x2A19); // // /** // * Serial UUIDs // */ // public static final UUID UUID_SERIAL_SERVICE = UUID.fromString("a495ff10-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SERIAL_CHAR = UUID.fromString("a495ff11-c5b1-4b44-b512-1370f02d74de"); // // /** // * Scratch UUIDs // */ // public static final UUID UUID_SCRATCH_SERVICE = UUID.fromString("a495ff20-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_1 = UUID.fromString("a495ff21-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_2 = UUID.fromString("a495ff22-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_3 = UUID.fromString("a495ff23-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_4 = UUID.fromString("a495ff24-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_5 = UUID.fromString("a495ff25-c5b1-4b44-b512-1370f02d74de"); // // /** // * OAD UUIDs // */ // public static final UUID UUID_OAD_SERVICE = UUID.fromString("F000FFC0-0451-4000-B000-000000000000"); // public static final UUID UUID_OAD_CHAR_IDENTIFY = UUID.fromString("F000FFC1-0451-4000-B000-000000000000"); // public static final UUID UUID_OAD_CHAR_BLOCK = UUID.fromString("F000FFC2-0451-4000-B000-000000000000"); // // // Used for registering BLE characteristic notifications // public static final UUID UUID_CLIENT_CHAR_CONFIG = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"); // // }
import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothGattService; import android.bluetooth.BluetoothProfile; import android.os.Handler; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.Suppress; import android.util.Log; import com.punchthrough.bean.sdk.internal.utility.Constants; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit;
} } }; private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { lastKnownGattState = newState; if (newState == BluetoothProfile.STATE_CONNECTED) { gattConnectLatch.countDown(); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { Log.i(TAG, "Disconnected from GATT server."); } } @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { discoverServicesLatch.countDown(); } else { Log.w(TAG, "onServicesDiscovered received: " + status); } } @Override public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { if (status == BluetoothGatt.GATT_SUCCESS) {
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Constants.java // public class Constants { // // private static UUID smallUUID(int hexBytes) { // return UUID.fromString(String.format("%08x-0000-1000-8000-00805f9b34fb", hexBytes)); // } // // /** // * Maximum allowed length for the name of a sketch being programmed to the Bean. // */ // public static final int MAX_SKETCH_NAME_LENGTH = 20; // // /** // * The byte order used by the CC2540 // */ // public static final ByteOrder CC2540_BYTE_ORDER = ByteOrder.LITTLE_ENDIAN; // // /** // * Device Profile UUIDs // */ // public static final UUID UUID_DEVICE_INFO_SERVICE = smallUUID(0x180A); // public static final UUID UUID_DEVICE_INFO_CHAR_HARDWARE_VERSION = smallUUID(0x2A27); // public static final UUID UUID_DEVICE_INFO_CHAR_FIRMWARE_VERSION = smallUUID(0x2A26); // public static final UUID UUID_DEVICE_INFO_CHAR_SOFTWARE_VERSION = smallUUID(0x2A28); // // /** // * Battery UUIDs // */ // public static final UUID UUID_BATTERY_SERVICE = smallUUID(0x180F); // public static final UUID UUID_BATTERY_CHARACTERISTIC = smallUUID(0x2A19); // // /** // * Serial UUIDs // */ // public static final UUID UUID_SERIAL_SERVICE = UUID.fromString("a495ff10-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SERIAL_CHAR = UUID.fromString("a495ff11-c5b1-4b44-b512-1370f02d74de"); // // /** // * Scratch UUIDs // */ // public static final UUID UUID_SCRATCH_SERVICE = UUID.fromString("a495ff20-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_1 = UUID.fromString("a495ff21-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_2 = UUID.fromString("a495ff22-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_3 = UUID.fromString("a495ff23-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_4 = UUID.fromString("a495ff24-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_5 = UUID.fromString("a495ff25-c5b1-4b44-b512-1370f02d74de"); // // /** // * OAD UUIDs // */ // public static final UUID UUID_OAD_SERVICE = UUID.fromString("F000FFC0-0451-4000-B000-000000000000"); // public static final UUID UUID_OAD_CHAR_IDENTIFY = UUID.fromString("F000FFC1-0451-4000-B000-000000000000"); // public static final UUID UUID_OAD_CHAR_BLOCK = UUID.fromString("F000FFC2-0451-4000-B000-000000000000"); // // // Used for registering BLE characteristic notifications // public static final UUID UUID_CLIENT_CHAR_CONFIG = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"); // // } // Path: sdk/src/androidTest/java/com/punchthrough/bean/sdk/TestBeanBLE.java import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothGattService; import android.bluetooth.BluetoothProfile; import android.os.Handler; import android.test.AndroidTestCase; import android.test.suitebuilder.annotation.Suppress; import android.util.Log; import com.punchthrough.bean.sdk.internal.utility.Constants; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; } } }; private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { lastKnownGattState = newState; if (newState == BluetoothProfile.STATE_CONNECTED) { gattConnectLatch.countDown(); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { Log.i(TAG, "Disconnected from GATT server."); } } @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { discoverServicesLatch.countDown(); } else { Log.w(TAG, "onServicesDiscovered received: " + status); } } @Override public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { if (status == BluetoothGatt.GATT_SUCCESS) {
if (characteristic.getUuid().equals(Constants.UUID_DEVICE_INFO_CHAR_HARDWARE_VERSION)) {
PunchThrough/bean-sdk-android
sdk/src/test/java/com/punchthrough/bean/sdk/upload/FirmwareBundleTest.java
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/ImageParsingException.java // public class ImageParsingException extends Exception { // public ImageParsingException(String detailMessage) { // super(detailMessage); // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/OADException.java // public class OADException extends Exception { // public OADException(String detailMessage) { // super(detailMessage); // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Convert.java // public static byte[] intArrayToByteArray(int[] intArray) { // // byte[] byteArray = new byte[intArray.length]; // // for (int i = 0; i < intArray.length; i++) { // byteArray[i] = intToByte(intArray[i]); // } // // return byteArray; // // }
import com.punchthrough.bean.sdk.internal.exception.ImageParsingException; import com.punchthrough.bean.sdk.internal.exception.OADException; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static com.punchthrough.bean.sdk.internal.utility.Convert.intArrayToByteArray; import static junit.framework.Assert.fail; import static org.assertj.core.api.Assertions.assertThat;
package com.punchthrough.bean.sdk.upload; public class FirmwareBundleTest { byte[] rawImageData = intArrayToByteArray(new int[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }); List<FirmwareImage> images = new ArrayList<>(); FirmwareImage imageA; FirmwareImage imageB; FirmwareBundle bundle; @Before
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/ImageParsingException.java // public class ImageParsingException extends Exception { // public ImageParsingException(String detailMessage) { // super(detailMessage); // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/OADException.java // public class OADException extends Exception { // public OADException(String detailMessage) { // super(detailMessage); // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Convert.java // public static byte[] intArrayToByteArray(int[] intArray) { // // byte[] byteArray = new byte[intArray.length]; // // for (int i = 0; i < intArray.length; i++) { // byteArray[i] = intToByte(intArray[i]); // } // // return byteArray; // // } // Path: sdk/src/test/java/com/punchthrough/bean/sdk/upload/FirmwareBundleTest.java import com.punchthrough.bean.sdk.internal.exception.ImageParsingException; import com.punchthrough.bean.sdk.internal.exception.OADException; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static com.punchthrough.bean.sdk.internal.utility.Convert.intArrayToByteArray; import static junit.framework.Assert.fail; import static org.assertj.core.api.Assertions.assertThat; package com.punchthrough.bean.sdk.upload; public class FirmwareBundleTest { byte[] rawImageData = intArrayToByteArray(new int[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }); List<FirmwareImage> images = new ArrayList<>(); FirmwareImage imageA; FirmwareImage imageB; FirmwareBundle bundle; @Before
public void setUp() throws ImageParsingException {
PunchThrough/bean-sdk-android
sdk/src/test/java/com/punchthrough/bean/sdk/upload/FirmwareBundleTest.java
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/ImageParsingException.java // public class ImageParsingException extends Exception { // public ImageParsingException(String detailMessage) { // super(detailMessage); // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/OADException.java // public class OADException extends Exception { // public OADException(String detailMessage) { // super(detailMessage); // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Convert.java // public static byte[] intArrayToByteArray(int[] intArray) { // // byte[] byteArray = new byte[intArray.length]; // // for (int i = 0; i < intArray.length; i++) { // byteArray[i] = intToByte(intArray[i]); // } // // return byteArray; // // }
import com.punchthrough.bean.sdk.internal.exception.ImageParsingException; import com.punchthrough.bean.sdk.internal.exception.OADException; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static com.punchthrough.bean.sdk.internal.utility.Convert.intArrayToByteArray; import static junit.framework.Assert.fail; import static org.assertj.core.api.Assertions.assertThat;
package com.punchthrough.bean.sdk.upload; public class FirmwareBundleTest { byte[] rawImageData = intArrayToByteArray(new int[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }); List<FirmwareImage> images = new ArrayList<>(); FirmwareImage imageA; FirmwareImage imageB; FirmwareBundle bundle; @Before public void setUp() throws ImageParsingException { imageA = new FirmwareImage(rawImageData, "123450000_a_testNameA.bin"); imageB = new FirmwareImage(rawImageData, "123450000_a_testNameB.bin"); } @Test public void testFirmwareBundleVersion() throws ImageParsingException { images.add(imageA); bundle = new FirmwareBundle(images); assertThat(bundle.version()).isEqualTo(123450000); } @Test
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/ImageParsingException.java // public class ImageParsingException extends Exception { // public ImageParsingException(String detailMessage) { // super(detailMessage); // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/OADException.java // public class OADException extends Exception { // public OADException(String detailMessage) { // super(detailMessage); // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Convert.java // public static byte[] intArrayToByteArray(int[] intArray) { // // byte[] byteArray = new byte[intArray.length]; // // for (int i = 0; i < intArray.length; i++) { // byteArray[i] = intToByte(intArray[i]); // } // // return byteArray; // // } // Path: sdk/src/test/java/com/punchthrough/bean/sdk/upload/FirmwareBundleTest.java import com.punchthrough.bean.sdk.internal.exception.ImageParsingException; import com.punchthrough.bean.sdk.internal.exception.OADException; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static com.punchthrough.bean.sdk.internal.utility.Convert.intArrayToByteArray; import static junit.framework.Assert.fail; import static org.assertj.core.api.Assertions.assertThat; package com.punchthrough.bean.sdk.upload; public class FirmwareBundleTest { byte[] rawImageData = intArrayToByteArray(new int[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }); List<FirmwareImage> images = new ArrayList<>(); FirmwareImage imageA; FirmwareImage imageB; FirmwareBundle bundle; @Before public void setUp() throws ImageParsingException { imageA = new FirmwareImage(rawImageData, "123450000_a_testNameA.bin"); imageB = new FirmwareImage(rawImageData, "123450000_a_testNameB.bin"); } @Test public void testFirmwareBundleVersion() throws ImageParsingException { images.add(imageA); bundle = new FirmwareBundle(images); assertThat(bundle.version()).isEqualTo(123450000); } @Test
public void testFirmwareBundleGetNextImageOneImage() throws ImageParsingException, OADException {
PunchThrough/bean-sdk-android
sdk/src/main/java/com/punchthrough/bean/sdk/upload/FirmwareImage.java
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/ImageParsingException.java // public class ImageParsingException extends Exception { // public ImageParsingException(String detailMessage) { // super(detailMessage); // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Constants.java // public class Constants { // // private static UUID smallUUID(int hexBytes) { // return UUID.fromString(String.format("%08x-0000-1000-8000-00805f9b34fb", hexBytes)); // } // // /** // * Maximum allowed length for the name of a sketch being programmed to the Bean. // */ // public static final int MAX_SKETCH_NAME_LENGTH = 20; // // /** // * The byte order used by the CC2540 // */ // public static final ByteOrder CC2540_BYTE_ORDER = ByteOrder.LITTLE_ENDIAN; // // /** // * Device Profile UUIDs // */ // public static final UUID UUID_DEVICE_INFO_SERVICE = smallUUID(0x180A); // public static final UUID UUID_DEVICE_INFO_CHAR_HARDWARE_VERSION = smallUUID(0x2A27); // public static final UUID UUID_DEVICE_INFO_CHAR_FIRMWARE_VERSION = smallUUID(0x2A26); // public static final UUID UUID_DEVICE_INFO_CHAR_SOFTWARE_VERSION = smallUUID(0x2A28); // // /** // * Battery UUIDs // */ // public static final UUID UUID_BATTERY_SERVICE = smallUUID(0x180F); // public static final UUID UUID_BATTERY_CHARACTERISTIC = smallUUID(0x2A19); // // /** // * Serial UUIDs // */ // public static final UUID UUID_SERIAL_SERVICE = UUID.fromString("a495ff10-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SERIAL_CHAR = UUID.fromString("a495ff11-c5b1-4b44-b512-1370f02d74de"); // // /** // * Scratch UUIDs // */ // public static final UUID UUID_SCRATCH_SERVICE = UUID.fromString("a495ff20-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_1 = UUID.fromString("a495ff21-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_2 = UUID.fromString("a495ff22-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_3 = UUID.fromString("a495ff23-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_4 = UUID.fromString("a495ff24-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_5 = UUID.fromString("a495ff25-c5b1-4b44-b512-1370f02d74de"); // // /** // * OAD UUIDs // */ // public static final UUID UUID_OAD_SERVICE = UUID.fromString("F000FFC0-0451-4000-B000-000000000000"); // public static final UUID UUID_OAD_CHAR_IDENTIFY = UUID.fromString("F000FFC1-0451-4000-B000-000000000000"); // public static final UUID UUID_OAD_CHAR_BLOCK = UUID.fromString("F000FFC2-0451-4000-B000-000000000000"); // // // Used for registering BLE characteristic notifications // public static final UUID UUID_CLIENT_CHAR_CONFIG = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"); // // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Convert.java // public static byte[] intToTwoBytes(int i, ByteOrder order) { // // byte[] bytes = ByteBuffer.allocate(4).order(order).putInt(i).array(); // // if (order == ByteOrder.LITTLE_ENDIAN) { // return Arrays.copyOfRange(bytes, 0, 2); // // } else if (order == ByteOrder.BIG_ENDIAN) { // return Arrays.copyOfRange(bytes, 2, 4); // // } else { // throw new IllegalArgumentException("ByteOrder must be BIG_ENDIAN or LITTLE_ENDIAN"); // // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Convert.java // public static int twoBytesToInt(byte[] bytes, ByteOrder order) { // // if (order == ByteOrder.BIG_ENDIAN) { // return bytesToInt(bytes[0], bytes[1]); // // } else if (order == ByteOrder.LITTLE_ENDIAN) { // return bytesToInt(bytes[1], bytes[0]); // // } else { // throw new IllegalArgumentException("ByteOrder must be BIG_ENDIAN or LITTLE_ENDIAN"); // // } // }
import com.punchthrough.bean.sdk.internal.exception.ImageParsingException; import com.punchthrough.bean.sdk.internal.utility.Chunk; import com.punchthrough.bean.sdk.internal.utility.Constants; import java.nio.ByteBuffer; import java.util.Arrays; import static com.punchthrough.bean.sdk.internal.utility.Convert.intToTwoBytes; import static com.punchthrough.bean.sdk.internal.utility.Convert.twoBytesToInt;
package com.punchthrough.bean.sdk.upload; /** * Holds data for a single firmware image */ public class FirmwareImage implements Chunk.Chunkable { private static final int FW_BLOCK_SIZE = 16; private byte[] rawData; private String filename;
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/ImageParsingException.java // public class ImageParsingException extends Exception { // public ImageParsingException(String detailMessage) { // super(detailMessage); // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Constants.java // public class Constants { // // private static UUID smallUUID(int hexBytes) { // return UUID.fromString(String.format("%08x-0000-1000-8000-00805f9b34fb", hexBytes)); // } // // /** // * Maximum allowed length for the name of a sketch being programmed to the Bean. // */ // public static final int MAX_SKETCH_NAME_LENGTH = 20; // // /** // * The byte order used by the CC2540 // */ // public static final ByteOrder CC2540_BYTE_ORDER = ByteOrder.LITTLE_ENDIAN; // // /** // * Device Profile UUIDs // */ // public static final UUID UUID_DEVICE_INFO_SERVICE = smallUUID(0x180A); // public static final UUID UUID_DEVICE_INFO_CHAR_HARDWARE_VERSION = smallUUID(0x2A27); // public static final UUID UUID_DEVICE_INFO_CHAR_FIRMWARE_VERSION = smallUUID(0x2A26); // public static final UUID UUID_DEVICE_INFO_CHAR_SOFTWARE_VERSION = smallUUID(0x2A28); // // /** // * Battery UUIDs // */ // public static final UUID UUID_BATTERY_SERVICE = smallUUID(0x180F); // public static final UUID UUID_BATTERY_CHARACTERISTIC = smallUUID(0x2A19); // // /** // * Serial UUIDs // */ // public static final UUID UUID_SERIAL_SERVICE = UUID.fromString("a495ff10-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SERIAL_CHAR = UUID.fromString("a495ff11-c5b1-4b44-b512-1370f02d74de"); // // /** // * Scratch UUIDs // */ // public static final UUID UUID_SCRATCH_SERVICE = UUID.fromString("a495ff20-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_1 = UUID.fromString("a495ff21-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_2 = UUID.fromString("a495ff22-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_3 = UUID.fromString("a495ff23-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_4 = UUID.fromString("a495ff24-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_5 = UUID.fromString("a495ff25-c5b1-4b44-b512-1370f02d74de"); // // /** // * OAD UUIDs // */ // public static final UUID UUID_OAD_SERVICE = UUID.fromString("F000FFC0-0451-4000-B000-000000000000"); // public static final UUID UUID_OAD_CHAR_IDENTIFY = UUID.fromString("F000FFC1-0451-4000-B000-000000000000"); // public static final UUID UUID_OAD_CHAR_BLOCK = UUID.fromString("F000FFC2-0451-4000-B000-000000000000"); // // // Used for registering BLE characteristic notifications // public static final UUID UUID_CLIENT_CHAR_CONFIG = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"); // // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Convert.java // public static byte[] intToTwoBytes(int i, ByteOrder order) { // // byte[] bytes = ByteBuffer.allocate(4).order(order).putInt(i).array(); // // if (order == ByteOrder.LITTLE_ENDIAN) { // return Arrays.copyOfRange(bytes, 0, 2); // // } else if (order == ByteOrder.BIG_ENDIAN) { // return Arrays.copyOfRange(bytes, 2, 4); // // } else { // throw new IllegalArgumentException("ByteOrder must be BIG_ENDIAN or LITTLE_ENDIAN"); // // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Convert.java // public static int twoBytesToInt(byte[] bytes, ByteOrder order) { // // if (order == ByteOrder.BIG_ENDIAN) { // return bytesToInt(bytes[0], bytes[1]); // // } else if (order == ByteOrder.LITTLE_ENDIAN) { // return bytesToInt(bytes[1], bytes[0]); // // } else { // throw new IllegalArgumentException("ByteOrder must be BIG_ENDIAN or LITTLE_ENDIAN"); // // } // } // Path: sdk/src/main/java/com/punchthrough/bean/sdk/upload/FirmwareImage.java import com.punchthrough.bean.sdk.internal.exception.ImageParsingException; import com.punchthrough.bean.sdk.internal.utility.Chunk; import com.punchthrough.bean.sdk.internal.utility.Constants; import java.nio.ByteBuffer; import java.util.Arrays; import static com.punchthrough.bean.sdk.internal.utility.Convert.intToTwoBytes; import static com.punchthrough.bean.sdk.internal.utility.Convert.twoBytesToInt; package com.punchthrough.bean.sdk.upload; /** * Holds data for a single firmware image */ public class FirmwareImage implements Chunk.Chunkable { private static final int FW_BLOCK_SIZE = 16; private byte[] rawData; private String filename;
public FirmwareImage(byte[] rawData, String filename) throws ImageParsingException {
PunchThrough/bean-sdk-android
sdk/src/main/java/com/punchthrough/bean/sdk/upload/FirmwareImage.java
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/ImageParsingException.java // public class ImageParsingException extends Exception { // public ImageParsingException(String detailMessage) { // super(detailMessage); // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Constants.java // public class Constants { // // private static UUID smallUUID(int hexBytes) { // return UUID.fromString(String.format("%08x-0000-1000-8000-00805f9b34fb", hexBytes)); // } // // /** // * Maximum allowed length for the name of a sketch being programmed to the Bean. // */ // public static final int MAX_SKETCH_NAME_LENGTH = 20; // // /** // * The byte order used by the CC2540 // */ // public static final ByteOrder CC2540_BYTE_ORDER = ByteOrder.LITTLE_ENDIAN; // // /** // * Device Profile UUIDs // */ // public static final UUID UUID_DEVICE_INFO_SERVICE = smallUUID(0x180A); // public static final UUID UUID_DEVICE_INFO_CHAR_HARDWARE_VERSION = smallUUID(0x2A27); // public static final UUID UUID_DEVICE_INFO_CHAR_FIRMWARE_VERSION = smallUUID(0x2A26); // public static final UUID UUID_DEVICE_INFO_CHAR_SOFTWARE_VERSION = smallUUID(0x2A28); // // /** // * Battery UUIDs // */ // public static final UUID UUID_BATTERY_SERVICE = smallUUID(0x180F); // public static final UUID UUID_BATTERY_CHARACTERISTIC = smallUUID(0x2A19); // // /** // * Serial UUIDs // */ // public static final UUID UUID_SERIAL_SERVICE = UUID.fromString("a495ff10-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SERIAL_CHAR = UUID.fromString("a495ff11-c5b1-4b44-b512-1370f02d74de"); // // /** // * Scratch UUIDs // */ // public static final UUID UUID_SCRATCH_SERVICE = UUID.fromString("a495ff20-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_1 = UUID.fromString("a495ff21-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_2 = UUID.fromString("a495ff22-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_3 = UUID.fromString("a495ff23-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_4 = UUID.fromString("a495ff24-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_5 = UUID.fromString("a495ff25-c5b1-4b44-b512-1370f02d74de"); // // /** // * OAD UUIDs // */ // public static final UUID UUID_OAD_SERVICE = UUID.fromString("F000FFC0-0451-4000-B000-000000000000"); // public static final UUID UUID_OAD_CHAR_IDENTIFY = UUID.fromString("F000FFC1-0451-4000-B000-000000000000"); // public static final UUID UUID_OAD_CHAR_BLOCK = UUID.fromString("F000FFC2-0451-4000-B000-000000000000"); // // // Used for registering BLE characteristic notifications // public static final UUID UUID_CLIENT_CHAR_CONFIG = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"); // // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Convert.java // public static byte[] intToTwoBytes(int i, ByteOrder order) { // // byte[] bytes = ByteBuffer.allocate(4).order(order).putInt(i).array(); // // if (order == ByteOrder.LITTLE_ENDIAN) { // return Arrays.copyOfRange(bytes, 0, 2); // // } else if (order == ByteOrder.BIG_ENDIAN) { // return Arrays.copyOfRange(bytes, 2, 4); // // } else { // throw new IllegalArgumentException("ByteOrder must be BIG_ENDIAN or LITTLE_ENDIAN"); // // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Convert.java // public static int twoBytesToInt(byte[] bytes, ByteOrder order) { // // if (order == ByteOrder.BIG_ENDIAN) { // return bytesToInt(bytes[0], bytes[1]); // // } else if (order == ByteOrder.LITTLE_ENDIAN) { // return bytesToInt(bytes[1], bytes[0]); // // } else { // throw new IllegalArgumentException("ByteOrder must be BIG_ENDIAN or LITTLE_ENDIAN"); // // } // }
import com.punchthrough.bean.sdk.internal.exception.ImageParsingException; import com.punchthrough.bean.sdk.internal.utility.Chunk; import com.punchthrough.bean.sdk.internal.utility.Constants; import java.nio.ByteBuffer; import java.util.Arrays; import static com.punchthrough.bean.sdk.internal.utility.Convert.intToTwoBytes; import static com.punchthrough.bean.sdk.internal.utility.Convert.twoBytesToInt;
package com.punchthrough.bean.sdk.upload; /** * Holds data for a single firmware image */ public class FirmwareImage implements Chunk.Chunkable { private static final int FW_BLOCK_SIZE = 16; private byte[] rawData; private String filename; public FirmwareImage(byte[] rawData, String filename) throws ImageParsingException { if (rawData.length < 16) { throw new ImageParsingException("Images need to be at least 16 bytes long"); } this.rawData = rawData; this.filename = filename; } /** * Parse a little-endian UInt16 from the data at the given offset. * * @param offset The offset at which to parse data * @return The Java int representation of the parsed bytes */ private int uint16FromData(int offset) {
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/ImageParsingException.java // public class ImageParsingException extends Exception { // public ImageParsingException(String detailMessage) { // super(detailMessage); // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Constants.java // public class Constants { // // private static UUID smallUUID(int hexBytes) { // return UUID.fromString(String.format("%08x-0000-1000-8000-00805f9b34fb", hexBytes)); // } // // /** // * Maximum allowed length for the name of a sketch being programmed to the Bean. // */ // public static final int MAX_SKETCH_NAME_LENGTH = 20; // // /** // * The byte order used by the CC2540 // */ // public static final ByteOrder CC2540_BYTE_ORDER = ByteOrder.LITTLE_ENDIAN; // // /** // * Device Profile UUIDs // */ // public static final UUID UUID_DEVICE_INFO_SERVICE = smallUUID(0x180A); // public static final UUID UUID_DEVICE_INFO_CHAR_HARDWARE_VERSION = smallUUID(0x2A27); // public static final UUID UUID_DEVICE_INFO_CHAR_FIRMWARE_VERSION = smallUUID(0x2A26); // public static final UUID UUID_DEVICE_INFO_CHAR_SOFTWARE_VERSION = smallUUID(0x2A28); // // /** // * Battery UUIDs // */ // public static final UUID UUID_BATTERY_SERVICE = smallUUID(0x180F); // public static final UUID UUID_BATTERY_CHARACTERISTIC = smallUUID(0x2A19); // // /** // * Serial UUIDs // */ // public static final UUID UUID_SERIAL_SERVICE = UUID.fromString("a495ff10-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SERIAL_CHAR = UUID.fromString("a495ff11-c5b1-4b44-b512-1370f02d74de"); // // /** // * Scratch UUIDs // */ // public static final UUID UUID_SCRATCH_SERVICE = UUID.fromString("a495ff20-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_1 = UUID.fromString("a495ff21-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_2 = UUID.fromString("a495ff22-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_3 = UUID.fromString("a495ff23-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_4 = UUID.fromString("a495ff24-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_5 = UUID.fromString("a495ff25-c5b1-4b44-b512-1370f02d74de"); // // /** // * OAD UUIDs // */ // public static final UUID UUID_OAD_SERVICE = UUID.fromString("F000FFC0-0451-4000-B000-000000000000"); // public static final UUID UUID_OAD_CHAR_IDENTIFY = UUID.fromString("F000FFC1-0451-4000-B000-000000000000"); // public static final UUID UUID_OAD_CHAR_BLOCK = UUID.fromString("F000FFC2-0451-4000-B000-000000000000"); // // // Used for registering BLE characteristic notifications // public static final UUID UUID_CLIENT_CHAR_CONFIG = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"); // // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Convert.java // public static byte[] intToTwoBytes(int i, ByteOrder order) { // // byte[] bytes = ByteBuffer.allocate(4).order(order).putInt(i).array(); // // if (order == ByteOrder.LITTLE_ENDIAN) { // return Arrays.copyOfRange(bytes, 0, 2); // // } else if (order == ByteOrder.BIG_ENDIAN) { // return Arrays.copyOfRange(bytes, 2, 4); // // } else { // throw new IllegalArgumentException("ByteOrder must be BIG_ENDIAN or LITTLE_ENDIAN"); // // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Convert.java // public static int twoBytesToInt(byte[] bytes, ByteOrder order) { // // if (order == ByteOrder.BIG_ENDIAN) { // return bytesToInt(bytes[0], bytes[1]); // // } else if (order == ByteOrder.LITTLE_ENDIAN) { // return bytesToInt(bytes[1], bytes[0]); // // } else { // throw new IllegalArgumentException("ByteOrder must be BIG_ENDIAN or LITTLE_ENDIAN"); // // } // } // Path: sdk/src/main/java/com/punchthrough/bean/sdk/upload/FirmwareImage.java import com.punchthrough.bean.sdk.internal.exception.ImageParsingException; import com.punchthrough.bean.sdk.internal.utility.Chunk; import com.punchthrough.bean.sdk.internal.utility.Constants; import java.nio.ByteBuffer; import java.util.Arrays; import static com.punchthrough.bean.sdk.internal.utility.Convert.intToTwoBytes; import static com.punchthrough.bean.sdk.internal.utility.Convert.twoBytesToInt; package com.punchthrough.bean.sdk.upload; /** * Holds data for a single firmware image */ public class FirmwareImage implements Chunk.Chunkable { private static final int FW_BLOCK_SIZE = 16; private byte[] rawData; private String filename; public FirmwareImage(byte[] rawData, String filename) throws ImageParsingException { if (rawData.length < 16) { throw new ImageParsingException("Images need to be at least 16 bytes long"); } this.rawData = rawData; this.filename = filename; } /** * Parse a little-endian UInt16 from the data at the given offset. * * @param offset The offset at which to parse data * @return The Java int representation of the parsed bytes */ private int uint16FromData(int offset) {
return twoBytesToInt(
PunchThrough/bean-sdk-android
sdk/src/main/java/com/punchthrough/bean/sdk/upload/FirmwareImage.java
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/ImageParsingException.java // public class ImageParsingException extends Exception { // public ImageParsingException(String detailMessage) { // super(detailMessage); // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Constants.java // public class Constants { // // private static UUID smallUUID(int hexBytes) { // return UUID.fromString(String.format("%08x-0000-1000-8000-00805f9b34fb", hexBytes)); // } // // /** // * Maximum allowed length for the name of a sketch being programmed to the Bean. // */ // public static final int MAX_SKETCH_NAME_LENGTH = 20; // // /** // * The byte order used by the CC2540 // */ // public static final ByteOrder CC2540_BYTE_ORDER = ByteOrder.LITTLE_ENDIAN; // // /** // * Device Profile UUIDs // */ // public static final UUID UUID_DEVICE_INFO_SERVICE = smallUUID(0x180A); // public static final UUID UUID_DEVICE_INFO_CHAR_HARDWARE_VERSION = smallUUID(0x2A27); // public static final UUID UUID_DEVICE_INFO_CHAR_FIRMWARE_VERSION = smallUUID(0x2A26); // public static final UUID UUID_DEVICE_INFO_CHAR_SOFTWARE_VERSION = smallUUID(0x2A28); // // /** // * Battery UUIDs // */ // public static final UUID UUID_BATTERY_SERVICE = smallUUID(0x180F); // public static final UUID UUID_BATTERY_CHARACTERISTIC = smallUUID(0x2A19); // // /** // * Serial UUIDs // */ // public static final UUID UUID_SERIAL_SERVICE = UUID.fromString("a495ff10-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SERIAL_CHAR = UUID.fromString("a495ff11-c5b1-4b44-b512-1370f02d74de"); // // /** // * Scratch UUIDs // */ // public static final UUID UUID_SCRATCH_SERVICE = UUID.fromString("a495ff20-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_1 = UUID.fromString("a495ff21-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_2 = UUID.fromString("a495ff22-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_3 = UUID.fromString("a495ff23-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_4 = UUID.fromString("a495ff24-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_5 = UUID.fromString("a495ff25-c5b1-4b44-b512-1370f02d74de"); // // /** // * OAD UUIDs // */ // public static final UUID UUID_OAD_SERVICE = UUID.fromString("F000FFC0-0451-4000-B000-000000000000"); // public static final UUID UUID_OAD_CHAR_IDENTIFY = UUID.fromString("F000FFC1-0451-4000-B000-000000000000"); // public static final UUID UUID_OAD_CHAR_BLOCK = UUID.fromString("F000FFC2-0451-4000-B000-000000000000"); // // // Used for registering BLE characteristic notifications // public static final UUID UUID_CLIENT_CHAR_CONFIG = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"); // // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Convert.java // public static byte[] intToTwoBytes(int i, ByteOrder order) { // // byte[] bytes = ByteBuffer.allocate(4).order(order).putInt(i).array(); // // if (order == ByteOrder.LITTLE_ENDIAN) { // return Arrays.copyOfRange(bytes, 0, 2); // // } else if (order == ByteOrder.BIG_ENDIAN) { // return Arrays.copyOfRange(bytes, 2, 4); // // } else { // throw new IllegalArgumentException("ByteOrder must be BIG_ENDIAN or LITTLE_ENDIAN"); // // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Convert.java // public static int twoBytesToInt(byte[] bytes, ByteOrder order) { // // if (order == ByteOrder.BIG_ENDIAN) { // return bytesToInt(bytes[0], bytes[1]); // // } else if (order == ByteOrder.LITTLE_ENDIAN) { // return bytesToInt(bytes[1], bytes[0]); // // } else { // throw new IllegalArgumentException("ByteOrder must be BIG_ENDIAN or LITTLE_ENDIAN"); // // } // }
import com.punchthrough.bean.sdk.internal.exception.ImageParsingException; import com.punchthrough.bean.sdk.internal.utility.Chunk; import com.punchthrough.bean.sdk.internal.utility.Constants; import java.nio.ByteBuffer; import java.util.Arrays; import static com.punchthrough.bean.sdk.internal.utility.Convert.intToTwoBytes; import static com.punchthrough.bean.sdk.internal.utility.Convert.twoBytesToInt;
public int intVersion() { return uint16FromData(4); } /** * The length of the image, in bytes. * @return The length of the image */ public int length() { return uint16FromData(6); } /** * The user-defined unique ID for the image. Currently determines image type. * @return The image's unique ID */ public byte[] uniqueID() { return uint8_4FromData(8); } /** * The reserved bytes of the image. These are not currently used and usually return 0xFFFF. * @return The image's reserved bytes */ public byte[] reserved() { return uint8_4FromData(12); } public byte[] metadata() { ByteBuffer buffer = ByteBuffer.allocate(12);
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/ImageParsingException.java // public class ImageParsingException extends Exception { // public ImageParsingException(String detailMessage) { // super(detailMessage); // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Constants.java // public class Constants { // // private static UUID smallUUID(int hexBytes) { // return UUID.fromString(String.format("%08x-0000-1000-8000-00805f9b34fb", hexBytes)); // } // // /** // * Maximum allowed length for the name of a sketch being programmed to the Bean. // */ // public static final int MAX_SKETCH_NAME_LENGTH = 20; // // /** // * The byte order used by the CC2540 // */ // public static final ByteOrder CC2540_BYTE_ORDER = ByteOrder.LITTLE_ENDIAN; // // /** // * Device Profile UUIDs // */ // public static final UUID UUID_DEVICE_INFO_SERVICE = smallUUID(0x180A); // public static final UUID UUID_DEVICE_INFO_CHAR_HARDWARE_VERSION = smallUUID(0x2A27); // public static final UUID UUID_DEVICE_INFO_CHAR_FIRMWARE_VERSION = smallUUID(0x2A26); // public static final UUID UUID_DEVICE_INFO_CHAR_SOFTWARE_VERSION = smallUUID(0x2A28); // // /** // * Battery UUIDs // */ // public static final UUID UUID_BATTERY_SERVICE = smallUUID(0x180F); // public static final UUID UUID_BATTERY_CHARACTERISTIC = smallUUID(0x2A19); // // /** // * Serial UUIDs // */ // public static final UUID UUID_SERIAL_SERVICE = UUID.fromString("a495ff10-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SERIAL_CHAR = UUID.fromString("a495ff11-c5b1-4b44-b512-1370f02d74de"); // // /** // * Scratch UUIDs // */ // public static final UUID UUID_SCRATCH_SERVICE = UUID.fromString("a495ff20-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_1 = UUID.fromString("a495ff21-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_2 = UUID.fromString("a495ff22-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_3 = UUID.fromString("a495ff23-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_4 = UUID.fromString("a495ff24-c5b1-4b44-b512-1370f02d74de"); // public static final UUID UUID_SCRATCH_CHAR_5 = UUID.fromString("a495ff25-c5b1-4b44-b512-1370f02d74de"); // // /** // * OAD UUIDs // */ // public static final UUID UUID_OAD_SERVICE = UUID.fromString("F000FFC0-0451-4000-B000-000000000000"); // public static final UUID UUID_OAD_CHAR_IDENTIFY = UUID.fromString("F000FFC1-0451-4000-B000-000000000000"); // public static final UUID UUID_OAD_CHAR_BLOCK = UUID.fromString("F000FFC2-0451-4000-B000-000000000000"); // // // Used for registering BLE characteristic notifications // public static final UUID UUID_CLIENT_CHAR_CONFIG = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"); // // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Convert.java // public static byte[] intToTwoBytes(int i, ByteOrder order) { // // byte[] bytes = ByteBuffer.allocate(4).order(order).putInt(i).array(); // // if (order == ByteOrder.LITTLE_ENDIAN) { // return Arrays.copyOfRange(bytes, 0, 2); // // } else if (order == ByteOrder.BIG_ENDIAN) { // return Arrays.copyOfRange(bytes, 2, 4); // // } else { // throw new IllegalArgumentException("ByteOrder must be BIG_ENDIAN or LITTLE_ENDIAN"); // // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Convert.java // public static int twoBytesToInt(byte[] bytes, ByteOrder order) { // // if (order == ByteOrder.BIG_ENDIAN) { // return bytesToInt(bytes[0], bytes[1]); // // } else if (order == ByteOrder.LITTLE_ENDIAN) { // return bytesToInt(bytes[1], bytes[0]); // // } else { // throw new IllegalArgumentException("ByteOrder must be BIG_ENDIAN or LITTLE_ENDIAN"); // // } // } // Path: sdk/src/main/java/com/punchthrough/bean/sdk/upload/FirmwareImage.java import com.punchthrough.bean.sdk.internal.exception.ImageParsingException; import com.punchthrough.bean.sdk.internal.utility.Chunk; import com.punchthrough.bean.sdk.internal.utility.Constants; import java.nio.ByteBuffer; import java.util.Arrays; import static com.punchthrough.bean.sdk.internal.utility.Convert.intToTwoBytes; import static com.punchthrough.bean.sdk.internal.utility.Convert.twoBytesToInt; public int intVersion() { return uint16FromData(4); } /** * The length of the image, in bytes. * @return The length of the image */ public int length() { return uint16FromData(6); } /** * The user-defined unique ID for the image. Currently determines image type. * @return The image's unique ID */ public byte[] uniqueID() { return uint8_4FromData(8); } /** * The reserved bytes of the image. These are not currently used and usually return 0xFFFF. * @return The image's reserved bytes */ public byte[] reserved() { return uint8_4FromData(12); } public byte[] metadata() { ByteBuffer buffer = ByteBuffer.allocate(12);
buffer.put(intToTwoBytes(intVersion(), Constants.CC2540_BYTE_ORDER));
PunchThrough/bean-sdk-android
sdk/src/test/java/com/punchthrough/bean/sdk/upload/FirmwareImageTest.java
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/ImageParsingException.java // public class ImageParsingException extends Exception { // public ImageParsingException(String detailMessage) { // super(detailMessage); // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Convert.java // public static byte[] intArrayToByteArray(int[] intArray) { // // byte[] byteArray = new byte[intArray.length]; // // for (int i = 0; i < intArray.length; i++) { // byteArray[i] = intToByte(intArray[i]); // } // // return byteArray; // // }
import com.punchthrough.bean.sdk.internal.exception.ImageParsingException; import org.junit.Test; import static com.punchthrough.bean.sdk.internal.utility.Convert.intArrayToByteArray; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail;
}); byte[] rawImageData_invalid = intArrayToByteArray(new int[] { // Valid header - 16 bytes data 0x2B, 0x65, // CRC 0xFF, 0xFF, // CRC Shadow 0x64, 0x00, // Version 0x00, 0x7C, // Length 0x41, 0x41, 0x41, 0x41, // AAAA 0xFF, 0xFF, 0xFF, 0xFF, // Reserved // Valid block - 16 bytes of image data 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // Invalid block - only 10 bytes of image data 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }); @Test
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/ImageParsingException.java // public class ImageParsingException extends Exception { // public ImageParsingException(String detailMessage) { // super(detailMessage); // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/utility/Convert.java // public static byte[] intArrayToByteArray(int[] intArray) { // // byte[] byteArray = new byte[intArray.length]; // // for (int i = 0; i < intArray.length; i++) { // byteArray[i] = intToByte(intArray[i]); // } // // return byteArray; // // } // Path: sdk/src/test/java/com/punchthrough/bean/sdk/upload/FirmwareImageTest.java import com.punchthrough.bean.sdk.internal.exception.ImageParsingException; import org.junit.Test; import static com.punchthrough.bean.sdk.internal.utility.Convert.intArrayToByteArray; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; }); byte[] rawImageData_invalid = intArrayToByteArray(new int[] { // Valid header - 16 bytes data 0x2B, 0x65, // CRC 0xFF, 0xFF, // CRC Shadow 0x64, 0x00, // Version 0x00, 0x7C, // Length 0x41, 0x41, 0x41, 0x41, // AAAA 0xFF, 0xFF, 0xFF, 0xFF, // Reserved // Valid block - 16 bytes of image data 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // Invalid block - only 10 bytes of image data 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }); @Test
public void testParsingValidImage() throws ImageParsingException {
PunchThrough/bean-sdk-android
sdk/src/main/java/com/punchthrough/bean/sdk/internal/ble/SendBuffer.java
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/message/Callback.java // public interface Callback<T> { // /** // * Override this method to get results back from an asynchronous process. // * // * @param result The result passed back from the asynchronous process // */ // public void onResult(T result); // }
import android.bluetooth.BluetoothGattCharacteristic; import android.util.Log; import com.punchthrough.bean.sdk.message.Callback; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask;
package com.punchthrough.bean.sdk.internal.ble; public class SendBuffer { private static final String TAG = "SendBuffer"; public static final int SEND_INTERVAL = 5; // ms private final GattClient gattClient; private final BluetoothGattCharacteristic charc; private final List<byte[]> packets = new ArrayList<>(); private final List<Integer> ids = new ArrayList<>();
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/message/Callback.java // public interface Callback<T> { // /** // * Override this method to get results back from an asynchronous process. // * // * @param result The result passed back from the asynchronous process // */ // public void onResult(T result); // } // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/ble/SendBuffer.java import android.bluetooth.BluetoothGattCharacteristic; import android.util.Log; import com.punchthrough.bean.sdk.message.Callback; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; package com.punchthrough.bean.sdk.internal.ble; public class SendBuffer { private static final String TAG = "SendBuffer"; public static final int SEND_INTERVAL = 5; // ms private final GattClient gattClient; private final BluetoothGattCharacteristic charc; private final List<byte[]> packets = new ArrayList<>(); private final List<Integer> ids = new ArrayList<>();
private final Callback<Integer> onPacketSent;
PunchThrough/bean-sdk-android
sdk/src/test/java/com/punchthrough/bean/sdk/bootloader/StatusTest.java
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/sketch/BeanSubstate.java // public enum BeanSubstate implements EnumParse.ParsableEnum { // INIT(0x00), // WRITE_ADDRESS(0x01), // WRITE_ADDRESS_ACK(0x02), // WRITE_CHUNK(0x03), // WRITE_CHUNK_ACK(0x04), // READ_ADDRESS(0x05), // READ_ADDRESS_ACK(0x06), // READ_CHUNK(0x07), // READ_CHUNK_ACK(0x08), // VERIFY(0x09), // DONE(0x0A), // DONE_ACK(0x0B), // // START(0x0C), // START_ACK(0x0D), // HELLO(0x0E), // HELLO_ACK(0x0F), // START_RSTAGAIN(0x10), // // DONE_RESET(0x11), // PROG_MODE(0x12), // PROG_MODE_ACK(0x13), // DEVICE_SIG(0x14), // DEVICE_SIG_ACK(0x15), // WRITE_CHUNK_TWO(0x16), // ERROR(0x17); // // private final int value; // // private BeanSubstate(final int value) { // this.value = value; // } // // public int getRawValue() { // return value; // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/NoEnumFoundException.java // public class NoEnumFoundException extends Exception { // public NoEnumFoundException(String detailMessage) { // super(detailMessage); // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/message/Status.java // @AutoParcel // public abstract class Status implements Parcelable { // /* AppMessages.h -> BL_MSG_STATUS_T: // * { // * PTD_UINT8 hlState; // BL_HL_STATE_T // * PTD_UINT8 intState; // BL_STATE_T // * PTD_UINT16 blocksSent; // * PTD_UINT16 bytesSent; // * } // */ // // public abstract BeanState beanState(); // // public abstract BeanSubstate beanSubstate(); // // public abstract int blocksSent(); // // public abstract int bytesSent(); // // public static Status create(BeanState beanState, BeanSubstate beanSubstate, int blocksSent, int bytesSent) { // return new AutoParcel_Status(beanState, beanSubstate, blocksSent, bytesSent); // } // // public static Status fromPayload(Buffer buffer) throws NoEnumFoundException { // BeanState beanState = EnumParse.enumWithRawValue(BeanState.class, buffer.readByte()); // BeanSubstate beanSubstate = EnumParse.enumWithRawValue(BeanSubstate.class, buffer.readByte()); // int blocksSent = bytesToInt(buffer.readByte(), buffer.readByte()); // int bytesSent = bytesToInt(buffer.readByte(), buffer.readByte()); // return Status.create(beanState, beanSubstate, blocksSent, bytesSent); // } // // }
import com.punchthrough.bean.sdk.internal.upload.sketch.BeanState; import com.punchthrough.bean.sdk.internal.upload.sketch.BeanSubstate; import com.punchthrough.bean.sdk.internal.exception.NoEnumFoundException; import com.punchthrough.bean.sdk.message.Status; import org.junit.Test; import okio.Buffer; import static org.assertj.core.api.Assertions.assertThat;
package com.punchthrough.bean.sdk.bootloader; public class StatusTest { @Test
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/sketch/BeanSubstate.java // public enum BeanSubstate implements EnumParse.ParsableEnum { // INIT(0x00), // WRITE_ADDRESS(0x01), // WRITE_ADDRESS_ACK(0x02), // WRITE_CHUNK(0x03), // WRITE_CHUNK_ACK(0x04), // READ_ADDRESS(0x05), // READ_ADDRESS_ACK(0x06), // READ_CHUNK(0x07), // READ_CHUNK_ACK(0x08), // VERIFY(0x09), // DONE(0x0A), // DONE_ACK(0x0B), // // START(0x0C), // START_ACK(0x0D), // HELLO(0x0E), // HELLO_ACK(0x0F), // START_RSTAGAIN(0x10), // // DONE_RESET(0x11), // PROG_MODE(0x12), // PROG_MODE_ACK(0x13), // DEVICE_SIG(0x14), // DEVICE_SIG_ACK(0x15), // WRITE_CHUNK_TWO(0x16), // ERROR(0x17); // // private final int value; // // private BeanSubstate(final int value) { // this.value = value; // } // // public int getRawValue() { // return value; // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/NoEnumFoundException.java // public class NoEnumFoundException extends Exception { // public NoEnumFoundException(String detailMessage) { // super(detailMessage); // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/message/Status.java // @AutoParcel // public abstract class Status implements Parcelable { // /* AppMessages.h -> BL_MSG_STATUS_T: // * { // * PTD_UINT8 hlState; // BL_HL_STATE_T // * PTD_UINT8 intState; // BL_STATE_T // * PTD_UINT16 blocksSent; // * PTD_UINT16 bytesSent; // * } // */ // // public abstract BeanState beanState(); // // public abstract BeanSubstate beanSubstate(); // // public abstract int blocksSent(); // // public abstract int bytesSent(); // // public static Status create(BeanState beanState, BeanSubstate beanSubstate, int blocksSent, int bytesSent) { // return new AutoParcel_Status(beanState, beanSubstate, blocksSent, bytesSent); // } // // public static Status fromPayload(Buffer buffer) throws NoEnumFoundException { // BeanState beanState = EnumParse.enumWithRawValue(BeanState.class, buffer.readByte()); // BeanSubstate beanSubstate = EnumParse.enumWithRawValue(BeanSubstate.class, buffer.readByte()); // int blocksSent = bytesToInt(buffer.readByte(), buffer.readByte()); // int bytesSent = bytesToInt(buffer.readByte(), buffer.readByte()); // return Status.create(beanState, beanSubstate, blocksSent, bytesSent); // } // // } // Path: sdk/src/test/java/com/punchthrough/bean/sdk/bootloader/StatusTest.java import com.punchthrough.bean.sdk.internal.upload.sketch.BeanState; import com.punchthrough.bean.sdk.internal.upload.sketch.BeanSubstate; import com.punchthrough.bean.sdk.internal.exception.NoEnumFoundException; import com.punchthrough.bean.sdk.message.Status; import org.junit.Test; import okio.Buffer; import static org.assertj.core.api.Assertions.assertThat; package com.punchthrough.bean.sdk.bootloader; public class StatusTest { @Test
public void testStatusFromPayload() throws NoEnumFoundException {
PunchThrough/bean-sdk-android
sdk/src/test/java/com/punchthrough/bean/sdk/bootloader/StatusTest.java
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/sketch/BeanSubstate.java // public enum BeanSubstate implements EnumParse.ParsableEnum { // INIT(0x00), // WRITE_ADDRESS(0x01), // WRITE_ADDRESS_ACK(0x02), // WRITE_CHUNK(0x03), // WRITE_CHUNK_ACK(0x04), // READ_ADDRESS(0x05), // READ_ADDRESS_ACK(0x06), // READ_CHUNK(0x07), // READ_CHUNK_ACK(0x08), // VERIFY(0x09), // DONE(0x0A), // DONE_ACK(0x0B), // // START(0x0C), // START_ACK(0x0D), // HELLO(0x0E), // HELLO_ACK(0x0F), // START_RSTAGAIN(0x10), // // DONE_RESET(0x11), // PROG_MODE(0x12), // PROG_MODE_ACK(0x13), // DEVICE_SIG(0x14), // DEVICE_SIG_ACK(0x15), // WRITE_CHUNK_TWO(0x16), // ERROR(0x17); // // private final int value; // // private BeanSubstate(final int value) { // this.value = value; // } // // public int getRawValue() { // return value; // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/NoEnumFoundException.java // public class NoEnumFoundException extends Exception { // public NoEnumFoundException(String detailMessage) { // super(detailMessage); // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/message/Status.java // @AutoParcel // public abstract class Status implements Parcelable { // /* AppMessages.h -> BL_MSG_STATUS_T: // * { // * PTD_UINT8 hlState; // BL_HL_STATE_T // * PTD_UINT8 intState; // BL_STATE_T // * PTD_UINT16 blocksSent; // * PTD_UINT16 bytesSent; // * } // */ // // public abstract BeanState beanState(); // // public abstract BeanSubstate beanSubstate(); // // public abstract int blocksSent(); // // public abstract int bytesSent(); // // public static Status create(BeanState beanState, BeanSubstate beanSubstate, int blocksSent, int bytesSent) { // return new AutoParcel_Status(beanState, beanSubstate, blocksSent, bytesSent); // } // // public static Status fromPayload(Buffer buffer) throws NoEnumFoundException { // BeanState beanState = EnumParse.enumWithRawValue(BeanState.class, buffer.readByte()); // BeanSubstate beanSubstate = EnumParse.enumWithRawValue(BeanSubstate.class, buffer.readByte()); // int blocksSent = bytesToInt(buffer.readByte(), buffer.readByte()); // int bytesSent = bytesToInt(buffer.readByte(), buffer.readByte()); // return Status.create(beanState, beanSubstate, blocksSent, bytesSent); // } // // }
import com.punchthrough.bean.sdk.internal.upload.sketch.BeanState; import com.punchthrough.bean.sdk.internal.upload.sketch.BeanSubstate; import com.punchthrough.bean.sdk.internal.exception.NoEnumFoundException; import com.punchthrough.bean.sdk.message.Status; import org.junit.Test; import okio.Buffer; import static org.assertj.core.api.Assertions.assertThat;
package com.punchthrough.bean.sdk.bootloader; public class StatusTest { @Test public void testStatusFromPayload() throws NoEnumFoundException { Buffer buffer = new Buffer(); buffer.writeByte(0x04); // State: VERIFY buffer.writeByte(0x0E); // Substate: HELLO buffer.writeByte(0x12); // Blocks sent: 4616 buffer.writeByte(0x08); buffer.writeByte(0x34); // Bytes sent: 13393 buffer.writeByte(0x51);
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/sketch/BeanSubstate.java // public enum BeanSubstate implements EnumParse.ParsableEnum { // INIT(0x00), // WRITE_ADDRESS(0x01), // WRITE_ADDRESS_ACK(0x02), // WRITE_CHUNK(0x03), // WRITE_CHUNK_ACK(0x04), // READ_ADDRESS(0x05), // READ_ADDRESS_ACK(0x06), // READ_CHUNK(0x07), // READ_CHUNK_ACK(0x08), // VERIFY(0x09), // DONE(0x0A), // DONE_ACK(0x0B), // // START(0x0C), // START_ACK(0x0D), // HELLO(0x0E), // HELLO_ACK(0x0F), // START_RSTAGAIN(0x10), // // DONE_RESET(0x11), // PROG_MODE(0x12), // PROG_MODE_ACK(0x13), // DEVICE_SIG(0x14), // DEVICE_SIG_ACK(0x15), // WRITE_CHUNK_TWO(0x16), // ERROR(0x17); // // private final int value; // // private BeanSubstate(final int value) { // this.value = value; // } // // public int getRawValue() { // return value; // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/NoEnumFoundException.java // public class NoEnumFoundException extends Exception { // public NoEnumFoundException(String detailMessage) { // super(detailMessage); // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/message/Status.java // @AutoParcel // public abstract class Status implements Parcelable { // /* AppMessages.h -> BL_MSG_STATUS_T: // * { // * PTD_UINT8 hlState; // BL_HL_STATE_T // * PTD_UINT8 intState; // BL_STATE_T // * PTD_UINT16 blocksSent; // * PTD_UINT16 bytesSent; // * } // */ // // public abstract BeanState beanState(); // // public abstract BeanSubstate beanSubstate(); // // public abstract int blocksSent(); // // public abstract int bytesSent(); // // public static Status create(BeanState beanState, BeanSubstate beanSubstate, int blocksSent, int bytesSent) { // return new AutoParcel_Status(beanState, beanSubstate, blocksSent, bytesSent); // } // // public static Status fromPayload(Buffer buffer) throws NoEnumFoundException { // BeanState beanState = EnumParse.enumWithRawValue(BeanState.class, buffer.readByte()); // BeanSubstate beanSubstate = EnumParse.enumWithRawValue(BeanSubstate.class, buffer.readByte()); // int blocksSent = bytesToInt(buffer.readByte(), buffer.readByte()); // int bytesSent = bytesToInt(buffer.readByte(), buffer.readByte()); // return Status.create(beanState, beanSubstate, blocksSent, bytesSent); // } // // } // Path: sdk/src/test/java/com/punchthrough/bean/sdk/bootloader/StatusTest.java import com.punchthrough.bean.sdk.internal.upload.sketch.BeanState; import com.punchthrough.bean.sdk.internal.upload.sketch.BeanSubstate; import com.punchthrough.bean.sdk.internal.exception.NoEnumFoundException; import com.punchthrough.bean.sdk.message.Status; import org.junit.Test; import okio.Buffer; import static org.assertj.core.api.Assertions.assertThat; package com.punchthrough.bean.sdk.bootloader; public class StatusTest { @Test public void testStatusFromPayload() throws NoEnumFoundException { Buffer buffer = new Buffer(); buffer.writeByte(0x04); // State: VERIFY buffer.writeByte(0x0E); // Substate: HELLO buffer.writeByte(0x12); // Blocks sent: 4616 buffer.writeByte(0x08); buffer.writeByte(0x34); // Bytes sent: 13393 buffer.writeByte(0x51);
Status status = Status.fromPayload(buffer);
PunchThrough/bean-sdk-android
sdk/src/test/java/com/punchthrough/bean/sdk/bootloader/StatusTest.java
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/sketch/BeanSubstate.java // public enum BeanSubstate implements EnumParse.ParsableEnum { // INIT(0x00), // WRITE_ADDRESS(0x01), // WRITE_ADDRESS_ACK(0x02), // WRITE_CHUNK(0x03), // WRITE_CHUNK_ACK(0x04), // READ_ADDRESS(0x05), // READ_ADDRESS_ACK(0x06), // READ_CHUNK(0x07), // READ_CHUNK_ACK(0x08), // VERIFY(0x09), // DONE(0x0A), // DONE_ACK(0x0B), // // START(0x0C), // START_ACK(0x0D), // HELLO(0x0E), // HELLO_ACK(0x0F), // START_RSTAGAIN(0x10), // // DONE_RESET(0x11), // PROG_MODE(0x12), // PROG_MODE_ACK(0x13), // DEVICE_SIG(0x14), // DEVICE_SIG_ACK(0x15), // WRITE_CHUNK_TWO(0x16), // ERROR(0x17); // // private final int value; // // private BeanSubstate(final int value) { // this.value = value; // } // // public int getRawValue() { // return value; // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/NoEnumFoundException.java // public class NoEnumFoundException extends Exception { // public NoEnumFoundException(String detailMessage) { // super(detailMessage); // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/message/Status.java // @AutoParcel // public abstract class Status implements Parcelable { // /* AppMessages.h -> BL_MSG_STATUS_T: // * { // * PTD_UINT8 hlState; // BL_HL_STATE_T // * PTD_UINT8 intState; // BL_STATE_T // * PTD_UINT16 blocksSent; // * PTD_UINT16 bytesSent; // * } // */ // // public abstract BeanState beanState(); // // public abstract BeanSubstate beanSubstate(); // // public abstract int blocksSent(); // // public abstract int bytesSent(); // // public static Status create(BeanState beanState, BeanSubstate beanSubstate, int blocksSent, int bytesSent) { // return new AutoParcel_Status(beanState, beanSubstate, blocksSent, bytesSent); // } // // public static Status fromPayload(Buffer buffer) throws NoEnumFoundException { // BeanState beanState = EnumParse.enumWithRawValue(BeanState.class, buffer.readByte()); // BeanSubstate beanSubstate = EnumParse.enumWithRawValue(BeanSubstate.class, buffer.readByte()); // int blocksSent = bytesToInt(buffer.readByte(), buffer.readByte()); // int bytesSent = bytesToInt(buffer.readByte(), buffer.readByte()); // return Status.create(beanState, beanSubstate, blocksSent, bytesSent); // } // // }
import com.punchthrough.bean.sdk.internal.upload.sketch.BeanState; import com.punchthrough.bean.sdk.internal.upload.sketch.BeanSubstate; import com.punchthrough.bean.sdk.internal.exception.NoEnumFoundException; import com.punchthrough.bean.sdk.message.Status; import org.junit.Test; import okio.Buffer; import static org.assertj.core.api.Assertions.assertThat;
package com.punchthrough.bean.sdk.bootloader; public class StatusTest { @Test public void testStatusFromPayload() throws NoEnumFoundException { Buffer buffer = new Buffer(); buffer.writeByte(0x04); // State: VERIFY buffer.writeByte(0x0E); // Substate: HELLO buffer.writeByte(0x12); // Blocks sent: 4616 buffer.writeByte(0x08); buffer.writeByte(0x34); // Bytes sent: 13393 buffer.writeByte(0x51); Status status = Status.fromPayload(buffer); assertThat(status.beanState()).isEqualTo(BeanState.VERIFY);
// Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/upload/sketch/BeanSubstate.java // public enum BeanSubstate implements EnumParse.ParsableEnum { // INIT(0x00), // WRITE_ADDRESS(0x01), // WRITE_ADDRESS_ACK(0x02), // WRITE_CHUNK(0x03), // WRITE_CHUNK_ACK(0x04), // READ_ADDRESS(0x05), // READ_ADDRESS_ACK(0x06), // READ_CHUNK(0x07), // READ_CHUNK_ACK(0x08), // VERIFY(0x09), // DONE(0x0A), // DONE_ACK(0x0B), // // START(0x0C), // START_ACK(0x0D), // HELLO(0x0E), // HELLO_ACK(0x0F), // START_RSTAGAIN(0x10), // // DONE_RESET(0x11), // PROG_MODE(0x12), // PROG_MODE_ACK(0x13), // DEVICE_SIG(0x14), // DEVICE_SIG_ACK(0x15), // WRITE_CHUNK_TWO(0x16), // ERROR(0x17); // // private final int value; // // private BeanSubstate(final int value) { // this.value = value; // } // // public int getRawValue() { // return value; // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/internal/exception/NoEnumFoundException.java // public class NoEnumFoundException extends Exception { // public NoEnumFoundException(String detailMessage) { // super(detailMessage); // } // } // // Path: sdk/src/main/java/com/punchthrough/bean/sdk/message/Status.java // @AutoParcel // public abstract class Status implements Parcelable { // /* AppMessages.h -> BL_MSG_STATUS_T: // * { // * PTD_UINT8 hlState; // BL_HL_STATE_T // * PTD_UINT8 intState; // BL_STATE_T // * PTD_UINT16 blocksSent; // * PTD_UINT16 bytesSent; // * } // */ // // public abstract BeanState beanState(); // // public abstract BeanSubstate beanSubstate(); // // public abstract int blocksSent(); // // public abstract int bytesSent(); // // public static Status create(BeanState beanState, BeanSubstate beanSubstate, int blocksSent, int bytesSent) { // return new AutoParcel_Status(beanState, beanSubstate, blocksSent, bytesSent); // } // // public static Status fromPayload(Buffer buffer) throws NoEnumFoundException { // BeanState beanState = EnumParse.enumWithRawValue(BeanState.class, buffer.readByte()); // BeanSubstate beanSubstate = EnumParse.enumWithRawValue(BeanSubstate.class, buffer.readByte()); // int blocksSent = bytesToInt(buffer.readByte(), buffer.readByte()); // int bytesSent = bytesToInt(buffer.readByte(), buffer.readByte()); // return Status.create(beanState, beanSubstate, blocksSent, bytesSent); // } // // } // Path: sdk/src/test/java/com/punchthrough/bean/sdk/bootloader/StatusTest.java import com.punchthrough.bean.sdk.internal.upload.sketch.BeanState; import com.punchthrough.bean.sdk.internal.upload.sketch.BeanSubstate; import com.punchthrough.bean.sdk.internal.exception.NoEnumFoundException; import com.punchthrough.bean.sdk.message.Status; import org.junit.Test; import okio.Buffer; import static org.assertj.core.api.Assertions.assertThat; package com.punchthrough.bean.sdk.bootloader; public class StatusTest { @Test public void testStatusFromPayload() throws NoEnumFoundException { Buffer buffer = new Buffer(); buffer.writeByte(0x04); // State: VERIFY buffer.writeByte(0x0E); // Substate: HELLO buffer.writeByte(0x12); // Blocks sent: 4616 buffer.writeByte(0x08); buffer.writeByte(0x34); // Bytes sent: 13393 buffer.writeByte(0x51); Status status = Status.fromPayload(buffer); assertThat(status.beanState()).isEqualTo(BeanState.VERIFY);
assertThat(status.beanSubstate()).isEqualTo(BeanSubstate.HELLO);
jasonbaldridge/maul
src/main/java/edu/berkeley/nlp/lm/StringWordIndexer.java
// Path: src/main/java/edu/berkeley/nlp/lm/collections/Indexer.java // public class Indexer<E extends Comparable<E>> implements Serializable // { // private static final long serialVersionUID = -8769544079136550516L; // // protected ArrayList<E> objects; // // protected TIntMap<E> indexes; // // protected boolean locked = false; // // private Semaphore sem; // // public void lock() { // this.locked = true; // } // // public E getObject(final int index) { // return objects.get(index); // } // // public boolean add(final E elem) { // final int oldSize = size(); // return getIndex(elem) >= oldSize; // } // // /** // * Returns the number of objects indexed. // */ // public int size() { // return objects.size(); // } // // /** // * Returns the index of the given object, or -1 if the object is not present // * in the indexer. // * // * @param o // * @return // */ // public int indexOf(final E o) { // final int index = indexes.get(o, -1); // // return index; // } // // /** // * Return the index of the element If doesn't exist, add it. // */ // public int getIndex(final E e) { // if (e == null) return -1; // // if (sem != null) sem.acquireUninterruptibly(); // int index = indexes.get(e, -1); // if (index < 0) { // if (locked) throw new RuntimeException("Attempt to add to locked indexer"); // index = size(); // objects.add(e); // assert size() >= 0 : "Too many objects in indexer"; // indexes.put(e, index); // } // if (sem != null) sem.release(); // return index; // } // // public Indexer(final boolean sync) { // objects = new ArrayList<E>(); // indexes = new TIntMap<E>(); // this.sem = sync ? new Semaphore(1) : null; // } // // public Indexer() { // this(false); // } // // public Indexer(final Collection<? extends E> c) { // this(); // for (final E a : c) // getIndex(a); // } // // /** // * Save some space my compacting underlying maps and lists. // */ // public void trim() { // objects.trimToSize(); // // indexes.switchToSortedList(); // } // // public Iterable<E> getObjects() { // return Collections.unmodifiableList(objects); // } // // }
import edu.berkeley.nlp.lm.collections.Indexer;
package edu.berkeley.nlp.lm; /** * Implementation of a WordIndexer in which words are represented as strings. * * @author adampauls * */ public class StringWordIndexer implements WordIndexer<String> { /** * */ private static final long serialVersionUID = 1L;
// Path: src/main/java/edu/berkeley/nlp/lm/collections/Indexer.java // public class Indexer<E extends Comparable<E>> implements Serializable // { // private static final long serialVersionUID = -8769544079136550516L; // // protected ArrayList<E> objects; // // protected TIntMap<E> indexes; // // protected boolean locked = false; // // private Semaphore sem; // // public void lock() { // this.locked = true; // } // // public E getObject(final int index) { // return objects.get(index); // } // // public boolean add(final E elem) { // final int oldSize = size(); // return getIndex(elem) >= oldSize; // } // // /** // * Returns the number of objects indexed. // */ // public int size() { // return objects.size(); // } // // /** // * Returns the index of the given object, or -1 if the object is not present // * in the indexer. // * // * @param o // * @return // */ // public int indexOf(final E o) { // final int index = indexes.get(o, -1); // // return index; // } // // /** // * Return the index of the element If doesn't exist, add it. // */ // public int getIndex(final E e) { // if (e == null) return -1; // // if (sem != null) sem.acquireUninterruptibly(); // int index = indexes.get(e, -1); // if (index < 0) { // if (locked) throw new RuntimeException("Attempt to add to locked indexer"); // index = size(); // objects.add(e); // assert size() >= 0 : "Too many objects in indexer"; // indexes.put(e, index); // } // if (sem != null) sem.release(); // return index; // } // // public Indexer(final boolean sync) { // objects = new ArrayList<E>(); // indexes = new TIntMap<E>(); // this.sem = sync ? new Semaphore(1) : null; // } // // public Indexer() { // this(false); // } // // public Indexer(final Collection<? extends E> c) { // this(); // for (final E a : c) // getIndex(a); // } // // /** // * Save some space my compacting underlying maps and lists. // */ // public void trim() { // objects.trimToSize(); // // indexes.switchToSortedList(); // } // // public Iterable<E> getObjects() { // return Collections.unmodifiableList(objects); // } // // } // Path: src/main/java/edu/berkeley/nlp/lm/StringWordIndexer.java import edu.berkeley.nlp.lm.collections.Indexer; package edu.berkeley.nlp.lm; /** * Implementation of a WordIndexer in which words are represented as strings. * * @author adampauls * */ public class StringWordIndexer implements WordIndexer<String> { /** * */ private static final long serialVersionUID = 1L;
private final Indexer<String> sparseIndexer;
jasonbaldridge/maul
src/main/java/edu/berkeley/nlp/lm/io/IOUtils.java
// Path: src/main/java/edu/berkeley/nlp/lm/util/StrUtils.java // public class StrUtils // { // // public static <T> String join(final List<T> objs) { // return join(objs, " "); // } // // public static <T> String join(final List<T> objs, final String delim) { // if (objs == null) return ""; // return join(objs, delim, 0, objs.size()); // } // // public static <T> String join(final List<T> objs, final String delim, final int start, final int end) { // if (objs == null) return ""; // final StringBuilder sb = new StringBuilder(); // boolean first = true; // for (int i = start; i < end; i++) { // if (!first) sb.append(delim); // sb.append(objs.get(i)); // first = false; // } // return sb.toString(); // } // // public static boolean isEmpty(final String s) { // return s == null || s.equals(""); // } // // }
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.nio.channels.Channels; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import edu.berkeley.nlp.lm.util.StrUtils;
package edu.berkeley.nlp.lm.io; /** * Some IO utility functions. Naming convention: "Hard" means that the function * throws a RuntimeException upon failure, "Easy" means it returns null. * * @author adampauls * @author Percy Liang * */ public class IOUtils { public static BufferedReader openIn(final String path) throws IOException { return openIn(new File(path)); } public static BufferedReader openIn(final File path) throws IOException { InputStream is = getBufferedInputStream(path); if (path.getName().endsWith(".gz")) is = new GZIPInputStream(is); return new BufferedReader(getReader(is)); } public static BufferedReader openInHard(final String path) { return openInHard(new File(path)); } public static BufferedReader openInHard(final File path) { try { return openIn(path); } catch (final Exception e) { throw new RuntimeException(e); } } public static PrintWriter openOut(final String path) throws IOException { return openOut(new File(path)); } public static PrintWriter openOut(final File path) throws IOException { OutputStream os = new FileOutputStream(path); if (path.getName().endsWith(".gz")) os = new GZIPOutputStream(os); return new PrintWriter(getWriter(os)); } public static PrintWriter openOutEasy(final String path) {
// Path: src/main/java/edu/berkeley/nlp/lm/util/StrUtils.java // public class StrUtils // { // // public static <T> String join(final List<T> objs) { // return join(objs, " "); // } // // public static <T> String join(final List<T> objs, final String delim) { // if (objs == null) return ""; // return join(objs, delim, 0, objs.size()); // } // // public static <T> String join(final List<T> objs, final String delim, final int start, final int end) { // if (objs == null) return ""; // final StringBuilder sb = new StringBuilder(); // boolean first = true; // for (int i = start; i < end; i++) { // if (!first) sb.append(delim); // sb.append(objs.get(i)); // first = false; // } // return sb.toString(); // } // // public static boolean isEmpty(final String s) { // return s == null || s.equals(""); // } // // } // Path: src/main/java/edu/berkeley/nlp/lm/io/IOUtils.java import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.nio.channels.Channels; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import edu.berkeley.nlp.lm.util.StrUtils; package edu.berkeley.nlp.lm.io; /** * Some IO utility functions. Naming convention: "Hard" means that the function * throws a RuntimeException upon failure, "Easy" means it returns null. * * @author adampauls * @author Percy Liang * */ public class IOUtils { public static BufferedReader openIn(final String path) throws IOException { return openIn(new File(path)); } public static BufferedReader openIn(final File path) throws IOException { InputStream is = getBufferedInputStream(path); if (path.getName().endsWith(".gz")) is = new GZIPInputStream(is); return new BufferedReader(getReader(is)); } public static BufferedReader openInHard(final String path) { return openInHard(new File(path)); } public static BufferedReader openInHard(final File path) { try { return openIn(path); } catch (final Exception e) { throw new RuntimeException(e); } } public static PrintWriter openOut(final String path) throws IOException { return openOut(new File(path)); } public static PrintWriter openOut(final File path) throws IOException { OutputStream os = new FileOutputStream(path); if (path.getName().endsWith(".gz")) os = new GZIPOutputStream(os); return new PrintWriter(getWriter(os)); } public static PrintWriter openOutEasy(final String path) {
if (StrUtils.isEmpty(path)) return null;
jasonbaldridge/maul
src/main/java/edu/berkeley/nlp/lm/io/NgramMapAddingCallback.java
// Path: src/main/java/edu/berkeley/nlp/lm/map/NgramMap.java // public interface NgramMap<V> // { // // public long put(int[] ngram, int startPos, int endPos, V val); // // public void handleNgramsFinished(int justFinishedOrder); // // public void trim(); // // public void initWithLengths(List<Long> numNGrams); // // public ValueContainer<V> getValues(); // // public long getValueAndOffset(final long contextOffset, final int contextOrder, int word, @OutputParameter V currProbVal); // // public int getMaxNgramOrder(); // // public long getNumNgrams(int ngramOrder); // // public Iterable<Entry<V>> getNgramsForOrder(final int ngramOrder); // // public CustomWidthArray getValueStoringArray(final int ngramOrder); // // public static class Entry<T> // { // /** // * @param key // * @param value // */ // public Entry(final int[] key, final T value) { // super(); // this.key = key; // this.value = value; // } // // public int[] key; // // public T value; // // } // // public boolean contains(int[] ngram, int startPos, int endPos); // // public V get(int[] ngram, int startPos, int endPos); // // public void clearStorage(); // // }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import edu.berkeley.nlp.lm.map.NgramMap;
package edu.berkeley.nlp.lm.io; /** * Reader callback which adds n-grams to an NgramMap * * @author adampauls * * @param <V> * Value type */ public final class NgramMapAddingCallback<V> implements ArpaLmReaderCallback<V> {
// Path: src/main/java/edu/berkeley/nlp/lm/map/NgramMap.java // public interface NgramMap<V> // { // // public long put(int[] ngram, int startPos, int endPos, V val); // // public void handleNgramsFinished(int justFinishedOrder); // // public void trim(); // // public void initWithLengths(List<Long> numNGrams); // // public ValueContainer<V> getValues(); // // public long getValueAndOffset(final long contextOffset, final int contextOrder, int word, @OutputParameter V currProbVal); // // public int getMaxNgramOrder(); // // public long getNumNgrams(int ngramOrder); // // public Iterable<Entry<V>> getNgramsForOrder(final int ngramOrder); // // public CustomWidthArray getValueStoringArray(final int ngramOrder); // // public static class Entry<T> // { // /** // * @param key // * @param value // */ // public Entry(final int[] key, final T value) { // super(); // this.key = key; // this.value = value; // } // // public int[] key; // // public T value; // // } // // public boolean contains(int[] ngram, int startPos, int endPos); // // public V get(int[] ngram, int startPos, int endPos); // // public void clearStorage(); // // } // Path: src/main/java/edu/berkeley/nlp/lm/io/NgramMapAddingCallback.java import java.util.ArrayList; import java.util.Arrays; import java.util.List; import edu.berkeley.nlp.lm.map.NgramMap; package edu.berkeley.nlp.lm.io; /** * Reader callback which adds n-grams to an NgramMap * * @author adampauls * * @param <V> * Value type */ public final class NgramMapAddingCallback<V> implements ArpaLmReaderCallback<V> {
private final NgramMap<V> map;
jasonbaldridge/maul
src/main/java/edu/berkeley/nlp/lm/cache/ContextEncodedDirectMappedLmCache.java
// Path: src/main/java/edu/berkeley/nlp/lm/ContextEncodedNgramLanguageModel.java // public static class LmContextInfo // { // // /** // * Offset of context (prefix) of an n-gram // */ // public long offset = -1L; // // /** // * The (0-based) length of <code>context</code> (i.e. // * <code>order == 0</code> iff <code>context</code> refers to a // * unigram). // * // * Use -1 for an empty context. // */ // public int order = -1; // // }
import java.util.Arrays; import java.util.concurrent.atomic.AtomicIntegerArray; import edu.berkeley.nlp.lm.ContextEncodedNgramLanguageModel.LmContextInfo; import edu.berkeley.nlp.lm.util.Annotations.OutputParameter;
public ContextEncodedDirectMappedLmCache(final int cacheBits, final boolean threadSafe) { cacheSize = (1 << cacheBits) - 1; this.threadSafe = threadSafe; if (threadSafe) { threadUnsafeArray = null; threadSafeArray = new ThreadLocal<long[]>() { @Override protected long[] initialValue() { return allocCache(); } }; } else { threadSafeArray = null; threadUnsafeArray = allocCache(); } } /** * @return */ private long[] allocCache() { final long[] array = new long[STRUCT_LENGTH * cacheSize]; Arrays.fill(array, -1); return array; } @Override
// Path: src/main/java/edu/berkeley/nlp/lm/ContextEncodedNgramLanguageModel.java // public static class LmContextInfo // { // // /** // * Offset of context (prefix) of an n-gram // */ // public long offset = -1L; // // /** // * The (0-based) length of <code>context</code> (i.e. // * <code>order == 0</code> iff <code>context</code> refers to a // * unigram). // * // * Use -1 for an empty context. // */ // public int order = -1; // // } // Path: src/main/java/edu/berkeley/nlp/lm/cache/ContextEncodedDirectMappedLmCache.java import java.util.Arrays; import java.util.concurrent.atomic.AtomicIntegerArray; import edu.berkeley.nlp.lm.ContextEncodedNgramLanguageModel.LmContextInfo; import edu.berkeley.nlp.lm.util.Annotations.OutputParameter; public ContextEncodedDirectMappedLmCache(final int cacheBits, final boolean threadSafe) { cacheSize = (1 << cacheBits) - 1; this.threadSafe = threadSafe; if (threadSafe) { threadUnsafeArray = null; threadSafeArray = new ThreadLocal<long[]>() { @Override protected long[] initialValue() { return allocCache(); } }; } else { threadSafeArray = null; threadUnsafeArray = allocCache(); } } /** * @return */ private long[] allocCache() { final long[] array = new long[STRUCT_LENGTH * cacheSize]; Arrays.fill(array, -1); return array; } @Override
public float getCached(final long contextOffset, final int contextOrder, final int word, final int hash, @OutputParameter final LmContextInfo outputPrefix) {
jasonbaldridge/maul
src/main/java/edu/berkeley/nlp/lm/collections/Iterators.java
// Path: src/main/java/edu/berkeley/nlp/lm/util/Pair.java // public class Pair<F, S> implements Serializable // { // static final long serialVersionUID = 42; // // F first; // // S second; // // public F getFirst() { // return first; // } // // public S getSecond() { // return second; // } // // @Override // public String toString() { // return "(" + getFirst() + ", " + getSecond() + ")"; // } // // public Pair(final F first, final S second) { // this.first = first; // this.second = second; // } // // public static <S, T> Pair<S, T> newPair(final S first, final T second) { // return new Pair<S, T>(first, second); // } // }
import java.util.Iterator; import edu.berkeley.nlp.lm.util.Pair;
* Wraps a base iterator with a transformation function. */ public static abstract class Transform<S, T> implements Iterator<T> { private final Iterator<S> base; public Transform(final Iterator<S> base) { this.base = base; } @Override public boolean hasNext() { return base.hasNext(); } @Override public T next() { return transform(base.next()); } protected abstract T transform(S next); @Override public void remove() { base.remove(); } }
// Path: src/main/java/edu/berkeley/nlp/lm/util/Pair.java // public class Pair<F, S> implements Serializable // { // static final long serialVersionUID = 42; // // F first; // // S second; // // public F getFirst() { // return first; // } // // public S getSecond() { // return second; // } // // @Override // public String toString() { // return "(" + getFirst() + ", " + getSecond() + ")"; // } // // public Pair(final F first, final S second) { // this.first = first; // this.second = second; // } // // public static <S, T> Pair<S, T> newPair(final S first, final T second) { // return new Pair<S, T>(first, second); // } // } // Path: src/main/java/edu/berkeley/nlp/lm/collections/Iterators.java import java.util.Iterator; import edu.berkeley.nlp.lm.util.Pair; * Wraps a base iterator with a transformation function. */ public static abstract class Transform<S, T> implements Iterator<T> { private final Iterator<S> base; public Transform(final Iterator<S> base) { this.base = base; } @Override public boolean hasNext() { return base.hasNext(); } @Override public T next() { return transform(base.next()); } protected abstract T transform(S next); @Override public void remove() { base.remove(); } }
public static <S, T> Iterator<Pair<S, T>> zip(final Iterator<S> s, final Iterator<T> t) {
jasonbaldridge/maul
src/main/java/edu/berkeley/nlp/lm/collections/LongToIntHashMap.java
// Path: src/main/java/edu/berkeley/nlp/lm/util/MurmurHash.java // public final class MurmurHash // { // // /** // * Generates 32 bit hash from byte array of the given length and seed. // * // * @param data // * int array to hash // * @param length // * length of the array to hash // * @param seed // * initial seed value // * @return 32 bit hash of the given array // */ // public static int hash32(final int[] data, int startPos, int endPos, int seed) { // // 'm' and 'r' are mixing constants generated offline. // // They're not really 'magic', they just happen to work well. // final int m = 0x5bd1e995; // final int r = 24; // final int length = endPos - startPos; // // Initialize the hash to a random value // int h = seed ^ length; // // for (int i = startPos; i < endPos; i++) { // int k = data[i]; // k *= m; // k ^= k >>> r; // k *= m; // h *= m; // h ^= k; // } // // h ^= h >>> 13; // h *= m; // h ^= h >>> 15; // // return h; // } // // public static int hash32(final int[] data, int startPos, int endPos) { // return hash32(data, startPos, endPos, 0x9747b28c); // } // // public static long hashOneLong(final long k_, final int seed) { // long k = k_; // final long m = 0xc6a4a7935bd1e995L; // final int r = 47; // // long h = (seed & 0xffffffffl) ^ (1 * m); // // k *= m; // k ^= k >>> r; // k *= m; // // h ^= k; // h *= m; // // h ^= h >>> r; // h *= m; // h ^= h >>> r; // // return h; // } // // public static long hashThreeLongs(final long k1, final long k2, final long k3) { // // final int seed = 0x9747b28c; // final long m = 0xc6a4a7935bd1e995L; // final int r = 47; // // long h = (seed & 0xffffffffl) ^ (1 * m); // for (int i = 0; i <= 2; ++i) { // long k = -1; // switch (i) { // case 0: // k = k1; // break; // case 1: // k = k2; // break; // case 2: // k = k3; // break; // default: // assert false; // } // k *= m; // k ^= k >>> r; // k *= m; // // h ^= k; // h *= m; // } // // h ^= h >>> r; // h *= m; // h ^= h >>> r; // // return h; // } // // }
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import edu.berkeley.nlp.lm.util.MurmurHash;
*/ private boolean putHelp(long k, int v, long[] keyArray, int[] valueArray) { checkNotImmutable(); assert v >= 0; int pos = find(k, true, keyArray, valueArray); // int pos = getInitialPos(k, keyArray); // long currKey = keyArray[pos]; // while (currKey != EMPTY_KEY && currKey != k) { // pos++; // if (pos == keyArray.length) pos = 0; // currKey = keyArray[pos]; // } // boolean wasEmpty = valueArray[pos] == EMPTY_VAL; valueArray[pos] = v; if (wasEmpty) { size++; keyArray[pos] = k; return true; } return false; } /** * @param k * @param keyArray * @return */ private static int getInitialPos(final long k, final int length) { if (length < 0) return (int) k;
// Path: src/main/java/edu/berkeley/nlp/lm/util/MurmurHash.java // public final class MurmurHash // { // // /** // * Generates 32 bit hash from byte array of the given length and seed. // * // * @param data // * int array to hash // * @param length // * length of the array to hash // * @param seed // * initial seed value // * @return 32 bit hash of the given array // */ // public static int hash32(final int[] data, int startPos, int endPos, int seed) { // // 'm' and 'r' are mixing constants generated offline. // // They're not really 'magic', they just happen to work well. // final int m = 0x5bd1e995; // final int r = 24; // final int length = endPos - startPos; // // Initialize the hash to a random value // int h = seed ^ length; // // for (int i = startPos; i < endPos; i++) { // int k = data[i]; // k *= m; // k ^= k >>> r; // k *= m; // h *= m; // h ^= k; // } // // h ^= h >>> 13; // h *= m; // h ^= h >>> 15; // // return h; // } // // public static int hash32(final int[] data, int startPos, int endPos) { // return hash32(data, startPos, endPos, 0x9747b28c); // } // // public static long hashOneLong(final long k_, final int seed) { // long k = k_; // final long m = 0xc6a4a7935bd1e995L; // final int r = 47; // // long h = (seed & 0xffffffffl) ^ (1 * m); // // k *= m; // k ^= k >>> r; // k *= m; // // h ^= k; // h *= m; // // h ^= h >>> r; // h *= m; // h ^= h >>> r; // // return h; // } // // public static long hashThreeLongs(final long k1, final long k2, final long k3) { // // final int seed = 0x9747b28c; // final long m = 0xc6a4a7935bd1e995L; // final int r = 47; // // long h = (seed & 0xffffffffl) ^ (1 * m); // for (int i = 0; i <= 2; ++i) { // long k = -1; // switch (i) { // case 0: // k = k1; // break; // case 1: // k = k2; // break; // case 2: // k = k3; // break; // default: // assert false; // } // k *= m; // k ^= k >>> r; // k *= m; // // h ^= k; // h *= m; // } // // h ^= h >>> r; // h *= m; // h ^= h >>> r; // // return h; // } // // } // Path: src/main/java/edu/berkeley/nlp/lm/collections/LongToIntHashMap.java import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import edu.berkeley.nlp.lm.util.MurmurHash; */ private boolean putHelp(long k, int v, long[] keyArray, int[] valueArray) { checkNotImmutable(); assert v >= 0; int pos = find(k, true, keyArray, valueArray); // int pos = getInitialPos(k, keyArray); // long currKey = keyArray[pos]; // while (currKey != EMPTY_KEY && currKey != k) { // pos++; // if (pos == keyArray.length) pos = 0; // currKey = keyArray[pos]; // } // boolean wasEmpty = valueArray[pos] == EMPTY_VAL; valueArray[pos] = v; if (wasEmpty) { size++; keyArray[pos] = k; return true; } return false; } /** * @param k * @param keyArray * @return */ private static int getInitialPos(final long k, final int length) { if (length < 0) return (int) k;
long hash = MurmurHash.hashOneLong(k, 31);
jasonbaldridge/maul
src/main/java/edu/berkeley/nlp/lm/map/UnigramHashMap.java
// Path: src/main/java/edu/berkeley/nlp/lm/collections/Iterators.java // public class Iterators // { // // /** // * Wraps an Iterator as an Iterable // * // * @param <T> // * @param it // * @return // */ // public static <T> Iterable<T> able(final Iterator<T> it) { // return new Iterable<T>() // { // boolean used = false; // // @Override // public Iterator<T> iterator() { // if (used) throw new RuntimeException("One use iterable"); // used = true; // return it; // } // }; // } // // public static <T> Iterable<T> flatten(final Iterator<Iterator<T>> iters) { // return Iterators.able(new IteratorIterator<T>(iters)); // } // // /** // * Wraps a two-level iteration scenario in an iterator. Each key of the keys // * iterator returns an iterator (via the factory) over T's. // * <p> // * The IteratorIterator loops through the iterator associated with each key // * until all the keys are used up. // */ // public static class IteratorIterator<T> implements Iterator<T> // { // Iterator<T> current = null; // // private final Iterator<Iterator<T>> iters; // // public IteratorIterator(final Iterator<Iterator<T>> iters) { // this.iters = iters; // current = getNextIterator(); // } // // private Iterator<T> getNextIterator() { // Iterator<T> next = null; // while (next == null) { // if (!iters.hasNext()) break; // next = iters.next(); // if (!next.hasNext()) next = null; // } // return next; // } // // @Override // public boolean hasNext() { // return current != null; // } // // @Override // public T next() { // final T next = current.next(); // if (!current.hasNext()) current = getNextIterator(); // return next; // } // // @Override // public void remove() { // throw new UnsupportedOperationException(); // } // // } // // /** // * Wraps a base iterator with a transformation function. // */ // public static abstract class Transform<S, T> implements Iterator<T> // { // // private final Iterator<S> base; // // public Transform(final Iterator<S> base) { // this.base = base; // } // // @Override // public boolean hasNext() { // return base.hasNext(); // } // // @Override // public T next() { // return transform(base.next()); // } // // protected abstract T transform(S next); // // @Override // public void remove() { // base.remove(); // } // // } // // public static <S, T> Iterator<Pair<S, T>> zip(final Iterator<S> s, final Iterator<T> t) { // return new Iterator<Pair<S, T>>() // { // @Override // public boolean hasNext() { // return s.hasNext() && t.hasNext(); // } // // @Override // public Pair<S, T> next() { // return Pair.newPair(s.next(), t.next()); // } // // @Override // public void remove() { // throw new UnsupportedOperationException(); // } // }; // } // // }
import java.io.Serializable; import java.util.Iterator; import edu.berkeley.nlp.lm.collections.Iterators;
* @see edu.berkeley.nlp.lm.map.HashMap#put(long) */ @Override public long put(final long key) { return ngramMap.wordOf(key); } @Override public final long getOffset(final long key) { final long word = ngramMap.wordOf(key); return (word < 0 || word >= numWords) ? EMPTY_KEY : word; } @Override public long getKey(final long contextOffset) { return ngramMap.combineToKey((int) contextOffset, 0L); } @Override public boolean isEmptyKey(final long key) { return key == EMPTY_KEY; } @Override public long size() { return numWords; } @Override public Iterable<Long> keys() {
// Path: src/main/java/edu/berkeley/nlp/lm/collections/Iterators.java // public class Iterators // { // // /** // * Wraps an Iterator as an Iterable // * // * @param <T> // * @param it // * @return // */ // public static <T> Iterable<T> able(final Iterator<T> it) { // return new Iterable<T>() // { // boolean used = false; // // @Override // public Iterator<T> iterator() { // if (used) throw new RuntimeException("One use iterable"); // used = true; // return it; // } // }; // } // // public static <T> Iterable<T> flatten(final Iterator<Iterator<T>> iters) { // return Iterators.able(new IteratorIterator<T>(iters)); // } // // /** // * Wraps a two-level iteration scenario in an iterator. Each key of the keys // * iterator returns an iterator (via the factory) over T's. // * <p> // * The IteratorIterator loops through the iterator associated with each key // * until all the keys are used up. // */ // public static class IteratorIterator<T> implements Iterator<T> // { // Iterator<T> current = null; // // private final Iterator<Iterator<T>> iters; // // public IteratorIterator(final Iterator<Iterator<T>> iters) { // this.iters = iters; // current = getNextIterator(); // } // // private Iterator<T> getNextIterator() { // Iterator<T> next = null; // while (next == null) { // if (!iters.hasNext()) break; // next = iters.next(); // if (!next.hasNext()) next = null; // } // return next; // } // // @Override // public boolean hasNext() { // return current != null; // } // // @Override // public T next() { // final T next = current.next(); // if (!current.hasNext()) current = getNextIterator(); // return next; // } // // @Override // public void remove() { // throw new UnsupportedOperationException(); // } // // } // // /** // * Wraps a base iterator with a transformation function. // */ // public static abstract class Transform<S, T> implements Iterator<T> // { // // private final Iterator<S> base; // // public Transform(final Iterator<S> base) { // this.base = base; // } // // @Override // public boolean hasNext() { // return base.hasNext(); // } // // @Override // public T next() { // return transform(base.next()); // } // // protected abstract T transform(S next); // // @Override // public void remove() { // base.remove(); // } // // } // // public static <S, T> Iterator<Pair<S, T>> zip(final Iterator<S> s, final Iterator<T> t) { // return new Iterator<Pair<S, T>>() // { // @Override // public boolean hasNext() { // return s.hasNext() && t.hasNext(); // } // // @Override // public Pair<S, T> next() { // return Pair.newPair(s.next(), t.next()); // } // // @Override // public void remove() { // throw new UnsupportedOperationException(); // } // }; // } // // } // Path: src/main/java/edu/berkeley/nlp/lm/map/UnigramHashMap.java import java.io.Serializable; import java.util.Iterator; import edu.berkeley.nlp.lm.collections.Iterators; * @see edu.berkeley.nlp.lm.map.HashMap#put(long) */ @Override public long put(final long key) { return ngramMap.wordOf(key); } @Override public final long getOffset(final long key) { final long word = ngramMap.wordOf(key); return (word < 0 || word >= numWords) ? EMPTY_KEY : word; } @Override public long getKey(final long contextOffset) { return ngramMap.combineToKey((int) contextOffset, 0L); } @Override public boolean isEmptyKey(final long key) { return key == EMPTY_KEY; } @Override public long size() { return numWords; } @Override public Iterable<Long> keys() {
return Iterators.able(new RangeIterator(numWords));
jasonbaldridge/maul
src/main/java/edu/berkeley/nlp/lm/values/ValueContainer.java
// Path: src/main/java/edu/berkeley/nlp/lm/map/NgramMap.java // public interface NgramMap<V> // { // // public long put(int[] ngram, int startPos, int endPos, V val); // // public void handleNgramsFinished(int justFinishedOrder); // // public void trim(); // // public void initWithLengths(List<Long> numNGrams); // // public ValueContainer<V> getValues(); // // public long getValueAndOffset(final long contextOffset, final int contextOrder, int word, @OutputParameter V currProbVal); // // public int getMaxNgramOrder(); // // public long getNumNgrams(int ngramOrder); // // public Iterable<Entry<V>> getNgramsForOrder(final int ngramOrder); // // public CustomWidthArray getValueStoringArray(final int ngramOrder); // // public static class Entry<T> // { // /** // * @param key // * @param value // */ // public Entry(final int[] key, final T value) { // super(); // this.key = key; // this.value = value; // } // // public int[] key; // // public T value; // // } // // public boolean contains(int[] ngram, int startPos, int endPos); // // public V get(int[] ngram, int startPos, int endPos); // // public void clearStorage(); // // }
import java.io.Serializable; import edu.berkeley.nlp.lm.map.NgramMap; import edu.berkeley.nlp.lm.util.Annotations.OutputParameter;
package edu.berkeley.nlp.lm.values; /** * Manages storage of arbitrary values in an NgramMap * * @author adampauls * * @param <V> */ public interface ValueContainer<V> extends Serializable { /** * Adds a new value at the specified offset. * * @param ngramOrder * As always, ngramOrder is 0-based (0=unigram) * @param offset * @param contextOffset * @param word * @param val * @param suffixOffset * @return Whether or not the add was successful */ public boolean add(int[] ngram, int startPos, int endPos, int ngramOrder, long offset, long contextOffset, int word, V val, long suffixOffset, boolean ngramIsNew); /** * Sets internal storage for size for a particular n-gram order * * @param size * @param ngramOrder */ public void setSizeAtLeast(long size, int ngramOrder); /** * Creates a fresh value container for copying purposes. * * @return */ public ValueContainer<V> createFreshValues(long[] numNgramsForEachOrder); /** * Gets the value living at a particular offset. * * @param offset * @param ngramOrder * @return */ public void getFromOffset(long offset, int ngramOrder, @OutputParameter V outputVal); /** * Destructively sets internal storage from another object. * * @param other */ public void setFromOtherValues(ValueContainer<V> other); /** * Clear storage after an n-gram order is complete * * @param ngramOrder * @param size */ public void trimAfterNgram(int ngramOrder, long size); /** * Final clean up of storage. */ public void trim(); /** * Creates a fresh value of object (useful for passing as an output * parameter) * * @return */ public V getScratchValue(); /** * Initializes a value container with the map that contains it */
// Path: src/main/java/edu/berkeley/nlp/lm/map/NgramMap.java // public interface NgramMap<V> // { // // public long put(int[] ngram, int startPos, int endPos, V val); // // public void handleNgramsFinished(int justFinishedOrder); // // public void trim(); // // public void initWithLengths(List<Long> numNGrams); // // public ValueContainer<V> getValues(); // // public long getValueAndOffset(final long contextOffset, final int contextOrder, int word, @OutputParameter V currProbVal); // // public int getMaxNgramOrder(); // // public long getNumNgrams(int ngramOrder); // // public Iterable<Entry<V>> getNgramsForOrder(final int ngramOrder); // // public CustomWidthArray getValueStoringArray(final int ngramOrder); // // public static class Entry<T> // { // /** // * @param key // * @param value // */ // public Entry(final int[] key, final T value) { // super(); // this.key = key; // this.value = value; // } // // public int[] key; // // public T value; // // } // // public boolean contains(int[] ngram, int startPos, int endPos); // // public V get(int[] ngram, int startPos, int endPos); // // public void clearStorage(); // // } // Path: src/main/java/edu/berkeley/nlp/lm/values/ValueContainer.java import java.io.Serializable; import edu.berkeley.nlp.lm.map.NgramMap; import edu.berkeley.nlp.lm.util.Annotations.OutputParameter; package edu.berkeley.nlp.lm.values; /** * Manages storage of arbitrary values in an NgramMap * * @author adampauls * * @param <V> */ public interface ValueContainer<V> extends Serializable { /** * Adds a new value at the specified offset. * * @param ngramOrder * As always, ngramOrder is 0-based (0=unigram) * @param offset * @param contextOffset * @param word * @param val * @param suffixOffset * @return Whether or not the add was successful */ public boolean add(int[] ngram, int startPos, int endPos, int ngramOrder, long offset, long contextOffset, int word, V val, long suffixOffset, boolean ngramIsNew); /** * Sets internal storage for size for a particular n-gram order * * @param size * @param ngramOrder */ public void setSizeAtLeast(long size, int ngramOrder); /** * Creates a fresh value container for copying purposes. * * @return */ public ValueContainer<V> createFreshValues(long[] numNgramsForEachOrder); /** * Gets the value living at a particular offset. * * @param offset * @param ngramOrder * @return */ public void getFromOffset(long offset, int ngramOrder, @OutputParameter V outputVal); /** * Destructively sets internal storage from another object. * * @param other */ public void setFromOtherValues(ValueContainer<V> other); /** * Clear storage after an n-gram order is complete * * @param ngramOrder * @param size */ public void trimAfterNgram(int ngramOrder, long size); /** * Final clean up of storage. */ public void trim(); /** * Creates a fresh value of object (useful for passing as an output * parameter) * * @return */ public V getScratchValue(); /** * Initializes a value container with the map that contains it */
public void setMap(NgramMap<V> map);
jasonbaldridge/maul
src/main/java/edu/berkeley/nlp/lm/ContextEncodedNgramLanguageModel.java
// Path: src/main/java/edu/berkeley/nlp/lm/collections/BoundedList.java // public class BoundedList<E> extends AbstractList<E> // { // private final E leftBoundary; // // private final E rightBoundary; // // private final List<E> list; // // /** // * Returns the object at the given index, provided the index is between 0 // * (inclusive) and size() (exclusive). If the index is < 0, then a left // * boundary object is returned. If the index is >= size(), a right boundary // * object is returned. The default boundary objects are both null, unless // * other objects are specified on construction. // */ // @Override // public E get(final int index) { // if (index < 0) return leftBoundary; // if (index >= list.size()) return rightBoundary; // return list.get(index); // } // // @Override // public int size() { // return list.size(); // } // // public BoundedList(final List<E> list, final E leftBoundary, final E rightBoundary) { // this.list = list; // this.leftBoundary = leftBoundary; // this.rightBoundary = rightBoundary; // } // // @Override // public List<E> subList(final int fromIndex, final int toIndex) { // final List<E> retVal = new ArrayList<E>(toIndex - fromIndex); // for (int i = fromIndex; i < toIndex; ++i) { // retVal.add(get(i)); // } // return retVal; // } // // }
import java.util.List; import edu.berkeley.nlp.lm.collections.BoundedList; import edu.berkeley.nlp.lm.util.Annotations.OutputParameter;
package edu.berkeley.nlp.lm; /** * Interface for language models which expose the internal context-encoding for * more efficient queries. (Note: language model implementations may internally * use a context-encoding without implementing this interface). A * context-encoding encodes an n-gram as a integer representing the last word, * and an offset which serves as a logical pointer to the (n-1) prefix words. * The integers represent words of type <code>W</code> in the vocabulary, and the mapping * from the vocabulary to integers is managed by an instance of the {@link WordIndexer} class. * * @author adampauls * * @param <W> */ public interface ContextEncodedNgramLanguageModel<W> extends NgramLanguageModel<W> { /** * Simple class for returning context offsets * * @author adampauls * */ public static class LmContextInfo { /** * Offset of context (prefix) of an n-gram */ public long offset = -1L; /** * The (0-based) length of <code>context</code> (i.e. * <code>order == 0</code> iff <code>context</code> refers to a * unigram). * * Use -1 for an empty context. */ public int order = -1; } /** * Get the score for an n-gram, and also get the context offset of the * n-gram's suffix. * * @param contextOffset * Offset of context (prefix) of an n-gram * @param contextOrder * The (0-based) length of <code>context</code> (i.e. * <code>order == 0</code> iff <code>context</code> refers to a * unigram). * @param word * Last word of the n-gram * @param outputContext * Offset of the suffix of the input n-gram. If the parameter is * <code>null</code> it will be ignored. This can be passed to * future queries for efficient access. * @return */ public float getLogProb(long contextOffset, int contextOrder, int word, @OutputParameter LmContextInfo outputContext); /** * Gets the offset which refers to an n-gram. If the n-gram is not in the * model, then it returns the shortest suffix of the n-gram which is. This * operation is not necessarily fast. * */ public LmContextInfo getOffsetForNgram(int[] ngram, int startPos, int endPos); /** * Gets the n-gram referred to by a context-encoding. This operation is not * necessarily fast. * */ public int[] getNgramForOffset(long contextOffset, int contextOrder, int word); public static class DefaultImplementations { public static <T> float scoreSentence(final List<T> sentence, final ContextEncodedNgramLanguageModel<T> lm) {
// Path: src/main/java/edu/berkeley/nlp/lm/collections/BoundedList.java // public class BoundedList<E> extends AbstractList<E> // { // private final E leftBoundary; // // private final E rightBoundary; // // private final List<E> list; // // /** // * Returns the object at the given index, provided the index is between 0 // * (inclusive) and size() (exclusive). If the index is < 0, then a left // * boundary object is returned. If the index is >= size(), a right boundary // * object is returned. The default boundary objects are both null, unless // * other objects are specified on construction. // */ // @Override // public E get(final int index) { // if (index < 0) return leftBoundary; // if (index >= list.size()) return rightBoundary; // return list.get(index); // } // // @Override // public int size() { // return list.size(); // } // // public BoundedList(final List<E> list, final E leftBoundary, final E rightBoundary) { // this.list = list; // this.leftBoundary = leftBoundary; // this.rightBoundary = rightBoundary; // } // // @Override // public List<E> subList(final int fromIndex, final int toIndex) { // final List<E> retVal = new ArrayList<E>(toIndex - fromIndex); // for (int i = fromIndex; i < toIndex; ++i) { // retVal.add(get(i)); // } // return retVal; // } // // } // Path: src/main/java/edu/berkeley/nlp/lm/ContextEncodedNgramLanguageModel.java import java.util.List; import edu.berkeley.nlp.lm.collections.BoundedList; import edu.berkeley.nlp.lm.util.Annotations.OutputParameter; package edu.berkeley.nlp.lm; /** * Interface for language models which expose the internal context-encoding for * more efficient queries. (Note: language model implementations may internally * use a context-encoding without implementing this interface). A * context-encoding encodes an n-gram as a integer representing the last word, * and an offset which serves as a logical pointer to the (n-1) prefix words. * The integers represent words of type <code>W</code> in the vocabulary, and the mapping * from the vocabulary to integers is managed by an instance of the {@link WordIndexer} class. * * @author adampauls * * @param <W> */ public interface ContextEncodedNgramLanguageModel<W> extends NgramLanguageModel<W> { /** * Simple class for returning context offsets * * @author adampauls * */ public static class LmContextInfo { /** * Offset of context (prefix) of an n-gram */ public long offset = -1L; /** * The (0-based) length of <code>context</code> (i.e. * <code>order == 0</code> iff <code>context</code> refers to a * unigram). * * Use -1 for an empty context. */ public int order = -1; } /** * Get the score for an n-gram, and also get the context offset of the * n-gram's suffix. * * @param contextOffset * Offset of context (prefix) of an n-gram * @param contextOrder * The (0-based) length of <code>context</code> (i.e. * <code>order == 0</code> iff <code>context</code> refers to a * unigram). * @param word * Last word of the n-gram * @param outputContext * Offset of the suffix of the input n-gram. If the parameter is * <code>null</code> it will be ignored. This can be passed to * future queries for efficient access. * @return */ public float getLogProb(long contextOffset, int contextOrder, int word, @OutputParameter LmContextInfo outputContext); /** * Gets the offset which refers to an n-gram. If the n-gram is not in the * model, then it returns the shortest suffix of the n-gram which is. This * operation is not necessarily fast. * */ public LmContextInfo getOffsetForNgram(int[] ngram, int startPos, int endPos); /** * Gets the n-gram referred to by a context-encoding. This operation is not * necessarily fast. * */ public int[] getNgramForOffset(long contextOffset, int contextOrder, int word); public static class DefaultImplementations { public static <T> float scoreSentence(final List<T> sentence, final ContextEncodedNgramLanguageModel<T> lm) {
final List<T> sentenceWithBounds = new BoundedList<T>(sentence, lm.getWordIndexer().getStartSymbol(), lm.getWordIndexer().getEndSymbol());
jasonbaldridge/maul
src/main/java/edu/berkeley/nlp/lm/ArrayEncodedNgramLanguageModel.java
// Path: src/main/java/edu/berkeley/nlp/lm/collections/BoundedList.java // public class BoundedList<E> extends AbstractList<E> // { // private final E leftBoundary; // // private final E rightBoundary; // // private final List<E> list; // // /** // * Returns the object at the given index, provided the index is between 0 // * (inclusive) and size() (exclusive). If the index is < 0, then a left // * boundary object is returned. If the index is >= size(), a right boundary // * object is returned. The default boundary objects are both null, unless // * other objects are specified on construction. // */ // @Override // public E get(final int index) { // if (index < 0) return leftBoundary; // if (index >= list.size()) return rightBoundary; // return list.get(index); // } // // @Override // public int size() { // return list.size(); // } // // public BoundedList(final List<E> list, final E leftBoundary, final E rightBoundary) { // this.list = list; // this.leftBoundary = leftBoundary; // this.rightBoundary = rightBoundary; // } // // @Override // public List<E> subList(final int fromIndex, final int toIndex) { // final List<E> retVal = new ArrayList<E>(toIndex - fromIndex); // for (int i = fromIndex; i < toIndex; ++i) { // retVal.add(get(i)); // } // return retVal; // } // // }
import java.util.List; import edu.berkeley.nlp.lm.collections.BoundedList;
package edu.berkeley.nlp.lm; /** * Top-level interface for an n-gram language model which accepts n-gram in an * array-of-integers encoding. The integers represent words of type * <code>W</code> in the vocabulary, and the mapping from the vocabulary to * integers is managed by an instance of the {@link WordIndexer} class. * * @author adampauls */ public interface ArrayEncodedNgramLanguageModel<W> extends NgramLanguageModel<W> { /** * Calculate language model score of an n-gram. <b>Warning:</b> if you * pass in an n-gram of length greater than <code>getLmOrder()</code>, * this call will silently ignore the extra words of context. In other * words, if you pass in a 5-gram (<code>endPos-startPos == 5</code>) to * a 3-gram model, it will only score the words from <code>startPos + 2</code> * to <code>endPos</code>. * * @param ngram * array of words in integer representation * @param startPos * start of the portion of the array to be read * @param endPos * end of the portion of the array to be read. * @return */ public float getLogProb(int[] ngram, int startPos, int endPos); /** * Equivalent to <code>getLogProb(ngram, 0, ngram.length)</code> * * @see #getLogProb(int[], int, int) */ public float getLogProb(int[] ngram); public static class DefaultImplementations { public static <T> float scoreSentence(final List<T> sentence, final ArrayEncodedNgramLanguageModel<T> lm) {
// Path: src/main/java/edu/berkeley/nlp/lm/collections/BoundedList.java // public class BoundedList<E> extends AbstractList<E> // { // private final E leftBoundary; // // private final E rightBoundary; // // private final List<E> list; // // /** // * Returns the object at the given index, provided the index is between 0 // * (inclusive) and size() (exclusive). If the index is < 0, then a left // * boundary object is returned. If the index is >= size(), a right boundary // * object is returned. The default boundary objects are both null, unless // * other objects are specified on construction. // */ // @Override // public E get(final int index) { // if (index < 0) return leftBoundary; // if (index >= list.size()) return rightBoundary; // return list.get(index); // } // // @Override // public int size() { // return list.size(); // } // // public BoundedList(final List<E> list, final E leftBoundary, final E rightBoundary) { // this.list = list; // this.leftBoundary = leftBoundary; // this.rightBoundary = rightBoundary; // } // // @Override // public List<E> subList(final int fromIndex, final int toIndex) { // final List<E> retVal = new ArrayList<E>(toIndex - fromIndex); // for (int i = fromIndex; i < toIndex; ++i) { // retVal.add(get(i)); // } // return retVal; // } // // } // Path: src/main/java/edu/berkeley/nlp/lm/ArrayEncodedNgramLanguageModel.java import java.util.List; import edu.berkeley.nlp.lm.collections.BoundedList; package edu.berkeley.nlp.lm; /** * Top-level interface for an n-gram language model which accepts n-gram in an * array-of-integers encoding. The integers represent words of type * <code>W</code> in the vocabulary, and the mapping from the vocabulary to * integers is managed by an instance of the {@link WordIndexer} class. * * @author adampauls */ public interface ArrayEncodedNgramLanguageModel<W> extends NgramLanguageModel<W> { /** * Calculate language model score of an n-gram. <b>Warning:</b> if you * pass in an n-gram of length greater than <code>getLmOrder()</code>, * this call will silently ignore the extra words of context. In other * words, if you pass in a 5-gram (<code>endPos-startPos == 5</code>) to * a 3-gram model, it will only score the words from <code>startPos + 2</code> * to <code>endPos</code>. * * @param ngram * array of words in integer representation * @param startPos * start of the portion of the array to be read * @param endPos * end of the portion of the array to be read. * @return */ public float getLogProb(int[] ngram, int startPos, int endPos); /** * Equivalent to <code>getLogProb(ngram, 0, ngram.length)</code> * * @see #getLogProb(int[], int, int) */ public float getLogProb(int[] ngram); public static class DefaultImplementations { public static <T> float scoreSentence(final List<T> sentence, final ArrayEncodedNgramLanguageModel<T> lm) {
final List<T> sentenceWithBounds = new BoundedList<T>(sentence, lm.getWordIndexer().getStartSymbol(), lm.getWordIndexer().getEndSymbol());
jasonbaldridge/maul
src/main/java/edu/berkeley/nlp/lm/map/ContextEncodedNgramMap.java
// Path: src/main/java/edu/berkeley/nlp/lm/ContextEncodedNgramLanguageModel.java // public static class LmContextInfo // { // // /** // * Offset of context (prefix) of an n-gram // */ // public long offset = -1L; // // /** // * The (0-based) length of <code>context</code> (i.e. // * <code>order == 0</code> iff <code>context</code> refers to a // * unigram). // * // * Use -1 for an empty context. // */ // public int order = -1; // // }
import edu.berkeley.nlp.lm.ContextEncodedNgramLanguageModel.LmContextInfo;
package edu.berkeley.nlp.lm.map; public interface ContextEncodedNgramMap<T> extends NgramMap<T> { public long getOffset(final long contextOffset, final int contextOrder, final int word);
// Path: src/main/java/edu/berkeley/nlp/lm/ContextEncodedNgramLanguageModel.java // public static class LmContextInfo // { // // /** // * Offset of context (prefix) of an n-gram // */ // public long offset = -1L; // // /** // * The (0-based) length of <code>context</code> (i.e. // * <code>order == 0</code> iff <code>context</code> refers to a // * unigram). // * // * Use -1 for an empty context. // */ // public int order = -1; // // } // Path: src/main/java/edu/berkeley/nlp/lm/map/ContextEncodedNgramMap.java import edu.berkeley.nlp.lm.ContextEncodedNgramLanguageModel.LmContextInfo; package edu.berkeley.nlp.lm.map; public interface ContextEncodedNgramMap<T> extends NgramMap<T> { public long getOffset(final long contextOffset, final int contextOrder, final int word);
public LmContextInfo getOffsetForNgram(int[] ngram, int startPos, int endPos);
jasonbaldridge/maul
src/main/java/edu/berkeley/nlp/lm/cache/ContextEncodedLmCache.java
// Path: src/main/java/edu/berkeley/nlp/lm/ContextEncodedNgramLanguageModel.java // public static class LmContextInfo // { // // /** // * Offset of context (prefix) of an n-gram // */ // public long offset = -1L; // // /** // * The (0-based) length of <code>context</code> (i.e. // * <code>order == 0</code> iff <code>context</code> refers to a // * unigram). // * // * Use -1 for an empty context. // */ // public int order = -1; // // }
import java.io.Serializable; import edu.berkeley.nlp.lm.ContextEncodedNgramLanguageModel.LmContextInfo; import edu.berkeley.nlp.lm.util.Annotations.OutputParameter;
package edu.berkeley.nlp.lm.cache; public interface ContextEncodedLmCache extends Serializable { /** * Should return Float.NaN if requested n-gram is not in the cache. * * @param contextOffset * @param contextOrder * @param word * @param hash * @param outputPrefix * @return */
// Path: src/main/java/edu/berkeley/nlp/lm/ContextEncodedNgramLanguageModel.java // public static class LmContextInfo // { // // /** // * Offset of context (prefix) of an n-gram // */ // public long offset = -1L; // // /** // * The (0-based) length of <code>context</code> (i.e. // * <code>order == 0</code> iff <code>context</code> refers to a // * unigram). // * // * Use -1 for an empty context. // */ // public int order = -1; // // } // Path: src/main/java/edu/berkeley/nlp/lm/cache/ContextEncodedLmCache.java import java.io.Serializable; import edu.berkeley.nlp.lm.ContextEncodedNgramLanguageModel.LmContextInfo; import edu.berkeley.nlp.lm.util.Annotations.OutputParameter; package edu.berkeley.nlp.lm.cache; public interface ContextEncodedLmCache extends Serializable { /** * Should return Float.NaN if requested n-gram is not in the cache. * * @param contextOffset * @param contextOrder * @param word * @param hash * @param outputPrefix * @return */
public float getCached(long contextOffset, int contextOrder, int word, int hash, @OutputParameter LmContextInfo outputPrefix);
jasonbaldridge/maul
src/main/java/edu/berkeley/nlp/lm/collections/LongHashSet.java
// Path: src/main/java/edu/berkeley/nlp/lm/util/MurmurHash.java // public final class MurmurHash // { // // /** // * Generates 32 bit hash from byte array of the given length and seed. // * // * @param data // * int array to hash // * @param length // * length of the array to hash // * @param seed // * initial seed value // * @return 32 bit hash of the given array // */ // public static int hash32(final int[] data, int startPos, int endPos, int seed) { // // 'm' and 'r' are mixing constants generated offline. // // They're not really 'magic', they just happen to work well. // final int m = 0x5bd1e995; // final int r = 24; // final int length = endPos - startPos; // // Initialize the hash to a random value // int h = seed ^ length; // // for (int i = startPos; i < endPos; i++) { // int k = data[i]; // k *= m; // k ^= k >>> r; // k *= m; // h *= m; // h ^= k; // } // // h ^= h >>> 13; // h *= m; // h ^= h >>> 15; // // return h; // } // // public static int hash32(final int[] data, int startPos, int endPos) { // return hash32(data, startPos, endPos, 0x9747b28c); // } // // public static long hashOneLong(final long k_, final int seed) { // long k = k_; // final long m = 0xc6a4a7935bd1e995L; // final int r = 47; // // long h = (seed & 0xffffffffl) ^ (1 * m); // // k *= m; // k ^= k >>> r; // k *= m; // // h ^= k; // h *= m; // // h ^= h >>> r; // h *= m; // h ^= h >>> r; // // return h; // } // // public static long hashThreeLongs(final long k1, final long k2, final long k3) { // // final int seed = 0x9747b28c; // final long m = 0xc6a4a7935bd1e995L; // final int r = 47; // // long h = (seed & 0xffffffffl) ^ (1 * m); // for (int i = 0; i <= 2; ++i) { // long k = -1; // switch (i) { // case 0: // k = k1; // break; // case 1: // k = k2; // break; // case 2: // k = k3; // break; // default: // assert false; // } // k *= m; // k ^= k >>> r; // k *= m; // // h ^= k; // h *= m; // } // // h ^= h >>> r; // h *= m; // h ^= h >>> r; // // return h; // } // // }
import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import edu.berkeley.nlp.lm.util.MurmurHash;
* @param k * @param v */ private boolean putHelp(long k, long[] keyArray) { assert k != EMPTY_KEY; int pos = find(k, true, keyArray); // int pos = getInitialPos(k, keyArray); long currKey = keyArray[pos]; // while (currKey != EMPTY_KEY && currKey != k) { // pos++; // if (pos == keyArray.length) pos = 0; // currKey = keyArray[pos]; // } // if (currKey == EMPTY_KEY) { size++; keyArray[pos] = k; return true; } return false; } /** * @param k * @param keyArray * @return */ private static int getInitialPos(final long k, final long[] keyArray) {
// Path: src/main/java/edu/berkeley/nlp/lm/util/MurmurHash.java // public final class MurmurHash // { // // /** // * Generates 32 bit hash from byte array of the given length and seed. // * // * @param data // * int array to hash // * @param length // * length of the array to hash // * @param seed // * initial seed value // * @return 32 bit hash of the given array // */ // public static int hash32(final int[] data, int startPos, int endPos, int seed) { // // 'm' and 'r' are mixing constants generated offline. // // They're not really 'magic', they just happen to work well. // final int m = 0x5bd1e995; // final int r = 24; // final int length = endPos - startPos; // // Initialize the hash to a random value // int h = seed ^ length; // // for (int i = startPos; i < endPos; i++) { // int k = data[i]; // k *= m; // k ^= k >>> r; // k *= m; // h *= m; // h ^= k; // } // // h ^= h >>> 13; // h *= m; // h ^= h >>> 15; // // return h; // } // // public static int hash32(final int[] data, int startPos, int endPos) { // return hash32(data, startPos, endPos, 0x9747b28c); // } // // public static long hashOneLong(final long k_, final int seed) { // long k = k_; // final long m = 0xc6a4a7935bd1e995L; // final int r = 47; // // long h = (seed & 0xffffffffl) ^ (1 * m); // // k *= m; // k ^= k >>> r; // k *= m; // // h ^= k; // h *= m; // // h ^= h >>> r; // h *= m; // h ^= h >>> r; // // return h; // } // // public static long hashThreeLongs(final long k1, final long k2, final long k3) { // // final int seed = 0x9747b28c; // final long m = 0xc6a4a7935bd1e995L; // final int r = 47; // // long h = (seed & 0xffffffffl) ^ (1 * m); // for (int i = 0; i <= 2; ++i) { // long k = -1; // switch (i) { // case 0: // k = k1; // break; // case 1: // k = k2; // break; // case 2: // k = k3; // break; // default: // assert false; // } // k *= m; // k ^= k >>> r; // k *= m; // // h ^= k; // h *= m; // } // // h ^= h >>> r; // h *= m; // h ^= h >>> r; // // return h; // } // // } // Path: src/main/java/edu/berkeley/nlp/lm/collections/LongHashSet.java import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import edu.berkeley.nlp.lm.util.MurmurHash; * @param k * @param v */ private boolean putHelp(long k, long[] keyArray) { assert k != EMPTY_KEY; int pos = find(k, true, keyArray); // int pos = getInitialPos(k, keyArray); long currKey = keyArray[pos]; // while (currKey != EMPTY_KEY && currKey != k) { // pos++; // if (pos == keyArray.length) pos = 0; // currKey = keyArray[pos]; // } // if (currKey == EMPTY_KEY) { size++; keyArray[pos] = k; return true; } return false; } /** * @param k * @param keyArray * @return */ private static int getInitialPos(final long k, final long[] keyArray) {
long hash = MurmurHash.hashOneLong(k, 47);
bjuvensjo/rsimulator
rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/SocketSimulator.java
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/config/CoreModule.java // public class CoreModule extends AbstractModule { // private final Logger log = LoggerFactory.getLogger(CoreModule.class); // private static final CacheManager cacheManager = CacheManager.create(); // // @Provides // @Named("rsimulator-core-properties") // java.util.Properties provideProperties() { // java.util.Properties properties = new java.util.Properties(); // URL resource = getClass().getResource("/rsimulator.properties"); // if (resource == null) { // properties.setProperty("simulatorCache", "false"); // properties.setProperty("ignoreXmlNamespaces", "false"); // } else { // try (BufferedInputStream bis = new BufferedInputStream(resource.openStream())) { // properties.load(bis); // } catch (Exception e) { // log.error("Error reading properties from: {}", resource.getPath(), e); // } // } // return properties; // } // // @Override // protected void configure() { // MapBinder<String, Handler> map = MapBinder.newMapBinder(binder(), String.class, Handler.class); // map.addBinding("json").to(JsonHandler.class); // map.addBinding("txt").to(TxtHandler.class); // map.addBinding("xml").to(XmlHandler.class); // // // ***** Interceptors for cache and script ***** // Arrays.asList("SimulatorCache", "FileUtilsCache", "PropsCache").forEach(name -> // bind(net.sf.ehcache.Cache.class).annotatedWith(Names.named(name)).toInstance(cacheManager.getCache(name))); // // // SimulatorPropertiesInterceptor simulatorPropertiesInterceptor = new SimulatorPropertiesInterceptor(); // SimulatorCacheInterceptor simulatorCacheInterceptor = new SimulatorCacheInterceptor(); // SimulatorScriptInterceptor simulatorScriptInterceptor = new SimulatorScriptInterceptor(); // FileUtilsCacheInterceptor fileUtilsCacheInterceptor = new FileUtilsCacheInterceptor(); // PropsCacheInterceptor propsCacheInterceptor = new PropsCacheInterceptor(); // // requestInjection(simulatorPropertiesInterceptor); // requestInjection(simulatorCacheInterceptor); // requestInjection(simulatorScriptInterceptor); // requestInjection(fileUtilsCacheInterceptor); // requestInjection(propsCacheInterceptor); // // // Order is significant // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Properties.class), // simulatorPropertiesInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Cache.class), // simulatorCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Script.class), // simulatorScriptInterceptor); // bindInterceptor(Matchers.subclassesOf(FileUtils.class), Matchers.annotatedWith(Cache.class), // fileUtilsCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Props.class), Matchers.annotatedWith(Cache.class), // propsCacheInterceptor); // } // } // // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/GlobalConfig.java // public class GlobalConfig { // public static int port; // public static String rootPath; // public static boolean useRootRelativePath; // // static { // port = System.getProperty(Constants.PORT) != null ? Integer.parseInt(System // .getProperty(Constants.PORT)) : Constants.DEFAULT_PORT; // // rootPath = System.getProperty(Constants.ROOT_PATH) != null ? System.getProperty(Constants.ROOT_PATH) // : Constants.DEFAULT_ROOT_PATH; // // useRootRelativePath = System.getProperty(Constants.USE_ROOT_RELATIVE_PATH) != null && "true".equals(System // .getProperty(Constants.USE_ROOT_RELATIVE_PATH)); // } // // private GlobalConfig() { // // noop // } // } // // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/SocketModule.java // public class SocketModule extends AbstractModule { // // /* // * (non-Javadoc) // * // * @see com.google.inject.AbstractModule#configure() // */ // @Override // protected void configure() { // bind(new TypeLiteral<String>() { // }).annotatedWith(Names.named("simulatorContentType")).toInstance("txt"); // // bind(new TypeLiteral<String>() { // }).annotatedWith(Names.named("encoding")).toInstance("Cp278"); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerLength")).toInstance(48); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerBodyLengthBeginIndex")).toInstance(4); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerBodyLengthEndIndex")).toInstance(8); // } // }
import com.github.bjuvensjo.rsimulator.core.config.CoreModule; import com.github.bjuvensjo.rsimulator.socket.config.GlobalConfig; import com.github.bjuvensjo.rsimulator.socket.config.SocketModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket;
package com.github.bjuvensjo.rsimulator.socket; /** * SocketSimulator. */ public class SocketSimulator { private static final Logger log = LoggerFactory.getLogger(SocketSimulator.class); @Inject private Manager manager; public SocketSimulator() {
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/config/CoreModule.java // public class CoreModule extends AbstractModule { // private final Logger log = LoggerFactory.getLogger(CoreModule.class); // private static final CacheManager cacheManager = CacheManager.create(); // // @Provides // @Named("rsimulator-core-properties") // java.util.Properties provideProperties() { // java.util.Properties properties = new java.util.Properties(); // URL resource = getClass().getResource("/rsimulator.properties"); // if (resource == null) { // properties.setProperty("simulatorCache", "false"); // properties.setProperty("ignoreXmlNamespaces", "false"); // } else { // try (BufferedInputStream bis = new BufferedInputStream(resource.openStream())) { // properties.load(bis); // } catch (Exception e) { // log.error("Error reading properties from: {}", resource.getPath(), e); // } // } // return properties; // } // // @Override // protected void configure() { // MapBinder<String, Handler> map = MapBinder.newMapBinder(binder(), String.class, Handler.class); // map.addBinding("json").to(JsonHandler.class); // map.addBinding("txt").to(TxtHandler.class); // map.addBinding("xml").to(XmlHandler.class); // // // ***** Interceptors for cache and script ***** // Arrays.asList("SimulatorCache", "FileUtilsCache", "PropsCache").forEach(name -> // bind(net.sf.ehcache.Cache.class).annotatedWith(Names.named(name)).toInstance(cacheManager.getCache(name))); // // // SimulatorPropertiesInterceptor simulatorPropertiesInterceptor = new SimulatorPropertiesInterceptor(); // SimulatorCacheInterceptor simulatorCacheInterceptor = new SimulatorCacheInterceptor(); // SimulatorScriptInterceptor simulatorScriptInterceptor = new SimulatorScriptInterceptor(); // FileUtilsCacheInterceptor fileUtilsCacheInterceptor = new FileUtilsCacheInterceptor(); // PropsCacheInterceptor propsCacheInterceptor = new PropsCacheInterceptor(); // // requestInjection(simulatorPropertiesInterceptor); // requestInjection(simulatorCacheInterceptor); // requestInjection(simulatorScriptInterceptor); // requestInjection(fileUtilsCacheInterceptor); // requestInjection(propsCacheInterceptor); // // // Order is significant // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Properties.class), // simulatorPropertiesInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Cache.class), // simulatorCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Script.class), // simulatorScriptInterceptor); // bindInterceptor(Matchers.subclassesOf(FileUtils.class), Matchers.annotatedWith(Cache.class), // fileUtilsCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Props.class), Matchers.annotatedWith(Cache.class), // propsCacheInterceptor); // } // } // // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/GlobalConfig.java // public class GlobalConfig { // public static int port; // public static String rootPath; // public static boolean useRootRelativePath; // // static { // port = System.getProperty(Constants.PORT) != null ? Integer.parseInt(System // .getProperty(Constants.PORT)) : Constants.DEFAULT_PORT; // // rootPath = System.getProperty(Constants.ROOT_PATH) != null ? System.getProperty(Constants.ROOT_PATH) // : Constants.DEFAULT_ROOT_PATH; // // useRootRelativePath = System.getProperty(Constants.USE_ROOT_RELATIVE_PATH) != null && "true".equals(System // .getProperty(Constants.USE_ROOT_RELATIVE_PATH)); // } // // private GlobalConfig() { // // noop // } // } // // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/SocketModule.java // public class SocketModule extends AbstractModule { // // /* // * (non-Javadoc) // * // * @see com.google.inject.AbstractModule#configure() // */ // @Override // protected void configure() { // bind(new TypeLiteral<String>() { // }).annotatedWith(Names.named("simulatorContentType")).toInstance("txt"); // // bind(new TypeLiteral<String>() { // }).annotatedWith(Names.named("encoding")).toInstance("Cp278"); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerLength")).toInstance(48); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerBodyLengthBeginIndex")).toInstance(4); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerBodyLengthEndIndex")).toInstance(8); // } // } // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/SocketSimulator.java import com.github.bjuvensjo.rsimulator.core.config.CoreModule; import com.github.bjuvensjo.rsimulator.socket.config.GlobalConfig; import com.github.bjuvensjo.rsimulator.socket.config.SocketModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; package com.github.bjuvensjo.rsimulator.socket; /** * SocketSimulator. */ public class SocketSimulator { private static final Logger log = LoggerFactory.getLogger(SocketSimulator.class); @Inject private Manager manager; public SocketSimulator() {
Injector injector = Guice.createInjector(new CoreModule(), new SocketModule());
bjuvensjo/rsimulator
rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/SocketSimulator.java
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/config/CoreModule.java // public class CoreModule extends AbstractModule { // private final Logger log = LoggerFactory.getLogger(CoreModule.class); // private static final CacheManager cacheManager = CacheManager.create(); // // @Provides // @Named("rsimulator-core-properties") // java.util.Properties provideProperties() { // java.util.Properties properties = new java.util.Properties(); // URL resource = getClass().getResource("/rsimulator.properties"); // if (resource == null) { // properties.setProperty("simulatorCache", "false"); // properties.setProperty("ignoreXmlNamespaces", "false"); // } else { // try (BufferedInputStream bis = new BufferedInputStream(resource.openStream())) { // properties.load(bis); // } catch (Exception e) { // log.error("Error reading properties from: {}", resource.getPath(), e); // } // } // return properties; // } // // @Override // protected void configure() { // MapBinder<String, Handler> map = MapBinder.newMapBinder(binder(), String.class, Handler.class); // map.addBinding("json").to(JsonHandler.class); // map.addBinding("txt").to(TxtHandler.class); // map.addBinding("xml").to(XmlHandler.class); // // // ***** Interceptors for cache and script ***** // Arrays.asList("SimulatorCache", "FileUtilsCache", "PropsCache").forEach(name -> // bind(net.sf.ehcache.Cache.class).annotatedWith(Names.named(name)).toInstance(cacheManager.getCache(name))); // // // SimulatorPropertiesInterceptor simulatorPropertiesInterceptor = new SimulatorPropertiesInterceptor(); // SimulatorCacheInterceptor simulatorCacheInterceptor = new SimulatorCacheInterceptor(); // SimulatorScriptInterceptor simulatorScriptInterceptor = new SimulatorScriptInterceptor(); // FileUtilsCacheInterceptor fileUtilsCacheInterceptor = new FileUtilsCacheInterceptor(); // PropsCacheInterceptor propsCacheInterceptor = new PropsCacheInterceptor(); // // requestInjection(simulatorPropertiesInterceptor); // requestInjection(simulatorCacheInterceptor); // requestInjection(simulatorScriptInterceptor); // requestInjection(fileUtilsCacheInterceptor); // requestInjection(propsCacheInterceptor); // // // Order is significant // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Properties.class), // simulatorPropertiesInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Cache.class), // simulatorCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Script.class), // simulatorScriptInterceptor); // bindInterceptor(Matchers.subclassesOf(FileUtils.class), Matchers.annotatedWith(Cache.class), // fileUtilsCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Props.class), Matchers.annotatedWith(Cache.class), // propsCacheInterceptor); // } // } // // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/GlobalConfig.java // public class GlobalConfig { // public static int port; // public static String rootPath; // public static boolean useRootRelativePath; // // static { // port = System.getProperty(Constants.PORT) != null ? Integer.parseInt(System // .getProperty(Constants.PORT)) : Constants.DEFAULT_PORT; // // rootPath = System.getProperty(Constants.ROOT_PATH) != null ? System.getProperty(Constants.ROOT_PATH) // : Constants.DEFAULT_ROOT_PATH; // // useRootRelativePath = System.getProperty(Constants.USE_ROOT_RELATIVE_PATH) != null && "true".equals(System // .getProperty(Constants.USE_ROOT_RELATIVE_PATH)); // } // // private GlobalConfig() { // // noop // } // } // // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/SocketModule.java // public class SocketModule extends AbstractModule { // // /* // * (non-Javadoc) // * // * @see com.google.inject.AbstractModule#configure() // */ // @Override // protected void configure() { // bind(new TypeLiteral<String>() { // }).annotatedWith(Names.named("simulatorContentType")).toInstance("txt"); // // bind(new TypeLiteral<String>() { // }).annotatedWith(Names.named("encoding")).toInstance("Cp278"); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerLength")).toInstance(48); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerBodyLengthBeginIndex")).toInstance(4); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerBodyLengthEndIndex")).toInstance(8); // } // }
import com.github.bjuvensjo.rsimulator.core.config.CoreModule; import com.github.bjuvensjo.rsimulator.socket.config.GlobalConfig; import com.github.bjuvensjo.rsimulator.socket.config.SocketModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket;
package com.github.bjuvensjo.rsimulator.socket; /** * SocketSimulator. */ public class SocketSimulator { private static final Logger log = LoggerFactory.getLogger(SocketSimulator.class); @Inject private Manager manager; public SocketSimulator() {
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/config/CoreModule.java // public class CoreModule extends AbstractModule { // private final Logger log = LoggerFactory.getLogger(CoreModule.class); // private static final CacheManager cacheManager = CacheManager.create(); // // @Provides // @Named("rsimulator-core-properties") // java.util.Properties provideProperties() { // java.util.Properties properties = new java.util.Properties(); // URL resource = getClass().getResource("/rsimulator.properties"); // if (resource == null) { // properties.setProperty("simulatorCache", "false"); // properties.setProperty("ignoreXmlNamespaces", "false"); // } else { // try (BufferedInputStream bis = new BufferedInputStream(resource.openStream())) { // properties.load(bis); // } catch (Exception e) { // log.error("Error reading properties from: {}", resource.getPath(), e); // } // } // return properties; // } // // @Override // protected void configure() { // MapBinder<String, Handler> map = MapBinder.newMapBinder(binder(), String.class, Handler.class); // map.addBinding("json").to(JsonHandler.class); // map.addBinding("txt").to(TxtHandler.class); // map.addBinding("xml").to(XmlHandler.class); // // // ***** Interceptors for cache and script ***** // Arrays.asList("SimulatorCache", "FileUtilsCache", "PropsCache").forEach(name -> // bind(net.sf.ehcache.Cache.class).annotatedWith(Names.named(name)).toInstance(cacheManager.getCache(name))); // // // SimulatorPropertiesInterceptor simulatorPropertiesInterceptor = new SimulatorPropertiesInterceptor(); // SimulatorCacheInterceptor simulatorCacheInterceptor = new SimulatorCacheInterceptor(); // SimulatorScriptInterceptor simulatorScriptInterceptor = new SimulatorScriptInterceptor(); // FileUtilsCacheInterceptor fileUtilsCacheInterceptor = new FileUtilsCacheInterceptor(); // PropsCacheInterceptor propsCacheInterceptor = new PropsCacheInterceptor(); // // requestInjection(simulatorPropertiesInterceptor); // requestInjection(simulatorCacheInterceptor); // requestInjection(simulatorScriptInterceptor); // requestInjection(fileUtilsCacheInterceptor); // requestInjection(propsCacheInterceptor); // // // Order is significant // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Properties.class), // simulatorPropertiesInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Cache.class), // simulatorCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Script.class), // simulatorScriptInterceptor); // bindInterceptor(Matchers.subclassesOf(FileUtils.class), Matchers.annotatedWith(Cache.class), // fileUtilsCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Props.class), Matchers.annotatedWith(Cache.class), // propsCacheInterceptor); // } // } // // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/GlobalConfig.java // public class GlobalConfig { // public static int port; // public static String rootPath; // public static boolean useRootRelativePath; // // static { // port = System.getProperty(Constants.PORT) != null ? Integer.parseInt(System // .getProperty(Constants.PORT)) : Constants.DEFAULT_PORT; // // rootPath = System.getProperty(Constants.ROOT_PATH) != null ? System.getProperty(Constants.ROOT_PATH) // : Constants.DEFAULT_ROOT_PATH; // // useRootRelativePath = System.getProperty(Constants.USE_ROOT_RELATIVE_PATH) != null && "true".equals(System // .getProperty(Constants.USE_ROOT_RELATIVE_PATH)); // } // // private GlobalConfig() { // // noop // } // } // // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/SocketModule.java // public class SocketModule extends AbstractModule { // // /* // * (non-Javadoc) // * // * @see com.google.inject.AbstractModule#configure() // */ // @Override // protected void configure() { // bind(new TypeLiteral<String>() { // }).annotatedWith(Names.named("simulatorContentType")).toInstance("txt"); // // bind(new TypeLiteral<String>() { // }).annotatedWith(Names.named("encoding")).toInstance("Cp278"); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerLength")).toInstance(48); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerBodyLengthBeginIndex")).toInstance(4); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerBodyLengthEndIndex")).toInstance(8); // } // } // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/SocketSimulator.java import com.github.bjuvensjo.rsimulator.core.config.CoreModule; import com.github.bjuvensjo.rsimulator.socket.config.GlobalConfig; import com.github.bjuvensjo.rsimulator.socket.config.SocketModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; package com.github.bjuvensjo.rsimulator.socket; /** * SocketSimulator. */ public class SocketSimulator { private static final Logger log = LoggerFactory.getLogger(SocketSimulator.class); @Inject private Manager manager; public SocketSimulator() {
Injector injector = Guice.createInjector(new CoreModule(), new SocketModule());
bjuvensjo/rsimulator
rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/SocketSimulator.java
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/config/CoreModule.java // public class CoreModule extends AbstractModule { // private final Logger log = LoggerFactory.getLogger(CoreModule.class); // private static final CacheManager cacheManager = CacheManager.create(); // // @Provides // @Named("rsimulator-core-properties") // java.util.Properties provideProperties() { // java.util.Properties properties = new java.util.Properties(); // URL resource = getClass().getResource("/rsimulator.properties"); // if (resource == null) { // properties.setProperty("simulatorCache", "false"); // properties.setProperty("ignoreXmlNamespaces", "false"); // } else { // try (BufferedInputStream bis = new BufferedInputStream(resource.openStream())) { // properties.load(bis); // } catch (Exception e) { // log.error("Error reading properties from: {}", resource.getPath(), e); // } // } // return properties; // } // // @Override // protected void configure() { // MapBinder<String, Handler> map = MapBinder.newMapBinder(binder(), String.class, Handler.class); // map.addBinding("json").to(JsonHandler.class); // map.addBinding("txt").to(TxtHandler.class); // map.addBinding("xml").to(XmlHandler.class); // // // ***** Interceptors for cache and script ***** // Arrays.asList("SimulatorCache", "FileUtilsCache", "PropsCache").forEach(name -> // bind(net.sf.ehcache.Cache.class).annotatedWith(Names.named(name)).toInstance(cacheManager.getCache(name))); // // // SimulatorPropertiesInterceptor simulatorPropertiesInterceptor = new SimulatorPropertiesInterceptor(); // SimulatorCacheInterceptor simulatorCacheInterceptor = new SimulatorCacheInterceptor(); // SimulatorScriptInterceptor simulatorScriptInterceptor = new SimulatorScriptInterceptor(); // FileUtilsCacheInterceptor fileUtilsCacheInterceptor = new FileUtilsCacheInterceptor(); // PropsCacheInterceptor propsCacheInterceptor = new PropsCacheInterceptor(); // // requestInjection(simulatorPropertiesInterceptor); // requestInjection(simulatorCacheInterceptor); // requestInjection(simulatorScriptInterceptor); // requestInjection(fileUtilsCacheInterceptor); // requestInjection(propsCacheInterceptor); // // // Order is significant // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Properties.class), // simulatorPropertiesInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Cache.class), // simulatorCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Script.class), // simulatorScriptInterceptor); // bindInterceptor(Matchers.subclassesOf(FileUtils.class), Matchers.annotatedWith(Cache.class), // fileUtilsCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Props.class), Matchers.annotatedWith(Cache.class), // propsCacheInterceptor); // } // } // // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/GlobalConfig.java // public class GlobalConfig { // public static int port; // public static String rootPath; // public static boolean useRootRelativePath; // // static { // port = System.getProperty(Constants.PORT) != null ? Integer.parseInt(System // .getProperty(Constants.PORT)) : Constants.DEFAULT_PORT; // // rootPath = System.getProperty(Constants.ROOT_PATH) != null ? System.getProperty(Constants.ROOT_PATH) // : Constants.DEFAULT_ROOT_PATH; // // useRootRelativePath = System.getProperty(Constants.USE_ROOT_RELATIVE_PATH) != null && "true".equals(System // .getProperty(Constants.USE_ROOT_RELATIVE_PATH)); // } // // private GlobalConfig() { // // noop // } // } // // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/SocketModule.java // public class SocketModule extends AbstractModule { // // /* // * (non-Javadoc) // * // * @see com.google.inject.AbstractModule#configure() // */ // @Override // protected void configure() { // bind(new TypeLiteral<String>() { // }).annotatedWith(Names.named("simulatorContentType")).toInstance("txt"); // // bind(new TypeLiteral<String>() { // }).annotatedWith(Names.named("encoding")).toInstance("Cp278"); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerLength")).toInstance(48); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerBodyLengthBeginIndex")).toInstance(4); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerBodyLengthEndIndex")).toInstance(8); // } // }
import com.github.bjuvensjo.rsimulator.core.config.CoreModule; import com.github.bjuvensjo.rsimulator.socket.config.GlobalConfig; import com.github.bjuvensjo.rsimulator.socket.config.SocketModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket;
package com.github.bjuvensjo.rsimulator.socket; /** * SocketSimulator. */ public class SocketSimulator { private static final Logger log = LoggerFactory.getLogger(SocketSimulator.class); @Inject private Manager manager; public SocketSimulator() { Injector injector = Guice.createInjector(new CoreModule(), new SocketModule()); injector.injectMembers(this); run(); } private void run() { try {
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/config/CoreModule.java // public class CoreModule extends AbstractModule { // private final Logger log = LoggerFactory.getLogger(CoreModule.class); // private static final CacheManager cacheManager = CacheManager.create(); // // @Provides // @Named("rsimulator-core-properties") // java.util.Properties provideProperties() { // java.util.Properties properties = new java.util.Properties(); // URL resource = getClass().getResource("/rsimulator.properties"); // if (resource == null) { // properties.setProperty("simulatorCache", "false"); // properties.setProperty("ignoreXmlNamespaces", "false"); // } else { // try (BufferedInputStream bis = new BufferedInputStream(resource.openStream())) { // properties.load(bis); // } catch (Exception e) { // log.error("Error reading properties from: {}", resource.getPath(), e); // } // } // return properties; // } // // @Override // protected void configure() { // MapBinder<String, Handler> map = MapBinder.newMapBinder(binder(), String.class, Handler.class); // map.addBinding("json").to(JsonHandler.class); // map.addBinding("txt").to(TxtHandler.class); // map.addBinding("xml").to(XmlHandler.class); // // // ***** Interceptors for cache and script ***** // Arrays.asList("SimulatorCache", "FileUtilsCache", "PropsCache").forEach(name -> // bind(net.sf.ehcache.Cache.class).annotatedWith(Names.named(name)).toInstance(cacheManager.getCache(name))); // // // SimulatorPropertiesInterceptor simulatorPropertiesInterceptor = new SimulatorPropertiesInterceptor(); // SimulatorCacheInterceptor simulatorCacheInterceptor = new SimulatorCacheInterceptor(); // SimulatorScriptInterceptor simulatorScriptInterceptor = new SimulatorScriptInterceptor(); // FileUtilsCacheInterceptor fileUtilsCacheInterceptor = new FileUtilsCacheInterceptor(); // PropsCacheInterceptor propsCacheInterceptor = new PropsCacheInterceptor(); // // requestInjection(simulatorPropertiesInterceptor); // requestInjection(simulatorCacheInterceptor); // requestInjection(simulatorScriptInterceptor); // requestInjection(fileUtilsCacheInterceptor); // requestInjection(propsCacheInterceptor); // // // Order is significant // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Properties.class), // simulatorPropertiesInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Cache.class), // simulatorCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Script.class), // simulatorScriptInterceptor); // bindInterceptor(Matchers.subclassesOf(FileUtils.class), Matchers.annotatedWith(Cache.class), // fileUtilsCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Props.class), Matchers.annotatedWith(Cache.class), // propsCacheInterceptor); // } // } // // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/GlobalConfig.java // public class GlobalConfig { // public static int port; // public static String rootPath; // public static boolean useRootRelativePath; // // static { // port = System.getProperty(Constants.PORT) != null ? Integer.parseInt(System // .getProperty(Constants.PORT)) : Constants.DEFAULT_PORT; // // rootPath = System.getProperty(Constants.ROOT_PATH) != null ? System.getProperty(Constants.ROOT_PATH) // : Constants.DEFAULT_ROOT_PATH; // // useRootRelativePath = System.getProperty(Constants.USE_ROOT_RELATIVE_PATH) != null && "true".equals(System // .getProperty(Constants.USE_ROOT_RELATIVE_PATH)); // } // // private GlobalConfig() { // // noop // } // } // // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/SocketModule.java // public class SocketModule extends AbstractModule { // // /* // * (non-Javadoc) // * // * @see com.google.inject.AbstractModule#configure() // */ // @Override // protected void configure() { // bind(new TypeLiteral<String>() { // }).annotatedWith(Names.named("simulatorContentType")).toInstance("txt"); // // bind(new TypeLiteral<String>() { // }).annotatedWith(Names.named("encoding")).toInstance("Cp278"); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerLength")).toInstance(48); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerBodyLengthBeginIndex")).toInstance(4); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerBodyLengthEndIndex")).toInstance(8); // } // } // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/SocketSimulator.java import com.github.bjuvensjo.rsimulator.core.config.CoreModule; import com.github.bjuvensjo.rsimulator.socket.config.GlobalConfig; import com.github.bjuvensjo.rsimulator.socket.config.SocketModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; package com.github.bjuvensjo.rsimulator.socket; /** * SocketSimulator. */ public class SocketSimulator { private static final Logger log = LoggerFactory.getLogger(SocketSimulator.class); @Inject private Manager manager; public SocketSimulator() { Injector injector = Guice.createInjector(new CoreModule(), new SocketModule()); injector.injectMembers(this); run(); } private void run() { try {
int port = GlobalConfig.port;
bjuvensjo/rsimulator
rsimulator-socket/src/test/java/com/github/bjuvensjo/rsimulator/socket/SocketSimulatorIT.java
// Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/GlobalConfig.java // public class GlobalConfig { // public static int port; // public static String rootPath; // public static boolean useRootRelativePath; // // static { // port = System.getProperty(Constants.PORT) != null ? Integer.parseInt(System // .getProperty(Constants.PORT)) : Constants.DEFAULT_PORT; // // rootPath = System.getProperty(Constants.ROOT_PATH) != null ? System.getProperty(Constants.ROOT_PATH) // : Constants.DEFAULT_ROOT_PATH; // // useRootRelativePath = System.getProperty(Constants.USE_ROOT_RELATIVE_PATH) != null && "true".equals(System // .getProperty(Constants.USE_ROOT_RELATIVE_PATH)); // } // // private GlobalConfig() { // // noop // } // } // // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/SocketModule.java // public class SocketModule extends AbstractModule { // // /* // * (non-Javadoc) // * // * @see com.google.inject.AbstractModule#configure() // */ // @Override // protected void configure() { // bind(new TypeLiteral<String>() { // }).annotatedWith(Names.named("simulatorContentType")).toInstance("txt"); // // bind(new TypeLiteral<String>() { // }).annotatedWith(Names.named("encoding")).toInstance("Cp278"); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerLength")).toInstance(48); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerBodyLengthBeginIndex")).toInstance(4); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerBodyLengthEndIndex")).toInstance(8); // } // }
import com.github.bjuvensjo.rsimulator.socket.config.GlobalConfig; import com.github.bjuvensjo.rsimulator.socket.config.SocketModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.name.Named; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import static org.junit.jupiter.api.Assertions.assertEquals;
package com.github.bjuvensjo.rsimulator.socket; public class SocketSimulatorIT { @Inject @Named("encoding") private String encoding; @BeforeEach public void init() {
// Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/GlobalConfig.java // public class GlobalConfig { // public static int port; // public static String rootPath; // public static boolean useRootRelativePath; // // static { // port = System.getProperty(Constants.PORT) != null ? Integer.parseInt(System // .getProperty(Constants.PORT)) : Constants.DEFAULT_PORT; // // rootPath = System.getProperty(Constants.ROOT_PATH) != null ? System.getProperty(Constants.ROOT_PATH) // : Constants.DEFAULT_ROOT_PATH; // // useRootRelativePath = System.getProperty(Constants.USE_ROOT_RELATIVE_PATH) != null && "true".equals(System // .getProperty(Constants.USE_ROOT_RELATIVE_PATH)); // } // // private GlobalConfig() { // // noop // } // } // // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/SocketModule.java // public class SocketModule extends AbstractModule { // // /* // * (non-Javadoc) // * // * @see com.google.inject.AbstractModule#configure() // */ // @Override // protected void configure() { // bind(new TypeLiteral<String>() { // }).annotatedWith(Names.named("simulatorContentType")).toInstance("txt"); // // bind(new TypeLiteral<String>() { // }).annotatedWith(Names.named("encoding")).toInstance("Cp278"); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerLength")).toInstance(48); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerBodyLengthBeginIndex")).toInstance(4); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerBodyLengthEndIndex")).toInstance(8); // } // } // Path: rsimulator-socket/src/test/java/com/github/bjuvensjo/rsimulator/socket/SocketSimulatorIT.java import com.github.bjuvensjo.rsimulator.socket.config.GlobalConfig; import com.github.bjuvensjo.rsimulator.socket.config.SocketModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.name.Named; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import static org.junit.jupiter.api.Assertions.assertEquals; package com.github.bjuvensjo.rsimulator.socket; public class SocketSimulatorIT { @Inject @Named("encoding") private String encoding; @BeforeEach public void init() {
Injector injector = Guice.createInjector(new SocketModule());
bjuvensjo/rsimulator
rsimulator-socket/src/test/java/com/github/bjuvensjo/rsimulator/socket/SocketSimulatorIT.java
// Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/GlobalConfig.java // public class GlobalConfig { // public static int port; // public static String rootPath; // public static boolean useRootRelativePath; // // static { // port = System.getProperty(Constants.PORT) != null ? Integer.parseInt(System // .getProperty(Constants.PORT)) : Constants.DEFAULT_PORT; // // rootPath = System.getProperty(Constants.ROOT_PATH) != null ? System.getProperty(Constants.ROOT_PATH) // : Constants.DEFAULT_ROOT_PATH; // // useRootRelativePath = System.getProperty(Constants.USE_ROOT_RELATIVE_PATH) != null && "true".equals(System // .getProperty(Constants.USE_ROOT_RELATIVE_PATH)); // } // // private GlobalConfig() { // // noop // } // } // // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/SocketModule.java // public class SocketModule extends AbstractModule { // // /* // * (non-Javadoc) // * // * @see com.google.inject.AbstractModule#configure() // */ // @Override // protected void configure() { // bind(new TypeLiteral<String>() { // }).annotatedWith(Names.named("simulatorContentType")).toInstance("txt"); // // bind(new TypeLiteral<String>() { // }).annotatedWith(Names.named("encoding")).toInstance("Cp278"); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerLength")).toInstance(48); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerBodyLengthBeginIndex")).toInstance(4); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerBodyLengthEndIndex")).toInstance(8); // } // }
import com.github.bjuvensjo.rsimulator.socket.config.GlobalConfig; import com.github.bjuvensjo.rsimulator.socket.config.SocketModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.name.Named; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import static org.junit.jupiter.api.Assertions.assertEquals;
package com.github.bjuvensjo.rsimulator.socket; public class SocketSimulatorIT { @Inject @Named("encoding") private String encoding; @BeforeEach public void init() { Injector injector = Guice.createInjector(new SocketModule()); injector.injectMembers(this); } @Disabled @Test public void test() { String header = " 00061234 "; String body = "123ABC"; String expected = "123AAAAAAAAAABBBBBBBBBBCCCCCCCCCCDDDDDDDDDDEEEEEEEEEE"; try {
// Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/GlobalConfig.java // public class GlobalConfig { // public static int port; // public static String rootPath; // public static boolean useRootRelativePath; // // static { // port = System.getProperty(Constants.PORT) != null ? Integer.parseInt(System // .getProperty(Constants.PORT)) : Constants.DEFAULT_PORT; // // rootPath = System.getProperty(Constants.ROOT_PATH) != null ? System.getProperty(Constants.ROOT_PATH) // : Constants.DEFAULT_ROOT_PATH; // // useRootRelativePath = System.getProperty(Constants.USE_ROOT_RELATIVE_PATH) != null && "true".equals(System // .getProperty(Constants.USE_ROOT_RELATIVE_PATH)); // } // // private GlobalConfig() { // // noop // } // } // // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/SocketModule.java // public class SocketModule extends AbstractModule { // // /* // * (non-Javadoc) // * // * @see com.google.inject.AbstractModule#configure() // */ // @Override // protected void configure() { // bind(new TypeLiteral<String>() { // }).annotatedWith(Names.named("simulatorContentType")).toInstance("txt"); // // bind(new TypeLiteral<String>() { // }).annotatedWith(Names.named("encoding")).toInstance("Cp278"); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerLength")).toInstance(48); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerBodyLengthBeginIndex")).toInstance(4); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerBodyLengthEndIndex")).toInstance(8); // } // } // Path: rsimulator-socket/src/test/java/com/github/bjuvensjo/rsimulator/socket/SocketSimulatorIT.java import com.github.bjuvensjo.rsimulator.socket.config.GlobalConfig; import com.github.bjuvensjo.rsimulator.socket.config.SocketModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.name.Named; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import static org.junit.jupiter.api.Assertions.assertEquals; package com.github.bjuvensjo.rsimulator.socket; public class SocketSimulatorIT { @Inject @Named("encoding") private String encoding; @BeforeEach public void init() { Injector injector = Guice.createInjector(new SocketModule()); injector.injectMembers(this); } @Disabled @Test public void test() { String header = " 00061234 "; String body = "123ABC"; String expected = "123AAAAAAAAAABBBBBBBBBBCCCCCCCCCCDDDDDDDDDDEEEEEEEEEE"; try {
Socket s = new Socket("localhost", GlobalConfig.port);
bjuvensjo/rsimulator
rsimulator-socket/src/test/java/com/github/bjuvensjo/rsimulator/socket/RequestReaderTest.java
// Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/SocketModule.java // public class SocketModule extends AbstractModule { // // /* // * (non-Javadoc) // * // * @see com.google.inject.AbstractModule#configure() // */ // @Override // protected void configure() { // bind(new TypeLiteral<String>() { // }).annotatedWith(Names.named("simulatorContentType")).toInstance("txt"); // // bind(new TypeLiteral<String>() { // }).annotatedWith(Names.named("encoding")).toInstance("Cp278"); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerLength")).toInstance(48); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerBodyLengthBeginIndex")).toInstance(4); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerBodyLengthEndIndex")).toInstance(8); // } // }
import com.github.bjuvensjo.rsimulator.socket.config.SocketModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.name.Named; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import static org.apache.commons.lang.StringUtils.leftPad; import static org.apache.commons.lang.StringUtils.rightPad; import static org.junit.jupiter.api.Assertions.assertEquals;
package com.github.bjuvensjo.rsimulator.socket; public class RequestReaderTest { @Inject @Named("encoding") private String encoding; @Inject @Named("headerLength") private int headerLength; @Inject @Named("headerBodyLengthBeginIndex") private int headerBodyLengthBeginIndex; @Inject @Named("headerBodyLengthEndIndex") private int headerBodyLengthEndIndex; @Inject private RequestReader requestReader; @BeforeEach public void init() {
// Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/SocketModule.java // public class SocketModule extends AbstractModule { // // /* // * (non-Javadoc) // * // * @see com.google.inject.AbstractModule#configure() // */ // @Override // protected void configure() { // bind(new TypeLiteral<String>() { // }).annotatedWith(Names.named("simulatorContentType")).toInstance("txt"); // // bind(new TypeLiteral<String>() { // }).annotatedWith(Names.named("encoding")).toInstance("Cp278"); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerLength")).toInstance(48); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerBodyLengthBeginIndex")).toInstance(4); // // bind(new TypeLiteral<Integer>() { // }).annotatedWith(Names.named("headerBodyLengthEndIndex")).toInstance(8); // } // } // Path: rsimulator-socket/src/test/java/com/github/bjuvensjo/rsimulator/socket/RequestReaderTest.java import com.github.bjuvensjo.rsimulator.socket.config.SocketModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.name.Named; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import static org.apache.commons.lang.StringUtils.leftPad; import static org.apache.commons.lang.StringUtils.rightPad; import static org.junit.jupiter.api.Assertions.assertEquals; package com.github.bjuvensjo.rsimulator.socket; public class RequestReaderTest { @Inject @Named("encoding") private String encoding; @Inject @Named("headerLength") private int headerLength; @Inject @Named("headerBodyLengthBeginIndex") private int headerBodyLengthBeginIndex; @Inject @Named("headerBodyLengthEndIndex") private int headerBodyLengthEndIndex; @Inject private RequestReader requestReader; @BeforeEach public void init() {
Injector injector = Guice.createInjector(new SocketModule());
bjuvensjo/rsimulator
rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/Manager.java
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/Simulator.java // @ImplementedBy(SimulatorImpl.class) // public interface Simulator { // // /** // * Returns a SimulatorResponse that matches the specified request. // * // * @param rootPath the root path on which to search recursively for matches to the specified request // * @param rootRelativePath the path on which to search recursively for matches to the specified request // * @param request the request // * @param contentType the content type of the request, e.g. txt or xml // * @param vars vars that can be used in for example scripts // * @return a SimulatorResponse that matches the specified request // */ // Optional<SimulatorResponse> service(String rootPath, String rootRelativePath, String request, String contentType, Map<String, Object>... vars); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // } // // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/GlobalConfig.java // public class GlobalConfig { // public static int port; // public static String rootPath; // public static boolean useRootRelativePath; // // static { // port = System.getProperty(Constants.PORT) != null ? Integer.parseInt(System // .getProperty(Constants.PORT)) : Constants.DEFAULT_PORT; // // rootPath = System.getProperty(Constants.ROOT_PATH) != null ? System.getProperty(Constants.ROOT_PATH) // : Constants.DEFAULT_ROOT_PATH; // // useRootRelativePath = System.getProperty(Constants.USE_ROOT_RELATIVE_PATH) != null && "true".equals(System // .getProperty(Constants.USE_ROOT_RELATIVE_PATH)); // } // // private GlobalConfig() { // // noop // } // }
import com.github.bjuvensjo.rsimulator.core.Simulator; import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import com.github.bjuvensjo.rsimulator.socket.config.GlobalConfig; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.util.Optional;
package com.github.bjuvensjo.rsimulator.socket; /** * Manager */ @Singleton public class Manager { @Inject private RequestReader requestReader; @Inject private ResponseWriter responseWriter; @Inject
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/Simulator.java // @ImplementedBy(SimulatorImpl.class) // public interface Simulator { // // /** // * Returns a SimulatorResponse that matches the specified request. // * // * @param rootPath the root path on which to search recursively for matches to the specified request // * @param rootRelativePath the path on which to search recursively for matches to the specified request // * @param request the request // * @param contentType the content type of the request, e.g. txt or xml // * @param vars vars that can be used in for example scripts // * @return a SimulatorResponse that matches the specified request // */ // Optional<SimulatorResponse> service(String rootPath, String rootRelativePath, String request, String contentType, Map<String, Object>... vars); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // } // // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/GlobalConfig.java // public class GlobalConfig { // public static int port; // public static String rootPath; // public static boolean useRootRelativePath; // // static { // port = System.getProperty(Constants.PORT) != null ? Integer.parseInt(System // .getProperty(Constants.PORT)) : Constants.DEFAULT_PORT; // // rootPath = System.getProperty(Constants.ROOT_PATH) != null ? System.getProperty(Constants.ROOT_PATH) // : Constants.DEFAULT_ROOT_PATH; // // useRootRelativePath = System.getProperty(Constants.USE_ROOT_RELATIVE_PATH) != null && "true".equals(System // .getProperty(Constants.USE_ROOT_RELATIVE_PATH)); // } // // private GlobalConfig() { // // noop // } // } // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/Manager.java import com.github.bjuvensjo.rsimulator.core.Simulator; import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import com.github.bjuvensjo.rsimulator.socket.config.GlobalConfig; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.util.Optional; package com.github.bjuvensjo.rsimulator.socket; /** * Manager */ @Singleton public class Manager { @Inject private RequestReader requestReader; @Inject private ResponseWriter responseWriter; @Inject
private Simulator simulator;
bjuvensjo/rsimulator
rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/Manager.java
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/Simulator.java // @ImplementedBy(SimulatorImpl.class) // public interface Simulator { // // /** // * Returns a SimulatorResponse that matches the specified request. // * // * @param rootPath the root path on which to search recursively for matches to the specified request // * @param rootRelativePath the path on which to search recursively for matches to the specified request // * @param request the request // * @param contentType the content type of the request, e.g. txt or xml // * @param vars vars that can be used in for example scripts // * @return a SimulatorResponse that matches the specified request // */ // Optional<SimulatorResponse> service(String rootPath, String rootRelativePath, String request, String contentType, Map<String, Object>... vars); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // } // // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/GlobalConfig.java // public class GlobalConfig { // public static int port; // public static String rootPath; // public static boolean useRootRelativePath; // // static { // port = System.getProperty(Constants.PORT) != null ? Integer.parseInt(System // .getProperty(Constants.PORT)) : Constants.DEFAULT_PORT; // // rootPath = System.getProperty(Constants.ROOT_PATH) != null ? System.getProperty(Constants.ROOT_PATH) // : Constants.DEFAULT_ROOT_PATH; // // useRootRelativePath = System.getProperty(Constants.USE_ROOT_RELATIVE_PATH) != null && "true".equals(System // .getProperty(Constants.USE_ROOT_RELATIVE_PATH)); // } // // private GlobalConfig() { // // noop // } // }
import com.github.bjuvensjo.rsimulator.core.Simulator; import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import com.github.bjuvensjo.rsimulator.socket.config.GlobalConfig; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.util.Optional;
package com.github.bjuvensjo.rsimulator.socket; /** * Manager */ @Singleton public class Manager { @Inject private RequestReader requestReader; @Inject private ResponseWriter responseWriter; @Inject private Simulator simulator; @Inject @Named("simulatorContentType") private String simulatorContentType; public void handle(Socket s) throws IOException { Worker worker = new Worker(s); new Thread(worker).start(); } class Worker implements Runnable { private final Logger log = LoggerFactory.getLogger(Worker.class); private final Socket s; public Worker(Socket s) throws IOException { this.s = s; } private RequestReader.Request read(InputStream in) throws IOException { return requestReader.read(in); }
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/Simulator.java // @ImplementedBy(SimulatorImpl.class) // public interface Simulator { // // /** // * Returns a SimulatorResponse that matches the specified request. // * // * @param rootPath the root path on which to search recursively for matches to the specified request // * @param rootRelativePath the path on which to search recursively for matches to the specified request // * @param request the request // * @param contentType the content type of the request, e.g. txt or xml // * @param vars vars that can be used in for example scripts // * @return a SimulatorResponse that matches the specified request // */ // Optional<SimulatorResponse> service(String rootPath, String rootRelativePath, String request, String contentType, Map<String, Object>... vars); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // } // // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/GlobalConfig.java // public class GlobalConfig { // public static int port; // public static String rootPath; // public static boolean useRootRelativePath; // // static { // port = System.getProperty(Constants.PORT) != null ? Integer.parseInt(System // .getProperty(Constants.PORT)) : Constants.DEFAULT_PORT; // // rootPath = System.getProperty(Constants.ROOT_PATH) != null ? System.getProperty(Constants.ROOT_PATH) // : Constants.DEFAULT_ROOT_PATH; // // useRootRelativePath = System.getProperty(Constants.USE_ROOT_RELATIVE_PATH) != null && "true".equals(System // .getProperty(Constants.USE_ROOT_RELATIVE_PATH)); // } // // private GlobalConfig() { // // noop // } // } // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/Manager.java import com.github.bjuvensjo.rsimulator.core.Simulator; import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import com.github.bjuvensjo.rsimulator.socket.config.GlobalConfig; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.util.Optional; package com.github.bjuvensjo.rsimulator.socket; /** * Manager */ @Singleton public class Manager { @Inject private RequestReader requestReader; @Inject private ResponseWriter responseWriter; @Inject private Simulator simulator; @Inject @Named("simulatorContentType") private String simulatorContentType; public void handle(Socket s) throws IOException { Worker worker = new Worker(s); new Thread(worker).start(); } class Worker implements Runnable { private final Logger log = LoggerFactory.getLogger(Worker.class); private final Socket s; public Worker(Socket s) throws IOException { this.s = s; } private RequestReader.Request read(InputStream in) throws IOException { return requestReader.read(in); }
private void write(RequestReader.Request request, SimulatorResponse simulatorResponse, OutputStream out) throws IOException {
bjuvensjo/rsimulator
rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/Manager.java
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/Simulator.java // @ImplementedBy(SimulatorImpl.class) // public interface Simulator { // // /** // * Returns a SimulatorResponse that matches the specified request. // * // * @param rootPath the root path on which to search recursively for matches to the specified request // * @param rootRelativePath the path on which to search recursively for matches to the specified request // * @param request the request // * @param contentType the content type of the request, e.g. txt or xml // * @param vars vars that can be used in for example scripts // * @return a SimulatorResponse that matches the specified request // */ // Optional<SimulatorResponse> service(String rootPath, String rootRelativePath, String request, String contentType, Map<String, Object>... vars); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // } // // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/GlobalConfig.java // public class GlobalConfig { // public static int port; // public static String rootPath; // public static boolean useRootRelativePath; // // static { // port = System.getProperty(Constants.PORT) != null ? Integer.parseInt(System // .getProperty(Constants.PORT)) : Constants.DEFAULT_PORT; // // rootPath = System.getProperty(Constants.ROOT_PATH) != null ? System.getProperty(Constants.ROOT_PATH) // : Constants.DEFAULT_ROOT_PATH; // // useRootRelativePath = System.getProperty(Constants.USE_ROOT_RELATIVE_PATH) != null && "true".equals(System // .getProperty(Constants.USE_ROOT_RELATIVE_PATH)); // } // // private GlobalConfig() { // // noop // } // }
import com.github.bjuvensjo.rsimulator.core.Simulator; import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import com.github.bjuvensjo.rsimulator.socket.config.GlobalConfig; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.util.Optional;
package com.github.bjuvensjo.rsimulator.socket; /** * Manager */ @Singleton public class Manager { @Inject private RequestReader requestReader; @Inject private ResponseWriter responseWriter; @Inject private Simulator simulator; @Inject @Named("simulatorContentType") private String simulatorContentType; public void handle(Socket s) throws IOException { Worker worker = new Worker(s); new Thread(worker).start(); } class Worker implements Runnable { private final Logger log = LoggerFactory.getLogger(Worker.class); private final Socket s; public Worker(Socket s) throws IOException { this.s = s; } private RequestReader.Request read(InputStream in) throws IOException { return requestReader.read(in); } private void write(RequestReader.Request request, SimulatorResponse simulatorResponse, OutputStream out) throws IOException { responseWriter.write(request, simulatorResponse, out); } private String getRootRelativePath(RequestReader.Request request) {
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/Simulator.java // @ImplementedBy(SimulatorImpl.class) // public interface Simulator { // // /** // * Returns a SimulatorResponse that matches the specified request. // * // * @param rootPath the root path on which to search recursively for matches to the specified request // * @param rootRelativePath the path on which to search recursively for matches to the specified request // * @param request the request // * @param contentType the content type of the request, e.g. txt or xml // * @param vars vars that can be used in for example scripts // * @return a SimulatorResponse that matches the specified request // */ // Optional<SimulatorResponse> service(String rootPath, String rootRelativePath, String request, String contentType, Map<String, Object>... vars); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // } // // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/config/GlobalConfig.java // public class GlobalConfig { // public static int port; // public static String rootPath; // public static boolean useRootRelativePath; // // static { // port = System.getProperty(Constants.PORT) != null ? Integer.parseInt(System // .getProperty(Constants.PORT)) : Constants.DEFAULT_PORT; // // rootPath = System.getProperty(Constants.ROOT_PATH) != null ? System.getProperty(Constants.ROOT_PATH) // : Constants.DEFAULT_ROOT_PATH; // // useRootRelativePath = System.getProperty(Constants.USE_ROOT_RELATIVE_PATH) != null && "true".equals(System // .getProperty(Constants.USE_ROOT_RELATIVE_PATH)); // } // // private GlobalConfig() { // // noop // } // } // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/Manager.java import com.github.bjuvensjo.rsimulator.core.Simulator; import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import com.github.bjuvensjo.rsimulator.socket.config.GlobalConfig; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.util.Optional; package com.github.bjuvensjo.rsimulator.socket; /** * Manager */ @Singleton public class Manager { @Inject private RequestReader requestReader; @Inject private ResponseWriter responseWriter; @Inject private Simulator simulator; @Inject @Named("simulatorContentType") private String simulatorContentType; public void handle(Socket s) throws IOException { Worker worker = new Worker(s); new Thread(worker).start(); } class Worker implements Runnable { private final Logger log = LoggerFactory.getLogger(Worker.class); private final Socket s; public Worker(Socket s) throws IOException { this.s = s; } private RequestReader.Request read(InputStream in) throws IOException { return requestReader.read(in); } private void write(RequestReader.Request request, SimulatorResponse simulatorResponse, OutputStream out) throws IOException { responseWriter.write(request, simulatorResponse, out); } private String getRootRelativePath(RequestReader.Request request) {
if (GlobalConfig.useRootRelativePath) {
bjuvensjo/rsimulator
rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorCacheInterceptor.java
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/util/Props.java // @ImplementedBy(PropsImpl.class) // public interface Props { // // /** // * Returns true if Simulator cache is on, otherwise false. // * // * @return true if Simulator cache is on, otherwise false // */ // boolean isSimulatorCache(); // // /** // * Returns true if xml namespaces should be ignored, otherwise false. // * // * @return true if xml namespaces should be ignored, otherwise false // */ // public boolean ignoreXmlNamespaces(); // // /** // * Returns the properties read from the specified path. // * // * @param path the path // * @return the properties read from the specified path // */ // Optional<Properties> getProperties(Path path); // }
import com.github.bjuvensjo.rsimulator.core.util.Props; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import net.sf.ehcache.Cache; import net.sf.ehcache.Element; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors;
package com.github.bjuvensjo.rsimulator.core; /** * SimulatorCacheInterceptor is an interceptor that caches invocations of * {@link Simulator#service(String, String, String, String, Map...)}. */ @Singleton public class SimulatorCacheInterceptor implements MethodInterceptor { private final Logger log = LoggerFactory.getLogger(SimulatorCacheInterceptor.class); @Inject @Named("SimulatorCache") Cache cache; @Inject
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/util/Props.java // @ImplementedBy(PropsImpl.class) // public interface Props { // // /** // * Returns true if Simulator cache is on, otherwise false. // * // * @return true if Simulator cache is on, otherwise false // */ // boolean isSimulatorCache(); // // /** // * Returns true if xml namespaces should be ignored, otherwise false. // * // * @return true if xml namespaces should be ignored, otherwise false // */ // public boolean ignoreXmlNamespaces(); // // /** // * Returns the properties read from the specified path. // * // * @param path the path // * @return the properties read from the specified path // */ // Optional<Properties> getProperties(Path path); // } // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorCacheInterceptor.java import com.github.bjuvensjo.rsimulator.core.util.Props; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import net.sf.ehcache.Cache; import net.sf.ehcache.Element; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; package com.github.bjuvensjo.rsimulator.core; /** * SimulatorCacheInterceptor is an interceptor that caches invocations of * {@link Simulator#service(String, String, String, String, Map...)}. */ @Singleton public class SimulatorCacheInterceptor implements MethodInterceptor { private final Logger log = LoggerFactory.getLogger(SimulatorCacheInterceptor.class); @Inject @Named("SimulatorCache") Cache cache; @Inject
Props props;
bjuvensjo/rsimulator
rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/util/FileUtilsImpl.java
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/config/Constants.java // public static final String REQUEST = "Request";
import com.github.bjuvensjo.rsimulator.core.config.Cache; import com.google.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.github.bjuvensjo.rsimulator.core.config.Constants.REQUEST;
package com.github.bjuvensjo.rsimulator.core.util; /** * FileUtilsImpl implements {@link FileUtils}. */ @Singleton public class FileUtilsImpl implements FileUtils { private static final String ENCODING = "UTF-8";
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/config/Constants.java // public static final String REQUEST = "Request"; // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/util/FileUtilsImpl.java import com.github.bjuvensjo.rsimulator.core.config.Cache; import com.google.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.github.bjuvensjo.rsimulator.core.config.Constants.REQUEST; package com.github.bjuvensjo.rsimulator.core.util; /** * FileUtilsImpl implements {@link FileUtils}. */ @Singleton public class FileUtilsImpl implements FileUtils { private static final String ENCODING = "UTF-8";
private static final String SUFFIX_PREFIX = REQUEST.concat(".");
bjuvensjo/rsimulator
rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorScriptInterceptor.java
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/config/Constants.java // public final class Constants { // /** // * The REQUEST constant holds the value used as convention for the last part of the name of request files. // */ // public static final String REQUEST = "Request"; // /** // * The RESPONSE constant holds the value used as convention for the last part of the name of response files. // */ // public static final String RESPONSE = "Response"; // // /** // * The CONTENT_TYPE constant is used as key in the script vars. // */ // public static final String CONTENT_TYPE = "contentType"; // // /** // * The EXCEPTION constant is used as key in the script vars. // */ // public static final String EXCEPTION = "exception"; // // /** // * The SIMULATOR_RESPONSE_OPTIONAL constant is used as key in the script vars. // */ // public static final String SIMULATOR_RESPONSE_OPTIONAL = "simulatorResponseOptional"; // // /** // * The SIMULATOR_REQUEST constant is used as key in the script vars. // */ // public static final String SIMULATOR_REQUEST = "simulatorRequest"; // // /** // * The ROOT_PATH constant is used as key in the script vars. // */ // public static final String ROOT_PATH = "rootPath"; // // /** // * The ROOT_RELATIVE_PATH constant is used as key in the script vars. // */ // public static final String ROOT_RELATIVE_PATH = "rootRelativePath"; // // private Constants() { // } // }
import com.google.inject.Singleton; import groovy.lang.Binding; import groovy.util.GroovyScriptEngine; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.Optional; import static com.github.bjuvensjo.rsimulator.core.config.Constants.*;
package com.github.bjuvensjo.rsimulator.core; /** * SimulatorScriptInterceptor is an interceptor that supports Groovy scripts intercepting invocations of * {@link Simulator#service(String, String, String, String, Map...)}. * <p> * The scripts supported are: * <ol> * <li>GlobalRequest.groovy; Must be put in the rootPath folder and is applied before the invocation.</li> * <li>&lt;TestName&gt;.groovy; Must be put in the same folder as test request and response and is applied first after * the invocation. The name of the groovy file must be the same as for the test request, e.g. Test1Request.txt - * Test1.groovy.</li> * <li>GlobalResponse.groovy; Must be put in the rootPath folder and is applied last after the invocation.</li> * </ol> * <p> * All script have a Map&lt;String, Object&gt; available through the variable vars. The keys contentType, simulatorResponse, * request, rootPath, rootRelativePath can be used to access invocation arguments and return value. In addition, the map * can be used to communicate arbitrary objects between the Groovy scripts. If a script sets a SimulatorResponse in the * vars map, this SimulatorResponse is directly returned. */ @Singleton public class SimulatorScriptInterceptor implements MethodInterceptor { private static final int ROOT_PATH_INDEX = 0; private static final int ROOT_RELATIVE_PATH_INDEX = 1; private static final int SIMULATOR_REQUEST_INDEX = 2; private static final int CONTENT_TYPE_INDEX = 3; private static final int VARS_INDEX = 4;
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/config/Constants.java // public final class Constants { // /** // * The REQUEST constant holds the value used as convention for the last part of the name of request files. // */ // public static final String REQUEST = "Request"; // /** // * The RESPONSE constant holds the value used as convention for the last part of the name of response files. // */ // public static final String RESPONSE = "Response"; // // /** // * The CONTENT_TYPE constant is used as key in the script vars. // */ // public static final String CONTENT_TYPE = "contentType"; // // /** // * The EXCEPTION constant is used as key in the script vars. // */ // public static final String EXCEPTION = "exception"; // // /** // * The SIMULATOR_RESPONSE_OPTIONAL constant is used as key in the script vars. // */ // public static final String SIMULATOR_RESPONSE_OPTIONAL = "simulatorResponseOptional"; // // /** // * The SIMULATOR_REQUEST constant is used as key in the script vars. // */ // public static final String SIMULATOR_REQUEST = "simulatorRequest"; // // /** // * The ROOT_PATH constant is used as key in the script vars. // */ // public static final String ROOT_PATH = "rootPath"; // // /** // * The ROOT_RELATIVE_PATH constant is used as key in the script vars. // */ // public static final String ROOT_RELATIVE_PATH = "rootRelativePath"; // // private Constants() { // } // } // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorScriptInterceptor.java import com.google.inject.Singleton; import groovy.lang.Binding; import groovy.util.GroovyScriptEngine; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.Optional; import static com.github.bjuvensjo.rsimulator.core.config.Constants.*; package com.github.bjuvensjo.rsimulator.core; /** * SimulatorScriptInterceptor is an interceptor that supports Groovy scripts intercepting invocations of * {@link Simulator#service(String, String, String, String, Map...)}. * <p> * The scripts supported are: * <ol> * <li>GlobalRequest.groovy; Must be put in the rootPath folder and is applied before the invocation.</li> * <li>&lt;TestName&gt;.groovy; Must be put in the same folder as test request and response and is applied first after * the invocation. The name of the groovy file must be the same as for the test request, e.g. Test1Request.txt - * Test1.groovy.</li> * <li>GlobalResponse.groovy; Must be put in the rootPath folder and is applied last after the invocation.</li> * </ol> * <p> * All script have a Map&lt;String, Object&gt; available through the variable vars. The keys contentType, simulatorResponse, * request, rootPath, rootRelativePath can be used to access invocation arguments and return value. In addition, the map * can be used to communicate arbitrary objects between the Groovy scripts. If a script sets a SimulatorResponse in the * vars map, this SimulatorResponse is directly returned. */ @Singleton public class SimulatorScriptInterceptor implements MethodInterceptor { private static final int ROOT_PATH_INDEX = 0; private static final int ROOT_RELATIVE_PATH_INDEX = 1; private static final int SIMULATOR_REQUEST_INDEX = 2; private static final int CONTENT_TYPE_INDEX = 3; private static final int VARS_INDEX = 4;
private static final String GROOVY_PATTERN = com.github.bjuvensjo.rsimulator.core.config.Constants.REQUEST + ".*";
bjuvensjo/rsimulator
rsimulator-proxy/src/test/java/com/github/bjuvensjo/rsimulator/proxy/URIMapperTest.java
// Path: rsimulator-proxy/src/main/java/com/github/bjuvensjo/rsimulator/proxy/config/ProxyModule.java // public class ProxyModule extends AbstractModule { // private final Logger log = LoggerFactory.getLogger(ProxyModule.class); // // /* // * (non-Javadoc) // * // * @see com.google.inject.AbstractModule#configure() // */ // @Override // protected void configure() { // // ***** Properties ***** // URL resource = getClass().getResource("/URIMapper.txt"); // if (resource == null) { // log.debug("No /URIMapper.txt resource exists."); // } else { // bind(File.class).annotatedWith(Names.named("uri-mappings")).toInstance( // new File(resource.getFile())); // } // } // }
import com.github.bjuvensjo.rsimulator.proxy.config.ProxyModule; import com.google.inject.Guice; import com.google.inject.Injector; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail;
package com.github.bjuvensjo.rsimulator.proxy; public class URIMapperTest { private URIMapper uriMapper; @BeforeEach public void init() {
// Path: rsimulator-proxy/src/main/java/com/github/bjuvensjo/rsimulator/proxy/config/ProxyModule.java // public class ProxyModule extends AbstractModule { // private final Logger log = LoggerFactory.getLogger(ProxyModule.class); // // /* // * (non-Javadoc) // * // * @see com.google.inject.AbstractModule#configure() // */ // @Override // protected void configure() { // // ***** Properties ***** // URL resource = getClass().getResource("/URIMapper.txt"); // if (resource == null) { // log.debug("No /URIMapper.txt resource exists."); // } else { // bind(File.class).annotatedWith(Names.named("uri-mappings")).toInstance( // new File(resource.getFile())); // } // } // } // Path: rsimulator-proxy/src/test/java/com/github/bjuvensjo/rsimulator/proxy/URIMapperTest.java import com.github.bjuvensjo.rsimulator.proxy.config.ProxyModule; import com.google.inject.Guice; import com.google.inject.Injector; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; package com.github.bjuvensjo.rsimulator.proxy; public class URIMapperTest { private URIMapper uriMapper; @BeforeEach public void init() {
Injector injector = Guice.createInjector(new ProxyModule());
bjuvensjo/rsimulator
rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/ResponseWriter.java
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // }
import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.OutputStream;
package com.github.bjuvensjo.rsimulator.socket; @Singleton public class ResponseWriter { private static final Logger log = LoggerFactory.getLogger(ResponseWriter.class); @Inject @Named("encoding") private String encoding; @Inject @Named("headerLength") private int headerLength; @Inject @Named("headerBodyLengthBeginIndex") private int headerBodyLengthBeginIndex; @Inject @Named("headerBodyLengthEndIndex") private int headerBodyLengthEndIndex;
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // } // Path: rsimulator-socket/src/main/java/com/github/bjuvensjo/rsimulator/socket/ResponseWriter.java import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.OutputStream; package com.github.bjuvensjo.rsimulator.socket; @Singleton public class ResponseWriter { private static final Logger log = LoggerFactory.getLogger(ResponseWriter.class); @Inject @Named("encoding") private String encoding; @Inject @Named("headerLength") private int headerLength; @Inject @Named("headerBodyLengthBeginIndex") private int headerBodyLengthBeginIndex; @Inject @Named("headerBodyLengthEndIndex") private int headerBodyLengthEndIndex;
public void write(RequestReader.Request request, SimulatorResponse simulatorResponse, OutputStream out) throws IOException {
bjuvensjo/rsimulator
rsimulator-http/src/main/java/com/github/bjuvensjo/rsimulator/http/ScriptFilter.java
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // } // // Path: rsimulator-http/src/main/java/com/github/bjuvensjo/rsimulator/http/config/Constants.java // public final class Constants { // /** // * The parameter name that is used to set/unset the use of relative root path. // */ // public static final String USE_ROOT_RELATIVE_PATH = "useRootRelativePath"; // /** // * The parameter name that is used to set the root path. // */ // public static final String ROOT_PATH = "rootPath"; // // public static final String SERVLET_REQUEST = "servletRequest"; // public static final String SERVLET_RESPONSE = "servletResponse"; // public static final String VARS = "vars"; // // public static final String DEFAULT_ROOT_PATH = "src/main/resources"; // public static final String SIMULATOR_RESPONSE = "simulatorResponse"; // // private Constants() { // } // } // // Path: rsimulator-http/src/main/java/com/github/bjuvensjo/rsimulator/http/config/GlobalConfig.java // public class GlobalConfig { // public static String rootPath; // public static boolean useRootRelativePath; // // static { // rootPath = System.getProperty(Constants.ROOT_PATH) != null ? System.getProperty(Constants.ROOT_PATH) // : Constants.DEFAULT_ROOT_PATH; // useRootRelativePath = System.getProperty(Constants.USE_ROOT_RELATIVE_PATH) != null && "true".equals(System // .getProperty(Constants.USE_ROOT_RELATIVE_PATH)); // } // // private GlobalConfig() { // // noop // } // }
import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import com.github.bjuvensjo.rsimulator.http.config.Constants; import com.github.bjuvensjo.rsimulator.http.config.GlobalConfig; import groovy.lang.Binding; import groovy.util.GroovyScriptEngine; import jakarta.servlet.*; import jakarta.servlet.annotation.WebFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.HashMap; import java.util.Map;
package com.github.bjuvensjo.rsimulator.http; @WebFilter(urlPatterns = {"/*"}) public class ScriptFilter implements Filter {
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // } // // Path: rsimulator-http/src/main/java/com/github/bjuvensjo/rsimulator/http/config/Constants.java // public final class Constants { // /** // * The parameter name that is used to set/unset the use of relative root path. // */ // public static final String USE_ROOT_RELATIVE_PATH = "useRootRelativePath"; // /** // * The parameter name that is used to set the root path. // */ // public static final String ROOT_PATH = "rootPath"; // // public static final String SERVLET_REQUEST = "servletRequest"; // public static final String SERVLET_RESPONSE = "servletResponse"; // public static final String VARS = "vars"; // // public static final String DEFAULT_ROOT_PATH = "src/main/resources"; // public static final String SIMULATOR_RESPONSE = "simulatorResponse"; // // private Constants() { // } // } // // Path: rsimulator-http/src/main/java/com/github/bjuvensjo/rsimulator/http/config/GlobalConfig.java // public class GlobalConfig { // public static String rootPath; // public static boolean useRootRelativePath; // // static { // rootPath = System.getProperty(Constants.ROOT_PATH) != null ? System.getProperty(Constants.ROOT_PATH) // : Constants.DEFAULT_ROOT_PATH; // useRootRelativePath = System.getProperty(Constants.USE_ROOT_RELATIVE_PATH) != null && "true".equals(System // .getProperty(Constants.USE_ROOT_RELATIVE_PATH)); // } // // private GlobalConfig() { // // noop // } // } // Path: rsimulator-http/src/main/java/com/github/bjuvensjo/rsimulator/http/ScriptFilter.java import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import com.github.bjuvensjo.rsimulator.http.config.Constants; import com.github.bjuvensjo.rsimulator.http.config.GlobalConfig; import groovy.lang.Binding; import groovy.util.GroovyScriptEngine; import jakarta.servlet.*; import jakarta.servlet.annotation.WebFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; package com.github.bjuvensjo.rsimulator.http; @WebFilter(urlPatterns = {"/*"}) public class ScriptFilter implements Filter {
private static final String GROOVY_PATTERN = com.github.bjuvensjo.rsimulator.core.config.Constants.REQUEST + ".*";
bjuvensjo/rsimulator
rsimulator-http/src/main/java/com/github/bjuvensjo/rsimulator/http/ScriptFilter.java
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // } // // Path: rsimulator-http/src/main/java/com/github/bjuvensjo/rsimulator/http/config/Constants.java // public final class Constants { // /** // * The parameter name that is used to set/unset the use of relative root path. // */ // public static final String USE_ROOT_RELATIVE_PATH = "useRootRelativePath"; // /** // * The parameter name that is used to set the root path. // */ // public static final String ROOT_PATH = "rootPath"; // // public static final String SERVLET_REQUEST = "servletRequest"; // public static final String SERVLET_RESPONSE = "servletResponse"; // public static final String VARS = "vars"; // // public static final String DEFAULT_ROOT_PATH = "src/main/resources"; // public static final String SIMULATOR_RESPONSE = "simulatorResponse"; // // private Constants() { // } // } // // Path: rsimulator-http/src/main/java/com/github/bjuvensjo/rsimulator/http/config/GlobalConfig.java // public class GlobalConfig { // public static String rootPath; // public static boolean useRootRelativePath; // // static { // rootPath = System.getProperty(Constants.ROOT_PATH) != null ? System.getProperty(Constants.ROOT_PATH) // : Constants.DEFAULT_ROOT_PATH; // useRootRelativePath = System.getProperty(Constants.USE_ROOT_RELATIVE_PATH) != null && "true".equals(System // .getProperty(Constants.USE_ROOT_RELATIVE_PATH)); // } // // private GlobalConfig() { // // noop // } // }
import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import com.github.bjuvensjo.rsimulator.http.config.Constants; import com.github.bjuvensjo.rsimulator.http.config.GlobalConfig; import groovy.lang.Binding; import groovy.util.GroovyScriptEngine; import jakarta.servlet.*; import jakarta.servlet.annotation.WebFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.HashMap; import java.util.Map;
package com.github.bjuvensjo.rsimulator.http; @WebFilter(urlPatterns = {"/*"}) public class ScriptFilter implements Filter { private static final String GROOVY_PATTERN = com.github.bjuvensjo.rsimulator.core.config.Constants.REQUEST + ".*"; private final Logger log = LoggerFactory.getLogger(ScriptFilter.class); @Override public void init(FilterConfig filterConfig) { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { log.debug("doFilter"); if (shouldApplyFilter(request)) { log.debug("ApplyingScripts"); Map<String, Object> vars = new HashMap<>(); vars.put(Constants.SERVLET_REQUEST, request); vars.put(Constants.SERVLET_RESPONSE, response);
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // } // // Path: rsimulator-http/src/main/java/com/github/bjuvensjo/rsimulator/http/config/Constants.java // public final class Constants { // /** // * The parameter name that is used to set/unset the use of relative root path. // */ // public static final String USE_ROOT_RELATIVE_PATH = "useRootRelativePath"; // /** // * The parameter name that is used to set the root path. // */ // public static final String ROOT_PATH = "rootPath"; // // public static final String SERVLET_REQUEST = "servletRequest"; // public static final String SERVLET_RESPONSE = "servletResponse"; // public static final String VARS = "vars"; // // public static final String DEFAULT_ROOT_PATH = "src/main/resources"; // public static final String SIMULATOR_RESPONSE = "simulatorResponse"; // // private Constants() { // } // } // // Path: rsimulator-http/src/main/java/com/github/bjuvensjo/rsimulator/http/config/GlobalConfig.java // public class GlobalConfig { // public static String rootPath; // public static boolean useRootRelativePath; // // static { // rootPath = System.getProperty(Constants.ROOT_PATH) != null ? System.getProperty(Constants.ROOT_PATH) // : Constants.DEFAULT_ROOT_PATH; // useRootRelativePath = System.getProperty(Constants.USE_ROOT_RELATIVE_PATH) != null && "true".equals(System // .getProperty(Constants.USE_ROOT_RELATIVE_PATH)); // } // // private GlobalConfig() { // // noop // } // } // Path: rsimulator-http/src/main/java/com/github/bjuvensjo/rsimulator/http/ScriptFilter.java import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import com.github.bjuvensjo.rsimulator.http.config.Constants; import com.github.bjuvensjo.rsimulator.http.config.GlobalConfig; import groovy.lang.Binding; import groovy.util.GroovyScriptEngine; import jakarta.servlet.*; import jakarta.servlet.annotation.WebFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; package com.github.bjuvensjo.rsimulator.http; @WebFilter(urlPatterns = {"/*"}) public class ScriptFilter implements Filter { private static final String GROOVY_PATTERN = com.github.bjuvensjo.rsimulator.core.config.Constants.REQUEST + ".*"; private final Logger log = LoggerFactory.getLogger(ScriptFilter.class); @Override public void init(FilterConfig filterConfig) { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { log.debug("doFilter"); if (shouldApplyFilter(request)) { log.debug("ApplyingScripts"); Map<String, Object> vars = new HashMap<>(); vars.put(Constants.SERVLET_REQUEST, request); vars.put(Constants.SERVLET_RESPONSE, response);
vars.put(Constants.ROOT_PATH, GlobalConfig.rootPath);
bjuvensjo/rsimulator
rsimulator-http/src/main/java/com/github/bjuvensjo/rsimulator/http/ScriptFilter.java
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // } // // Path: rsimulator-http/src/main/java/com/github/bjuvensjo/rsimulator/http/config/Constants.java // public final class Constants { // /** // * The parameter name that is used to set/unset the use of relative root path. // */ // public static final String USE_ROOT_RELATIVE_PATH = "useRootRelativePath"; // /** // * The parameter name that is used to set the root path. // */ // public static final String ROOT_PATH = "rootPath"; // // public static final String SERVLET_REQUEST = "servletRequest"; // public static final String SERVLET_RESPONSE = "servletResponse"; // public static final String VARS = "vars"; // // public static final String DEFAULT_ROOT_PATH = "src/main/resources"; // public static final String SIMULATOR_RESPONSE = "simulatorResponse"; // // private Constants() { // } // } // // Path: rsimulator-http/src/main/java/com/github/bjuvensjo/rsimulator/http/config/GlobalConfig.java // public class GlobalConfig { // public static String rootPath; // public static boolean useRootRelativePath; // // static { // rootPath = System.getProperty(Constants.ROOT_PATH) != null ? System.getProperty(Constants.ROOT_PATH) // : Constants.DEFAULT_ROOT_PATH; // useRootRelativePath = System.getProperty(Constants.USE_ROOT_RELATIVE_PATH) != null && "true".equals(System // .getProperty(Constants.USE_ROOT_RELATIVE_PATH)); // } // // private GlobalConfig() { // // noop // } // }
import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import com.github.bjuvensjo.rsimulator.http.config.Constants; import com.github.bjuvensjo.rsimulator.http.config.GlobalConfig; import groovy.lang.Binding; import groovy.util.GroovyScriptEngine; import jakarta.servlet.*; import jakarta.servlet.annotation.WebFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.HashMap; import java.util.Map;
request.setAttribute(Constants.USE_ROOT_RELATIVE_PATH, vars.get(Constants.USE_ROOT_RELATIVE_PATH)); chain.doFilter(request, response); vars.put(Constants.SIMULATOR_RESPONSE, request.getAttribute(Constants.SIMULATOR_RESPONSE)); applyScript(Scope.LOCAL_RESPONSE, vars); applyScript(Scope.GLOBAL_RESPONSE, vars); } else { chain.doFilter(request, response); } } private boolean shouldApplyFilter(ServletRequest request) { String theRootPath = request.getParameter(Constants.ROOT_PATH); String theUseRootRelativePath = request.getParameter(Constants.USE_ROOT_RELATIVE_PATH); return (theRootPath == null && theUseRootRelativePath == null); } private void applyScript(Scope type, Map<String, Object> vars) { try { String root = null; String script = null; switch (type) { case GLOBAL_REQUEST: root = GlobalConfig.rootPath; script = "GlobalServletRequest.groovy"; break; case GLOBAL_RESPONSE: root = GlobalConfig.rootPath; script = "GlobalServletResponse.groovy"; break; case LOCAL_RESPONSE:
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // } // // Path: rsimulator-http/src/main/java/com/github/bjuvensjo/rsimulator/http/config/Constants.java // public final class Constants { // /** // * The parameter name that is used to set/unset the use of relative root path. // */ // public static final String USE_ROOT_RELATIVE_PATH = "useRootRelativePath"; // /** // * The parameter name that is used to set the root path. // */ // public static final String ROOT_PATH = "rootPath"; // // public static final String SERVLET_REQUEST = "servletRequest"; // public static final String SERVLET_RESPONSE = "servletResponse"; // public static final String VARS = "vars"; // // public static final String DEFAULT_ROOT_PATH = "src/main/resources"; // public static final String SIMULATOR_RESPONSE = "simulatorResponse"; // // private Constants() { // } // } // // Path: rsimulator-http/src/main/java/com/github/bjuvensjo/rsimulator/http/config/GlobalConfig.java // public class GlobalConfig { // public static String rootPath; // public static boolean useRootRelativePath; // // static { // rootPath = System.getProperty(Constants.ROOT_PATH) != null ? System.getProperty(Constants.ROOT_PATH) // : Constants.DEFAULT_ROOT_PATH; // useRootRelativePath = System.getProperty(Constants.USE_ROOT_RELATIVE_PATH) != null && "true".equals(System // .getProperty(Constants.USE_ROOT_RELATIVE_PATH)); // } // // private GlobalConfig() { // // noop // } // } // Path: rsimulator-http/src/main/java/com/github/bjuvensjo/rsimulator/http/ScriptFilter.java import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import com.github.bjuvensjo.rsimulator.http.config.Constants; import com.github.bjuvensjo.rsimulator.http.config.GlobalConfig; import groovy.lang.Binding; import groovy.util.GroovyScriptEngine; import jakarta.servlet.*; import jakarta.servlet.annotation.WebFilter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; request.setAttribute(Constants.USE_ROOT_RELATIVE_PATH, vars.get(Constants.USE_ROOT_RELATIVE_PATH)); chain.doFilter(request, response); vars.put(Constants.SIMULATOR_RESPONSE, request.getAttribute(Constants.SIMULATOR_RESPONSE)); applyScript(Scope.LOCAL_RESPONSE, vars); applyScript(Scope.GLOBAL_RESPONSE, vars); } else { chain.doFilter(request, response); } } private boolean shouldApplyFilter(ServletRequest request) { String theRootPath = request.getParameter(Constants.ROOT_PATH); String theUseRootRelativePath = request.getParameter(Constants.USE_ROOT_RELATIVE_PATH); return (theRootPath == null && theUseRootRelativePath == null); } private void applyScript(Scope type, Map<String, Object> vars) { try { String root = null; String script = null; switch (type) { case GLOBAL_REQUEST: root = GlobalConfig.rootPath; script = "GlobalServletRequest.groovy"; break; case GLOBAL_RESPONSE: root = GlobalConfig.rootPath; script = "GlobalServletResponse.groovy"; break; case LOCAL_RESPONSE:
SimulatorResponse simulatorResponse = (SimulatorResponse) vars.get(Constants.SIMULATOR_RESPONSE);
bjuvensjo/rsimulator
rsimulator-aop/src/main/java/com/github/bjuvensjo/rsimulator/aop/AopAllianceSimulatorImpl.java
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/config/CoreModule.java // public class CoreModule extends AbstractModule { // private final Logger log = LoggerFactory.getLogger(CoreModule.class); // private static final CacheManager cacheManager = CacheManager.create(); // // @Provides // @Named("rsimulator-core-properties") // java.util.Properties provideProperties() { // java.util.Properties properties = new java.util.Properties(); // URL resource = getClass().getResource("/rsimulator.properties"); // if (resource == null) { // properties.setProperty("simulatorCache", "false"); // properties.setProperty("ignoreXmlNamespaces", "false"); // } else { // try (BufferedInputStream bis = new BufferedInputStream(resource.openStream())) { // properties.load(bis); // } catch (Exception e) { // log.error("Error reading properties from: {}", resource.getPath(), e); // } // } // return properties; // } // // @Override // protected void configure() { // MapBinder<String, Handler> map = MapBinder.newMapBinder(binder(), String.class, Handler.class); // map.addBinding("json").to(JsonHandler.class); // map.addBinding("txt").to(TxtHandler.class); // map.addBinding("xml").to(XmlHandler.class); // // // ***** Interceptors for cache and script ***** // Arrays.asList("SimulatorCache", "FileUtilsCache", "PropsCache").forEach(name -> // bind(net.sf.ehcache.Cache.class).annotatedWith(Names.named(name)).toInstance(cacheManager.getCache(name))); // // // SimulatorPropertiesInterceptor simulatorPropertiesInterceptor = new SimulatorPropertiesInterceptor(); // SimulatorCacheInterceptor simulatorCacheInterceptor = new SimulatorCacheInterceptor(); // SimulatorScriptInterceptor simulatorScriptInterceptor = new SimulatorScriptInterceptor(); // FileUtilsCacheInterceptor fileUtilsCacheInterceptor = new FileUtilsCacheInterceptor(); // PropsCacheInterceptor propsCacheInterceptor = new PropsCacheInterceptor(); // // requestInjection(simulatorPropertiesInterceptor); // requestInjection(simulatorCacheInterceptor); // requestInjection(simulatorScriptInterceptor); // requestInjection(fileUtilsCacheInterceptor); // requestInjection(propsCacheInterceptor); // // // Order is significant // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Properties.class), // simulatorPropertiesInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Cache.class), // simulatorCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Script.class), // simulatorScriptInterceptor); // bindInterceptor(Matchers.subclassesOf(FileUtils.class), Matchers.annotatedWith(Cache.class), // fileUtilsCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Props.class), Matchers.annotatedWith(Cache.class), // propsCacheInterceptor); // } // }
import com.github.bjuvensjo.rsimulator.core.config.CoreModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import org.aopalliance.intercept.MethodInvocation; import java.io.File; import java.lang.reflect.Method; import java.net.URL;
package com.github.bjuvensjo.rsimulator.aop; /** * AopAllianceSimulatorImpl. */ public class AopAllianceSimulatorImpl implements AopAllianceSimulator { @Inject private SimulatorAdapter simulatorAdapter; private String rootPath; private boolean useRootRelativePath = false; /** * Creates an AopAllianceSimulatorImpl. */ public AopAllianceSimulatorImpl() {
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/config/CoreModule.java // public class CoreModule extends AbstractModule { // private final Logger log = LoggerFactory.getLogger(CoreModule.class); // private static final CacheManager cacheManager = CacheManager.create(); // // @Provides // @Named("rsimulator-core-properties") // java.util.Properties provideProperties() { // java.util.Properties properties = new java.util.Properties(); // URL resource = getClass().getResource("/rsimulator.properties"); // if (resource == null) { // properties.setProperty("simulatorCache", "false"); // properties.setProperty("ignoreXmlNamespaces", "false"); // } else { // try (BufferedInputStream bis = new BufferedInputStream(resource.openStream())) { // properties.load(bis); // } catch (Exception e) { // log.error("Error reading properties from: {}", resource.getPath(), e); // } // } // return properties; // } // // @Override // protected void configure() { // MapBinder<String, Handler> map = MapBinder.newMapBinder(binder(), String.class, Handler.class); // map.addBinding("json").to(JsonHandler.class); // map.addBinding("txt").to(TxtHandler.class); // map.addBinding("xml").to(XmlHandler.class); // // // ***** Interceptors for cache and script ***** // Arrays.asList("SimulatorCache", "FileUtilsCache", "PropsCache").forEach(name -> // bind(net.sf.ehcache.Cache.class).annotatedWith(Names.named(name)).toInstance(cacheManager.getCache(name))); // // // SimulatorPropertiesInterceptor simulatorPropertiesInterceptor = new SimulatorPropertiesInterceptor(); // SimulatorCacheInterceptor simulatorCacheInterceptor = new SimulatorCacheInterceptor(); // SimulatorScriptInterceptor simulatorScriptInterceptor = new SimulatorScriptInterceptor(); // FileUtilsCacheInterceptor fileUtilsCacheInterceptor = new FileUtilsCacheInterceptor(); // PropsCacheInterceptor propsCacheInterceptor = new PropsCacheInterceptor(); // // requestInjection(simulatorPropertiesInterceptor); // requestInjection(simulatorCacheInterceptor); // requestInjection(simulatorScriptInterceptor); // requestInjection(fileUtilsCacheInterceptor); // requestInjection(propsCacheInterceptor); // // // Order is significant // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Properties.class), // simulatorPropertiesInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Cache.class), // simulatorCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Script.class), // simulatorScriptInterceptor); // bindInterceptor(Matchers.subclassesOf(FileUtils.class), Matchers.annotatedWith(Cache.class), // fileUtilsCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Props.class), Matchers.annotatedWith(Cache.class), // propsCacheInterceptor); // } // } // Path: rsimulator-aop/src/main/java/com/github/bjuvensjo/rsimulator/aop/AopAllianceSimulatorImpl.java import com.github.bjuvensjo.rsimulator.core.config.CoreModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import org.aopalliance.intercept.MethodInvocation; import java.io.File; import java.lang.reflect.Method; import java.net.URL; package com.github.bjuvensjo.rsimulator.aop; /** * AopAllianceSimulatorImpl. */ public class AopAllianceSimulatorImpl implements AopAllianceSimulator { @Inject private SimulatorAdapter simulatorAdapter; private String rootPath; private boolean useRootRelativePath = false; /** * Creates an AopAllianceSimulatorImpl. */ public AopAllianceSimulatorImpl() {
Injector injector = Guice.createInjector(new CoreModule());
bjuvensjo/rsimulator
rsimulator-http/src/test/java/com/github/bjuvensjo/rsimulator/http/HttpSimulatorIT.java
// Path: rsimulator-http/src/main/java/com/github/bjuvensjo/rsimulator/http/config/HttpSimulatorConfig.java // public final class HttpSimulatorConfig { // private static final int READ_TIMEOUT = 12000; // private static final String DEFAULT_SERVER_URL = "http://localhost:8080"; // private static final String METHOD = "GET"; // // private HttpSimulatorConfig() { // } // // /** // * Configures the HttpSimulator (running on the default http://localhost:8080) with the root path of the folder of // * the specified testClass class folder. // * // * @param testClass the testClass // * @throws IOException if something goes wrong // */ // public static void config(Class<?> testClass) throws IOException { // config(testClass, DEFAULT_SERVER_URL); // } // // /** // * Configures the HttpSimulator running on the specified serverURL (e.g. http://localhost:8080) with the root path // * of the folder of the specified testClass class folder. // * // * @param testClass the testClass // * @param serverURL the serverURL // * @throws IOException if something goes wrong // */ // public static void config(Class<?> testClass, String serverURL) throws IOException { // String resource = testClass.getSimpleName() + ".class"; // String rootPath = new File(testClass.getResource(resource).getPath()).getParentFile().getPath(); // config(rootPath, false, serverURL); // } // // /** // * Configures the HttpSimulator (running on the default http://localhost:8080) with the specified root path and // * useRootRelativePath. // * // * @param rootPath the rootPath // * @param useRootRelativePath the useRootRelativePath // * @throws IOException if something goes wrong // */ // public static void config(String rootPath, boolean useRootRelativePath) throws IOException { // config(rootPath, useRootRelativePath, DEFAULT_SERVER_URL); // } // // /** // * Configures the HttpSimulator running on the specified serverURL (e.g. http://localhost:8080) with the specified // * root path and useRootRelativePath. // * // * @param rootPath the rootPath // * @param useRootRelativePath the useRootRelativePath // * @param serverURL the serverURL // * @throws IOException if something goes wrong // */ // public static void config(String rootPath, boolean useRootRelativePath, String serverURL) throws IOException { // HttpURLConnection con = null; // try { // String urlString = serverURL + "/?" + Constants.ROOT_PATH + // "=" + rootPath + "&" + Constants.USE_ROOT_RELATIVE_PATH + "=" + // useRootRelativePath; // con = (HttpURLConnection) new URL(urlString).openConnection(); // con.setRequestMethod(METHOD); // con.setReadTimeout(READ_TIMEOUT); // con.getResponseCode(); // } finally { // con.disconnect(); // } // } // }
import com.github.bjuvensjo.rsimulator.http.config.HttpSimulatorConfig; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.Paths; import static org.junit.jupiter.api.Assertions.*;
package com.github.bjuvensjo.rsimulator.http; public class HttpSimulatorIT { private static final int BUFFER_SIZE = 500; private static final int READ_TIMEOUT = 12000; private static final String ENCODING = "UTF-8"; private static final String PORT = System.getProperty("jetty.port", "25001"); @BeforeEach public void init() { try { String resource = "/txt-examples"; String rootPath = Paths.get(getClass().getResource(resource).toURI()).toString().replace(resource, "");
// Path: rsimulator-http/src/main/java/com/github/bjuvensjo/rsimulator/http/config/HttpSimulatorConfig.java // public final class HttpSimulatorConfig { // private static final int READ_TIMEOUT = 12000; // private static final String DEFAULT_SERVER_URL = "http://localhost:8080"; // private static final String METHOD = "GET"; // // private HttpSimulatorConfig() { // } // // /** // * Configures the HttpSimulator (running on the default http://localhost:8080) with the root path of the folder of // * the specified testClass class folder. // * // * @param testClass the testClass // * @throws IOException if something goes wrong // */ // public static void config(Class<?> testClass) throws IOException { // config(testClass, DEFAULT_SERVER_URL); // } // // /** // * Configures the HttpSimulator running on the specified serverURL (e.g. http://localhost:8080) with the root path // * of the folder of the specified testClass class folder. // * // * @param testClass the testClass // * @param serverURL the serverURL // * @throws IOException if something goes wrong // */ // public static void config(Class<?> testClass, String serverURL) throws IOException { // String resource = testClass.getSimpleName() + ".class"; // String rootPath = new File(testClass.getResource(resource).getPath()).getParentFile().getPath(); // config(rootPath, false, serverURL); // } // // /** // * Configures the HttpSimulator (running on the default http://localhost:8080) with the specified root path and // * useRootRelativePath. // * // * @param rootPath the rootPath // * @param useRootRelativePath the useRootRelativePath // * @throws IOException if something goes wrong // */ // public static void config(String rootPath, boolean useRootRelativePath) throws IOException { // config(rootPath, useRootRelativePath, DEFAULT_SERVER_URL); // } // // /** // * Configures the HttpSimulator running on the specified serverURL (e.g. http://localhost:8080) with the specified // * root path and useRootRelativePath. // * // * @param rootPath the rootPath // * @param useRootRelativePath the useRootRelativePath // * @param serverURL the serverURL // * @throws IOException if something goes wrong // */ // public static void config(String rootPath, boolean useRootRelativePath, String serverURL) throws IOException { // HttpURLConnection con = null; // try { // String urlString = serverURL + "/?" + Constants.ROOT_PATH + // "=" + rootPath + "&" + Constants.USE_ROOT_RELATIVE_PATH + "=" + // useRootRelativePath; // con = (HttpURLConnection) new URL(urlString).openConnection(); // con.setRequestMethod(METHOD); // con.setReadTimeout(READ_TIMEOUT); // con.getResponseCode(); // } finally { // con.disconnect(); // } // } // } // Path: rsimulator-http/src/test/java/com/github/bjuvensjo/rsimulator/http/HttpSimulatorIT.java import com.github.bjuvensjo.rsimulator.http.config.HttpSimulatorConfig; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.Paths; import static org.junit.jupiter.api.Assertions.*; package com.github.bjuvensjo.rsimulator.http; public class HttpSimulatorIT { private static final int BUFFER_SIZE = 500; private static final int READ_TIMEOUT = 12000; private static final String ENCODING = "UTF-8"; private static final String PORT = System.getProperty("jetty.port", "25001"); @BeforeEach public void init() { try { String resource = "/txt-examples"; String rootPath = Paths.get(getClass().getResource(resource).toURI()).toString().replace(resource, "");
HttpSimulatorConfig.config(rootPath, true, "http://localhost:" + PORT);
bjuvensjo/rsimulator
rsimulator-proxy/src/main/java/com/github/bjuvensjo/rsimulator/proxy/Proxy.java
// Path: rsimulator-proxy/src/main/java/com/github/bjuvensjo/rsimulator/proxy/config/ProxyModule.java // public class ProxyModule extends AbstractModule { // private final Logger log = LoggerFactory.getLogger(ProxyModule.class); // // /* // * (non-Javadoc) // * // * @see com.google.inject.AbstractModule#configure() // */ // @Override // protected void configure() { // // ***** Properties ***** // URL resource = getClass().getResource("/URIMapper.txt"); // if (resource == null) { // log.debug("No /URIMapper.txt resource exists."); // } else { // bind(File.class).annotatedWith(Names.named("uri-mappings")).toInstance( // new File(resource.getFile())); // } // } // }
import com.github.bjuvensjo.rsimulator.proxy.config.ProxyModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import jakarta.servlet.ServletConfig; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL;
package com.github.bjuvensjo.rsimulator.proxy; /** * The Proxy servlet proxies as {@link URIMapper} is configured. */ @WebServlet(urlPatterns = "/*") public class Proxy extends HttpServlet { private static final long serialVersionUID = 1L; private final Logger log = LoggerFactory.getLogger(Proxy.class); private static final int READ_TIMEOUT = 12000; @Inject private URIMapper uriMapper; @Inject private RequestHandler requestHandler; @Inject private ResponseHandler responseHandler; @Inject private SecurityHandler securityHandler; @Override public void init(ServletConfig config) throws ServletException { super.init(config); try {
// Path: rsimulator-proxy/src/main/java/com/github/bjuvensjo/rsimulator/proxy/config/ProxyModule.java // public class ProxyModule extends AbstractModule { // private final Logger log = LoggerFactory.getLogger(ProxyModule.class); // // /* // * (non-Javadoc) // * // * @see com.google.inject.AbstractModule#configure() // */ // @Override // protected void configure() { // // ***** Properties ***** // URL resource = getClass().getResource("/URIMapper.txt"); // if (resource == null) { // log.debug("No /URIMapper.txt resource exists."); // } else { // bind(File.class).annotatedWith(Names.named("uri-mappings")).toInstance( // new File(resource.getFile())); // } // } // } // Path: rsimulator-proxy/src/main/java/com/github/bjuvensjo/rsimulator/proxy/Proxy.java import com.github.bjuvensjo.rsimulator.proxy.config.ProxyModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import jakarta.servlet.ServletConfig; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; package com.github.bjuvensjo.rsimulator.proxy; /** * The Proxy servlet proxies as {@link URIMapper} is configured. */ @WebServlet(urlPatterns = "/*") public class Proxy extends HttpServlet { private static final long serialVersionUID = 1L; private final Logger log = LoggerFactory.getLogger(Proxy.class); private static final int READ_TIMEOUT = 12000; @Inject private URIMapper uriMapper; @Inject private RequestHandler requestHandler; @Inject private ResponseHandler responseHandler; @Inject private SecurityHandler securityHandler; @Override public void init(ServletConfig config) throws ServletException { super.init(config); try {
Injector injector = Guice.createInjector(new ProxyModule());
bjuvensjo/rsimulator
rsimulator-cxf-rt-transport/src/main/java/com/github/bjuvensjo/rsimulator/cxf/transport/RSimulatorConduit.java
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/Simulator.java // @ImplementedBy(SimulatorImpl.class) // public interface Simulator { // // /** // * Returns a SimulatorResponse that matches the specified request. // * // * @param rootPath the root path on which to search recursively for matches to the specified request // * @param rootRelativePath the path on which to search recursively for matches to the specified request // * @param request the request // * @param contentType the content type of the request, e.g. txt or xml // * @param vars vars that can be used in for example scripts // * @return a SimulatorResponse that matches the specified request // */ // Optional<SimulatorResponse> service(String rootPath, String rootRelativePath, String request, String contentType, Map<String, Object>... vars); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // }
import com.github.bjuvensjo.rsimulator.core.Simulator; import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import org.apache.cxf.Bus; import org.apache.cxf.common.logging.LogUtils; import org.apache.cxf.io.CachedOutputStream; import org.apache.cxf.message.Exchange; import org.apache.cxf.message.Message; import org.apache.cxf.message.MessageImpl; import org.apache.cxf.service.Service; import org.apache.cxf.service.model.EndpointInfo; import org.apache.cxf.transport.AbstractConduit; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.Optional; import java.util.Properties; import java.util.logging.Logger;
package com.github.bjuvensjo.rsimulator.cxf.transport; /** * Conduit implementation that takes incoming requests and tries to find corresponding response using call-by-reference * to a local jvm simulator instance without using the http-protocol. */ public class RSimulatorConduit extends AbstractConduit { private static final Logger LOG = LogUtils.getL7dLogger(RSimulatorConduit.class);
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/Simulator.java // @ImplementedBy(SimulatorImpl.class) // public interface Simulator { // // /** // * Returns a SimulatorResponse that matches the specified request. // * // * @param rootPath the root path on which to search recursively for matches to the specified request // * @param rootRelativePath the path on which to search recursively for matches to the specified request // * @param request the request // * @param contentType the content type of the request, e.g. txt or xml // * @param vars vars that can be used in for example scripts // * @return a SimulatorResponse that matches the specified request // */ // Optional<SimulatorResponse> service(String rootPath, String rootRelativePath, String request, String contentType, Map<String, Object>... vars); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // } // Path: rsimulator-cxf-rt-transport/src/main/java/com/github/bjuvensjo/rsimulator/cxf/transport/RSimulatorConduit.java import com.github.bjuvensjo.rsimulator.core.Simulator; import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import org.apache.cxf.Bus; import org.apache.cxf.common.logging.LogUtils; import org.apache.cxf.io.CachedOutputStream; import org.apache.cxf.message.Exchange; import org.apache.cxf.message.Message; import org.apache.cxf.message.MessageImpl; import org.apache.cxf.service.Service; import org.apache.cxf.service.model.EndpointInfo; import org.apache.cxf.transport.AbstractConduit; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.Optional; import java.util.Properties; import java.util.logging.Logger; package com.github.bjuvensjo.rsimulator.cxf.transport; /** * Conduit implementation that takes incoming requests and tries to find corresponding response using call-by-reference * to a local jvm simulator instance without using the http-protocol. */ public class RSimulatorConduit extends AbstractConduit { private static final Logger LOG = LogUtils.getL7dLogger(RSimulatorConduit.class);
private final Simulator simulator;
bjuvensjo/rsimulator
rsimulator-cxf-rt-transport/src/main/java/com/github/bjuvensjo/rsimulator/cxf/transport/RSimulatorConduit.java
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/Simulator.java // @ImplementedBy(SimulatorImpl.class) // public interface Simulator { // // /** // * Returns a SimulatorResponse that matches the specified request. // * // * @param rootPath the root path on which to search recursively for matches to the specified request // * @param rootRelativePath the path on which to search recursively for matches to the specified request // * @param request the request // * @param contentType the content type of the request, e.g. txt or xml // * @param vars vars that can be used in for example scripts // * @return a SimulatorResponse that matches the specified request // */ // Optional<SimulatorResponse> service(String rootPath, String rootRelativePath, String request, String contentType, Map<String, Object>... vars); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // }
import com.github.bjuvensjo.rsimulator.core.Simulator; import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import org.apache.cxf.Bus; import org.apache.cxf.common.logging.LogUtils; import org.apache.cxf.io.CachedOutputStream; import org.apache.cxf.message.Exchange; import org.apache.cxf.message.Message; import org.apache.cxf.message.MessageImpl; import org.apache.cxf.service.Service; import org.apache.cxf.service.model.EndpointInfo; import org.apache.cxf.transport.AbstractConduit; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.Optional; import java.util.Properties; import java.util.logging.Logger;
RSimulatorConduit(EndpointInfo endpointInfo, Simulator simulator, Bus bus, String rootPath) { super(endpointInfo.getTarget()); this.simulator = simulator; this.bus = bus; this.rootPath = rootPath; } @Override public void prepare(Message message) { message.setContent(OutputStream.class, new CachedOutputStream()); } @Override public void close(Message message) throws IOException { super.close(message); if (!isInbound(message)) { // notify caller that a response is received this.getMessageObserver().onMessage(createResponseMessage(message)); } } private boolean isInbound(Message message) { return Boolean.TRUE.equals(message.get("org.apache.cxf.message.inbound")); } private Message createResponseMessage(Message requestMessage) throws IOException { Message responseMessage = new MessageImpl(); OutputStream os = requestMessage.getContent(OutputStream.class); String encoding = getEncoding(requestMessage); String request = toString((CachedOutputStream) os, encoding);
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/Simulator.java // @ImplementedBy(SimulatorImpl.class) // public interface Simulator { // // /** // * Returns a SimulatorResponse that matches the specified request. // * // * @param rootPath the root path on which to search recursively for matches to the specified request // * @param rootRelativePath the path on which to search recursively for matches to the specified request // * @param request the request // * @param contentType the content type of the request, e.g. txt or xml // * @param vars vars that can be used in for example scripts // * @return a SimulatorResponse that matches the specified request // */ // Optional<SimulatorResponse> service(String rootPath, String rootRelativePath, String request, String contentType, Map<String, Object>... vars); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // } // Path: rsimulator-cxf-rt-transport/src/main/java/com/github/bjuvensjo/rsimulator/cxf/transport/RSimulatorConduit.java import com.github.bjuvensjo.rsimulator.core.Simulator; import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import org.apache.cxf.Bus; import org.apache.cxf.common.logging.LogUtils; import org.apache.cxf.io.CachedOutputStream; import org.apache.cxf.message.Exchange; import org.apache.cxf.message.Message; import org.apache.cxf.message.MessageImpl; import org.apache.cxf.service.Service; import org.apache.cxf.service.model.EndpointInfo; import org.apache.cxf.transport.AbstractConduit; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.Optional; import java.util.Properties; import java.util.logging.Logger; RSimulatorConduit(EndpointInfo endpointInfo, Simulator simulator, Bus bus, String rootPath) { super(endpointInfo.getTarget()); this.simulator = simulator; this.bus = bus; this.rootPath = rootPath; } @Override public void prepare(Message message) { message.setContent(OutputStream.class, new CachedOutputStream()); } @Override public void close(Message message) throws IOException { super.close(message); if (!isInbound(message)) { // notify caller that a response is received this.getMessageObserver().onMessage(createResponseMessage(message)); } } private boolean isInbound(Message message) { return Boolean.TRUE.equals(message.get("org.apache.cxf.message.inbound")); } private Message createResponseMessage(Message requestMessage) throws IOException { Message responseMessage = new MessageImpl(); OutputStream os = requestMessage.getContent(OutputStream.class); String encoding = getEncoding(requestMessage); String request = toString((CachedOutputStream) os, encoding);
Optional<SimulatorResponse> response = findResponse(getPath(requestMessage), request);
bjuvensjo/rsimulator
rsimulator-cxf-rt-transport/src/main/java/com/github/bjuvensjo/rsimulator/cxf/transport/RSimulatorTransportFactory.java
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/Simulator.java // @ImplementedBy(SimulatorImpl.class) // public interface Simulator { // // /** // * Returns a SimulatorResponse that matches the specified request. // * // * @param rootPath the root path on which to search recursively for matches to the specified request // * @param rootRelativePath the path on which to search recursively for matches to the specified request // * @param request the request // * @param contentType the content type of the request, e.g. txt or xml // * @param vars vars that can be used in for example scripts // * @return a SimulatorResponse that matches the specified request // */ // Optional<SimulatorResponse> service(String rootPath, String rootRelativePath, String request, String contentType, Map<String, Object>... vars); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/config/CoreModule.java // public class CoreModule extends AbstractModule { // private final Logger log = LoggerFactory.getLogger(CoreModule.class); // private static final CacheManager cacheManager = CacheManager.create(); // // @Provides // @Named("rsimulator-core-properties") // java.util.Properties provideProperties() { // java.util.Properties properties = new java.util.Properties(); // URL resource = getClass().getResource("/rsimulator.properties"); // if (resource == null) { // properties.setProperty("simulatorCache", "false"); // properties.setProperty("ignoreXmlNamespaces", "false"); // } else { // try (BufferedInputStream bis = new BufferedInputStream(resource.openStream())) { // properties.load(bis); // } catch (Exception e) { // log.error("Error reading properties from: {}", resource.getPath(), e); // } // } // return properties; // } // // @Override // protected void configure() { // MapBinder<String, Handler> map = MapBinder.newMapBinder(binder(), String.class, Handler.class); // map.addBinding("json").to(JsonHandler.class); // map.addBinding("txt").to(TxtHandler.class); // map.addBinding("xml").to(XmlHandler.class); // // // ***** Interceptors for cache and script ***** // Arrays.asList("SimulatorCache", "FileUtilsCache", "PropsCache").forEach(name -> // bind(net.sf.ehcache.Cache.class).annotatedWith(Names.named(name)).toInstance(cacheManager.getCache(name))); // // // SimulatorPropertiesInterceptor simulatorPropertiesInterceptor = new SimulatorPropertiesInterceptor(); // SimulatorCacheInterceptor simulatorCacheInterceptor = new SimulatorCacheInterceptor(); // SimulatorScriptInterceptor simulatorScriptInterceptor = new SimulatorScriptInterceptor(); // FileUtilsCacheInterceptor fileUtilsCacheInterceptor = new FileUtilsCacheInterceptor(); // PropsCacheInterceptor propsCacheInterceptor = new PropsCacheInterceptor(); // // requestInjection(simulatorPropertiesInterceptor); // requestInjection(simulatorCacheInterceptor); // requestInjection(simulatorScriptInterceptor); // requestInjection(fileUtilsCacheInterceptor); // requestInjection(propsCacheInterceptor); // // // Order is significant // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Properties.class), // simulatorPropertiesInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Cache.class), // simulatorCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Script.class), // simulatorScriptInterceptor); // bindInterceptor(Matchers.subclassesOf(FileUtils.class), Matchers.annotatedWith(Cache.class), // fileUtilsCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Props.class), Matchers.annotatedWith(Cache.class), // propsCacheInterceptor); // } // }
import com.github.bjuvensjo.rsimulator.core.Simulator; import com.github.bjuvensjo.rsimulator.core.config.CoreModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import org.apache.cxf.Bus; import org.apache.cxf.service.model.EndpointInfo; import org.apache.cxf.transport.AbstractTransportFactory; import org.apache.cxf.transport.Conduit; import org.apache.cxf.transport.ConduitInitiator; import org.apache.cxf.transport.http.HTTPTransportFactory; import org.apache.cxf.ws.addressing.EndpointReferenceType; import java.util.Collections; import java.util.List; import java.util.Set;
package com.github.bjuvensjo.rsimulator.cxf.transport; /** * Custom transport factory for CXF that provides Conduits which uses RSimulator CoreModule to match outgoing requests * with responses. * <p> * The purpose is to be able to use the simulator easily and efficient without the requirement of using the http-protocol. */ public class RSimulatorTransportFactory extends AbstractTransportFactory implements ConduitInitiator { private final Set<String> uriPrefixes; private final String rootPath; @Inject
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/Simulator.java // @ImplementedBy(SimulatorImpl.class) // public interface Simulator { // // /** // * Returns a SimulatorResponse that matches the specified request. // * // * @param rootPath the root path on which to search recursively for matches to the specified request // * @param rootRelativePath the path on which to search recursively for matches to the specified request // * @param request the request // * @param contentType the content type of the request, e.g. txt or xml // * @param vars vars that can be used in for example scripts // * @return a SimulatorResponse that matches the specified request // */ // Optional<SimulatorResponse> service(String rootPath, String rootRelativePath, String request, String contentType, Map<String, Object>... vars); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/config/CoreModule.java // public class CoreModule extends AbstractModule { // private final Logger log = LoggerFactory.getLogger(CoreModule.class); // private static final CacheManager cacheManager = CacheManager.create(); // // @Provides // @Named("rsimulator-core-properties") // java.util.Properties provideProperties() { // java.util.Properties properties = new java.util.Properties(); // URL resource = getClass().getResource("/rsimulator.properties"); // if (resource == null) { // properties.setProperty("simulatorCache", "false"); // properties.setProperty("ignoreXmlNamespaces", "false"); // } else { // try (BufferedInputStream bis = new BufferedInputStream(resource.openStream())) { // properties.load(bis); // } catch (Exception e) { // log.error("Error reading properties from: {}", resource.getPath(), e); // } // } // return properties; // } // // @Override // protected void configure() { // MapBinder<String, Handler> map = MapBinder.newMapBinder(binder(), String.class, Handler.class); // map.addBinding("json").to(JsonHandler.class); // map.addBinding("txt").to(TxtHandler.class); // map.addBinding("xml").to(XmlHandler.class); // // // ***** Interceptors for cache and script ***** // Arrays.asList("SimulatorCache", "FileUtilsCache", "PropsCache").forEach(name -> // bind(net.sf.ehcache.Cache.class).annotatedWith(Names.named(name)).toInstance(cacheManager.getCache(name))); // // // SimulatorPropertiesInterceptor simulatorPropertiesInterceptor = new SimulatorPropertiesInterceptor(); // SimulatorCacheInterceptor simulatorCacheInterceptor = new SimulatorCacheInterceptor(); // SimulatorScriptInterceptor simulatorScriptInterceptor = new SimulatorScriptInterceptor(); // FileUtilsCacheInterceptor fileUtilsCacheInterceptor = new FileUtilsCacheInterceptor(); // PropsCacheInterceptor propsCacheInterceptor = new PropsCacheInterceptor(); // // requestInjection(simulatorPropertiesInterceptor); // requestInjection(simulatorCacheInterceptor); // requestInjection(simulatorScriptInterceptor); // requestInjection(fileUtilsCacheInterceptor); // requestInjection(propsCacheInterceptor); // // // Order is significant // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Properties.class), // simulatorPropertiesInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Cache.class), // simulatorCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Script.class), // simulatorScriptInterceptor); // bindInterceptor(Matchers.subclassesOf(FileUtils.class), Matchers.annotatedWith(Cache.class), // fileUtilsCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Props.class), Matchers.annotatedWith(Cache.class), // propsCacheInterceptor); // } // } // Path: rsimulator-cxf-rt-transport/src/main/java/com/github/bjuvensjo/rsimulator/cxf/transport/RSimulatorTransportFactory.java import com.github.bjuvensjo.rsimulator.core.Simulator; import com.github.bjuvensjo.rsimulator.core.config.CoreModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import org.apache.cxf.Bus; import org.apache.cxf.service.model.EndpointInfo; import org.apache.cxf.transport.AbstractTransportFactory; import org.apache.cxf.transport.Conduit; import org.apache.cxf.transport.ConduitInitiator; import org.apache.cxf.transport.http.HTTPTransportFactory; import org.apache.cxf.ws.addressing.EndpointReferenceType; import java.util.Collections; import java.util.List; import java.util.Set; package com.github.bjuvensjo.rsimulator.cxf.transport; /** * Custom transport factory for CXF that provides Conduits which uses RSimulator CoreModule to match outgoing requests * with responses. * <p> * The purpose is to be able to use the simulator easily and efficient without the requirement of using the http-protocol. */ public class RSimulatorTransportFactory extends AbstractTransportFactory implements ConduitInitiator { private final Set<String> uriPrefixes; private final String rootPath; @Inject
private Simulator simulator;
bjuvensjo/rsimulator
rsimulator-cxf-rt-transport/src/main/java/com/github/bjuvensjo/rsimulator/cxf/transport/RSimulatorTransportFactory.java
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/Simulator.java // @ImplementedBy(SimulatorImpl.class) // public interface Simulator { // // /** // * Returns a SimulatorResponse that matches the specified request. // * // * @param rootPath the root path on which to search recursively for matches to the specified request // * @param rootRelativePath the path on which to search recursively for matches to the specified request // * @param request the request // * @param contentType the content type of the request, e.g. txt or xml // * @param vars vars that can be used in for example scripts // * @return a SimulatorResponse that matches the specified request // */ // Optional<SimulatorResponse> service(String rootPath, String rootRelativePath, String request, String contentType, Map<String, Object>... vars); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/config/CoreModule.java // public class CoreModule extends AbstractModule { // private final Logger log = LoggerFactory.getLogger(CoreModule.class); // private static final CacheManager cacheManager = CacheManager.create(); // // @Provides // @Named("rsimulator-core-properties") // java.util.Properties provideProperties() { // java.util.Properties properties = new java.util.Properties(); // URL resource = getClass().getResource("/rsimulator.properties"); // if (resource == null) { // properties.setProperty("simulatorCache", "false"); // properties.setProperty("ignoreXmlNamespaces", "false"); // } else { // try (BufferedInputStream bis = new BufferedInputStream(resource.openStream())) { // properties.load(bis); // } catch (Exception e) { // log.error("Error reading properties from: {}", resource.getPath(), e); // } // } // return properties; // } // // @Override // protected void configure() { // MapBinder<String, Handler> map = MapBinder.newMapBinder(binder(), String.class, Handler.class); // map.addBinding("json").to(JsonHandler.class); // map.addBinding("txt").to(TxtHandler.class); // map.addBinding("xml").to(XmlHandler.class); // // // ***** Interceptors for cache and script ***** // Arrays.asList("SimulatorCache", "FileUtilsCache", "PropsCache").forEach(name -> // bind(net.sf.ehcache.Cache.class).annotatedWith(Names.named(name)).toInstance(cacheManager.getCache(name))); // // // SimulatorPropertiesInterceptor simulatorPropertiesInterceptor = new SimulatorPropertiesInterceptor(); // SimulatorCacheInterceptor simulatorCacheInterceptor = new SimulatorCacheInterceptor(); // SimulatorScriptInterceptor simulatorScriptInterceptor = new SimulatorScriptInterceptor(); // FileUtilsCacheInterceptor fileUtilsCacheInterceptor = new FileUtilsCacheInterceptor(); // PropsCacheInterceptor propsCacheInterceptor = new PropsCacheInterceptor(); // // requestInjection(simulatorPropertiesInterceptor); // requestInjection(simulatorCacheInterceptor); // requestInjection(simulatorScriptInterceptor); // requestInjection(fileUtilsCacheInterceptor); // requestInjection(propsCacheInterceptor); // // // Order is significant // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Properties.class), // simulatorPropertiesInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Cache.class), // simulatorCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Script.class), // simulatorScriptInterceptor); // bindInterceptor(Matchers.subclassesOf(FileUtils.class), Matchers.annotatedWith(Cache.class), // fileUtilsCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Props.class), Matchers.annotatedWith(Cache.class), // propsCacheInterceptor); // } // }
import com.github.bjuvensjo.rsimulator.core.Simulator; import com.github.bjuvensjo.rsimulator.core.config.CoreModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import org.apache.cxf.Bus; import org.apache.cxf.service.model.EndpointInfo; import org.apache.cxf.transport.AbstractTransportFactory; import org.apache.cxf.transport.Conduit; import org.apache.cxf.transport.ConduitInitiator; import org.apache.cxf.transport.http.HTTPTransportFactory; import org.apache.cxf.ws.addressing.EndpointReferenceType; import java.util.Collections; import java.util.List; import java.util.Set;
package com.github.bjuvensjo.rsimulator.cxf.transport; /** * Custom transport factory for CXF that provides Conduits which uses RSimulator CoreModule to match outgoing requests * with responses. * <p> * The purpose is to be able to use the simulator easily and efficient without the requirement of using the http-protocol. */ public class RSimulatorTransportFactory extends AbstractTransportFactory implements ConduitInitiator { private final Set<String> uriPrefixes; private final String rootPath; @Inject private Simulator simulator; /** * Minimal constructor that registers itself as a factory for the "http://"-protocol. * * @param rootPath absolute path where the simulator should use as root when trying to find response */ public RSimulatorTransportFactory(String rootPath) { this(rootPath, Collections.singletonList("http://")); } /** * Constructor that accepts a list of protocols and a rootPath. * * @param rootPath absolute path where the simulator should use as root when trying to find response * @param protocols list of protocols for which this transport factory should be used */ public RSimulatorTransportFactory(String rootPath, List<String> protocols) { super(HTTPTransportFactory.DEFAULT_NAMESPACES);
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/Simulator.java // @ImplementedBy(SimulatorImpl.class) // public interface Simulator { // // /** // * Returns a SimulatorResponse that matches the specified request. // * // * @param rootPath the root path on which to search recursively for matches to the specified request // * @param rootRelativePath the path on which to search recursively for matches to the specified request // * @param request the request // * @param contentType the content type of the request, e.g. txt or xml // * @param vars vars that can be used in for example scripts // * @return a SimulatorResponse that matches the specified request // */ // Optional<SimulatorResponse> service(String rootPath, String rootRelativePath, String request, String contentType, Map<String, Object>... vars); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/config/CoreModule.java // public class CoreModule extends AbstractModule { // private final Logger log = LoggerFactory.getLogger(CoreModule.class); // private static final CacheManager cacheManager = CacheManager.create(); // // @Provides // @Named("rsimulator-core-properties") // java.util.Properties provideProperties() { // java.util.Properties properties = new java.util.Properties(); // URL resource = getClass().getResource("/rsimulator.properties"); // if (resource == null) { // properties.setProperty("simulatorCache", "false"); // properties.setProperty("ignoreXmlNamespaces", "false"); // } else { // try (BufferedInputStream bis = new BufferedInputStream(resource.openStream())) { // properties.load(bis); // } catch (Exception e) { // log.error("Error reading properties from: {}", resource.getPath(), e); // } // } // return properties; // } // // @Override // protected void configure() { // MapBinder<String, Handler> map = MapBinder.newMapBinder(binder(), String.class, Handler.class); // map.addBinding("json").to(JsonHandler.class); // map.addBinding("txt").to(TxtHandler.class); // map.addBinding("xml").to(XmlHandler.class); // // // ***** Interceptors for cache and script ***** // Arrays.asList("SimulatorCache", "FileUtilsCache", "PropsCache").forEach(name -> // bind(net.sf.ehcache.Cache.class).annotatedWith(Names.named(name)).toInstance(cacheManager.getCache(name))); // // // SimulatorPropertiesInterceptor simulatorPropertiesInterceptor = new SimulatorPropertiesInterceptor(); // SimulatorCacheInterceptor simulatorCacheInterceptor = new SimulatorCacheInterceptor(); // SimulatorScriptInterceptor simulatorScriptInterceptor = new SimulatorScriptInterceptor(); // FileUtilsCacheInterceptor fileUtilsCacheInterceptor = new FileUtilsCacheInterceptor(); // PropsCacheInterceptor propsCacheInterceptor = new PropsCacheInterceptor(); // // requestInjection(simulatorPropertiesInterceptor); // requestInjection(simulatorCacheInterceptor); // requestInjection(simulatorScriptInterceptor); // requestInjection(fileUtilsCacheInterceptor); // requestInjection(propsCacheInterceptor); // // // Order is significant // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Properties.class), // simulatorPropertiesInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Cache.class), // simulatorCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Script.class), // simulatorScriptInterceptor); // bindInterceptor(Matchers.subclassesOf(FileUtils.class), Matchers.annotatedWith(Cache.class), // fileUtilsCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Props.class), Matchers.annotatedWith(Cache.class), // propsCacheInterceptor); // } // } // Path: rsimulator-cxf-rt-transport/src/main/java/com/github/bjuvensjo/rsimulator/cxf/transport/RSimulatorTransportFactory.java import com.github.bjuvensjo.rsimulator.core.Simulator; import com.github.bjuvensjo.rsimulator.core.config.CoreModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import org.apache.cxf.Bus; import org.apache.cxf.service.model.EndpointInfo; import org.apache.cxf.transport.AbstractTransportFactory; import org.apache.cxf.transport.Conduit; import org.apache.cxf.transport.ConduitInitiator; import org.apache.cxf.transport.http.HTTPTransportFactory; import org.apache.cxf.ws.addressing.EndpointReferenceType; import java.util.Collections; import java.util.List; import java.util.Set; package com.github.bjuvensjo.rsimulator.cxf.transport; /** * Custom transport factory for CXF that provides Conduits which uses RSimulator CoreModule to match outgoing requests * with responses. * <p> * The purpose is to be able to use the simulator easily and efficient without the requirement of using the http-protocol. */ public class RSimulatorTransportFactory extends AbstractTransportFactory implements ConduitInitiator { private final Set<String> uriPrefixes; private final String rootPath; @Inject private Simulator simulator; /** * Minimal constructor that registers itself as a factory for the "http://"-protocol. * * @param rootPath absolute path where the simulator should use as root when trying to find response */ public RSimulatorTransportFactory(String rootPath) { this(rootPath, Collections.singletonList("http://")); } /** * Constructor that accepts a list of protocols and a rootPath. * * @param rootPath absolute path where the simulator should use as root when trying to find response * @param protocols list of protocols for which this transport factory should be used */ public RSimulatorTransportFactory(String rootPath, List<String> protocols) { super(HTTPTransportFactory.DEFAULT_NAMESPACES);
Injector injector = Guice.createInjector(new CoreModule());
bjuvensjo/rsimulator
rsimulator-aop/src/main/java/com/github/bjuvensjo/rsimulator/aop/SimulatorAdapter.java
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/Simulator.java // @ImplementedBy(SimulatorImpl.class) // public interface Simulator { // // /** // * Returns a SimulatorResponse that matches the specified request. // * // * @param rootPath the root path on which to search recursively for matches to the specified request // * @param rootRelativePath the path on which to search recursively for matches to the specified request // * @param request the request // * @param contentType the content type of the request, e.g. txt or xml // * @param vars vars that can be used in for example scripts // * @return a SimulatorResponse that matches the specified request // */ // Optional<SimulatorResponse> service(String rootPath, String rootRelativePath, String request, String contentType, Map<String, Object>... vars); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // }
import com.github.bjuvensjo.rsimulator.core.Simulator; import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import com.google.inject.Inject; import com.google.inject.Singleton; import com.thoughtworks.xstream.XStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Optional;
package com.github.bjuvensjo.rsimulator.aop; /** * The SimulatorAdapter is used to simulate java interface method invocations by means of AOP. */ @Singleton class SimulatorAdapter { private static final String CONTENT_TYPE = "xml"; private static final String REQUEST_BEGIN = "<request>"; private static final String REQUEST_END = "</request>"; private static final String RESPONSE_BEGIN = "<response>"; private static final int RESPONSE_BEGIN_LENGTH = RESPONSE_BEGIN.length(); private static final String RESPONSE_END = "</response>"; private static final String XML_VERSION = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; private final Logger log = LoggerFactory.getLogger(SimulatorAdapter.class); @Inject
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/Simulator.java // @ImplementedBy(SimulatorImpl.class) // public interface Simulator { // // /** // * Returns a SimulatorResponse that matches the specified request. // * // * @param rootPath the root path on which to search recursively for matches to the specified request // * @param rootRelativePath the path on which to search recursively for matches to the specified request // * @param request the request // * @param contentType the content type of the request, e.g. txt or xml // * @param vars vars that can be used in for example scripts // * @return a SimulatorResponse that matches the specified request // */ // Optional<SimulatorResponse> service(String rootPath, String rootRelativePath, String request, String contentType, Map<String, Object>... vars); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // } // Path: rsimulator-aop/src/main/java/com/github/bjuvensjo/rsimulator/aop/SimulatorAdapter.java import com.github.bjuvensjo.rsimulator.core.Simulator; import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import com.google.inject.Inject; import com.google.inject.Singleton; import com.thoughtworks.xstream.XStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Optional; package com.github.bjuvensjo.rsimulator.aop; /** * The SimulatorAdapter is used to simulate java interface method invocations by means of AOP. */ @Singleton class SimulatorAdapter { private static final String CONTENT_TYPE = "xml"; private static final String REQUEST_BEGIN = "<request>"; private static final String REQUEST_END = "</request>"; private static final String RESPONSE_BEGIN = "<response>"; private static final int RESPONSE_BEGIN_LENGTH = RESPONSE_BEGIN.length(); private static final String RESPONSE_END = "</response>"; private static final String XML_VERSION = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; private final Logger log = LoggerFactory.getLogger(SimulatorAdapter.class); @Inject
private Simulator simulator;
bjuvensjo/rsimulator
rsimulator-aop/src/main/java/com/github/bjuvensjo/rsimulator/aop/SimulatorAdapter.java
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/Simulator.java // @ImplementedBy(SimulatorImpl.class) // public interface Simulator { // // /** // * Returns a SimulatorResponse that matches the specified request. // * // * @param rootPath the root path on which to search recursively for matches to the specified request // * @param rootRelativePath the path on which to search recursively for matches to the specified request // * @param request the request // * @param contentType the content type of the request, e.g. txt or xml // * @param vars vars that can be used in for example scripts // * @return a SimulatorResponse that matches the specified request // */ // Optional<SimulatorResponse> service(String rootPath, String rootRelativePath, String request, String contentType, Map<String, Object>... vars); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // }
import com.github.bjuvensjo.rsimulator.core.Simulator; import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import com.google.inject.Inject; import com.google.inject.Singleton; import com.thoughtworks.xstream.XStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Optional;
package com.github.bjuvensjo.rsimulator.aop; /** * The SimulatorAdapter is used to simulate java interface method invocations by means of AOP. */ @Singleton class SimulatorAdapter { private static final String CONTENT_TYPE = "xml"; private static final String REQUEST_BEGIN = "<request>"; private static final String REQUEST_END = "</request>"; private static final String RESPONSE_BEGIN = "<response>"; private static final int RESPONSE_BEGIN_LENGTH = RESPONSE_BEGIN.length(); private static final String RESPONSE_END = "</response>"; private static final String XML_VERSION = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; private final Logger log = LoggerFactory.getLogger(SimulatorAdapter.class); @Inject private Simulator simulator; /** * Returns some simulation response if found. * * @param declaringClassCanonicalName the class that declares the intercepted method * @param methodName the name of the intercepted method * @param arguments the arguments to the intercepted method * @param rootPath the root path in which to (recursively) find simulator test data * @param useRootRelativePath true if the declaringClassCanonicalName and methodName should be used as an relative path extension of rootPath, otherwise false * @return some simulation response * @throws Exception if something goes wrong */ @SuppressWarnings("unchecked") public Object service(String declaringClassCanonicalName, String methodName, Object[] arguments, String rootPath, boolean useRootRelativePath) throws Exception { String rootRelativePath = useRootRelativePath ? getRootRelativePath(declaringClassCanonicalName, methodName) : ""; String simulatorRequest = createRequest(arguments);
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/Simulator.java // @ImplementedBy(SimulatorImpl.class) // public interface Simulator { // // /** // * Returns a SimulatorResponse that matches the specified request. // * // * @param rootPath the root path on which to search recursively for matches to the specified request // * @param rootRelativePath the path on which to search recursively for matches to the specified request // * @param request the request // * @param contentType the content type of the request, e.g. txt or xml // * @param vars vars that can be used in for example scripts // * @return a SimulatorResponse that matches the specified request // */ // Optional<SimulatorResponse> service(String rootPath, String rootRelativePath, String request, String contentType, Map<String, Object>... vars); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // } // Path: rsimulator-aop/src/main/java/com/github/bjuvensjo/rsimulator/aop/SimulatorAdapter.java import com.github.bjuvensjo.rsimulator.core.Simulator; import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import com.google.inject.Inject; import com.google.inject.Singleton; import com.thoughtworks.xstream.XStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Optional; package com.github.bjuvensjo.rsimulator.aop; /** * The SimulatorAdapter is used to simulate java interface method invocations by means of AOP. */ @Singleton class SimulatorAdapter { private static final String CONTENT_TYPE = "xml"; private static final String REQUEST_BEGIN = "<request>"; private static final String REQUEST_END = "</request>"; private static final String RESPONSE_BEGIN = "<response>"; private static final int RESPONSE_BEGIN_LENGTH = RESPONSE_BEGIN.length(); private static final String RESPONSE_END = "</response>"; private static final String XML_VERSION = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; private final Logger log = LoggerFactory.getLogger(SimulatorAdapter.class); @Inject private Simulator simulator; /** * Returns some simulation response if found. * * @param declaringClassCanonicalName the class that declares the intercepted method * @param methodName the name of the intercepted method * @param arguments the arguments to the intercepted method * @param rootPath the root path in which to (recursively) find simulator test data * @param useRootRelativePath true if the declaringClassCanonicalName and methodName should be used as an relative path extension of rootPath, otherwise false * @return some simulation response * @throws Exception if something goes wrong */ @SuppressWarnings("unchecked") public Object service(String declaringClassCanonicalName, String methodName, Object[] arguments, String rootPath, boolean useRootRelativePath) throws Exception { String rootRelativePath = useRootRelativePath ? getRootRelativePath(declaringClassCanonicalName, methodName) : ""; String simulatorRequest = createRequest(arguments);
Optional<SimulatorResponse> simulatorResponseOptional = simulator.service(rootPath, rootRelativePath, simulatorRequest, CONTENT_TYPE);
bjuvensjo/rsimulator
rsimulator-http/src/test/java/com/github/bjuvensjo/rsimulator/http/ScriptFilterIT.java
// Path: rsimulator-http/src/main/java/com/github/bjuvensjo/rsimulator/http/config/HttpSimulatorConfig.java // public final class HttpSimulatorConfig { // private static final int READ_TIMEOUT = 12000; // private static final String DEFAULT_SERVER_URL = "http://localhost:8080"; // private static final String METHOD = "GET"; // // private HttpSimulatorConfig() { // } // // /** // * Configures the HttpSimulator (running on the default http://localhost:8080) with the root path of the folder of // * the specified testClass class folder. // * // * @param testClass the testClass // * @throws IOException if something goes wrong // */ // public static void config(Class<?> testClass) throws IOException { // config(testClass, DEFAULT_SERVER_URL); // } // // /** // * Configures the HttpSimulator running on the specified serverURL (e.g. http://localhost:8080) with the root path // * of the folder of the specified testClass class folder. // * // * @param testClass the testClass // * @param serverURL the serverURL // * @throws IOException if something goes wrong // */ // public static void config(Class<?> testClass, String serverURL) throws IOException { // String resource = testClass.getSimpleName() + ".class"; // String rootPath = new File(testClass.getResource(resource).getPath()).getParentFile().getPath(); // config(rootPath, false, serverURL); // } // // /** // * Configures the HttpSimulator (running on the default http://localhost:8080) with the specified root path and // * useRootRelativePath. // * // * @param rootPath the rootPath // * @param useRootRelativePath the useRootRelativePath // * @throws IOException if something goes wrong // */ // public static void config(String rootPath, boolean useRootRelativePath) throws IOException { // config(rootPath, useRootRelativePath, DEFAULT_SERVER_URL); // } // // /** // * Configures the HttpSimulator running on the specified serverURL (e.g. http://localhost:8080) with the specified // * root path and useRootRelativePath. // * // * @param rootPath the rootPath // * @param useRootRelativePath the useRootRelativePath // * @param serverURL the serverURL // * @throws IOException if something goes wrong // */ // public static void config(String rootPath, boolean useRootRelativePath, String serverURL) throws IOException { // HttpURLConnection con = null; // try { // String urlString = serverURL + "/?" + Constants.ROOT_PATH + // "=" + rootPath + "&" + Constants.USE_ROOT_RELATIVE_PATH + "=" + // useRootRelativePath; // con = (HttpURLConnection) new URL(urlString).openConnection(); // con.setRequestMethod(METHOD); // con.setReadTimeout(READ_TIMEOUT); // con.getResponseCode(); // } finally { // con.disconnect(); // } // } // }
import com.github.bjuvensjo.rsimulator.http.config.HttpSimulatorConfig; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.Paths; import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.*;
package com.github.bjuvensjo.rsimulator.http; public class ScriptFilterIT { private static final int BUFFER_SIZE = 500; private static final int READ_TIMEOUT = 12000; private static final String ENCODING = "UTF-8"; private static final String PORT = System.getProperty("jetty.port", "25001"); @BeforeEach public void setUp() throws Exception { String resource = "/txt-examples"; String rootPath = Paths.get(getClass().getResource(resource).toURI()).toString().replace(resource, "");
// Path: rsimulator-http/src/main/java/com/github/bjuvensjo/rsimulator/http/config/HttpSimulatorConfig.java // public final class HttpSimulatorConfig { // private static final int READ_TIMEOUT = 12000; // private static final String DEFAULT_SERVER_URL = "http://localhost:8080"; // private static final String METHOD = "GET"; // // private HttpSimulatorConfig() { // } // // /** // * Configures the HttpSimulator (running on the default http://localhost:8080) with the root path of the folder of // * the specified testClass class folder. // * // * @param testClass the testClass // * @throws IOException if something goes wrong // */ // public static void config(Class<?> testClass) throws IOException { // config(testClass, DEFAULT_SERVER_URL); // } // // /** // * Configures the HttpSimulator running on the specified serverURL (e.g. http://localhost:8080) with the root path // * of the folder of the specified testClass class folder. // * // * @param testClass the testClass // * @param serverURL the serverURL // * @throws IOException if something goes wrong // */ // public static void config(Class<?> testClass, String serverURL) throws IOException { // String resource = testClass.getSimpleName() + ".class"; // String rootPath = new File(testClass.getResource(resource).getPath()).getParentFile().getPath(); // config(rootPath, false, serverURL); // } // // /** // * Configures the HttpSimulator (running on the default http://localhost:8080) with the specified root path and // * useRootRelativePath. // * // * @param rootPath the rootPath // * @param useRootRelativePath the useRootRelativePath // * @throws IOException if something goes wrong // */ // public static void config(String rootPath, boolean useRootRelativePath) throws IOException { // config(rootPath, useRootRelativePath, DEFAULT_SERVER_URL); // } // // /** // * Configures the HttpSimulator running on the specified serverURL (e.g. http://localhost:8080) with the specified // * root path and useRootRelativePath. // * // * @param rootPath the rootPath // * @param useRootRelativePath the useRootRelativePath // * @param serverURL the serverURL // * @throws IOException if something goes wrong // */ // public static void config(String rootPath, boolean useRootRelativePath, String serverURL) throws IOException { // HttpURLConnection con = null; // try { // String urlString = serverURL + "/?" + Constants.ROOT_PATH + // "=" + rootPath + "&" + Constants.USE_ROOT_RELATIVE_PATH + "=" + // useRootRelativePath; // con = (HttpURLConnection) new URL(urlString).openConnection(); // con.setRequestMethod(METHOD); // con.setReadTimeout(READ_TIMEOUT); // con.getResponseCode(); // } finally { // con.disconnect(); // } // } // } // Path: rsimulator-http/src/test/java/com/github/bjuvensjo/rsimulator/http/ScriptFilterIT.java import com.github.bjuvensjo.rsimulator.http.config.HttpSimulatorConfig; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.Paths; import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.*; package com.github.bjuvensjo.rsimulator.http; public class ScriptFilterIT { private static final int BUFFER_SIZE = 500; private static final int READ_TIMEOUT = 12000; private static final String ENCODING = "UTF-8"; private static final String PORT = System.getProperty("jetty.port", "25001"); @BeforeEach public void setUp() throws Exception { String resource = "/txt-examples"; String rootPath = Paths.get(getClass().getResource(resource).toURI()).toString().replace(resource, "");
HttpSimulatorConfig.config(rootPath, true, "http://localhost:" + PORT);
bjuvensjo/rsimulator
rsimulator-camel-direct/src/main/java/com/github/bjuvensjo/rsimulator/camel/direct/DirectProcessor.java
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/Simulator.java // @ImplementedBy(SimulatorImpl.class) // public interface Simulator { // // /** // * Returns a SimulatorResponse that matches the specified request. // * // * @param rootPath the root path on which to search recursively for matches to the specified request // * @param rootRelativePath the path on which to search recursively for matches to the specified request // * @param request the request // * @param contentType the content type of the request, e.g. txt or xml // * @param vars vars that can be used in for example scripts // * @return a SimulatorResponse that matches the specified request // */ // Optional<SimulatorResponse> service(String rootPath, String rootRelativePath, String request, String contentType, Map<String, Object>... vars); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/config/CoreModule.java // public class CoreModule extends AbstractModule { // private final Logger log = LoggerFactory.getLogger(CoreModule.class); // private static final CacheManager cacheManager = CacheManager.create(); // // @Provides // @Named("rsimulator-core-properties") // java.util.Properties provideProperties() { // java.util.Properties properties = new java.util.Properties(); // URL resource = getClass().getResource("/rsimulator.properties"); // if (resource == null) { // properties.setProperty("simulatorCache", "false"); // properties.setProperty("ignoreXmlNamespaces", "false"); // } else { // try (BufferedInputStream bis = new BufferedInputStream(resource.openStream())) { // properties.load(bis); // } catch (Exception e) { // log.error("Error reading properties from: {}", resource.getPath(), e); // } // } // return properties; // } // // @Override // protected void configure() { // MapBinder<String, Handler> map = MapBinder.newMapBinder(binder(), String.class, Handler.class); // map.addBinding("json").to(JsonHandler.class); // map.addBinding("txt").to(TxtHandler.class); // map.addBinding("xml").to(XmlHandler.class); // // // ***** Interceptors for cache and script ***** // Arrays.asList("SimulatorCache", "FileUtilsCache", "PropsCache").forEach(name -> // bind(net.sf.ehcache.Cache.class).annotatedWith(Names.named(name)).toInstance(cacheManager.getCache(name))); // // // SimulatorPropertiesInterceptor simulatorPropertiesInterceptor = new SimulatorPropertiesInterceptor(); // SimulatorCacheInterceptor simulatorCacheInterceptor = new SimulatorCacheInterceptor(); // SimulatorScriptInterceptor simulatorScriptInterceptor = new SimulatorScriptInterceptor(); // FileUtilsCacheInterceptor fileUtilsCacheInterceptor = new FileUtilsCacheInterceptor(); // PropsCacheInterceptor propsCacheInterceptor = new PropsCacheInterceptor(); // // requestInjection(simulatorPropertiesInterceptor); // requestInjection(simulatorCacheInterceptor); // requestInjection(simulatorScriptInterceptor); // requestInjection(fileUtilsCacheInterceptor); // requestInjection(propsCacheInterceptor); // // // Order is significant // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Properties.class), // simulatorPropertiesInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Cache.class), // simulatorCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Script.class), // simulatorScriptInterceptor); // bindInterceptor(Matchers.subclassesOf(FileUtils.class), Matchers.annotatedWith(Cache.class), // fileUtilsCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Props.class), Matchers.annotatedWith(Cache.class), // propsCacheInterceptor); // } // }
import com.github.bjuvensjo.rsimulator.core.Simulator; import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import com.github.bjuvensjo.rsimulator.core.config.CoreModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import org.apache.camel.Exchange; import org.apache.camel.Processor; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern;
package com.github.bjuvensjo.rsimulator.camel.direct; public class DirectProcessor implements Processor { private static final Pattern ACCEPT_PATTERN = Pattern.compile("([^;]+)"); private static final Pattern CONTENT_TYPE_PATTERN = Pattern.compile("([^;]+)"); private static final String DEFAULT = "default"; Map<String, String> accepts; String endpointUri; DirectComponentConfig directComponentConfig; @Inject
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/Simulator.java // @ImplementedBy(SimulatorImpl.class) // public interface Simulator { // // /** // * Returns a SimulatorResponse that matches the specified request. // * // * @param rootPath the root path on which to search recursively for matches to the specified request // * @param rootRelativePath the path on which to search recursively for matches to the specified request // * @param request the request // * @param contentType the content type of the request, e.g. txt or xml // * @param vars vars that can be used in for example scripts // * @return a SimulatorResponse that matches the specified request // */ // Optional<SimulatorResponse> service(String rootPath, String rootRelativePath, String request, String contentType, Map<String, Object>... vars); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/config/CoreModule.java // public class CoreModule extends AbstractModule { // private final Logger log = LoggerFactory.getLogger(CoreModule.class); // private static final CacheManager cacheManager = CacheManager.create(); // // @Provides // @Named("rsimulator-core-properties") // java.util.Properties provideProperties() { // java.util.Properties properties = new java.util.Properties(); // URL resource = getClass().getResource("/rsimulator.properties"); // if (resource == null) { // properties.setProperty("simulatorCache", "false"); // properties.setProperty("ignoreXmlNamespaces", "false"); // } else { // try (BufferedInputStream bis = new BufferedInputStream(resource.openStream())) { // properties.load(bis); // } catch (Exception e) { // log.error("Error reading properties from: {}", resource.getPath(), e); // } // } // return properties; // } // // @Override // protected void configure() { // MapBinder<String, Handler> map = MapBinder.newMapBinder(binder(), String.class, Handler.class); // map.addBinding("json").to(JsonHandler.class); // map.addBinding("txt").to(TxtHandler.class); // map.addBinding("xml").to(XmlHandler.class); // // // ***** Interceptors for cache and script ***** // Arrays.asList("SimulatorCache", "FileUtilsCache", "PropsCache").forEach(name -> // bind(net.sf.ehcache.Cache.class).annotatedWith(Names.named(name)).toInstance(cacheManager.getCache(name))); // // // SimulatorPropertiesInterceptor simulatorPropertiesInterceptor = new SimulatorPropertiesInterceptor(); // SimulatorCacheInterceptor simulatorCacheInterceptor = new SimulatorCacheInterceptor(); // SimulatorScriptInterceptor simulatorScriptInterceptor = new SimulatorScriptInterceptor(); // FileUtilsCacheInterceptor fileUtilsCacheInterceptor = new FileUtilsCacheInterceptor(); // PropsCacheInterceptor propsCacheInterceptor = new PropsCacheInterceptor(); // // requestInjection(simulatorPropertiesInterceptor); // requestInjection(simulatorCacheInterceptor); // requestInjection(simulatorScriptInterceptor); // requestInjection(fileUtilsCacheInterceptor); // requestInjection(propsCacheInterceptor); // // // Order is significant // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Properties.class), // simulatorPropertiesInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Cache.class), // simulatorCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Script.class), // simulatorScriptInterceptor); // bindInterceptor(Matchers.subclassesOf(FileUtils.class), Matchers.annotatedWith(Cache.class), // fileUtilsCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Props.class), Matchers.annotatedWith(Cache.class), // propsCacheInterceptor); // } // } // Path: rsimulator-camel-direct/src/main/java/com/github/bjuvensjo/rsimulator/camel/direct/DirectProcessor.java import com.github.bjuvensjo.rsimulator.core.Simulator; import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import com.github.bjuvensjo.rsimulator.core.config.CoreModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import org.apache.camel.Exchange; import org.apache.camel.Processor; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; package com.github.bjuvensjo.rsimulator.camel.direct; public class DirectProcessor implements Processor { private static final Pattern ACCEPT_PATTERN = Pattern.compile("([^;]+)"); private static final Pattern CONTENT_TYPE_PATTERN = Pattern.compile("([^;]+)"); private static final String DEFAULT = "default"; Map<String, String> accepts; String endpointUri; DirectComponentConfig directComponentConfig; @Inject
Simulator simulator;
bjuvensjo/rsimulator
rsimulator-camel-direct/src/main/java/com/github/bjuvensjo/rsimulator/camel/direct/DirectProcessor.java
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/Simulator.java // @ImplementedBy(SimulatorImpl.class) // public interface Simulator { // // /** // * Returns a SimulatorResponse that matches the specified request. // * // * @param rootPath the root path on which to search recursively for matches to the specified request // * @param rootRelativePath the path on which to search recursively for matches to the specified request // * @param request the request // * @param contentType the content type of the request, e.g. txt or xml // * @param vars vars that can be used in for example scripts // * @return a SimulatorResponse that matches the specified request // */ // Optional<SimulatorResponse> service(String rootPath, String rootRelativePath, String request, String contentType, Map<String, Object>... vars); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/config/CoreModule.java // public class CoreModule extends AbstractModule { // private final Logger log = LoggerFactory.getLogger(CoreModule.class); // private static final CacheManager cacheManager = CacheManager.create(); // // @Provides // @Named("rsimulator-core-properties") // java.util.Properties provideProperties() { // java.util.Properties properties = new java.util.Properties(); // URL resource = getClass().getResource("/rsimulator.properties"); // if (resource == null) { // properties.setProperty("simulatorCache", "false"); // properties.setProperty("ignoreXmlNamespaces", "false"); // } else { // try (BufferedInputStream bis = new BufferedInputStream(resource.openStream())) { // properties.load(bis); // } catch (Exception e) { // log.error("Error reading properties from: {}", resource.getPath(), e); // } // } // return properties; // } // // @Override // protected void configure() { // MapBinder<String, Handler> map = MapBinder.newMapBinder(binder(), String.class, Handler.class); // map.addBinding("json").to(JsonHandler.class); // map.addBinding("txt").to(TxtHandler.class); // map.addBinding("xml").to(XmlHandler.class); // // // ***** Interceptors for cache and script ***** // Arrays.asList("SimulatorCache", "FileUtilsCache", "PropsCache").forEach(name -> // bind(net.sf.ehcache.Cache.class).annotatedWith(Names.named(name)).toInstance(cacheManager.getCache(name))); // // // SimulatorPropertiesInterceptor simulatorPropertiesInterceptor = new SimulatorPropertiesInterceptor(); // SimulatorCacheInterceptor simulatorCacheInterceptor = new SimulatorCacheInterceptor(); // SimulatorScriptInterceptor simulatorScriptInterceptor = new SimulatorScriptInterceptor(); // FileUtilsCacheInterceptor fileUtilsCacheInterceptor = new FileUtilsCacheInterceptor(); // PropsCacheInterceptor propsCacheInterceptor = new PropsCacheInterceptor(); // // requestInjection(simulatorPropertiesInterceptor); // requestInjection(simulatorCacheInterceptor); // requestInjection(simulatorScriptInterceptor); // requestInjection(fileUtilsCacheInterceptor); // requestInjection(propsCacheInterceptor); // // // Order is significant // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Properties.class), // simulatorPropertiesInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Cache.class), // simulatorCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Script.class), // simulatorScriptInterceptor); // bindInterceptor(Matchers.subclassesOf(FileUtils.class), Matchers.annotatedWith(Cache.class), // fileUtilsCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Props.class), Matchers.annotatedWith(Cache.class), // propsCacheInterceptor); // } // }
import com.github.bjuvensjo.rsimulator.core.Simulator; import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import com.github.bjuvensjo.rsimulator.core.config.CoreModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import org.apache.camel.Exchange; import org.apache.camel.Processor; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern;
package com.github.bjuvensjo.rsimulator.camel.direct; public class DirectProcessor implements Processor { private static final Pattern ACCEPT_PATTERN = Pattern.compile("([^;]+)"); private static final Pattern CONTENT_TYPE_PATTERN = Pattern.compile("([^;]+)"); private static final String DEFAULT = "default"; Map<String, String> accepts; String endpointUri; DirectComponentConfig directComponentConfig; @Inject Simulator simulator; Map<String, String> simulatorContentTypes; DirectProcessor(String endpointUri, DirectComponentConfig directComponentConfig) { this.endpointUri = endpointUri; this.directComponentConfig = directComponentConfig;
// Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/Simulator.java // @ImplementedBy(SimulatorImpl.class) // public interface Simulator { // // /** // * Returns a SimulatorResponse that matches the specified request. // * // * @param rootPath the root path on which to search recursively for matches to the specified request // * @param rootRelativePath the path on which to search recursively for matches to the specified request // * @param request the request // * @param contentType the content type of the request, e.g. txt or xml // * @param vars vars that can be used in for example scripts // * @return a SimulatorResponse that matches the specified request // */ // Optional<SimulatorResponse> service(String rootPath, String rootRelativePath, String request, String contentType, Map<String, Object>... vars); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/SimulatorResponse.java // public interface SimulatorResponse { // // /** // * Returns the properties of a specific test data request and response pair. If the name of the test data request // * file for instance is Test1Request.xml, the properties file must be named Test1.properties. For supported // * properties, see *PropertiesInterceptor classes. // * // * @return the properties of a specific test data request and response pair // */ // Optional<Properties> getProperties(); // // /** // * Sets the specified properties. // * // * @param properties the properties to set // */ // void setProperties(Optional<Properties> properties); // // /** // * Returns the test data response. // * // * @return the test data response // */ // String getResponse(); // // /** // * Sets the specified response. // * // * @param response the response to set // */ // void setResponse(String response); // // /** // * Returns the matching request path. // * // * @return the matching request path // */ // Path getMatchingRequest(); // // /** // * Sets the specified path. // * // * @param path the path to set // */ // void setMatchingRequest(Path path); // } // // Path: rsimulator-core/src/main/java/com/github/bjuvensjo/rsimulator/core/config/CoreModule.java // public class CoreModule extends AbstractModule { // private final Logger log = LoggerFactory.getLogger(CoreModule.class); // private static final CacheManager cacheManager = CacheManager.create(); // // @Provides // @Named("rsimulator-core-properties") // java.util.Properties provideProperties() { // java.util.Properties properties = new java.util.Properties(); // URL resource = getClass().getResource("/rsimulator.properties"); // if (resource == null) { // properties.setProperty("simulatorCache", "false"); // properties.setProperty("ignoreXmlNamespaces", "false"); // } else { // try (BufferedInputStream bis = new BufferedInputStream(resource.openStream())) { // properties.load(bis); // } catch (Exception e) { // log.error("Error reading properties from: {}", resource.getPath(), e); // } // } // return properties; // } // // @Override // protected void configure() { // MapBinder<String, Handler> map = MapBinder.newMapBinder(binder(), String.class, Handler.class); // map.addBinding("json").to(JsonHandler.class); // map.addBinding("txt").to(TxtHandler.class); // map.addBinding("xml").to(XmlHandler.class); // // // ***** Interceptors for cache and script ***** // Arrays.asList("SimulatorCache", "FileUtilsCache", "PropsCache").forEach(name -> // bind(net.sf.ehcache.Cache.class).annotatedWith(Names.named(name)).toInstance(cacheManager.getCache(name))); // // // SimulatorPropertiesInterceptor simulatorPropertiesInterceptor = new SimulatorPropertiesInterceptor(); // SimulatorCacheInterceptor simulatorCacheInterceptor = new SimulatorCacheInterceptor(); // SimulatorScriptInterceptor simulatorScriptInterceptor = new SimulatorScriptInterceptor(); // FileUtilsCacheInterceptor fileUtilsCacheInterceptor = new FileUtilsCacheInterceptor(); // PropsCacheInterceptor propsCacheInterceptor = new PropsCacheInterceptor(); // // requestInjection(simulatorPropertiesInterceptor); // requestInjection(simulatorCacheInterceptor); // requestInjection(simulatorScriptInterceptor); // requestInjection(fileUtilsCacheInterceptor); // requestInjection(propsCacheInterceptor); // // // Order is significant // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Properties.class), // simulatorPropertiesInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Cache.class), // simulatorCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Simulator.class), Matchers.annotatedWith(Script.class), // simulatorScriptInterceptor); // bindInterceptor(Matchers.subclassesOf(FileUtils.class), Matchers.annotatedWith(Cache.class), // fileUtilsCacheInterceptor); // bindInterceptor(Matchers.subclassesOf(Props.class), Matchers.annotatedWith(Cache.class), // propsCacheInterceptor); // } // } // Path: rsimulator-camel-direct/src/main/java/com/github/bjuvensjo/rsimulator/camel/direct/DirectProcessor.java import com.github.bjuvensjo.rsimulator.core.Simulator; import com.github.bjuvensjo.rsimulator.core.SimulatorResponse; import com.github.bjuvensjo.rsimulator.core.config.CoreModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import org.apache.camel.Exchange; import org.apache.camel.Processor; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; package com.github.bjuvensjo.rsimulator.camel.direct; public class DirectProcessor implements Processor { private static final Pattern ACCEPT_PATTERN = Pattern.compile("([^;]+)"); private static final Pattern CONTENT_TYPE_PATTERN = Pattern.compile("([^;]+)"); private static final String DEFAULT = "default"; Map<String, String> accepts; String endpointUri; DirectComponentConfig directComponentConfig; @Inject Simulator simulator; Map<String, String> simulatorContentTypes; DirectProcessor(String endpointUri, DirectComponentConfig directComponentConfig) { this.endpointUri = endpointUri; this.directComponentConfig = directComponentConfig;
Injector injector = Guice.createInjector(new CoreModule());
Qualtagh/JBroTable
src/io/github/qualtagh/swing/table/view/JBroTableColumn.java
// Path: src/io/github/qualtagh/swing/table/model/Utils.java // public class Utils { // private static final Logger LOGGER = Logger.getLogger( Utils.class ); // // public static boolean equals( Object o1, Object o2 ) { // return o1 == null ? o2 == null : o2 != null && o1.equals( o2 ); // } // // public static String rpad( String s, int n ) { // if ( null == s ) // return null; // if ( n <= 0 ) // return ""; // if ( n < s.length() ) // return s.substring( 0, n ); // return String.format( "%1$-" + n + "s", s ); // } // // public static String rpad( String text, char padChar, int length ) { // if ( text == null ) // return null; // if ( length <= 0 || length < text.length() ) // return text; // StringBuilder result = new StringBuilder( text ); // while ( result.length() < length ) // result.append( padChar ); // return result.toString(); // } // // public static void initSimpleConsoleLogger() { // String logProps = "log4j.rootLogger=DEBUG, Console\n" + // "log4j.appender.Console=org.apache.log4j.ConsoleAppender\n" + // "log4j.appender.Console.layout=org.apache.log4j.PatternLayout\n" + // "log4j.appender.Console.layout.ConversionPattern=%d{dd.MM.yy HH:mm:ss,SSS} [%p] - %m%n\n"; // Properties props = new Properties(); // try { // props.load( new ByteArrayInputStream( logProps.getBytes() ) ); // } catch ( IOException e ) { // } // PropertyConfigurator.configure( props ); // } // // public static void setSystemLookAndFeel() { // try { // UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() ); // } catch ( InstantiationException e ) { // LOGGER.error( null, e ); // } catch ( ClassNotFoundException e ) { // LOGGER.error( null, e ); // } catch ( IllegalAccessException e ) { // LOGGER.error( null, e ); // } catch ( UnsupportedLookAndFeelException e ) { // LOGGER.error( null, e ); // } // } // // public static void updateComponentTreeUI() { // for ( Window window : Window.getWindows() ) // updateComponentTreeUI( window ); // } // // private static void updateComponentTreeUI( Window window ) { // SwingUtilities.updateComponentTreeUI( window ); // for ( Window w : window.getOwnedWindows() ) // updateComponentTreeUI( w ); // } // }
import javax.swing.table.TableColumn; import io.github.qualtagh.swing.table.model.Utils;
} public int getColspan() { return colspan; } public void setColspan( int colspan ) { this.colspan = colspan; } public int getRowspan() { return rowspan; } @Override public String toString() { return "Column: " + getIdentifier() + " (" + getHeaderValue() + ") ( " + x + ", " + y + " )"; } @Override public int hashCode() { return identifier == null ? 0 : identifier.hashCode(); } @Override public boolean equals( Object obj ) { if ( !( obj instanceof JBroTableColumn ) ) return false; if ( obj == this ) return true;
// Path: src/io/github/qualtagh/swing/table/model/Utils.java // public class Utils { // private static final Logger LOGGER = Logger.getLogger( Utils.class ); // // public static boolean equals( Object o1, Object o2 ) { // return o1 == null ? o2 == null : o2 != null && o1.equals( o2 ); // } // // public static String rpad( String s, int n ) { // if ( null == s ) // return null; // if ( n <= 0 ) // return ""; // if ( n < s.length() ) // return s.substring( 0, n ); // return String.format( "%1$-" + n + "s", s ); // } // // public static String rpad( String text, char padChar, int length ) { // if ( text == null ) // return null; // if ( length <= 0 || length < text.length() ) // return text; // StringBuilder result = new StringBuilder( text ); // while ( result.length() < length ) // result.append( padChar ); // return result.toString(); // } // // public static void initSimpleConsoleLogger() { // String logProps = "log4j.rootLogger=DEBUG, Console\n" + // "log4j.appender.Console=org.apache.log4j.ConsoleAppender\n" + // "log4j.appender.Console.layout=org.apache.log4j.PatternLayout\n" + // "log4j.appender.Console.layout.ConversionPattern=%d{dd.MM.yy HH:mm:ss,SSS} [%p] - %m%n\n"; // Properties props = new Properties(); // try { // props.load( new ByteArrayInputStream( logProps.getBytes() ) ); // } catch ( IOException e ) { // } // PropertyConfigurator.configure( props ); // } // // public static void setSystemLookAndFeel() { // try { // UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() ); // } catch ( InstantiationException e ) { // LOGGER.error( null, e ); // } catch ( ClassNotFoundException e ) { // LOGGER.error( null, e ); // } catch ( IllegalAccessException e ) { // LOGGER.error( null, e ); // } catch ( UnsupportedLookAndFeelException e ) { // LOGGER.error( null, e ); // } // } // // public static void updateComponentTreeUI() { // for ( Window window : Window.getWindows() ) // updateComponentTreeUI( window ); // } // // private static void updateComponentTreeUI( Window window ) { // SwingUtilities.updateComponentTreeUI( window ); // for ( Window w : window.getOwnedWindows() ) // updateComponentTreeUI( w ); // } // } // Path: src/io/github/qualtagh/swing/table/view/JBroTableColumn.java import javax.swing.table.TableColumn; import io.github.qualtagh.swing.table.model.Utils; } public int getColspan() { return colspan; } public void setColspan( int colspan ) { this.colspan = colspan; } public int getRowspan() { return rowspan; } @Override public String toString() { return "Column: " + getIdentifier() + " (" + getHeaderValue() + ") ( " + x + ", " + y + " )"; } @Override public int hashCode() { return identifier == null ? 0 : identifier.hashCode(); } @Override public boolean equals( Object obj ) { if ( !( obj instanceof JBroTableColumn ) ) return false; if ( obj == this ) return true;
return Utils.equals( identifier, ( ( JBroTableColumn )obj ).identifier );
leonardoanalista/java2word
java2word/src/main/java/word/w2004/elements/TableV2.java
// Path: java2word/src/main/java/word/api/interfaces/IElement.java // public interface IElement { // // /** // * <p>This method returns the content (XML or HTML) of the Element and the content.</p> // * <p>If you are using W2004, the return will be the XML required to generate the element.</p> // * // * <p>Important: Once you call this method, the Document value is cached an no elements can be added later.</p> // * // * @return this is the String value of the element ready to be appended/inserted in the Document.<br> // * // * <p>This is the XML that generates a <code>BreakLine</code>:</p> // * <code> // * <w:p wsp:rsidR='008979E8' wsp:rsidRDefault='008979E8'/> // * </code> // */ // public String getContent(); // // } // // Path: java2word/src/main/java/word/w2004/elements/tableElements/TableRow.java // public class TableRow implements IElement, IFluentElementStylable<TableRowStyle>{ // // private StringBuilder txt = new StringBuilder(""); // private TableRowStyle style = new TableRowStyle(); // private final String tableRowTop = "\n <w:tr>{styleRowPh}"; // private final String tableRowBottom = "\n </w:tr>"; // // public TableRow(Object[] cols) { // txt.append(tableRowTop); // // for (int i = 0; i < cols.length; i++) { // //TableCell knows how to do the rest. // txt.append( TableCell.with(cols[i]).create().getContent() ); // } // // txt.append(tableRowBottom); // } // // @Override // public TableRowStyle withStyle() { // style.setElement(this); // return style; // } // // @Override // public String getContent() { // String withStyle = style.getNewContentWithStyle(txt.toString()); // return withStyle; // } // // public static TableRow with(Object ... colls) { // return new TableRow(colls); // } // // }
import word.api.interfaces.IElement; import word.w2004.elements.tableElements.TableRow;
package word.w2004.elements; /** * @author leonardo_correa * */ public class TableV2 implements IElement { private StringBuilder txt = new StringBuilder(""); private boolean hasBeenCalledBefore = false; public String getContent() { if (hasBeenCalledBefore) { return txt.toString(); } else { hasBeenCalledBefore = true; } if ("".equals(txt.toString())) { return ""; } // here it goes txt.insert(0, tableTop); txt.append("\n" + tableBottom); //apply style return txt.toString(); } /** * You always have to use TableRow to add new rows to the table. Eg.: * <code> * tbl.addRow( TableRowV2.with("Simple String cell") ); * </code> * See documentation on method "TableRowV2.with" for very detailed information. * * @param row * @return */
// Path: java2word/src/main/java/word/api/interfaces/IElement.java // public interface IElement { // // /** // * <p>This method returns the content (XML or HTML) of the Element and the content.</p> // * <p>If you are using W2004, the return will be the XML required to generate the element.</p> // * // * <p>Important: Once you call this method, the Document value is cached an no elements can be added later.</p> // * // * @return this is the String value of the element ready to be appended/inserted in the Document.<br> // * // * <p>This is the XML that generates a <code>BreakLine</code>:</p> // * <code> // * <w:p wsp:rsidR='008979E8' wsp:rsidRDefault='008979E8'/> // * </code> // */ // public String getContent(); // // } // // Path: java2word/src/main/java/word/w2004/elements/tableElements/TableRow.java // public class TableRow implements IElement, IFluentElementStylable<TableRowStyle>{ // // private StringBuilder txt = new StringBuilder(""); // private TableRowStyle style = new TableRowStyle(); // private final String tableRowTop = "\n <w:tr>{styleRowPh}"; // private final String tableRowBottom = "\n </w:tr>"; // // public TableRow(Object[] cols) { // txt.append(tableRowTop); // // for (int i = 0; i < cols.length; i++) { // //TableCell knows how to do the rest. // txt.append( TableCell.with(cols[i]).create().getContent() ); // } // // txt.append(tableRowBottom); // } // // @Override // public TableRowStyle withStyle() { // style.setElement(this); // return style; // } // // @Override // public String getContent() { // String withStyle = style.getNewContentWithStyle(txt.toString()); // return withStyle; // } // // public static TableRow with(Object ... colls) { // return new TableRow(colls); // } // // } // Path: java2word/src/main/java/word/w2004/elements/TableV2.java import word.api.interfaces.IElement; import word.w2004.elements.tableElements.TableRow; package word.w2004.elements; /** * @author leonardo_correa * */ public class TableV2 implements IElement { private StringBuilder txt = new StringBuilder(""); private boolean hasBeenCalledBefore = false; public String getContent() { if (hasBeenCalledBefore) { return txt.toString(); } else { hasBeenCalledBefore = true; } if ("".equals(txt.toString())) { return ""; } // here it goes txt.insert(0, tableTop); txt.append("\n" + tableBottom); //apply style return txt.toString(); } /** * You always have to use TableRow to add new rows to the table. Eg.: * <code> * tbl.addRow( TableRowV2.with("Simple String cell") ); * </code> * See documentation on method "TableRowV2.with" for very detailed information. * * @param row * @return */
public TableRow addRow(TableRow row) {
leonardoanalista/java2word
java2word/src/test/java/word/w2004/HeadingStyleTest.java
// Path: java2word/src/main/java/word/w2004/style/HeadingStyle.java // public class HeadingStyle extends AbstractStyle implements ISuperStylin{ // // /** // * Default align is left // */ // private Align align = Align.LEFT; // private boolean bold = false; // private boolean italic = false; // // //we could abstract this or not... if we want to apply style to one word inside a the Heading, you can NOT apply align JUSTIFIED, for example. // //For this reason I will leave this here for instance... // public enum Align { // CENTER("center"), LEFT("left"), RIGHT("right"), JUSTIFIED("both"); // // private String value; // // Align(String value) { // this.value = value; // } // // public String getValue() { // return value; // } // } // // // //This method holds the logic to replace all place holders for styling. // //I also noticed if you don't replace the place holder, it doesn't cause any error! // //But we should try to replace in order to keep the result xml clean. // @Override // public String getNewContentWithStyle(String txt) { // String alignValue = "\n <w:jc w:val=\"" + align.getValue()+ "\" />"; // txt = txt.replace("{styleAlign}", alignValue); // // StringBuilder sbText = new StringBuilder(""); // // applyBoldAndItalic(sbText); // // if(!"".equals(sbText.toString())) { // sbText.insert(0, "\n <w:rPr>"); // sbText.append("\n </w:rPr>"); // } // // txt = txt.replace("{styleText}", sbText.toString());//Convention: apply styles // txt = txt.replaceAll("[{]style(.*)[}]", ""); //Convention: remove unused styles after... // // return txt; // } // // // private void applyBoldAndItalic(StringBuilder sbText) { // if(bold) { // sbText.append("\n <w:b/><w:b-cs/>"); // } // if(italic) { // sbText.append("\n <w:i/>"); // } // } // // // //### Getters setters... ### // // /** // * Heading alignment // * @param align // * @return fluent @HeadingStyle // */ // public HeadingStyle align(Align align) { // this.align = align; // return this; // } // // /** // * Set Heading font to bold // * @return fluent @HeadingStyle // */ // public HeadingStyle bold() { // bold = true; // return this; // } // // /** // * Set Heading font to italic // * @return fluent @HeadingStyle // */ // public HeadingStyle italic() { // italic = true; // return this; // } // // // }
import junit.framework.Assert; import org.junit.Test; import word.w2004.style.HeadingStyle;
package word.w2004; public class HeadingStyleTest extends Assert{ @Test public void sanityTest(){
// Path: java2word/src/main/java/word/w2004/style/HeadingStyle.java // public class HeadingStyle extends AbstractStyle implements ISuperStylin{ // // /** // * Default align is left // */ // private Align align = Align.LEFT; // private boolean bold = false; // private boolean italic = false; // // //we could abstract this or not... if we want to apply style to one word inside a the Heading, you can NOT apply align JUSTIFIED, for example. // //For this reason I will leave this here for instance... // public enum Align { // CENTER("center"), LEFT("left"), RIGHT("right"), JUSTIFIED("both"); // // private String value; // // Align(String value) { // this.value = value; // } // // public String getValue() { // return value; // } // } // // // //This method holds the logic to replace all place holders for styling. // //I also noticed if you don't replace the place holder, it doesn't cause any error! // //But we should try to replace in order to keep the result xml clean. // @Override // public String getNewContentWithStyle(String txt) { // String alignValue = "\n <w:jc w:val=\"" + align.getValue()+ "\" />"; // txt = txt.replace("{styleAlign}", alignValue); // // StringBuilder sbText = new StringBuilder(""); // // applyBoldAndItalic(sbText); // // if(!"".equals(sbText.toString())) { // sbText.insert(0, "\n <w:rPr>"); // sbText.append("\n </w:rPr>"); // } // // txt = txt.replace("{styleText}", sbText.toString());//Convention: apply styles // txt = txt.replaceAll("[{]style(.*)[}]", ""); //Convention: remove unused styles after... // // return txt; // } // // // private void applyBoldAndItalic(StringBuilder sbText) { // if(bold) { // sbText.append("\n <w:b/><w:b-cs/>"); // } // if(italic) { // sbText.append("\n <w:i/>"); // } // } // // // //### Getters setters... ### // // /** // * Heading alignment // * @param align // * @return fluent @HeadingStyle // */ // public HeadingStyle align(Align align) { // this.align = align; // return this; // } // // /** // * Set Heading font to bold // * @return fluent @HeadingStyle // */ // public HeadingStyle bold() { // bold = true; // return this; // } // // /** // * Set Heading font to italic // * @return fluent @HeadingStyle // */ // public HeadingStyle italic() { // italic = true; // return this; // } // // // } // Path: java2word/src/test/java/word/w2004/HeadingStyleTest.java import junit.framework.Assert; import org.junit.Test; import word.w2004.style.HeadingStyle; package word.w2004; public class HeadingStyleTest extends Assert{ @Test public void sanityTest(){
HeadingStyle style = new HeadingStyle();
leonardoanalista/java2word
java2word/src/main/java/word/w2004/elements/Table.java
// Path: java2word/src/main/java/word/api/interfaces/IElement.java // public interface IElement { // // /** // * <p>This method returns the content (XML or HTML) of the Element and the content.</p> // * <p>If you are using W2004, the return will be the XML required to generate the element.</p> // * // * <p>Important: Once you call this method, the Document value is cached an no elements can be added later.</p> // * // * @return this is the String value of the element ready to be appended/inserted in the Document.<br> // * // * <p>This is the XML that generates a <code>BreakLine</code>:</p> // * <code> // * <w:p wsp:rsidR='008979E8' wsp:rsidRDefault='008979E8'/> // * </code> // */ // public String getContent(); // // } // // Path: java2word/src/main/java/word/w2004/elements/tableElements/ITableItemStrategy.java // public interface ITableItemStrategy{ // public String getTop(); // public String getMiddle(); // public String getBottom(); // } // // Path: java2word/src/main/java/word/w2004/elements/tableElements/TableEle.java // public enum TableEle{ // TH("th"), TD("td"), TF("tf"), TABLE_DEF("tableDef"); //TR("tr"), // // private String value; // // TableEle(String value){ // this.value = value; // } // // public String getValue(){ // return this.value; // } // // }; // // Path: java2word/src/main/java/word/w2004/elements/tableElements/TableFactoryMethod.java // public class TableFactoryMethod { // // private static TableFactoryMethod instance; // // private TableFactoryMethod() { // } // // public static TableFactoryMethod getInstance() { // if (instance == null) { // instance = new TableFactoryMethod(); // } // return instance; // } // // public ITableItemStrategy getTableItem(TableEle tableEle) { // if (tableEle == null) { // return null; // } // // return getTableEle(tableEle); // } // // private ITableItemStrategy getTableEle(TableEle tableEle) { // if (tableEle.getValue().equals("tableDef")) { // return new TableDefinition(); // }else if (tableEle.getValue().equals("th")) { // return new TableHeader(); // }else if (tableEle.getValue().equals("td")) { // return new TableCol(); // }else { //if (tableEle.getValue().equals("tf")) { // return new TableFooter(); // } // } // // }
import word.api.interfaces.IElement; import word.w2004.elements.tableElements.ITableItemStrategy; import word.w2004.elements.tableElements.TableEle; import word.w2004.elements.tableElements.TableFactoryMethod;
package word.w2004.elements; /** * @author leonardo_correa * */ public class Table implements IElement { StringBuilder txt = new StringBuilder(""); private boolean hasBeenCalledBefore = false; // if getContent has already // been called, I cached the // result for future // invocations private boolean isRepeatTableHeaderOnEveryPage = false; public String getContent() { if ("".equals(txt.toString())) { return ""; } if (hasBeenCalledBefore) { return txt.toString(); } else { hasBeenCalledBefore = true; }
// Path: java2word/src/main/java/word/api/interfaces/IElement.java // public interface IElement { // // /** // * <p>This method returns the content (XML or HTML) of the Element and the content.</p> // * <p>If you are using W2004, the return will be the XML required to generate the element.</p> // * // * <p>Important: Once you call this method, the Document value is cached an no elements can be added later.</p> // * // * @return this is the String value of the element ready to be appended/inserted in the Document.<br> // * // * <p>This is the XML that generates a <code>BreakLine</code>:</p> // * <code> // * <w:p wsp:rsidR='008979E8' wsp:rsidRDefault='008979E8'/> // * </code> // */ // public String getContent(); // // } // // Path: java2word/src/main/java/word/w2004/elements/tableElements/ITableItemStrategy.java // public interface ITableItemStrategy{ // public String getTop(); // public String getMiddle(); // public String getBottom(); // } // // Path: java2word/src/main/java/word/w2004/elements/tableElements/TableEle.java // public enum TableEle{ // TH("th"), TD("td"), TF("tf"), TABLE_DEF("tableDef"); //TR("tr"), // // private String value; // // TableEle(String value){ // this.value = value; // } // // public String getValue(){ // return this.value; // } // // }; // // Path: java2word/src/main/java/word/w2004/elements/tableElements/TableFactoryMethod.java // public class TableFactoryMethod { // // private static TableFactoryMethod instance; // // private TableFactoryMethod() { // } // // public static TableFactoryMethod getInstance() { // if (instance == null) { // instance = new TableFactoryMethod(); // } // return instance; // } // // public ITableItemStrategy getTableItem(TableEle tableEle) { // if (tableEle == null) { // return null; // } // // return getTableEle(tableEle); // } // // private ITableItemStrategy getTableEle(TableEle tableEle) { // if (tableEle.getValue().equals("tableDef")) { // return new TableDefinition(); // }else if (tableEle.getValue().equals("th")) { // return new TableHeader(); // }else if (tableEle.getValue().equals("td")) { // return new TableCol(); // }else { //if (tableEle.getValue().equals("tf")) { // return new TableFooter(); // } // } // // } // Path: java2word/src/main/java/word/w2004/elements/Table.java import word.api.interfaces.IElement; import word.w2004.elements.tableElements.ITableItemStrategy; import word.w2004.elements.tableElements.TableEle; import word.w2004.elements.tableElements.TableFactoryMethod; package word.w2004.elements; /** * @author leonardo_correa * */ public class Table implements IElement { StringBuilder txt = new StringBuilder(""); private boolean hasBeenCalledBefore = false; // if getContent has already // been called, I cached the // result for future // invocations private boolean isRepeatTableHeaderOnEveryPage = false; public String getContent() { if ("".equals(txt.toString())) { return ""; } if (hasBeenCalledBefore) { return txt.toString(); } else { hasBeenCalledBefore = true; }
ITableItemStrategy tableDef = TableFactoryMethod.getInstance()
leonardoanalista/java2word
java2word/src/main/java/word/w2004/elements/Table.java
// Path: java2word/src/main/java/word/api/interfaces/IElement.java // public interface IElement { // // /** // * <p>This method returns the content (XML or HTML) of the Element and the content.</p> // * <p>If you are using W2004, the return will be the XML required to generate the element.</p> // * // * <p>Important: Once you call this method, the Document value is cached an no elements can be added later.</p> // * // * @return this is the String value of the element ready to be appended/inserted in the Document.<br> // * // * <p>This is the XML that generates a <code>BreakLine</code>:</p> // * <code> // * <w:p wsp:rsidR='008979E8' wsp:rsidRDefault='008979E8'/> // * </code> // */ // public String getContent(); // // } // // Path: java2word/src/main/java/word/w2004/elements/tableElements/ITableItemStrategy.java // public interface ITableItemStrategy{ // public String getTop(); // public String getMiddle(); // public String getBottom(); // } // // Path: java2word/src/main/java/word/w2004/elements/tableElements/TableEle.java // public enum TableEle{ // TH("th"), TD("td"), TF("tf"), TABLE_DEF("tableDef"); //TR("tr"), // // private String value; // // TableEle(String value){ // this.value = value; // } // // public String getValue(){ // return this.value; // } // // }; // // Path: java2word/src/main/java/word/w2004/elements/tableElements/TableFactoryMethod.java // public class TableFactoryMethod { // // private static TableFactoryMethod instance; // // private TableFactoryMethod() { // } // // public static TableFactoryMethod getInstance() { // if (instance == null) { // instance = new TableFactoryMethod(); // } // return instance; // } // // public ITableItemStrategy getTableItem(TableEle tableEle) { // if (tableEle == null) { // return null; // } // // return getTableEle(tableEle); // } // // private ITableItemStrategy getTableEle(TableEle tableEle) { // if (tableEle.getValue().equals("tableDef")) { // return new TableDefinition(); // }else if (tableEle.getValue().equals("th")) { // return new TableHeader(); // }else if (tableEle.getValue().equals("td")) { // return new TableCol(); // }else { //if (tableEle.getValue().equals("tf")) { // return new TableFooter(); // } // } // // }
import word.api.interfaces.IElement; import word.w2004.elements.tableElements.ITableItemStrategy; import word.w2004.elements.tableElements.TableEle; import word.w2004.elements.tableElements.TableFactoryMethod;
package word.w2004.elements; /** * @author leonardo_correa * */ public class Table implements IElement { StringBuilder txt = new StringBuilder(""); private boolean hasBeenCalledBefore = false; // if getContent has already // been called, I cached the // result for future // invocations private boolean isRepeatTableHeaderOnEveryPage = false; public String getContent() { if ("".equals(txt.toString())) { return ""; } if (hasBeenCalledBefore) { return txt.toString(); } else { hasBeenCalledBefore = true; }
// Path: java2word/src/main/java/word/api/interfaces/IElement.java // public interface IElement { // // /** // * <p>This method returns the content (XML or HTML) of the Element and the content.</p> // * <p>If you are using W2004, the return will be the XML required to generate the element.</p> // * // * <p>Important: Once you call this method, the Document value is cached an no elements can be added later.</p> // * // * @return this is the String value of the element ready to be appended/inserted in the Document.<br> // * // * <p>This is the XML that generates a <code>BreakLine</code>:</p> // * <code> // * <w:p wsp:rsidR='008979E8' wsp:rsidRDefault='008979E8'/> // * </code> // */ // public String getContent(); // // } // // Path: java2word/src/main/java/word/w2004/elements/tableElements/ITableItemStrategy.java // public interface ITableItemStrategy{ // public String getTop(); // public String getMiddle(); // public String getBottom(); // } // // Path: java2word/src/main/java/word/w2004/elements/tableElements/TableEle.java // public enum TableEle{ // TH("th"), TD("td"), TF("tf"), TABLE_DEF("tableDef"); //TR("tr"), // // private String value; // // TableEle(String value){ // this.value = value; // } // // public String getValue(){ // return this.value; // } // // }; // // Path: java2word/src/main/java/word/w2004/elements/tableElements/TableFactoryMethod.java // public class TableFactoryMethod { // // private static TableFactoryMethod instance; // // private TableFactoryMethod() { // } // // public static TableFactoryMethod getInstance() { // if (instance == null) { // instance = new TableFactoryMethod(); // } // return instance; // } // // public ITableItemStrategy getTableItem(TableEle tableEle) { // if (tableEle == null) { // return null; // } // // return getTableEle(tableEle); // } // // private ITableItemStrategy getTableEle(TableEle tableEle) { // if (tableEle.getValue().equals("tableDef")) { // return new TableDefinition(); // }else if (tableEle.getValue().equals("th")) { // return new TableHeader(); // }else if (tableEle.getValue().equals("td")) { // return new TableCol(); // }else { //if (tableEle.getValue().equals("tf")) { // return new TableFooter(); // } // } // // } // Path: java2word/src/main/java/word/w2004/elements/Table.java import word.api.interfaces.IElement; import word.w2004.elements.tableElements.ITableItemStrategy; import word.w2004.elements.tableElements.TableEle; import word.w2004.elements.tableElements.TableFactoryMethod; package word.w2004.elements; /** * @author leonardo_correa * */ public class Table implements IElement { StringBuilder txt = new StringBuilder(""); private boolean hasBeenCalledBefore = false; // if getContent has already // been called, I cached the // result for future // invocations private boolean isRepeatTableHeaderOnEveryPage = false; public String getContent() { if ("".equals(txt.toString())) { return ""; } if (hasBeenCalledBefore) { return txt.toString(); } else { hasBeenCalledBefore = true; }
ITableItemStrategy tableDef = TableFactoryMethod.getInstance()
leonardoanalista/java2word
java2word/src/main/java/word/w2004/elements/Table.java
// Path: java2word/src/main/java/word/api/interfaces/IElement.java // public interface IElement { // // /** // * <p>This method returns the content (XML or HTML) of the Element and the content.</p> // * <p>If you are using W2004, the return will be the XML required to generate the element.</p> // * // * <p>Important: Once you call this method, the Document value is cached an no elements can be added later.</p> // * // * @return this is the String value of the element ready to be appended/inserted in the Document.<br> // * // * <p>This is the XML that generates a <code>BreakLine</code>:</p> // * <code> // * <w:p wsp:rsidR='008979E8' wsp:rsidRDefault='008979E8'/> // * </code> // */ // public String getContent(); // // } // // Path: java2word/src/main/java/word/w2004/elements/tableElements/ITableItemStrategy.java // public interface ITableItemStrategy{ // public String getTop(); // public String getMiddle(); // public String getBottom(); // } // // Path: java2word/src/main/java/word/w2004/elements/tableElements/TableEle.java // public enum TableEle{ // TH("th"), TD("td"), TF("tf"), TABLE_DEF("tableDef"); //TR("tr"), // // private String value; // // TableEle(String value){ // this.value = value; // } // // public String getValue(){ // return this.value; // } // // }; // // Path: java2word/src/main/java/word/w2004/elements/tableElements/TableFactoryMethod.java // public class TableFactoryMethod { // // private static TableFactoryMethod instance; // // private TableFactoryMethod() { // } // // public static TableFactoryMethod getInstance() { // if (instance == null) { // instance = new TableFactoryMethod(); // } // return instance; // } // // public ITableItemStrategy getTableItem(TableEle tableEle) { // if (tableEle == null) { // return null; // } // // return getTableEle(tableEle); // } // // private ITableItemStrategy getTableEle(TableEle tableEle) { // if (tableEle.getValue().equals("tableDef")) { // return new TableDefinition(); // }else if (tableEle.getValue().equals("th")) { // return new TableHeader(); // }else if (tableEle.getValue().equals("td")) { // return new TableCol(); // }else { //if (tableEle.getValue().equals("tf")) { // return new TableFooter(); // } // } // // }
import word.api.interfaces.IElement; import word.w2004.elements.tableElements.ITableItemStrategy; import word.w2004.elements.tableElements.TableEle; import word.w2004.elements.tableElements.TableFactoryMethod;
package word.w2004.elements; /** * @author leonardo_correa * */ public class Table implements IElement { StringBuilder txt = new StringBuilder(""); private boolean hasBeenCalledBefore = false; // if getContent has already // been called, I cached the // result for future // invocations private boolean isRepeatTableHeaderOnEveryPage = false; public String getContent() { if ("".equals(txt.toString())) { return ""; } if (hasBeenCalledBefore) { return txt.toString(); } else { hasBeenCalledBefore = true; } ITableItemStrategy tableDef = TableFactoryMethod.getInstance()
// Path: java2word/src/main/java/word/api/interfaces/IElement.java // public interface IElement { // // /** // * <p>This method returns the content (XML or HTML) of the Element and the content.</p> // * <p>If you are using W2004, the return will be the XML required to generate the element.</p> // * // * <p>Important: Once you call this method, the Document value is cached an no elements can be added later.</p> // * // * @return this is the String value of the element ready to be appended/inserted in the Document.<br> // * // * <p>This is the XML that generates a <code>BreakLine</code>:</p> // * <code> // * <w:p wsp:rsidR='008979E8' wsp:rsidRDefault='008979E8'/> // * </code> // */ // public String getContent(); // // } // // Path: java2word/src/main/java/word/w2004/elements/tableElements/ITableItemStrategy.java // public interface ITableItemStrategy{ // public String getTop(); // public String getMiddle(); // public String getBottom(); // } // // Path: java2word/src/main/java/word/w2004/elements/tableElements/TableEle.java // public enum TableEle{ // TH("th"), TD("td"), TF("tf"), TABLE_DEF("tableDef"); //TR("tr"), // // private String value; // // TableEle(String value){ // this.value = value; // } // // public String getValue(){ // return this.value; // } // // }; // // Path: java2word/src/main/java/word/w2004/elements/tableElements/TableFactoryMethod.java // public class TableFactoryMethod { // // private static TableFactoryMethod instance; // // private TableFactoryMethod() { // } // // public static TableFactoryMethod getInstance() { // if (instance == null) { // instance = new TableFactoryMethod(); // } // return instance; // } // // public ITableItemStrategy getTableItem(TableEle tableEle) { // if (tableEle == null) { // return null; // } // // return getTableEle(tableEle); // } // // private ITableItemStrategy getTableEle(TableEle tableEle) { // if (tableEle.getValue().equals("tableDef")) { // return new TableDefinition(); // }else if (tableEle.getValue().equals("th")) { // return new TableHeader(); // }else if (tableEle.getValue().equals("td")) { // return new TableCol(); // }else { //if (tableEle.getValue().equals("tf")) { // return new TableFooter(); // } // } // // } // Path: java2word/src/main/java/word/w2004/elements/Table.java import word.api.interfaces.IElement; import word.w2004.elements.tableElements.ITableItemStrategy; import word.w2004.elements.tableElements.TableEle; import word.w2004.elements.tableElements.TableFactoryMethod; package word.w2004.elements; /** * @author leonardo_correa * */ public class Table implements IElement { StringBuilder txt = new StringBuilder(""); private boolean hasBeenCalledBefore = false; // if getContent has already // been called, I cached the // result for future // invocations private boolean isRepeatTableHeaderOnEveryPage = false; public String getContent() { if ("".equals(txt.toString())) { return ""; } if (hasBeenCalledBefore) { return txt.toString(); } else { hasBeenCalledBefore = true; } ITableItemStrategy tableDef = TableFactoryMethod.getInstance()
.getTableItem(TableEle.TABLE_DEF);
leonardoanalista/java2word
java2word/src/main/java/word/w2004/Body2004.java
// Path: java2word/src/main/java/word/api/interfaces/IBody.java // public interface IBody extends IHasElement{ // // /** // * @author leonardo_correa // * This is to provide another way to add raw text to the body or replace something like style or whatever you want. // * // * Like Serializable, IBody has no methods or fields and serves only to identify the semantics of being IBody. // */ // // public IHeader getHeader(); // // public void setHeader(IHeader header); // // public IFooter getFooter(); // // public void setFooter(IFooter footer); // // } // // Path: java2word/src/main/java/word/api/interfaces/IElement.java // public interface IElement { // // /** // * <p>This method returns the content (XML or HTML) of the Element and the content.</p> // * <p>If you are using W2004, the return will be the XML required to generate the element.</p> // * // * <p>Important: Once you call this method, the Document value is cached an no elements can be added later.</p> // * // * @return this is the String value of the element ready to be appended/inserted in the Document.<br> // * // * <p>This is the XML that generates a <code>BreakLine</code>:</p> // * <code> // * <w:p wsp:rsidR='008979E8' wsp:rsidRDefault='008979E8'/> // * </code> // */ // public String getContent(); // // } // // Path: java2word/src/main/java/word/api/interfaces/IFooter.java // public interface IFooter extends IHasElement{ // // public void showPageNumber(boolean value);//default is true // // } // // Path: java2word/src/main/java/word/api/interfaces/IHeader.java // public interface IHeader extends IHasElement{ // // void setHideHeaderAndFooterFirstPage(boolean value); // boolean getHideHeaderAndFooterFirstPage(); // // String getHideHeaderAndFooterFirstPageXml(); // // }
import word.api.interfaces.IBody; import word.api.interfaces.IElement; import word.api.interfaces.IFooter; import word.api.interfaces.IHeader;
package word.w2004; public class Body2004 implements IBody { StringBuilder txt = new StringBuilder("");
// Path: java2word/src/main/java/word/api/interfaces/IBody.java // public interface IBody extends IHasElement{ // // /** // * @author leonardo_correa // * This is to provide another way to add raw text to the body or replace something like style or whatever you want. // * // * Like Serializable, IBody has no methods or fields and serves only to identify the semantics of being IBody. // */ // // public IHeader getHeader(); // // public void setHeader(IHeader header); // // public IFooter getFooter(); // // public void setFooter(IFooter footer); // // } // // Path: java2word/src/main/java/word/api/interfaces/IElement.java // public interface IElement { // // /** // * <p>This method returns the content (XML or HTML) of the Element and the content.</p> // * <p>If you are using W2004, the return will be the XML required to generate the element.</p> // * // * <p>Important: Once you call this method, the Document value is cached an no elements can be added later.</p> // * // * @return this is the String value of the element ready to be appended/inserted in the Document.<br> // * // * <p>This is the XML that generates a <code>BreakLine</code>:</p> // * <code> // * <w:p wsp:rsidR='008979E8' wsp:rsidRDefault='008979E8'/> // * </code> // */ // public String getContent(); // // } // // Path: java2word/src/main/java/word/api/interfaces/IFooter.java // public interface IFooter extends IHasElement{ // // public void showPageNumber(boolean value);//default is true // // } // // Path: java2word/src/main/java/word/api/interfaces/IHeader.java // public interface IHeader extends IHasElement{ // // void setHideHeaderAndFooterFirstPage(boolean value); // boolean getHideHeaderAndFooterFirstPage(); // // String getHideHeaderAndFooterFirstPageXml(); // // } // Path: java2word/src/main/java/word/w2004/Body2004.java import word.api.interfaces.IBody; import word.api.interfaces.IElement; import word.api.interfaces.IFooter; import word.api.interfaces.IHeader; package word.w2004; public class Body2004 implements IBody { StringBuilder txt = new StringBuilder("");
IHeader header = new Header2004();
leonardoanalista/java2word
java2word/src/main/java/word/w2004/Body2004.java
// Path: java2word/src/main/java/word/api/interfaces/IBody.java // public interface IBody extends IHasElement{ // // /** // * @author leonardo_correa // * This is to provide another way to add raw text to the body or replace something like style or whatever you want. // * // * Like Serializable, IBody has no methods or fields and serves only to identify the semantics of being IBody. // */ // // public IHeader getHeader(); // // public void setHeader(IHeader header); // // public IFooter getFooter(); // // public void setFooter(IFooter footer); // // } // // Path: java2word/src/main/java/word/api/interfaces/IElement.java // public interface IElement { // // /** // * <p>This method returns the content (XML or HTML) of the Element and the content.</p> // * <p>If you are using W2004, the return will be the XML required to generate the element.</p> // * // * <p>Important: Once you call this method, the Document value is cached an no elements can be added later.</p> // * // * @return this is the String value of the element ready to be appended/inserted in the Document.<br> // * // * <p>This is the XML that generates a <code>BreakLine</code>:</p> // * <code> // * <w:p wsp:rsidR='008979E8' wsp:rsidRDefault='008979E8'/> // * </code> // */ // public String getContent(); // // } // // Path: java2word/src/main/java/word/api/interfaces/IFooter.java // public interface IFooter extends IHasElement{ // // public void showPageNumber(boolean value);//default is true // // } // // Path: java2word/src/main/java/word/api/interfaces/IHeader.java // public interface IHeader extends IHasElement{ // // void setHideHeaderAndFooterFirstPage(boolean value); // boolean getHideHeaderAndFooterFirstPage(); // // String getHideHeaderAndFooterFirstPageXml(); // // }
import word.api.interfaces.IBody; import word.api.interfaces.IElement; import word.api.interfaces.IFooter; import word.api.interfaces.IHeader;
package word.w2004; public class Body2004 implements IBody { StringBuilder txt = new StringBuilder(""); IHeader header = new Header2004();
// Path: java2word/src/main/java/word/api/interfaces/IBody.java // public interface IBody extends IHasElement{ // // /** // * @author leonardo_correa // * This is to provide another way to add raw text to the body or replace something like style or whatever you want. // * // * Like Serializable, IBody has no methods or fields and serves only to identify the semantics of being IBody. // */ // // public IHeader getHeader(); // // public void setHeader(IHeader header); // // public IFooter getFooter(); // // public void setFooter(IFooter footer); // // } // // Path: java2word/src/main/java/word/api/interfaces/IElement.java // public interface IElement { // // /** // * <p>This method returns the content (XML or HTML) of the Element and the content.</p> // * <p>If you are using W2004, the return will be the XML required to generate the element.</p> // * // * <p>Important: Once you call this method, the Document value is cached an no elements can be added later.</p> // * // * @return this is the String value of the element ready to be appended/inserted in the Document.<br> // * // * <p>This is the XML that generates a <code>BreakLine</code>:</p> // * <code> // * <w:p wsp:rsidR='008979E8' wsp:rsidRDefault='008979E8'/> // * </code> // */ // public String getContent(); // // } // // Path: java2word/src/main/java/word/api/interfaces/IFooter.java // public interface IFooter extends IHasElement{ // // public void showPageNumber(boolean value);//default is true // // } // // Path: java2word/src/main/java/word/api/interfaces/IHeader.java // public interface IHeader extends IHasElement{ // // void setHideHeaderAndFooterFirstPage(boolean value); // boolean getHideHeaderAndFooterFirstPage(); // // String getHideHeaderAndFooterFirstPageXml(); // // } // Path: java2word/src/main/java/word/w2004/Body2004.java import word.api.interfaces.IBody; import word.api.interfaces.IElement; import word.api.interfaces.IFooter; import word.api.interfaces.IHeader; package word.w2004; public class Body2004 implements IBody { StringBuilder txt = new StringBuilder(""); IHeader header = new Header2004();
IFooter footer = new Footer2004();
leonardoanalista/java2word
java2word/src/main/java/word/w2004/Body2004.java
// Path: java2word/src/main/java/word/api/interfaces/IBody.java // public interface IBody extends IHasElement{ // // /** // * @author leonardo_correa // * This is to provide another way to add raw text to the body or replace something like style or whatever you want. // * // * Like Serializable, IBody has no methods or fields and serves only to identify the semantics of being IBody. // */ // // public IHeader getHeader(); // // public void setHeader(IHeader header); // // public IFooter getFooter(); // // public void setFooter(IFooter footer); // // } // // Path: java2word/src/main/java/word/api/interfaces/IElement.java // public interface IElement { // // /** // * <p>This method returns the content (XML or HTML) of the Element and the content.</p> // * <p>If you are using W2004, the return will be the XML required to generate the element.</p> // * // * <p>Important: Once you call this method, the Document value is cached an no elements can be added later.</p> // * // * @return this is the String value of the element ready to be appended/inserted in the Document.<br> // * // * <p>This is the XML that generates a <code>BreakLine</code>:</p> // * <code> // * <w:p wsp:rsidR='008979E8' wsp:rsidRDefault='008979E8'/> // * </code> // */ // public String getContent(); // // } // // Path: java2word/src/main/java/word/api/interfaces/IFooter.java // public interface IFooter extends IHasElement{ // // public void showPageNumber(boolean value);//default is true // // } // // Path: java2word/src/main/java/word/api/interfaces/IHeader.java // public interface IHeader extends IHasElement{ // // void setHideHeaderAndFooterFirstPage(boolean value); // boolean getHideHeaderAndFooterFirstPage(); // // String getHideHeaderAndFooterFirstPageXml(); // // }
import word.api.interfaces.IBody; import word.api.interfaces.IElement; import word.api.interfaces.IFooter; import word.api.interfaces.IHeader;
package word.w2004; public class Body2004 implements IBody { StringBuilder txt = new StringBuilder(""); IHeader header = new Header2004(); IFooter footer = new Footer2004();
// Path: java2word/src/main/java/word/api/interfaces/IBody.java // public interface IBody extends IHasElement{ // // /** // * @author leonardo_correa // * This is to provide another way to add raw text to the body or replace something like style or whatever you want. // * // * Like Serializable, IBody has no methods or fields and serves only to identify the semantics of being IBody. // */ // // public IHeader getHeader(); // // public void setHeader(IHeader header); // // public IFooter getFooter(); // // public void setFooter(IFooter footer); // // } // // Path: java2word/src/main/java/word/api/interfaces/IElement.java // public interface IElement { // // /** // * <p>This method returns the content (XML or HTML) of the Element and the content.</p> // * <p>If you are using W2004, the return will be the XML required to generate the element.</p> // * // * <p>Important: Once you call this method, the Document value is cached an no elements can be added later.</p> // * // * @return this is the String value of the element ready to be appended/inserted in the Document.<br> // * // * <p>This is the XML that generates a <code>BreakLine</code>:</p> // * <code> // * <w:p wsp:rsidR='008979E8' wsp:rsidRDefault='008979E8'/> // * </code> // */ // public String getContent(); // // } // // Path: java2word/src/main/java/word/api/interfaces/IFooter.java // public interface IFooter extends IHasElement{ // // public void showPageNumber(boolean value);//default is true // // } // // Path: java2word/src/main/java/word/api/interfaces/IHeader.java // public interface IHeader extends IHasElement{ // // void setHideHeaderAndFooterFirstPage(boolean value); // boolean getHideHeaderAndFooterFirstPage(); // // String getHideHeaderAndFooterFirstPageXml(); // // } // Path: java2word/src/main/java/word/w2004/Body2004.java import word.api.interfaces.IBody; import word.api.interfaces.IElement; import word.api.interfaces.IFooter; import word.api.interfaces.IHeader; package word.w2004; public class Body2004 implements IBody { StringBuilder txt = new StringBuilder(""); IHeader header = new Header2004(); IFooter footer = new Footer2004();
public void addEle(IElement e) {
leonardoanalista/java2word
java2word/src/test/java/word/w2004/BreakLineTest.java
// Path: java2word/src/main/java/word/api/interfaces/IElement.java // public interface IElement { // // /** // * <p>This method returns the content (XML or HTML) of the Element and the content.</p> // * <p>If you are using W2004, the return will be the XML required to generate the element.</p> // * // * <p>Important: Once you call this method, the Document value is cached an no elements can be added later.</p> // * // * @return this is the String value of the element ready to be appended/inserted in the Document.<br> // * // * <p>This is the XML that generates a <code>BreakLine</code>:</p> // * <code> // * <w:p wsp:rsidR='008979E8' wsp:rsidRDefault='008979E8'/> // * </code> // */ // public String getContent(); // // } // // Path: java2word/src/main/java/word/api/interfaces/IFluentElement.java // public interface IFluentElement <F>{ // // /** // * This method is just to keep the API consistent when you do something like: // * Heading1 myHEading = Heading1.with("h3333").<b>create();</b> // * It is just to have that "create()" at the end but the following code is the same: // * Heading1 myHEading = Heading1.with("h3333"); // * // * Anyway, it is here for sake of consistency or semantic // * // * @return // * // */ // public F create(); // // } // // Path: java2word/src/main/java/word/api/interfaces/ISuperStylin.java // public interface ISuperStylin { // // /** // * This method will called by IElement.getContent(); // */ // public String getNewContentWithStyle(String txt); // // /** // * // * // */ // public void setElement(IElement element); // // /** // * This method returns the element. There should be a cast for the return. // * The other option to avoid type cast is use covariant type return // * // */ // public IElement create(); // // } // // Path: java2word/src/main/java/word/utils/TestUtils.java // public class TestUtils { // // public static int regexCount(String text, String regex){ // if(text == null || regex == null){ // throw new IllegalArgumentException("Can't be null."); // } // Pattern pattern = Pattern.compile(regex); // Matcher matcher = pattern.matcher(text); // // int total = 0; // while (matcher.find()) { // total ++; // } // // return total; // } // // public static void createLocalDoc(String myDoc) { // createLocalDocument(myDoc, "Java2word_allInOne.doc"); // } // // public static void createLocalDoc(String myDoc, String fileName) { // if("".equals(fileName) || fileName == null) { // fileName = "Java2word_allInOne.doc"; // } // createLocalDocument(myDoc, fileName); // } // // public static void createLocalDocument(String myDoc, String fileName) { // //Property prop = new Property(""); // Properties prop = new Properties(); // String tmpDocs = ""; // try { // prop.load(new FileInputStream("build.properties")); // } catch (IOException e) { // e.printStackTrace(); // } // tmpDocs = (String) prop.get("tmp.docs.dir"); // // //System.out.println(tmpDocs); // //"/home/leonardo/Desktop/Java2word_allInOne.doc" // // File fileObj = new File(tmpDocs + "/" + fileName); // // PrintWriter writer = null; // try { // writer = new PrintWriter(fileObj); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } // String myWord = myDoc; // // writer.println(myWord); // writer.close(); // } // // } // // Path: java2word/src/main/java/word/w2004/elements/BreakLine.java // public class BreakLine implements IElement, IFluentElement<BreakLine> { // /**Number of repetitions.*/ // private int times = 1; // // @Override // public final String getContent() { // StringBuilder res = new StringBuilder(""); // applyBreakLineTimes(res); // return res.toString(); // } // // /** Apply the repetition of break lines. // * @param res string to be added content // */ // private void applyBreakLineTimes(final StringBuilder res) { // for (int i = 0; i < times; i++) { // res.append("\n<w:p wsp:rsidR=\"008979E8\" wsp:rsidRDefault=\"008979E8\"/>"); // } // } // // /** // * constructor: Number of break lines you want to add. // * @param times number of breaklines // */ // public BreakLine(final int times) { // this.times = times; // } // // /** constructor: By default, 1 Number of break line when no number is provided. // * @param times // */ // public BreakLine() { // } // // /** Created Breaklines according to the number of times provided. // * @param value number of times // * @return the Breakline object ready to go! // */ // public static BreakLine times(final Integer value) { // return new BreakLine(value); // } // // /** returns the Breakline object. // * @return the object breakline // */ // @Override // public final BreakLine create() { // return this; // } // // }
import junit.framework.Assert; import org.junit.Test; import word.api.interfaces.IElement; import word.api.interfaces.IFluentElement; import word.api.interfaces.ISuperStylin; import word.utils.TestUtils; import word.w2004.elements.BreakLine;
package word.w2004; public class BreakLineTest extends Assert { @Test public void testBreakDefaultTest() {
// Path: java2word/src/main/java/word/api/interfaces/IElement.java // public interface IElement { // // /** // * <p>This method returns the content (XML or HTML) of the Element and the content.</p> // * <p>If you are using W2004, the return will be the XML required to generate the element.</p> // * // * <p>Important: Once you call this method, the Document value is cached an no elements can be added later.</p> // * // * @return this is the String value of the element ready to be appended/inserted in the Document.<br> // * // * <p>This is the XML that generates a <code>BreakLine</code>:</p> // * <code> // * <w:p wsp:rsidR='008979E8' wsp:rsidRDefault='008979E8'/> // * </code> // */ // public String getContent(); // // } // // Path: java2word/src/main/java/word/api/interfaces/IFluentElement.java // public interface IFluentElement <F>{ // // /** // * This method is just to keep the API consistent when you do something like: // * Heading1 myHEading = Heading1.with("h3333").<b>create();</b> // * It is just to have that "create()" at the end but the following code is the same: // * Heading1 myHEading = Heading1.with("h3333"); // * // * Anyway, it is here for sake of consistency or semantic // * // * @return // * // */ // public F create(); // // } // // Path: java2word/src/main/java/word/api/interfaces/ISuperStylin.java // public interface ISuperStylin { // // /** // * This method will called by IElement.getContent(); // */ // public String getNewContentWithStyle(String txt); // // /** // * // * // */ // public void setElement(IElement element); // // /** // * This method returns the element. There should be a cast for the return. // * The other option to avoid type cast is use covariant type return // * // */ // public IElement create(); // // } // // Path: java2word/src/main/java/word/utils/TestUtils.java // public class TestUtils { // // public static int regexCount(String text, String regex){ // if(text == null || regex == null){ // throw new IllegalArgumentException("Can't be null."); // } // Pattern pattern = Pattern.compile(regex); // Matcher matcher = pattern.matcher(text); // // int total = 0; // while (matcher.find()) { // total ++; // } // // return total; // } // // public static void createLocalDoc(String myDoc) { // createLocalDocument(myDoc, "Java2word_allInOne.doc"); // } // // public static void createLocalDoc(String myDoc, String fileName) { // if("".equals(fileName) || fileName == null) { // fileName = "Java2word_allInOne.doc"; // } // createLocalDocument(myDoc, fileName); // } // // public static void createLocalDocument(String myDoc, String fileName) { // //Property prop = new Property(""); // Properties prop = new Properties(); // String tmpDocs = ""; // try { // prop.load(new FileInputStream("build.properties")); // } catch (IOException e) { // e.printStackTrace(); // } // tmpDocs = (String) prop.get("tmp.docs.dir"); // // //System.out.println(tmpDocs); // //"/home/leonardo/Desktop/Java2word_allInOne.doc" // // File fileObj = new File(tmpDocs + "/" + fileName); // // PrintWriter writer = null; // try { // writer = new PrintWriter(fileObj); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } // String myWord = myDoc; // // writer.println(myWord); // writer.close(); // } // // } // // Path: java2word/src/main/java/word/w2004/elements/BreakLine.java // public class BreakLine implements IElement, IFluentElement<BreakLine> { // /**Number of repetitions.*/ // private int times = 1; // // @Override // public final String getContent() { // StringBuilder res = new StringBuilder(""); // applyBreakLineTimes(res); // return res.toString(); // } // // /** Apply the repetition of break lines. // * @param res string to be added content // */ // private void applyBreakLineTimes(final StringBuilder res) { // for (int i = 0; i < times; i++) { // res.append("\n<w:p wsp:rsidR=\"008979E8\" wsp:rsidRDefault=\"008979E8\"/>"); // } // } // // /** // * constructor: Number of break lines you want to add. // * @param times number of breaklines // */ // public BreakLine(final int times) { // this.times = times; // } // // /** constructor: By default, 1 Number of break line when no number is provided. // * @param times // */ // public BreakLine() { // } // // /** Created Breaklines according to the number of times provided. // * @param value number of times // * @return the Breakline object ready to go! // */ // public static BreakLine times(final Integer value) { // return new BreakLine(value); // } // // /** returns the Breakline object. // * @return the object breakline // */ // @Override // public final BreakLine create() { // return this; // } // // } // Path: java2word/src/test/java/word/w2004/BreakLineTest.java import junit.framework.Assert; import org.junit.Test; import word.api.interfaces.IElement; import word.api.interfaces.IFluentElement; import word.api.interfaces.ISuperStylin; import word.utils.TestUtils; import word.w2004.elements.BreakLine; package word.w2004; public class BreakLineTest extends Assert { @Test public void testBreakDefaultTest() {
BreakLine br = new BreakLine();
leonardoanalista/java2word
java2word/src/main/java/word/w2004/Header2004.java
// Path: java2word/src/main/java/word/api/interfaces/IElement.java // public interface IElement { // // /** // * <p>This method returns the content (XML or HTML) of the Element and the content.</p> // * <p>If you are using W2004, the return will be the XML required to generate the element.</p> // * // * <p>Important: Once you call this method, the Document value is cached an no elements can be added later.</p> // * // * @return this is the String value of the element ready to be appended/inserted in the Document.<br> // * // * <p>This is the XML that generates a <code>BreakLine</code>:</p> // * <code> // * <w:p wsp:rsidR='008979E8' wsp:rsidRDefault='008979E8'/> // * </code> // */ // public String getContent(); // // } // // Path: java2word/src/main/java/word/api/interfaces/IHeader.java // public interface IHeader extends IHasElement{ // // void setHideHeaderAndFooterFirstPage(boolean value); // boolean getHideHeaderAndFooterFirstPage(); // // String getHideHeaderAndFooterFirstPageXml(); // // }
import word.api.interfaces.IElement; import word.api.interfaces.IHeader;
package word.w2004; public class Header2004 implements IHeader{ StringBuilder txt = new StringBuilder(""); private boolean hasBeenCalledBefore = false; // if getContent has already been called, I cached the result for future invocations private boolean hideHeaderAndFooterFirstPage = false;
// Path: java2word/src/main/java/word/api/interfaces/IElement.java // public interface IElement { // // /** // * <p>This method returns the content (XML or HTML) of the Element and the content.</p> // * <p>If you are using W2004, the return will be the XML required to generate the element.</p> // * // * <p>Important: Once you call this method, the Document value is cached an no elements can be added later.</p> // * // * @return this is the String value of the element ready to be appended/inserted in the Document.<br> // * // * <p>This is the XML that generates a <code>BreakLine</code>:</p> // * <code> // * <w:p wsp:rsidR='008979E8' wsp:rsidRDefault='008979E8'/> // * </code> // */ // public String getContent(); // // } // // Path: java2word/src/main/java/word/api/interfaces/IHeader.java // public interface IHeader extends IHasElement{ // // void setHideHeaderAndFooterFirstPage(boolean value); // boolean getHideHeaderAndFooterFirstPage(); // // String getHideHeaderAndFooterFirstPageXml(); // // } // Path: java2word/src/main/java/word/w2004/Header2004.java import word.api.interfaces.IElement; import word.api.interfaces.IHeader; package word.w2004; public class Header2004 implements IHeader{ StringBuilder txt = new StringBuilder(""); private boolean hasBeenCalledBefore = false; // if getContent has already been called, I cached the result for future invocations private boolean hideHeaderAndFooterFirstPage = false;
public void addEle(IElement e) {
leonardoanalista/java2word
java2word/src/main/java/word/w2004/Document2004.java
// Path: java2word/src/main/java/word/api/interfaces/IBody.java // public interface IBody extends IHasElement{ // // /** // * @author leonardo_correa // * This is to provide another way to add raw text to the body or replace something like style or whatever you want. // * // * Like Serializable, IBody has no methods or fields and serves only to identify the semantics of being IBody. // */ // // public IHeader getHeader(); // // public void setHeader(IHeader header); // // public IFooter getFooter(); // // public void setFooter(IFooter footer); // // } // // Path: java2word/src/main/java/word/api/interfaces/IDocument.java // public interface IDocument extends IHasElement { // // /** // * @return the URI ready to be added to the document // */ // String getUri(); // // /** // * @return the body of the document // */ // IBody getBody(); // // /** // * @return the header that may contain other elements // */ // IHeader getHeader(); // // /** // * @return the Footer that may contain other elements // */ // IFooter getFooter(); // // /** // * Sets page orientation to Landscape. Default is Portrait // */ // void setPageOrientationLandscape(); // // // /** // * @param title Represents the title of the document. The title can be different than the file name. The title is used when searching for the document and also when creating Web pages from the document. // * @return fluent @Document reference // */ // public Document2004 title(String title); // // /** // * @param subject Represents the subject of the document. This property can be used to group similar files together, so you can search for all files that have the same subject. // * @return fluent @Document reference // */ // public Document2004 subject(String subject); // // /** // * @param keywords Represents keywords to be used when searching for the document. // * @return fluent @Document reference // */ // public Document2004 keywords(String keywords); // // /** // * @param description Represents comments to be used when searching for the document. // * @return fluent @Document reference // */ // public Document2004 description(String description); // // /** // * @param category Represents the author who created the document. // * @return fluent @Document reference // */ // public Document2004 category(String category); // // /** // * @param author Represents the name of the author of the document. // * @return fluent @Document reference // */ // public Document2004 author(String author); // // /** // * @param lastAuthor Represents the name of the author who last saved the document. // * @return fluent @Document reference // */ // public Document2004 lastAuthor(String lastAuthor); // // /** // * @param manager Represents the manager of the author of the document. This property can be used to group similar files together, so you can search for all the files that have the same manager. // * @return fluent @Document reference // */ // public Document2004 manager(String manager); // // /** // * @param company Represents the company that employs the author. This property can be used to group similar files together, so you can search for all files that have the same company. // * @return fluent @Document reference // */ // public Document2004 company(String company); // // /** // * @param encoding The encoding you want to use in your document. UTF-8 or ISO8859-1, according to the Enum @Encoding // * @return // */ // public Document2004 encoding(Encoding encoding); // // /** // * It gives a chance to set up your own encoding by passing the final string ready to go. // * @param encoding // * @return // */ // public Document2004 encoding(String encoding); // // // } // // Path: java2word/src/main/java/word/api/interfaces/IElement.java // public interface IElement { // // /** // * <p>This method returns the content (XML or HTML) of the Element and the content.</p> // * <p>If you are using W2004, the return will be the XML required to generate the element.</p> // * // * <p>Important: Once you call this method, the Document value is cached an no elements can be added later.</p> // * // * @return this is the String value of the element ready to be appended/inserted in the Document.<br> // * // * <p>This is the XML that generates a <code>BreakLine</code>:</p> // * <code> // * <w:p wsp:rsidR='008979E8' wsp:rsidRDefault='008979E8'/> // * </code> // */ // public String getContent(); // // } // // Path: java2word/src/main/java/word/api/interfaces/IFooter.java // public interface IFooter extends IHasElement{ // // public void showPageNumber(boolean value);//default is true // // } // // Path: java2word/src/main/java/word/api/interfaces/IHeader.java // public interface IHeader extends IHasElement{ // // void setHideHeaderAndFooterFirstPage(boolean value); // boolean getHideHeaderAndFooterFirstPage(); // // String getHideHeaderAndFooterFirstPageXml(); // // }
import word.api.interfaces.IBody; import word.api.interfaces.IDocument; import word.api.interfaces.IElement; import word.api.interfaces.IFooter; import word.api.interfaces.IHeader;
package word.w2004; /** * This is the main class in this API. It represents the MS Word document. * @author leonardo_correa * */ public class Document2004 implements IDocument, IElement{ private boolean hasBeenCalledBefore = false; // if getContent has already been called, I cached the result for future invocations private StringBuilder txt = new StringBuilder();
// Path: java2word/src/main/java/word/api/interfaces/IBody.java // public interface IBody extends IHasElement{ // // /** // * @author leonardo_correa // * This is to provide another way to add raw text to the body or replace something like style or whatever you want. // * // * Like Serializable, IBody has no methods or fields and serves only to identify the semantics of being IBody. // */ // // public IHeader getHeader(); // // public void setHeader(IHeader header); // // public IFooter getFooter(); // // public void setFooter(IFooter footer); // // } // // Path: java2word/src/main/java/word/api/interfaces/IDocument.java // public interface IDocument extends IHasElement { // // /** // * @return the URI ready to be added to the document // */ // String getUri(); // // /** // * @return the body of the document // */ // IBody getBody(); // // /** // * @return the header that may contain other elements // */ // IHeader getHeader(); // // /** // * @return the Footer that may contain other elements // */ // IFooter getFooter(); // // /** // * Sets page orientation to Landscape. Default is Portrait // */ // void setPageOrientationLandscape(); // // // /** // * @param title Represents the title of the document. The title can be different than the file name. The title is used when searching for the document and also when creating Web pages from the document. // * @return fluent @Document reference // */ // public Document2004 title(String title); // // /** // * @param subject Represents the subject of the document. This property can be used to group similar files together, so you can search for all files that have the same subject. // * @return fluent @Document reference // */ // public Document2004 subject(String subject); // // /** // * @param keywords Represents keywords to be used when searching for the document. // * @return fluent @Document reference // */ // public Document2004 keywords(String keywords); // // /** // * @param description Represents comments to be used when searching for the document. // * @return fluent @Document reference // */ // public Document2004 description(String description); // // /** // * @param category Represents the author who created the document. // * @return fluent @Document reference // */ // public Document2004 category(String category); // // /** // * @param author Represents the name of the author of the document. // * @return fluent @Document reference // */ // public Document2004 author(String author); // // /** // * @param lastAuthor Represents the name of the author who last saved the document. // * @return fluent @Document reference // */ // public Document2004 lastAuthor(String lastAuthor); // // /** // * @param manager Represents the manager of the author of the document. This property can be used to group similar files together, so you can search for all the files that have the same manager. // * @return fluent @Document reference // */ // public Document2004 manager(String manager); // // /** // * @param company Represents the company that employs the author. This property can be used to group similar files together, so you can search for all files that have the same company. // * @return fluent @Document reference // */ // public Document2004 company(String company); // // /** // * @param encoding The encoding you want to use in your document. UTF-8 or ISO8859-1, according to the Enum @Encoding // * @return // */ // public Document2004 encoding(Encoding encoding); // // /** // * It gives a chance to set up your own encoding by passing the final string ready to go. // * @param encoding // * @return // */ // public Document2004 encoding(String encoding); // // // } // // Path: java2word/src/main/java/word/api/interfaces/IElement.java // public interface IElement { // // /** // * <p>This method returns the content (XML or HTML) of the Element and the content.</p> // * <p>If you are using W2004, the return will be the XML required to generate the element.</p> // * // * <p>Important: Once you call this method, the Document value is cached an no elements can be added later.</p> // * // * @return this is the String value of the element ready to be appended/inserted in the Document.<br> // * // * <p>This is the XML that generates a <code>BreakLine</code>:</p> // * <code> // * <w:p wsp:rsidR='008979E8' wsp:rsidRDefault='008979E8'/> // * </code> // */ // public String getContent(); // // } // // Path: java2word/src/main/java/word/api/interfaces/IFooter.java // public interface IFooter extends IHasElement{ // // public void showPageNumber(boolean value);//default is true // // } // // Path: java2word/src/main/java/word/api/interfaces/IHeader.java // public interface IHeader extends IHasElement{ // // void setHideHeaderAndFooterFirstPage(boolean value); // boolean getHideHeaderAndFooterFirstPage(); // // String getHideHeaderAndFooterFirstPageXml(); // // } // Path: java2word/src/main/java/word/w2004/Document2004.java import word.api.interfaces.IBody; import word.api.interfaces.IDocument; import word.api.interfaces.IElement; import word.api.interfaces.IFooter; import word.api.interfaces.IHeader; package word.w2004; /** * This is the main class in this API. It represents the MS Word document. * @author leonardo_correa * */ public class Document2004 implements IDocument, IElement{ private boolean hasBeenCalledBefore = false; // if getContent has already been called, I cached the result for future invocations private StringBuilder txt = new StringBuilder();
private IBody body = new Body2004();