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 |
|---|---|---|---|---|---|---|
hortonworks-spark/spark-llap | src/main/java/com/hortonworks/hwc/HiveWarehouseSession.java | // Path: src/main/java/com/hortonworks/spark/sql/hive/llap/HiveWarehouseBuilder.java
// public class HiveWarehouseBuilder {
//
// HiveWarehouseSessionState sessionState = new HiveWarehouseSessionState();
//
// //Can only be instantiated through session(SparkSession session)
// private HiveWarehouseBuilder() {
// }
//
// public static HiveWarehouseBuilder session(SparkSession session) {
// HiveWarehouseBuilder builder = new HiveWarehouseBuilder();
// builder.sessionState.session = session;
// //Copy all static configuration (e.g. spark-defaults.conf)
// //with keys matching HWConf.CONF_PREFIX into
// //the SparkSQL session conf for this session
// //Otherwise these settings will not be available to
// //v2 DataSourceReader or DataSourceWriter
// //See: {@link org.apache.spark.sql.sources.v2.SessionConfigSupport}
// session.conf().getAll().foreach(new scala.runtime.AbstractFunction1<scala.Tuple2<String, String>, Object>() {
// public Object apply(Tuple2<String, String> keyValue) {
// String key = keyValue._1;
// String value = keyValue._2;
// if(key.startsWith(HiveWarehouseSession.CONF_PREFIX)) {
// session.sessionState().conf().setConfString(key, value);
// }
// return null;
// }
// });
// return builder;
// }
//
// public HiveWarehouseBuilder userPassword(String user, String password) {
// HWConf.USER.setString(sessionState, user);
// HWConf.PASSWORD.setString(sessionState, password);
// return this;
// }
//
// public HiveWarehouseBuilder hs2url(String hs2url) {
// sessionState.session.conf().set(HIVESERVER2_JDBC_URL, hs2url);
// return this;
// }
//
// public HiveWarehouseBuilder principal(String principal) {
// sessionState.session.conf().set(HIVESERVER2_JDBC_URL_PRINCIPAL, principal);
// return this;
// }
//
// public HiveWarehouseBuilder credentialsEnabled() {
// sessionState.session.conf().set(HIVESERVER2_CREDENTIAL_ENABLED, "true");
// return this;
// }
//
// //Hive JDBC doesn't support java.sql.Statement.setLargeMaxResults(long)
// //Need to use setMaxResults(int) instead
// public HiveWarehouseBuilder maxExecResults(int maxExecResults) {
// HWConf.MAX_EXEC_RESULTS.setInt(sessionState, maxExecResults);
// return this;
// }
//
// public HiveWarehouseBuilder dbcp2Conf(String dbcp2Conf) {
// HWConf.DBCP2_CONF.setString(sessionState, dbcp2Conf);
// return this;
// }
//
// public HiveWarehouseBuilder defaultDB(String defaultDB) {
// HWConf.DEFAULT_DB.setString(sessionState, defaultDB);
// return this;
// }
//
// //This is the only way for application to obtain a HiveWarehouseSessionImpl
// public HiveWarehouseSessionImpl build() {
// HWConf.RESOLVED_HS2_URL.setString(sessionState, HWConf.getConnectionUrl(sessionState));
// return new HiveWarehouseSessionImpl(this.sessionState);
// }
//
// // Revealed internally for test only. Exposed for Python side.
// public HiveWarehouseSessionState sessionStateForTest() {
// return this.sessionState;
// }
// }
| import com.hortonworks.spark.sql.hive.llap.HiveWarehouseBuilder;
import org.apache.spark.sql.SparkSession; | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* 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.hortonworks.hwc;
public interface HiveWarehouseSession extends com.hortonworks.spark.sql.hive.llap.HiveWarehouseSession {
String HIVE_WAREHOUSE_CONNECTOR = "com.hortonworks.spark.sql.hive.llap.HiveWarehouseConnector";
String DATAFRAME_TO_STREAM = "com.hortonworks.spark.sql.hive.llap.HiveStreamingDataSource";
String STREAM_TO_STREAM = "com.hortonworks.spark.sql.hive.llap.streaming.HiveStreamingDataSource";
| // Path: src/main/java/com/hortonworks/spark/sql/hive/llap/HiveWarehouseBuilder.java
// public class HiveWarehouseBuilder {
//
// HiveWarehouseSessionState sessionState = new HiveWarehouseSessionState();
//
// //Can only be instantiated through session(SparkSession session)
// private HiveWarehouseBuilder() {
// }
//
// public static HiveWarehouseBuilder session(SparkSession session) {
// HiveWarehouseBuilder builder = new HiveWarehouseBuilder();
// builder.sessionState.session = session;
// //Copy all static configuration (e.g. spark-defaults.conf)
// //with keys matching HWConf.CONF_PREFIX into
// //the SparkSQL session conf for this session
// //Otherwise these settings will not be available to
// //v2 DataSourceReader or DataSourceWriter
// //See: {@link org.apache.spark.sql.sources.v2.SessionConfigSupport}
// session.conf().getAll().foreach(new scala.runtime.AbstractFunction1<scala.Tuple2<String, String>, Object>() {
// public Object apply(Tuple2<String, String> keyValue) {
// String key = keyValue._1;
// String value = keyValue._2;
// if(key.startsWith(HiveWarehouseSession.CONF_PREFIX)) {
// session.sessionState().conf().setConfString(key, value);
// }
// return null;
// }
// });
// return builder;
// }
//
// public HiveWarehouseBuilder userPassword(String user, String password) {
// HWConf.USER.setString(sessionState, user);
// HWConf.PASSWORD.setString(sessionState, password);
// return this;
// }
//
// public HiveWarehouseBuilder hs2url(String hs2url) {
// sessionState.session.conf().set(HIVESERVER2_JDBC_URL, hs2url);
// return this;
// }
//
// public HiveWarehouseBuilder principal(String principal) {
// sessionState.session.conf().set(HIVESERVER2_JDBC_URL_PRINCIPAL, principal);
// return this;
// }
//
// public HiveWarehouseBuilder credentialsEnabled() {
// sessionState.session.conf().set(HIVESERVER2_CREDENTIAL_ENABLED, "true");
// return this;
// }
//
// //Hive JDBC doesn't support java.sql.Statement.setLargeMaxResults(long)
// //Need to use setMaxResults(int) instead
// public HiveWarehouseBuilder maxExecResults(int maxExecResults) {
// HWConf.MAX_EXEC_RESULTS.setInt(sessionState, maxExecResults);
// return this;
// }
//
// public HiveWarehouseBuilder dbcp2Conf(String dbcp2Conf) {
// HWConf.DBCP2_CONF.setString(sessionState, dbcp2Conf);
// return this;
// }
//
// public HiveWarehouseBuilder defaultDB(String defaultDB) {
// HWConf.DEFAULT_DB.setString(sessionState, defaultDB);
// return this;
// }
//
// //This is the only way for application to obtain a HiveWarehouseSessionImpl
// public HiveWarehouseSessionImpl build() {
// HWConf.RESOLVED_HS2_URL.setString(sessionState, HWConf.getConnectionUrl(sessionState));
// return new HiveWarehouseSessionImpl(this.sessionState);
// }
//
// // Revealed internally for test only. Exposed for Python side.
// public HiveWarehouseSessionState sessionStateForTest() {
// return this.sessionState;
// }
// }
// Path: src/main/java/com/hortonworks/hwc/HiveWarehouseSession.java
import com.hortonworks.spark.sql.hive.llap.HiveWarehouseBuilder;
import org.apache.spark.sql.SparkSession;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* 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.hortonworks.hwc;
public interface HiveWarehouseSession extends com.hortonworks.spark.sql.hive.llap.HiveWarehouseSession {
String HIVE_WAREHOUSE_CONNECTOR = "com.hortonworks.spark.sql.hive.llap.HiveWarehouseConnector";
String DATAFRAME_TO_STREAM = "com.hortonworks.spark.sql.hive.llap.HiveStreamingDataSource";
String STREAM_TO_STREAM = "com.hortonworks.spark.sql.hive.llap.streaming.HiveStreamingDataSource";
| static HiveWarehouseBuilder session(SparkSession session) { |
hortonworks-spark/spark-llap | src/main/java/com/hortonworks/spark/sql/hive/llap/streaming/HiveStreamingDataSource.java | // Path: src/main/java/com/hortonworks/spark/sql/hive/llap/HiveWarehouseSession.java
// public interface HiveWarehouseSession {
//
// String HIVE_WAREHOUSE_CONNECTOR = "com.hortonworks.spark.sql.hive.llap.HiveWarehouseConnector";
// String SPARK_DATASOURCES_PREFIX = "spark.datasource";
// String HIVE_WAREHOUSE_POSTFIX = "hive.warehouse";
// String CONF_PREFIX = SPARK_DATASOURCES_PREFIX + "." + HIVE_WAREHOUSE_POSTFIX;
//
// Dataset<Row> executeQuery(String sql);
// Dataset<Row> q(String sql);
//
// Dataset<Row> execute(String sql);
//
// boolean executeUpdate(String sql);
//
// Dataset<Row> table(String sql);
//
// SparkSession session();
//
// void setDatabase(String name);
//
// Dataset<Row> showDatabases();
//
// Dataset<Row> showTables();
//
// Dataset<Row> describeTable(String table);
//
// void createDatabase(String database, boolean ifNotExists);
//
// CreateTableBuilder createTable(String tableName);
//
// void dropDatabase(String database, boolean ifExists, boolean cascade);
//
// void dropTable(String table, boolean ifExists, boolean purge);
// }
| import java.util.Arrays;
import java.util.List;
import com.hortonworks.spark.sql.hive.llap.HiveWarehouseSession;
import org.apache.spark.sql.sources.v2.DataSourceOptions;
import org.apache.spark.sql.sources.v2.DataSourceV2;
import org.apache.spark.sql.sources.v2.StreamWriteSupport;
import org.apache.spark.sql.sources.v2.writer.streaming.StreamWriter;
import org.apache.spark.sql.sources.v2.SessionConfigSupport;
import org.apache.spark.sql.streaming.OutputMode;
import org.apache.spark.sql.types.StructType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package com.hortonworks.spark.sql.hive.llap.streaming;
public class HiveStreamingDataSource implements DataSourceV2, StreamWriteSupport, SessionConfigSupport {
private static Logger LOG = LoggerFactory.getLogger(HiveStreamingDataSource.class);
@Override
public StreamWriter createStreamWriter(final String queryId, final StructType schema, final OutputMode mode,
final DataSourceOptions options) {
return createDataSourceWriter(queryId, schema, options);
}
private HiveStreamingDataSourceWriter createDataSourceWriter(final String id, final StructType schema,
final DataSourceOptions options) {
String dbName = null;
if(options.get("default.db").isPresent()) {
dbName = options.get("default.db").get();
} else {
dbName = options.get("database").orElse("default");
}
String tableName = options.get("table").orElse(null);
String partition = options.get("partition").orElse(null);
List<String> partitionValues = partition == null ? null : Arrays.asList(partition.split(","));
String metastoreUri = options.get("metastoreUri").orElse("thrift://localhost:9083");
String metastoreKerberosPrincipal = options.get("metastoreKrbPrincipal").orElse(null);
LOG.info("OPTIONS - database: {} table: {} partition: {} metastoreUri: {} metastoreKerberosPrincipal: {}",
dbName, tableName, partition, metastoreUri, metastoreKerberosPrincipal);
return new HiveStreamingDataSourceWriter(id, schema, dbName, tableName,
partitionValues, metastoreUri, metastoreKerberosPrincipal);
}
@Override public String keyPrefix() { | // Path: src/main/java/com/hortonworks/spark/sql/hive/llap/HiveWarehouseSession.java
// public interface HiveWarehouseSession {
//
// String HIVE_WAREHOUSE_CONNECTOR = "com.hortonworks.spark.sql.hive.llap.HiveWarehouseConnector";
// String SPARK_DATASOURCES_PREFIX = "spark.datasource";
// String HIVE_WAREHOUSE_POSTFIX = "hive.warehouse";
// String CONF_PREFIX = SPARK_DATASOURCES_PREFIX + "." + HIVE_WAREHOUSE_POSTFIX;
//
// Dataset<Row> executeQuery(String sql);
// Dataset<Row> q(String sql);
//
// Dataset<Row> execute(String sql);
//
// boolean executeUpdate(String sql);
//
// Dataset<Row> table(String sql);
//
// SparkSession session();
//
// void setDatabase(String name);
//
// Dataset<Row> showDatabases();
//
// Dataset<Row> showTables();
//
// Dataset<Row> describeTable(String table);
//
// void createDatabase(String database, boolean ifNotExists);
//
// CreateTableBuilder createTable(String tableName);
//
// void dropDatabase(String database, boolean ifExists, boolean cascade);
//
// void dropTable(String table, boolean ifExists, boolean purge);
// }
// Path: src/main/java/com/hortonworks/spark/sql/hive/llap/streaming/HiveStreamingDataSource.java
import java.util.Arrays;
import java.util.List;
import com.hortonworks.spark.sql.hive.llap.HiveWarehouseSession;
import org.apache.spark.sql.sources.v2.DataSourceOptions;
import org.apache.spark.sql.sources.v2.DataSourceV2;
import org.apache.spark.sql.sources.v2.StreamWriteSupport;
import org.apache.spark.sql.sources.v2.writer.streaming.StreamWriter;
import org.apache.spark.sql.sources.v2.SessionConfigSupport;
import org.apache.spark.sql.streaming.OutputMode;
import org.apache.spark.sql.types.StructType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package com.hortonworks.spark.sql.hive.llap.streaming;
public class HiveStreamingDataSource implements DataSourceV2, StreamWriteSupport, SessionConfigSupport {
private static Logger LOG = LoggerFactory.getLogger(HiveStreamingDataSource.class);
@Override
public StreamWriter createStreamWriter(final String queryId, final StructType schema, final OutputMode mode,
final DataSourceOptions options) {
return createDataSourceWriter(queryId, schema, options);
}
private HiveStreamingDataSourceWriter createDataSourceWriter(final String id, final StructType schema,
final DataSourceOptions options) {
String dbName = null;
if(options.get("default.db").isPresent()) {
dbName = options.get("default.db").get();
} else {
dbName = options.get("database").orElse("default");
}
String tableName = options.get("table").orElse(null);
String partition = options.get("partition").orElse(null);
List<String> partitionValues = partition == null ? null : Arrays.asList(partition.split(","));
String metastoreUri = options.get("metastoreUri").orElse("thrift://localhost:9083");
String metastoreKerberosPrincipal = options.get("metastoreKrbPrincipal").orElse(null);
LOG.info("OPTIONS - database: {} table: {} partition: {} metastoreUri: {} metastoreKerberosPrincipal: {}",
dbName, tableName, partition, metastoreUri, metastoreKerberosPrincipal);
return new HiveStreamingDataSourceWriter(id, schema, dbName, tableName,
partitionValues, metastoreUri, metastoreKerberosPrincipal);
}
@Override public String keyPrefix() { | return HiveWarehouseSession.HIVE_WAREHOUSE_POSTFIX; |
hortonworks-spark/spark-llap | src/main/java/com/hortonworks/spark/sql/hive/llap/streaming/HiveStreamingDataSourceWriter.java | // Path: src/main/java/com/hortonworks/spark/sql/hive/llap/HiveStreamingDataWriterFactory.java
// public class HiveStreamingDataWriterFactory implements DataWriterFactory<InternalRow> {
//
// private String jobId;
// private StructType schema;
// private long commitIntervalRows;
// private String db;
// private String table;
// private List<String> partition;
// private String metastoreUri;
// private String metastoreKrbPrincipal;
//
// public HiveStreamingDataWriterFactory(String jobId, StructType schema, long commitIntervalRows, String db,
// String table, List<String> partition, final String metastoreUri, final String metastoreKrbPrincipal) {
// this.jobId = jobId;
// this.schema = schema;
// this.db = db;
// this.table = table;
// this.partition = partition;
// this.commitIntervalRows = commitIntervalRows;
// this.metastoreUri = metastoreUri;
// this.metastoreKrbPrincipal = metastoreKrbPrincipal;
// }
//
// @Override
// public DataWriter<InternalRow> createDataWriter(int partitionId, int attemptNumber) {
// ClassLoader restoredClassloader = Thread.currentThread().getContextClassLoader();
// ClassLoader isolatedClassloader = HiveIsolatedClassLoader.isolatedClassLoader();
// try {
// Thread.currentThread().setContextClassLoader(isolatedClassloader);
// return new HiveStreamingDataWriter(jobId, schema, commitIntervalRows, partitionId, attemptNumber, db,
// table, partition, metastoreUri, metastoreKrbPrincipal);
// } finally {
// Thread.currentThread().setContextClassLoader(restoredClassloader);
// }
// }
// }
| import java.util.List;
import org.apache.spark.sql.catalyst.InternalRow;
import org.apache.spark.sql.sources.v2.writer.DataWriterFactory;
import org.apache.spark.sql.sources.v2.writer.SupportsWriteInternalRow;
import org.apache.spark.sql.sources.v2.writer.WriterCommitMessage;
import org.apache.spark.sql.sources.v2.writer.streaming.StreamWriter;
import org.apache.spark.sql.types.StructType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hortonworks.spark.sql.hive.llap.HiveStreamingDataWriterFactory; | package com.hortonworks.spark.sql.hive.llap.streaming;
public class HiveStreamingDataSourceWriter implements SupportsWriteInternalRow, StreamWriter {
private static Logger LOG = LoggerFactory.getLogger(HiveStreamingDataSourceWriter.class);
private String jobId;
private StructType schema;
private String db;
private String table;
private List<String> partition;
private String metastoreUri;
private String metastoreKerberosPrincipal;
public HiveStreamingDataSourceWriter(String jobId, StructType schema, String db,
String table, List<String> partition, final String metastoreUri, final String metastoreKerberosPrincipal) {
this.jobId = jobId;
this.schema = schema;
this.db = db;
this.table = table;
this.partition = partition;
this.metastoreUri = metastoreUri;
this.metastoreKerberosPrincipal = metastoreKerberosPrincipal;
}
@Override
public DataWriterFactory<InternalRow> createInternalRowWriterFactory() {
// for the streaming case, commit transaction happens on task commit() (atleast-once), so interval is set to -1 | // Path: src/main/java/com/hortonworks/spark/sql/hive/llap/HiveStreamingDataWriterFactory.java
// public class HiveStreamingDataWriterFactory implements DataWriterFactory<InternalRow> {
//
// private String jobId;
// private StructType schema;
// private long commitIntervalRows;
// private String db;
// private String table;
// private List<String> partition;
// private String metastoreUri;
// private String metastoreKrbPrincipal;
//
// public HiveStreamingDataWriterFactory(String jobId, StructType schema, long commitIntervalRows, String db,
// String table, List<String> partition, final String metastoreUri, final String metastoreKrbPrincipal) {
// this.jobId = jobId;
// this.schema = schema;
// this.db = db;
// this.table = table;
// this.partition = partition;
// this.commitIntervalRows = commitIntervalRows;
// this.metastoreUri = metastoreUri;
// this.metastoreKrbPrincipal = metastoreKrbPrincipal;
// }
//
// @Override
// public DataWriter<InternalRow> createDataWriter(int partitionId, int attemptNumber) {
// ClassLoader restoredClassloader = Thread.currentThread().getContextClassLoader();
// ClassLoader isolatedClassloader = HiveIsolatedClassLoader.isolatedClassLoader();
// try {
// Thread.currentThread().setContextClassLoader(isolatedClassloader);
// return new HiveStreamingDataWriter(jobId, schema, commitIntervalRows, partitionId, attemptNumber, db,
// table, partition, metastoreUri, metastoreKrbPrincipal);
// } finally {
// Thread.currentThread().setContextClassLoader(restoredClassloader);
// }
// }
// }
// Path: src/main/java/com/hortonworks/spark/sql/hive/llap/streaming/HiveStreamingDataSourceWriter.java
import java.util.List;
import org.apache.spark.sql.catalyst.InternalRow;
import org.apache.spark.sql.sources.v2.writer.DataWriterFactory;
import org.apache.spark.sql.sources.v2.writer.SupportsWriteInternalRow;
import org.apache.spark.sql.sources.v2.writer.WriterCommitMessage;
import org.apache.spark.sql.sources.v2.writer.streaming.StreamWriter;
import org.apache.spark.sql.types.StructType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hortonworks.spark.sql.hive.llap.HiveStreamingDataWriterFactory;
package com.hortonworks.spark.sql.hive.llap.streaming;
public class HiveStreamingDataSourceWriter implements SupportsWriteInternalRow, StreamWriter {
private static Logger LOG = LoggerFactory.getLogger(HiveStreamingDataSourceWriter.class);
private String jobId;
private StructType schema;
private String db;
private String table;
private List<String> partition;
private String metastoreUri;
private String metastoreKerberosPrincipal;
public HiveStreamingDataSourceWriter(String jobId, StructType schema, String db,
String table, List<String> partition, final String metastoreUri, final String metastoreKerberosPrincipal) {
this.jobId = jobId;
this.schema = schema;
this.db = db;
this.table = table;
this.partition = partition;
this.metastoreUri = metastoreUri;
this.metastoreKerberosPrincipal = metastoreKerberosPrincipal;
}
@Override
public DataWriterFactory<InternalRow> createInternalRowWriterFactory() {
// for the streaming case, commit transaction happens on task commit() (atleast-once), so interval is set to -1 | return new HiveStreamingDataWriterFactory(jobId, schema, -1, db, table, partition, metastoreUri, |
hortonworks-spark/spark-llap | src/main/java/com/hortonworks/spark/sql/hive/llap/util/SchemaUtil.java | // Path: src/main/java/com/hortonworks/spark/sql/hive/llap/CreateTableBuilder.java
// public class CreateTableBuilder implements com.hortonworks.hwc.CreateTableBuilder {
// private HiveWarehouseSession hive;
// private String database;
// private String tableName;
// private boolean ifNotExists;
// private List<Pair<String, String>> cols = new ArrayList<>();
// private List<Pair<String, String>> parts = new ArrayList<>();
// private List<Pair<String, String>> props = new ArrayList<>();
// private String[] clusters;
// private Long buckets;
//
// public CreateTableBuilder(HiveWarehouseSession hive, String database, String tableName) {
// this.hive = hive;
// this.tableName = tableName;
// this.database = database;
// }
//
// @Override
// public CreateTableBuilder ifNotExists() {
// this.ifNotExists = true;
// return this;
// }
//
// @Override
// public CreateTableBuilder column(String name, String type) {
// cols.add(Pair.of(name, type));
// return this;
// }
//
// @Override
// public CreateTableBuilder partition(String name, String type) {
// parts.add(Pair.of(name, type));
// return this;
// }
//
// @Override
// public CreateTableBuilder prop(String key, String value) {
// props.add(Pair.of(key, value));
// return this;
// }
//
// @Override
// public CreateTableBuilder clusterBy(long numBuckets, String ... columns) {
// this.buckets = numBuckets;
// this.clusters = columns;
// return this;
// }
//
// @Override
// public void create() {
// hive.executeUpdate(this.toString());
// }
//
// public String toString() {
// StringBuilder builder = new StringBuilder();
// builder.append(createTablePrelude(database, tableName, ifNotExists));
// if(cols.size() > 0) {
// List<String> colsStrings = new ArrayList<>();
// for(Pair<String, String> col : cols) {
// colsStrings.add(col.getKey() + " " + col.getValue());
// }
// builder.append(columnSpec(join(",", colsStrings)));
// }
// if(parts.size() > 0) {
// List<String> partsStrings = new ArrayList<>();
// for(Pair<String, String> part : parts) {
// partsStrings.add(part.getKey() + " " + part.getValue());
// }
// builder.append(partitionSpec(join(",", partsStrings)));
// }
// if(clusters != null) {
// builder.append(bucketSpec(join(",", clusters), buckets));
// }
// //Currently only managed ORC tables are supported
// builder.append(" STORED AS ORC ");
// if(props.size() > 0) {
// List<String> keyValueStrings = new ArrayList<>();
// for(Pair<String, String> keyValue : props) {
// keyValueStrings.add(format("\"%s\"=\"%s\"", keyValue.getKey(), keyValue.getValue()));
// }
// builder.append(tblProperties(join(",", keyValueStrings)));
// }
// return builder.toString();
// }
// }
| import com.hortonworks.spark.sql.hive.llap.CreateTableBuilder;
import org.apache.hadoop.hive.llap.FieldDesc;
import org.apache.hadoop.hive.llap.Schema;
import org.apache.spark.sql.types.*;
import java.util.ArrayList;
import java.util.List;
import static java.lang.String.format; | package com.hortonworks.spark.sql.hive.llap.util;
public class SchemaUtil {
private static final String HIVE_TYPE_STRING = "HIVE_TYPE_STRING";
public static StructType convertSchema(Schema schema) {
List<FieldDesc> columns = schema.getColumns();
List<String> types = new ArrayList<>();
for(FieldDesc fieldDesc : columns) {
String name;
if(fieldDesc.getName().contains(".")) {
name = fieldDesc.getName().split("\\.")[1];
} else {
name = fieldDesc.getName();
}
types.add(format("`%s` %s", name, fieldDesc.getTypeInfo().toString()));
}
return StructType.fromDDL(String.join(", ", types));
}
public static String[] columnNames(StructType schema) {
String[] requiredColumns = new String[schema.length()];
int i = 0;
for (StructField field : schema.fields()) {
requiredColumns[i] = field.name();
i++;
}
return requiredColumns;
}
/**
*
* Builds create table query from given dataframe schema.
*
* @param schema spark dataframe schema
* @param database database name for create table query
* @param table table name for create table query
* @return a create table query string
*/
public static String buildHiveCreateTableQueryFromSparkDFSchema(StructType schema, String database, String table) { | // Path: src/main/java/com/hortonworks/spark/sql/hive/llap/CreateTableBuilder.java
// public class CreateTableBuilder implements com.hortonworks.hwc.CreateTableBuilder {
// private HiveWarehouseSession hive;
// private String database;
// private String tableName;
// private boolean ifNotExists;
// private List<Pair<String, String>> cols = new ArrayList<>();
// private List<Pair<String, String>> parts = new ArrayList<>();
// private List<Pair<String, String>> props = new ArrayList<>();
// private String[] clusters;
// private Long buckets;
//
// public CreateTableBuilder(HiveWarehouseSession hive, String database, String tableName) {
// this.hive = hive;
// this.tableName = tableName;
// this.database = database;
// }
//
// @Override
// public CreateTableBuilder ifNotExists() {
// this.ifNotExists = true;
// return this;
// }
//
// @Override
// public CreateTableBuilder column(String name, String type) {
// cols.add(Pair.of(name, type));
// return this;
// }
//
// @Override
// public CreateTableBuilder partition(String name, String type) {
// parts.add(Pair.of(name, type));
// return this;
// }
//
// @Override
// public CreateTableBuilder prop(String key, String value) {
// props.add(Pair.of(key, value));
// return this;
// }
//
// @Override
// public CreateTableBuilder clusterBy(long numBuckets, String ... columns) {
// this.buckets = numBuckets;
// this.clusters = columns;
// return this;
// }
//
// @Override
// public void create() {
// hive.executeUpdate(this.toString());
// }
//
// public String toString() {
// StringBuilder builder = new StringBuilder();
// builder.append(createTablePrelude(database, tableName, ifNotExists));
// if(cols.size() > 0) {
// List<String> colsStrings = new ArrayList<>();
// for(Pair<String, String> col : cols) {
// colsStrings.add(col.getKey() + " " + col.getValue());
// }
// builder.append(columnSpec(join(",", colsStrings)));
// }
// if(parts.size() > 0) {
// List<String> partsStrings = new ArrayList<>();
// for(Pair<String, String> part : parts) {
// partsStrings.add(part.getKey() + " " + part.getValue());
// }
// builder.append(partitionSpec(join(",", partsStrings)));
// }
// if(clusters != null) {
// builder.append(bucketSpec(join(",", clusters), buckets));
// }
// //Currently only managed ORC tables are supported
// builder.append(" STORED AS ORC ");
// if(props.size() > 0) {
// List<String> keyValueStrings = new ArrayList<>();
// for(Pair<String, String> keyValue : props) {
// keyValueStrings.add(format("\"%s\"=\"%s\"", keyValue.getKey(), keyValue.getValue()));
// }
// builder.append(tblProperties(join(",", keyValueStrings)));
// }
// return builder.toString();
// }
// }
// Path: src/main/java/com/hortonworks/spark/sql/hive/llap/util/SchemaUtil.java
import com.hortonworks.spark.sql.hive.llap.CreateTableBuilder;
import org.apache.hadoop.hive.llap.FieldDesc;
import org.apache.hadoop.hive.llap.Schema;
import org.apache.spark.sql.types.*;
import java.util.ArrayList;
import java.util.List;
import static java.lang.String.format;
package com.hortonworks.spark.sql.hive.llap.util;
public class SchemaUtil {
private static final String HIVE_TYPE_STRING = "HIVE_TYPE_STRING";
public static StructType convertSchema(Schema schema) {
List<FieldDesc> columns = schema.getColumns();
List<String> types = new ArrayList<>();
for(FieldDesc fieldDesc : columns) {
String name;
if(fieldDesc.getName().contains(".")) {
name = fieldDesc.getName().split("\\.")[1];
} else {
name = fieldDesc.getName();
}
types.add(format("`%s` %s", name, fieldDesc.getTypeInfo().toString()));
}
return StructType.fromDDL(String.join(", ", types));
}
public static String[] columnNames(StructType schema) {
String[] requiredColumns = new String[schema.length()];
int i = 0;
for (StructField field : schema.fields()) {
requiredColumns[i] = field.name();
i++;
}
return requiredColumns;
}
/**
*
* Builds create table query from given dataframe schema.
*
* @param schema spark dataframe schema
* @param database database name for create table query
* @param table table name for create table query
* @return a create table query string
*/
public static String buildHiveCreateTableQueryFromSparkDFSchema(StructType schema, String database, String table) { | CreateTableBuilder createTableBuilder = new CreateTableBuilder(null, database, table); |
hortonworks-spark/spark-llap | src/test/java/com/hortonworks/spark/sql/hive/llap/MockWriteSupport.java | // Path: src/main/java/com/hortonworks/spark/sql/hive/llap/util/SerializableHadoopConfiguration.java
// public class SerializableHadoopConfiguration implements Serializable {
// Configuration conf;
//
// public SerializableHadoopConfiguration(Configuration hadoopConf) {
// this.conf = hadoopConf;
//
// if (this.conf == null) {
// this.conf = new Configuration();
// }
// }
//
// public SerializableHadoopConfiguration() {
// this.conf = new Configuration();
// }
//
// public Configuration get() {
// return this.conf;
// }
//
// private void writeObject(java.io.ObjectOutputStream out) throws IOException {
// this.conf.write(out);
// }
//
// private void readObject(java.io.ObjectInputStream in) throws IOException {
// this.conf = new Configuration();
// this.conf.readFields(in);
// }
// }
//
// Path: src/test/java/com/hortonworks/spark/sql/hive/llap/MockHiveWarehouseConnector.java
// public static int[] testVector = {1, 2, 3, 4, 5};
| import com.hortonworks.spark.sql.hive.llap.util.SerializableHadoopConfiguration;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.spark.sql.catalyst.InternalRow;
import org.apache.spark.sql.execution.datasources.OutputWriter;
import org.apache.spark.sql.execution.datasources.orc.OrcOutputWriter;
import org.apache.spark.sql.sources.v2.writer.DataWriter;
import org.apache.spark.sql.sources.v2.writer.DataWriterFactory;
import org.apache.spark.sql.sources.v2.writer.WriterCommitMessage;
import org.apache.spark.sql.types.StructType;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.hortonworks.spark.sql.hive.llap.MockHiveWarehouseConnector.testVector;
import static org.junit.Assert.assertEquals; | package com.hortonworks.spark.sql.hive.llap;
public class MockWriteSupport {
public static class MockHiveWarehouseDataSourceWriter extends HiveWarehouseDataSourceWriter {
public MockHiveWarehouseDataSourceWriter(Map<String, String> options, String jobId, StructType schema, Path path,
Configuration conf) {
super(options, jobId, schema, path, conf);
}
@Override
public DataWriterFactory<InternalRow> createInternalRowWriterFactory() { | // Path: src/main/java/com/hortonworks/spark/sql/hive/llap/util/SerializableHadoopConfiguration.java
// public class SerializableHadoopConfiguration implements Serializable {
// Configuration conf;
//
// public SerializableHadoopConfiguration(Configuration hadoopConf) {
// this.conf = hadoopConf;
//
// if (this.conf == null) {
// this.conf = new Configuration();
// }
// }
//
// public SerializableHadoopConfiguration() {
// this.conf = new Configuration();
// }
//
// public Configuration get() {
// return this.conf;
// }
//
// private void writeObject(java.io.ObjectOutputStream out) throws IOException {
// this.conf.write(out);
// }
//
// private void readObject(java.io.ObjectInputStream in) throws IOException {
// this.conf = new Configuration();
// this.conf.readFields(in);
// }
// }
//
// Path: src/test/java/com/hortonworks/spark/sql/hive/llap/MockHiveWarehouseConnector.java
// public static int[] testVector = {1, 2, 3, 4, 5};
// Path: src/test/java/com/hortonworks/spark/sql/hive/llap/MockWriteSupport.java
import com.hortonworks.spark.sql.hive.llap.util.SerializableHadoopConfiguration;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.spark.sql.catalyst.InternalRow;
import org.apache.spark.sql.execution.datasources.OutputWriter;
import org.apache.spark.sql.execution.datasources.orc.OrcOutputWriter;
import org.apache.spark.sql.sources.v2.writer.DataWriter;
import org.apache.spark.sql.sources.v2.writer.DataWriterFactory;
import org.apache.spark.sql.sources.v2.writer.WriterCommitMessage;
import org.apache.spark.sql.types.StructType;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.hortonworks.spark.sql.hive.llap.MockHiveWarehouseConnector.testVector;
import static org.junit.Assert.assertEquals;
package com.hortonworks.spark.sql.hive.llap;
public class MockWriteSupport {
public static class MockHiveWarehouseDataSourceWriter extends HiveWarehouseDataSourceWriter {
public MockHiveWarehouseDataSourceWriter(Map<String, String> options, String jobId, StructType schema, Path path,
Configuration conf) {
super(options, jobId, schema, path, conf);
}
@Override
public DataWriterFactory<InternalRow> createInternalRowWriterFactory() { | return new MockHiveWarehouseDataWriterFactory(jobId, schema, path, new SerializableHadoopConfiguration(conf)); |
michel-kraemer/vertx-lang-typescript | src/test/java/de/undercouch/vertx/lang/typescript/compiler/EngineCompilerTest.java | // Path: src/main/java/de/undercouch/vertx/lang/typescript/compiler/EngineCompiler.java
// public class EngineCompiler implements TypeScriptCompiler {
// /**
// * Path to the TypeScript compiler
// */
// static final String TYPESCRIPT_JS = "typescript/lib/typescriptServices.js";
//
// /**
// * Path to a helper script calling the TypeScript compiler
// */
// static final String COMPILE_JS = "vertx-typescript/util/compile.js";
//
// /**
// * The JavaScript engine hosting the TypeScript compiler
// */
// private ScriptEngine engine;
//
// /**
// * Creates the JavaScript engine that hosts the TypeScript compiler. Loads
// * the compiler and a helper script and evaluates them within the engine.
// * @return the engine
// */
// private synchronized ScriptEngine getEngine() {
// if (engine != null) {
// return engine;
// }
//
// // create JavaScript engine
// ScriptEngineManager mgr = new ScriptEngineManager();
// engine = mgr.getEngineByName("nashorn");
// if (engine == null) {
// throw new IllegalStateException("Could not find Nashorn JavaScript engine.");
// }
//
// // load TypeScript compiler
// loadScript(TYPESCRIPT_JS, src -> {
// // WORKAROUND for a bug in Nashorn (https://bugs.openjdk.java.net/browse/JDK-8079426)
// // Inside the TypeScript compiler `ts.Diagnostics` is defined as a literal
// // with more than 256 items. This causes all elements to be undefined.
// // The bug has been fixed but it still occurs in Java 8u45.
//
// // find function where the diagnostics are defined
// String startStr = "ts.Diagnostics = {";
// String endStr = "};";
// int start = src.indexOf(startStr);
// int end = src.indexOf(endStr, start);
// String diagnostics = src.substring(start + startStr.length(), end);
//
// // change lines so properties are set one by one
// String[] diagLines = diagnostics.split("\n");
// for (int i = 0; i < diagLines.length; ++i) {
// diagLines[i] = diagLines[i].replaceFirst("^\\s*(.+?):", "ts.Diagnostics.$1 =");
// }
//
// // replace original lines with new ones
// String newDiagnostics = startStr + "};\n" + String.join("\n", diagLines) + ";";
// src = src.substring(0, start) + newDiagnostics + src.substring(end + endStr.length());
//
// return src;
// });
//
// // load compile.js
// loadScript(COMPILE_JS, null);
//
// // define some globals
// engine.put("__lineSeparator", System.lineSeparator());
// engine.put("__isFileNotFoundException", (Function<Object, Boolean>)(e ->
// e instanceof FileNotFoundException));
// engine.put("__printlnErr", (Consumer<Object>)System.err::println);
//
// return engine;
// }
//
// /**
// * Loads a JavaScript file and evaluate it within {@link #engine}
// * @param name the name of the file to load
// */
// private void loadScript(String name, Function<String, String> processSource) {
// URL url = getClass().getClassLoader().getResource(name);
// if (url == null) {
// throw new IllegalStateException("Cannot find " + name + " on classpath");
// }
//
// try {
// String src = Source.fromURL(url, StandardCharsets.UTF_8).toString();
// if (processSource != null) {
// src = processSource.apply(src);
// }
// engine.eval(src);
// } catch (ScriptException | IOException e) {
// throw new IllegalStateException("Could not evaluate " + name, e);
// }
// }
//
// @Override
// public String compile(String filename, SourceFactory sourceFactory) throws IOException {
// ScriptEngine e = getEngine();
// ScriptObjectMirror o = (ScriptObjectMirror)e.get("compileTypescript");
// return (String)o.call(null, filename, sourceFactory);
// }
// }
//
// Path: src/main/java/de/undercouch/vertx/lang/typescript/compiler/TypeScriptCompiler.java
// public interface TypeScriptCompiler {
// /**
// * Compiles the given TypeScript file
// * @param filename the name of the file to compile
// * @param sourceFactory the factory that loads source files
// * @return the generated code
// * @throws IOException if one of the source files to compile could not be loaded
// */
// String compile(String filename, SourceFactory sourceFactory) throws IOException;
// }
| import org.junit.Before;
import de.undercouch.vertx.lang.typescript.compiler.EngineCompiler;
import de.undercouch.vertx.lang.typescript.compiler.TypeScriptCompiler;
| // Copyright 2015 Michel Kraemer
//
// 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 de.undercouch.vertx.lang.typescript.compiler;
/**
* Tests the {@link EngineCompiler}
* @author Michel Kraemer
*/
public class EngineCompilerTest extends CompilerTestBase {
private EngineCompiler compiler = new EngineCompiler();
@Before
public void beforeMethod() {
// skip EngineCompiler tests on Circle CI, because they are likely to time out
org.junit.Assume.assumeTrue(System.getenv("CIRCLE_BUILD_NUM") == null);
}
@Override
| // Path: src/main/java/de/undercouch/vertx/lang/typescript/compiler/EngineCompiler.java
// public class EngineCompiler implements TypeScriptCompiler {
// /**
// * Path to the TypeScript compiler
// */
// static final String TYPESCRIPT_JS = "typescript/lib/typescriptServices.js";
//
// /**
// * Path to a helper script calling the TypeScript compiler
// */
// static final String COMPILE_JS = "vertx-typescript/util/compile.js";
//
// /**
// * The JavaScript engine hosting the TypeScript compiler
// */
// private ScriptEngine engine;
//
// /**
// * Creates the JavaScript engine that hosts the TypeScript compiler. Loads
// * the compiler and a helper script and evaluates them within the engine.
// * @return the engine
// */
// private synchronized ScriptEngine getEngine() {
// if (engine != null) {
// return engine;
// }
//
// // create JavaScript engine
// ScriptEngineManager mgr = new ScriptEngineManager();
// engine = mgr.getEngineByName("nashorn");
// if (engine == null) {
// throw new IllegalStateException("Could not find Nashorn JavaScript engine.");
// }
//
// // load TypeScript compiler
// loadScript(TYPESCRIPT_JS, src -> {
// // WORKAROUND for a bug in Nashorn (https://bugs.openjdk.java.net/browse/JDK-8079426)
// // Inside the TypeScript compiler `ts.Diagnostics` is defined as a literal
// // with more than 256 items. This causes all elements to be undefined.
// // The bug has been fixed but it still occurs in Java 8u45.
//
// // find function where the diagnostics are defined
// String startStr = "ts.Diagnostics = {";
// String endStr = "};";
// int start = src.indexOf(startStr);
// int end = src.indexOf(endStr, start);
// String diagnostics = src.substring(start + startStr.length(), end);
//
// // change lines so properties are set one by one
// String[] diagLines = diagnostics.split("\n");
// for (int i = 0; i < diagLines.length; ++i) {
// diagLines[i] = diagLines[i].replaceFirst("^\\s*(.+?):", "ts.Diagnostics.$1 =");
// }
//
// // replace original lines with new ones
// String newDiagnostics = startStr + "};\n" + String.join("\n", diagLines) + ";";
// src = src.substring(0, start) + newDiagnostics + src.substring(end + endStr.length());
//
// return src;
// });
//
// // load compile.js
// loadScript(COMPILE_JS, null);
//
// // define some globals
// engine.put("__lineSeparator", System.lineSeparator());
// engine.put("__isFileNotFoundException", (Function<Object, Boolean>)(e ->
// e instanceof FileNotFoundException));
// engine.put("__printlnErr", (Consumer<Object>)System.err::println);
//
// return engine;
// }
//
// /**
// * Loads a JavaScript file and evaluate it within {@link #engine}
// * @param name the name of the file to load
// */
// private void loadScript(String name, Function<String, String> processSource) {
// URL url = getClass().getClassLoader().getResource(name);
// if (url == null) {
// throw new IllegalStateException("Cannot find " + name + " on classpath");
// }
//
// try {
// String src = Source.fromURL(url, StandardCharsets.UTF_8).toString();
// if (processSource != null) {
// src = processSource.apply(src);
// }
// engine.eval(src);
// } catch (ScriptException | IOException e) {
// throw new IllegalStateException("Could not evaluate " + name, e);
// }
// }
//
// @Override
// public String compile(String filename, SourceFactory sourceFactory) throws IOException {
// ScriptEngine e = getEngine();
// ScriptObjectMirror o = (ScriptObjectMirror)e.get("compileTypescript");
// return (String)o.call(null, filename, sourceFactory);
// }
// }
//
// Path: src/main/java/de/undercouch/vertx/lang/typescript/compiler/TypeScriptCompiler.java
// public interface TypeScriptCompiler {
// /**
// * Compiles the given TypeScript file
// * @param filename the name of the file to compile
// * @param sourceFactory the factory that loads source files
// * @return the generated code
// * @throws IOException if one of the source files to compile could not be loaded
// */
// String compile(String filename, SourceFactory sourceFactory) throws IOException;
// }
// Path: src/test/java/de/undercouch/vertx/lang/typescript/compiler/EngineCompilerTest.java
import org.junit.Before;
import de.undercouch.vertx.lang.typescript.compiler.EngineCompiler;
import de.undercouch.vertx.lang.typescript.compiler.TypeScriptCompiler;
// Copyright 2015 Michel Kraemer
//
// 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 de.undercouch.vertx.lang.typescript.compiler;
/**
* Tests the {@link EngineCompiler}
* @author Michel Kraemer
*/
public class EngineCompilerTest extends CompilerTestBase {
private EngineCompiler compiler = new EngineCompiler();
@Before
public void beforeMethod() {
// skip EngineCompiler tests on Circle CI, because they are likely to time out
org.junit.Assume.assumeTrue(System.getenv("CIRCLE_BUILD_NUM") == null);
}
@Override
| protected TypeScriptCompiler getCompiler() {
|
michel-kraemer/vertx-lang-typescript | src/test/java/de/undercouch/vertx/lang/typescript/compiler/CompilerTestBase.java | // Path: src/main/java/de/undercouch/vertx/lang/typescript/TypeScriptClassLoader.java
// public class TypeScriptClassLoader extends ClassLoader implements SourceFactory {
// /**
// * A cache for already loaded source files
// */
// private Map<String, Source> sourceCache = new HashMap<>();
//
// /**
// * A cache for already compiled sources
// */
// private final Cache codeCache;
//
// /**
// * A TypeScript compiler
// */
// private final TypeScriptCompiler compiler;
//
// /**
// * Creates a new class loader
// * @param parent the parent class loader
// * @param compiler a TypeScript compiler
// * @param codeCache a cache for already compiled sources
// */
// public TypeScriptClassLoader(ClassLoader parent, TypeScriptCompiler compiler, Cache codeCache) {
// super(parent);
// this.compiler = compiler;
// this.codeCache = codeCache;
// }
//
// @Override
// public InputStream getResourceAsStream(String name) {
// try {
// // load and compile TypeScript sources
// String lowerName = name.toLowerCase();
// if (lowerName.endsWith(".ts")) {
// return load(name);
// } else if (lowerName.endsWith(".ts.js")) {
// return load(name.substring(0, name.length() - 3));
// }
//
// // try to load other files directly
// InputStream r = super.getResourceAsStream(name);
// if (r == null && lowerName.endsWith(".js")) {
// // try to load .ts file instead
// return load(name.substring(0, name.length() - 3) + ".ts");
// }
// return r;
// } catch (IOException e) {
// // according to the interface
// return null;
// }
// }
//
// @Override
// public Source getSource(String name, String baseFilename) throws IOException {
// if (baseFilename != null && (name.startsWith("./") || name.startsWith("../"))) {
// // resolve relative path
// Source baseSource = getSource(baseFilename, null);
// if (baseSource != null) {
// name = baseSource.getURI().resolve(name).normalize().toString();
// }
// }
//
// Source result = sourceCache.get(name);
// if (result == null) {
// // check if we've got a URL
// URL u;
// if (name.matches("^[a-z]+:/.*")) {
// try {
// u = new URL(name);
// } catch (MalformedURLException e) {
// // no URL, might be a Windows path instead
// u = null;
// }
// } else {
// u = null;
// }
//
// // search class path
// if (u == null) {
// u = getParent().getResource(name);
// }
// if (u != null) {
// result = Source.fromURL(u, StandardCharsets.UTF_8);
// }
//
// // search file system (will throw if the file could not be found)
// if (result == null) {
// result = Source.fromFile(new File(name), StandardCharsets.UTF_8);
// }
//
// // at this point 'result' should never be null
// assert result != null;
// sourceCache.put(name, result);
// }
//
// return result;
// }
//
// /**
// * Loads and compiles a file with the given name
// * @param name the file name
// * @return an input stream delivering the
// * @throws IOException
// */
// private InputStream load(String name) throws IOException {
// // load file from class path or from file system
// Source src = getSource(name, null);
//
// // check if we have compiled the file before
// String code = codeCache.get(src);
// if (code == null) {
// // compile it now
// code = compiler.compile(name, this);
// codeCache.put(src, code);
// }
//
// return new ByteArrayInputStream(code.getBytes(StandardCharsets.UTF_8));
// }
// }
//
// Path: src/main/java/de/undercouch/vertx/lang/typescript/cache/NoopCache.java
// public class NoopCache implements Cache {
// @Override
// public String get(Source src) {
// return null;
// }
//
// @Override
// public void put(Source src, String value) {
// // do not cache
// }
// }
| import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.junit.Test;
import de.undercouch.vertx.lang.typescript.TypeScriptClassLoader;
import de.undercouch.vertx.lang.typescript.cache.NoopCache;
| // Copyright 2015 Michel Kraemer
//
// 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 de.undercouch.vertx.lang.typescript.compiler;
/**
* Common tests for all compilers
* @author Michel Kraemer
*/
public abstract class CompilerTestBase {
/**
* @return the actual compiler to test
*/
abstract protected TypeScriptCompiler getCompiler();
/**
* Compiles a very simple script
* @throws Exception if something goes wrong
*/
@Test
public void simpleScript() throws Exception {
| // Path: src/main/java/de/undercouch/vertx/lang/typescript/TypeScriptClassLoader.java
// public class TypeScriptClassLoader extends ClassLoader implements SourceFactory {
// /**
// * A cache for already loaded source files
// */
// private Map<String, Source> sourceCache = new HashMap<>();
//
// /**
// * A cache for already compiled sources
// */
// private final Cache codeCache;
//
// /**
// * A TypeScript compiler
// */
// private final TypeScriptCompiler compiler;
//
// /**
// * Creates a new class loader
// * @param parent the parent class loader
// * @param compiler a TypeScript compiler
// * @param codeCache a cache for already compiled sources
// */
// public TypeScriptClassLoader(ClassLoader parent, TypeScriptCompiler compiler, Cache codeCache) {
// super(parent);
// this.compiler = compiler;
// this.codeCache = codeCache;
// }
//
// @Override
// public InputStream getResourceAsStream(String name) {
// try {
// // load and compile TypeScript sources
// String lowerName = name.toLowerCase();
// if (lowerName.endsWith(".ts")) {
// return load(name);
// } else if (lowerName.endsWith(".ts.js")) {
// return load(name.substring(0, name.length() - 3));
// }
//
// // try to load other files directly
// InputStream r = super.getResourceAsStream(name);
// if (r == null && lowerName.endsWith(".js")) {
// // try to load .ts file instead
// return load(name.substring(0, name.length() - 3) + ".ts");
// }
// return r;
// } catch (IOException e) {
// // according to the interface
// return null;
// }
// }
//
// @Override
// public Source getSource(String name, String baseFilename) throws IOException {
// if (baseFilename != null && (name.startsWith("./") || name.startsWith("../"))) {
// // resolve relative path
// Source baseSource = getSource(baseFilename, null);
// if (baseSource != null) {
// name = baseSource.getURI().resolve(name).normalize().toString();
// }
// }
//
// Source result = sourceCache.get(name);
// if (result == null) {
// // check if we've got a URL
// URL u;
// if (name.matches("^[a-z]+:/.*")) {
// try {
// u = new URL(name);
// } catch (MalformedURLException e) {
// // no URL, might be a Windows path instead
// u = null;
// }
// } else {
// u = null;
// }
//
// // search class path
// if (u == null) {
// u = getParent().getResource(name);
// }
// if (u != null) {
// result = Source.fromURL(u, StandardCharsets.UTF_8);
// }
//
// // search file system (will throw if the file could not be found)
// if (result == null) {
// result = Source.fromFile(new File(name), StandardCharsets.UTF_8);
// }
//
// // at this point 'result' should never be null
// assert result != null;
// sourceCache.put(name, result);
// }
//
// return result;
// }
//
// /**
// * Loads and compiles a file with the given name
// * @param name the file name
// * @return an input stream delivering the
// * @throws IOException
// */
// private InputStream load(String name) throws IOException {
// // load file from class path or from file system
// Source src = getSource(name, null);
//
// // check if we have compiled the file before
// String code = codeCache.get(src);
// if (code == null) {
// // compile it now
// code = compiler.compile(name, this);
// codeCache.put(src, code);
// }
//
// return new ByteArrayInputStream(code.getBytes(StandardCharsets.UTF_8));
// }
// }
//
// Path: src/main/java/de/undercouch/vertx/lang/typescript/cache/NoopCache.java
// public class NoopCache implements Cache {
// @Override
// public String get(Source src) {
// return null;
// }
//
// @Override
// public void put(Source src, String value) {
// // do not cache
// }
// }
// Path: src/test/java/de/undercouch/vertx/lang/typescript/compiler/CompilerTestBase.java
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.junit.Test;
import de.undercouch.vertx.lang.typescript.TypeScriptClassLoader;
import de.undercouch.vertx.lang.typescript.cache.NoopCache;
// Copyright 2015 Michel Kraemer
//
// 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 de.undercouch.vertx.lang.typescript.compiler;
/**
* Common tests for all compilers
* @author Michel Kraemer
*/
public abstract class CompilerTestBase {
/**
* @return the actual compiler to test
*/
abstract protected TypeScriptCompiler getCompiler();
/**
* Compiles a very simple script
* @throws Exception if something goes wrong
*/
@Test
public void simpleScript() throws Exception {
| TypeScriptClassLoader cl = new TypeScriptClassLoader(this.getClass().getClassLoader(),
|
michel-kraemer/vertx-lang-typescript | src/test/java/de/undercouch/vertx/lang/typescript/compiler/CompilerTestBase.java | // Path: src/main/java/de/undercouch/vertx/lang/typescript/TypeScriptClassLoader.java
// public class TypeScriptClassLoader extends ClassLoader implements SourceFactory {
// /**
// * A cache for already loaded source files
// */
// private Map<String, Source> sourceCache = new HashMap<>();
//
// /**
// * A cache for already compiled sources
// */
// private final Cache codeCache;
//
// /**
// * A TypeScript compiler
// */
// private final TypeScriptCompiler compiler;
//
// /**
// * Creates a new class loader
// * @param parent the parent class loader
// * @param compiler a TypeScript compiler
// * @param codeCache a cache for already compiled sources
// */
// public TypeScriptClassLoader(ClassLoader parent, TypeScriptCompiler compiler, Cache codeCache) {
// super(parent);
// this.compiler = compiler;
// this.codeCache = codeCache;
// }
//
// @Override
// public InputStream getResourceAsStream(String name) {
// try {
// // load and compile TypeScript sources
// String lowerName = name.toLowerCase();
// if (lowerName.endsWith(".ts")) {
// return load(name);
// } else if (lowerName.endsWith(".ts.js")) {
// return load(name.substring(0, name.length() - 3));
// }
//
// // try to load other files directly
// InputStream r = super.getResourceAsStream(name);
// if (r == null && lowerName.endsWith(".js")) {
// // try to load .ts file instead
// return load(name.substring(0, name.length() - 3) + ".ts");
// }
// return r;
// } catch (IOException e) {
// // according to the interface
// return null;
// }
// }
//
// @Override
// public Source getSource(String name, String baseFilename) throws IOException {
// if (baseFilename != null && (name.startsWith("./") || name.startsWith("../"))) {
// // resolve relative path
// Source baseSource = getSource(baseFilename, null);
// if (baseSource != null) {
// name = baseSource.getURI().resolve(name).normalize().toString();
// }
// }
//
// Source result = sourceCache.get(name);
// if (result == null) {
// // check if we've got a URL
// URL u;
// if (name.matches("^[a-z]+:/.*")) {
// try {
// u = new URL(name);
// } catch (MalformedURLException e) {
// // no URL, might be a Windows path instead
// u = null;
// }
// } else {
// u = null;
// }
//
// // search class path
// if (u == null) {
// u = getParent().getResource(name);
// }
// if (u != null) {
// result = Source.fromURL(u, StandardCharsets.UTF_8);
// }
//
// // search file system (will throw if the file could not be found)
// if (result == null) {
// result = Source.fromFile(new File(name), StandardCharsets.UTF_8);
// }
//
// // at this point 'result' should never be null
// assert result != null;
// sourceCache.put(name, result);
// }
//
// return result;
// }
//
// /**
// * Loads and compiles a file with the given name
// * @param name the file name
// * @return an input stream delivering the
// * @throws IOException
// */
// private InputStream load(String name) throws IOException {
// // load file from class path or from file system
// Source src = getSource(name, null);
//
// // check if we have compiled the file before
// String code = codeCache.get(src);
// if (code == null) {
// // compile it now
// code = compiler.compile(name, this);
// codeCache.put(src, code);
// }
//
// return new ByteArrayInputStream(code.getBytes(StandardCharsets.UTF_8));
// }
// }
//
// Path: src/main/java/de/undercouch/vertx/lang/typescript/cache/NoopCache.java
// public class NoopCache implements Cache {
// @Override
// public String get(Source src) {
// return null;
// }
//
// @Override
// public void put(Source src, String value) {
// // do not cache
// }
// }
| import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.junit.Test;
import de.undercouch.vertx.lang.typescript.TypeScriptClassLoader;
import de.undercouch.vertx.lang.typescript.cache.NoopCache;
| // Copyright 2015 Michel Kraemer
//
// 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 de.undercouch.vertx.lang.typescript.compiler;
/**
* Common tests for all compilers
* @author Michel Kraemer
*/
public abstract class CompilerTestBase {
/**
* @return the actual compiler to test
*/
abstract protected TypeScriptCompiler getCompiler();
/**
* Compiles a very simple script
* @throws Exception if something goes wrong
*/
@Test
public void simpleScript() throws Exception {
TypeScriptClassLoader cl = new TypeScriptClassLoader(this.getClass().getClassLoader(),
| // Path: src/main/java/de/undercouch/vertx/lang/typescript/TypeScriptClassLoader.java
// public class TypeScriptClassLoader extends ClassLoader implements SourceFactory {
// /**
// * A cache for already loaded source files
// */
// private Map<String, Source> sourceCache = new HashMap<>();
//
// /**
// * A cache for already compiled sources
// */
// private final Cache codeCache;
//
// /**
// * A TypeScript compiler
// */
// private final TypeScriptCompiler compiler;
//
// /**
// * Creates a new class loader
// * @param parent the parent class loader
// * @param compiler a TypeScript compiler
// * @param codeCache a cache for already compiled sources
// */
// public TypeScriptClassLoader(ClassLoader parent, TypeScriptCompiler compiler, Cache codeCache) {
// super(parent);
// this.compiler = compiler;
// this.codeCache = codeCache;
// }
//
// @Override
// public InputStream getResourceAsStream(String name) {
// try {
// // load and compile TypeScript sources
// String lowerName = name.toLowerCase();
// if (lowerName.endsWith(".ts")) {
// return load(name);
// } else if (lowerName.endsWith(".ts.js")) {
// return load(name.substring(0, name.length() - 3));
// }
//
// // try to load other files directly
// InputStream r = super.getResourceAsStream(name);
// if (r == null && lowerName.endsWith(".js")) {
// // try to load .ts file instead
// return load(name.substring(0, name.length() - 3) + ".ts");
// }
// return r;
// } catch (IOException e) {
// // according to the interface
// return null;
// }
// }
//
// @Override
// public Source getSource(String name, String baseFilename) throws IOException {
// if (baseFilename != null && (name.startsWith("./") || name.startsWith("../"))) {
// // resolve relative path
// Source baseSource = getSource(baseFilename, null);
// if (baseSource != null) {
// name = baseSource.getURI().resolve(name).normalize().toString();
// }
// }
//
// Source result = sourceCache.get(name);
// if (result == null) {
// // check if we've got a URL
// URL u;
// if (name.matches("^[a-z]+:/.*")) {
// try {
// u = new URL(name);
// } catch (MalformedURLException e) {
// // no URL, might be a Windows path instead
// u = null;
// }
// } else {
// u = null;
// }
//
// // search class path
// if (u == null) {
// u = getParent().getResource(name);
// }
// if (u != null) {
// result = Source.fromURL(u, StandardCharsets.UTF_8);
// }
//
// // search file system (will throw if the file could not be found)
// if (result == null) {
// result = Source.fromFile(new File(name), StandardCharsets.UTF_8);
// }
//
// // at this point 'result' should never be null
// assert result != null;
// sourceCache.put(name, result);
// }
//
// return result;
// }
//
// /**
// * Loads and compiles a file with the given name
// * @param name the file name
// * @return an input stream delivering the
// * @throws IOException
// */
// private InputStream load(String name) throws IOException {
// // load file from class path or from file system
// Source src = getSource(name, null);
//
// // check if we have compiled the file before
// String code = codeCache.get(src);
// if (code == null) {
// // compile it now
// code = compiler.compile(name, this);
// codeCache.put(src, code);
// }
//
// return new ByteArrayInputStream(code.getBytes(StandardCharsets.UTF_8));
// }
// }
//
// Path: src/main/java/de/undercouch/vertx/lang/typescript/cache/NoopCache.java
// public class NoopCache implements Cache {
// @Override
// public String get(Source src) {
// return null;
// }
//
// @Override
// public void put(Source src, String value) {
// // do not cache
// }
// }
// Path: src/test/java/de/undercouch/vertx/lang/typescript/compiler/CompilerTestBase.java
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.junit.Test;
import de.undercouch.vertx.lang.typescript.TypeScriptClassLoader;
import de.undercouch.vertx.lang.typescript.cache.NoopCache;
// Copyright 2015 Michel Kraemer
//
// 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 de.undercouch.vertx.lang.typescript.compiler;
/**
* Common tests for all compilers
* @author Michel Kraemer
*/
public abstract class CompilerTestBase {
/**
* @return the actual compiler to test
*/
abstract protected TypeScriptCompiler getCompiler();
/**
* Compiles a very simple script
* @throws Exception if something goes wrong
*/
@Test
public void simpleScript() throws Exception {
TypeScriptClassLoader cl = new TypeScriptClassLoader(this.getClass().getClassLoader(),
| null, new NoopCache());
|
NonVolatileComputing/Mnemonic | core/src/main/java/com/intel/bigdatamem/BigDataPMemAllocator.java | // Path: core/src/main/java/com/intel/mnemonic/service/allocatorservice/NonVolatileMemoryAllocatorService.java
// public interface NonVolatileMemoryAllocatorService extends VolatileMemoryAllocatorService {
//
// /**
// * retrieve a bytebuffer from its handler
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @param handler
// * the handler of a nonvolatile bytebuffer
// *
// * @return the nonvolatile bytebuffer
// *
// */
// public ByteBuffer retrieveByteBuffer(long id, long handler);
//
// /**
// * retrieve the size of a nonvolatile memory object
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @param handler
// * the handler of a nonvolatile object
// *
// * @return the size of nonvolatile object
// *
// */
// public long retrieveSize(long id, long handler);
//
// /**
// * get the handler of a nonvolatile bytebuffer
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @param buf
// * the nonvolatile bytebuffer
// *
// * @return the handler of this specified nonvolatile bytebuffer
// *
// */
// public long getByteBufferHandler(long id, ByteBuffer buf);
//
// /**
// * set a handler to a key.
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @param key
// * the key to set this handler
// *
// * @param handler
// * the handler
// */
// public void setHandler(long id, long key, long handler);
//
// /**
// * get a handler from specified key.
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @param key
// * the key to get its handler
// *
// * @return the handler of the specified key
// */
// public long getHandler(long id, long key);
//
// /**
// * return the number of available keys to use.
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @return the number of keys
// */
// public long handlerCapacity(long id);
//
// /**
// * return the base address of this persistent memory pool.
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @return the base address of this pmem pool
// */
// public long getBaseAddress(long id);
//
// }
| import java.nio.ByteBuffer;
import org.flowcomputing.commons.resgc.*;
import org.flowcomputing.commons.primitives.*;
import com.intel.mnemonic.service.allocatorservice.NonVolatileMemoryAllocatorService; | package com.intel.bigdatamem;
/**
* manage a big native persistent memory pool through libpmalloc.so provided by pmalloc project.
*
*
*/
public class BigDataPMemAllocator extends CommonPersistAllocator<BigDataPMemAllocator> implements PMAddressTranslator{
private boolean m_activegc = true;
private long m_gctimeout = 100;
private long m_nid = -1;
private long b_addr = 0; | // Path: core/src/main/java/com/intel/mnemonic/service/allocatorservice/NonVolatileMemoryAllocatorService.java
// public interface NonVolatileMemoryAllocatorService extends VolatileMemoryAllocatorService {
//
// /**
// * retrieve a bytebuffer from its handler
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @param handler
// * the handler of a nonvolatile bytebuffer
// *
// * @return the nonvolatile bytebuffer
// *
// */
// public ByteBuffer retrieveByteBuffer(long id, long handler);
//
// /**
// * retrieve the size of a nonvolatile memory object
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @param handler
// * the handler of a nonvolatile object
// *
// * @return the size of nonvolatile object
// *
// */
// public long retrieveSize(long id, long handler);
//
// /**
// * get the handler of a nonvolatile bytebuffer
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @param buf
// * the nonvolatile bytebuffer
// *
// * @return the handler of this specified nonvolatile bytebuffer
// *
// */
// public long getByteBufferHandler(long id, ByteBuffer buf);
//
// /**
// * set a handler to a key.
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @param key
// * the key to set this handler
// *
// * @param handler
// * the handler
// */
// public void setHandler(long id, long key, long handler);
//
// /**
// * get a handler from specified key.
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @param key
// * the key to get its handler
// *
// * @return the handler of the specified key
// */
// public long getHandler(long id, long key);
//
// /**
// * return the number of available keys to use.
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @return the number of keys
// */
// public long handlerCapacity(long id);
//
// /**
// * return the base address of this persistent memory pool.
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @return the base address of this pmem pool
// */
// public long getBaseAddress(long id);
//
// }
// Path: core/src/main/java/com/intel/bigdatamem/BigDataPMemAllocator.java
import java.nio.ByteBuffer;
import org.flowcomputing.commons.resgc.*;
import org.flowcomputing.commons.primitives.*;
import com.intel.mnemonic.service.allocatorservice.NonVolatileMemoryAllocatorService;
package com.intel.bigdatamem;
/**
* manage a big native persistent memory pool through libpmalloc.so provided by pmalloc project.
*
*
*/
public class BigDataPMemAllocator extends CommonPersistAllocator<BigDataPMemAllocator> implements PMAddressTranslator{
private boolean m_activegc = true;
private long m_gctimeout = 100;
private long m_nid = -1;
private long b_addr = 0; | private NonVolatileMemoryAllocatorService m_nvmasvc = null; |
NonVolatileComputing/Mnemonic | core/src/main/java/com/intel/bigdatamem/BigDataMemAllocator.java | // Path: core/src/main/java/com/intel/mnemonic/service/allocatorservice/VolatileMemoryAllocatorService.java
// public interface VolatileMemoryAllocatorService {
//
// /**
// * Provide the service identifier for this allocator
// *
// * @return the service identifer of this allocator
// */
// public String getServiceId();
//
// /**
// * Initialize a memory pool through native interface backed by native
// * library.
// *
// * @param capacity
// * the capacity of memory pool
// *
// * @param uri
// * the location of memory pool will be created
// *
// * @param isnew
// * a place holder, always specify it as true
// *
// * @return the identifier of created memory pool
// */
// public long init(long capacity, String uri, boolean isnew);
//
// /**
// * close the memory pool through native interface.
// *
// */
// public void close(long id);
//
//
// /**
// * force to synchronize uncommitted data to backed memory pool through
// * native interface.
// */
// public void sync(long id);
//
// /**
// * allocate specified size of memory block from backed memory pool.
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @param size
// * specify size of memory block to be allocated
// *
// * @return the address of allocated memory block from native memory pool
// */
// public long allocate(long id, long size, boolean initzero);
//
// /**
// * reallocate a specified size of memory block from backed memory pool.
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @param address
// * the address of previous allocated memory block. it can be
// * null.
// *
// * @param size
// * specify new size of memory block to be reallocated
// *
// * @return the address of reallocated memory block from native memory pool
// */
// public long reallocate(long id, long address, long size, boolean initzero);
//
// /**
// * free a memory block by specify its address into backed memory pool.
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @param address
// * the address of allocated memory block.
// */
// public void free(long id, long address);
//
// /**
// * create a ByteBuffer object which backed buffer is coming from backed
// * native memory pool.
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @param size
// * the size of backed buffer that is managed by created
// * ByteBuffer object.
// *
// * @return a created ByteBuffer object with a backed native memory block
// */
// public ByteBuffer createByteBuffer(long id, long size);
//
// /**
// * resize a ByteBuffer object which backed buffer is coming from backed
// * native memory pool.
// * NOTE: the ByteBuffer object will be renewed and lost metadata e.g. position, mark and etc.
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @param bytebuf
// * the specified ByteBuffer object to be destroyed
// *
// * @param size
// * the new size of backed buffer that is managed by created
// * ByteBuffer object.
// *
// * @return a created ByteBuffer object with a backed native memory block
// */
// public ByteBuffer resizeByteBuffer(long id, ByteBuffer bytebuf, long size);
//
// /**
// * destroy a native memory block backed ByteBuffer object.
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @param bytebuf
// * the specified ByteBuffer object to be destroyed
// */
// public void destroyByteBuffer(long id, ByteBuffer bytebuf);
// }
| import java.nio.ByteBuffer;
import org.flowcomputing.commons.resgc.*;
import org.flowcomputing.commons.primitives.*;
import com.intel.mnemonic.service.allocatorservice.VolatileMemoryAllocatorService; | package com.intel.bigdatamem;
/**
* manage a big native memory pool through libvmem.so that is provied by Intel nvml library.
*
*
*/
public class BigDataMemAllocator extends CommonAllocator<BigDataMemAllocator> {
private boolean m_activegc = true;
private long m_gctimeout = 100;
private long m_nid = -1; | // Path: core/src/main/java/com/intel/mnemonic/service/allocatorservice/VolatileMemoryAllocatorService.java
// public interface VolatileMemoryAllocatorService {
//
// /**
// * Provide the service identifier for this allocator
// *
// * @return the service identifer of this allocator
// */
// public String getServiceId();
//
// /**
// * Initialize a memory pool through native interface backed by native
// * library.
// *
// * @param capacity
// * the capacity of memory pool
// *
// * @param uri
// * the location of memory pool will be created
// *
// * @param isnew
// * a place holder, always specify it as true
// *
// * @return the identifier of created memory pool
// */
// public long init(long capacity, String uri, boolean isnew);
//
// /**
// * close the memory pool through native interface.
// *
// */
// public void close(long id);
//
//
// /**
// * force to synchronize uncommitted data to backed memory pool through
// * native interface.
// */
// public void sync(long id);
//
// /**
// * allocate specified size of memory block from backed memory pool.
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @param size
// * specify size of memory block to be allocated
// *
// * @return the address of allocated memory block from native memory pool
// */
// public long allocate(long id, long size, boolean initzero);
//
// /**
// * reallocate a specified size of memory block from backed memory pool.
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @param address
// * the address of previous allocated memory block. it can be
// * null.
// *
// * @param size
// * specify new size of memory block to be reallocated
// *
// * @return the address of reallocated memory block from native memory pool
// */
// public long reallocate(long id, long address, long size, boolean initzero);
//
// /**
// * free a memory block by specify its address into backed memory pool.
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @param address
// * the address of allocated memory block.
// */
// public void free(long id, long address);
//
// /**
// * create a ByteBuffer object which backed buffer is coming from backed
// * native memory pool.
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @param size
// * the size of backed buffer that is managed by created
// * ByteBuffer object.
// *
// * @return a created ByteBuffer object with a backed native memory block
// */
// public ByteBuffer createByteBuffer(long id, long size);
//
// /**
// * resize a ByteBuffer object which backed buffer is coming from backed
// * native memory pool.
// * NOTE: the ByteBuffer object will be renewed and lost metadata e.g. position, mark and etc.
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @param bytebuf
// * the specified ByteBuffer object to be destroyed
// *
// * @param size
// * the new size of backed buffer that is managed by created
// * ByteBuffer object.
// *
// * @return a created ByteBuffer object with a backed native memory block
// */
// public ByteBuffer resizeByteBuffer(long id, ByteBuffer bytebuf, long size);
//
// /**
// * destroy a native memory block backed ByteBuffer object.
// *
// * @param id
// * the identifier of backed memory pool
// *
// * @param bytebuf
// * the specified ByteBuffer object to be destroyed
// */
// public void destroyByteBuffer(long id, ByteBuffer bytebuf);
// }
// Path: core/src/main/java/com/intel/bigdatamem/BigDataMemAllocator.java
import java.nio.ByteBuffer;
import org.flowcomputing.commons.resgc.*;
import org.flowcomputing.commons.primitives.*;
import com.intel.mnemonic.service.allocatorservice.VolatileMemoryAllocatorService;
package com.intel.bigdatamem;
/**
* manage a big native memory pool through libvmem.so that is provied by Intel nvml library.
*
*
*/
public class BigDataMemAllocator extends CommonAllocator<BigDataMemAllocator> {
private boolean m_activegc = true;
private long m_gctimeout = 100;
private long m_nid = -1; | private VolatileMemoryAllocatorService m_vmasvc = null; |
qibin0506/Glin | glin/src/main/java/org/loader/glin/parser/Parser.java | // Path: glin/src/main/java/org/loader/glin/RawResult.java
// public class RawResult {
// private int statusCode;
// private String message;
// private String response;
//
// public RawResult() {}
//
// public RawResult(int statusCode, String message, String response) {
// this.statusCode = statusCode;
// this.message = message;
// this.response = response;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public void setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/Result.java
// public class Result<T> {
// private boolean ok;
// private String message;
// private T result;
// private int code;
// private Object obj;
// private boolean isCache;
//
// public boolean isOK() {
// return ok;
// }
//
// public void ok(boolean ok) {
// this.ok = ok;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String mMessage) {
// this.message = mMessage;
// }
//
// public T getResult() {
// return result;
// }
//
// public void setResult(T mResult) {
// this.result = mResult;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
//
// public Object getObj() {
// return obj;
// }
//
// public void setObj(Object obj) {
// this.obj = obj;
// }
//
// public <V> V assertGetObj() {
// return (V) getObj();
// }
//
// public boolean isCache() {
// return isCache;
// }
//
// public void setCache(boolean cache) {
// isCache = cache;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("ok: ").append(ok).append("\n");
// sb.append("message: ").append(message).append("\n");
// sb.append("obj: ").append(obj).append("\n");
// sb.append("result: ").append(result).append("\n");
// sb.append("code: ").append(code).append("\n");
// sb.append("is_cache: ").append(isCache);
//
// return sb.toString();
// }
// }
| import org.loader.glin.RawResult;
import org.loader.glin.Result; | package org.loader.glin.parser;
/**
* Created by qibin on 2016/7/13.
*/
public abstract class Parser {
public String mKey;
public Parser() {
}
public Parser(String key) {
mKey = key;
}
/**
*
* @param klass the class of data struct
* @param netResult
* @param <T>
* @return
*/ | // Path: glin/src/main/java/org/loader/glin/RawResult.java
// public class RawResult {
// private int statusCode;
// private String message;
// private String response;
//
// public RawResult() {}
//
// public RawResult(int statusCode, String message, String response) {
// this.statusCode = statusCode;
// this.message = message;
// this.response = response;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public void setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/Result.java
// public class Result<T> {
// private boolean ok;
// private String message;
// private T result;
// private int code;
// private Object obj;
// private boolean isCache;
//
// public boolean isOK() {
// return ok;
// }
//
// public void ok(boolean ok) {
// this.ok = ok;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String mMessage) {
// this.message = mMessage;
// }
//
// public T getResult() {
// return result;
// }
//
// public void setResult(T mResult) {
// this.result = mResult;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
//
// public Object getObj() {
// return obj;
// }
//
// public void setObj(Object obj) {
// this.obj = obj;
// }
//
// public <V> V assertGetObj() {
// return (V) getObj();
// }
//
// public boolean isCache() {
// return isCache;
// }
//
// public void setCache(boolean cache) {
// isCache = cache;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("ok: ").append(ok).append("\n");
// sb.append("message: ").append(message).append("\n");
// sb.append("obj: ").append(obj).append("\n");
// sb.append("result: ").append(result).append("\n");
// sb.append("code: ").append(code).append("\n");
// sb.append("is_cache: ").append(isCache);
//
// return sb.toString();
// }
// }
// Path: glin/src/main/java/org/loader/glin/parser/Parser.java
import org.loader.glin.RawResult;
import org.loader.glin.Result;
package org.loader.glin.parser;
/**
* Created by qibin on 2016/7/13.
*/
public abstract class Parser {
public String mKey;
public Parser() {
}
public Parser(String key) {
mKey = key;
}
/**
*
* @param klass the class of data struct
* @param netResult
* @param <T>
* @return
*/ | public abstract <T> Result<T> parse(Class<T> klass, RawResult netResult); |
qibin0506/Glin | glin/src/main/java/org/loader/glin/parser/Parser.java | // Path: glin/src/main/java/org/loader/glin/RawResult.java
// public class RawResult {
// private int statusCode;
// private String message;
// private String response;
//
// public RawResult() {}
//
// public RawResult(int statusCode, String message, String response) {
// this.statusCode = statusCode;
// this.message = message;
// this.response = response;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public void setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/Result.java
// public class Result<T> {
// private boolean ok;
// private String message;
// private T result;
// private int code;
// private Object obj;
// private boolean isCache;
//
// public boolean isOK() {
// return ok;
// }
//
// public void ok(boolean ok) {
// this.ok = ok;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String mMessage) {
// this.message = mMessage;
// }
//
// public T getResult() {
// return result;
// }
//
// public void setResult(T mResult) {
// this.result = mResult;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
//
// public Object getObj() {
// return obj;
// }
//
// public void setObj(Object obj) {
// this.obj = obj;
// }
//
// public <V> V assertGetObj() {
// return (V) getObj();
// }
//
// public boolean isCache() {
// return isCache;
// }
//
// public void setCache(boolean cache) {
// isCache = cache;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("ok: ").append(ok).append("\n");
// sb.append("message: ").append(message).append("\n");
// sb.append("obj: ").append(obj).append("\n");
// sb.append("result: ").append(result).append("\n");
// sb.append("code: ").append(code).append("\n");
// sb.append("is_cache: ").append(isCache);
//
// return sb.toString();
// }
// }
| import org.loader.glin.RawResult;
import org.loader.glin.Result; | package org.loader.glin.parser;
/**
* Created by qibin on 2016/7/13.
*/
public abstract class Parser {
public String mKey;
public Parser() {
}
public Parser(String key) {
mKey = key;
}
/**
*
* @param klass the class of data struct
* @param netResult
* @param <T>
* @return
*/ | // Path: glin/src/main/java/org/loader/glin/RawResult.java
// public class RawResult {
// private int statusCode;
// private String message;
// private String response;
//
// public RawResult() {}
//
// public RawResult(int statusCode, String message, String response) {
// this.statusCode = statusCode;
// this.message = message;
// this.response = response;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public void setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/Result.java
// public class Result<T> {
// private boolean ok;
// private String message;
// private T result;
// private int code;
// private Object obj;
// private boolean isCache;
//
// public boolean isOK() {
// return ok;
// }
//
// public void ok(boolean ok) {
// this.ok = ok;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String mMessage) {
// this.message = mMessage;
// }
//
// public T getResult() {
// return result;
// }
//
// public void setResult(T mResult) {
// this.result = mResult;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
//
// public Object getObj() {
// return obj;
// }
//
// public void setObj(Object obj) {
// this.obj = obj;
// }
//
// public <V> V assertGetObj() {
// return (V) getObj();
// }
//
// public boolean isCache() {
// return isCache;
// }
//
// public void setCache(boolean cache) {
// isCache = cache;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("ok: ").append(ok).append("\n");
// sb.append("message: ").append(message).append("\n");
// sb.append("obj: ").append(obj).append("\n");
// sb.append("result: ").append(result).append("\n");
// sb.append("code: ").append(code).append("\n");
// sb.append("is_cache: ").append(isCache);
//
// return sb.toString();
// }
// }
// Path: glin/src/main/java/org/loader/glin/parser/Parser.java
import org.loader.glin.RawResult;
import org.loader.glin.Result;
package org.loader.glin.parser;
/**
* Created by qibin on 2016/7/13.
*/
public abstract class Parser {
public String mKey;
public Parser() {
}
public Parser(String key) {
mKey = key;
}
/**
*
* @param klass the class of data struct
* @param netResult
* @param <T>
* @return
*/ | public abstract <T> Result<T> parse(Class<T> klass, RawResult netResult); |
qibin0506/Glin | glin/src/main/java/org/loader/glin/client/IRequest.java | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/Params.java
// public class Params {
//
// public static final String DEFAULT_JSON_KEY = "json";
//
// private LinkedHashMap<String, String> mParams;
// private LinkedHashMap<String, File> mFiles;
//
// public Params() {
// mParams = new LinkedHashMap<>();
// mFiles = new LinkedHashMap<>();
// }
//
// public Params(String key, Object value) {
// this();
// add(key, value);
// }
//
// public Params add(String key, Object value) {
// if (key == null) { return this;}
// if (value == null) { mParams.put(key, null);}
// else if (value instanceof File) { mFiles.put(key, (File) value);}
// else { mParams.put(key, value.toString());}
// return this;
// }
//
// public LinkedHashMap<String, String> get() {
// return mParams;
// }
//
// public String getParams(String key) {
// return mParams.get(key);
// }
//
// public File getFile(String key) {
// return mFiles.get(key);
// }
//
// public LinkedHashMap<String, File> files() {
// return mFiles;
// }
//
// public void remove(String key) {
// if (mParams.containsKey(key)) { mParams.remove(key);}
// if (mFiles.containsKey(key)) { mFiles.remove(key);}
// }
//
// public String encode() {
// String query = null;
// for (Map.Entry<String, String> entry : mParams.entrySet()) {
// if (query == null) { query = entry.getKey() + "=" + entry.getValue();}
// else { query += "&" + entry.getKey() + "=" + entry.getValue();}
// }
//
// return query;
// }
//
// public Iterator<String> iterator() {
// return mParams.keySet().iterator();
// }
//
// public Iterator<String> fileIterator() {
// return mFiles.keySet().iterator();
// }
//
// public boolean isEmpty() {
// return mParams.isEmpty() && mFiles.isEmpty();
// }
// }
| import org.loader.glin.Callback;
import org.loader.glin.Params;
import java.util.LinkedHashMap; | package org.loader.glin.client;
/**
* Created by qibin on 2016/8/29.
*/
public interface IRequest {
<T> void get(final String url, final LinkedHashMap<String, String> header, final Object tag, | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/Params.java
// public class Params {
//
// public static final String DEFAULT_JSON_KEY = "json";
//
// private LinkedHashMap<String, String> mParams;
// private LinkedHashMap<String, File> mFiles;
//
// public Params() {
// mParams = new LinkedHashMap<>();
// mFiles = new LinkedHashMap<>();
// }
//
// public Params(String key, Object value) {
// this();
// add(key, value);
// }
//
// public Params add(String key, Object value) {
// if (key == null) { return this;}
// if (value == null) { mParams.put(key, null);}
// else if (value instanceof File) { mFiles.put(key, (File) value);}
// else { mParams.put(key, value.toString());}
// return this;
// }
//
// public LinkedHashMap<String, String> get() {
// return mParams;
// }
//
// public String getParams(String key) {
// return mParams.get(key);
// }
//
// public File getFile(String key) {
// return mFiles.get(key);
// }
//
// public LinkedHashMap<String, File> files() {
// return mFiles;
// }
//
// public void remove(String key) {
// if (mParams.containsKey(key)) { mParams.remove(key);}
// if (mFiles.containsKey(key)) { mFiles.remove(key);}
// }
//
// public String encode() {
// String query = null;
// for (Map.Entry<String, String> entry : mParams.entrySet()) {
// if (query == null) { query = entry.getKey() + "=" + entry.getValue();}
// else { query += "&" + entry.getKey() + "=" + entry.getValue();}
// }
//
// return query;
// }
//
// public Iterator<String> iterator() {
// return mParams.keySet().iterator();
// }
//
// public Iterator<String> fileIterator() {
// return mFiles.keySet().iterator();
// }
//
// public boolean isEmpty() {
// return mParams.isEmpty() && mFiles.isEmpty();
// }
// }
// Path: glin/src/main/java/org/loader/glin/client/IRequest.java
import org.loader.glin.Callback;
import org.loader.glin.Params;
import java.util.LinkedHashMap;
package org.loader.glin.client;
/**
* Created by qibin on 2016/8/29.
*/
public interface IRequest {
<T> void get(final String url, final LinkedHashMap<String, String> header, final Object tag, | final boolean shouldCache, final Callback<T> callback); |
qibin0506/Glin | glin/src/main/java/org/loader/glin/client/IRequest.java | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/Params.java
// public class Params {
//
// public static final String DEFAULT_JSON_KEY = "json";
//
// private LinkedHashMap<String, String> mParams;
// private LinkedHashMap<String, File> mFiles;
//
// public Params() {
// mParams = new LinkedHashMap<>();
// mFiles = new LinkedHashMap<>();
// }
//
// public Params(String key, Object value) {
// this();
// add(key, value);
// }
//
// public Params add(String key, Object value) {
// if (key == null) { return this;}
// if (value == null) { mParams.put(key, null);}
// else if (value instanceof File) { mFiles.put(key, (File) value);}
// else { mParams.put(key, value.toString());}
// return this;
// }
//
// public LinkedHashMap<String, String> get() {
// return mParams;
// }
//
// public String getParams(String key) {
// return mParams.get(key);
// }
//
// public File getFile(String key) {
// return mFiles.get(key);
// }
//
// public LinkedHashMap<String, File> files() {
// return mFiles;
// }
//
// public void remove(String key) {
// if (mParams.containsKey(key)) { mParams.remove(key);}
// if (mFiles.containsKey(key)) { mFiles.remove(key);}
// }
//
// public String encode() {
// String query = null;
// for (Map.Entry<String, String> entry : mParams.entrySet()) {
// if (query == null) { query = entry.getKey() + "=" + entry.getValue();}
// else { query += "&" + entry.getKey() + "=" + entry.getValue();}
// }
//
// return query;
// }
//
// public Iterator<String> iterator() {
// return mParams.keySet().iterator();
// }
//
// public Iterator<String> fileIterator() {
// return mFiles.keySet().iterator();
// }
//
// public boolean isEmpty() {
// return mParams.isEmpty() && mFiles.isEmpty();
// }
// }
| import org.loader.glin.Callback;
import org.loader.glin.Params;
import java.util.LinkedHashMap; | package org.loader.glin.client;
/**
* Created by qibin on 2016/8/29.
*/
public interface IRequest {
<T> void get(final String url, final LinkedHashMap<String, String> header, final Object tag,
final boolean shouldCache, final Callback<T> callback);
| // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/Params.java
// public class Params {
//
// public static final String DEFAULT_JSON_KEY = "json";
//
// private LinkedHashMap<String, String> mParams;
// private LinkedHashMap<String, File> mFiles;
//
// public Params() {
// mParams = new LinkedHashMap<>();
// mFiles = new LinkedHashMap<>();
// }
//
// public Params(String key, Object value) {
// this();
// add(key, value);
// }
//
// public Params add(String key, Object value) {
// if (key == null) { return this;}
// if (value == null) { mParams.put(key, null);}
// else if (value instanceof File) { mFiles.put(key, (File) value);}
// else { mParams.put(key, value.toString());}
// return this;
// }
//
// public LinkedHashMap<String, String> get() {
// return mParams;
// }
//
// public String getParams(String key) {
// return mParams.get(key);
// }
//
// public File getFile(String key) {
// return mFiles.get(key);
// }
//
// public LinkedHashMap<String, File> files() {
// return mFiles;
// }
//
// public void remove(String key) {
// if (mParams.containsKey(key)) { mParams.remove(key);}
// if (mFiles.containsKey(key)) { mFiles.remove(key);}
// }
//
// public String encode() {
// String query = null;
// for (Map.Entry<String, String> entry : mParams.entrySet()) {
// if (query == null) { query = entry.getKey() + "=" + entry.getValue();}
// else { query += "&" + entry.getKey() + "=" + entry.getValue();}
// }
//
// return query;
// }
//
// public Iterator<String> iterator() {
// return mParams.keySet().iterator();
// }
//
// public Iterator<String> fileIterator() {
// return mFiles.keySet().iterator();
// }
//
// public boolean isEmpty() {
// return mParams.isEmpty() && mFiles.isEmpty();
// }
// }
// Path: glin/src/main/java/org/loader/glin/client/IRequest.java
import org.loader.glin.Callback;
import org.loader.glin.Params;
import java.util.LinkedHashMap;
package org.loader.glin.client;
/**
* Created by qibin on 2016/8/29.
*/
public interface IRequest {
<T> void get(final String url, final LinkedHashMap<String, String> header, final Object tag,
final boolean shouldCache, final Callback<T> callback);
| <T> void post(final String url, final LinkedHashMap<String, String> header, final Params params, |
qibin0506/Glin | glin/src/main/java/org/loader/glin/cache/ICacheProvider.java | // Path: glin/src/main/java/org/loader/glin/RawResult.java
// public class RawResult {
// private int statusCode;
// private String message;
// private String response;
//
// public RawResult() {}
//
// public RawResult(int statusCode, String message, String response) {
// this.statusCode = statusCode;
// this.message = message;
// this.response = response;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public void setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/Result.java
// public class Result<T> {
// private boolean ok;
// private String message;
// private T result;
// private int code;
// private Object obj;
// private boolean isCache;
//
// public boolean isOK() {
// return ok;
// }
//
// public void ok(boolean ok) {
// this.ok = ok;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String mMessage) {
// this.message = mMessage;
// }
//
// public T getResult() {
// return result;
// }
//
// public void setResult(T mResult) {
// this.result = mResult;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
//
// public Object getObj() {
// return obj;
// }
//
// public void setObj(Object obj) {
// this.obj = obj;
// }
//
// public <V> V assertGetObj() {
// return (V) getObj();
// }
//
// public boolean isCache() {
// return isCache;
// }
//
// public void setCache(boolean cache) {
// isCache = cache;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("ok: ").append(ok).append("\n");
// sb.append("message: ").append(message).append("\n");
// sb.append("obj: ").append(obj).append("\n");
// sb.append("result: ").append(result).append("\n");
// sb.append("code: ").append(code).append("\n");
// sb.append("is_cache: ").append(isCache);
//
// return sb.toString();
// }
// }
| import org.loader.glin.RawResult;
import org.loader.glin.Result; | package org.loader.glin.cache;
public interface ICacheProvider {
/**
* get cache by key of {@link #getKey(String, String)}
* @param key key
* @param klass type of data struct, see also {@link org.loader.glin.helper.Helper}
* @param isList is result a List
* @return cache data
*/
<T> Result<T> get(String key, Class<T> klass, boolean isList);
/**
* cache data
* @param key see {@link #getKey(String, String)}
* @param netResult the origin result
* @param result parsed result
*/ | // Path: glin/src/main/java/org/loader/glin/RawResult.java
// public class RawResult {
// private int statusCode;
// private String message;
// private String response;
//
// public RawResult() {}
//
// public RawResult(int statusCode, String message, String response) {
// this.statusCode = statusCode;
// this.message = message;
// this.response = response;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public void setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/Result.java
// public class Result<T> {
// private boolean ok;
// private String message;
// private T result;
// private int code;
// private Object obj;
// private boolean isCache;
//
// public boolean isOK() {
// return ok;
// }
//
// public void ok(boolean ok) {
// this.ok = ok;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String mMessage) {
// this.message = mMessage;
// }
//
// public T getResult() {
// return result;
// }
//
// public void setResult(T mResult) {
// this.result = mResult;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
//
// public Object getObj() {
// return obj;
// }
//
// public void setObj(Object obj) {
// this.obj = obj;
// }
//
// public <V> V assertGetObj() {
// return (V) getObj();
// }
//
// public boolean isCache() {
// return isCache;
// }
//
// public void setCache(boolean cache) {
// isCache = cache;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("ok: ").append(ok).append("\n");
// sb.append("message: ").append(message).append("\n");
// sb.append("obj: ").append(obj).append("\n");
// sb.append("result: ").append(result).append("\n");
// sb.append("code: ").append(code).append("\n");
// sb.append("is_cache: ").append(isCache);
//
// return sb.toString();
// }
// }
// Path: glin/src/main/java/org/loader/glin/cache/ICacheProvider.java
import org.loader.glin.RawResult;
import org.loader.glin.Result;
package org.loader.glin.cache;
public interface ICacheProvider {
/**
* get cache by key of {@link #getKey(String, String)}
* @param key key
* @param klass type of data struct, see also {@link org.loader.glin.helper.Helper}
* @param isList is result a List
* @return cache data
*/
<T> Result<T> get(String key, Class<T> klass, boolean isList);
/**
* cache data
* @param key see {@link #getKey(String, String)}
* @param netResult the origin result
* @param result parsed result
*/ | <T> void put(String key, RawResult netResult, Result<T> result); |
qibin0506/Glin | glinsample/src/main/java/org/loader/glinsample/chan/CheckEnvChanNode.java | // Path: glin/src/main/java/org/loader/glin/Context.java
// public class Context {
// private Call<?> call;
// private Result<?> result;
// private RawResult rawResult;
//
// public Context() {}
//
// public Context(Call<?> call) {
// this.call = call;
// }
//
// public Call<?> getCall() {
// return call;
// }
//
// public void setCall(Call<?> call) {
// this.call = call;
// }
//
// public Result<?> getResult() {
// return result;
// }
//
// public void setResult(Result<?> result) {
// this.result = result;
// }
//
// public RawResult getRawResult() {
// return rawResult;
// }
//
// public void setRawResult(RawResult rawResult) {
// this.rawResult = rawResult;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/chan/ChanNode.java
// public abstract class ChanNode {
// private ChanNode mNext;
// private Context mContext;
//
// private boolean beforeCall;
//
// public final void beforeCall(boolean invoke) {
// beforeCall = invoke;
// }
//
// public final boolean isBeforeCall() {
// return beforeCall;
// }
//
// public final void exec(Context ctx) {
// mContext = ctx;
// run(ctx);
// }
//
// public final ChanNode nextChanNode() {
// return mNext;
// }
//
// public final void nextChanNode(ChanNode chanNode) {
// mNext = chanNode;
// }
//
// protected final void next() {
// if (mNext != null) {
// mNext.exec(mContext);
// return;
// }
//
// if (beforeCall) { mContext.getCall().exec();}
// }
//
// protected final void cancel() {
// cancel(Call.DEF_HTTP_CODE_CHAN_CANCELED);
// }
//
// protected final void cancel(int code) {
// cancel(code, Call.DEF_MSG_CHAN_CANCELED);
// }
//
// protected final void cancel(int code, String msg) {
// mNext = null;
// if (beforeCall) {
// mContext.getCall().cancel(code, msg);
// }
// }
//
// public abstract void run(Context ctx);
// }
| import android.util.Log;
import org.loader.glin.Context;
import org.loader.glin.chan.ChanNode; | package org.loader.glinsample.chan;
public class CheckEnvChanNode extends ChanNode {
@Override | // Path: glin/src/main/java/org/loader/glin/Context.java
// public class Context {
// private Call<?> call;
// private Result<?> result;
// private RawResult rawResult;
//
// public Context() {}
//
// public Context(Call<?> call) {
// this.call = call;
// }
//
// public Call<?> getCall() {
// return call;
// }
//
// public void setCall(Call<?> call) {
// this.call = call;
// }
//
// public Result<?> getResult() {
// return result;
// }
//
// public void setResult(Result<?> result) {
// this.result = result;
// }
//
// public RawResult getRawResult() {
// return rawResult;
// }
//
// public void setRawResult(RawResult rawResult) {
// this.rawResult = rawResult;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/chan/ChanNode.java
// public abstract class ChanNode {
// private ChanNode mNext;
// private Context mContext;
//
// private boolean beforeCall;
//
// public final void beforeCall(boolean invoke) {
// beforeCall = invoke;
// }
//
// public final boolean isBeforeCall() {
// return beforeCall;
// }
//
// public final void exec(Context ctx) {
// mContext = ctx;
// run(ctx);
// }
//
// public final ChanNode nextChanNode() {
// return mNext;
// }
//
// public final void nextChanNode(ChanNode chanNode) {
// mNext = chanNode;
// }
//
// protected final void next() {
// if (mNext != null) {
// mNext.exec(mContext);
// return;
// }
//
// if (beforeCall) { mContext.getCall().exec();}
// }
//
// protected final void cancel() {
// cancel(Call.DEF_HTTP_CODE_CHAN_CANCELED);
// }
//
// protected final void cancel(int code) {
// cancel(code, Call.DEF_MSG_CHAN_CANCELED);
// }
//
// protected final void cancel(int code, String msg) {
// mNext = null;
// if (beforeCall) {
// mContext.getCall().cancel(code, msg);
// }
// }
//
// public abstract void run(Context ctx);
// }
// Path: glinsample/src/main/java/org/loader/glinsample/chan/CheckEnvChanNode.java
import android.util.Log;
import org.loader.glin.Context;
import org.loader.glin.chan.ChanNode;
package org.loader.glinsample.chan;
public class CheckEnvChanNode extends ChanNode {
@Override | public void run(Context ctx) { |
qibin0506/Glin | glin/src/main/java/org/loader/glin/chan/LogChanNode.java | // Path: glin/src/main/java/org/loader/glin/Context.java
// public class Context {
// private Call<?> call;
// private Result<?> result;
// private RawResult rawResult;
//
// public Context() {}
//
// public Context(Call<?> call) {
// this.call = call;
// }
//
// public Call<?> getCall() {
// return call;
// }
//
// public void setCall(Call<?> call) {
// this.call = call;
// }
//
// public Result<?> getResult() {
// return result;
// }
//
// public void setResult(Result<?> result) {
// this.result = result;
// }
//
// public RawResult getRawResult() {
// return rawResult;
// }
//
// public void setRawResult(RawResult rawResult) {
// this.rawResult = rawResult;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/helper/LogHelper.java
// public class LogHelper {
// private boolean isDebugMode;
// private LogPrinter mLogPrinter;
// private StringBuilder mLogAppender;
//
// public static LogHelper get(boolean debug, LogPrinter logPrinter) {
// LogHelper helper = new LogHelper(logPrinter);
// helper.isDebugMode(debug);
// return helper;
// }
//
// private LogHelper(LogPrinter logPrinter) {
// mLogPrinter = logPrinter;
// }
//
// public void isDebugMode(boolean debug) {
// isDebugMode = debug;
// }
//
// public boolean isDebugMode() {
// return isDebugMode;
// }
//
// public StringBuilder getLogAppender() {
// if (mLogAppender == null) {
// mLogAppender = new StringBuilder();
// }
// return mLogAppender;
// }
//
// public void print() {
// if (!isDebugMode || mLogAppender == null || mLogAppender.length() == 0) { return;}
// print(mLogAppender.toString());
// }
//
// public void print(String content) {
// if (!isDebugMode) { return;}
//
// mLogPrinter.print("Glin", "*******************--BEGIN--*******************");
// mLogPrinter.print("Glin", content);
// mLogPrinter.print("Glin", "********************--END--********************");
// }
//
// public interface LogPrinter {
// void print(String tag, String content);
// }
// }
| import org.loader.glin.Context;
import org.loader.glin.helper.LogHelper;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | package org.loader.glin.chan;
/**
* Created by qibin on 2016/7/13.
*/
public class LogChanNode extends ChanNode implements Cloneable {
private boolean isDebug; | // Path: glin/src/main/java/org/loader/glin/Context.java
// public class Context {
// private Call<?> call;
// private Result<?> result;
// private RawResult rawResult;
//
// public Context() {}
//
// public Context(Call<?> call) {
// this.call = call;
// }
//
// public Call<?> getCall() {
// return call;
// }
//
// public void setCall(Call<?> call) {
// this.call = call;
// }
//
// public Result<?> getResult() {
// return result;
// }
//
// public void setResult(Result<?> result) {
// this.result = result;
// }
//
// public RawResult getRawResult() {
// return rawResult;
// }
//
// public void setRawResult(RawResult rawResult) {
// this.rawResult = rawResult;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/helper/LogHelper.java
// public class LogHelper {
// private boolean isDebugMode;
// private LogPrinter mLogPrinter;
// private StringBuilder mLogAppender;
//
// public static LogHelper get(boolean debug, LogPrinter logPrinter) {
// LogHelper helper = new LogHelper(logPrinter);
// helper.isDebugMode(debug);
// return helper;
// }
//
// private LogHelper(LogPrinter logPrinter) {
// mLogPrinter = logPrinter;
// }
//
// public void isDebugMode(boolean debug) {
// isDebugMode = debug;
// }
//
// public boolean isDebugMode() {
// return isDebugMode;
// }
//
// public StringBuilder getLogAppender() {
// if (mLogAppender == null) {
// mLogAppender = new StringBuilder();
// }
// return mLogAppender;
// }
//
// public void print() {
// if (!isDebugMode || mLogAppender == null || mLogAppender.length() == 0) { return;}
// print(mLogAppender.toString());
// }
//
// public void print(String content) {
// if (!isDebugMode) { return;}
//
// mLogPrinter.print("Glin", "*******************--BEGIN--*******************");
// mLogPrinter.print("Glin", content);
// mLogPrinter.print("Glin", "********************--END--********************");
// }
//
// public interface LogPrinter {
// void print(String tag, String content);
// }
// }
// Path: glin/src/main/java/org/loader/glin/chan/LogChanNode.java
import org.loader.glin.Context;
import org.loader.glin.helper.LogHelper;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
package org.loader.glin.chan;
/**
* Created by qibin on 2016/7/13.
*/
public class LogChanNode extends ChanNode implements Cloneable {
private boolean isDebug; | private LogHelper.LogPrinter mLogPrinter; |
qibin0506/Glin | glin/src/main/java/org/loader/glin/chan/LogChanNode.java | // Path: glin/src/main/java/org/loader/glin/Context.java
// public class Context {
// private Call<?> call;
// private Result<?> result;
// private RawResult rawResult;
//
// public Context() {}
//
// public Context(Call<?> call) {
// this.call = call;
// }
//
// public Call<?> getCall() {
// return call;
// }
//
// public void setCall(Call<?> call) {
// this.call = call;
// }
//
// public Result<?> getResult() {
// return result;
// }
//
// public void setResult(Result<?> result) {
// this.result = result;
// }
//
// public RawResult getRawResult() {
// return rawResult;
// }
//
// public void setRawResult(RawResult rawResult) {
// this.rawResult = rawResult;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/helper/LogHelper.java
// public class LogHelper {
// private boolean isDebugMode;
// private LogPrinter mLogPrinter;
// private StringBuilder mLogAppender;
//
// public static LogHelper get(boolean debug, LogPrinter logPrinter) {
// LogHelper helper = new LogHelper(logPrinter);
// helper.isDebugMode(debug);
// return helper;
// }
//
// private LogHelper(LogPrinter logPrinter) {
// mLogPrinter = logPrinter;
// }
//
// public void isDebugMode(boolean debug) {
// isDebugMode = debug;
// }
//
// public boolean isDebugMode() {
// return isDebugMode;
// }
//
// public StringBuilder getLogAppender() {
// if (mLogAppender == null) {
// mLogAppender = new StringBuilder();
// }
// return mLogAppender;
// }
//
// public void print() {
// if (!isDebugMode || mLogAppender == null || mLogAppender.length() == 0) { return;}
// print(mLogAppender.toString());
// }
//
// public void print(String content) {
// if (!isDebugMode) { return;}
//
// mLogPrinter.print("Glin", "*******************--BEGIN--*******************");
// mLogPrinter.print("Glin", content);
// mLogPrinter.print("Glin", "********************--END--********************");
// }
//
// public interface LogPrinter {
// void print(String tag, String content);
// }
// }
| import org.loader.glin.Context;
import org.loader.glin.helper.LogHelper;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | package org.loader.glin.chan;
/**
* Created by qibin on 2016/7/13.
*/
public class LogChanNode extends ChanNode implements Cloneable {
private boolean isDebug;
private LogHelper.LogPrinter mLogPrinter;
public LogChanNode(boolean debug, LogHelper.LogPrinter printer) {
isDebug = debug;
mLogPrinter = printer;
}
@Override | // Path: glin/src/main/java/org/loader/glin/Context.java
// public class Context {
// private Call<?> call;
// private Result<?> result;
// private RawResult rawResult;
//
// public Context() {}
//
// public Context(Call<?> call) {
// this.call = call;
// }
//
// public Call<?> getCall() {
// return call;
// }
//
// public void setCall(Call<?> call) {
// this.call = call;
// }
//
// public Result<?> getResult() {
// return result;
// }
//
// public void setResult(Result<?> result) {
// this.result = result;
// }
//
// public RawResult getRawResult() {
// return rawResult;
// }
//
// public void setRawResult(RawResult rawResult) {
// this.rawResult = rawResult;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/helper/LogHelper.java
// public class LogHelper {
// private boolean isDebugMode;
// private LogPrinter mLogPrinter;
// private StringBuilder mLogAppender;
//
// public static LogHelper get(boolean debug, LogPrinter logPrinter) {
// LogHelper helper = new LogHelper(logPrinter);
// helper.isDebugMode(debug);
// return helper;
// }
//
// private LogHelper(LogPrinter logPrinter) {
// mLogPrinter = logPrinter;
// }
//
// public void isDebugMode(boolean debug) {
// isDebugMode = debug;
// }
//
// public boolean isDebugMode() {
// return isDebugMode;
// }
//
// public StringBuilder getLogAppender() {
// if (mLogAppender == null) {
// mLogAppender = new StringBuilder();
// }
// return mLogAppender;
// }
//
// public void print() {
// if (!isDebugMode || mLogAppender == null || mLogAppender.length() == 0) { return;}
// print(mLogAppender.toString());
// }
//
// public void print(String content) {
// if (!isDebugMode) { return;}
//
// mLogPrinter.print("Glin", "*******************--BEGIN--*******************");
// mLogPrinter.print("Glin", content);
// mLogPrinter.print("Glin", "********************--END--********************");
// }
//
// public interface LogPrinter {
// void print(String tag, String content);
// }
// }
// Path: glin/src/main/java/org/loader/glin/chan/LogChanNode.java
import org.loader.glin.Context;
import org.loader.glin.helper.LogHelper;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
package org.loader.glin.chan;
/**
* Created by qibin on 2016/7/13.
*/
public class LogChanNode extends ChanNode implements Cloneable {
private boolean isDebug;
private LogHelper.LogPrinter mLogPrinter;
public LogChanNode(boolean debug, LogHelper.LogPrinter printer) {
isDebug = debug;
mLogPrinter = printer;
}
@Override | public void run(Context ctx) { |
qibin0506/Glin | glin/src/main/java/org/loader/glin/client/IClient.java | // Path: glin/src/main/java/org/loader/glin/cache/ICacheProvider.java
// public interface ICacheProvider {
// /**
// * get cache by key of {@link #getKey(String, String)}
// * @param key key
// * @param klass type of data struct, see also {@link org.loader.glin.helper.Helper}
// * @param isList is result a List
// * @return cache data
// */
// <T> Result<T> get(String key, Class<T> klass, boolean isList);
//
// /**
// * cache data
// * @param key see {@link #getKey(String, String)}
// * @param netResult the origin result
// * @param result parsed result
// */
// <T> void put(String key, RawResult netResult, Result<T> result);
//
// /**
// * provide the key
// * @param url the request url
// * @param params the request params, maybe key1=value1&key2=value2 while your request is POST, maybe null while your request is GET, maybe json string while your request is POST Json
// * @return
// */
// String getKey(String url, String params);
// }
//
// Path: glin/src/main/java/org/loader/glin/factory/ParserFactory.java
// public interface ParserFactory {
// Parser getParser();
// Parser getListParser();
// }
//
// Path: glin/src/main/java/org/loader/glin/interceptor/IResultInterceptor.java
// public interface IResultInterceptor {
// /**
// * 是否拦截结果
// * @param result
// * @return true callback不会执行
// */
// boolean intercept(Result<?> result);
// }
| import org.loader.glin.cache.ICacheProvider;
import org.loader.glin.factory.ParserFactory;
import org.loader.glin.interceptor.IResultInterceptor;
import java.util.LinkedHashMap; | package org.loader.glin.client;
/**
* Created by qibin on 2016/7/13.
*/
public interface IClient extends IRequest {
void cancel(final Object tag);
| // Path: glin/src/main/java/org/loader/glin/cache/ICacheProvider.java
// public interface ICacheProvider {
// /**
// * get cache by key of {@link #getKey(String, String)}
// * @param key key
// * @param klass type of data struct, see also {@link org.loader.glin.helper.Helper}
// * @param isList is result a List
// * @return cache data
// */
// <T> Result<T> get(String key, Class<T> klass, boolean isList);
//
// /**
// * cache data
// * @param key see {@link #getKey(String, String)}
// * @param netResult the origin result
// * @param result parsed result
// */
// <T> void put(String key, RawResult netResult, Result<T> result);
//
// /**
// * provide the key
// * @param url the request url
// * @param params the request params, maybe key1=value1&key2=value2 while your request is POST, maybe null while your request is GET, maybe json string while your request is POST Json
// * @return
// */
// String getKey(String url, String params);
// }
//
// Path: glin/src/main/java/org/loader/glin/factory/ParserFactory.java
// public interface ParserFactory {
// Parser getParser();
// Parser getListParser();
// }
//
// Path: glin/src/main/java/org/loader/glin/interceptor/IResultInterceptor.java
// public interface IResultInterceptor {
// /**
// * 是否拦截结果
// * @param result
// * @return true callback不会执行
// */
// boolean intercept(Result<?> result);
// }
// Path: glin/src/main/java/org/loader/glin/client/IClient.java
import org.loader.glin.cache.ICacheProvider;
import org.loader.glin.factory.ParserFactory;
import org.loader.glin.interceptor.IResultInterceptor;
import java.util.LinkedHashMap;
package org.loader.glin.client;
/**
* Created by qibin on 2016/7/13.
*/
public interface IClient extends IRequest {
void cancel(final Object tag);
| void parserFactory(ParserFactory factory); |
qibin0506/Glin | glin/src/main/java/org/loader/glin/client/IClient.java | // Path: glin/src/main/java/org/loader/glin/cache/ICacheProvider.java
// public interface ICacheProvider {
// /**
// * get cache by key of {@link #getKey(String, String)}
// * @param key key
// * @param klass type of data struct, see also {@link org.loader.glin.helper.Helper}
// * @param isList is result a List
// * @return cache data
// */
// <T> Result<T> get(String key, Class<T> klass, boolean isList);
//
// /**
// * cache data
// * @param key see {@link #getKey(String, String)}
// * @param netResult the origin result
// * @param result parsed result
// */
// <T> void put(String key, RawResult netResult, Result<T> result);
//
// /**
// * provide the key
// * @param url the request url
// * @param params the request params, maybe key1=value1&key2=value2 while your request is POST, maybe null while your request is GET, maybe json string while your request is POST Json
// * @return
// */
// String getKey(String url, String params);
// }
//
// Path: glin/src/main/java/org/loader/glin/factory/ParserFactory.java
// public interface ParserFactory {
// Parser getParser();
// Parser getListParser();
// }
//
// Path: glin/src/main/java/org/loader/glin/interceptor/IResultInterceptor.java
// public interface IResultInterceptor {
// /**
// * 是否拦截结果
// * @param result
// * @return true callback不会执行
// */
// boolean intercept(Result<?> result);
// }
| import org.loader.glin.cache.ICacheProvider;
import org.loader.glin.factory.ParserFactory;
import org.loader.glin.interceptor.IResultInterceptor;
import java.util.LinkedHashMap; | package org.loader.glin.client;
/**
* Created by qibin on 2016/7/13.
*/
public interface IClient extends IRequest {
void cancel(final Object tag);
void parserFactory(ParserFactory factory);
LinkedHashMap<String, String> headers();
| // Path: glin/src/main/java/org/loader/glin/cache/ICacheProvider.java
// public interface ICacheProvider {
// /**
// * get cache by key of {@link #getKey(String, String)}
// * @param key key
// * @param klass type of data struct, see also {@link org.loader.glin.helper.Helper}
// * @param isList is result a List
// * @return cache data
// */
// <T> Result<T> get(String key, Class<T> klass, boolean isList);
//
// /**
// * cache data
// * @param key see {@link #getKey(String, String)}
// * @param netResult the origin result
// * @param result parsed result
// */
// <T> void put(String key, RawResult netResult, Result<T> result);
//
// /**
// * provide the key
// * @param url the request url
// * @param params the request params, maybe key1=value1&key2=value2 while your request is POST, maybe null while your request is GET, maybe json string while your request is POST Json
// * @return
// */
// String getKey(String url, String params);
// }
//
// Path: glin/src/main/java/org/loader/glin/factory/ParserFactory.java
// public interface ParserFactory {
// Parser getParser();
// Parser getListParser();
// }
//
// Path: glin/src/main/java/org/loader/glin/interceptor/IResultInterceptor.java
// public interface IResultInterceptor {
// /**
// * 是否拦截结果
// * @param result
// * @return true callback不会执行
// */
// boolean intercept(Result<?> result);
// }
// Path: glin/src/main/java/org/loader/glin/client/IClient.java
import org.loader.glin.cache.ICacheProvider;
import org.loader.glin.factory.ParserFactory;
import org.loader.glin.interceptor.IResultInterceptor;
import java.util.LinkedHashMap;
package org.loader.glin.client;
/**
* Created by qibin on 2016/7/13.
*/
public interface IClient extends IRequest {
void cancel(final Object tag);
void parserFactory(ParserFactory factory);
LinkedHashMap<String, String> headers();
| void resultInterceptor(IResultInterceptor interceptor); |
qibin0506/Glin | glin/src/main/java/org/loader/glin/client/IClient.java | // Path: glin/src/main/java/org/loader/glin/cache/ICacheProvider.java
// public interface ICacheProvider {
// /**
// * get cache by key of {@link #getKey(String, String)}
// * @param key key
// * @param klass type of data struct, see also {@link org.loader.glin.helper.Helper}
// * @param isList is result a List
// * @return cache data
// */
// <T> Result<T> get(String key, Class<T> klass, boolean isList);
//
// /**
// * cache data
// * @param key see {@link #getKey(String, String)}
// * @param netResult the origin result
// * @param result parsed result
// */
// <T> void put(String key, RawResult netResult, Result<T> result);
//
// /**
// * provide the key
// * @param url the request url
// * @param params the request params, maybe key1=value1&key2=value2 while your request is POST, maybe null while your request is GET, maybe json string while your request is POST Json
// * @return
// */
// String getKey(String url, String params);
// }
//
// Path: glin/src/main/java/org/loader/glin/factory/ParserFactory.java
// public interface ParserFactory {
// Parser getParser();
// Parser getListParser();
// }
//
// Path: glin/src/main/java/org/loader/glin/interceptor/IResultInterceptor.java
// public interface IResultInterceptor {
// /**
// * 是否拦截结果
// * @param result
// * @return true callback不会执行
// */
// boolean intercept(Result<?> result);
// }
| import org.loader.glin.cache.ICacheProvider;
import org.loader.glin.factory.ParserFactory;
import org.loader.glin.interceptor.IResultInterceptor;
import java.util.LinkedHashMap; | package org.loader.glin.client;
/**
* Created by qibin on 2016/7/13.
*/
public interface IClient extends IRequest {
void cancel(final Object tag);
void parserFactory(ParserFactory factory);
LinkedHashMap<String, String> headers();
void resultInterceptor(IResultInterceptor interceptor);
| // Path: glin/src/main/java/org/loader/glin/cache/ICacheProvider.java
// public interface ICacheProvider {
// /**
// * get cache by key of {@link #getKey(String, String)}
// * @param key key
// * @param klass type of data struct, see also {@link org.loader.glin.helper.Helper}
// * @param isList is result a List
// * @return cache data
// */
// <T> Result<T> get(String key, Class<T> klass, boolean isList);
//
// /**
// * cache data
// * @param key see {@link #getKey(String, String)}
// * @param netResult the origin result
// * @param result parsed result
// */
// <T> void put(String key, RawResult netResult, Result<T> result);
//
// /**
// * provide the key
// * @param url the request url
// * @param params the request params, maybe key1=value1&key2=value2 while your request is POST, maybe null while your request is GET, maybe json string while your request is POST Json
// * @return
// */
// String getKey(String url, String params);
// }
//
// Path: glin/src/main/java/org/loader/glin/factory/ParserFactory.java
// public interface ParserFactory {
// Parser getParser();
// Parser getListParser();
// }
//
// Path: glin/src/main/java/org/loader/glin/interceptor/IResultInterceptor.java
// public interface IResultInterceptor {
// /**
// * 是否拦截结果
// * @param result
// * @return true callback不会执行
// */
// boolean intercept(Result<?> result);
// }
// Path: glin/src/main/java/org/loader/glin/client/IClient.java
import org.loader.glin.cache.ICacheProvider;
import org.loader.glin.factory.ParserFactory;
import org.loader.glin.interceptor.IResultInterceptor;
import java.util.LinkedHashMap;
package org.loader.glin.client;
/**
* Created by qibin on 2016/7/13.
*/
public interface IClient extends IRequest {
void cancel(final Object tag);
void parserFactory(ParserFactory factory);
LinkedHashMap<String, String> headers();
void resultInterceptor(IResultInterceptor interceptor);
| void cacheProvider(ICacheProvider provider); |
qibin0506/Glin | glin/src/main/java/org/loader/glin/call/PostCall.java | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/Params.java
// public class Params {
//
// public static final String DEFAULT_JSON_KEY = "json";
//
// private LinkedHashMap<String, String> mParams;
// private LinkedHashMap<String, File> mFiles;
//
// public Params() {
// mParams = new LinkedHashMap<>();
// mFiles = new LinkedHashMap<>();
// }
//
// public Params(String key, Object value) {
// this();
// add(key, value);
// }
//
// public Params add(String key, Object value) {
// if (key == null) { return this;}
// if (value == null) { mParams.put(key, null);}
// else if (value instanceof File) { mFiles.put(key, (File) value);}
// else { mParams.put(key, value.toString());}
// return this;
// }
//
// public LinkedHashMap<String, String> get() {
// return mParams;
// }
//
// public String getParams(String key) {
// return mParams.get(key);
// }
//
// public File getFile(String key) {
// return mFiles.get(key);
// }
//
// public LinkedHashMap<String, File> files() {
// return mFiles;
// }
//
// public void remove(String key) {
// if (mParams.containsKey(key)) { mParams.remove(key);}
// if (mFiles.containsKey(key)) { mFiles.remove(key);}
// }
//
// public String encode() {
// String query = null;
// for (Map.Entry<String, String> entry : mParams.entrySet()) {
// if (query == null) { query = entry.getKey() + "=" + entry.getValue();}
// else { query += "&" + entry.getKey() + "=" + entry.getValue();}
// }
//
// return query;
// }
//
// public Iterator<String> iterator() {
// return mParams.keySet().iterator();
// }
//
// public Iterator<String> fileIterator() {
// return mFiles.keySet().iterator();
// }
//
// public boolean isEmpty() {
// return mParams.isEmpty() && mFiles.isEmpty();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/client/IClient.java
// public interface IClient extends IRequest {
//
// void cancel(final Object tag);
//
// void parserFactory(ParserFactory factory);
//
// LinkedHashMap<String, String> headers();
//
// void resultInterceptor(IResultInterceptor interceptor);
//
// void cacheProvider(ICacheProvider provider);
//
// void timeout(long ms);
// }
| import org.loader.glin.Callback;
import org.loader.glin.Params;
import org.loader.glin.client.IClient; | package org.loader.glin.call;
/**
* Created by qibin on 2016/7/13.
*/
public class PostCall<T> extends Call<T> {
public PostCall(IClient client, String url, | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/Params.java
// public class Params {
//
// public static final String DEFAULT_JSON_KEY = "json";
//
// private LinkedHashMap<String, String> mParams;
// private LinkedHashMap<String, File> mFiles;
//
// public Params() {
// mParams = new LinkedHashMap<>();
// mFiles = new LinkedHashMap<>();
// }
//
// public Params(String key, Object value) {
// this();
// add(key, value);
// }
//
// public Params add(String key, Object value) {
// if (key == null) { return this;}
// if (value == null) { mParams.put(key, null);}
// else if (value instanceof File) { mFiles.put(key, (File) value);}
// else { mParams.put(key, value.toString());}
// return this;
// }
//
// public LinkedHashMap<String, String> get() {
// return mParams;
// }
//
// public String getParams(String key) {
// return mParams.get(key);
// }
//
// public File getFile(String key) {
// return mFiles.get(key);
// }
//
// public LinkedHashMap<String, File> files() {
// return mFiles;
// }
//
// public void remove(String key) {
// if (mParams.containsKey(key)) { mParams.remove(key);}
// if (mFiles.containsKey(key)) { mFiles.remove(key);}
// }
//
// public String encode() {
// String query = null;
// for (Map.Entry<String, String> entry : mParams.entrySet()) {
// if (query == null) { query = entry.getKey() + "=" + entry.getValue();}
// else { query += "&" + entry.getKey() + "=" + entry.getValue();}
// }
//
// return query;
// }
//
// public Iterator<String> iterator() {
// return mParams.keySet().iterator();
// }
//
// public Iterator<String> fileIterator() {
// return mFiles.keySet().iterator();
// }
//
// public boolean isEmpty() {
// return mParams.isEmpty() && mFiles.isEmpty();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/client/IClient.java
// public interface IClient extends IRequest {
//
// void cancel(final Object tag);
//
// void parserFactory(ParserFactory factory);
//
// LinkedHashMap<String, String> headers();
//
// void resultInterceptor(IResultInterceptor interceptor);
//
// void cacheProvider(ICacheProvider provider);
//
// void timeout(long ms);
// }
// Path: glin/src/main/java/org/loader/glin/call/PostCall.java
import org.loader.glin.Callback;
import org.loader.glin.Params;
import org.loader.glin.client.IClient;
package org.loader.glin.call;
/**
* Created by qibin on 2016/7/13.
*/
public class PostCall<T> extends Call<T> {
public PostCall(IClient client, String url, | Params params, Object tag, |
qibin0506/Glin | glin/src/main/java/org/loader/glin/call/PostCall.java | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/Params.java
// public class Params {
//
// public static final String DEFAULT_JSON_KEY = "json";
//
// private LinkedHashMap<String, String> mParams;
// private LinkedHashMap<String, File> mFiles;
//
// public Params() {
// mParams = new LinkedHashMap<>();
// mFiles = new LinkedHashMap<>();
// }
//
// public Params(String key, Object value) {
// this();
// add(key, value);
// }
//
// public Params add(String key, Object value) {
// if (key == null) { return this;}
// if (value == null) { mParams.put(key, null);}
// else if (value instanceof File) { mFiles.put(key, (File) value);}
// else { mParams.put(key, value.toString());}
// return this;
// }
//
// public LinkedHashMap<String, String> get() {
// return mParams;
// }
//
// public String getParams(String key) {
// return mParams.get(key);
// }
//
// public File getFile(String key) {
// return mFiles.get(key);
// }
//
// public LinkedHashMap<String, File> files() {
// return mFiles;
// }
//
// public void remove(String key) {
// if (mParams.containsKey(key)) { mParams.remove(key);}
// if (mFiles.containsKey(key)) { mFiles.remove(key);}
// }
//
// public String encode() {
// String query = null;
// for (Map.Entry<String, String> entry : mParams.entrySet()) {
// if (query == null) { query = entry.getKey() + "=" + entry.getValue();}
// else { query += "&" + entry.getKey() + "=" + entry.getValue();}
// }
//
// return query;
// }
//
// public Iterator<String> iterator() {
// return mParams.keySet().iterator();
// }
//
// public Iterator<String> fileIterator() {
// return mFiles.keySet().iterator();
// }
//
// public boolean isEmpty() {
// return mParams.isEmpty() && mFiles.isEmpty();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/client/IClient.java
// public interface IClient extends IRequest {
//
// void cancel(final Object tag);
//
// void parserFactory(ParserFactory factory);
//
// LinkedHashMap<String, String> headers();
//
// void resultInterceptor(IResultInterceptor interceptor);
//
// void cacheProvider(ICacheProvider provider);
//
// void timeout(long ms);
// }
| import org.loader.glin.Callback;
import org.loader.glin.Params;
import org.loader.glin.client.IClient; | package org.loader.glin.call;
/**
* Created by qibin on 2016/7/13.
*/
public class PostCall<T> extends Call<T> {
public PostCall(IClient client, String url,
Params params, Object tag,
boolean cache) {
super(client, url, params, tag, cache);
}
@Override | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/Params.java
// public class Params {
//
// public static final String DEFAULT_JSON_KEY = "json";
//
// private LinkedHashMap<String, String> mParams;
// private LinkedHashMap<String, File> mFiles;
//
// public Params() {
// mParams = new LinkedHashMap<>();
// mFiles = new LinkedHashMap<>();
// }
//
// public Params(String key, Object value) {
// this();
// add(key, value);
// }
//
// public Params add(String key, Object value) {
// if (key == null) { return this;}
// if (value == null) { mParams.put(key, null);}
// else if (value instanceof File) { mFiles.put(key, (File) value);}
// else { mParams.put(key, value.toString());}
// return this;
// }
//
// public LinkedHashMap<String, String> get() {
// return mParams;
// }
//
// public String getParams(String key) {
// return mParams.get(key);
// }
//
// public File getFile(String key) {
// return mFiles.get(key);
// }
//
// public LinkedHashMap<String, File> files() {
// return mFiles;
// }
//
// public void remove(String key) {
// if (mParams.containsKey(key)) { mParams.remove(key);}
// if (mFiles.containsKey(key)) { mFiles.remove(key);}
// }
//
// public String encode() {
// String query = null;
// for (Map.Entry<String, String> entry : mParams.entrySet()) {
// if (query == null) { query = entry.getKey() + "=" + entry.getValue();}
// else { query += "&" + entry.getKey() + "=" + entry.getValue();}
// }
//
// return query;
// }
//
// public Iterator<String> iterator() {
// return mParams.keySet().iterator();
// }
//
// public Iterator<String> fileIterator() {
// return mFiles.keySet().iterator();
// }
//
// public boolean isEmpty() {
// return mParams.isEmpty() && mFiles.isEmpty();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/client/IClient.java
// public interface IClient extends IRequest {
//
// void cancel(final Object tag);
//
// void parserFactory(ParserFactory factory);
//
// LinkedHashMap<String, String> headers();
//
// void resultInterceptor(IResultInterceptor interceptor);
//
// void cacheProvider(ICacheProvider provider);
//
// void timeout(long ms);
// }
// Path: glin/src/main/java/org/loader/glin/call/PostCall.java
import org.loader.glin.Callback;
import org.loader.glin.Params;
import org.loader.glin.client.IClient;
package org.loader.glin.call;
/**
* Created by qibin on 2016/7/13.
*/
public class PostCall<T> extends Call<T> {
public PostCall(IClient client, String url,
Params params, Object tag,
boolean cache) {
super(client, url, params, tag, cache);
}
@Override | public void exec(final Callback<T> callback) { |
qibin0506/Glin | glin/src/main/java/org/loader/glin/Callback.java | // Path: glin/src/main/java/org/loader/glin/chan/ChanNode.java
// public abstract class ChanNode {
// private ChanNode mNext;
// private Context mContext;
//
// private boolean beforeCall;
//
// public final void beforeCall(boolean invoke) {
// beforeCall = invoke;
// }
//
// public final boolean isBeforeCall() {
// return beforeCall;
// }
//
// public final void exec(Context ctx) {
// mContext = ctx;
// run(ctx);
// }
//
// public final ChanNode nextChanNode() {
// return mNext;
// }
//
// public final void nextChanNode(ChanNode chanNode) {
// mNext = chanNode;
// }
//
// protected final void next() {
// if (mNext != null) {
// mNext.exec(mContext);
// return;
// }
//
// if (beforeCall) { mContext.getCall().exec();}
// }
//
// protected final void cancel() {
// cancel(Call.DEF_HTTP_CODE_CHAN_CANCELED);
// }
//
// protected final void cancel(int code) {
// cancel(code, Call.DEF_MSG_CHAN_CANCELED);
// }
//
// protected final void cancel(int code, String msg) {
// mNext = null;
// if (beforeCall) {
// mContext.getCall().cancel(code, msg);
// }
// }
//
// public abstract void run(Context ctx);
// }
| import org.loader.glin.chan.ChanNode; | package org.loader.glin;
/**
* Created by qibin on 2016/7/13.
*/
public abstract class Callback<T> {
private Context mContext; | // Path: glin/src/main/java/org/loader/glin/chan/ChanNode.java
// public abstract class ChanNode {
// private ChanNode mNext;
// private Context mContext;
//
// private boolean beforeCall;
//
// public final void beforeCall(boolean invoke) {
// beforeCall = invoke;
// }
//
// public final boolean isBeforeCall() {
// return beforeCall;
// }
//
// public final void exec(Context ctx) {
// mContext = ctx;
// run(ctx);
// }
//
// public final ChanNode nextChanNode() {
// return mNext;
// }
//
// public final void nextChanNode(ChanNode chanNode) {
// mNext = chanNode;
// }
//
// protected final void next() {
// if (mNext != null) {
// mNext.exec(mContext);
// return;
// }
//
// if (beforeCall) { mContext.getCall().exec();}
// }
//
// protected final void cancel() {
// cancel(Call.DEF_HTTP_CODE_CHAN_CANCELED);
// }
//
// protected final void cancel(int code) {
// cancel(code, Call.DEF_MSG_CHAN_CANCELED);
// }
//
// protected final void cancel(int code, String msg) {
// mNext = null;
// if (beforeCall) {
// mContext.getCall().cancel(code, msg);
// }
// }
//
// public abstract void run(Context ctx);
// }
// Path: glin/src/main/java/org/loader/glin/Callback.java
import org.loader.glin.chan.ChanNode;
package org.loader.glin;
/**
* Created by qibin on 2016/7/13.
*/
public abstract class Callback<T> {
private Context mContext; | private ChanNode mAfterChanNode; |
qibin0506/Glin | glinsample/src/main/java/org/loader/glinsample/chan/EndChanNode.java | // Path: glin/src/main/java/org/loader/glin/Context.java
// public class Context {
// private Call<?> call;
// private Result<?> result;
// private RawResult rawResult;
//
// public Context() {}
//
// public Context(Call<?> call) {
// this.call = call;
// }
//
// public Call<?> getCall() {
// return call;
// }
//
// public void setCall(Call<?> call) {
// this.call = call;
// }
//
// public Result<?> getResult() {
// return result;
// }
//
// public void setResult(Result<?> result) {
// this.result = result;
// }
//
// public RawResult getRawResult() {
// return rawResult;
// }
//
// public void setRawResult(RawResult rawResult) {
// this.rawResult = rawResult;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/chan/ChanNode.java
// public abstract class ChanNode {
// private ChanNode mNext;
// private Context mContext;
//
// private boolean beforeCall;
//
// public final void beforeCall(boolean invoke) {
// beforeCall = invoke;
// }
//
// public final boolean isBeforeCall() {
// return beforeCall;
// }
//
// public final void exec(Context ctx) {
// mContext = ctx;
// run(ctx);
// }
//
// public final ChanNode nextChanNode() {
// return mNext;
// }
//
// public final void nextChanNode(ChanNode chanNode) {
// mNext = chanNode;
// }
//
// protected final void next() {
// if (mNext != null) {
// mNext.exec(mContext);
// return;
// }
//
// if (beforeCall) { mContext.getCall().exec();}
// }
//
// protected final void cancel() {
// cancel(Call.DEF_HTTP_CODE_CHAN_CANCELED);
// }
//
// protected final void cancel(int code) {
// cancel(code, Call.DEF_MSG_CHAN_CANCELED);
// }
//
// protected final void cancel(int code, String msg) {
// mNext = null;
// if (beforeCall) {
// mContext.getCall().cancel(code, msg);
// }
// }
//
// public abstract void run(Context ctx);
// }
| import android.util.Log;
import org.loader.glin.Context;
import org.loader.glin.chan.ChanNode; | package org.loader.glinsample.chan;
public class EndChanNode extends ChanNode {
@Override | // Path: glin/src/main/java/org/loader/glin/Context.java
// public class Context {
// private Call<?> call;
// private Result<?> result;
// private RawResult rawResult;
//
// public Context() {}
//
// public Context(Call<?> call) {
// this.call = call;
// }
//
// public Call<?> getCall() {
// return call;
// }
//
// public void setCall(Call<?> call) {
// this.call = call;
// }
//
// public Result<?> getResult() {
// return result;
// }
//
// public void setResult(Result<?> result) {
// this.result = result;
// }
//
// public RawResult getRawResult() {
// return rawResult;
// }
//
// public void setRawResult(RawResult rawResult) {
// this.rawResult = rawResult;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/chan/ChanNode.java
// public abstract class ChanNode {
// private ChanNode mNext;
// private Context mContext;
//
// private boolean beforeCall;
//
// public final void beforeCall(boolean invoke) {
// beforeCall = invoke;
// }
//
// public final boolean isBeforeCall() {
// return beforeCall;
// }
//
// public final void exec(Context ctx) {
// mContext = ctx;
// run(ctx);
// }
//
// public final ChanNode nextChanNode() {
// return mNext;
// }
//
// public final void nextChanNode(ChanNode chanNode) {
// mNext = chanNode;
// }
//
// protected final void next() {
// if (mNext != null) {
// mNext.exec(mContext);
// return;
// }
//
// if (beforeCall) { mContext.getCall().exec();}
// }
//
// protected final void cancel() {
// cancel(Call.DEF_HTTP_CODE_CHAN_CANCELED);
// }
//
// protected final void cancel(int code) {
// cancel(code, Call.DEF_MSG_CHAN_CANCELED);
// }
//
// protected final void cancel(int code, String msg) {
// mNext = null;
// if (beforeCall) {
// mContext.getCall().cancel(code, msg);
// }
// }
//
// public abstract void run(Context ctx);
// }
// Path: glinsample/src/main/java/org/loader/glinsample/chan/EndChanNode.java
import android.util.Log;
import org.loader.glin.Context;
import org.loader.glin.chan.ChanNode;
package org.loader.glinsample.chan;
public class EndChanNode extends ChanNode {
@Override | public void run(Context ctx) { |
qibin0506/Glin | glinsample/src/main/java/org/loader/glinsample/utils/Parsers.java | // Path: glin/src/main/java/org/loader/glin/RawResult.java
// public class RawResult {
// private int statusCode;
// private String message;
// private String response;
//
// public RawResult() {}
//
// public RawResult(int statusCode, String message, String response) {
// this.statusCode = statusCode;
// this.message = message;
// this.response = response;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public void setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/Result.java
// public class Result<T> {
// private boolean ok;
// private String message;
// private T result;
// private int code;
// private Object obj;
// private boolean isCache;
//
// public boolean isOK() {
// return ok;
// }
//
// public void ok(boolean ok) {
// this.ok = ok;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String mMessage) {
// this.message = mMessage;
// }
//
// public T getResult() {
// return result;
// }
//
// public void setResult(T mResult) {
// this.result = mResult;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
//
// public Object getObj() {
// return obj;
// }
//
// public void setObj(Object obj) {
// this.obj = obj;
// }
//
// public <V> V assertGetObj() {
// return (V) getObj();
// }
//
// public boolean isCache() {
// return isCache;
// }
//
// public void setCache(boolean cache) {
// isCache = cache;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("ok: ").append(ok).append("\n");
// sb.append("message: ").append(message).append("\n");
// sb.append("obj: ").append(obj).append("\n");
// sb.append("result: ").append(result).append("\n");
// sb.append("code: ").append(code).append("\n");
// sb.append("is_cache: ").append(isCache);
//
// return sb.toString();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/factory/ParserFactory.java
// public interface ParserFactory {
// Parser getParser();
// Parser getListParser();
// }
//
// Path: glin/src/main/java/org/loader/glin/parser/Parser.java
// public abstract class Parser {
// public String mKey;
//
// public Parser() {
//
// }
//
// public Parser(String key) {
// mKey = key;
// }
//
// /**
// *
// * @param klass the class of data struct
// * @param netResult
// * @param <T>
// * @return
// */
// public abstract <T> Result<T> parse(Class<T> klass, RawResult netResult);
// }
| import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.loader.glin.RawResult;
import org.loader.glin.Result;
import org.loader.glin.factory.ParserFactory;
import org.loader.glin.parser.Parser; | package org.loader.glinsample.utils;
public class Parsers implements ParserFactory {
@Override | // Path: glin/src/main/java/org/loader/glin/RawResult.java
// public class RawResult {
// private int statusCode;
// private String message;
// private String response;
//
// public RawResult() {}
//
// public RawResult(int statusCode, String message, String response) {
// this.statusCode = statusCode;
// this.message = message;
// this.response = response;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public void setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/Result.java
// public class Result<T> {
// private boolean ok;
// private String message;
// private T result;
// private int code;
// private Object obj;
// private boolean isCache;
//
// public boolean isOK() {
// return ok;
// }
//
// public void ok(boolean ok) {
// this.ok = ok;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String mMessage) {
// this.message = mMessage;
// }
//
// public T getResult() {
// return result;
// }
//
// public void setResult(T mResult) {
// this.result = mResult;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
//
// public Object getObj() {
// return obj;
// }
//
// public void setObj(Object obj) {
// this.obj = obj;
// }
//
// public <V> V assertGetObj() {
// return (V) getObj();
// }
//
// public boolean isCache() {
// return isCache;
// }
//
// public void setCache(boolean cache) {
// isCache = cache;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("ok: ").append(ok).append("\n");
// sb.append("message: ").append(message).append("\n");
// sb.append("obj: ").append(obj).append("\n");
// sb.append("result: ").append(result).append("\n");
// sb.append("code: ").append(code).append("\n");
// sb.append("is_cache: ").append(isCache);
//
// return sb.toString();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/factory/ParserFactory.java
// public interface ParserFactory {
// Parser getParser();
// Parser getListParser();
// }
//
// Path: glin/src/main/java/org/loader/glin/parser/Parser.java
// public abstract class Parser {
// public String mKey;
//
// public Parser() {
//
// }
//
// public Parser(String key) {
// mKey = key;
// }
//
// /**
// *
// * @param klass the class of data struct
// * @param netResult
// * @param <T>
// * @return
// */
// public abstract <T> Result<T> parse(Class<T> klass, RawResult netResult);
// }
// Path: glinsample/src/main/java/org/loader/glinsample/utils/Parsers.java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.loader.glin.RawResult;
import org.loader.glin.Result;
import org.loader.glin.factory.ParserFactory;
import org.loader.glin.parser.Parser;
package org.loader.glinsample.utils;
public class Parsers implements ParserFactory {
@Override | public Parser getParser() { |
qibin0506/Glin | glinsample/src/main/java/org/loader/glinsample/utils/Parsers.java | // Path: glin/src/main/java/org/loader/glin/RawResult.java
// public class RawResult {
// private int statusCode;
// private String message;
// private String response;
//
// public RawResult() {}
//
// public RawResult(int statusCode, String message, String response) {
// this.statusCode = statusCode;
// this.message = message;
// this.response = response;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public void setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/Result.java
// public class Result<T> {
// private boolean ok;
// private String message;
// private T result;
// private int code;
// private Object obj;
// private boolean isCache;
//
// public boolean isOK() {
// return ok;
// }
//
// public void ok(boolean ok) {
// this.ok = ok;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String mMessage) {
// this.message = mMessage;
// }
//
// public T getResult() {
// return result;
// }
//
// public void setResult(T mResult) {
// this.result = mResult;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
//
// public Object getObj() {
// return obj;
// }
//
// public void setObj(Object obj) {
// this.obj = obj;
// }
//
// public <V> V assertGetObj() {
// return (V) getObj();
// }
//
// public boolean isCache() {
// return isCache;
// }
//
// public void setCache(boolean cache) {
// isCache = cache;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("ok: ").append(ok).append("\n");
// sb.append("message: ").append(message).append("\n");
// sb.append("obj: ").append(obj).append("\n");
// sb.append("result: ").append(result).append("\n");
// sb.append("code: ").append(code).append("\n");
// sb.append("is_cache: ").append(isCache);
//
// return sb.toString();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/factory/ParserFactory.java
// public interface ParserFactory {
// Parser getParser();
// Parser getListParser();
// }
//
// Path: glin/src/main/java/org/loader/glin/parser/Parser.java
// public abstract class Parser {
// public String mKey;
//
// public Parser() {
//
// }
//
// public Parser(String key) {
// mKey = key;
// }
//
// /**
// *
// * @param klass the class of data struct
// * @param netResult
// * @param <T>
// * @return
// */
// public abstract <T> Result<T> parse(Class<T> klass, RawResult netResult);
// }
| import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.loader.glin.RawResult;
import org.loader.glin.Result;
import org.loader.glin.factory.ParserFactory;
import org.loader.glin.parser.Parser; | package org.loader.glinsample.utils;
public class Parsers implements ParserFactory {
@Override
public Parser getParser() {
return new Parser() {
@Override | // Path: glin/src/main/java/org/loader/glin/RawResult.java
// public class RawResult {
// private int statusCode;
// private String message;
// private String response;
//
// public RawResult() {}
//
// public RawResult(int statusCode, String message, String response) {
// this.statusCode = statusCode;
// this.message = message;
// this.response = response;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public void setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/Result.java
// public class Result<T> {
// private boolean ok;
// private String message;
// private T result;
// private int code;
// private Object obj;
// private boolean isCache;
//
// public boolean isOK() {
// return ok;
// }
//
// public void ok(boolean ok) {
// this.ok = ok;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String mMessage) {
// this.message = mMessage;
// }
//
// public T getResult() {
// return result;
// }
//
// public void setResult(T mResult) {
// this.result = mResult;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
//
// public Object getObj() {
// return obj;
// }
//
// public void setObj(Object obj) {
// this.obj = obj;
// }
//
// public <V> V assertGetObj() {
// return (V) getObj();
// }
//
// public boolean isCache() {
// return isCache;
// }
//
// public void setCache(boolean cache) {
// isCache = cache;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("ok: ").append(ok).append("\n");
// sb.append("message: ").append(message).append("\n");
// sb.append("obj: ").append(obj).append("\n");
// sb.append("result: ").append(result).append("\n");
// sb.append("code: ").append(code).append("\n");
// sb.append("is_cache: ").append(isCache);
//
// return sb.toString();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/factory/ParserFactory.java
// public interface ParserFactory {
// Parser getParser();
// Parser getListParser();
// }
//
// Path: glin/src/main/java/org/loader/glin/parser/Parser.java
// public abstract class Parser {
// public String mKey;
//
// public Parser() {
//
// }
//
// public Parser(String key) {
// mKey = key;
// }
//
// /**
// *
// * @param klass the class of data struct
// * @param netResult
// * @param <T>
// * @return
// */
// public abstract <T> Result<T> parse(Class<T> klass, RawResult netResult);
// }
// Path: glinsample/src/main/java/org/loader/glinsample/utils/Parsers.java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.loader.glin.RawResult;
import org.loader.glin.Result;
import org.loader.glin.factory.ParserFactory;
import org.loader.glin.parser.Parser;
package org.loader.glinsample.utils;
public class Parsers implements ParserFactory {
@Override
public Parser getParser() {
return new Parser() {
@Override | public <T> Result<T> parse(Class<T> klass, RawResult netResult) { |
qibin0506/Glin | glinsample/src/main/java/org/loader/glinsample/utils/Parsers.java | // Path: glin/src/main/java/org/loader/glin/RawResult.java
// public class RawResult {
// private int statusCode;
// private String message;
// private String response;
//
// public RawResult() {}
//
// public RawResult(int statusCode, String message, String response) {
// this.statusCode = statusCode;
// this.message = message;
// this.response = response;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public void setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/Result.java
// public class Result<T> {
// private boolean ok;
// private String message;
// private T result;
// private int code;
// private Object obj;
// private boolean isCache;
//
// public boolean isOK() {
// return ok;
// }
//
// public void ok(boolean ok) {
// this.ok = ok;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String mMessage) {
// this.message = mMessage;
// }
//
// public T getResult() {
// return result;
// }
//
// public void setResult(T mResult) {
// this.result = mResult;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
//
// public Object getObj() {
// return obj;
// }
//
// public void setObj(Object obj) {
// this.obj = obj;
// }
//
// public <V> V assertGetObj() {
// return (V) getObj();
// }
//
// public boolean isCache() {
// return isCache;
// }
//
// public void setCache(boolean cache) {
// isCache = cache;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("ok: ").append(ok).append("\n");
// sb.append("message: ").append(message).append("\n");
// sb.append("obj: ").append(obj).append("\n");
// sb.append("result: ").append(result).append("\n");
// sb.append("code: ").append(code).append("\n");
// sb.append("is_cache: ").append(isCache);
//
// return sb.toString();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/factory/ParserFactory.java
// public interface ParserFactory {
// Parser getParser();
// Parser getListParser();
// }
//
// Path: glin/src/main/java/org/loader/glin/parser/Parser.java
// public abstract class Parser {
// public String mKey;
//
// public Parser() {
//
// }
//
// public Parser(String key) {
// mKey = key;
// }
//
// /**
// *
// * @param klass the class of data struct
// * @param netResult
// * @param <T>
// * @return
// */
// public abstract <T> Result<T> parse(Class<T> klass, RawResult netResult);
// }
| import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.loader.glin.RawResult;
import org.loader.glin.Result;
import org.loader.glin.factory.ParserFactory;
import org.loader.glin.parser.Parser; | package org.loader.glinsample.utils;
public class Parsers implements ParserFactory {
@Override
public Parser getParser() {
return new Parser() {
@Override | // Path: glin/src/main/java/org/loader/glin/RawResult.java
// public class RawResult {
// private int statusCode;
// private String message;
// private String response;
//
// public RawResult() {}
//
// public RawResult(int statusCode, String message, String response) {
// this.statusCode = statusCode;
// this.message = message;
// this.response = response;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public void setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/Result.java
// public class Result<T> {
// private boolean ok;
// private String message;
// private T result;
// private int code;
// private Object obj;
// private boolean isCache;
//
// public boolean isOK() {
// return ok;
// }
//
// public void ok(boolean ok) {
// this.ok = ok;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String mMessage) {
// this.message = mMessage;
// }
//
// public T getResult() {
// return result;
// }
//
// public void setResult(T mResult) {
// this.result = mResult;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
//
// public Object getObj() {
// return obj;
// }
//
// public void setObj(Object obj) {
// this.obj = obj;
// }
//
// public <V> V assertGetObj() {
// return (V) getObj();
// }
//
// public boolean isCache() {
// return isCache;
// }
//
// public void setCache(boolean cache) {
// isCache = cache;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("ok: ").append(ok).append("\n");
// sb.append("message: ").append(message).append("\n");
// sb.append("obj: ").append(obj).append("\n");
// sb.append("result: ").append(result).append("\n");
// sb.append("code: ").append(code).append("\n");
// sb.append("is_cache: ").append(isCache);
//
// return sb.toString();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/factory/ParserFactory.java
// public interface ParserFactory {
// Parser getParser();
// Parser getListParser();
// }
//
// Path: glin/src/main/java/org/loader/glin/parser/Parser.java
// public abstract class Parser {
// public String mKey;
//
// public Parser() {
//
// }
//
// public Parser(String key) {
// mKey = key;
// }
//
// /**
// *
// * @param klass the class of data struct
// * @param netResult
// * @param <T>
// * @return
// */
// public abstract <T> Result<T> parse(Class<T> klass, RawResult netResult);
// }
// Path: glinsample/src/main/java/org/loader/glinsample/utils/Parsers.java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.loader.glin.RawResult;
import org.loader.glin.Result;
import org.loader.glin.factory.ParserFactory;
import org.loader.glin.parser.Parser;
package org.loader.glinsample.utils;
public class Parsers implements ParserFactory {
@Override
public Parser getParser() {
return new Parser() {
@Override | public <T> Result<T> parse(Class<T> klass, RawResult netResult) { |
qibin0506/Glin | glin/src/main/java/org/loader/glin/call/PutCall.java | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/Params.java
// public class Params {
//
// public static final String DEFAULT_JSON_KEY = "json";
//
// private LinkedHashMap<String, String> mParams;
// private LinkedHashMap<String, File> mFiles;
//
// public Params() {
// mParams = new LinkedHashMap<>();
// mFiles = new LinkedHashMap<>();
// }
//
// public Params(String key, Object value) {
// this();
// add(key, value);
// }
//
// public Params add(String key, Object value) {
// if (key == null) { return this;}
// if (value == null) { mParams.put(key, null);}
// else if (value instanceof File) { mFiles.put(key, (File) value);}
// else { mParams.put(key, value.toString());}
// return this;
// }
//
// public LinkedHashMap<String, String> get() {
// return mParams;
// }
//
// public String getParams(String key) {
// return mParams.get(key);
// }
//
// public File getFile(String key) {
// return mFiles.get(key);
// }
//
// public LinkedHashMap<String, File> files() {
// return mFiles;
// }
//
// public void remove(String key) {
// if (mParams.containsKey(key)) { mParams.remove(key);}
// if (mFiles.containsKey(key)) { mFiles.remove(key);}
// }
//
// public String encode() {
// String query = null;
// for (Map.Entry<String, String> entry : mParams.entrySet()) {
// if (query == null) { query = entry.getKey() + "=" + entry.getValue();}
// else { query += "&" + entry.getKey() + "=" + entry.getValue();}
// }
//
// return query;
// }
//
// public Iterator<String> iterator() {
// return mParams.keySet().iterator();
// }
//
// public Iterator<String> fileIterator() {
// return mFiles.keySet().iterator();
// }
//
// public boolean isEmpty() {
// return mParams.isEmpty() && mFiles.isEmpty();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/client/IClient.java
// public interface IClient extends IRequest {
//
// void cancel(final Object tag);
//
// void parserFactory(ParserFactory factory);
//
// LinkedHashMap<String, String> headers();
//
// void resultInterceptor(IResultInterceptor interceptor);
//
// void cacheProvider(ICacheProvider provider);
//
// void timeout(long ms);
// }
| import org.loader.glin.Callback;
import org.loader.glin.Params;
import org.loader.glin.client.IClient; | package org.loader.glin.call;
/**
* Created by qibin on 2016/7/14.
*/
public class PutCall<T> extends Call<T> {
public PutCall(IClient client, String url, | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/Params.java
// public class Params {
//
// public static final String DEFAULT_JSON_KEY = "json";
//
// private LinkedHashMap<String, String> mParams;
// private LinkedHashMap<String, File> mFiles;
//
// public Params() {
// mParams = new LinkedHashMap<>();
// mFiles = new LinkedHashMap<>();
// }
//
// public Params(String key, Object value) {
// this();
// add(key, value);
// }
//
// public Params add(String key, Object value) {
// if (key == null) { return this;}
// if (value == null) { mParams.put(key, null);}
// else if (value instanceof File) { mFiles.put(key, (File) value);}
// else { mParams.put(key, value.toString());}
// return this;
// }
//
// public LinkedHashMap<String, String> get() {
// return mParams;
// }
//
// public String getParams(String key) {
// return mParams.get(key);
// }
//
// public File getFile(String key) {
// return mFiles.get(key);
// }
//
// public LinkedHashMap<String, File> files() {
// return mFiles;
// }
//
// public void remove(String key) {
// if (mParams.containsKey(key)) { mParams.remove(key);}
// if (mFiles.containsKey(key)) { mFiles.remove(key);}
// }
//
// public String encode() {
// String query = null;
// for (Map.Entry<String, String> entry : mParams.entrySet()) {
// if (query == null) { query = entry.getKey() + "=" + entry.getValue();}
// else { query += "&" + entry.getKey() + "=" + entry.getValue();}
// }
//
// return query;
// }
//
// public Iterator<String> iterator() {
// return mParams.keySet().iterator();
// }
//
// public Iterator<String> fileIterator() {
// return mFiles.keySet().iterator();
// }
//
// public boolean isEmpty() {
// return mParams.isEmpty() && mFiles.isEmpty();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/client/IClient.java
// public interface IClient extends IRequest {
//
// void cancel(final Object tag);
//
// void parserFactory(ParserFactory factory);
//
// LinkedHashMap<String, String> headers();
//
// void resultInterceptor(IResultInterceptor interceptor);
//
// void cacheProvider(ICacheProvider provider);
//
// void timeout(long ms);
// }
// Path: glin/src/main/java/org/loader/glin/call/PutCall.java
import org.loader.glin.Callback;
import org.loader.glin.Params;
import org.loader.glin.client.IClient;
package org.loader.glin.call;
/**
* Created by qibin on 2016/7/14.
*/
public class PutCall<T> extends Call<T> {
public PutCall(IClient client, String url, | Params params, Object tag, |
qibin0506/Glin | glin/src/main/java/org/loader/glin/call/PutCall.java | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/Params.java
// public class Params {
//
// public static final String DEFAULT_JSON_KEY = "json";
//
// private LinkedHashMap<String, String> mParams;
// private LinkedHashMap<String, File> mFiles;
//
// public Params() {
// mParams = new LinkedHashMap<>();
// mFiles = new LinkedHashMap<>();
// }
//
// public Params(String key, Object value) {
// this();
// add(key, value);
// }
//
// public Params add(String key, Object value) {
// if (key == null) { return this;}
// if (value == null) { mParams.put(key, null);}
// else if (value instanceof File) { mFiles.put(key, (File) value);}
// else { mParams.put(key, value.toString());}
// return this;
// }
//
// public LinkedHashMap<String, String> get() {
// return mParams;
// }
//
// public String getParams(String key) {
// return mParams.get(key);
// }
//
// public File getFile(String key) {
// return mFiles.get(key);
// }
//
// public LinkedHashMap<String, File> files() {
// return mFiles;
// }
//
// public void remove(String key) {
// if (mParams.containsKey(key)) { mParams.remove(key);}
// if (mFiles.containsKey(key)) { mFiles.remove(key);}
// }
//
// public String encode() {
// String query = null;
// for (Map.Entry<String, String> entry : mParams.entrySet()) {
// if (query == null) { query = entry.getKey() + "=" + entry.getValue();}
// else { query += "&" + entry.getKey() + "=" + entry.getValue();}
// }
//
// return query;
// }
//
// public Iterator<String> iterator() {
// return mParams.keySet().iterator();
// }
//
// public Iterator<String> fileIterator() {
// return mFiles.keySet().iterator();
// }
//
// public boolean isEmpty() {
// return mParams.isEmpty() && mFiles.isEmpty();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/client/IClient.java
// public interface IClient extends IRequest {
//
// void cancel(final Object tag);
//
// void parserFactory(ParserFactory factory);
//
// LinkedHashMap<String, String> headers();
//
// void resultInterceptor(IResultInterceptor interceptor);
//
// void cacheProvider(ICacheProvider provider);
//
// void timeout(long ms);
// }
| import org.loader.glin.Callback;
import org.loader.glin.Params;
import org.loader.glin.client.IClient; | package org.loader.glin.call;
/**
* Created by qibin on 2016/7/14.
*/
public class PutCall<T> extends Call<T> {
public PutCall(IClient client, String url,
Params params, Object tag,
boolean cache) {
super(client, url, params, tag, cache);
}
@Override | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/Params.java
// public class Params {
//
// public static final String DEFAULT_JSON_KEY = "json";
//
// private LinkedHashMap<String, String> mParams;
// private LinkedHashMap<String, File> mFiles;
//
// public Params() {
// mParams = new LinkedHashMap<>();
// mFiles = new LinkedHashMap<>();
// }
//
// public Params(String key, Object value) {
// this();
// add(key, value);
// }
//
// public Params add(String key, Object value) {
// if (key == null) { return this;}
// if (value == null) { mParams.put(key, null);}
// else if (value instanceof File) { mFiles.put(key, (File) value);}
// else { mParams.put(key, value.toString());}
// return this;
// }
//
// public LinkedHashMap<String, String> get() {
// return mParams;
// }
//
// public String getParams(String key) {
// return mParams.get(key);
// }
//
// public File getFile(String key) {
// return mFiles.get(key);
// }
//
// public LinkedHashMap<String, File> files() {
// return mFiles;
// }
//
// public void remove(String key) {
// if (mParams.containsKey(key)) { mParams.remove(key);}
// if (mFiles.containsKey(key)) { mFiles.remove(key);}
// }
//
// public String encode() {
// String query = null;
// for (Map.Entry<String, String> entry : mParams.entrySet()) {
// if (query == null) { query = entry.getKey() + "=" + entry.getValue();}
// else { query += "&" + entry.getKey() + "=" + entry.getValue();}
// }
//
// return query;
// }
//
// public Iterator<String> iterator() {
// return mParams.keySet().iterator();
// }
//
// public Iterator<String> fileIterator() {
// return mFiles.keySet().iterator();
// }
//
// public boolean isEmpty() {
// return mParams.isEmpty() && mFiles.isEmpty();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/client/IClient.java
// public interface IClient extends IRequest {
//
// void cancel(final Object tag);
//
// void parserFactory(ParserFactory factory);
//
// LinkedHashMap<String, String> headers();
//
// void resultInterceptor(IResultInterceptor interceptor);
//
// void cacheProvider(ICacheProvider provider);
//
// void timeout(long ms);
// }
// Path: glin/src/main/java/org/loader/glin/call/PutCall.java
import org.loader.glin.Callback;
import org.loader.glin.Params;
import org.loader.glin.client.IClient;
package org.loader.glin.call;
/**
* Created by qibin on 2016/7/14.
*/
public class PutCall<T> extends Call<T> {
public PutCall(IClient client, String url,
Params params, Object tag,
boolean cache) {
super(client, url, params, tag, cache);
}
@Override | public void exec(Callback<T> callback) { |
qibin0506/Glin | glin/src/main/java/org/loader/glin/call/JsonCall.java | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/Params.java
// public class Params {
//
// public static final String DEFAULT_JSON_KEY = "json";
//
// private LinkedHashMap<String, String> mParams;
// private LinkedHashMap<String, File> mFiles;
//
// public Params() {
// mParams = new LinkedHashMap<>();
// mFiles = new LinkedHashMap<>();
// }
//
// public Params(String key, Object value) {
// this();
// add(key, value);
// }
//
// public Params add(String key, Object value) {
// if (key == null) { return this;}
// if (value == null) { mParams.put(key, null);}
// else if (value instanceof File) { mFiles.put(key, (File) value);}
// else { mParams.put(key, value.toString());}
// return this;
// }
//
// public LinkedHashMap<String, String> get() {
// return mParams;
// }
//
// public String getParams(String key) {
// return mParams.get(key);
// }
//
// public File getFile(String key) {
// return mFiles.get(key);
// }
//
// public LinkedHashMap<String, File> files() {
// return mFiles;
// }
//
// public void remove(String key) {
// if (mParams.containsKey(key)) { mParams.remove(key);}
// if (mFiles.containsKey(key)) { mFiles.remove(key);}
// }
//
// public String encode() {
// String query = null;
// for (Map.Entry<String, String> entry : mParams.entrySet()) {
// if (query == null) { query = entry.getKey() + "=" + entry.getValue();}
// else { query += "&" + entry.getKey() + "=" + entry.getValue();}
// }
//
// return query;
// }
//
// public Iterator<String> iterator() {
// return mParams.keySet().iterator();
// }
//
// public Iterator<String> fileIterator() {
// return mFiles.keySet().iterator();
// }
//
// public boolean isEmpty() {
// return mParams.isEmpty() && mFiles.isEmpty();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/client/IClient.java
// public interface IClient extends IRequest {
//
// void cancel(final Object tag);
//
// void parserFactory(ParserFactory factory);
//
// LinkedHashMap<String, String> headers();
//
// void resultInterceptor(IResultInterceptor interceptor);
//
// void cacheProvider(ICacheProvider provider);
//
// void timeout(long ms);
// }
| import org.loader.glin.Callback;
import org.loader.glin.Params;
import org.loader.glin.client.IClient; | package org.loader.glin.call;
/**
* Created by qibin on 2016/7/13.
*/
public class JsonCall<T> extends Call<T> {
public JsonCall(IClient client, String url, | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/Params.java
// public class Params {
//
// public static final String DEFAULT_JSON_KEY = "json";
//
// private LinkedHashMap<String, String> mParams;
// private LinkedHashMap<String, File> mFiles;
//
// public Params() {
// mParams = new LinkedHashMap<>();
// mFiles = new LinkedHashMap<>();
// }
//
// public Params(String key, Object value) {
// this();
// add(key, value);
// }
//
// public Params add(String key, Object value) {
// if (key == null) { return this;}
// if (value == null) { mParams.put(key, null);}
// else if (value instanceof File) { mFiles.put(key, (File) value);}
// else { mParams.put(key, value.toString());}
// return this;
// }
//
// public LinkedHashMap<String, String> get() {
// return mParams;
// }
//
// public String getParams(String key) {
// return mParams.get(key);
// }
//
// public File getFile(String key) {
// return mFiles.get(key);
// }
//
// public LinkedHashMap<String, File> files() {
// return mFiles;
// }
//
// public void remove(String key) {
// if (mParams.containsKey(key)) { mParams.remove(key);}
// if (mFiles.containsKey(key)) { mFiles.remove(key);}
// }
//
// public String encode() {
// String query = null;
// for (Map.Entry<String, String> entry : mParams.entrySet()) {
// if (query == null) { query = entry.getKey() + "=" + entry.getValue();}
// else { query += "&" + entry.getKey() + "=" + entry.getValue();}
// }
//
// return query;
// }
//
// public Iterator<String> iterator() {
// return mParams.keySet().iterator();
// }
//
// public Iterator<String> fileIterator() {
// return mFiles.keySet().iterator();
// }
//
// public boolean isEmpty() {
// return mParams.isEmpty() && mFiles.isEmpty();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/client/IClient.java
// public interface IClient extends IRequest {
//
// void cancel(final Object tag);
//
// void parserFactory(ParserFactory factory);
//
// LinkedHashMap<String, String> headers();
//
// void resultInterceptor(IResultInterceptor interceptor);
//
// void cacheProvider(ICacheProvider provider);
//
// void timeout(long ms);
// }
// Path: glin/src/main/java/org/loader/glin/call/JsonCall.java
import org.loader.glin.Callback;
import org.loader.glin.Params;
import org.loader.glin.client.IClient;
package org.loader.glin.call;
/**
* Created by qibin on 2016/7/13.
*/
public class JsonCall<T> extends Call<T> {
public JsonCall(IClient client, String url, | Params params, Object tag, |
qibin0506/Glin | glin/src/main/java/org/loader/glin/call/JsonCall.java | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/Params.java
// public class Params {
//
// public static final String DEFAULT_JSON_KEY = "json";
//
// private LinkedHashMap<String, String> mParams;
// private LinkedHashMap<String, File> mFiles;
//
// public Params() {
// mParams = new LinkedHashMap<>();
// mFiles = new LinkedHashMap<>();
// }
//
// public Params(String key, Object value) {
// this();
// add(key, value);
// }
//
// public Params add(String key, Object value) {
// if (key == null) { return this;}
// if (value == null) { mParams.put(key, null);}
// else if (value instanceof File) { mFiles.put(key, (File) value);}
// else { mParams.put(key, value.toString());}
// return this;
// }
//
// public LinkedHashMap<String, String> get() {
// return mParams;
// }
//
// public String getParams(String key) {
// return mParams.get(key);
// }
//
// public File getFile(String key) {
// return mFiles.get(key);
// }
//
// public LinkedHashMap<String, File> files() {
// return mFiles;
// }
//
// public void remove(String key) {
// if (mParams.containsKey(key)) { mParams.remove(key);}
// if (mFiles.containsKey(key)) { mFiles.remove(key);}
// }
//
// public String encode() {
// String query = null;
// for (Map.Entry<String, String> entry : mParams.entrySet()) {
// if (query == null) { query = entry.getKey() + "=" + entry.getValue();}
// else { query += "&" + entry.getKey() + "=" + entry.getValue();}
// }
//
// return query;
// }
//
// public Iterator<String> iterator() {
// return mParams.keySet().iterator();
// }
//
// public Iterator<String> fileIterator() {
// return mFiles.keySet().iterator();
// }
//
// public boolean isEmpty() {
// return mParams.isEmpty() && mFiles.isEmpty();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/client/IClient.java
// public interface IClient extends IRequest {
//
// void cancel(final Object tag);
//
// void parserFactory(ParserFactory factory);
//
// LinkedHashMap<String, String> headers();
//
// void resultInterceptor(IResultInterceptor interceptor);
//
// void cacheProvider(ICacheProvider provider);
//
// void timeout(long ms);
// }
| import org.loader.glin.Callback;
import org.loader.glin.Params;
import org.loader.glin.client.IClient; | package org.loader.glin.call;
/**
* Created by qibin on 2016/7/13.
*/
public class JsonCall<T> extends Call<T> {
public JsonCall(IClient client, String url,
Params params, Object tag,
boolean cache) {
super(client, url, params, tag, cache);
}
@Override | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/Params.java
// public class Params {
//
// public static final String DEFAULT_JSON_KEY = "json";
//
// private LinkedHashMap<String, String> mParams;
// private LinkedHashMap<String, File> mFiles;
//
// public Params() {
// mParams = new LinkedHashMap<>();
// mFiles = new LinkedHashMap<>();
// }
//
// public Params(String key, Object value) {
// this();
// add(key, value);
// }
//
// public Params add(String key, Object value) {
// if (key == null) { return this;}
// if (value == null) { mParams.put(key, null);}
// else if (value instanceof File) { mFiles.put(key, (File) value);}
// else { mParams.put(key, value.toString());}
// return this;
// }
//
// public LinkedHashMap<String, String> get() {
// return mParams;
// }
//
// public String getParams(String key) {
// return mParams.get(key);
// }
//
// public File getFile(String key) {
// return mFiles.get(key);
// }
//
// public LinkedHashMap<String, File> files() {
// return mFiles;
// }
//
// public void remove(String key) {
// if (mParams.containsKey(key)) { mParams.remove(key);}
// if (mFiles.containsKey(key)) { mFiles.remove(key);}
// }
//
// public String encode() {
// String query = null;
// for (Map.Entry<String, String> entry : mParams.entrySet()) {
// if (query == null) { query = entry.getKey() + "=" + entry.getValue();}
// else { query += "&" + entry.getKey() + "=" + entry.getValue();}
// }
//
// return query;
// }
//
// public Iterator<String> iterator() {
// return mParams.keySet().iterator();
// }
//
// public Iterator<String> fileIterator() {
// return mFiles.keySet().iterator();
// }
//
// public boolean isEmpty() {
// return mParams.isEmpty() && mFiles.isEmpty();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/client/IClient.java
// public interface IClient extends IRequest {
//
// void cancel(final Object tag);
//
// void parserFactory(ParserFactory factory);
//
// LinkedHashMap<String, String> headers();
//
// void resultInterceptor(IResultInterceptor interceptor);
//
// void cacheProvider(ICacheProvider provider);
//
// void timeout(long ms);
// }
// Path: glin/src/main/java/org/loader/glin/call/JsonCall.java
import org.loader.glin.Callback;
import org.loader.glin.Params;
import org.loader.glin.client.IClient;
package org.loader.glin.call;
/**
* Created by qibin on 2016/7/13.
*/
public class JsonCall<T> extends Call<T> {
public JsonCall(IClient client, String url,
Params params, Object tag,
boolean cache) {
super(client, url, params, tag, cache);
}
@Override | public void exec(final Callback<T> callback) { |
qibin0506/Glin | glin/src/main/java/org/loader/glin/chan/GlobalChanNode.java | // Path: glin/src/main/java/org/loader/glin/Context.java
// public class Context {
// private Call<?> call;
// private Result<?> result;
// private RawResult rawResult;
//
// public Context() {}
//
// public Context(Call<?> call) {
// this.call = call;
// }
//
// public Call<?> getCall() {
// return call;
// }
//
// public void setCall(Call<?> call) {
// this.call = call;
// }
//
// public Result<?> getResult() {
// return result;
// }
//
// public void setResult(Result<?> result) {
// this.result = result;
// }
//
// public RawResult getRawResult() {
// return rawResult;
// }
//
// public void setRawResult(RawResult rawResult) {
// this.rawResult = rawResult;
// }
// }
| import org.loader.glin.Context; | package org.loader.glin.chan;
/**
* <p class="note">File Note</p>
* Created by qibin on 2017/11/13.
*/
public class GlobalChanNode extends ChanNode {
private ChanNode[] mGlobalChanNodes;
public GlobalChanNode(ChanNode ...chanNodes) {
mGlobalChanNodes = chanNodes;
}
@Override | // Path: glin/src/main/java/org/loader/glin/Context.java
// public class Context {
// private Call<?> call;
// private Result<?> result;
// private RawResult rawResult;
//
// public Context() {}
//
// public Context(Call<?> call) {
// this.call = call;
// }
//
// public Call<?> getCall() {
// return call;
// }
//
// public void setCall(Call<?> call) {
// this.call = call;
// }
//
// public Result<?> getResult() {
// return result;
// }
//
// public void setResult(Result<?> result) {
// this.result = result;
// }
//
// public RawResult getRawResult() {
// return rawResult;
// }
//
// public void setRawResult(RawResult rawResult) {
// this.rawResult = rawResult;
// }
// }
// Path: glin/src/main/java/org/loader/glin/chan/GlobalChanNode.java
import org.loader.glin.Context;
package org.loader.glin.chan;
/**
* <p class="note">File Note</p>
* Created by qibin on 2017/11/13.
*/
public class GlobalChanNode extends ChanNode {
private ChanNode[] mGlobalChanNodes;
public GlobalChanNode(ChanNode ...chanNodes) {
mGlobalChanNodes = chanNodes;
}
@Override | public void run(Context ctx) { |
qibin0506/Glin | glin/src/main/java/org/loader/glin/helper/ClientHelper.java | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/RawResult.java
// public class RawResult {
// private int statusCode;
// private String message;
// private String response;
//
// public RawResult() {}
//
// public RawResult(int statusCode, String message, String response) {
// this.statusCode = statusCode;
// this.message = message;
// this.response = response;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public void setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/Result.java
// public class Result<T> {
// private boolean ok;
// private String message;
// private T result;
// private int code;
// private Object obj;
// private boolean isCache;
//
// public boolean isOK() {
// return ok;
// }
//
// public void ok(boolean ok) {
// this.ok = ok;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String mMessage) {
// this.message = mMessage;
// }
//
// public T getResult() {
// return result;
// }
//
// public void setResult(T mResult) {
// this.result = mResult;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
//
// public Object getObj() {
// return obj;
// }
//
// public void setObj(Object obj) {
// this.obj = obj;
// }
//
// public <V> V assertGetObj() {
// return (V) getObj();
// }
//
// public boolean isCache() {
// return isCache;
// }
//
// public void setCache(boolean cache) {
// isCache = cache;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("ok: ").append(ok).append("\n");
// sb.append("message: ").append(message).append("\n");
// sb.append("obj: ").append(obj).append("\n");
// sb.append("result: ").append(result).append("\n");
// sb.append("code: ").append(code).append("\n");
// sb.append("is_cache: ").append(isCache);
//
// return sb.toString();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/cache/ICacheProvider.java
// public interface ICacheProvider {
// /**
// * get cache by key of {@link #getKey(String, String)}
// * @param key key
// * @param klass type of data struct, see also {@link org.loader.glin.helper.Helper}
// * @param isList is result a List
// * @return cache data
// */
// <T> Result<T> get(String key, Class<T> klass, boolean isList);
//
// /**
// * cache data
// * @param key see {@link #getKey(String, String)}
// * @param netResult the origin result
// * @param result parsed result
// */
// <T> void put(String key, RawResult netResult, Result<T> result);
//
// /**
// * provide the key
// * @param url the request url
// * @param params the request params, maybe key1=value1&key2=value2 while your request is POST, maybe null while your request is GET, maybe json string while your request is POST Json
// * @return
// */
// String getKey(String url, String params);
// }
//
// Path: glin/src/main/java/org/loader/glin/factory/ParserFactory.java
// public interface ParserFactory {
// Parser getParser();
// Parser getListParser();
// }
//
// Path: glin/src/main/java/org/loader/glin/interceptor/IResultInterceptor.java
// public interface IResultInterceptor {
// /**
// * 是否拦截结果
// * @param result
// * @return true callback不会执行
// */
// boolean intercept(Result<?> result);
// }
| import org.loader.glin.Callback;
import org.loader.glin.RawResult;
import org.loader.glin.Result;
import org.loader.glin.cache.ICacheProvider;
import org.loader.glin.factory.ParserFactory;
import org.loader.glin.interceptor.IResultInterceptor;
import java.util.List; | package org.loader.glin.helper;
/**
* ClientHelper, useful when you convert response, cache your data and intercept your callback
*/
public final class ClientHelper {
private ParserFactory mParserFactory; | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/RawResult.java
// public class RawResult {
// private int statusCode;
// private String message;
// private String response;
//
// public RawResult() {}
//
// public RawResult(int statusCode, String message, String response) {
// this.statusCode = statusCode;
// this.message = message;
// this.response = response;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public void setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/Result.java
// public class Result<T> {
// private boolean ok;
// private String message;
// private T result;
// private int code;
// private Object obj;
// private boolean isCache;
//
// public boolean isOK() {
// return ok;
// }
//
// public void ok(boolean ok) {
// this.ok = ok;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String mMessage) {
// this.message = mMessage;
// }
//
// public T getResult() {
// return result;
// }
//
// public void setResult(T mResult) {
// this.result = mResult;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
//
// public Object getObj() {
// return obj;
// }
//
// public void setObj(Object obj) {
// this.obj = obj;
// }
//
// public <V> V assertGetObj() {
// return (V) getObj();
// }
//
// public boolean isCache() {
// return isCache;
// }
//
// public void setCache(boolean cache) {
// isCache = cache;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("ok: ").append(ok).append("\n");
// sb.append("message: ").append(message).append("\n");
// sb.append("obj: ").append(obj).append("\n");
// sb.append("result: ").append(result).append("\n");
// sb.append("code: ").append(code).append("\n");
// sb.append("is_cache: ").append(isCache);
//
// return sb.toString();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/cache/ICacheProvider.java
// public interface ICacheProvider {
// /**
// * get cache by key of {@link #getKey(String, String)}
// * @param key key
// * @param klass type of data struct, see also {@link org.loader.glin.helper.Helper}
// * @param isList is result a List
// * @return cache data
// */
// <T> Result<T> get(String key, Class<T> klass, boolean isList);
//
// /**
// * cache data
// * @param key see {@link #getKey(String, String)}
// * @param netResult the origin result
// * @param result parsed result
// */
// <T> void put(String key, RawResult netResult, Result<T> result);
//
// /**
// * provide the key
// * @param url the request url
// * @param params the request params, maybe key1=value1&key2=value2 while your request is POST, maybe null while your request is GET, maybe json string while your request is POST Json
// * @return
// */
// String getKey(String url, String params);
// }
//
// Path: glin/src/main/java/org/loader/glin/factory/ParserFactory.java
// public interface ParserFactory {
// Parser getParser();
// Parser getListParser();
// }
//
// Path: glin/src/main/java/org/loader/glin/interceptor/IResultInterceptor.java
// public interface IResultInterceptor {
// /**
// * 是否拦截结果
// * @param result
// * @return true callback不会执行
// */
// boolean intercept(Result<?> result);
// }
// Path: glin/src/main/java/org/loader/glin/helper/ClientHelper.java
import org.loader.glin.Callback;
import org.loader.glin.RawResult;
import org.loader.glin.Result;
import org.loader.glin.cache.ICacheProvider;
import org.loader.glin.factory.ParserFactory;
import org.loader.glin.interceptor.IResultInterceptor;
import java.util.List;
package org.loader.glin.helper;
/**
* ClientHelper, useful when you convert response, cache your data and intercept your callback
*/
public final class ClientHelper {
private ParserFactory mParserFactory; | private ICacheProvider mCacheProvider; |
qibin0506/Glin | glin/src/main/java/org/loader/glin/helper/ClientHelper.java | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/RawResult.java
// public class RawResult {
// private int statusCode;
// private String message;
// private String response;
//
// public RawResult() {}
//
// public RawResult(int statusCode, String message, String response) {
// this.statusCode = statusCode;
// this.message = message;
// this.response = response;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public void setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/Result.java
// public class Result<T> {
// private boolean ok;
// private String message;
// private T result;
// private int code;
// private Object obj;
// private boolean isCache;
//
// public boolean isOK() {
// return ok;
// }
//
// public void ok(boolean ok) {
// this.ok = ok;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String mMessage) {
// this.message = mMessage;
// }
//
// public T getResult() {
// return result;
// }
//
// public void setResult(T mResult) {
// this.result = mResult;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
//
// public Object getObj() {
// return obj;
// }
//
// public void setObj(Object obj) {
// this.obj = obj;
// }
//
// public <V> V assertGetObj() {
// return (V) getObj();
// }
//
// public boolean isCache() {
// return isCache;
// }
//
// public void setCache(boolean cache) {
// isCache = cache;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("ok: ").append(ok).append("\n");
// sb.append("message: ").append(message).append("\n");
// sb.append("obj: ").append(obj).append("\n");
// sb.append("result: ").append(result).append("\n");
// sb.append("code: ").append(code).append("\n");
// sb.append("is_cache: ").append(isCache);
//
// return sb.toString();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/cache/ICacheProvider.java
// public interface ICacheProvider {
// /**
// * get cache by key of {@link #getKey(String, String)}
// * @param key key
// * @param klass type of data struct, see also {@link org.loader.glin.helper.Helper}
// * @param isList is result a List
// * @return cache data
// */
// <T> Result<T> get(String key, Class<T> klass, boolean isList);
//
// /**
// * cache data
// * @param key see {@link #getKey(String, String)}
// * @param netResult the origin result
// * @param result parsed result
// */
// <T> void put(String key, RawResult netResult, Result<T> result);
//
// /**
// * provide the key
// * @param url the request url
// * @param params the request params, maybe key1=value1&key2=value2 while your request is POST, maybe null while your request is GET, maybe json string while your request is POST Json
// * @return
// */
// String getKey(String url, String params);
// }
//
// Path: glin/src/main/java/org/loader/glin/factory/ParserFactory.java
// public interface ParserFactory {
// Parser getParser();
// Parser getListParser();
// }
//
// Path: glin/src/main/java/org/loader/glin/interceptor/IResultInterceptor.java
// public interface IResultInterceptor {
// /**
// * 是否拦截结果
// * @param result
// * @return true callback不会执行
// */
// boolean intercept(Result<?> result);
// }
| import org.loader.glin.Callback;
import org.loader.glin.RawResult;
import org.loader.glin.Result;
import org.loader.glin.cache.ICacheProvider;
import org.loader.glin.factory.ParserFactory;
import org.loader.glin.interceptor.IResultInterceptor;
import java.util.List; | package org.loader.glin.helper;
/**
* ClientHelper, useful when you convert response, cache your data and intercept your callback
*/
public final class ClientHelper {
private ParserFactory mParserFactory;
private ICacheProvider mCacheProvider; | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/RawResult.java
// public class RawResult {
// private int statusCode;
// private String message;
// private String response;
//
// public RawResult() {}
//
// public RawResult(int statusCode, String message, String response) {
// this.statusCode = statusCode;
// this.message = message;
// this.response = response;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public void setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/Result.java
// public class Result<T> {
// private boolean ok;
// private String message;
// private T result;
// private int code;
// private Object obj;
// private boolean isCache;
//
// public boolean isOK() {
// return ok;
// }
//
// public void ok(boolean ok) {
// this.ok = ok;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String mMessage) {
// this.message = mMessage;
// }
//
// public T getResult() {
// return result;
// }
//
// public void setResult(T mResult) {
// this.result = mResult;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
//
// public Object getObj() {
// return obj;
// }
//
// public void setObj(Object obj) {
// this.obj = obj;
// }
//
// public <V> V assertGetObj() {
// return (V) getObj();
// }
//
// public boolean isCache() {
// return isCache;
// }
//
// public void setCache(boolean cache) {
// isCache = cache;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("ok: ").append(ok).append("\n");
// sb.append("message: ").append(message).append("\n");
// sb.append("obj: ").append(obj).append("\n");
// sb.append("result: ").append(result).append("\n");
// sb.append("code: ").append(code).append("\n");
// sb.append("is_cache: ").append(isCache);
//
// return sb.toString();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/cache/ICacheProvider.java
// public interface ICacheProvider {
// /**
// * get cache by key of {@link #getKey(String, String)}
// * @param key key
// * @param klass type of data struct, see also {@link org.loader.glin.helper.Helper}
// * @param isList is result a List
// * @return cache data
// */
// <T> Result<T> get(String key, Class<T> klass, boolean isList);
//
// /**
// * cache data
// * @param key see {@link #getKey(String, String)}
// * @param netResult the origin result
// * @param result parsed result
// */
// <T> void put(String key, RawResult netResult, Result<T> result);
//
// /**
// * provide the key
// * @param url the request url
// * @param params the request params, maybe key1=value1&key2=value2 while your request is POST, maybe null while your request is GET, maybe json string while your request is POST Json
// * @return
// */
// String getKey(String url, String params);
// }
//
// Path: glin/src/main/java/org/loader/glin/factory/ParserFactory.java
// public interface ParserFactory {
// Parser getParser();
// Parser getListParser();
// }
//
// Path: glin/src/main/java/org/loader/glin/interceptor/IResultInterceptor.java
// public interface IResultInterceptor {
// /**
// * 是否拦截结果
// * @param result
// * @return true callback不会执行
// */
// boolean intercept(Result<?> result);
// }
// Path: glin/src/main/java/org/loader/glin/helper/ClientHelper.java
import org.loader.glin.Callback;
import org.loader.glin.RawResult;
import org.loader.glin.Result;
import org.loader.glin.cache.ICacheProvider;
import org.loader.glin.factory.ParserFactory;
import org.loader.glin.interceptor.IResultInterceptor;
import java.util.List;
package org.loader.glin.helper;
/**
* ClientHelper, useful when you convert response, cache your data and intercept your callback
*/
public final class ClientHelper {
private ParserFactory mParserFactory;
private ICacheProvider mCacheProvider; | private IResultInterceptor mResultInterceptor; |
qibin0506/Glin | glin/src/main/java/org/loader/glin/helper/ClientHelper.java | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/RawResult.java
// public class RawResult {
// private int statusCode;
// private String message;
// private String response;
//
// public RawResult() {}
//
// public RawResult(int statusCode, String message, String response) {
// this.statusCode = statusCode;
// this.message = message;
// this.response = response;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public void setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/Result.java
// public class Result<T> {
// private boolean ok;
// private String message;
// private T result;
// private int code;
// private Object obj;
// private boolean isCache;
//
// public boolean isOK() {
// return ok;
// }
//
// public void ok(boolean ok) {
// this.ok = ok;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String mMessage) {
// this.message = mMessage;
// }
//
// public T getResult() {
// return result;
// }
//
// public void setResult(T mResult) {
// this.result = mResult;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
//
// public Object getObj() {
// return obj;
// }
//
// public void setObj(Object obj) {
// this.obj = obj;
// }
//
// public <V> V assertGetObj() {
// return (V) getObj();
// }
//
// public boolean isCache() {
// return isCache;
// }
//
// public void setCache(boolean cache) {
// isCache = cache;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("ok: ").append(ok).append("\n");
// sb.append("message: ").append(message).append("\n");
// sb.append("obj: ").append(obj).append("\n");
// sb.append("result: ").append(result).append("\n");
// sb.append("code: ").append(code).append("\n");
// sb.append("is_cache: ").append(isCache);
//
// return sb.toString();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/cache/ICacheProvider.java
// public interface ICacheProvider {
// /**
// * get cache by key of {@link #getKey(String, String)}
// * @param key key
// * @param klass type of data struct, see also {@link org.loader.glin.helper.Helper}
// * @param isList is result a List
// * @return cache data
// */
// <T> Result<T> get(String key, Class<T> klass, boolean isList);
//
// /**
// * cache data
// * @param key see {@link #getKey(String, String)}
// * @param netResult the origin result
// * @param result parsed result
// */
// <T> void put(String key, RawResult netResult, Result<T> result);
//
// /**
// * provide the key
// * @param url the request url
// * @param params the request params, maybe key1=value1&key2=value2 while your request is POST, maybe null while your request is GET, maybe json string while your request is POST Json
// * @return
// */
// String getKey(String url, String params);
// }
//
// Path: glin/src/main/java/org/loader/glin/factory/ParserFactory.java
// public interface ParserFactory {
// Parser getParser();
// Parser getListParser();
// }
//
// Path: glin/src/main/java/org/loader/glin/interceptor/IResultInterceptor.java
// public interface IResultInterceptor {
// /**
// * 是否拦截结果
// * @param result
// * @return true callback不会执行
// */
// boolean intercept(Result<?> result);
// }
| import org.loader.glin.Callback;
import org.loader.glin.RawResult;
import org.loader.glin.Result;
import org.loader.glin.cache.ICacheProvider;
import org.loader.glin.factory.ParserFactory;
import org.loader.glin.interceptor.IResultInterceptor;
import java.util.List; | package org.loader.glin.helper;
/**
* ClientHelper, useful when you convert response, cache your data and intercept your callback
*/
public final class ClientHelper {
private ParserFactory mParserFactory;
private ICacheProvider mCacheProvider;
private IResultInterceptor mResultInterceptor;
public ClientHelper parserFactory(ParserFactory parserFactory) {
mParserFactory = parserFactory;
return this;
}
public ClientHelper cacheProvider(ICacheProvider cacheProvider) {
mCacheProvider = cacheProvider;
return this;
}
public ClientHelper resultInterceptor(IResultInterceptor resultInterceptor) {
mResultInterceptor = resultInterceptor;
return this;
}
/**
* convert the http response to Result
* @param callback
* @param netResult
* @param <T>
* @return return the result
*/ | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/RawResult.java
// public class RawResult {
// private int statusCode;
// private String message;
// private String response;
//
// public RawResult() {}
//
// public RawResult(int statusCode, String message, String response) {
// this.statusCode = statusCode;
// this.message = message;
// this.response = response;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public void setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/Result.java
// public class Result<T> {
// private boolean ok;
// private String message;
// private T result;
// private int code;
// private Object obj;
// private boolean isCache;
//
// public boolean isOK() {
// return ok;
// }
//
// public void ok(boolean ok) {
// this.ok = ok;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String mMessage) {
// this.message = mMessage;
// }
//
// public T getResult() {
// return result;
// }
//
// public void setResult(T mResult) {
// this.result = mResult;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
//
// public Object getObj() {
// return obj;
// }
//
// public void setObj(Object obj) {
// this.obj = obj;
// }
//
// public <V> V assertGetObj() {
// return (V) getObj();
// }
//
// public boolean isCache() {
// return isCache;
// }
//
// public void setCache(boolean cache) {
// isCache = cache;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("ok: ").append(ok).append("\n");
// sb.append("message: ").append(message).append("\n");
// sb.append("obj: ").append(obj).append("\n");
// sb.append("result: ").append(result).append("\n");
// sb.append("code: ").append(code).append("\n");
// sb.append("is_cache: ").append(isCache);
//
// return sb.toString();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/cache/ICacheProvider.java
// public interface ICacheProvider {
// /**
// * get cache by key of {@link #getKey(String, String)}
// * @param key key
// * @param klass type of data struct, see also {@link org.loader.glin.helper.Helper}
// * @param isList is result a List
// * @return cache data
// */
// <T> Result<T> get(String key, Class<T> klass, boolean isList);
//
// /**
// * cache data
// * @param key see {@link #getKey(String, String)}
// * @param netResult the origin result
// * @param result parsed result
// */
// <T> void put(String key, RawResult netResult, Result<T> result);
//
// /**
// * provide the key
// * @param url the request url
// * @param params the request params, maybe key1=value1&key2=value2 while your request is POST, maybe null while your request is GET, maybe json string while your request is POST Json
// * @return
// */
// String getKey(String url, String params);
// }
//
// Path: glin/src/main/java/org/loader/glin/factory/ParserFactory.java
// public interface ParserFactory {
// Parser getParser();
// Parser getListParser();
// }
//
// Path: glin/src/main/java/org/loader/glin/interceptor/IResultInterceptor.java
// public interface IResultInterceptor {
// /**
// * 是否拦截结果
// * @param result
// * @return true callback不会执行
// */
// boolean intercept(Result<?> result);
// }
// Path: glin/src/main/java/org/loader/glin/helper/ClientHelper.java
import org.loader.glin.Callback;
import org.loader.glin.RawResult;
import org.loader.glin.Result;
import org.loader.glin.cache.ICacheProvider;
import org.loader.glin.factory.ParserFactory;
import org.loader.glin.interceptor.IResultInterceptor;
import java.util.List;
package org.loader.glin.helper;
/**
* ClientHelper, useful when you convert response, cache your data and intercept your callback
*/
public final class ClientHelper {
private ParserFactory mParserFactory;
private ICacheProvider mCacheProvider;
private IResultInterceptor mResultInterceptor;
public ClientHelper parserFactory(ParserFactory parserFactory) {
mParserFactory = parserFactory;
return this;
}
public ClientHelper cacheProvider(ICacheProvider cacheProvider) {
mCacheProvider = cacheProvider;
return this;
}
public ClientHelper resultInterceptor(IResultInterceptor resultInterceptor) {
mResultInterceptor = resultInterceptor;
return this;
}
/**
* convert the http response to Result
* @param callback
* @param netResult
* @param <T>
* @return return the result
*/ | public <T> Result<T> parseResponse(Callback<T> callback, RawResult netResult) { |
qibin0506/Glin | glin/src/main/java/org/loader/glin/helper/ClientHelper.java | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/RawResult.java
// public class RawResult {
// private int statusCode;
// private String message;
// private String response;
//
// public RawResult() {}
//
// public RawResult(int statusCode, String message, String response) {
// this.statusCode = statusCode;
// this.message = message;
// this.response = response;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public void setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/Result.java
// public class Result<T> {
// private boolean ok;
// private String message;
// private T result;
// private int code;
// private Object obj;
// private boolean isCache;
//
// public boolean isOK() {
// return ok;
// }
//
// public void ok(boolean ok) {
// this.ok = ok;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String mMessage) {
// this.message = mMessage;
// }
//
// public T getResult() {
// return result;
// }
//
// public void setResult(T mResult) {
// this.result = mResult;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
//
// public Object getObj() {
// return obj;
// }
//
// public void setObj(Object obj) {
// this.obj = obj;
// }
//
// public <V> V assertGetObj() {
// return (V) getObj();
// }
//
// public boolean isCache() {
// return isCache;
// }
//
// public void setCache(boolean cache) {
// isCache = cache;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("ok: ").append(ok).append("\n");
// sb.append("message: ").append(message).append("\n");
// sb.append("obj: ").append(obj).append("\n");
// sb.append("result: ").append(result).append("\n");
// sb.append("code: ").append(code).append("\n");
// sb.append("is_cache: ").append(isCache);
//
// return sb.toString();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/cache/ICacheProvider.java
// public interface ICacheProvider {
// /**
// * get cache by key of {@link #getKey(String, String)}
// * @param key key
// * @param klass type of data struct, see also {@link org.loader.glin.helper.Helper}
// * @param isList is result a List
// * @return cache data
// */
// <T> Result<T> get(String key, Class<T> klass, boolean isList);
//
// /**
// * cache data
// * @param key see {@link #getKey(String, String)}
// * @param netResult the origin result
// * @param result parsed result
// */
// <T> void put(String key, RawResult netResult, Result<T> result);
//
// /**
// * provide the key
// * @param url the request url
// * @param params the request params, maybe key1=value1&key2=value2 while your request is POST, maybe null while your request is GET, maybe json string while your request is POST Json
// * @return
// */
// String getKey(String url, String params);
// }
//
// Path: glin/src/main/java/org/loader/glin/factory/ParserFactory.java
// public interface ParserFactory {
// Parser getParser();
// Parser getListParser();
// }
//
// Path: glin/src/main/java/org/loader/glin/interceptor/IResultInterceptor.java
// public interface IResultInterceptor {
// /**
// * 是否拦截结果
// * @param result
// * @return true callback不会执行
// */
// boolean intercept(Result<?> result);
// }
| import org.loader.glin.Callback;
import org.loader.glin.RawResult;
import org.loader.glin.Result;
import org.loader.glin.cache.ICacheProvider;
import org.loader.glin.factory.ParserFactory;
import org.loader.glin.interceptor.IResultInterceptor;
import java.util.List; | package org.loader.glin.helper;
/**
* ClientHelper, useful when you convert response, cache your data and intercept your callback
*/
public final class ClientHelper {
private ParserFactory mParserFactory;
private ICacheProvider mCacheProvider;
private IResultInterceptor mResultInterceptor;
public ClientHelper parserFactory(ParserFactory parserFactory) {
mParserFactory = parserFactory;
return this;
}
public ClientHelper cacheProvider(ICacheProvider cacheProvider) {
mCacheProvider = cacheProvider;
return this;
}
public ClientHelper resultInterceptor(IResultInterceptor resultInterceptor) {
mResultInterceptor = resultInterceptor;
return this;
}
/**
* convert the http response to Result
* @param callback
* @param netResult
* @param <T>
* @return return the result
*/ | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/RawResult.java
// public class RawResult {
// private int statusCode;
// private String message;
// private String response;
//
// public RawResult() {}
//
// public RawResult(int statusCode, String message, String response) {
// this.statusCode = statusCode;
// this.message = message;
// this.response = response;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public void setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/Result.java
// public class Result<T> {
// private boolean ok;
// private String message;
// private T result;
// private int code;
// private Object obj;
// private boolean isCache;
//
// public boolean isOK() {
// return ok;
// }
//
// public void ok(boolean ok) {
// this.ok = ok;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String mMessage) {
// this.message = mMessage;
// }
//
// public T getResult() {
// return result;
// }
//
// public void setResult(T mResult) {
// this.result = mResult;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
//
// public Object getObj() {
// return obj;
// }
//
// public void setObj(Object obj) {
// this.obj = obj;
// }
//
// public <V> V assertGetObj() {
// return (V) getObj();
// }
//
// public boolean isCache() {
// return isCache;
// }
//
// public void setCache(boolean cache) {
// isCache = cache;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("ok: ").append(ok).append("\n");
// sb.append("message: ").append(message).append("\n");
// sb.append("obj: ").append(obj).append("\n");
// sb.append("result: ").append(result).append("\n");
// sb.append("code: ").append(code).append("\n");
// sb.append("is_cache: ").append(isCache);
//
// return sb.toString();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/cache/ICacheProvider.java
// public interface ICacheProvider {
// /**
// * get cache by key of {@link #getKey(String, String)}
// * @param key key
// * @param klass type of data struct, see also {@link org.loader.glin.helper.Helper}
// * @param isList is result a List
// * @return cache data
// */
// <T> Result<T> get(String key, Class<T> klass, boolean isList);
//
// /**
// * cache data
// * @param key see {@link #getKey(String, String)}
// * @param netResult the origin result
// * @param result parsed result
// */
// <T> void put(String key, RawResult netResult, Result<T> result);
//
// /**
// * provide the key
// * @param url the request url
// * @param params the request params, maybe key1=value1&key2=value2 while your request is POST, maybe null while your request is GET, maybe json string while your request is POST Json
// * @return
// */
// String getKey(String url, String params);
// }
//
// Path: glin/src/main/java/org/loader/glin/factory/ParserFactory.java
// public interface ParserFactory {
// Parser getParser();
// Parser getListParser();
// }
//
// Path: glin/src/main/java/org/loader/glin/interceptor/IResultInterceptor.java
// public interface IResultInterceptor {
// /**
// * 是否拦截结果
// * @param result
// * @return true callback不会执行
// */
// boolean intercept(Result<?> result);
// }
// Path: glin/src/main/java/org/loader/glin/helper/ClientHelper.java
import org.loader.glin.Callback;
import org.loader.glin.RawResult;
import org.loader.glin.Result;
import org.loader.glin.cache.ICacheProvider;
import org.loader.glin.factory.ParserFactory;
import org.loader.glin.interceptor.IResultInterceptor;
import java.util.List;
package org.loader.glin.helper;
/**
* ClientHelper, useful when you convert response, cache your data and intercept your callback
*/
public final class ClientHelper {
private ParserFactory mParserFactory;
private ICacheProvider mCacheProvider;
private IResultInterceptor mResultInterceptor;
public ClientHelper parserFactory(ParserFactory parserFactory) {
mParserFactory = parserFactory;
return this;
}
public ClientHelper cacheProvider(ICacheProvider cacheProvider) {
mCacheProvider = cacheProvider;
return this;
}
public ClientHelper resultInterceptor(IResultInterceptor resultInterceptor) {
mResultInterceptor = resultInterceptor;
return this;
}
/**
* convert the http response to Result
* @param callback
* @param netResult
* @param <T>
* @return return the result
*/ | public <T> Result<T> parseResponse(Callback<T> callback, RawResult netResult) { |
qibin0506/Glin | glin/src/main/java/org/loader/glin/helper/ClientHelper.java | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/RawResult.java
// public class RawResult {
// private int statusCode;
// private String message;
// private String response;
//
// public RawResult() {}
//
// public RawResult(int statusCode, String message, String response) {
// this.statusCode = statusCode;
// this.message = message;
// this.response = response;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public void setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/Result.java
// public class Result<T> {
// private boolean ok;
// private String message;
// private T result;
// private int code;
// private Object obj;
// private boolean isCache;
//
// public boolean isOK() {
// return ok;
// }
//
// public void ok(boolean ok) {
// this.ok = ok;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String mMessage) {
// this.message = mMessage;
// }
//
// public T getResult() {
// return result;
// }
//
// public void setResult(T mResult) {
// this.result = mResult;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
//
// public Object getObj() {
// return obj;
// }
//
// public void setObj(Object obj) {
// this.obj = obj;
// }
//
// public <V> V assertGetObj() {
// return (V) getObj();
// }
//
// public boolean isCache() {
// return isCache;
// }
//
// public void setCache(boolean cache) {
// isCache = cache;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("ok: ").append(ok).append("\n");
// sb.append("message: ").append(message).append("\n");
// sb.append("obj: ").append(obj).append("\n");
// sb.append("result: ").append(result).append("\n");
// sb.append("code: ").append(code).append("\n");
// sb.append("is_cache: ").append(isCache);
//
// return sb.toString();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/cache/ICacheProvider.java
// public interface ICacheProvider {
// /**
// * get cache by key of {@link #getKey(String, String)}
// * @param key key
// * @param klass type of data struct, see also {@link org.loader.glin.helper.Helper}
// * @param isList is result a List
// * @return cache data
// */
// <T> Result<T> get(String key, Class<T> klass, boolean isList);
//
// /**
// * cache data
// * @param key see {@link #getKey(String, String)}
// * @param netResult the origin result
// * @param result parsed result
// */
// <T> void put(String key, RawResult netResult, Result<T> result);
//
// /**
// * provide the key
// * @param url the request url
// * @param params the request params, maybe key1=value1&key2=value2 while your request is POST, maybe null while your request is GET, maybe json string while your request is POST Json
// * @return
// */
// String getKey(String url, String params);
// }
//
// Path: glin/src/main/java/org/loader/glin/factory/ParserFactory.java
// public interface ParserFactory {
// Parser getParser();
// Parser getListParser();
// }
//
// Path: glin/src/main/java/org/loader/glin/interceptor/IResultInterceptor.java
// public interface IResultInterceptor {
// /**
// * 是否拦截结果
// * @param result
// * @return true callback不会执行
// */
// boolean intercept(Result<?> result);
// }
| import org.loader.glin.Callback;
import org.loader.glin.RawResult;
import org.loader.glin.Result;
import org.loader.glin.cache.ICacheProvider;
import org.loader.glin.factory.ParserFactory;
import org.loader.glin.interceptor.IResultInterceptor;
import java.util.List; | package org.loader.glin.helper;
/**
* ClientHelper, useful when you convert response, cache your data and intercept your callback
*/
public final class ClientHelper {
private ParserFactory mParserFactory;
private ICacheProvider mCacheProvider;
private IResultInterceptor mResultInterceptor;
public ClientHelper parserFactory(ParserFactory parserFactory) {
mParserFactory = parserFactory;
return this;
}
public ClientHelper cacheProvider(ICacheProvider cacheProvider) {
mCacheProvider = cacheProvider;
return this;
}
public ClientHelper resultInterceptor(IResultInterceptor resultInterceptor) {
mResultInterceptor = resultInterceptor;
return this;
}
/**
* convert the http response to Result
* @param callback
* @param netResult
* @param <T>
* @return return the result
*/ | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/RawResult.java
// public class RawResult {
// private int statusCode;
// private String message;
// private String response;
//
// public RawResult() {}
//
// public RawResult(int statusCode, String message, String response) {
// this.statusCode = statusCode;
// this.message = message;
// this.response = response;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public void setStatusCode(int statusCode) {
// this.statusCode = statusCode;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public String getResponse() {
// return response;
// }
//
// public void setResponse(String response) {
// this.response = response;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/Result.java
// public class Result<T> {
// private boolean ok;
// private String message;
// private T result;
// private int code;
// private Object obj;
// private boolean isCache;
//
// public boolean isOK() {
// return ok;
// }
//
// public void ok(boolean ok) {
// this.ok = ok;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setMessage(String mMessage) {
// this.message = mMessage;
// }
//
// public T getResult() {
// return result;
// }
//
// public void setResult(T mResult) {
// this.result = mResult;
// }
//
// public int getCode() {
// return code;
// }
//
// public void setCode(int code) {
// this.code = code;
// }
//
// public Object getObj() {
// return obj;
// }
//
// public void setObj(Object obj) {
// this.obj = obj;
// }
//
// public <V> V assertGetObj() {
// return (V) getObj();
// }
//
// public boolean isCache() {
// return isCache;
// }
//
// public void setCache(boolean cache) {
// isCache = cache;
// }
//
// @Override
// public String toString() {
// StringBuilder sb = new StringBuilder();
// sb.append("ok: ").append(ok).append("\n");
// sb.append("message: ").append(message).append("\n");
// sb.append("obj: ").append(obj).append("\n");
// sb.append("result: ").append(result).append("\n");
// sb.append("code: ").append(code).append("\n");
// sb.append("is_cache: ").append(isCache);
//
// return sb.toString();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/cache/ICacheProvider.java
// public interface ICacheProvider {
// /**
// * get cache by key of {@link #getKey(String, String)}
// * @param key key
// * @param klass type of data struct, see also {@link org.loader.glin.helper.Helper}
// * @param isList is result a List
// * @return cache data
// */
// <T> Result<T> get(String key, Class<T> klass, boolean isList);
//
// /**
// * cache data
// * @param key see {@link #getKey(String, String)}
// * @param netResult the origin result
// * @param result parsed result
// */
// <T> void put(String key, RawResult netResult, Result<T> result);
//
// /**
// * provide the key
// * @param url the request url
// * @param params the request params, maybe key1=value1&key2=value2 while your request is POST, maybe null while your request is GET, maybe json string while your request is POST Json
// * @return
// */
// String getKey(String url, String params);
// }
//
// Path: glin/src/main/java/org/loader/glin/factory/ParserFactory.java
// public interface ParserFactory {
// Parser getParser();
// Parser getListParser();
// }
//
// Path: glin/src/main/java/org/loader/glin/interceptor/IResultInterceptor.java
// public interface IResultInterceptor {
// /**
// * 是否拦截结果
// * @param result
// * @return true callback不会执行
// */
// boolean intercept(Result<?> result);
// }
// Path: glin/src/main/java/org/loader/glin/helper/ClientHelper.java
import org.loader.glin.Callback;
import org.loader.glin.RawResult;
import org.loader.glin.Result;
import org.loader.glin.cache.ICacheProvider;
import org.loader.glin.factory.ParserFactory;
import org.loader.glin.interceptor.IResultInterceptor;
import java.util.List;
package org.loader.glin.helper;
/**
* ClientHelper, useful when you convert response, cache your data and intercept your callback
*/
public final class ClientHelper {
private ParserFactory mParserFactory;
private ICacheProvider mCacheProvider;
private IResultInterceptor mResultInterceptor;
public ClientHelper parserFactory(ParserFactory parserFactory) {
mParserFactory = parserFactory;
return this;
}
public ClientHelper cacheProvider(ICacheProvider cacheProvider) {
mCacheProvider = cacheProvider;
return this;
}
public ClientHelper resultInterceptor(IResultInterceptor resultInterceptor) {
mResultInterceptor = resultInterceptor;
return this;
}
/**
* convert the http response to Result
* @param callback
* @param netResult
* @param <T>
* @return return the result
*/ | public <T> Result<T> parseResponse(Callback<T> callback, RawResult netResult) { |
qibin0506/Glin | glin/src/main/java/org/loader/glin/call/GetCall.java | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/Params.java
// public class Params {
//
// public static final String DEFAULT_JSON_KEY = "json";
//
// private LinkedHashMap<String, String> mParams;
// private LinkedHashMap<String, File> mFiles;
//
// public Params() {
// mParams = new LinkedHashMap<>();
// mFiles = new LinkedHashMap<>();
// }
//
// public Params(String key, Object value) {
// this();
// add(key, value);
// }
//
// public Params add(String key, Object value) {
// if (key == null) { return this;}
// if (value == null) { mParams.put(key, null);}
// else if (value instanceof File) { mFiles.put(key, (File) value);}
// else { mParams.put(key, value.toString());}
// return this;
// }
//
// public LinkedHashMap<String, String> get() {
// return mParams;
// }
//
// public String getParams(String key) {
// return mParams.get(key);
// }
//
// public File getFile(String key) {
// return mFiles.get(key);
// }
//
// public LinkedHashMap<String, File> files() {
// return mFiles;
// }
//
// public void remove(String key) {
// if (mParams.containsKey(key)) { mParams.remove(key);}
// if (mFiles.containsKey(key)) { mFiles.remove(key);}
// }
//
// public String encode() {
// String query = null;
// for (Map.Entry<String, String> entry : mParams.entrySet()) {
// if (query == null) { query = entry.getKey() + "=" + entry.getValue();}
// else { query += "&" + entry.getKey() + "=" + entry.getValue();}
// }
//
// return query;
// }
//
// public Iterator<String> iterator() {
// return mParams.keySet().iterator();
// }
//
// public Iterator<String> fileIterator() {
// return mFiles.keySet().iterator();
// }
//
// public boolean isEmpty() {
// return mParams.isEmpty() && mFiles.isEmpty();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/client/IClient.java
// public interface IClient extends IRequest {
//
// void cancel(final Object tag);
//
// void parserFactory(ParserFactory factory);
//
// LinkedHashMap<String, String> headers();
//
// void resultInterceptor(IResultInterceptor interceptor);
//
// void cacheProvider(ICacheProvider provider);
//
// void timeout(long ms);
// }
| import org.loader.glin.Callback;
import org.loader.glin.Params;
import org.loader.glin.client.IClient; | package org.loader.glin.call;
/**
* Created by qibin on 2016/7/13.
*/
public class GetCall<T> extends Call<T> {
public GetCall(IClient client, String url, | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/Params.java
// public class Params {
//
// public static final String DEFAULT_JSON_KEY = "json";
//
// private LinkedHashMap<String, String> mParams;
// private LinkedHashMap<String, File> mFiles;
//
// public Params() {
// mParams = new LinkedHashMap<>();
// mFiles = new LinkedHashMap<>();
// }
//
// public Params(String key, Object value) {
// this();
// add(key, value);
// }
//
// public Params add(String key, Object value) {
// if (key == null) { return this;}
// if (value == null) { mParams.put(key, null);}
// else if (value instanceof File) { mFiles.put(key, (File) value);}
// else { mParams.put(key, value.toString());}
// return this;
// }
//
// public LinkedHashMap<String, String> get() {
// return mParams;
// }
//
// public String getParams(String key) {
// return mParams.get(key);
// }
//
// public File getFile(String key) {
// return mFiles.get(key);
// }
//
// public LinkedHashMap<String, File> files() {
// return mFiles;
// }
//
// public void remove(String key) {
// if (mParams.containsKey(key)) { mParams.remove(key);}
// if (mFiles.containsKey(key)) { mFiles.remove(key);}
// }
//
// public String encode() {
// String query = null;
// for (Map.Entry<String, String> entry : mParams.entrySet()) {
// if (query == null) { query = entry.getKey() + "=" + entry.getValue();}
// else { query += "&" + entry.getKey() + "=" + entry.getValue();}
// }
//
// return query;
// }
//
// public Iterator<String> iterator() {
// return mParams.keySet().iterator();
// }
//
// public Iterator<String> fileIterator() {
// return mFiles.keySet().iterator();
// }
//
// public boolean isEmpty() {
// return mParams.isEmpty() && mFiles.isEmpty();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/client/IClient.java
// public interface IClient extends IRequest {
//
// void cancel(final Object tag);
//
// void parserFactory(ParserFactory factory);
//
// LinkedHashMap<String, String> headers();
//
// void resultInterceptor(IResultInterceptor interceptor);
//
// void cacheProvider(ICacheProvider provider);
//
// void timeout(long ms);
// }
// Path: glin/src/main/java/org/loader/glin/call/GetCall.java
import org.loader.glin.Callback;
import org.loader.glin.Params;
import org.loader.glin.client.IClient;
package org.loader.glin.call;
/**
* Created by qibin on 2016/7/13.
*/
public class GetCall<T> extends Call<T> {
public GetCall(IClient client, String url, | Params params, Object tag, |
qibin0506/Glin | glin/src/main/java/org/loader/glin/call/GetCall.java | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/Params.java
// public class Params {
//
// public static final String DEFAULT_JSON_KEY = "json";
//
// private LinkedHashMap<String, String> mParams;
// private LinkedHashMap<String, File> mFiles;
//
// public Params() {
// mParams = new LinkedHashMap<>();
// mFiles = new LinkedHashMap<>();
// }
//
// public Params(String key, Object value) {
// this();
// add(key, value);
// }
//
// public Params add(String key, Object value) {
// if (key == null) { return this;}
// if (value == null) { mParams.put(key, null);}
// else if (value instanceof File) { mFiles.put(key, (File) value);}
// else { mParams.put(key, value.toString());}
// return this;
// }
//
// public LinkedHashMap<String, String> get() {
// return mParams;
// }
//
// public String getParams(String key) {
// return mParams.get(key);
// }
//
// public File getFile(String key) {
// return mFiles.get(key);
// }
//
// public LinkedHashMap<String, File> files() {
// return mFiles;
// }
//
// public void remove(String key) {
// if (mParams.containsKey(key)) { mParams.remove(key);}
// if (mFiles.containsKey(key)) { mFiles.remove(key);}
// }
//
// public String encode() {
// String query = null;
// for (Map.Entry<String, String> entry : mParams.entrySet()) {
// if (query == null) { query = entry.getKey() + "=" + entry.getValue();}
// else { query += "&" + entry.getKey() + "=" + entry.getValue();}
// }
//
// return query;
// }
//
// public Iterator<String> iterator() {
// return mParams.keySet().iterator();
// }
//
// public Iterator<String> fileIterator() {
// return mFiles.keySet().iterator();
// }
//
// public boolean isEmpty() {
// return mParams.isEmpty() && mFiles.isEmpty();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/client/IClient.java
// public interface IClient extends IRequest {
//
// void cancel(final Object tag);
//
// void parserFactory(ParserFactory factory);
//
// LinkedHashMap<String, String> headers();
//
// void resultInterceptor(IResultInterceptor interceptor);
//
// void cacheProvider(ICacheProvider provider);
//
// void timeout(long ms);
// }
| import org.loader.glin.Callback;
import org.loader.glin.Params;
import org.loader.glin.client.IClient; | package org.loader.glin.call;
/**
* Created by qibin on 2016/7/13.
*/
public class GetCall<T> extends Call<T> {
public GetCall(IClient client, String url,
Params params, Object tag,
boolean cache) {
super(client, url, params, tag, cache);
}
@Override | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/Params.java
// public class Params {
//
// public static final String DEFAULT_JSON_KEY = "json";
//
// private LinkedHashMap<String, String> mParams;
// private LinkedHashMap<String, File> mFiles;
//
// public Params() {
// mParams = new LinkedHashMap<>();
// mFiles = new LinkedHashMap<>();
// }
//
// public Params(String key, Object value) {
// this();
// add(key, value);
// }
//
// public Params add(String key, Object value) {
// if (key == null) { return this;}
// if (value == null) { mParams.put(key, null);}
// else if (value instanceof File) { mFiles.put(key, (File) value);}
// else { mParams.put(key, value.toString());}
// return this;
// }
//
// public LinkedHashMap<String, String> get() {
// return mParams;
// }
//
// public String getParams(String key) {
// return mParams.get(key);
// }
//
// public File getFile(String key) {
// return mFiles.get(key);
// }
//
// public LinkedHashMap<String, File> files() {
// return mFiles;
// }
//
// public void remove(String key) {
// if (mParams.containsKey(key)) { mParams.remove(key);}
// if (mFiles.containsKey(key)) { mFiles.remove(key);}
// }
//
// public String encode() {
// String query = null;
// for (Map.Entry<String, String> entry : mParams.entrySet()) {
// if (query == null) { query = entry.getKey() + "=" + entry.getValue();}
// else { query += "&" + entry.getKey() + "=" + entry.getValue();}
// }
//
// return query;
// }
//
// public Iterator<String> iterator() {
// return mParams.keySet().iterator();
// }
//
// public Iterator<String> fileIterator() {
// return mFiles.keySet().iterator();
// }
//
// public boolean isEmpty() {
// return mParams.isEmpty() && mFiles.isEmpty();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/client/IClient.java
// public interface IClient extends IRequest {
//
// void cancel(final Object tag);
//
// void parserFactory(ParserFactory factory);
//
// LinkedHashMap<String, String> headers();
//
// void resultInterceptor(IResultInterceptor interceptor);
//
// void cacheProvider(ICacheProvider provider);
//
// void timeout(long ms);
// }
// Path: glin/src/main/java/org/loader/glin/call/GetCall.java
import org.loader.glin.Callback;
import org.loader.glin.Params;
import org.loader.glin.client.IClient;
package org.loader.glin.call;
/**
* Created by qibin on 2016/7/13.
*/
public class GetCall<T> extends Call<T> {
public GetCall(IClient client, String url,
Params params, Object tag,
boolean cache) {
super(client, url, params, tag, cache);
}
@Override | public void exec(final Callback<T> callback) { |
qibin0506/Glin | glin/src/main/java/org/loader/glin/chan/ChanNode.java | // Path: glin/src/main/java/org/loader/glin/Context.java
// public class Context {
// private Call<?> call;
// private Result<?> result;
// private RawResult rawResult;
//
// public Context() {}
//
// public Context(Call<?> call) {
// this.call = call;
// }
//
// public Call<?> getCall() {
// return call;
// }
//
// public void setCall(Call<?> call) {
// this.call = call;
// }
//
// public Result<?> getResult() {
// return result;
// }
//
// public void setResult(Result<?> result) {
// this.result = result;
// }
//
// public RawResult getRawResult() {
// return rawResult;
// }
//
// public void setRawResult(RawResult rawResult) {
// this.rawResult = rawResult;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/call/Call.java
// public abstract class Call<T> {
//
// public static final int DEF_HTTP_CODE_CHAN_CANCELED = 468;
// public static final String DEF_MSG_CHAN_CANCELED = "chan canceled";
//
// protected String mUrl;
// protected Params mParams;
// protected LinkedHashMap<String, String> mHeaders;
//
// protected IClient mClient;
// protected Object mTag;
//
// protected boolean shouldCache;
//
// private ChanNode mBeforeChanNode;
// private ChanNode mAfterChanNode;
//
// private GlobalChanNode mBeforeGlobalChanNode;
// private GlobalChanNode mAfterGlobalChanNode;
//
// private Callback<T> mCallback;
//
// public Call(IClient client, String url,
// Params params, Object tag,
// boolean cache) {
// mClient = client;
// mUrl = url;
// mParams = params;
// mTag = tag;
// shouldCache = cache;
// }
//
// public Call<T> before(ChanNode chanNode) {
// if (mBeforeChanNode == null) {
// mBeforeChanNode = chanNode;
// chanNode.beforeCall(true);
// } else {
// next(chanNode, mBeforeChanNode);
// }
//
// return this;
// }
//
// public Call<T> after(ChanNode chanNode) {
// if (mAfterChanNode == null) {
// mAfterChanNode = chanNode;
// chanNode.beforeCall(false);
// } else {
// next(chanNode, mAfterChanNode);
// }
// return this;
// }
//
// public Call<T> next(ChanNode chanNode) {
// ChanNode current = mAfterChanNode == null ? mBeforeChanNode : mAfterChanNode;
// return next(chanNode, current);
// }
//
// private Call<T> next(ChanNode chanNode, ChanNode header) {
// ChanNode current = header;
//
// if (current == null) {
// throw new RuntimeException("there is no before chans, please call before() first");
// }
//
// while(current.nextChanNode() != null) {
// current = current.nextChanNode();
// }
//
// current.nextChanNode(chanNode);
// chanNode.beforeCall(current.isBeforeCall());
//
// return this;
// }
//
// public void enqueue(Callback<T> callback) {
// mCallback = callback;
//
// if (mBeforeGlobalChanNode != null) {
// before(mBeforeGlobalChanNode);
// }
//
// if (mAfterGlobalChanNode != null) {
// ChanNode after = mAfterChanNode;
// mAfterChanNode = mAfterGlobalChanNode;
// mAfterChanNode.nextChanNode(after);
// }
//
// Context ctx = new Context(this);
// callback.attach(ctx, mAfterChanNode);
//
// if (mBeforeChanNode != null) {
// mBeforeChanNode.exec(ctx);
// return;
// }
//
// exec(callback);
// }
//
// public void exec() { exec(mCallback);}
//
// public abstract void exec(Callback<T> callback);
//
// public void cancel(int code, String msg) {
// if (mCallback != null) {
// Result<T> result = new Result<>();
// result.ok(false);
// result.setCode(code);
// result.setMessage(msg);
// mCallback.onResponse(result);
// }
// }
//
// public void setGlobalChanNode(GlobalChanNode before, GlobalChanNode after) {
// mBeforeGlobalChanNode = before;
// mAfterGlobalChanNode = after;
//
// if (mBeforeGlobalChanNode != null) {
// mBeforeGlobalChanNode.beforeCall(true);
// }
//
// if (mAfterGlobalChanNode != null) {
// mAfterGlobalChanNode.beforeCall(false);
// }
// }
//
// public Call<T> header(LinkedHashMap<String, String> headers) {
// mHeaders = headers;
// return this;
// }
//
// public Call<T> shouldCache(boolean cache) {
// shouldCache = cache;
// return this;
// }
//
// public Call<T> rewriteUrl(String url) {
// mUrl = url;
// return this;
// }
//
// public LinkedHashMap<String, String> getHeaders() {
// return mHeaders;
// }
//
// public Params getParams() {
// return mParams;
// }
//
// public String getUrl() {
// return mUrl;
// }
//
// public boolean shouldCache() {
// return shouldCache;
// }
// }
| import org.loader.glin.Context;
import org.loader.glin.call.Call; | package org.loader.glin.chan;
/**
* Created by qibin on 2016/7/13.
*/
public abstract class ChanNode {
private ChanNode mNext; | // Path: glin/src/main/java/org/loader/glin/Context.java
// public class Context {
// private Call<?> call;
// private Result<?> result;
// private RawResult rawResult;
//
// public Context() {}
//
// public Context(Call<?> call) {
// this.call = call;
// }
//
// public Call<?> getCall() {
// return call;
// }
//
// public void setCall(Call<?> call) {
// this.call = call;
// }
//
// public Result<?> getResult() {
// return result;
// }
//
// public void setResult(Result<?> result) {
// this.result = result;
// }
//
// public RawResult getRawResult() {
// return rawResult;
// }
//
// public void setRawResult(RawResult rawResult) {
// this.rawResult = rawResult;
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/call/Call.java
// public abstract class Call<T> {
//
// public static final int DEF_HTTP_CODE_CHAN_CANCELED = 468;
// public static final String DEF_MSG_CHAN_CANCELED = "chan canceled";
//
// protected String mUrl;
// protected Params mParams;
// protected LinkedHashMap<String, String> mHeaders;
//
// protected IClient mClient;
// protected Object mTag;
//
// protected boolean shouldCache;
//
// private ChanNode mBeforeChanNode;
// private ChanNode mAfterChanNode;
//
// private GlobalChanNode mBeforeGlobalChanNode;
// private GlobalChanNode mAfterGlobalChanNode;
//
// private Callback<T> mCallback;
//
// public Call(IClient client, String url,
// Params params, Object tag,
// boolean cache) {
// mClient = client;
// mUrl = url;
// mParams = params;
// mTag = tag;
// shouldCache = cache;
// }
//
// public Call<T> before(ChanNode chanNode) {
// if (mBeforeChanNode == null) {
// mBeforeChanNode = chanNode;
// chanNode.beforeCall(true);
// } else {
// next(chanNode, mBeforeChanNode);
// }
//
// return this;
// }
//
// public Call<T> after(ChanNode chanNode) {
// if (mAfterChanNode == null) {
// mAfterChanNode = chanNode;
// chanNode.beforeCall(false);
// } else {
// next(chanNode, mAfterChanNode);
// }
// return this;
// }
//
// public Call<T> next(ChanNode chanNode) {
// ChanNode current = mAfterChanNode == null ? mBeforeChanNode : mAfterChanNode;
// return next(chanNode, current);
// }
//
// private Call<T> next(ChanNode chanNode, ChanNode header) {
// ChanNode current = header;
//
// if (current == null) {
// throw new RuntimeException("there is no before chans, please call before() first");
// }
//
// while(current.nextChanNode() != null) {
// current = current.nextChanNode();
// }
//
// current.nextChanNode(chanNode);
// chanNode.beforeCall(current.isBeforeCall());
//
// return this;
// }
//
// public void enqueue(Callback<T> callback) {
// mCallback = callback;
//
// if (mBeforeGlobalChanNode != null) {
// before(mBeforeGlobalChanNode);
// }
//
// if (mAfterGlobalChanNode != null) {
// ChanNode after = mAfterChanNode;
// mAfterChanNode = mAfterGlobalChanNode;
// mAfterChanNode.nextChanNode(after);
// }
//
// Context ctx = new Context(this);
// callback.attach(ctx, mAfterChanNode);
//
// if (mBeforeChanNode != null) {
// mBeforeChanNode.exec(ctx);
// return;
// }
//
// exec(callback);
// }
//
// public void exec() { exec(mCallback);}
//
// public abstract void exec(Callback<T> callback);
//
// public void cancel(int code, String msg) {
// if (mCallback != null) {
// Result<T> result = new Result<>();
// result.ok(false);
// result.setCode(code);
// result.setMessage(msg);
// mCallback.onResponse(result);
// }
// }
//
// public void setGlobalChanNode(GlobalChanNode before, GlobalChanNode after) {
// mBeforeGlobalChanNode = before;
// mAfterGlobalChanNode = after;
//
// if (mBeforeGlobalChanNode != null) {
// mBeforeGlobalChanNode.beforeCall(true);
// }
//
// if (mAfterGlobalChanNode != null) {
// mAfterGlobalChanNode.beforeCall(false);
// }
// }
//
// public Call<T> header(LinkedHashMap<String, String> headers) {
// mHeaders = headers;
// return this;
// }
//
// public Call<T> shouldCache(boolean cache) {
// shouldCache = cache;
// return this;
// }
//
// public Call<T> rewriteUrl(String url) {
// mUrl = url;
// return this;
// }
//
// public LinkedHashMap<String, String> getHeaders() {
// return mHeaders;
// }
//
// public Params getParams() {
// return mParams;
// }
//
// public String getUrl() {
// return mUrl;
// }
//
// public boolean shouldCache() {
// return shouldCache;
// }
// }
// Path: glin/src/main/java/org/loader/glin/chan/ChanNode.java
import org.loader.glin.Context;
import org.loader.glin.call.Call;
package org.loader.glin.chan;
/**
* Created by qibin on 2016/7/13.
*/
public abstract class ChanNode {
private ChanNode mNext; | private Context mContext; |
qibin0506/Glin | glinsample/src/main/java/org/loader/glinsample/api/Api.java | // Path: glin/src/main/java/org/loader/glin/call/Call.java
// public abstract class Call<T> {
//
// public static final int DEF_HTTP_CODE_CHAN_CANCELED = 468;
// public static final String DEF_MSG_CHAN_CANCELED = "chan canceled";
//
// protected String mUrl;
// protected Params mParams;
// protected LinkedHashMap<String, String> mHeaders;
//
// protected IClient mClient;
// protected Object mTag;
//
// protected boolean shouldCache;
//
// private ChanNode mBeforeChanNode;
// private ChanNode mAfterChanNode;
//
// private GlobalChanNode mBeforeGlobalChanNode;
// private GlobalChanNode mAfterGlobalChanNode;
//
// private Callback<T> mCallback;
//
// public Call(IClient client, String url,
// Params params, Object tag,
// boolean cache) {
// mClient = client;
// mUrl = url;
// mParams = params;
// mTag = tag;
// shouldCache = cache;
// }
//
// public Call<T> before(ChanNode chanNode) {
// if (mBeforeChanNode == null) {
// mBeforeChanNode = chanNode;
// chanNode.beforeCall(true);
// } else {
// next(chanNode, mBeforeChanNode);
// }
//
// return this;
// }
//
// public Call<T> after(ChanNode chanNode) {
// if (mAfterChanNode == null) {
// mAfterChanNode = chanNode;
// chanNode.beforeCall(false);
// } else {
// next(chanNode, mAfterChanNode);
// }
// return this;
// }
//
// public Call<T> next(ChanNode chanNode) {
// ChanNode current = mAfterChanNode == null ? mBeforeChanNode : mAfterChanNode;
// return next(chanNode, current);
// }
//
// private Call<T> next(ChanNode chanNode, ChanNode header) {
// ChanNode current = header;
//
// if (current == null) {
// throw new RuntimeException("there is no before chans, please call before() first");
// }
//
// while(current.nextChanNode() != null) {
// current = current.nextChanNode();
// }
//
// current.nextChanNode(chanNode);
// chanNode.beforeCall(current.isBeforeCall());
//
// return this;
// }
//
// public void enqueue(Callback<T> callback) {
// mCallback = callback;
//
// if (mBeforeGlobalChanNode != null) {
// before(mBeforeGlobalChanNode);
// }
//
// if (mAfterGlobalChanNode != null) {
// ChanNode after = mAfterChanNode;
// mAfterChanNode = mAfterGlobalChanNode;
// mAfterChanNode.nextChanNode(after);
// }
//
// Context ctx = new Context(this);
// callback.attach(ctx, mAfterChanNode);
//
// if (mBeforeChanNode != null) {
// mBeforeChanNode.exec(ctx);
// return;
// }
//
// exec(callback);
// }
//
// public void exec() { exec(mCallback);}
//
// public abstract void exec(Callback<T> callback);
//
// public void cancel(int code, String msg) {
// if (mCallback != null) {
// Result<T> result = new Result<>();
// result.ok(false);
// result.setCode(code);
// result.setMessage(msg);
// mCallback.onResponse(result);
// }
// }
//
// public void setGlobalChanNode(GlobalChanNode before, GlobalChanNode after) {
// mBeforeGlobalChanNode = before;
// mAfterGlobalChanNode = after;
//
// if (mBeforeGlobalChanNode != null) {
// mBeforeGlobalChanNode.beforeCall(true);
// }
//
// if (mAfterGlobalChanNode != null) {
// mAfterGlobalChanNode.beforeCall(false);
// }
// }
//
// public Call<T> header(LinkedHashMap<String, String> headers) {
// mHeaders = headers;
// return this;
// }
//
// public Call<T> shouldCache(boolean cache) {
// shouldCache = cache;
// return this;
// }
//
// public Call<T> rewriteUrl(String url) {
// mUrl = url;
// return this;
// }
//
// public LinkedHashMap<String, String> getHeaders() {
// return mHeaders;
// }
//
// public Params getParams() {
// return mParams;
// }
//
// public String getUrl() {
// return mUrl;
// }
//
// public boolean shouldCache() {
// return shouldCache;
// }
// }
//
// Path: glinsample/src/main/java/org/loader/glinsample/bean/UserInfo.java
// public class UserInfo implements Serializable {
// private String id;
// private String name;
// private int age;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getAge() {
// return age;
// }
//
// public void setAge(int age) {
// this.age = age;
// }
// }
| import org.loader.glin.annotation.Arg;
import org.loader.glin.annotation.GET;
import org.loader.glin.annotation.POST;
import org.loader.glin.annotation.Path;
import org.loader.glin.annotation.ShouldCache;
import org.loader.glin.call.Call;
import org.loader.glinsample.bean.UserInfo; | package org.loader.glinsample.api;
public interface Api {
@GET("/user/{:path}/") | // Path: glin/src/main/java/org/loader/glin/call/Call.java
// public abstract class Call<T> {
//
// public static final int DEF_HTTP_CODE_CHAN_CANCELED = 468;
// public static final String DEF_MSG_CHAN_CANCELED = "chan canceled";
//
// protected String mUrl;
// protected Params mParams;
// protected LinkedHashMap<String, String> mHeaders;
//
// protected IClient mClient;
// protected Object mTag;
//
// protected boolean shouldCache;
//
// private ChanNode mBeforeChanNode;
// private ChanNode mAfterChanNode;
//
// private GlobalChanNode mBeforeGlobalChanNode;
// private GlobalChanNode mAfterGlobalChanNode;
//
// private Callback<T> mCallback;
//
// public Call(IClient client, String url,
// Params params, Object tag,
// boolean cache) {
// mClient = client;
// mUrl = url;
// mParams = params;
// mTag = tag;
// shouldCache = cache;
// }
//
// public Call<T> before(ChanNode chanNode) {
// if (mBeforeChanNode == null) {
// mBeforeChanNode = chanNode;
// chanNode.beforeCall(true);
// } else {
// next(chanNode, mBeforeChanNode);
// }
//
// return this;
// }
//
// public Call<T> after(ChanNode chanNode) {
// if (mAfterChanNode == null) {
// mAfterChanNode = chanNode;
// chanNode.beforeCall(false);
// } else {
// next(chanNode, mAfterChanNode);
// }
// return this;
// }
//
// public Call<T> next(ChanNode chanNode) {
// ChanNode current = mAfterChanNode == null ? mBeforeChanNode : mAfterChanNode;
// return next(chanNode, current);
// }
//
// private Call<T> next(ChanNode chanNode, ChanNode header) {
// ChanNode current = header;
//
// if (current == null) {
// throw new RuntimeException("there is no before chans, please call before() first");
// }
//
// while(current.nextChanNode() != null) {
// current = current.nextChanNode();
// }
//
// current.nextChanNode(chanNode);
// chanNode.beforeCall(current.isBeforeCall());
//
// return this;
// }
//
// public void enqueue(Callback<T> callback) {
// mCallback = callback;
//
// if (mBeforeGlobalChanNode != null) {
// before(mBeforeGlobalChanNode);
// }
//
// if (mAfterGlobalChanNode != null) {
// ChanNode after = mAfterChanNode;
// mAfterChanNode = mAfterGlobalChanNode;
// mAfterChanNode.nextChanNode(after);
// }
//
// Context ctx = new Context(this);
// callback.attach(ctx, mAfterChanNode);
//
// if (mBeforeChanNode != null) {
// mBeforeChanNode.exec(ctx);
// return;
// }
//
// exec(callback);
// }
//
// public void exec() { exec(mCallback);}
//
// public abstract void exec(Callback<T> callback);
//
// public void cancel(int code, String msg) {
// if (mCallback != null) {
// Result<T> result = new Result<>();
// result.ok(false);
// result.setCode(code);
// result.setMessage(msg);
// mCallback.onResponse(result);
// }
// }
//
// public void setGlobalChanNode(GlobalChanNode before, GlobalChanNode after) {
// mBeforeGlobalChanNode = before;
// mAfterGlobalChanNode = after;
//
// if (mBeforeGlobalChanNode != null) {
// mBeforeGlobalChanNode.beforeCall(true);
// }
//
// if (mAfterGlobalChanNode != null) {
// mAfterGlobalChanNode.beforeCall(false);
// }
// }
//
// public Call<T> header(LinkedHashMap<String, String> headers) {
// mHeaders = headers;
// return this;
// }
//
// public Call<T> shouldCache(boolean cache) {
// shouldCache = cache;
// return this;
// }
//
// public Call<T> rewriteUrl(String url) {
// mUrl = url;
// return this;
// }
//
// public LinkedHashMap<String, String> getHeaders() {
// return mHeaders;
// }
//
// public Params getParams() {
// return mParams;
// }
//
// public String getUrl() {
// return mUrl;
// }
//
// public boolean shouldCache() {
// return shouldCache;
// }
// }
//
// Path: glinsample/src/main/java/org/loader/glinsample/bean/UserInfo.java
// public class UserInfo implements Serializable {
// private String id;
// private String name;
// private int age;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getAge() {
// return age;
// }
//
// public void setAge(int age) {
// this.age = age;
// }
// }
// Path: glinsample/src/main/java/org/loader/glinsample/api/Api.java
import org.loader.glin.annotation.Arg;
import org.loader.glin.annotation.GET;
import org.loader.glin.annotation.POST;
import org.loader.glin.annotation.Path;
import org.loader.glin.annotation.ShouldCache;
import org.loader.glin.call.Call;
import org.loader.glinsample.bean.UserInfo;
package org.loader.glinsample.api;
public interface Api {
@GET("/user/{:path}/") | Call<UserInfo> uid(@Path("path") String path); |
qibin0506/Glin | glinsample/src/main/java/org/loader/glinsample/api/Api.java | // Path: glin/src/main/java/org/loader/glin/call/Call.java
// public abstract class Call<T> {
//
// public static final int DEF_HTTP_CODE_CHAN_CANCELED = 468;
// public static final String DEF_MSG_CHAN_CANCELED = "chan canceled";
//
// protected String mUrl;
// protected Params mParams;
// protected LinkedHashMap<String, String> mHeaders;
//
// protected IClient mClient;
// protected Object mTag;
//
// protected boolean shouldCache;
//
// private ChanNode mBeforeChanNode;
// private ChanNode mAfterChanNode;
//
// private GlobalChanNode mBeforeGlobalChanNode;
// private GlobalChanNode mAfterGlobalChanNode;
//
// private Callback<T> mCallback;
//
// public Call(IClient client, String url,
// Params params, Object tag,
// boolean cache) {
// mClient = client;
// mUrl = url;
// mParams = params;
// mTag = tag;
// shouldCache = cache;
// }
//
// public Call<T> before(ChanNode chanNode) {
// if (mBeforeChanNode == null) {
// mBeforeChanNode = chanNode;
// chanNode.beforeCall(true);
// } else {
// next(chanNode, mBeforeChanNode);
// }
//
// return this;
// }
//
// public Call<T> after(ChanNode chanNode) {
// if (mAfterChanNode == null) {
// mAfterChanNode = chanNode;
// chanNode.beforeCall(false);
// } else {
// next(chanNode, mAfterChanNode);
// }
// return this;
// }
//
// public Call<T> next(ChanNode chanNode) {
// ChanNode current = mAfterChanNode == null ? mBeforeChanNode : mAfterChanNode;
// return next(chanNode, current);
// }
//
// private Call<T> next(ChanNode chanNode, ChanNode header) {
// ChanNode current = header;
//
// if (current == null) {
// throw new RuntimeException("there is no before chans, please call before() first");
// }
//
// while(current.nextChanNode() != null) {
// current = current.nextChanNode();
// }
//
// current.nextChanNode(chanNode);
// chanNode.beforeCall(current.isBeforeCall());
//
// return this;
// }
//
// public void enqueue(Callback<T> callback) {
// mCallback = callback;
//
// if (mBeforeGlobalChanNode != null) {
// before(mBeforeGlobalChanNode);
// }
//
// if (mAfterGlobalChanNode != null) {
// ChanNode after = mAfterChanNode;
// mAfterChanNode = mAfterGlobalChanNode;
// mAfterChanNode.nextChanNode(after);
// }
//
// Context ctx = new Context(this);
// callback.attach(ctx, mAfterChanNode);
//
// if (mBeforeChanNode != null) {
// mBeforeChanNode.exec(ctx);
// return;
// }
//
// exec(callback);
// }
//
// public void exec() { exec(mCallback);}
//
// public abstract void exec(Callback<T> callback);
//
// public void cancel(int code, String msg) {
// if (mCallback != null) {
// Result<T> result = new Result<>();
// result.ok(false);
// result.setCode(code);
// result.setMessage(msg);
// mCallback.onResponse(result);
// }
// }
//
// public void setGlobalChanNode(GlobalChanNode before, GlobalChanNode after) {
// mBeforeGlobalChanNode = before;
// mAfterGlobalChanNode = after;
//
// if (mBeforeGlobalChanNode != null) {
// mBeforeGlobalChanNode.beforeCall(true);
// }
//
// if (mAfterGlobalChanNode != null) {
// mAfterGlobalChanNode.beforeCall(false);
// }
// }
//
// public Call<T> header(LinkedHashMap<String, String> headers) {
// mHeaders = headers;
// return this;
// }
//
// public Call<T> shouldCache(boolean cache) {
// shouldCache = cache;
// return this;
// }
//
// public Call<T> rewriteUrl(String url) {
// mUrl = url;
// return this;
// }
//
// public LinkedHashMap<String, String> getHeaders() {
// return mHeaders;
// }
//
// public Params getParams() {
// return mParams;
// }
//
// public String getUrl() {
// return mUrl;
// }
//
// public boolean shouldCache() {
// return shouldCache;
// }
// }
//
// Path: glinsample/src/main/java/org/loader/glinsample/bean/UserInfo.java
// public class UserInfo implements Serializable {
// private String id;
// private String name;
// private int age;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getAge() {
// return age;
// }
//
// public void setAge(int age) {
// this.age = age;
// }
// }
| import org.loader.glin.annotation.Arg;
import org.loader.glin.annotation.GET;
import org.loader.glin.annotation.POST;
import org.loader.glin.annotation.Path;
import org.loader.glin.annotation.ShouldCache;
import org.loader.glin.call.Call;
import org.loader.glinsample.bean.UserInfo; | package org.loader.glinsample.api;
public interface Api {
@GET("/user/{:path}/") | // Path: glin/src/main/java/org/loader/glin/call/Call.java
// public abstract class Call<T> {
//
// public static final int DEF_HTTP_CODE_CHAN_CANCELED = 468;
// public static final String DEF_MSG_CHAN_CANCELED = "chan canceled";
//
// protected String mUrl;
// protected Params mParams;
// protected LinkedHashMap<String, String> mHeaders;
//
// protected IClient mClient;
// protected Object mTag;
//
// protected boolean shouldCache;
//
// private ChanNode mBeforeChanNode;
// private ChanNode mAfterChanNode;
//
// private GlobalChanNode mBeforeGlobalChanNode;
// private GlobalChanNode mAfterGlobalChanNode;
//
// private Callback<T> mCallback;
//
// public Call(IClient client, String url,
// Params params, Object tag,
// boolean cache) {
// mClient = client;
// mUrl = url;
// mParams = params;
// mTag = tag;
// shouldCache = cache;
// }
//
// public Call<T> before(ChanNode chanNode) {
// if (mBeforeChanNode == null) {
// mBeforeChanNode = chanNode;
// chanNode.beforeCall(true);
// } else {
// next(chanNode, mBeforeChanNode);
// }
//
// return this;
// }
//
// public Call<T> after(ChanNode chanNode) {
// if (mAfterChanNode == null) {
// mAfterChanNode = chanNode;
// chanNode.beforeCall(false);
// } else {
// next(chanNode, mAfterChanNode);
// }
// return this;
// }
//
// public Call<T> next(ChanNode chanNode) {
// ChanNode current = mAfterChanNode == null ? mBeforeChanNode : mAfterChanNode;
// return next(chanNode, current);
// }
//
// private Call<T> next(ChanNode chanNode, ChanNode header) {
// ChanNode current = header;
//
// if (current == null) {
// throw new RuntimeException("there is no before chans, please call before() first");
// }
//
// while(current.nextChanNode() != null) {
// current = current.nextChanNode();
// }
//
// current.nextChanNode(chanNode);
// chanNode.beforeCall(current.isBeforeCall());
//
// return this;
// }
//
// public void enqueue(Callback<T> callback) {
// mCallback = callback;
//
// if (mBeforeGlobalChanNode != null) {
// before(mBeforeGlobalChanNode);
// }
//
// if (mAfterGlobalChanNode != null) {
// ChanNode after = mAfterChanNode;
// mAfterChanNode = mAfterGlobalChanNode;
// mAfterChanNode.nextChanNode(after);
// }
//
// Context ctx = new Context(this);
// callback.attach(ctx, mAfterChanNode);
//
// if (mBeforeChanNode != null) {
// mBeforeChanNode.exec(ctx);
// return;
// }
//
// exec(callback);
// }
//
// public void exec() { exec(mCallback);}
//
// public abstract void exec(Callback<T> callback);
//
// public void cancel(int code, String msg) {
// if (mCallback != null) {
// Result<T> result = new Result<>();
// result.ok(false);
// result.setCode(code);
// result.setMessage(msg);
// mCallback.onResponse(result);
// }
// }
//
// public void setGlobalChanNode(GlobalChanNode before, GlobalChanNode after) {
// mBeforeGlobalChanNode = before;
// mAfterGlobalChanNode = after;
//
// if (mBeforeGlobalChanNode != null) {
// mBeforeGlobalChanNode.beforeCall(true);
// }
//
// if (mAfterGlobalChanNode != null) {
// mAfterGlobalChanNode.beforeCall(false);
// }
// }
//
// public Call<T> header(LinkedHashMap<String, String> headers) {
// mHeaders = headers;
// return this;
// }
//
// public Call<T> shouldCache(boolean cache) {
// shouldCache = cache;
// return this;
// }
//
// public Call<T> rewriteUrl(String url) {
// mUrl = url;
// return this;
// }
//
// public LinkedHashMap<String, String> getHeaders() {
// return mHeaders;
// }
//
// public Params getParams() {
// return mParams;
// }
//
// public String getUrl() {
// return mUrl;
// }
//
// public boolean shouldCache() {
// return shouldCache;
// }
// }
//
// Path: glinsample/src/main/java/org/loader/glinsample/bean/UserInfo.java
// public class UserInfo implements Serializable {
// private String id;
// private String name;
// private int age;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getAge() {
// return age;
// }
//
// public void setAge(int age) {
// this.age = age;
// }
// }
// Path: glinsample/src/main/java/org/loader/glinsample/api/Api.java
import org.loader.glin.annotation.Arg;
import org.loader.glin.annotation.GET;
import org.loader.glin.annotation.POST;
import org.loader.glin.annotation.Path;
import org.loader.glin.annotation.ShouldCache;
import org.loader.glin.call.Call;
import org.loader.glinsample.bean.UserInfo;
package org.loader.glinsample.api;
public interface Api {
@GET("/user/{:path}/") | Call<UserInfo> uid(@Path("path") String path); |
qibin0506/Glin | glin/src/main/java/org/loader/glin/call/DelCall.java | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/Params.java
// public class Params {
//
// public static final String DEFAULT_JSON_KEY = "json";
//
// private LinkedHashMap<String, String> mParams;
// private LinkedHashMap<String, File> mFiles;
//
// public Params() {
// mParams = new LinkedHashMap<>();
// mFiles = new LinkedHashMap<>();
// }
//
// public Params(String key, Object value) {
// this();
// add(key, value);
// }
//
// public Params add(String key, Object value) {
// if (key == null) { return this;}
// if (value == null) { mParams.put(key, null);}
// else if (value instanceof File) { mFiles.put(key, (File) value);}
// else { mParams.put(key, value.toString());}
// return this;
// }
//
// public LinkedHashMap<String, String> get() {
// return mParams;
// }
//
// public String getParams(String key) {
// return mParams.get(key);
// }
//
// public File getFile(String key) {
// return mFiles.get(key);
// }
//
// public LinkedHashMap<String, File> files() {
// return mFiles;
// }
//
// public void remove(String key) {
// if (mParams.containsKey(key)) { mParams.remove(key);}
// if (mFiles.containsKey(key)) { mFiles.remove(key);}
// }
//
// public String encode() {
// String query = null;
// for (Map.Entry<String, String> entry : mParams.entrySet()) {
// if (query == null) { query = entry.getKey() + "=" + entry.getValue();}
// else { query += "&" + entry.getKey() + "=" + entry.getValue();}
// }
//
// return query;
// }
//
// public Iterator<String> iterator() {
// return mParams.keySet().iterator();
// }
//
// public Iterator<String> fileIterator() {
// return mFiles.keySet().iterator();
// }
//
// public boolean isEmpty() {
// return mParams.isEmpty() && mFiles.isEmpty();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/client/IClient.java
// public interface IClient extends IRequest {
//
// void cancel(final Object tag);
//
// void parserFactory(ParserFactory factory);
//
// LinkedHashMap<String, String> headers();
//
// void resultInterceptor(IResultInterceptor interceptor);
//
// void cacheProvider(ICacheProvider provider);
//
// void timeout(long ms);
// }
| import org.loader.glin.Callback;
import org.loader.glin.Params;
import org.loader.glin.client.IClient; | package org.loader.glin.call;
/**
* Created by qibin on 2016/7/14.
*/
public class DelCall<T> extends Call<T> {
public DelCall(IClient client, String url, | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/Params.java
// public class Params {
//
// public static final String DEFAULT_JSON_KEY = "json";
//
// private LinkedHashMap<String, String> mParams;
// private LinkedHashMap<String, File> mFiles;
//
// public Params() {
// mParams = new LinkedHashMap<>();
// mFiles = new LinkedHashMap<>();
// }
//
// public Params(String key, Object value) {
// this();
// add(key, value);
// }
//
// public Params add(String key, Object value) {
// if (key == null) { return this;}
// if (value == null) { mParams.put(key, null);}
// else if (value instanceof File) { mFiles.put(key, (File) value);}
// else { mParams.put(key, value.toString());}
// return this;
// }
//
// public LinkedHashMap<String, String> get() {
// return mParams;
// }
//
// public String getParams(String key) {
// return mParams.get(key);
// }
//
// public File getFile(String key) {
// return mFiles.get(key);
// }
//
// public LinkedHashMap<String, File> files() {
// return mFiles;
// }
//
// public void remove(String key) {
// if (mParams.containsKey(key)) { mParams.remove(key);}
// if (mFiles.containsKey(key)) { mFiles.remove(key);}
// }
//
// public String encode() {
// String query = null;
// for (Map.Entry<String, String> entry : mParams.entrySet()) {
// if (query == null) { query = entry.getKey() + "=" + entry.getValue();}
// else { query += "&" + entry.getKey() + "=" + entry.getValue();}
// }
//
// return query;
// }
//
// public Iterator<String> iterator() {
// return mParams.keySet().iterator();
// }
//
// public Iterator<String> fileIterator() {
// return mFiles.keySet().iterator();
// }
//
// public boolean isEmpty() {
// return mParams.isEmpty() && mFiles.isEmpty();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/client/IClient.java
// public interface IClient extends IRequest {
//
// void cancel(final Object tag);
//
// void parserFactory(ParserFactory factory);
//
// LinkedHashMap<String, String> headers();
//
// void resultInterceptor(IResultInterceptor interceptor);
//
// void cacheProvider(ICacheProvider provider);
//
// void timeout(long ms);
// }
// Path: glin/src/main/java/org/loader/glin/call/DelCall.java
import org.loader.glin.Callback;
import org.loader.glin.Params;
import org.loader.glin.client.IClient;
package org.loader.glin.call;
/**
* Created by qibin on 2016/7/14.
*/
public class DelCall<T> extends Call<T> {
public DelCall(IClient client, String url, | Params params, Object tag, |
qibin0506/Glin | glin/src/main/java/org/loader/glin/call/DelCall.java | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/Params.java
// public class Params {
//
// public static final String DEFAULT_JSON_KEY = "json";
//
// private LinkedHashMap<String, String> mParams;
// private LinkedHashMap<String, File> mFiles;
//
// public Params() {
// mParams = new LinkedHashMap<>();
// mFiles = new LinkedHashMap<>();
// }
//
// public Params(String key, Object value) {
// this();
// add(key, value);
// }
//
// public Params add(String key, Object value) {
// if (key == null) { return this;}
// if (value == null) { mParams.put(key, null);}
// else if (value instanceof File) { mFiles.put(key, (File) value);}
// else { mParams.put(key, value.toString());}
// return this;
// }
//
// public LinkedHashMap<String, String> get() {
// return mParams;
// }
//
// public String getParams(String key) {
// return mParams.get(key);
// }
//
// public File getFile(String key) {
// return mFiles.get(key);
// }
//
// public LinkedHashMap<String, File> files() {
// return mFiles;
// }
//
// public void remove(String key) {
// if (mParams.containsKey(key)) { mParams.remove(key);}
// if (mFiles.containsKey(key)) { mFiles.remove(key);}
// }
//
// public String encode() {
// String query = null;
// for (Map.Entry<String, String> entry : mParams.entrySet()) {
// if (query == null) { query = entry.getKey() + "=" + entry.getValue();}
// else { query += "&" + entry.getKey() + "=" + entry.getValue();}
// }
//
// return query;
// }
//
// public Iterator<String> iterator() {
// return mParams.keySet().iterator();
// }
//
// public Iterator<String> fileIterator() {
// return mFiles.keySet().iterator();
// }
//
// public boolean isEmpty() {
// return mParams.isEmpty() && mFiles.isEmpty();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/client/IClient.java
// public interface IClient extends IRequest {
//
// void cancel(final Object tag);
//
// void parserFactory(ParserFactory factory);
//
// LinkedHashMap<String, String> headers();
//
// void resultInterceptor(IResultInterceptor interceptor);
//
// void cacheProvider(ICacheProvider provider);
//
// void timeout(long ms);
// }
| import org.loader.glin.Callback;
import org.loader.glin.Params;
import org.loader.glin.client.IClient; | package org.loader.glin.call;
/**
* Created by qibin on 2016/7/14.
*/
public class DelCall<T> extends Call<T> {
public DelCall(IClient client, String url,
Params params, Object tag,
boolean cache) {
super(client, url, params, tag, cache);
}
@Override | // Path: glin/src/main/java/org/loader/glin/Callback.java
// public abstract class Callback<T> {
//
// private Context mContext;
// private ChanNode mAfterChanNode;
//
// public final void attach(Context ctx, ChanNode afterChanNode) {
// mContext = ctx;
// mAfterChanNode = afterChanNode;
// }
//
// public final void afterResponse(Result<T> result, RawResult rawResult) {
// mContext.setRawResult(rawResult);
// mContext.setResult(result);
//
// if (mAfterChanNode != null) {
// mAfterChanNode.exec(mContext);
// }
// }
//
// public abstract void onResponse(Result<T> result);
// }
//
// Path: glin/src/main/java/org/loader/glin/Params.java
// public class Params {
//
// public static final String DEFAULT_JSON_KEY = "json";
//
// private LinkedHashMap<String, String> mParams;
// private LinkedHashMap<String, File> mFiles;
//
// public Params() {
// mParams = new LinkedHashMap<>();
// mFiles = new LinkedHashMap<>();
// }
//
// public Params(String key, Object value) {
// this();
// add(key, value);
// }
//
// public Params add(String key, Object value) {
// if (key == null) { return this;}
// if (value == null) { mParams.put(key, null);}
// else if (value instanceof File) { mFiles.put(key, (File) value);}
// else { mParams.put(key, value.toString());}
// return this;
// }
//
// public LinkedHashMap<String, String> get() {
// return mParams;
// }
//
// public String getParams(String key) {
// return mParams.get(key);
// }
//
// public File getFile(String key) {
// return mFiles.get(key);
// }
//
// public LinkedHashMap<String, File> files() {
// return mFiles;
// }
//
// public void remove(String key) {
// if (mParams.containsKey(key)) { mParams.remove(key);}
// if (mFiles.containsKey(key)) { mFiles.remove(key);}
// }
//
// public String encode() {
// String query = null;
// for (Map.Entry<String, String> entry : mParams.entrySet()) {
// if (query == null) { query = entry.getKey() + "=" + entry.getValue();}
// else { query += "&" + entry.getKey() + "=" + entry.getValue();}
// }
//
// return query;
// }
//
// public Iterator<String> iterator() {
// return mParams.keySet().iterator();
// }
//
// public Iterator<String> fileIterator() {
// return mFiles.keySet().iterator();
// }
//
// public boolean isEmpty() {
// return mParams.isEmpty() && mFiles.isEmpty();
// }
// }
//
// Path: glin/src/main/java/org/loader/glin/client/IClient.java
// public interface IClient extends IRequest {
//
// void cancel(final Object tag);
//
// void parserFactory(ParserFactory factory);
//
// LinkedHashMap<String, String> headers();
//
// void resultInterceptor(IResultInterceptor interceptor);
//
// void cacheProvider(ICacheProvider provider);
//
// void timeout(long ms);
// }
// Path: glin/src/main/java/org/loader/glin/call/DelCall.java
import org.loader.glin.Callback;
import org.loader.glin.Params;
import org.loader.glin.client.IClient;
package org.loader.glin.call;
/**
* Created by qibin on 2016/7/14.
*/
public class DelCall<T> extends Call<T> {
public DelCall(IClient client, String url,
Params params, Object tag,
boolean cache) {
super(client, url, params, tag, cache);
}
@Override | public void exec(Callback<T> callback) { |
CaMnter/EasyGank | app/src/main/java/com/camnter/easygank/model/impl/DataModel.java | // Path: app/src/main/java/com/camnter/easygank/bean/GankData.java
// public class GankData extends Error implements Serializable {
//
// @SerializedName("results") public ArrayList<BaseGankData> results;
// }
//
// Path: app/src/main/java/com/camnter/easygank/gank/EasyGank.java
// public class EasyGank {
//
// private static EasyGank ourInstance;
//
// private GankService gankService;
//
//
// public static EasyGank getInstance() {
// if (ourInstance == null) ourInstance = new EasyGank();
// return ourInstance;
// }
//
//
// private EasyGank() {
// OkHttpClient okHttpClient = new OkHttpClient();
// okHttpClient.setReadTimeout(7676, TimeUnit.MILLISECONDS);
//
// /*
// * 查看网络请求发送状况
// */
// if (EasyApplication.getInstance().log) {
// okHttpClient.interceptors().add(chain -> {
// Response response = chain.proceed(chain.request());
// com.orhanobut.logger.Logger.d(chain.request().urlString());
// return response;
// });
// }
//
// Retrofit retrofit = new Retrofit.Builder().baseUrl(GankApi.BASE_URL)
// .addCallAdapterFactory(
// RxJavaCallAdapterFactory.create())
// .addConverterFactory(GsonConverterFactory.create(
// EasyApplication.getInstance().gson))
// .client(okHttpClient)
// .build();
// this.gankService = retrofit.create(GankService.class);
// }
//
//
// public GankService getGankService() {
// return gankService;
// }
// }
//
// Path: app/src/main/java/com/camnter/easygank/model/IDataModel.java
// public interface IDataModel {
// /**
// * 分页查询( Android、iOS、前端、拓展资源、福利、休息视频 )数据
// *
// * @param type 数据类型
// * @param size 数据个数
// * @param page 第几页
// * @return Observable<GankData>
// */
// Observable<GankData> getData(String type, int size, int page);
// }
| import com.camnter.easygank.bean.GankData;
import com.camnter.easygank.gank.EasyGank;
import com.camnter.easygank.model.IDataModel;
import rx.Observable; | /*
* {EasyGank} Copyright (C) {2015} {CaMnter}
*
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.camnter.easygank.model.impl;
/**
* Description:DataModel
* Created by:CaMnter
* Time:2016-01-06 17:50
*/
public class DataModel implements IDataModel {
private static final DataModel ourInstance = new DataModel();
public static DataModel getInstance() {
return ourInstance;
}
private DataModel() {
}
/**
* 分页查询( Android、iOS、前端、拓展资源、福利、休息视频 )数据
*
* @param type 数据类型
* @param size 数据个数
* @param page 第几页
* @return Observable<GankData>
*/ | // Path: app/src/main/java/com/camnter/easygank/bean/GankData.java
// public class GankData extends Error implements Serializable {
//
// @SerializedName("results") public ArrayList<BaseGankData> results;
// }
//
// Path: app/src/main/java/com/camnter/easygank/gank/EasyGank.java
// public class EasyGank {
//
// private static EasyGank ourInstance;
//
// private GankService gankService;
//
//
// public static EasyGank getInstance() {
// if (ourInstance == null) ourInstance = new EasyGank();
// return ourInstance;
// }
//
//
// private EasyGank() {
// OkHttpClient okHttpClient = new OkHttpClient();
// okHttpClient.setReadTimeout(7676, TimeUnit.MILLISECONDS);
//
// /*
// * 查看网络请求发送状况
// */
// if (EasyApplication.getInstance().log) {
// okHttpClient.interceptors().add(chain -> {
// Response response = chain.proceed(chain.request());
// com.orhanobut.logger.Logger.d(chain.request().urlString());
// return response;
// });
// }
//
// Retrofit retrofit = new Retrofit.Builder().baseUrl(GankApi.BASE_URL)
// .addCallAdapterFactory(
// RxJavaCallAdapterFactory.create())
// .addConverterFactory(GsonConverterFactory.create(
// EasyApplication.getInstance().gson))
// .client(okHttpClient)
// .build();
// this.gankService = retrofit.create(GankService.class);
// }
//
//
// public GankService getGankService() {
// return gankService;
// }
// }
//
// Path: app/src/main/java/com/camnter/easygank/model/IDataModel.java
// public interface IDataModel {
// /**
// * 分页查询( Android、iOS、前端、拓展资源、福利、休息视频 )数据
// *
// * @param type 数据类型
// * @param size 数据个数
// * @param page 第几页
// * @return Observable<GankData>
// */
// Observable<GankData> getData(String type, int size, int page);
// }
// Path: app/src/main/java/com/camnter/easygank/model/impl/DataModel.java
import com.camnter.easygank.bean.GankData;
import com.camnter.easygank.gank.EasyGank;
import com.camnter.easygank.model.IDataModel;
import rx.Observable;
/*
* {EasyGank} Copyright (C) {2015} {CaMnter}
*
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.camnter.easygank.model.impl;
/**
* Description:DataModel
* Created by:CaMnter
* Time:2016-01-06 17:50
*/
public class DataModel implements IDataModel {
private static final DataModel ourInstance = new DataModel();
public static DataModel getInstance() {
return ourInstance;
}
private DataModel() {
}
/**
* 分页查询( Android、iOS、前端、拓展资源、福利、休息视频 )数据
*
* @param type 数据类型
* @param size 数据个数
* @param page 第几页
* @return Observable<GankData>
*/ | @Override public Observable<GankData> getData(String type, int size, int page) { |
CaMnter/EasyGank | app/src/main/java/com/camnter/easygank/model/impl/DataModel.java | // Path: app/src/main/java/com/camnter/easygank/bean/GankData.java
// public class GankData extends Error implements Serializable {
//
// @SerializedName("results") public ArrayList<BaseGankData> results;
// }
//
// Path: app/src/main/java/com/camnter/easygank/gank/EasyGank.java
// public class EasyGank {
//
// private static EasyGank ourInstance;
//
// private GankService gankService;
//
//
// public static EasyGank getInstance() {
// if (ourInstance == null) ourInstance = new EasyGank();
// return ourInstance;
// }
//
//
// private EasyGank() {
// OkHttpClient okHttpClient = new OkHttpClient();
// okHttpClient.setReadTimeout(7676, TimeUnit.MILLISECONDS);
//
// /*
// * 查看网络请求发送状况
// */
// if (EasyApplication.getInstance().log) {
// okHttpClient.interceptors().add(chain -> {
// Response response = chain.proceed(chain.request());
// com.orhanobut.logger.Logger.d(chain.request().urlString());
// return response;
// });
// }
//
// Retrofit retrofit = new Retrofit.Builder().baseUrl(GankApi.BASE_URL)
// .addCallAdapterFactory(
// RxJavaCallAdapterFactory.create())
// .addConverterFactory(GsonConverterFactory.create(
// EasyApplication.getInstance().gson))
// .client(okHttpClient)
// .build();
// this.gankService = retrofit.create(GankService.class);
// }
//
//
// public GankService getGankService() {
// return gankService;
// }
// }
//
// Path: app/src/main/java/com/camnter/easygank/model/IDataModel.java
// public interface IDataModel {
// /**
// * 分页查询( Android、iOS、前端、拓展资源、福利、休息视频 )数据
// *
// * @param type 数据类型
// * @param size 数据个数
// * @param page 第几页
// * @return Observable<GankData>
// */
// Observable<GankData> getData(String type, int size, int page);
// }
| import com.camnter.easygank.bean.GankData;
import com.camnter.easygank.gank.EasyGank;
import com.camnter.easygank.model.IDataModel;
import rx.Observable; | /*
* {EasyGank} Copyright (C) {2015} {CaMnter}
*
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.camnter.easygank.model.impl;
/**
* Description:DataModel
* Created by:CaMnter
* Time:2016-01-06 17:50
*/
public class DataModel implements IDataModel {
private static final DataModel ourInstance = new DataModel();
public static DataModel getInstance() {
return ourInstance;
}
private DataModel() {
}
/**
* 分页查询( Android、iOS、前端、拓展资源、福利、休息视频 )数据
*
* @param type 数据类型
* @param size 数据个数
* @param page 第几页
* @return Observable<GankData>
*/
@Override public Observable<GankData> getData(String type, int size, int page) { | // Path: app/src/main/java/com/camnter/easygank/bean/GankData.java
// public class GankData extends Error implements Serializable {
//
// @SerializedName("results") public ArrayList<BaseGankData> results;
// }
//
// Path: app/src/main/java/com/camnter/easygank/gank/EasyGank.java
// public class EasyGank {
//
// private static EasyGank ourInstance;
//
// private GankService gankService;
//
//
// public static EasyGank getInstance() {
// if (ourInstance == null) ourInstance = new EasyGank();
// return ourInstance;
// }
//
//
// private EasyGank() {
// OkHttpClient okHttpClient = new OkHttpClient();
// okHttpClient.setReadTimeout(7676, TimeUnit.MILLISECONDS);
//
// /*
// * 查看网络请求发送状况
// */
// if (EasyApplication.getInstance().log) {
// okHttpClient.interceptors().add(chain -> {
// Response response = chain.proceed(chain.request());
// com.orhanobut.logger.Logger.d(chain.request().urlString());
// return response;
// });
// }
//
// Retrofit retrofit = new Retrofit.Builder().baseUrl(GankApi.BASE_URL)
// .addCallAdapterFactory(
// RxJavaCallAdapterFactory.create())
// .addConverterFactory(GsonConverterFactory.create(
// EasyApplication.getInstance().gson))
// .client(okHttpClient)
// .build();
// this.gankService = retrofit.create(GankService.class);
// }
//
//
// public GankService getGankService() {
// return gankService;
// }
// }
//
// Path: app/src/main/java/com/camnter/easygank/model/IDataModel.java
// public interface IDataModel {
// /**
// * 分页查询( Android、iOS、前端、拓展资源、福利、休息视频 )数据
// *
// * @param type 数据类型
// * @param size 数据个数
// * @param page 第几页
// * @return Observable<GankData>
// */
// Observable<GankData> getData(String type, int size, int page);
// }
// Path: app/src/main/java/com/camnter/easygank/model/impl/DataModel.java
import com.camnter.easygank.bean.GankData;
import com.camnter.easygank.gank.EasyGank;
import com.camnter.easygank.model.IDataModel;
import rx.Observable;
/*
* {EasyGank} Copyright (C) {2015} {CaMnter}
*
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.camnter.easygank.model.impl;
/**
* Description:DataModel
* Created by:CaMnter
* Time:2016-01-06 17:50
*/
public class DataModel implements IDataModel {
private static final DataModel ourInstance = new DataModel();
public static DataModel getInstance() {
return ourInstance;
}
private DataModel() {
}
/**
* 分页查询( Android、iOS、前端、拓展资源、福利、休息视频 )数据
*
* @param type 数据类型
* @param size 数据个数
* @param page 第几页
* @return Observable<GankData>
*/
@Override public Observable<GankData> getData(String type, int size, int page) { | return EasyGank.getInstance().getGankService().getData(type, size, page); |
CaMnter/EasyGank | app/src/main/java/com/camnter/easygank/EasyApplication.java | // Path: app/src/main/java/com/camnter/easygank/gank/GankApi.java
// public class GankApi {
// public static final String GANK_HOME_PAGE_NAME = "干货集中营";
// public static final String GANK_HOME_PAGE_URL = "http://gank.io/";
//
// public static final String BASE_URL = "http://gank.io/api/";
//
// public static final String DATA_TYPE_WELFARE = "福利";
// public static final String DATA_TYPE_ANDROID = "Android";
// public static final String DATA_TYPE_IOS = "iOS";
// public static final String DATA_TYPE_REST_VIDEO = "休息视频";
// public static final String DATA_TYPE_EXTEND_RESOURCES = "拓展资源";
// public static final String DATA_TYPE_JS = "前端";
// public static final String DATA_TYPE_APP = "App";
// public static final String DATA_TYPE_RECOMMEND = "瞎推荐";
// public static final String DATA_TYPE_ALL = "all";
//
// public static final int DEFAULT_DATA_SIZE = 10;
// public static final int DEFAULT_DAILY_SIZE = 15;
//
// public static final String GANK_DATA_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
// }
| import com.google.gson.GsonBuilder;
import com.orhanobut.logger.Logger;
import android.app.Application;
import android.content.Context;
import android.support.multidex.MultiDex;
import com.anupcowkur.reservoir.Reservoir;
import com.camnter.easygank.gank.GankApi;
import com.google.gson.Gson; | /*
* {EasyGank} Copyright (C) {2015} {CaMnter}
*
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.camnter.easygank;
/**
* Description:EasyApplication
* Created by:CaMnter
* Time:2016-01-03 23:14
*/
public class EasyApplication extends Application {
private static EasyApplication ourInstance = new EasyApplication();
public boolean log = true;
public Gson gson;
public static final long ONE_KB = 1024L;
public static final long ONE_MB = ONE_KB * 1024L;
public static final long CACHE_DATA_MAX_SIZE = ONE_MB * 3L;
public static EasyApplication getInstance() {
return ourInstance;
}
@Override protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
@Override public void onCreate() {
super.onCreate();
ourInstance = this;
Logger.init();
this.initGson();
this.initReservoir();
}
private void initGson() { | // Path: app/src/main/java/com/camnter/easygank/gank/GankApi.java
// public class GankApi {
// public static final String GANK_HOME_PAGE_NAME = "干货集中营";
// public static final String GANK_HOME_PAGE_URL = "http://gank.io/";
//
// public static final String BASE_URL = "http://gank.io/api/";
//
// public static final String DATA_TYPE_WELFARE = "福利";
// public static final String DATA_TYPE_ANDROID = "Android";
// public static final String DATA_TYPE_IOS = "iOS";
// public static final String DATA_TYPE_REST_VIDEO = "休息视频";
// public static final String DATA_TYPE_EXTEND_RESOURCES = "拓展资源";
// public static final String DATA_TYPE_JS = "前端";
// public static final String DATA_TYPE_APP = "App";
// public static final String DATA_TYPE_RECOMMEND = "瞎推荐";
// public static final String DATA_TYPE_ALL = "all";
//
// public static final int DEFAULT_DATA_SIZE = 10;
// public static final int DEFAULT_DAILY_SIZE = 15;
//
// public static final String GANK_DATA_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
// }
// Path: app/src/main/java/com/camnter/easygank/EasyApplication.java
import com.google.gson.GsonBuilder;
import com.orhanobut.logger.Logger;
import android.app.Application;
import android.content.Context;
import android.support.multidex.MultiDex;
import com.anupcowkur.reservoir.Reservoir;
import com.camnter.easygank.gank.GankApi;
import com.google.gson.Gson;
/*
* {EasyGank} Copyright (C) {2015} {CaMnter}
*
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.camnter.easygank;
/**
* Description:EasyApplication
* Created by:CaMnter
* Time:2016-01-03 23:14
*/
public class EasyApplication extends Application {
private static EasyApplication ourInstance = new EasyApplication();
public boolean log = true;
public Gson gson;
public static final long ONE_KB = 1024L;
public static final long ONE_MB = ONE_KB * 1024L;
public static final long CACHE_DATA_MAX_SIZE = ONE_MB * 3L;
public static EasyApplication getInstance() {
return ourInstance;
}
@Override protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
@Override public void onCreate() {
super.onCreate();
ourInstance = this;
Logger.init();
this.initGson();
this.initReservoir();
}
private void initGson() { | this.gson = new GsonBuilder().setDateFormat(GankApi.GANK_DATA_FORMAT).create(); |
CaMnter/EasyGank | app/src/main/java/com/camnter/easygank/model/impl/DailyModel.java | // Path: app/src/main/java/com/camnter/easygank/bean/GankDaily.java
// public class GankDaily extends Error implements Serializable {
//
// @SerializedName("results") public DailyResults results;
//
// @SerializedName("category") public ArrayList<String> category;
//
// public class DailyResults {
//
// @SerializedName("福利") public ArrayList<BaseGankData> welfareData;
//
// @SerializedName("Android") public ArrayList<BaseGankData> androidData;
//
// @SerializedName("iOS") public ArrayList<BaseGankData> iosData;
//
// @SerializedName("前端") public ArrayList<BaseGankData> jsData;
//
// @SerializedName("休息视频") public ArrayList<BaseGankData> videoData;
//
// @SerializedName("拓展资源") public ArrayList<BaseGankData> resourcesData;
//
// @SerializedName("App") public ArrayList<BaseGankData> appData;
//
// @SerializedName("瞎推荐") public ArrayList<BaseGankData> recommendData;
// }
// }
//
// Path: app/src/main/java/com/camnter/easygank/gank/EasyGank.java
// public class EasyGank {
//
// private static EasyGank ourInstance;
//
// private GankService gankService;
//
//
// public static EasyGank getInstance() {
// if (ourInstance == null) ourInstance = new EasyGank();
// return ourInstance;
// }
//
//
// private EasyGank() {
// OkHttpClient okHttpClient = new OkHttpClient();
// okHttpClient.setReadTimeout(7676, TimeUnit.MILLISECONDS);
//
// /*
// * 查看网络请求发送状况
// */
// if (EasyApplication.getInstance().log) {
// okHttpClient.interceptors().add(chain -> {
// Response response = chain.proceed(chain.request());
// com.orhanobut.logger.Logger.d(chain.request().urlString());
// return response;
// });
// }
//
// Retrofit retrofit = new Retrofit.Builder().baseUrl(GankApi.BASE_URL)
// .addCallAdapterFactory(
// RxJavaCallAdapterFactory.create())
// .addConverterFactory(GsonConverterFactory.create(
// EasyApplication.getInstance().gson))
// .client(okHttpClient)
// .build();
// this.gankService = retrofit.create(GankService.class);
// }
//
//
// public GankService getGankService() {
// return gankService;
// }
// }
//
// Path: app/src/main/java/com/camnter/easygank/model/IDailyModel.java
// public interface IDailyModel {
// /**
// * 查询每日数据
// *
// * @param year year
// * @param month month
// * @param day day
// * @return Observable<GankDaily>
// */
// Observable<GankDaily> getDaily(int year, int month, int day);
// }
| import com.camnter.easygank.bean.GankDaily;
import com.camnter.easygank.gank.EasyGank;
import com.camnter.easygank.model.IDailyModel;
import rx.Observable; | /*
* {EasyGank} Copyright (C) {2015} {CaMnter}
*
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.camnter.easygank.model.impl;
/**
* Description:DailyModel
* Created by:CaMnter
* Time:2016-01-03 18:02
*/
public class DailyModel implements IDailyModel {
private static final DailyModel ourInstance = new DailyModel();
public static DailyModel getInstance() {
return ourInstance;
}
private DailyModel() {
}
/**
* 查询每日数据
*
* @param year year
* @param month month
* @param day day
* @return Observable<GankDaily>
*/ | // Path: app/src/main/java/com/camnter/easygank/bean/GankDaily.java
// public class GankDaily extends Error implements Serializable {
//
// @SerializedName("results") public DailyResults results;
//
// @SerializedName("category") public ArrayList<String> category;
//
// public class DailyResults {
//
// @SerializedName("福利") public ArrayList<BaseGankData> welfareData;
//
// @SerializedName("Android") public ArrayList<BaseGankData> androidData;
//
// @SerializedName("iOS") public ArrayList<BaseGankData> iosData;
//
// @SerializedName("前端") public ArrayList<BaseGankData> jsData;
//
// @SerializedName("休息视频") public ArrayList<BaseGankData> videoData;
//
// @SerializedName("拓展资源") public ArrayList<BaseGankData> resourcesData;
//
// @SerializedName("App") public ArrayList<BaseGankData> appData;
//
// @SerializedName("瞎推荐") public ArrayList<BaseGankData> recommendData;
// }
// }
//
// Path: app/src/main/java/com/camnter/easygank/gank/EasyGank.java
// public class EasyGank {
//
// private static EasyGank ourInstance;
//
// private GankService gankService;
//
//
// public static EasyGank getInstance() {
// if (ourInstance == null) ourInstance = new EasyGank();
// return ourInstance;
// }
//
//
// private EasyGank() {
// OkHttpClient okHttpClient = new OkHttpClient();
// okHttpClient.setReadTimeout(7676, TimeUnit.MILLISECONDS);
//
// /*
// * 查看网络请求发送状况
// */
// if (EasyApplication.getInstance().log) {
// okHttpClient.interceptors().add(chain -> {
// Response response = chain.proceed(chain.request());
// com.orhanobut.logger.Logger.d(chain.request().urlString());
// return response;
// });
// }
//
// Retrofit retrofit = new Retrofit.Builder().baseUrl(GankApi.BASE_URL)
// .addCallAdapterFactory(
// RxJavaCallAdapterFactory.create())
// .addConverterFactory(GsonConverterFactory.create(
// EasyApplication.getInstance().gson))
// .client(okHttpClient)
// .build();
// this.gankService = retrofit.create(GankService.class);
// }
//
//
// public GankService getGankService() {
// return gankService;
// }
// }
//
// Path: app/src/main/java/com/camnter/easygank/model/IDailyModel.java
// public interface IDailyModel {
// /**
// * 查询每日数据
// *
// * @param year year
// * @param month month
// * @param day day
// * @return Observable<GankDaily>
// */
// Observable<GankDaily> getDaily(int year, int month, int day);
// }
// Path: app/src/main/java/com/camnter/easygank/model/impl/DailyModel.java
import com.camnter.easygank.bean.GankDaily;
import com.camnter.easygank.gank.EasyGank;
import com.camnter.easygank.model.IDailyModel;
import rx.Observable;
/*
* {EasyGank} Copyright (C) {2015} {CaMnter}
*
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.camnter.easygank.model.impl;
/**
* Description:DailyModel
* Created by:CaMnter
* Time:2016-01-03 18:02
*/
public class DailyModel implements IDailyModel {
private static final DailyModel ourInstance = new DailyModel();
public static DailyModel getInstance() {
return ourInstance;
}
private DailyModel() {
}
/**
* 查询每日数据
*
* @param year year
* @param month month
* @param day day
* @return Observable<GankDaily>
*/ | @Override public Observable<GankDaily> getDaily(int year, int month, int day) { |
CaMnter/EasyGank | app/src/main/java/com/camnter/easygank/model/impl/DailyModel.java | // Path: app/src/main/java/com/camnter/easygank/bean/GankDaily.java
// public class GankDaily extends Error implements Serializable {
//
// @SerializedName("results") public DailyResults results;
//
// @SerializedName("category") public ArrayList<String> category;
//
// public class DailyResults {
//
// @SerializedName("福利") public ArrayList<BaseGankData> welfareData;
//
// @SerializedName("Android") public ArrayList<BaseGankData> androidData;
//
// @SerializedName("iOS") public ArrayList<BaseGankData> iosData;
//
// @SerializedName("前端") public ArrayList<BaseGankData> jsData;
//
// @SerializedName("休息视频") public ArrayList<BaseGankData> videoData;
//
// @SerializedName("拓展资源") public ArrayList<BaseGankData> resourcesData;
//
// @SerializedName("App") public ArrayList<BaseGankData> appData;
//
// @SerializedName("瞎推荐") public ArrayList<BaseGankData> recommendData;
// }
// }
//
// Path: app/src/main/java/com/camnter/easygank/gank/EasyGank.java
// public class EasyGank {
//
// private static EasyGank ourInstance;
//
// private GankService gankService;
//
//
// public static EasyGank getInstance() {
// if (ourInstance == null) ourInstance = new EasyGank();
// return ourInstance;
// }
//
//
// private EasyGank() {
// OkHttpClient okHttpClient = new OkHttpClient();
// okHttpClient.setReadTimeout(7676, TimeUnit.MILLISECONDS);
//
// /*
// * 查看网络请求发送状况
// */
// if (EasyApplication.getInstance().log) {
// okHttpClient.interceptors().add(chain -> {
// Response response = chain.proceed(chain.request());
// com.orhanobut.logger.Logger.d(chain.request().urlString());
// return response;
// });
// }
//
// Retrofit retrofit = new Retrofit.Builder().baseUrl(GankApi.BASE_URL)
// .addCallAdapterFactory(
// RxJavaCallAdapterFactory.create())
// .addConverterFactory(GsonConverterFactory.create(
// EasyApplication.getInstance().gson))
// .client(okHttpClient)
// .build();
// this.gankService = retrofit.create(GankService.class);
// }
//
//
// public GankService getGankService() {
// return gankService;
// }
// }
//
// Path: app/src/main/java/com/camnter/easygank/model/IDailyModel.java
// public interface IDailyModel {
// /**
// * 查询每日数据
// *
// * @param year year
// * @param month month
// * @param day day
// * @return Observable<GankDaily>
// */
// Observable<GankDaily> getDaily(int year, int month, int day);
// }
| import com.camnter.easygank.bean.GankDaily;
import com.camnter.easygank.gank.EasyGank;
import com.camnter.easygank.model.IDailyModel;
import rx.Observable; | /*
* {EasyGank} Copyright (C) {2015} {CaMnter}
*
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.camnter.easygank.model.impl;
/**
* Description:DailyModel
* Created by:CaMnter
* Time:2016-01-03 18:02
*/
public class DailyModel implements IDailyModel {
private static final DailyModel ourInstance = new DailyModel();
public static DailyModel getInstance() {
return ourInstance;
}
private DailyModel() {
}
/**
* 查询每日数据
*
* @param year year
* @param month month
* @param day day
* @return Observable<GankDaily>
*/
@Override public Observable<GankDaily> getDaily(int year, int month, int day) { | // Path: app/src/main/java/com/camnter/easygank/bean/GankDaily.java
// public class GankDaily extends Error implements Serializable {
//
// @SerializedName("results") public DailyResults results;
//
// @SerializedName("category") public ArrayList<String> category;
//
// public class DailyResults {
//
// @SerializedName("福利") public ArrayList<BaseGankData> welfareData;
//
// @SerializedName("Android") public ArrayList<BaseGankData> androidData;
//
// @SerializedName("iOS") public ArrayList<BaseGankData> iosData;
//
// @SerializedName("前端") public ArrayList<BaseGankData> jsData;
//
// @SerializedName("休息视频") public ArrayList<BaseGankData> videoData;
//
// @SerializedName("拓展资源") public ArrayList<BaseGankData> resourcesData;
//
// @SerializedName("App") public ArrayList<BaseGankData> appData;
//
// @SerializedName("瞎推荐") public ArrayList<BaseGankData> recommendData;
// }
// }
//
// Path: app/src/main/java/com/camnter/easygank/gank/EasyGank.java
// public class EasyGank {
//
// private static EasyGank ourInstance;
//
// private GankService gankService;
//
//
// public static EasyGank getInstance() {
// if (ourInstance == null) ourInstance = new EasyGank();
// return ourInstance;
// }
//
//
// private EasyGank() {
// OkHttpClient okHttpClient = new OkHttpClient();
// okHttpClient.setReadTimeout(7676, TimeUnit.MILLISECONDS);
//
// /*
// * 查看网络请求发送状况
// */
// if (EasyApplication.getInstance().log) {
// okHttpClient.interceptors().add(chain -> {
// Response response = chain.proceed(chain.request());
// com.orhanobut.logger.Logger.d(chain.request().urlString());
// return response;
// });
// }
//
// Retrofit retrofit = new Retrofit.Builder().baseUrl(GankApi.BASE_URL)
// .addCallAdapterFactory(
// RxJavaCallAdapterFactory.create())
// .addConverterFactory(GsonConverterFactory.create(
// EasyApplication.getInstance().gson))
// .client(okHttpClient)
// .build();
// this.gankService = retrofit.create(GankService.class);
// }
//
//
// public GankService getGankService() {
// return gankService;
// }
// }
//
// Path: app/src/main/java/com/camnter/easygank/model/IDailyModel.java
// public interface IDailyModel {
// /**
// * 查询每日数据
// *
// * @param year year
// * @param month month
// * @param day day
// * @return Observable<GankDaily>
// */
// Observable<GankDaily> getDaily(int year, int month, int day);
// }
// Path: app/src/main/java/com/camnter/easygank/model/impl/DailyModel.java
import com.camnter.easygank.bean.GankDaily;
import com.camnter.easygank.gank.EasyGank;
import com.camnter.easygank.model.IDailyModel;
import rx.Observable;
/*
* {EasyGank} Copyright (C) {2015} {CaMnter}
*
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.camnter.easygank.model.impl;
/**
* Description:DailyModel
* Created by:CaMnter
* Time:2016-01-03 18:02
*/
public class DailyModel implements IDailyModel {
private static final DailyModel ourInstance = new DailyModel();
public static DailyModel getInstance() {
return ourInstance;
}
private DailyModel() {
}
/**
* 查询每日数据
*
* @param year year
* @param month month
* @param day day
* @return Observable<GankDaily>
*/
@Override public Observable<GankDaily> getDaily(int year, int month, int day) { | return EasyGank.getInstance().getGankService().getDaily(year, month, day); |
CaMnter/EasyGank | app/src/main/java/com/camnter/easygank/gank/GankService.java | // Path: app/src/main/java/com/camnter/easygank/bean/GankDaily.java
// public class GankDaily extends Error implements Serializable {
//
// @SerializedName("results") public DailyResults results;
//
// @SerializedName("category") public ArrayList<String> category;
//
// public class DailyResults {
//
// @SerializedName("福利") public ArrayList<BaseGankData> welfareData;
//
// @SerializedName("Android") public ArrayList<BaseGankData> androidData;
//
// @SerializedName("iOS") public ArrayList<BaseGankData> iosData;
//
// @SerializedName("前端") public ArrayList<BaseGankData> jsData;
//
// @SerializedName("休息视频") public ArrayList<BaseGankData> videoData;
//
// @SerializedName("拓展资源") public ArrayList<BaseGankData> resourcesData;
//
// @SerializedName("App") public ArrayList<BaseGankData> appData;
//
// @SerializedName("瞎推荐") public ArrayList<BaseGankData> recommendData;
// }
// }
//
// Path: app/src/main/java/com/camnter/easygank/bean/GankData.java
// public class GankData extends Error implements Serializable {
//
// @SerializedName("results") public ArrayList<BaseGankData> results;
// }
| import com.camnter.easygank.bean.GankDaily;
import com.camnter.easygank.bean.GankData;
import retrofit.http.GET;
import retrofit.http.Path;
import rx.Observable; | /*
* {EasyGank} Copyright (C) {2015} {CaMnter}
*
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.camnter.easygank.gank;
/**
* Description:GankService
* Created by:CaMnter
* Time:2016-01-03 16:18
*/
public interface GankService {
/**
* @param year year
* @param month month
* @param day day
* @return Observable<GankDaily>
*/
@GET("day/{year}/{month}/{day}") Observable<GankDaily> getDaily(
@Path("year") int year, @Path("month") int month, @Path("day") int day);
/**
* 找妹子、Android、iOS、前端、扩展资源、休息视频
*
* @param type 数据类型
* @param size 数据个数
* @param page 第几页
* @return Observable<GankWelfare>
*/ | // Path: app/src/main/java/com/camnter/easygank/bean/GankDaily.java
// public class GankDaily extends Error implements Serializable {
//
// @SerializedName("results") public DailyResults results;
//
// @SerializedName("category") public ArrayList<String> category;
//
// public class DailyResults {
//
// @SerializedName("福利") public ArrayList<BaseGankData> welfareData;
//
// @SerializedName("Android") public ArrayList<BaseGankData> androidData;
//
// @SerializedName("iOS") public ArrayList<BaseGankData> iosData;
//
// @SerializedName("前端") public ArrayList<BaseGankData> jsData;
//
// @SerializedName("休息视频") public ArrayList<BaseGankData> videoData;
//
// @SerializedName("拓展资源") public ArrayList<BaseGankData> resourcesData;
//
// @SerializedName("App") public ArrayList<BaseGankData> appData;
//
// @SerializedName("瞎推荐") public ArrayList<BaseGankData> recommendData;
// }
// }
//
// Path: app/src/main/java/com/camnter/easygank/bean/GankData.java
// public class GankData extends Error implements Serializable {
//
// @SerializedName("results") public ArrayList<BaseGankData> results;
// }
// Path: app/src/main/java/com/camnter/easygank/gank/GankService.java
import com.camnter.easygank.bean.GankDaily;
import com.camnter.easygank.bean.GankData;
import retrofit.http.GET;
import retrofit.http.Path;
import rx.Observable;
/*
* {EasyGank} Copyright (C) {2015} {CaMnter}
*
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.camnter.easygank.gank;
/**
* Description:GankService
* Created by:CaMnter
* Time:2016-01-03 16:18
*/
public interface GankService {
/**
* @param year year
* @param month month
* @param day day
* @return Observable<GankDaily>
*/
@GET("day/{year}/{month}/{day}") Observable<GankDaily> getDaily(
@Path("year") int year, @Path("month") int month, @Path("day") int day);
/**
* 找妹子、Android、iOS、前端、扩展资源、休息视频
*
* @param type 数据类型
* @param size 数据个数
* @param page 第几页
* @return Observable<GankWelfare>
*/ | @GET("data/{type}/{size}/{page}") Observable<GankData> getData( |
CaMnter/EasyGank | app/src/main/java/com/camnter/easygank/presenter/iview/MainView.java | // Path: app/src/main/java/com/camnter/easygank/bean/BaseGankData.java
// public class BaseGankData implements Serializable {
//
// // 发布人
// @SerializedName("who") public String who;
//
// // 发布时间
// @SerializedName("publishedAt") public Date publishedAt;
//
// // 标题
// @SerializedName("desc") public String desc;
//
// // 类型, 一般都是"福利"
// @SerializedName("type") public String type;
//
// // 图片url
// @SerializedName("url") public String url;
//
// // 是否可用
// @SerializedName("used") public Boolean used;
//
// // 对象id
// @SerializedName("objectId") public String objectId;
//
// // 创建时间
// @SerializedName("createdAt") public Date createdAt;
//
// // 更新时间
// @SerializedName("updatedAt") public Date updatedAt;
// }
//
// Path: app/src/main/java/com/camnter/easygank/bean/GankDaily.java
// public class GankDaily extends Error implements Serializable {
//
// @SerializedName("results") public DailyResults results;
//
// @SerializedName("category") public ArrayList<String> category;
//
// public class DailyResults {
//
// @SerializedName("福利") public ArrayList<BaseGankData> welfareData;
//
// @SerializedName("Android") public ArrayList<BaseGankData> androidData;
//
// @SerializedName("iOS") public ArrayList<BaseGankData> iosData;
//
// @SerializedName("前端") public ArrayList<BaseGankData> jsData;
//
// @SerializedName("休息视频") public ArrayList<BaseGankData> videoData;
//
// @SerializedName("拓展资源") public ArrayList<BaseGankData> resourcesData;
//
// @SerializedName("App") public ArrayList<BaseGankData> appData;
//
// @SerializedName("瞎推荐") public ArrayList<BaseGankData> recommendData;
// }
// }
//
// Path: app/src/main/java/com/camnter/easygank/core/mvp/MvpView.java
// public interface MvpView {
// /**
// * 发生错误
// *
// * @param e e
// */
// void onFailure(Throwable e);
// }
| import com.camnter.easygank.bean.BaseGankData;
import com.camnter.easygank.bean.GankDaily;
import com.camnter.easygank.core.mvp.MvpView;
import java.util.ArrayList;
import java.util.List; | /*
* {EasyGank} Copyright (C) {2015} {CaMnter}
*
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.camnter.easygank.presenter.iview;
/**
* Description:MainView
* Created by:CaMnter
* Time:2016-01-04 16:38
*/
public interface MainView extends MvpView {
/**
* 查询 每日干货 成功
*
* @param dailyData dailyData
* @param refresh 是否刷新
*/
void onGetDailySuccess(List<GankDaily> dailyData, boolean refresh);
/**
* 查询 ( Android、iOS、前端、拓展资源、福利、休息视频 ) 成功
*
* @param data data
* @param refresh 是否刷新
*/ | // Path: app/src/main/java/com/camnter/easygank/bean/BaseGankData.java
// public class BaseGankData implements Serializable {
//
// // 发布人
// @SerializedName("who") public String who;
//
// // 发布时间
// @SerializedName("publishedAt") public Date publishedAt;
//
// // 标题
// @SerializedName("desc") public String desc;
//
// // 类型, 一般都是"福利"
// @SerializedName("type") public String type;
//
// // 图片url
// @SerializedName("url") public String url;
//
// // 是否可用
// @SerializedName("used") public Boolean used;
//
// // 对象id
// @SerializedName("objectId") public String objectId;
//
// // 创建时间
// @SerializedName("createdAt") public Date createdAt;
//
// // 更新时间
// @SerializedName("updatedAt") public Date updatedAt;
// }
//
// Path: app/src/main/java/com/camnter/easygank/bean/GankDaily.java
// public class GankDaily extends Error implements Serializable {
//
// @SerializedName("results") public DailyResults results;
//
// @SerializedName("category") public ArrayList<String> category;
//
// public class DailyResults {
//
// @SerializedName("福利") public ArrayList<BaseGankData> welfareData;
//
// @SerializedName("Android") public ArrayList<BaseGankData> androidData;
//
// @SerializedName("iOS") public ArrayList<BaseGankData> iosData;
//
// @SerializedName("前端") public ArrayList<BaseGankData> jsData;
//
// @SerializedName("休息视频") public ArrayList<BaseGankData> videoData;
//
// @SerializedName("拓展资源") public ArrayList<BaseGankData> resourcesData;
//
// @SerializedName("App") public ArrayList<BaseGankData> appData;
//
// @SerializedName("瞎推荐") public ArrayList<BaseGankData> recommendData;
// }
// }
//
// Path: app/src/main/java/com/camnter/easygank/core/mvp/MvpView.java
// public interface MvpView {
// /**
// * 发生错误
// *
// * @param e e
// */
// void onFailure(Throwable e);
// }
// Path: app/src/main/java/com/camnter/easygank/presenter/iview/MainView.java
import com.camnter.easygank.bean.BaseGankData;
import com.camnter.easygank.bean.GankDaily;
import com.camnter.easygank.core.mvp.MvpView;
import java.util.ArrayList;
import java.util.List;
/*
* {EasyGank} Copyright (C) {2015} {CaMnter}
*
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.camnter.easygank.presenter.iview;
/**
* Description:MainView
* Created by:CaMnter
* Time:2016-01-04 16:38
*/
public interface MainView extends MvpView {
/**
* 查询 每日干货 成功
*
* @param dailyData dailyData
* @param refresh 是否刷新
*/
void onGetDailySuccess(List<GankDaily> dailyData, boolean refresh);
/**
* 查询 ( Android、iOS、前端、拓展资源、福利、休息视频 ) 成功
*
* @param data data
* @param refresh 是否刷新
*/ | void onGetDataSuccess(List<BaseGankData> data, boolean refresh); |
CaMnter/EasyGank | app/src/main/java/com/camnter/easygank/core/mvp/BasePresenter.java | // Path: app/src/main/java/com/camnter/easygank/data/DataManager.java
// public class DataManager {
//
// private static DataManager dataManager;
//
// private DailyModel dailyModel;
// private DataModel dataModel;
//
//
// public synchronized static DataManager getInstance() {
// if (dataManager == null) {
// dataManager = new DataManager();
// }
// return dataManager;
// }
//
//
// private DataManager() {
// this.dataModel = DataModel.getInstance();
// this.dailyModel = DailyModel.getInstance();
// }
//
//
// public Observable<List<GankDaily>> getDailyDataByNetwork(MainPresenter.EasyDate currentDate) {
// return Observable.just(currentDate)
// .flatMapIterable(MainPresenter.EasyDate::getPastTime)
// .flatMap(easyDate -> {
// /*
// * 感觉Android的数据应该不会为null
// * 所以以Android的数据为判断是否当天有数据
// */
// return this.dailyModel.getDaily(easyDate.getYear(),
// easyDate.getMonth(), easyDate.getDay())
// .filter(dailyData ->
// dailyData.results.androidData != null);
// })
// .toSortedList((dailyData, dailyData2) -> {
// return dailyData2.results.androidData.get(0).publishedAt.compareTo(
// dailyData.results.androidData.get(0).publishedAt);
// })
// .compose(RxUtils.applyIOToMainThreadSchedulers());
// }
//
//
// public Observable<ArrayList<BaseGankData>> getDataByNetWork(String type, int size, int page) {
// return this.dataModel.getData(type, size, page)
// .map(gankData -> gankData.results)
// .compose(RxUtils.applyIOToMainThreadSchedulers());
// }
//
//
// public Observable<ArrayList<ArrayList<BaseGankData>>> getDailyDetailByDailyResults(GankDaily.DailyResults results) {
// return Observable.just(results).map(dailyResults -> {
// ArrayList<ArrayList<BaseGankData>> cardData = new ArrayList<>();
// if (dailyResults.welfareData != null && dailyResults.welfareData.size() > 0) {
// cardData.add(dailyResults.welfareData);
// }
// if (dailyResults.androidData != null && dailyResults.androidData.size() > 0) {
// cardData.add(dailyResults.androidData);
// }
// if (dailyResults.iosData != null && dailyResults.iosData.size() > 0) {
// cardData.add(dailyResults.iosData);
// }
// if (dailyResults.jsData != null && dailyResults.jsData.size() > 0) {
// cardData.add(dailyResults.jsData);
// }
// if (dailyResults.videoData != null && dailyResults.videoData.size() > 0) {
// cardData.add(dailyResults.videoData);
// }
// if (dailyResults.resourcesData != null && dailyResults.resourcesData.size() > 0) {
// cardData.add(dailyResults.resourcesData);
// }
// if (dailyResults.appData != null && dailyResults.appData.size() > 0) {
// cardData.add(dailyResults.appData);
// }
// if (dailyResults.recommendData != null && dailyResults.recommendData.size() > 0) {
// cardData.add(dailyResults.recommendData);
// }
// return cardData;
// }).compose(RxUtils.applyIOToMainThreadSchedulers());
// }
// }
| import com.camnter.easygank.data.DataManager;
import rx.subscriptions.CompositeSubscription; | /*
* {EasyGank} Copyright (C) {2015} {CaMnter}
*
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.camnter.easygank.core.mvp;
/**
* Description:BasePresenter
* <p>
* Base class that implements the Presenter interface and provides a base implementation for
* attachView() and detachView(). It also handles keeping a reference to the mvpView that
* can be accessed from the children classes by calling getMvpView().
* <p>
* Created by:CaMnter
* Time:2016-01-03 18:10
*/
public class BasePresenter<T extends MvpView> implements Presenter<T> {
private T mMvpView;
public CompositeSubscription mCompositeSubscription; | // Path: app/src/main/java/com/camnter/easygank/data/DataManager.java
// public class DataManager {
//
// private static DataManager dataManager;
//
// private DailyModel dailyModel;
// private DataModel dataModel;
//
//
// public synchronized static DataManager getInstance() {
// if (dataManager == null) {
// dataManager = new DataManager();
// }
// return dataManager;
// }
//
//
// private DataManager() {
// this.dataModel = DataModel.getInstance();
// this.dailyModel = DailyModel.getInstance();
// }
//
//
// public Observable<List<GankDaily>> getDailyDataByNetwork(MainPresenter.EasyDate currentDate) {
// return Observable.just(currentDate)
// .flatMapIterable(MainPresenter.EasyDate::getPastTime)
// .flatMap(easyDate -> {
// /*
// * 感觉Android的数据应该不会为null
// * 所以以Android的数据为判断是否当天有数据
// */
// return this.dailyModel.getDaily(easyDate.getYear(),
// easyDate.getMonth(), easyDate.getDay())
// .filter(dailyData ->
// dailyData.results.androidData != null);
// })
// .toSortedList((dailyData, dailyData2) -> {
// return dailyData2.results.androidData.get(0).publishedAt.compareTo(
// dailyData.results.androidData.get(0).publishedAt);
// })
// .compose(RxUtils.applyIOToMainThreadSchedulers());
// }
//
//
// public Observable<ArrayList<BaseGankData>> getDataByNetWork(String type, int size, int page) {
// return this.dataModel.getData(type, size, page)
// .map(gankData -> gankData.results)
// .compose(RxUtils.applyIOToMainThreadSchedulers());
// }
//
//
// public Observable<ArrayList<ArrayList<BaseGankData>>> getDailyDetailByDailyResults(GankDaily.DailyResults results) {
// return Observable.just(results).map(dailyResults -> {
// ArrayList<ArrayList<BaseGankData>> cardData = new ArrayList<>();
// if (dailyResults.welfareData != null && dailyResults.welfareData.size() > 0) {
// cardData.add(dailyResults.welfareData);
// }
// if (dailyResults.androidData != null && dailyResults.androidData.size() > 0) {
// cardData.add(dailyResults.androidData);
// }
// if (dailyResults.iosData != null && dailyResults.iosData.size() > 0) {
// cardData.add(dailyResults.iosData);
// }
// if (dailyResults.jsData != null && dailyResults.jsData.size() > 0) {
// cardData.add(dailyResults.jsData);
// }
// if (dailyResults.videoData != null && dailyResults.videoData.size() > 0) {
// cardData.add(dailyResults.videoData);
// }
// if (dailyResults.resourcesData != null && dailyResults.resourcesData.size() > 0) {
// cardData.add(dailyResults.resourcesData);
// }
// if (dailyResults.appData != null && dailyResults.appData.size() > 0) {
// cardData.add(dailyResults.appData);
// }
// if (dailyResults.recommendData != null && dailyResults.recommendData.size() > 0) {
// cardData.add(dailyResults.recommendData);
// }
// return cardData;
// }).compose(RxUtils.applyIOToMainThreadSchedulers());
// }
// }
// Path: app/src/main/java/com/camnter/easygank/core/mvp/BasePresenter.java
import com.camnter.easygank.data.DataManager;
import rx.subscriptions.CompositeSubscription;
/*
* {EasyGank} Copyright (C) {2015} {CaMnter}
*
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.camnter.easygank.core.mvp;
/**
* Description:BasePresenter
* <p>
* Base class that implements the Presenter interface and provides a base implementation for
* attachView() and detachView(). It also handles keeping a reference to the mvpView that
* can be accessed from the children classes by calling getMvpView().
* <p>
* Created by:CaMnter
* Time:2016-01-03 18:10
*/
public class BasePresenter<T extends MvpView> implements Presenter<T> {
private T mMvpView;
public CompositeSubscription mCompositeSubscription; | public DataManager mDataManager; |
CaMnter/EasyGank | app/src/main/java/com/camnter/easygank/utils/GlideUtils.java | // Path: app/src/main/java/com/camnter/easygank/widget/GlideCircleTransform.java
// public class GlideCircleTransform extends BitmapTransformation {
//
// public GlideCircleTransform(Context context) {
// super(context);
// }
//
//
// @Override
// protected Bitmap transform(BitmapPool pool, Bitmap inBitmap, int destWidth, int destHeight) {
// if (inBitmap == null) return null;
//
// int size = Math.min(inBitmap.getWidth(), inBitmap.getHeight());
// int x = (inBitmap.getWidth() - size) / 2;
// int y = (inBitmap.getHeight() - size) / 2;
//
// Bitmap squared = Bitmap.createBitmap(inBitmap, x, y, size, size);
// Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
// if (result == null) {
// result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
// }
//
// Canvas canvas = new Canvas(result);
// Paint paint = new Paint();
// paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP,
// BitmapShader.TileMode.CLAMP));
// paint.setAntiAlias(true);
// float r = size / 2f;
// canvas.drawCircle(r, r, r, paint);
// return result;
// }
//
//
// @Override public String getId() {
// return getClass().getName();
// }
// }
| import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.camnter.easygank.R;
import com.camnter.easygank.widget.GlideCircleTransform;
import com.orhanobut.logger.Logger;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.DrawableRes;
import android.view.View;
import android.widget.ImageView;
import com.bumptech.glide.Glide; | .getSize((width, height) -> {
if (!view.isShown()) {
view.setVisibility(View.VISIBLE);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public static void displayCircleHeader(ImageView view, @DrawableRes int res) {
// 不能崩
if (view == null) {
Logger.e("GlideUtils -> display -> imageView is null");
return;
}
Context context = view.getContext();
// View你还活着吗?
if (context instanceof Activity) {
if (((Activity) context).isFinishing()) {
return;
}
}
try {
Glide.with(context)
.load(res)
.centerCrop()
.placeholder(R.mipmap.img_default_gray) | // Path: app/src/main/java/com/camnter/easygank/widget/GlideCircleTransform.java
// public class GlideCircleTransform extends BitmapTransformation {
//
// public GlideCircleTransform(Context context) {
// super(context);
// }
//
//
// @Override
// protected Bitmap transform(BitmapPool pool, Bitmap inBitmap, int destWidth, int destHeight) {
// if (inBitmap == null) return null;
//
// int size = Math.min(inBitmap.getWidth(), inBitmap.getHeight());
// int x = (inBitmap.getWidth() - size) / 2;
// int y = (inBitmap.getHeight() - size) / 2;
//
// Bitmap squared = Bitmap.createBitmap(inBitmap, x, y, size, size);
// Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
// if (result == null) {
// result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
// }
//
// Canvas canvas = new Canvas(result);
// Paint paint = new Paint();
// paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP,
// BitmapShader.TileMode.CLAMP));
// paint.setAntiAlias(true);
// float r = size / 2f;
// canvas.drawCircle(r, r, r, paint);
// return result;
// }
//
//
// @Override public String getId() {
// return getClass().getName();
// }
// }
// Path: app/src/main/java/com/camnter/easygank/utils/GlideUtils.java
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.camnter.easygank.R;
import com.camnter.easygank.widget.GlideCircleTransform;
import com.orhanobut.logger.Logger;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.DrawableRes;
import android.view.View;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
.getSize((width, height) -> {
if (!view.isShown()) {
view.setVisibility(View.VISIBLE);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public static void displayCircleHeader(ImageView view, @DrawableRes int res) {
// 不能崩
if (view == null) {
Logger.e("GlideUtils -> display -> imageView is null");
return;
}
Context context = view.getContext();
// View你还活着吗?
if (context instanceof Activity) {
if (((Activity) context).isFinishing()) {
return;
}
}
try {
Glide.with(context)
.load(res)
.centerCrop()
.placeholder(R.mipmap.img_default_gray) | .bitmapTransform(new GlideCircleTransform(context)) |
CaMnter/EasyGank | app/src/main/java/com/camnter/easygank/gank/EasyGank.java | // Path: app/src/main/java/com/camnter/easygank/EasyApplication.java
// public class EasyApplication extends Application {
// private static EasyApplication ourInstance = new EasyApplication();
// public boolean log = true;
// public Gson gson;
//
// public static final long ONE_KB = 1024L;
// public static final long ONE_MB = ONE_KB * 1024L;
// public static final long CACHE_DATA_MAX_SIZE = ONE_MB * 3L;
//
//
// public static EasyApplication getInstance() {
// return ourInstance;
// }
//
//
// @Override protected void attachBaseContext(Context base) {
// super.attachBaseContext(base);
// MultiDex.install(this);
// }
//
//
// @Override public void onCreate() {
// super.onCreate();
// ourInstance = this;
// Logger.init();
// this.initGson();
// this.initReservoir();
// }
//
//
// private void initGson() {
// this.gson = new GsonBuilder().setDateFormat(GankApi.GANK_DATA_FORMAT).create();
// }
//
//
// private void initReservoir() {
// try {
// Reservoir.init(this, CACHE_DATA_MAX_SIZE, this.gson);
// } catch (Exception e) {
// //failure
// e.printStackTrace();
// }
// }
// }
| import retrofit.RxJavaCallAdapterFactory;
import com.camnter.easygank.EasyApplication;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Response;
import java.util.concurrent.TimeUnit;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit; | /*
* {EasyGank} Copyright (C) {2015} {CaMnter}
*
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.camnter.easygank.gank;
/**
* Description:EasyGank
* Created by:CaMnter
* Time:2016-01-03 18:24
*/
public class EasyGank {
private static EasyGank ourInstance;
private GankService gankService;
public static EasyGank getInstance() {
if (ourInstance == null) ourInstance = new EasyGank();
return ourInstance;
}
private EasyGank() {
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(7676, TimeUnit.MILLISECONDS);
/*
* 查看网络请求发送状况
*/ | // Path: app/src/main/java/com/camnter/easygank/EasyApplication.java
// public class EasyApplication extends Application {
// private static EasyApplication ourInstance = new EasyApplication();
// public boolean log = true;
// public Gson gson;
//
// public static final long ONE_KB = 1024L;
// public static final long ONE_MB = ONE_KB * 1024L;
// public static final long CACHE_DATA_MAX_SIZE = ONE_MB * 3L;
//
//
// public static EasyApplication getInstance() {
// return ourInstance;
// }
//
//
// @Override protected void attachBaseContext(Context base) {
// super.attachBaseContext(base);
// MultiDex.install(this);
// }
//
//
// @Override public void onCreate() {
// super.onCreate();
// ourInstance = this;
// Logger.init();
// this.initGson();
// this.initReservoir();
// }
//
//
// private void initGson() {
// this.gson = new GsonBuilder().setDateFormat(GankApi.GANK_DATA_FORMAT).create();
// }
//
//
// private void initReservoir() {
// try {
// Reservoir.init(this, CACHE_DATA_MAX_SIZE, this.gson);
// } catch (Exception e) {
// //failure
// e.printStackTrace();
// }
// }
// }
// Path: app/src/main/java/com/camnter/easygank/gank/EasyGank.java
import retrofit.RxJavaCallAdapterFactory;
import com.camnter.easygank.EasyApplication;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Response;
import java.util.concurrent.TimeUnit;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
/*
* {EasyGank} Copyright (C) {2015} {CaMnter}
*
* This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
* This is free software, and you are welcome to redistribute it
* under certain conditions; type `show c' for details.
*
* The hypothetical commands `show w' and `show c' should show the appropriate
* parts of the General Public License. Of course, your program's commands
* might be different; for a GUI interface, you would use an "about box".
*
* You should also get your employer (if you work as a programmer) or school,
* if any, to sign a "copyright disclaimer" for the program, if necessary.
* For more information on this, and how to apply and follow the GNU GPL, see
* <http://www.gnu.org/licenses/>.
*
* The GNU General Public License does not permit incorporating your program
* into proprietary programs. If your program is a subroutine library, you
* may consider it more useful to permit linking proprietary applications with
* the library. If this is what you want to do, use the GNU Lesser General
* Public License instead of this License. But first, please read
* <http://www.gnu.org/philosophy/why-not-lgpl.html>.
*/
package com.camnter.easygank.gank;
/**
* Description:EasyGank
* Created by:CaMnter
* Time:2016-01-03 18:24
*/
public class EasyGank {
private static EasyGank ourInstance;
private GankService gankService;
public static EasyGank getInstance() {
if (ourInstance == null) ourInstance = new EasyGank();
return ourInstance;
}
private EasyGank() {
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(7676, TimeUnit.MILLISECONDS);
/*
* 查看网络请求发送状况
*/ | if (EasyApplication.getInstance().log) { |
l0s/fernet-java8 | fernet-jersey-auth/src/test/java/com/macasaet/fernet/jaxrs/exception/TokenValidationExceptionMapperTest.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/PayloadValidationException.java
// public class PayloadValidationException extends TokenValidationException {
//
// private static final long serialVersionUID = -2067765218609208844L;
//
// public PayloadValidationException(final String message) {
// super(message);
// }
//
// public PayloadValidationException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// public PayloadValidationException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/TokenExpiredException.java
// public class TokenExpiredException extends TokenValidationException {
//
// private static final long serialVersionUID = -8250681539503776783L;
//
// public TokenExpiredException(final String message) {
// super(message);
// }
//
// public TokenExpiredException(final Throwable cause) {
// this(cause.getMessage(), cause);
// }
//
// public TokenExpiredException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/TokenValidationException.java
// public class TokenValidationException extends RuntimeException {
//
// private static final long serialVersionUID = 5175834607547919885L;
//
// public TokenValidationException(final String message) {
// super(message);
// }
//
// public TokenValidationException(final Throwable cause) {
// this(cause.getMessage(), cause);
// }
//
// public TokenValidationException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import javax.ws.rs.core.Response;
import org.junit.Before;
import org.junit.Test;
import com.macasaet.fernet.PayloadValidationException;
import com.macasaet.fernet.TokenExpiredException;
import com.macasaet.fernet.TokenValidationException; | /**
Copyright 2018 Carlos Macasaet
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
https://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.macasaet.fernet.jaxrs.exception;
public class TokenValidationExceptionMapperTest {
private TokenValidationExceptionMapper mapper;
@Before
public void setUp() throws Exception {
mapper = new TokenValidationExceptionMapper();
}
@Test
public final void verifyToResponseGeneratesForbidden() {
// given | // Path: fernet-java8/src/main/java/com/macasaet/fernet/PayloadValidationException.java
// public class PayloadValidationException extends TokenValidationException {
//
// private static final long serialVersionUID = -2067765218609208844L;
//
// public PayloadValidationException(final String message) {
// super(message);
// }
//
// public PayloadValidationException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// public PayloadValidationException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/TokenExpiredException.java
// public class TokenExpiredException extends TokenValidationException {
//
// private static final long serialVersionUID = -8250681539503776783L;
//
// public TokenExpiredException(final String message) {
// super(message);
// }
//
// public TokenExpiredException(final Throwable cause) {
// this(cause.getMessage(), cause);
// }
//
// public TokenExpiredException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/TokenValidationException.java
// public class TokenValidationException extends RuntimeException {
//
// private static final long serialVersionUID = 5175834607547919885L;
//
// public TokenValidationException(final String message) {
// super(message);
// }
//
// public TokenValidationException(final Throwable cause) {
// this(cause.getMessage(), cause);
// }
//
// public TokenValidationException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
// Path: fernet-jersey-auth/src/test/java/com/macasaet/fernet/jaxrs/exception/TokenValidationExceptionMapperTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import javax.ws.rs.core.Response;
import org.junit.Before;
import org.junit.Test;
import com.macasaet.fernet.PayloadValidationException;
import com.macasaet.fernet.TokenExpiredException;
import com.macasaet.fernet.TokenValidationException;
/**
Copyright 2018 Carlos Macasaet
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
https://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.macasaet.fernet.jaxrs.exception;
public class TokenValidationExceptionMapperTest {
private TokenValidationExceptionMapper mapper;
@Before
public void setUp() throws Exception {
mapper = new TokenValidationExceptionMapper();
}
@Test
public final void verifyToResponseGeneratesForbidden() {
// given | final PayloadValidationException exception = new PayloadValidationException("Invalid payload"); |
l0s/fernet-java8 | fernet-jersey-auth/src/test/java/com/macasaet/fernet/jaxrs/exception/TokenValidationExceptionMapperTest.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/PayloadValidationException.java
// public class PayloadValidationException extends TokenValidationException {
//
// private static final long serialVersionUID = -2067765218609208844L;
//
// public PayloadValidationException(final String message) {
// super(message);
// }
//
// public PayloadValidationException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// public PayloadValidationException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/TokenExpiredException.java
// public class TokenExpiredException extends TokenValidationException {
//
// private static final long serialVersionUID = -8250681539503776783L;
//
// public TokenExpiredException(final String message) {
// super(message);
// }
//
// public TokenExpiredException(final Throwable cause) {
// this(cause.getMessage(), cause);
// }
//
// public TokenExpiredException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/TokenValidationException.java
// public class TokenValidationException extends RuntimeException {
//
// private static final long serialVersionUID = 5175834607547919885L;
//
// public TokenValidationException(final String message) {
// super(message);
// }
//
// public TokenValidationException(final Throwable cause) {
// this(cause.getMessage(), cause);
// }
//
// public TokenValidationException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import javax.ws.rs.core.Response;
import org.junit.Before;
import org.junit.Test;
import com.macasaet.fernet.PayloadValidationException;
import com.macasaet.fernet.TokenExpiredException;
import com.macasaet.fernet.TokenValidationException; | /**
Copyright 2018 Carlos Macasaet
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
https://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.macasaet.fernet.jaxrs.exception;
public class TokenValidationExceptionMapperTest {
private TokenValidationExceptionMapper mapper;
@Before
public void setUp() throws Exception {
mapper = new TokenValidationExceptionMapper();
}
@Test
public final void verifyToResponseGeneratesForbidden() {
// given
final PayloadValidationException exception = new PayloadValidationException("Invalid payload");
// when
final Response response = mapper.toResponse(exception);
// then
assertEquals(403, response.getStatus());
}
@Test
public final void verifyToResponseGeneratesUnauthorized() {
// given | // Path: fernet-java8/src/main/java/com/macasaet/fernet/PayloadValidationException.java
// public class PayloadValidationException extends TokenValidationException {
//
// private static final long serialVersionUID = -2067765218609208844L;
//
// public PayloadValidationException(final String message) {
// super(message);
// }
//
// public PayloadValidationException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// public PayloadValidationException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/TokenExpiredException.java
// public class TokenExpiredException extends TokenValidationException {
//
// private static final long serialVersionUID = -8250681539503776783L;
//
// public TokenExpiredException(final String message) {
// super(message);
// }
//
// public TokenExpiredException(final Throwable cause) {
// this(cause.getMessage(), cause);
// }
//
// public TokenExpiredException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/TokenValidationException.java
// public class TokenValidationException extends RuntimeException {
//
// private static final long serialVersionUID = 5175834607547919885L;
//
// public TokenValidationException(final String message) {
// super(message);
// }
//
// public TokenValidationException(final Throwable cause) {
// this(cause.getMessage(), cause);
// }
//
// public TokenValidationException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
// Path: fernet-jersey-auth/src/test/java/com/macasaet/fernet/jaxrs/exception/TokenValidationExceptionMapperTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import javax.ws.rs.core.Response;
import org.junit.Before;
import org.junit.Test;
import com.macasaet.fernet.PayloadValidationException;
import com.macasaet.fernet.TokenExpiredException;
import com.macasaet.fernet.TokenValidationException;
/**
Copyright 2018 Carlos Macasaet
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
https://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.macasaet.fernet.jaxrs.exception;
public class TokenValidationExceptionMapperTest {
private TokenValidationExceptionMapper mapper;
@Before
public void setUp() throws Exception {
mapper = new TokenValidationExceptionMapper();
}
@Test
public final void verifyToResponseGeneratesForbidden() {
// given
final PayloadValidationException exception = new PayloadValidationException("Invalid payload");
// when
final Response response = mapper.toResponse(exception);
// then
assertEquals(403, response.getStatus());
}
@Test
public final void verifyToResponseGeneratesUnauthorized() {
// given | final TokenValidationException exception = new TokenExpiredException("token expired"); |
l0s/fernet-java8 | fernet-jersey-auth/src/test/java/com/macasaet/fernet/jaxrs/exception/TokenValidationExceptionMapperTest.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/PayloadValidationException.java
// public class PayloadValidationException extends TokenValidationException {
//
// private static final long serialVersionUID = -2067765218609208844L;
//
// public PayloadValidationException(final String message) {
// super(message);
// }
//
// public PayloadValidationException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// public PayloadValidationException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/TokenExpiredException.java
// public class TokenExpiredException extends TokenValidationException {
//
// private static final long serialVersionUID = -8250681539503776783L;
//
// public TokenExpiredException(final String message) {
// super(message);
// }
//
// public TokenExpiredException(final Throwable cause) {
// this(cause.getMessage(), cause);
// }
//
// public TokenExpiredException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/TokenValidationException.java
// public class TokenValidationException extends RuntimeException {
//
// private static final long serialVersionUID = 5175834607547919885L;
//
// public TokenValidationException(final String message) {
// super(message);
// }
//
// public TokenValidationException(final Throwable cause) {
// this(cause.getMessage(), cause);
// }
//
// public TokenValidationException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import javax.ws.rs.core.Response;
import org.junit.Before;
import org.junit.Test;
import com.macasaet.fernet.PayloadValidationException;
import com.macasaet.fernet.TokenExpiredException;
import com.macasaet.fernet.TokenValidationException; | /**
Copyright 2018 Carlos Macasaet
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
https://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.macasaet.fernet.jaxrs.exception;
public class TokenValidationExceptionMapperTest {
private TokenValidationExceptionMapper mapper;
@Before
public void setUp() throws Exception {
mapper = new TokenValidationExceptionMapper();
}
@Test
public final void verifyToResponseGeneratesForbidden() {
// given
final PayloadValidationException exception = new PayloadValidationException("Invalid payload");
// when
final Response response = mapper.toResponse(exception);
// then
assertEquals(403, response.getStatus());
}
@Test
public final void verifyToResponseGeneratesUnauthorized() {
// given | // Path: fernet-java8/src/main/java/com/macasaet/fernet/PayloadValidationException.java
// public class PayloadValidationException extends TokenValidationException {
//
// private static final long serialVersionUID = -2067765218609208844L;
//
// public PayloadValidationException(final String message) {
// super(message);
// }
//
// public PayloadValidationException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// public PayloadValidationException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/TokenExpiredException.java
// public class TokenExpiredException extends TokenValidationException {
//
// private static final long serialVersionUID = -8250681539503776783L;
//
// public TokenExpiredException(final String message) {
// super(message);
// }
//
// public TokenExpiredException(final Throwable cause) {
// this(cause.getMessage(), cause);
// }
//
// public TokenExpiredException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/TokenValidationException.java
// public class TokenValidationException extends RuntimeException {
//
// private static final long serialVersionUID = 5175834607547919885L;
//
// public TokenValidationException(final String message) {
// super(message);
// }
//
// public TokenValidationException(final Throwable cause) {
// this(cause.getMessage(), cause);
// }
//
// public TokenValidationException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
// Path: fernet-jersey-auth/src/test/java/com/macasaet/fernet/jaxrs/exception/TokenValidationExceptionMapperTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import javax.ws.rs.core.Response;
import org.junit.Before;
import org.junit.Test;
import com.macasaet.fernet.PayloadValidationException;
import com.macasaet.fernet.TokenExpiredException;
import com.macasaet.fernet.TokenValidationException;
/**
Copyright 2018 Carlos Macasaet
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
https://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.macasaet.fernet.jaxrs.exception;
public class TokenValidationExceptionMapperTest {
private TokenValidationExceptionMapper mapper;
@Before
public void setUp() throws Exception {
mapper = new TokenValidationExceptionMapper();
}
@Test
public final void verifyToResponseGeneratesForbidden() {
// given
final PayloadValidationException exception = new PayloadValidationException("Invalid payload");
// when
final Response response = mapper.toResponse(exception);
// then
assertEquals(403, response.getStatus());
}
@Test
public final void verifyToResponseGeneratesUnauthorized() {
// given | final TokenValidationException exception = new TokenExpiredException("token expired"); |
l0s/fernet-java8 | fernet-jersey-auth/src/main/java/com/macasaet/fernet/jersey/FernetTokenFeature.java | // Path: fernet-jersey-auth/src/main/java/com/macasaet/fernet/jaxrs/exception/IllegalTokenExceptionMapper.java
// @Provider
// public class IllegalTokenExceptionMapper implements ExceptionMapper<IllegalTokenException> {
//
// public Response toResponse(final IllegalTokenException exception) {
// return new NotAuthorizedException("Bearer error=\"invalid_token\", error_description=\"mal-formed token\"").getResponse();
// }
//
// }
| import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import com.macasaet.fernet.jaxrs.exception.IllegalTokenExceptionMapper; | /**
Copyright 2018 Carlos Macasaet
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
https://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.macasaet.fernet.jersey;
/**
* {@link Feature} that enables Fernet token injection into Resource method parameters.
*
* <p>Copyright © 2018 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
* @see com.macasaet.fernet.jaxrs.FernetToken
* @see com.macasaet.fernet.Token
*/
public class FernetTokenFeature implements Feature {
public boolean configure(final FeatureContext context) {
context.register(new FernetTokenBinder()); | // Path: fernet-jersey-auth/src/main/java/com/macasaet/fernet/jaxrs/exception/IllegalTokenExceptionMapper.java
// @Provider
// public class IllegalTokenExceptionMapper implements ExceptionMapper<IllegalTokenException> {
//
// public Response toResponse(final IllegalTokenException exception) {
// return new NotAuthorizedException("Bearer error=\"invalid_token\", error_description=\"mal-formed token\"").getResponse();
// }
//
// }
// Path: fernet-jersey-auth/src/main/java/com/macasaet/fernet/jersey/FernetTokenFeature.java
import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import com.macasaet.fernet.jaxrs.exception.IllegalTokenExceptionMapper;
/**
Copyright 2018 Carlos Macasaet
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
https://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.macasaet.fernet.jersey;
/**
* {@link Feature} that enables Fernet token injection into Resource method parameters.
*
* <p>Copyright © 2018 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
* @see com.macasaet.fernet.jaxrs.FernetToken
* @see com.macasaet.fernet.Token
*/
public class FernetTokenFeature implements Feature {
public boolean configure(final FeatureContext context) {
context.register(new FernetTokenBinder()); | context.register(IllegalTokenExceptionMapper.class); |
l0s/fernet-java8 | fernet-java8/src/main/java/com/macasaet/fernet/Key.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String cipherTransformation = encryptionAlgorithm + "/CBC/PKCS5Padding";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String encryptionAlgorithm = "AES";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int encryptionKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int fernetKeyBytes = signingKeyBytes + encryptionKeyBytes;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String signingAlgorithm = "HmacSHA256";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signingKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenPrefixBytes = versionBytes + timestampBytes + initializationVectorBytes;
| import static com.macasaet.fernet.Constants.cipherTransformation;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.encryptionAlgorithm;
import static com.macasaet.fernet.Constants.encryptionKeyBytes;
import static com.macasaet.fernet.Constants.fernetKeyBytes;
import static com.macasaet.fernet.Constants.signingAlgorithm;
import static com.macasaet.fernet.Constants.signingKeyBytes;
import static com.macasaet.fernet.Constants.tokenPrefixBytes;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.copyOfRange;
import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64.Encoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; | /**
Copyright 2017 Carlos Macasaet
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
https://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.macasaet.fernet;
/**
* A Fernet shared secret key.
*
* <p>Copyright © 2017 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
*/
@SuppressWarnings({"PMD.AvoidDuplicateLiterals", "PMD.TooManyMethods"})
public class Key {
private final byte[] signingKey;
private final byte[] encryptionKey;
/**
* Create a Key from individual components.
*
* @param signingKey
* a 128-bit (16 byte) key for signing tokens.
* @param encryptionKey
* a 128-bit (16 byte) key for encrypting and decrypting token contents.
*/
public Key(final byte[] signingKey, final byte[] encryptionKey) { | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String cipherTransformation = encryptionAlgorithm + "/CBC/PKCS5Padding";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String encryptionAlgorithm = "AES";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int encryptionKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int fernetKeyBytes = signingKeyBytes + encryptionKeyBytes;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String signingAlgorithm = "HmacSHA256";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signingKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenPrefixBytes = versionBytes + timestampBytes + initializationVectorBytes;
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Key.java
import static com.macasaet.fernet.Constants.cipherTransformation;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.encryptionAlgorithm;
import static com.macasaet.fernet.Constants.encryptionKeyBytes;
import static com.macasaet.fernet.Constants.fernetKeyBytes;
import static com.macasaet.fernet.Constants.signingAlgorithm;
import static com.macasaet.fernet.Constants.signingKeyBytes;
import static com.macasaet.fernet.Constants.tokenPrefixBytes;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.copyOfRange;
import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64.Encoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
Copyright 2017 Carlos Macasaet
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
https://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.macasaet.fernet;
/**
* A Fernet shared secret key.
*
* <p>Copyright © 2017 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
*/
@SuppressWarnings({"PMD.AvoidDuplicateLiterals", "PMD.TooManyMethods"})
public class Key {
private final byte[] signingKey;
private final byte[] encryptionKey;
/**
* Create a Key from individual components.
*
* @param signingKey
* a 128-bit (16 byte) key for signing tokens.
* @param encryptionKey
* a 128-bit (16 byte) key for encrypting and decrypting token contents.
*/
public Key(final byte[] signingKey, final byte[] encryptionKey) { | if (signingKey == null || signingKey.length != signingKeyBytes) { |
l0s/fernet-java8 | fernet-java8/src/main/java/com/macasaet/fernet/Key.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String cipherTransformation = encryptionAlgorithm + "/CBC/PKCS5Padding";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String encryptionAlgorithm = "AES";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int encryptionKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int fernetKeyBytes = signingKeyBytes + encryptionKeyBytes;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String signingAlgorithm = "HmacSHA256";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signingKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenPrefixBytes = versionBytes + timestampBytes + initializationVectorBytes;
| import static com.macasaet.fernet.Constants.cipherTransformation;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.encryptionAlgorithm;
import static com.macasaet.fernet.Constants.encryptionKeyBytes;
import static com.macasaet.fernet.Constants.fernetKeyBytes;
import static com.macasaet.fernet.Constants.signingAlgorithm;
import static com.macasaet.fernet.Constants.signingKeyBytes;
import static com.macasaet.fernet.Constants.tokenPrefixBytes;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.copyOfRange;
import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64.Encoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; | /**
Copyright 2017 Carlos Macasaet
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
https://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.macasaet.fernet;
/**
* A Fernet shared secret key.
*
* <p>Copyright © 2017 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
*/
@SuppressWarnings({"PMD.AvoidDuplicateLiterals", "PMD.TooManyMethods"})
public class Key {
private final byte[] signingKey;
private final byte[] encryptionKey;
/**
* Create a Key from individual components.
*
* @param signingKey
* a 128-bit (16 byte) key for signing tokens.
* @param encryptionKey
* a 128-bit (16 byte) key for encrypting and decrypting token contents.
*/
public Key(final byte[] signingKey, final byte[] encryptionKey) {
if (signingKey == null || signingKey.length != signingKeyBytes) {
throw new IllegalArgumentException("Signing key must be 128 bits");
} | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String cipherTransformation = encryptionAlgorithm + "/CBC/PKCS5Padding";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String encryptionAlgorithm = "AES";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int encryptionKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int fernetKeyBytes = signingKeyBytes + encryptionKeyBytes;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String signingAlgorithm = "HmacSHA256";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signingKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenPrefixBytes = versionBytes + timestampBytes + initializationVectorBytes;
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Key.java
import static com.macasaet.fernet.Constants.cipherTransformation;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.encryptionAlgorithm;
import static com.macasaet.fernet.Constants.encryptionKeyBytes;
import static com.macasaet.fernet.Constants.fernetKeyBytes;
import static com.macasaet.fernet.Constants.signingAlgorithm;
import static com.macasaet.fernet.Constants.signingKeyBytes;
import static com.macasaet.fernet.Constants.tokenPrefixBytes;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.copyOfRange;
import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64.Encoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
Copyright 2017 Carlos Macasaet
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
https://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.macasaet.fernet;
/**
* A Fernet shared secret key.
*
* <p>Copyright © 2017 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
*/
@SuppressWarnings({"PMD.AvoidDuplicateLiterals", "PMD.TooManyMethods"})
public class Key {
private final byte[] signingKey;
private final byte[] encryptionKey;
/**
* Create a Key from individual components.
*
* @param signingKey
* a 128-bit (16 byte) key for signing tokens.
* @param encryptionKey
* a 128-bit (16 byte) key for encrypting and decrypting token contents.
*/
public Key(final byte[] signingKey, final byte[] encryptionKey) {
if (signingKey == null || signingKey.length != signingKeyBytes) {
throw new IllegalArgumentException("Signing key must be 128 bits");
} | if (encryptionKey == null || encryptionKey.length != encryptionKeyBytes) { |
l0s/fernet-java8 | fernet-java8/src/main/java/com/macasaet/fernet/Key.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String cipherTransformation = encryptionAlgorithm + "/CBC/PKCS5Padding";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String encryptionAlgorithm = "AES";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int encryptionKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int fernetKeyBytes = signingKeyBytes + encryptionKeyBytes;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String signingAlgorithm = "HmacSHA256";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signingKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenPrefixBytes = versionBytes + timestampBytes + initializationVectorBytes;
| import static com.macasaet.fernet.Constants.cipherTransformation;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.encryptionAlgorithm;
import static com.macasaet.fernet.Constants.encryptionKeyBytes;
import static com.macasaet.fernet.Constants.fernetKeyBytes;
import static com.macasaet.fernet.Constants.signingAlgorithm;
import static com.macasaet.fernet.Constants.signingKeyBytes;
import static com.macasaet.fernet.Constants.tokenPrefixBytes;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.copyOfRange;
import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64.Encoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; | /**
Copyright 2017 Carlos Macasaet
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
https://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.macasaet.fernet;
/**
* A Fernet shared secret key.
*
* <p>Copyright © 2017 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
*/
@SuppressWarnings({"PMD.AvoidDuplicateLiterals", "PMD.TooManyMethods"})
public class Key {
private final byte[] signingKey;
private final byte[] encryptionKey;
/**
* Create a Key from individual components.
*
* @param signingKey
* a 128-bit (16 byte) key for signing tokens.
* @param encryptionKey
* a 128-bit (16 byte) key for encrypting and decrypting token contents.
*/
public Key(final byte[] signingKey, final byte[] encryptionKey) {
if (signingKey == null || signingKey.length != signingKeyBytes) {
throw new IllegalArgumentException("Signing key must be 128 bits");
}
if (encryptionKey == null || encryptionKey.length != encryptionKeyBytes) {
throw new IllegalArgumentException("Encryption key must be 128 bits");
}
this.signingKey = copyOf(signingKey, signingKeyBytes);
this.encryptionKey = copyOf(encryptionKey, encryptionKeyBytes);
}
/**
* Create a Key from a payload containing the signing and encryption
* key.
*
* @param concatenatedKeys an array of 32 bytes of which the first 16 is
* the signing key and the last 16 is the
* encryption/decryption key
*/
public Key(final byte[] concatenatedKeys) {
this(copyOfRange(concatenatedKeys, 0, signingKeyBytes), | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String cipherTransformation = encryptionAlgorithm + "/CBC/PKCS5Padding";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String encryptionAlgorithm = "AES";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int encryptionKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int fernetKeyBytes = signingKeyBytes + encryptionKeyBytes;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String signingAlgorithm = "HmacSHA256";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signingKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenPrefixBytes = versionBytes + timestampBytes + initializationVectorBytes;
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Key.java
import static com.macasaet.fernet.Constants.cipherTransformation;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.encryptionAlgorithm;
import static com.macasaet.fernet.Constants.encryptionKeyBytes;
import static com.macasaet.fernet.Constants.fernetKeyBytes;
import static com.macasaet.fernet.Constants.signingAlgorithm;
import static com.macasaet.fernet.Constants.signingKeyBytes;
import static com.macasaet.fernet.Constants.tokenPrefixBytes;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.copyOfRange;
import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64.Encoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
Copyright 2017 Carlos Macasaet
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
https://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.macasaet.fernet;
/**
* A Fernet shared secret key.
*
* <p>Copyright © 2017 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
*/
@SuppressWarnings({"PMD.AvoidDuplicateLiterals", "PMD.TooManyMethods"})
public class Key {
private final byte[] signingKey;
private final byte[] encryptionKey;
/**
* Create a Key from individual components.
*
* @param signingKey
* a 128-bit (16 byte) key for signing tokens.
* @param encryptionKey
* a 128-bit (16 byte) key for encrypting and decrypting token contents.
*/
public Key(final byte[] signingKey, final byte[] encryptionKey) {
if (signingKey == null || signingKey.length != signingKeyBytes) {
throw new IllegalArgumentException("Signing key must be 128 bits");
}
if (encryptionKey == null || encryptionKey.length != encryptionKeyBytes) {
throw new IllegalArgumentException("Encryption key must be 128 bits");
}
this.signingKey = copyOf(signingKey, signingKeyBytes);
this.encryptionKey = copyOf(encryptionKey, encryptionKeyBytes);
}
/**
* Create a Key from a payload containing the signing and encryption
* key.
*
* @param concatenatedKeys an array of 32 bytes of which the first 16 is
* the signing key and the last 16 is the
* encryption/decryption key
*/
public Key(final byte[] concatenatedKeys) {
this(copyOfRange(concatenatedKeys, 0, signingKeyBytes), | copyOfRange(concatenatedKeys, signingKeyBytes, fernetKeyBytes)); |
l0s/fernet-java8 | fernet-java8/src/main/java/com/macasaet/fernet/Key.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String cipherTransformation = encryptionAlgorithm + "/CBC/PKCS5Padding";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String encryptionAlgorithm = "AES";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int encryptionKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int fernetKeyBytes = signingKeyBytes + encryptionKeyBytes;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String signingAlgorithm = "HmacSHA256";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signingKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenPrefixBytes = versionBytes + timestampBytes + initializationVectorBytes;
| import static com.macasaet.fernet.Constants.cipherTransformation;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.encryptionAlgorithm;
import static com.macasaet.fernet.Constants.encryptionKeyBytes;
import static com.macasaet.fernet.Constants.fernetKeyBytes;
import static com.macasaet.fernet.Constants.signingAlgorithm;
import static com.macasaet.fernet.Constants.signingKeyBytes;
import static com.macasaet.fernet.Constants.tokenPrefixBytes;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.copyOfRange;
import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64.Encoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; | /**
Copyright 2017 Carlos Macasaet
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
https://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.macasaet.fernet;
/**
* A Fernet shared secret key.
*
* <p>Copyright © 2017 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
*/
@SuppressWarnings({"PMD.AvoidDuplicateLiterals", "PMD.TooManyMethods"})
public class Key {
private final byte[] signingKey;
private final byte[] encryptionKey;
/**
* Create a Key from individual components.
*
* @param signingKey
* a 128-bit (16 byte) key for signing tokens.
* @param encryptionKey
* a 128-bit (16 byte) key for encrypting and decrypting token contents.
*/
public Key(final byte[] signingKey, final byte[] encryptionKey) {
if (signingKey == null || signingKey.length != signingKeyBytes) {
throw new IllegalArgumentException("Signing key must be 128 bits");
}
if (encryptionKey == null || encryptionKey.length != encryptionKeyBytes) {
throw new IllegalArgumentException("Encryption key must be 128 bits");
}
this.signingKey = copyOf(signingKey, signingKeyBytes);
this.encryptionKey = copyOf(encryptionKey, encryptionKeyBytes);
}
/**
* Create a Key from a payload containing the signing and encryption
* key.
*
* @param concatenatedKeys an array of 32 bytes of which the first 16 is
* the signing key and the last 16 is the
* encryption/decryption key
*/
public Key(final byte[] concatenatedKeys) {
this(copyOfRange(concatenatedKeys, 0, signingKeyBytes),
copyOfRange(concatenatedKeys, signingKeyBytes, fernetKeyBytes));
}
/**
* @param string
* a Base 64 URL string in the format Signing-key (128 bits) || Encryption-key (128 bits)
*/
public Key(final String string) { | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String cipherTransformation = encryptionAlgorithm + "/CBC/PKCS5Padding";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String encryptionAlgorithm = "AES";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int encryptionKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int fernetKeyBytes = signingKeyBytes + encryptionKeyBytes;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String signingAlgorithm = "HmacSHA256";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signingKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenPrefixBytes = versionBytes + timestampBytes + initializationVectorBytes;
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Key.java
import static com.macasaet.fernet.Constants.cipherTransformation;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.encryptionAlgorithm;
import static com.macasaet.fernet.Constants.encryptionKeyBytes;
import static com.macasaet.fernet.Constants.fernetKeyBytes;
import static com.macasaet.fernet.Constants.signingAlgorithm;
import static com.macasaet.fernet.Constants.signingKeyBytes;
import static com.macasaet.fernet.Constants.tokenPrefixBytes;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.copyOfRange;
import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64.Encoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
Copyright 2017 Carlos Macasaet
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
https://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.macasaet.fernet;
/**
* A Fernet shared secret key.
*
* <p>Copyright © 2017 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
*/
@SuppressWarnings({"PMD.AvoidDuplicateLiterals", "PMD.TooManyMethods"})
public class Key {
private final byte[] signingKey;
private final byte[] encryptionKey;
/**
* Create a Key from individual components.
*
* @param signingKey
* a 128-bit (16 byte) key for signing tokens.
* @param encryptionKey
* a 128-bit (16 byte) key for encrypting and decrypting token contents.
*/
public Key(final byte[] signingKey, final byte[] encryptionKey) {
if (signingKey == null || signingKey.length != signingKeyBytes) {
throw new IllegalArgumentException("Signing key must be 128 bits");
}
if (encryptionKey == null || encryptionKey.length != encryptionKeyBytes) {
throw new IllegalArgumentException("Encryption key must be 128 bits");
}
this.signingKey = copyOf(signingKey, signingKeyBytes);
this.encryptionKey = copyOf(encryptionKey, encryptionKeyBytes);
}
/**
* Create a Key from a payload containing the signing and encryption
* key.
*
* @param concatenatedKeys an array of 32 bytes of which the first 16 is
* the signing key and the last 16 is the
* encryption/decryption key
*/
public Key(final byte[] concatenatedKeys) {
this(copyOfRange(concatenatedKeys, 0, signingKeyBytes),
copyOfRange(concatenatedKeys, signingKeyBytes, fernetKeyBytes));
}
/**
* @param string
* a Base 64 URL string in the format Signing-key (128 bits) || Encryption-key (128 bits)
*/
public Key(final String string) { | this(decoder.decode(string)); |
l0s/fernet-java8 | fernet-java8/src/main/java/com/macasaet/fernet/Key.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String cipherTransformation = encryptionAlgorithm + "/CBC/PKCS5Padding";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String encryptionAlgorithm = "AES";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int encryptionKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int fernetKeyBytes = signingKeyBytes + encryptionKeyBytes;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String signingAlgorithm = "HmacSHA256";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signingKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenPrefixBytes = versionBytes + timestampBytes + initializationVectorBytes;
| import static com.macasaet.fernet.Constants.cipherTransformation;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.encryptionAlgorithm;
import static com.macasaet.fernet.Constants.encryptionKeyBytes;
import static com.macasaet.fernet.Constants.fernetKeyBytes;
import static com.macasaet.fernet.Constants.signingAlgorithm;
import static com.macasaet.fernet.Constants.signingKeyBytes;
import static com.macasaet.fernet.Constants.tokenPrefixBytes;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.copyOfRange;
import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64.Encoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; | * the seconds after the epoch that the token was generated
* @param initializationVector
* the encryption and decryption initialization vector
* @param cipherText
* the encrypted content of the token
* @return the HMAC signature
*/
public byte[] sign(final byte version, final Instant timestamp, final IvParameterSpec initializationVector,
final byte[] cipherText) {
try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream(
getTokenPrefixBytes() + cipherText.length)) {
return sign(version, timestamp, initializationVector, cipherText, byteStream);
} catch (final IOException e) {
// this should not happen as I/O is to memory only
throw new IllegalStateException(e.getMessage(), e);
}
}
/**
* Encrypt a payload to embed in a Fernet token
*
* @param payload the raw bytes of the data to store in a token
* @param initializationVector random bytes from a high-entropy source to initialise the AES cipher
* @return the AES-encrypted payload. The length will always be a multiple of 16 (128 bits).
* @see #decrypt(byte[], IvParameterSpec)
*/
@SuppressWarnings("PMD.LawOfDemeter")
public byte[] encrypt(final byte[] payload, final IvParameterSpec initializationVector) {
final SecretKeySpec encryptionKeySpec = getEncryptionKeySpec();
try { | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String cipherTransformation = encryptionAlgorithm + "/CBC/PKCS5Padding";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String encryptionAlgorithm = "AES";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int encryptionKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int fernetKeyBytes = signingKeyBytes + encryptionKeyBytes;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String signingAlgorithm = "HmacSHA256";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signingKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenPrefixBytes = versionBytes + timestampBytes + initializationVectorBytes;
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Key.java
import static com.macasaet.fernet.Constants.cipherTransformation;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.encryptionAlgorithm;
import static com.macasaet.fernet.Constants.encryptionKeyBytes;
import static com.macasaet.fernet.Constants.fernetKeyBytes;
import static com.macasaet.fernet.Constants.signingAlgorithm;
import static com.macasaet.fernet.Constants.signingKeyBytes;
import static com.macasaet.fernet.Constants.tokenPrefixBytes;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.copyOfRange;
import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64.Encoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
* the seconds after the epoch that the token was generated
* @param initializationVector
* the encryption and decryption initialization vector
* @param cipherText
* the encrypted content of the token
* @return the HMAC signature
*/
public byte[] sign(final byte version, final Instant timestamp, final IvParameterSpec initializationVector,
final byte[] cipherText) {
try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream(
getTokenPrefixBytes() + cipherText.length)) {
return sign(version, timestamp, initializationVector, cipherText, byteStream);
} catch (final IOException e) {
// this should not happen as I/O is to memory only
throw new IllegalStateException(e.getMessage(), e);
}
}
/**
* Encrypt a payload to embed in a Fernet token
*
* @param payload the raw bytes of the data to store in a token
* @param initializationVector random bytes from a high-entropy source to initialise the AES cipher
* @return the AES-encrypted payload. The length will always be a multiple of 16 (128 bits).
* @see #decrypt(byte[], IvParameterSpec)
*/
@SuppressWarnings("PMD.LawOfDemeter")
public byte[] encrypt(final byte[] payload, final IvParameterSpec initializationVector) {
final SecretKeySpec encryptionKeySpec = getEncryptionKeySpec();
try { | final Cipher cipher = Cipher.getInstance(cipherTransformation); |
l0s/fernet-java8 | fernet-java8/src/main/java/com/macasaet/fernet/Key.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String cipherTransformation = encryptionAlgorithm + "/CBC/PKCS5Padding";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String encryptionAlgorithm = "AES";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int encryptionKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int fernetKeyBytes = signingKeyBytes + encryptionKeyBytes;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String signingAlgorithm = "HmacSHA256";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signingKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenPrefixBytes = versionBytes + timestampBytes + initializationVectorBytes;
| import static com.macasaet.fernet.Constants.cipherTransformation;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.encryptionAlgorithm;
import static com.macasaet.fernet.Constants.encryptionKeyBytes;
import static com.macasaet.fernet.Constants.fernetKeyBytes;
import static com.macasaet.fernet.Constants.signingAlgorithm;
import static com.macasaet.fernet.Constants.signingKeyBytes;
import static com.macasaet.fernet.Constants.tokenPrefixBytes;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.copyOfRange;
import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64.Encoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; | }
/**
* @return the AES key for encrypting and decrypting the token payload
*/
protected SecretKeySpec getEncryptionKeySpec() {
return new SecretKeySpec(getEncryptionKey(), getEncryptionAlgorithm());
}
/**
* Warning: Modifying the returned byte array will write through to this object.
*
* @return the raw underlying signing key bytes
*/
@SuppressWarnings("PMD.MethodReturnsInternalArray")
protected byte[] getSigningKey() {
return signingKey;
}
/**
* Warning: Modifying the returned byte array will write through to this object.
*
* @return the raw underlying encryption key bytes
*/
@SuppressWarnings("PMD.MethodReturnsInternalArray")
protected byte[] getEncryptionKey() {
return encryptionKey;
}
protected int getTokenPrefixBytes() { | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String cipherTransformation = encryptionAlgorithm + "/CBC/PKCS5Padding";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String encryptionAlgorithm = "AES";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int encryptionKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int fernetKeyBytes = signingKeyBytes + encryptionKeyBytes;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String signingAlgorithm = "HmacSHA256";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signingKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenPrefixBytes = versionBytes + timestampBytes + initializationVectorBytes;
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Key.java
import static com.macasaet.fernet.Constants.cipherTransformation;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.encryptionAlgorithm;
import static com.macasaet.fernet.Constants.encryptionKeyBytes;
import static com.macasaet.fernet.Constants.fernetKeyBytes;
import static com.macasaet.fernet.Constants.signingAlgorithm;
import static com.macasaet.fernet.Constants.signingKeyBytes;
import static com.macasaet.fernet.Constants.tokenPrefixBytes;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.copyOfRange;
import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64.Encoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
}
/**
* @return the AES key for encrypting and decrypting the token payload
*/
protected SecretKeySpec getEncryptionKeySpec() {
return new SecretKeySpec(getEncryptionKey(), getEncryptionAlgorithm());
}
/**
* Warning: Modifying the returned byte array will write through to this object.
*
* @return the raw underlying signing key bytes
*/
@SuppressWarnings("PMD.MethodReturnsInternalArray")
protected byte[] getSigningKey() {
return signingKey;
}
/**
* Warning: Modifying the returned byte array will write through to this object.
*
* @return the raw underlying encryption key bytes
*/
@SuppressWarnings("PMD.MethodReturnsInternalArray")
protected byte[] getEncryptionKey() {
return encryptionKey;
}
protected int getTokenPrefixBytes() { | return tokenPrefixBytes; |
l0s/fernet-java8 | fernet-java8/src/main/java/com/macasaet/fernet/Key.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String cipherTransformation = encryptionAlgorithm + "/CBC/PKCS5Padding";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String encryptionAlgorithm = "AES";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int encryptionKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int fernetKeyBytes = signingKeyBytes + encryptionKeyBytes;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String signingAlgorithm = "HmacSHA256";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signingKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenPrefixBytes = versionBytes + timestampBytes + initializationVectorBytes;
| import static com.macasaet.fernet.Constants.cipherTransformation;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.encryptionAlgorithm;
import static com.macasaet.fernet.Constants.encryptionKeyBytes;
import static com.macasaet.fernet.Constants.fernetKeyBytes;
import static com.macasaet.fernet.Constants.signingAlgorithm;
import static com.macasaet.fernet.Constants.signingKeyBytes;
import static com.macasaet.fernet.Constants.tokenPrefixBytes;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.copyOfRange;
import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64.Encoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; | */
protected SecretKeySpec getEncryptionKeySpec() {
return new SecretKeySpec(getEncryptionKey(), getEncryptionAlgorithm());
}
/**
* Warning: Modifying the returned byte array will write through to this object.
*
* @return the raw underlying signing key bytes
*/
@SuppressWarnings("PMD.MethodReturnsInternalArray")
protected byte[] getSigningKey() {
return signingKey;
}
/**
* Warning: Modifying the returned byte array will write through to this object.
*
* @return the raw underlying encryption key bytes
*/
@SuppressWarnings("PMD.MethodReturnsInternalArray")
protected byte[] getEncryptionKey() {
return encryptionKey;
}
protected int getTokenPrefixBytes() {
return tokenPrefixBytes;
}
protected String getSigningAlgorithm() { | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String cipherTransformation = encryptionAlgorithm + "/CBC/PKCS5Padding";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String encryptionAlgorithm = "AES";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int encryptionKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int fernetKeyBytes = signingKeyBytes + encryptionKeyBytes;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String signingAlgorithm = "HmacSHA256";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signingKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenPrefixBytes = versionBytes + timestampBytes + initializationVectorBytes;
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Key.java
import static com.macasaet.fernet.Constants.cipherTransformation;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.encryptionAlgorithm;
import static com.macasaet.fernet.Constants.encryptionKeyBytes;
import static com.macasaet.fernet.Constants.fernetKeyBytes;
import static com.macasaet.fernet.Constants.signingAlgorithm;
import static com.macasaet.fernet.Constants.signingKeyBytes;
import static com.macasaet.fernet.Constants.tokenPrefixBytes;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.copyOfRange;
import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64.Encoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
*/
protected SecretKeySpec getEncryptionKeySpec() {
return new SecretKeySpec(getEncryptionKey(), getEncryptionAlgorithm());
}
/**
* Warning: Modifying the returned byte array will write through to this object.
*
* @return the raw underlying signing key bytes
*/
@SuppressWarnings("PMD.MethodReturnsInternalArray")
protected byte[] getSigningKey() {
return signingKey;
}
/**
* Warning: Modifying the returned byte array will write through to this object.
*
* @return the raw underlying encryption key bytes
*/
@SuppressWarnings("PMD.MethodReturnsInternalArray")
protected byte[] getEncryptionKey() {
return encryptionKey;
}
protected int getTokenPrefixBytes() {
return tokenPrefixBytes;
}
protected String getSigningAlgorithm() { | return signingAlgorithm; |
l0s/fernet-java8 | fernet-java8/src/main/java/com/macasaet/fernet/Key.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String cipherTransformation = encryptionAlgorithm + "/CBC/PKCS5Padding";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String encryptionAlgorithm = "AES";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int encryptionKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int fernetKeyBytes = signingKeyBytes + encryptionKeyBytes;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String signingAlgorithm = "HmacSHA256";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signingKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenPrefixBytes = versionBytes + timestampBytes + initializationVectorBytes;
| import static com.macasaet.fernet.Constants.cipherTransformation;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.encryptionAlgorithm;
import static com.macasaet.fernet.Constants.encryptionKeyBytes;
import static com.macasaet.fernet.Constants.fernetKeyBytes;
import static com.macasaet.fernet.Constants.signingAlgorithm;
import static com.macasaet.fernet.Constants.signingKeyBytes;
import static com.macasaet.fernet.Constants.tokenPrefixBytes;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.copyOfRange;
import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64.Encoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; |
/**
* Warning: Modifying the returned byte array will write through to this object.
*
* @return the raw underlying signing key bytes
*/
@SuppressWarnings("PMD.MethodReturnsInternalArray")
protected byte[] getSigningKey() {
return signingKey;
}
/**
* Warning: Modifying the returned byte array will write through to this object.
*
* @return the raw underlying encryption key bytes
*/
@SuppressWarnings("PMD.MethodReturnsInternalArray")
protected byte[] getEncryptionKey() {
return encryptionKey;
}
protected int getTokenPrefixBytes() {
return tokenPrefixBytes;
}
protected String getSigningAlgorithm() {
return signingAlgorithm;
}
protected String getEncryptionAlgorithm() { | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String cipherTransformation = encryptionAlgorithm + "/CBC/PKCS5Padding";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String encryptionAlgorithm = "AES";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int encryptionKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int fernetKeyBytes = signingKeyBytes + encryptionKeyBytes;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String signingAlgorithm = "HmacSHA256";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signingKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenPrefixBytes = versionBytes + timestampBytes + initializationVectorBytes;
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Key.java
import static com.macasaet.fernet.Constants.cipherTransformation;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.encryptionAlgorithm;
import static com.macasaet.fernet.Constants.encryptionKeyBytes;
import static com.macasaet.fernet.Constants.fernetKeyBytes;
import static com.macasaet.fernet.Constants.signingAlgorithm;
import static com.macasaet.fernet.Constants.signingKeyBytes;
import static com.macasaet.fernet.Constants.tokenPrefixBytes;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.copyOfRange;
import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64.Encoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* Warning: Modifying the returned byte array will write through to this object.
*
* @return the raw underlying signing key bytes
*/
@SuppressWarnings("PMD.MethodReturnsInternalArray")
protected byte[] getSigningKey() {
return signingKey;
}
/**
* Warning: Modifying the returned byte array will write through to this object.
*
* @return the raw underlying encryption key bytes
*/
@SuppressWarnings("PMD.MethodReturnsInternalArray")
protected byte[] getEncryptionKey() {
return encryptionKey;
}
protected int getTokenPrefixBytes() {
return tokenPrefixBytes;
}
protected String getSigningAlgorithm() {
return signingAlgorithm;
}
protected String getEncryptionAlgorithm() { | return encryptionAlgorithm; |
l0s/fernet-java8 | fernet-java8/src/main/java/com/macasaet/fernet/Key.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String cipherTransformation = encryptionAlgorithm + "/CBC/PKCS5Padding";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String encryptionAlgorithm = "AES";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int encryptionKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int fernetKeyBytes = signingKeyBytes + encryptionKeyBytes;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String signingAlgorithm = "HmacSHA256";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signingKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenPrefixBytes = versionBytes + timestampBytes + initializationVectorBytes;
| import static com.macasaet.fernet.Constants.cipherTransformation;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.encryptionAlgorithm;
import static com.macasaet.fernet.Constants.encryptionKeyBytes;
import static com.macasaet.fernet.Constants.fernetKeyBytes;
import static com.macasaet.fernet.Constants.signingAlgorithm;
import static com.macasaet.fernet.Constants.signingKeyBytes;
import static com.macasaet.fernet.Constants.tokenPrefixBytes;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.copyOfRange;
import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64.Encoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; | * @return the raw underlying signing key bytes
*/
@SuppressWarnings("PMD.MethodReturnsInternalArray")
protected byte[] getSigningKey() {
return signingKey;
}
/**
* Warning: Modifying the returned byte array will write through to this object.
*
* @return the raw underlying encryption key bytes
*/
@SuppressWarnings("PMD.MethodReturnsInternalArray")
protected byte[] getEncryptionKey() {
return encryptionKey;
}
protected int getTokenPrefixBytes() {
return tokenPrefixBytes;
}
protected String getSigningAlgorithm() {
return signingAlgorithm;
}
protected String getEncryptionAlgorithm() {
return encryptionAlgorithm;
}
protected Encoder getEncoder() { | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String cipherTransformation = encryptionAlgorithm + "/CBC/PKCS5Padding";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String encryptionAlgorithm = "AES";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int encryptionKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int fernetKeyBytes = signingKeyBytes + encryptionKeyBytes;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final String signingAlgorithm = "HmacSHA256";
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signingKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenPrefixBytes = versionBytes + timestampBytes + initializationVectorBytes;
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Key.java
import static com.macasaet.fernet.Constants.cipherTransformation;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.encryptionAlgorithm;
import static com.macasaet.fernet.Constants.encryptionKeyBytes;
import static com.macasaet.fernet.Constants.fernetKeyBytes;
import static com.macasaet.fernet.Constants.signingAlgorithm;
import static com.macasaet.fernet.Constants.signingKeyBytes;
import static com.macasaet.fernet.Constants.tokenPrefixBytes;
import static java.util.Arrays.copyOf;
import static java.util.Arrays.copyOfRange;
import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64.Encoder;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.Mac;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
* @return the raw underlying signing key bytes
*/
@SuppressWarnings("PMD.MethodReturnsInternalArray")
protected byte[] getSigningKey() {
return signingKey;
}
/**
* Warning: Modifying the returned byte array will write through to this object.
*
* @return the raw underlying encryption key bytes
*/
@SuppressWarnings("PMD.MethodReturnsInternalArray")
protected byte[] getEncryptionKey() {
return encryptionKey;
}
protected int getTokenPrefixBytes() {
return tokenPrefixBytes;
}
protected String getSigningAlgorithm() {
return signingAlgorithm;
}
protected String getEncryptionAlgorithm() {
return encryptionAlgorithm;
}
protected Encoder getEncoder() { | return encoder; |
l0s/fernet-java8 | fernet-jersey-auth/src/main/java/com/macasaet/fernet/jersey/FernetSecretFeature.java | // Path: fernet-jersey-auth/src/main/java/com/macasaet/fernet/jaxrs/exception/IllegalTokenExceptionMapper.java
// @Provider
// public class IllegalTokenExceptionMapper implements ExceptionMapper<IllegalTokenException> {
//
// public Response toResponse(final IllegalTokenException exception) {
// return new NotAuthorizedException("Bearer error=\"invalid_token\", error_description=\"mal-formed token\"").getResponse();
// }
//
// }
//
// Path: fernet-jersey-auth/src/main/java/com/macasaet/fernet/jaxrs/exception/TokenValidationExceptionMapper.java
// @Provider
// @SuppressWarnings("PMD.LawOfDemeter")
// public class TokenValidationExceptionMapper implements ExceptionMapper<TokenValidationException> {
//
// public Response toResponse(final TokenValidationException exception) {
// if (exception instanceof PayloadValidationException) {
// return status(FORBIDDEN).entity("Request could not be validated.").type(TEXT_PLAIN_TYPE).build();
// }
// return new NotAuthorizedException("Bearer error=\"invalid_token\"").getResponse();
// }
//
// }
| import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import com.macasaet.fernet.jaxrs.exception.IllegalTokenExceptionMapper;
import com.macasaet.fernet.jaxrs.exception.TokenValidationExceptionMapper; | /**
Copyright 2018 Carlos Macasaet
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
https://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.macasaet.fernet.jersey;
/**
* {@link Feature} that enables Fernet payload injection into Resource method parameters. In order to use this, the
* application will also need to register a custom {@link com.macasaet.fernet.Validator Validator} that extracts the
* payload from the token and a {@link java.util.function.Supplier Supplier<Collection<Key>>} that provides
* valid Fernet keys.
*
* <p>Copyright © 2018 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
* @see com.macasaet.fernet.jaxrs.FernetSecret
*/
public class FernetSecretFeature implements Feature {
public boolean configure(final FeatureContext context) {
context.register(new FernetSecretBinder()); | // Path: fernet-jersey-auth/src/main/java/com/macasaet/fernet/jaxrs/exception/IllegalTokenExceptionMapper.java
// @Provider
// public class IllegalTokenExceptionMapper implements ExceptionMapper<IllegalTokenException> {
//
// public Response toResponse(final IllegalTokenException exception) {
// return new NotAuthorizedException("Bearer error=\"invalid_token\", error_description=\"mal-formed token\"").getResponse();
// }
//
// }
//
// Path: fernet-jersey-auth/src/main/java/com/macasaet/fernet/jaxrs/exception/TokenValidationExceptionMapper.java
// @Provider
// @SuppressWarnings("PMD.LawOfDemeter")
// public class TokenValidationExceptionMapper implements ExceptionMapper<TokenValidationException> {
//
// public Response toResponse(final TokenValidationException exception) {
// if (exception instanceof PayloadValidationException) {
// return status(FORBIDDEN).entity("Request could not be validated.").type(TEXT_PLAIN_TYPE).build();
// }
// return new NotAuthorizedException("Bearer error=\"invalid_token\"").getResponse();
// }
//
// }
// Path: fernet-jersey-auth/src/main/java/com/macasaet/fernet/jersey/FernetSecretFeature.java
import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import com.macasaet.fernet.jaxrs.exception.IllegalTokenExceptionMapper;
import com.macasaet.fernet.jaxrs.exception.TokenValidationExceptionMapper;
/**
Copyright 2018 Carlos Macasaet
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
https://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.macasaet.fernet.jersey;
/**
* {@link Feature} that enables Fernet payload injection into Resource method parameters. In order to use this, the
* application will also need to register a custom {@link com.macasaet.fernet.Validator Validator} that extracts the
* payload from the token and a {@link java.util.function.Supplier Supplier<Collection<Key>>} that provides
* valid Fernet keys.
*
* <p>Copyright © 2018 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
* @see com.macasaet.fernet.jaxrs.FernetSecret
*/
public class FernetSecretFeature implements Feature {
public boolean configure(final FeatureContext context) {
context.register(new FernetSecretBinder()); | context.register(TokenValidationExceptionMapper.class); |
l0s/fernet-java8 | fernet-jersey-auth/src/main/java/com/macasaet/fernet/jersey/FernetSecretFeature.java | // Path: fernet-jersey-auth/src/main/java/com/macasaet/fernet/jaxrs/exception/IllegalTokenExceptionMapper.java
// @Provider
// public class IllegalTokenExceptionMapper implements ExceptionMapper<IllegalTokenException> {
//
// public Response toResponse(final IllegalTokenException exception) {
// return new NotAuthorizedException("Bearer error=\"invalid_token\", error_description=\"mal-formed token\"").getResponse();
// }
//
// }
//
// Path: fernet-jersey-auth/src/main/java/com/macasaet/fernet/jaxrs/exception/TokenValidationExceptionMapper.java
// @Provider
// @SuppressWarnings("PMD.LawOfDemeter")
// public class TokenValidationExceptionMapper implements ExceptionMapper<TokenValidationException> {
//
// public Response toResponse(final TokenValidationException exception) {
// if (exception instanceof PayloadValidationException) {
// return status(FORBIDDEN).entity("Request could not be validated.").type(TEXT_PLAIN_TYPE).build();
// }
// return new NotAuthorizedException("Bearer error=\"invalid_token\"").getResponse();
// }
//
// }
| import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import com.macasaet.fernet.jaxrs.exception.IllegalTokenExceptionMapper;
import com.macasaet.fernet.jaxrs.exception.TokenValidationExceptionMapper; | /**
Copyright 2018 Carlos Macasaet
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
https://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.macasaet.fernet.jersey;
/**
* {@link Feature} that enables Fernet payload injection into Resource method parameters. In order to use this, the
* application will also need to register a custom {@link com.macasaet.fernet.Validator Validator} that extracts the
* payload from the token and a {@link java.util.function.Supplier Supplier<Collection<Key>>} that provides
* valid Fernet keys.
*
* <p>Copyright © 2018 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
* @see com.macasaet.fernet.jaxrs.FernetSecret
*/
public class FernetSecretFeature implements Feature {
public boolean configure(final FeatureContext context) {
context.register(new FernetSecretBinder());
context.register(TokenValidationExceptionMapper.class); | // Path: fernet-jersey-auth/src/main/java/com/macasaet/fernet/jaxrs/exception/IllegalTokenExceptionMapper.java
// @Provider
// public class IllegalTokenExceptionMapper implements ExceptionMapper<IllegalTokenException> {
//
// public Response toResponse(final IllegalTokenException exception) {
// return new NotAuthorizedException("Bearer error=\"invalid_token\", error_description=\"mal-formed token\"").getResponse();
// }
//
// }
//
// Path: fernet-jersey-auth/src/main/java/com/macasaet/fernet/jaxrs/exception/TokenValidationExceptionMapper.java
// @Provider
// @SuppressWarnings("PMD.LawOfDemeter")
// public class TokenValidationExceptionMapper implements ExceptionMapper<TokenValidationException> {
//
// public Response toResponse(final TokenValidationException exception) {
// if (exception instanceof PayloadValidationException) {
// return status(FORBIDDEN).entity("Request could not be validated.").type(TEXT_PLAIN_TYPE).build();
// }
// return new NotAuthorizedException("Bearer error=\"invalid_token\"").getResponse();
// }
//
// }
// Path: fernet-jersey-auth/src/main/java/com/macasaet/fernet/jersey/FernetSecretFeature.java
import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import com.macasaet.fernet.jaxrs.exception.IllegalTokenExceptionMapper;
import com.macasaet.fernet.jaxrs.exception.TokenValidationExceptionMapper;
/**
Copyright 2018 Carlos Macasaet
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
https://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.macasaet.fernet.jersey;
/**
* {@link Feature} that enables Fernet payload injection into Resource method parameters. In order to use this, the
* application will also need to register a custom {@link com.macasaet.fernet.Validator Validator} that extracts the
* payload from the token and a {@link java.util.function.Supplier Supplier<Collection<Key>>} that provides
* valid Fernet keys.
*
* <p>Copyright © 2018 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
* @see com.macasaet.fernet.jaxrs.FernetSecret
*/
public class FernetSecretFeature implements Feature {
public boolean configure(final FeatureContext context) {
context.register(new FernetSecretBinder());
context.register(TokenValidationExceptionMapper.class); | context.register(IllegalTokenExceptionMapper.class); |
l0s/fernet-java8 | fernet-java8/src/test/java/com/macasaet/fernet/example/autofill/AutofillExampleIT.java | // Path: fernet-java8/src/test/java/com/macasaet/fernet/example/autofill/Client.java
// public static class Form {
// public String notificationType;
// public String firstName;
// public String lastName;
// public String emailAddress;
// public boolean autofilled = false;
// }
| import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import org.junit.Test;
import com.macasaet.fernet.example.autofill.Client.Form; | /**
Copyright 2017 Carlos Macasaet
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.macasaet.fernet.example.autofill;
/**
* <p>In this example, a website presents a form that requires a user to provide personally-identifying information in
* order to sign up for various types of notifications. In this scenario, the user may wish to register for multiple
* notification types. In order to streamline subsequent registrations, we would like to auto-fill the form. However, if
* the user's computer is compromised, we do not want to allow third-parties to glean the user's personal information.</p>
*
* <p>In this example, the server embeds the user's personal information in a Fernet token. The client is responsible for
* storing it.</p>
*
* <p>Copyright © 2017 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
*/
public class AutofillExampleIT {
private Instant now = Instant.now();
private Clock clock = new Clock() {
public Clock withZone(ZoneId zone) {
return this;
}
public Instant instant() {
return now;
}
public ZoneId getZone() {
return ZoneOffset.UTC;
}
};
private final Server server = new Server(clock);
private final Client client = new Client(clock, server);
@Test
public final void demo() throws Exception {
// the first time the form is presented, all the information must be provided | // Path: fernet-java8/src/test/java/com/macasaet/fernet/example/autofill/Client.java
// public static class Form {
// public String notificationType;
// public String firstName;
// public String lastName;
// public String emailAddress;
// public boolean autofilled = false;
// }
// Path: fernet-java8/src/test/java/com/macasaet/fernet/example/autofill/AutofillExampleIT.java
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import org.junit.Test;
import com.macasaet.fernet.example.autofill.Client.Form;
/**
Copyright 2017 Carlos Macasaet
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.macasaet.fernet.example.autofill;
/**
* <p>In this example, a website presents a form that requires a user to provide personally-identifying information in
* order to sign up for various types of notifications. In this scenario, the user may wish to register for multiple
* notification types. In order to streamline subsequent registrations, we would like to auto-fill the form. However, if
* the user's computer is compromised, we do not want to allow third-parties to glean the user's personal information.</p>
*
* <p>In this example, the server embeds the user's personal information in a Fernet token. The client is responsible for
* storing it.</p>
*
* <p>Copyright © 2017 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
*/
public class AutofillExampleIT {
private Instant now = Instant.now();
private Clock clock = new Clock() {
public Clock withZone(ZoneId zone) {
return this;
}
public Instant instant() {
return now;
}
public ZoneId getZone() {
return ZoneOffset.UTC;
}
};
private final Server server = new Server(clock);
private final Client client = new Client(clock, server);
@Test
public final void demo() throws Exception {
// the first time the form is presented, all the information must be provided | Form form = client.renderForm(); |
l0s/fernet-java8 | fernet-java8/src/main/java/com/macasaet/fernet/Token.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int cipherTextBlockSize = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int initializationVectorBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int minimumTokenBytes = tokenStaticBytes + cipherTextBlockSize;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signatureBytes = 32;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final byte supportedVersion = (byte) 0x80;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenStaticBytes = versionBytes + timestampBytes + initializationVectorBytes + signatureBytes;
| import static com.macasaet.fernet.Constants.charset;
import static com.macasaet.fernet.Constants.cipherTextBlockSize;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.initializationVectorBytes;
import static com.macasaet.fernet.Constants.minimumTokenBytes;
import static com.macasaet.fernet.Constants.signatureBytes;
import static com.macasaet.fernet.Constants.supportedVersion;
import static com.macasaet.fernet.Constants.tokenStaticBytes;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Base64.Encoder;
import java.util.Collection;
import javax.crypto.spec.IvParameterSpec; | /**
Copyright 2017 Carlos Macasaet
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.macasaet.fernet;
/**
* A Fernet token.
*
* <p>Copyright © 2017 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
*/
@SuppressWarnings({"PMD.TooManyMethods", "PMD.AvoidDuplicateLiterals"})
/*
* TooManyMethods can be avoided by making the following API-breaking changes:
* * remove the static `generate` methods and introduce a `TokenFactory` or `TokenBuilder`
* * remove the public `validateAndDecrypt` methods since they are already available in the `Validator` interface
*
* AvoidDuplicateLiterals is from the method-level @SuppressWarnings annotations
*/
public class Token {
private final byte version;
private final Instant timestamp;
private final IvParameterSpec initializationVector;
private final byte[] cipherText;
private final byte[] hmac;
/**
* <p>Initialise a new Token from raw components. No validation of the signature is performed. However, the other
* fields are validated to ensure they conform to the Fernet specification.</p>
*
* <p>Warning: Subsequent modifications to the input arrays will write through to this object.</p>
*
* @param version
* The version of the Fernet token specification. Currently, only 0x80 is supported.
* @param timestamp
* the time the token was generated
* @param initializationVector
* the randomly-generated bytes used to initialise the encryption cipher
* @param cipherText
* the encrypted the encrypted payload
* @param hmac
* the signature of the token
*/
@SuppressWarnings({"PMD.ArrayIsStoredDirectly", "PMD.CyclomaticComplexity"})
protected Token(final byte version, final Instant timestamp, final IvParameterSpec initializationVector,
final byte[] cipherText, final byte[] hmac) { | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int cipherTextBlockSize = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int initializationVectorBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int minimumTokenBytes = tokenStaticBytes + cipherTextBlockSize;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signatureBytes = 32;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final byte supportedVersion = (byte) 0x80;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenStaticBytes = versionBytes + timestampBytes + initializationVectorBytes + signatureBytes;
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Token.java
import static com.macasaet.fernet.Constants.charset;
import static com.macasaet.fernet.Constants.cipherTextBlockSize;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.initializationVectorBytes;
import static com.macasaet.fernet.Constants.minimumTokenBytes;
import static com.macasaet.fernet.Constants.signatureBytes;
import static com.macasaet.fernet.Constants.supportedVersion;
import static com.macasaet.fernet.Constants.tokenStaticBytes;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Base64.Encoder;
import java.util.Collection;
import javax.crypto.spec.IvParameterSpec;
/**
Copyright 2017 Carlos Macasaet
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.macasaet.fernet;
/**
* A Fernet token.
*
* <p>Copyright © 2017 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
*/
@SuppressWarnings({"PMD.TooManyMethods", "PMD.AvoidDuplicateLiterals"})
/*
* TooManyMethods can be avoided by making the following API-breaking changes:
* * remove the static `generate` methods and introduce a `TokenFactory` or `TokenBuilder`
* * remove the public `validateAndDecrypt` methods since they are already available in the `Validator` interface
*
* AvoidDuplicateLiterals is from the method-level @SuppressWarnings annotations
*/
public class Token {
private final byte version;
private final Instant timestamp;
private final IvParameterSpec initializationVector;
private final byte[] cipherText;
private final byte[] hmac;
/**
* <p>Initialise a new Token from raw components. No validation of the signature is performed. However, the other
* fields are validated to ensure they conform to the Fernet specification.</p>
*
* <p>Warning: Subsequent modifications to the input arrays will write through to this object.</p>
*
* @param version
* The version of the Fernet token specification. Currently, only 0x80 is supported.
* @param timestamp
* the time the token was generated
* @param initializationVector
* the randomly-generated bytes used to initialise the encryption cipher
* @param cipherText
* the encrypted the encrypted payload
* @param hmac
* the signature of the token
*/
@SuppressWarnings({"PMD.ArrayIsStoredDirectly", "PMD.CyclomaticComplexity"})
protected Token(final byte version, final Instant timestamp, final IvParameterSpec initializationVector,
final byte[] cipherText, final byte[] hmac) { | if (version != supportedVersion) { |
l0s/fernet-java8 | fernet-java8/src/main/java/com/macasaet/fernet/Token.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int cipherTextBlockSize = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int initializationVectorBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int minimumTokenBytes = tokenStaticBytes + cipherTextBlockSize;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signatureBytes = 32;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final byte supportedVersion = (byte) 0x80;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenStaticBytes = versionBytes + timestampBytes + initializationVectorBytes + signatureBytes;
| import static com.macasaet.fernet.Constants.charset;
import static com.macasaet.fernet.Constants.cipherTextBlockSize;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.initializationVectorBytes;
import static com.macasaet.fernet.Constants.minimumTokenBytes;
import static com.macasaet.fernet.Constants.signatureBytes;
import static com.macasaet.fernet.Constants.supportedVersion;
import static com.macasaet.fernet.Constants.tokenStaticBytes;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Base64.Encoder;
import java.util.Collection;
import javax.crypto.spec.IvParameterSpec; | /**
Copyright 2017 Carlos Macasaet
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.macasaet.fernet;
/**
* A Fernet token.
*
* <p>Copyright © 2017 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
*/
@SuppressWarnings({"PMD.TooManyMethods", "PMD.AvoidDuplicateLiterals"})
/*
* TooManyMethods can be avoided by making the following API-breaking changes:
* * remove the static `generate` methods and introduce a `TokenFactory` or `TokenBuilder`
* * remove the public `validateAndDecrypt` methods since they are already available in the `Validator` interface
*
* AvoidDuplicateLiterals is from the method-level @SuppressWarnings annotations
*/
public class Token {
private final byte version;
private final Instant timestamp;
private final IvParameterSpec initializationVector;
private final byte[] cipherText;
private final byte[] hmac;
/**
* <p>Initialise a new Token from raw components. No validation of the signature is performed. However, the other
* fields are validated to ensure they conform to the Fernet specification.</p>
*
* <p>Warning: Subsequent modifications to the input arrays will write through to this object.</p>
*
* @param version
* The version of the Fernet token specification. Currently, only 0x80 is supported.
* @param timestamp
* the time the token was generated
* @param initializationVector
* the randomly-generated bytes used to initialise the encryption cipher
* @param cipherText
* the encrypted the encrypted payload
* @param hmac
* the signature of the token
*/
@SuppressWarnings({"PMD.ArrayIsStoredDirectly", "PMD.CyclomaticComplexity"})
protected Token(final byte version, final Instant timestamp, final IvParameterSpec initializationVector,
final byte[] cipherText, final byte[] hmac) {
if (version != supportedVersion) {
throw new IllegalTokenException("Unsupported version: " + version);
}
if (timestamp == null) {
throw new IllegalTokenException("timestamp cannot be null");
} | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int cipherTextBlockSize = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int initializationVectorBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int minimumTokenBytes = tokenStaticBytes + cipherTextBlockSize;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signatureBytes = 32;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final byte supportedVersion = (byte) 0x80;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenStaticBytes = versionBytes + timestampBytes + initializationVectorBytes + signatureBytes;
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Token.java
import static com.macasaet.fernet.Constants.charset;
import static com.macasaet.fernet.Constants.cipherTextBlockSize;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.initializationVectorBytes;
import static com.macasaet.fernet.Constants.minimumTokenBytes;
import static com.macasaet.fernet.Constants.signatureBytes;
import static com.macasaet.fernet.Constants.supportedVersion;
import static com.macasaet.fernet.Constants.tokenStaticBytes;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Base64.Encoder;
import java.util.Collection;
import javax.crypto.spec.IvParameterSpec;
/**
Copyright 2017 Carlos Macasaet
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.macasaet.fernet;
/**
* A Fernet token.
*
* <p>Copyright © 2017 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
*/
@SuppressWarnings({"PMD.TooManyMethods", "PMD.AvoidDuplicateLiterals"})
/*
* TooManyMethods can be avoided by making the following API-breaking changes:
* * remove the static `generate` methods and introduce a `TokenFactory` or `TokenBuilder`
* * remove the public `validateAndDecrypt` methods since they are already available in the `Validator` interface
*
* AvoidDuplicateLiterals is from the method-level @SuppressWarnings annotations
*/
public class Token {
private final byte version;
private final Instant timestamp;
private final IvParameterSpec initializationVector;
private final byte[] cipherText;
private final byte[] hmac;
/**
* <p>Initialise a new Token from raw components. No validation of the signature is performed. However, the other
* fields are validated to ensure they conform to the Fernet specification.</p>
*
* <p>Warning: Subsequent modifications to the input arrays will write through to this object.</p>
*
* @param version
* The version of the Fernet token specification. Currently, only 0x80 is supported.
* @param timestamp
* the time the token was generated
* @param initializationVector
* the randomly-generated bytes used to initialise the encryption cipher
* @param cipherText
* the encrypted the encrypted payload
* @param hmac
* the signature of the token
*/
@SuppressWarnings({"PMD.ArrayIsStoredDirectly", "PMD.CyclomaticComplexity"})
protected Token(final byte version, final Instant timestamp, final IvParameterSpec initializationVector,
final byte[] cipherText, final byte[] hmac) {
if (version != supportedVersion) {
throw new IllegalTokenException("Unsupported version: " + version);
}
if (timestamp == null) {
throw new IllegalTokenException("timestamp cannot be null");
} | if (initializationVector == null || initializationVector.getIV().length != initializationVectorBytes) { |
l0s/fernet-java8 | fernet-java8/src/main/java/com/macasaet/fernet/Token.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int cipherTextBlockSize = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int initializationVectorBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int minimumTokenBytes = tokenStaticBytes + cipherTextBlockSize;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signatureBytes = 32;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final byte supportedVersion = (byte) 0x80;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenStaticBytes = versionBytes + timestampBytes + initializationVectorBytes + signatureBytes;
| import static com.macasaet.fernet.Constants.charset;
import static com.macasaet.fernet.Constants.cipherTextBlockSize;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.initializationVectorBytes;
import static com.macasaet.fernet.Constants.minimumTokenBytes;
import static com.macasaet.fernet.Constants.signatureBytes;
import static com.macasaet.fernet.Constants.supportedVersion;
import static com.macasaet.fernet.Constants.tokenStaticBytes;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Base64.Encoder;
import java.util.Collection;
import javax.crypto.spec.IvParameterSpec; | /**
Copyright 2017 Carlos Macasaet
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.macasaet.fernet;
/**
* A Fernet token.
*
* <p>Copyright © 2017 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
*/
@SuppressWarnings({"PMD.TooManyMethods", "PMD.AvoidDuplicateLiterals"})
/*
* TooManyMethods can be avoided by making the following API-breaking changes:
* * remove the static `generate` methods and introduce a `TokenFactory` or `TokenBuilder`
* * remove the public `validateAndDecrypt` methods since they are already available in the `Validator` interface
*
* AvoidDuplicateLiterals is from the method-level @SuppressWarnings annotations
*/
public class Token {
private final byte version;
private final Instant timestamp;
private final IvParameterSpec initializationVector;
private final byte[] cipherText;
private final byte[] hmac;
/**
* <p>Initialise a new Token from raw components. No validation of the signature is performed. However, the other
* fields are validated to ensure they conform to the Fernet specification.</p>
*
* <p>Warning: Subsequent modifications to the input arrays will write through to this object.</p>
*
* @param version
* The version of the Fernet token specification. Currently, only 0x80 is supported.
* @param timestamp
* the time the token was generated
* @param initializationVector
* the randomly-generated bytes used to initialise the encryption cipher
* @param cipherText
* the encrypted the encrypted payload
* @param hmac
* the signature of the token
*/
@SuppressWarnings({"PMD.ArrayIsStoredDirectly", "PMD.CyclomaticComplexity"})
protected Token(final byte version, final Instant timestamp, final IvParameterSpec initializationVector,
final byte[] cipherText, final byte[] hmac) {
if (version != supportedVersion) {
throw new IllegalTokenException("Unsupported version: " + version);
}
if (timestamp == null) {
throw new IllegalTokenException("timestamp cannot be null");
}
if (initializationVector == null || initializationVector.getIV().length != initializationVectorBytes) {
throw new IllegalTokenException("Initialization Vector must be 128 bits");
} | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int cipherTextBlockSize = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int initializationVectorBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int minimumTokenBytes = tokenStaticBytes + cipherTextBlockSize;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signatureBytes = 32;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final byte supportedVersion = (byte) 0x80;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenStaticBytes = versionBytes + timestampBytes + initializationVectorBytes + signatureBytes;
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Token.java
import static com.macasaet.fernet.Constants.charset;
import static com.macasaet.fernet.Constants.cipherTextBlockSize;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.initializationVectorBytes;
import static com.macasaet.fernet.Constants.minimumTokenBytes;
import static com.macasaet.fernet.Constants.signatureBytes;
import static com.macasaet.fernet.Constants.supportedVersion;
import static com.macasaet.fernet.Constants.tokenStaticBytes;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Base64.Encoder;
import java.util.Collection;
import javax.crypto.spec.IvParameterSpec;
/**
Copyright 2017 Carlos Macasaet
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.macasaet.fernet;
/**
* A Fernet token.
*
* <p>Copyright © 2017 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
*/
@SuppressWarnings({"PMD.TooManyMethods", "PMD.AvoidDuplicateLiterals"})
/*
* TooManyMethods can be avoided by making the following API-breaking changes:
* * remove the static `generate` methods and introduce a `TokenFactory` or `TokenBuilder`
* * remove the public `validateAndDecrypt` methods since they are already available in the `Validator` interface
*
* AvoidDuplicateLiterals is from the method-level @SuppressWarnings annotations
*/
public class Token {
private final byte version;
private final Instant timestamp;
private final IvParameterSpec initializationVector;
private final byte[] cipherText;
private final byte[] hmac;
/**
* <p>Initialise a new Token from raw components. No validation of the signature is performed. However, the other
* fields are validated to ensure they conform to the Fernet specification.</p>
*
* <p>Warning: Subsequent modifications to the input arrays will write through to this object.</p>
*
* @param version
* The version of the Fernet token specification. Currently, only 0x80 is supported.
* @param timestamp
* the time the token was generated
* @param initializationVector
* the randomly-generated bytes used to initialise the encryption cipher
* @param cipherText
* the encrypted the encrypted payload
* @param hmac
* the signature of the token
*/
@SuppressWarnings({"PMD.ArrayIsStoredDirectly", "PMD.CyclomaticComplexity"})
protected Token(final byte version, final Instant timestamp, final IvParameterSpec initializationVector,
final byte[] cipherText, final byte[] hmac) {
if (version != supportedVersion) {
throw new IllegalTokenException("Unsupported version: " + version);
}
if (timestamp == null) {
throw new IllegalTokenException("timestamp cannot be null");
}
if (initializationVector == null || initializationVector.getIV().length != initializationVectorBytes) {
throw new IllegalTokenException("Initialization Vector must be 128 bits");
} | if (cipherText == null || cipherText.length % cipherTextBlockSize != 0) { |
l0s/fernet-java8 | fernet-java8/src/main/java/com/macasaet/fernet/Token.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int cipherTextBlockSize = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int initializationVectorBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int minimumTokenBytes = tokenStaticBytes + cipherTextBlockSize;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signatureBytes = 32;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final byte supportedVersion = (byte) 0x80;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenStaticBytes = versionBytes + timestampBytes + initializationVectorBytes + signatureBytes;
| import static com.macasaet.fernet.Constants.charset;
import static com.macasaet.fernet.Constants.cipherTextBlockSize;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.initializationVectorBytes;
import static com.macasaet.fernet.Constants.minimumTokenBytes;
import static com.macasaet.fernet.Constants.signatureBytes;
import static com.macasaet.fernet.Constants.supportedVersion;
import static com.macasaet.fernet.Constants.tokenStaticBytes;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Base64.Encoder;
import java.util.Collection;
import javax.crypto.spec.IvParameterSpec; | /**
Copyright 2017 Carlos Macasaet
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.macasaet.fernet;
/**
* A Fernet token.
*
* <p>Copyright © 2017 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
*/
@SuppressWarnings({"PMD.TooManyMethods", "PMD.AvoidDuplicateLiterals"})
/*
* TooManyMethods can be avoided by making the following API-breaking changes:
* * remove the static `generate` methods and introduce a `TokenFactory` or `TokenBuilder`
* * remove the public `validateAndDecrypt` methods since they are already available in the `Validator` interface
*
* AvoidDuplicateLiterals is from the method-level @SuppressWarnings annotations
*/
public class Token {
private final byte version;
private final Instant timestamp;
private final IvParameterSpec initializationVector;
private final byte[] cipherText;
private final byte[] hmac;
/**
* <p>Initialise a new Token from raw components. No validation of the signature is performed. However, the other
* fields are validated to ensure they conform to the Fernet specification.</p>
*
* <p>Warning: Subsequent modifications to the input arrays will write through to this object.</p>
*
* @param version
* The version of the Fernet token specification. Currently, only 0x80 is supported.
* @param timestamp
* the time the token was generated
* @param initializationVector
* the randomly-generated bytes used to initialise the encryption cipher
* @param cipherText
* the encrypted the encrypted payload
* @param hmac
* the signature of the token
*/
@SuppressWarnings({"PMD.ArrayIsStoredDirectly", "PMD.CyclomaticComplexity"})
protected Token(final byte version, final Instant timestamp, final IvParameterSpec initializationVector,
final byte[] cipherText, final byte[] hmac) {
if (version != supportedVersion) {
throw new IllegalTokenException("Unsupported version: " + version);
}
if (timestamp == null) {
throw new IllegalTokenException("timestamp cannot be null");
}
if (initializationVector == null || initializationVector.getIV().length != initializationVectorBytes) {
throw new IllegalTokenException("Initialization Vector must be 128 bits");
}
if (cipherText == null || cipherText.length % cipherTextBlockSize != 0) {
throw new IllegalTokenException("Ciphertext must be a multiple of 128 bits");
} | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int cipherTextBlockSize = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int initializationVectorBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int minimumTokenBytes = tokenStaticBytes + cipherTextBlockSize;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signatureBytes = 32;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final byte supportedVersion = (byte) 0x80;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenStaticBytes = versionBytes + timestampBytes + initializationVectorBytes + signatureBytes;
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Token.java
import static com.macasaet.fernet.Constants.charset;
import static com.macasaet.fernet.Constants.cipherTextBlockSize;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.initializationVectorBytes;
import static com.macasaet.fernet.Constants.minimumTokenBytes;
import static com.macasaet.fernet.Constants.signatureBytes;
import static com.macasaet.fernet.Constants.supportedVersion;
import static com.macasaet.fernet.Constants.tokenStaticBytes;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Base64.Encoder;
import java.util.Collection;
import javax.crypto.spec.IvParameterSpec;
/**
Copyright 2017 Carlos Macasaet
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.macasaet.fernet;
/**
* A Fernet token.
*
* <p>Copyright © 2017 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
*/
@SuppressWarnings({"PMD.TooManyMethods", "PMD.AvoidDuplicateLiterals"})
/*
* TooManyMethods can be avoided by making the following API-breaking changes:
* * remove the static `generate` methods and introduce a `TokenFactory` or `TokenBuilder`
* * remove the public `validateAndDecrypt` methods since they are already available in the `Validator` interface
*
* AvoidDuplicateLiterals is from the method-level @SuppressWarnings annotations
*/
public class Token {
private final byte version;
private final Instant timestamp;
private final IvParameterSpec initializationVector;
private final byte[] cipherText;
private final byte[] hmac;
/**
* <p>Initialise a new Token from raw components. No validation of the signature is performed. However, the other
* fields are validated to ensure they conform to the Fernet specification.</p>
*
* <p>Warning: Subsequent modifications to the input arrays will write through to this object.</p>
*
* @param version
* The version of the Fernet token specification. Currently, only 0x80 is supported.
* @param timestamp
* the time the token was generated
* @param initializationVector
* the randomly-generated bytes used to initialise the encryption cipher
* @param cipherText
* the encrypted the encrypted payload
* @param hmac
* the signature of the token
*/
@SuppressWarnings({"PMD.ArrayIsStoredDirectly", "PMD.CyclomaticComplexity"})
protected Token(final byte version, final Instant timestamp, final IvParameterSpec initializationVector,
final byte[] cipherText, final byte[] hmac) {
if (version != supportedVersion) {
throw new IllegalTokenException("Unsupported version: " + version);
}
if (timestamp == null) {
throw new IllegalTokenException("timestamp cannot be null");
}
if (initializationVector == null || initializationVector.getIV().length != initializationVectorBytes) {
throw new IllegalTokenException("Initialization Vector must be 128 bits");
}
if (cipherText == null || cipherText.length % cipherTextBlockSize != 0) {
throw new IllegalTokenException("Ciphertext must be a multiple of 128 bits");
} | if (hmac == null || hmac.length != signatureBytes) { |
l0s/fernet-java8 | fernet-java8/src/main/java/com/macasaet/fernet/Token.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int cipherTextBlockSize = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int initializationVectorBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int minimumTokenBytes = tokenStaticBytes + cipherTextBlockSize;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signatureBytes = 32;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final byte supportedVersion = (byte) 0x80;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenStaticBytes = versionBytes + timestampBytes + initializationVectorBytes + signatureBytes;
| import static com.macasaet.fernet.Constants.charset;
import static com.macasaet.fernet.Constants.cipherTextBlockSize;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.initializationVectorBytes;
import static com.macasaet.fernet.Constants.minimumTokenBytes;
import static com.macasaet.fernet.Constants.signatureBytes;
import static com.macasaet.fernet.Constants.supportedVersion;
import static com.macasaet.fernet.Constants.tokenStaticBytes;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Base64.Encoder;
import java.util.Collection;
import javax.crypto.spec.IvParameterSpec; | throw new IllegalTokenException("timestamp cannot be null");
}
if (initializationVector == null || initializationVector.getIV().length != initializationVectorBytes) {
throw new IllegalTokenException("Initialization Vector must be 128 bits");
}
if (cipherText == null || cipherText.length % cipherTextBlockSize != 0) {
throw new IllegalTokenException("Ciphertext must be a multiple of 128 bits");
}
if (hmac == null || hmac.length != signatureBytes) {
throw new IllegalTokenException("hmac must be 256 bits");
}
this.version = version;
this.timestamp = timestamp;
this.initializationVector = initializationVector;
this.cipherText = cipherText;
this.hmac = hmac;
}
/**
* Read a Token from bytes. This does NOT validate that the token was
* generated using a valid {@link Key}.
*
* @param bytes a Fernet token in the form Version | Timestamp | IV |
* Ciphertext | HMAC
* @return a new Token
* @throws IllegalTokenException if the input string cannot be a valid
* token irrespective of key or timestamp.
*/
@SuppressWarnings({"PMD.PrematureDeclaration", "PMD.DataflowAnomalyAnalysis"})
public static Token fromBytes(final byte[] bytes) { | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int cipherTextBlockSize = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int initializationVectorBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int minimumTokenBytes = tokenStaticBytes + cipherTextBlockSize;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signatureBytes = 32;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final byte supportedVersion = (byte) 0x80;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenStaticBytes = versionBytes + timestampBytes + initializationVectorBytes + signatureBytes;
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Token.java
import static com.macasaet.fernet.Constants.charset;
import static com.macasaet.fernet.Constants.cipherTextBlockSize;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.initializationVectorBytes;
import static com.macasaet.fernet.Constants.minimumTokenBytes;
import static com.macasaet.fernet.Constants.signatureBytes;
import static com.macasaet.fernet.Constants.supportedVersion;
import static com.macasaet.fernet.Constants.tokenStaticBytes;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Base64.Encoder;
import java.util.Collection;
import javax.crypto.spec.IvParameterSpec;
throw new IllegalTokenException("timestamp cannot be null");
}
if (initializationVector == null || initializationVector.getIV().length != initializationVectorBytes) {
throw new IllegalTokenException("Initialization Vector must be 128 bits");
}
if (cipherText == null || cipherText.length % cipherTextBlockSize != 0) {
throw new IllegalTokenException("Ciphertext must be a multiple of 128 bits");
}
if (hmac == null || hmac.length != signatureBytes) {
throw new IllegalTokenException("hmac must be 256 bits");
}
this.version = version;
this.timestamp = timestamp;
this.initializationVector = initializationVector;
this.cipherText = cipherText;
this.hmac = hmac;
}
/**
* Read a Token from bytes. This does NOT validate that the token was
* generated using a valid {@link Key}.
*
* @param bytes a Fernet token in the form Version | Timestamp | IV |
* Ciphertext | HMAC
* @return a new Token
* @throws IllegalTokenException if the input string cannot be a valid
* token irrespective of key or timestamp.
*/
@SuppressWarnings({"PMD.PrematureDeclaration", "PMD.DataflowAnomalyAnalysis"})
public static Token fromBytes(final byte[] bytes) { | if (bytes.length < minimumTokenBytes) { |
l0s/fernet-java8 | fernet-java8/src/main/java/com/macasaet/fernet/Token.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int cipherTextBlockSize = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int initializationVectorBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int minimumTokenBytes = tokenStaticBytes + cipherTextBlockSize;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signatureBytes = 32;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final byte supportedVersion = (byte) 0x80;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenStaticBytes = versionBytes + timestampBytes + initializationVectorBytes + signatureBytes;
| import static com.macasaet.fernet.Constants.charset;
import static com.macasaet.fernet.Constants.cipherTextBlockSize;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.initializationVectorBytes;
import static com.macasaet.fernet.Constants.minimumTokenBytes;
import static com.macasaet.fernet.Constants.signatureBytes;
import static com.macasaet.fernet.Constants.supportedVersion;
import static com.macasaet.fernet.Constants.tokenStaticBytes;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Base64.Encoder;
import java.util.Collection;
import javax.crypto.spec.IvParameterSpec; | throw new IllegalTokenException("hmac must be 256 bits");
}
this.version = version;
this.timestamp = timestamp;
this.initializationVector = initializationVector;
this.cipherText = cipherText;
this.hmac = hmac;
}
/**
* Read a Token from bytes. This does NOT validate that the token was
* generated using a valid {@link Key}.
*
* @param bytes a Fernet token in the form Version | Timestamp | IV |
* Ciphertext | HMAC
* @return a new Token
* @throws IllegalTokenException if the input string cannot be a valid
* token irrespective of key or timestamp.
*/
@SuppressWarnings({"PMD.PrematureDeclaration", "PMD.DataflowAnomalyAnalysis"})
public static Token fromBytes(final byte[] bytes) {
if (bytes.length < minimumTokenBytes) {
throw new IllegalTokenException("Not enough bits to generate a Token");
}
try (ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes)) {
try (DataInputStream dataStream = new DataInputStream(inputStream)) {
final byte version = dataStream.readByte();
final long timestampSeconds = dataStream.readLong();
final byte[] initializationVector = read(dataStream, initializationVectorBytes); | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int cipherTextBlockSize = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int initializationVectorBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int minimumTokenBytes = tokenStaticBytes + cipherTextBlockSize;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signatureBytes = 32;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final byte supportedVersion = (byte) 0x80;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenStaticBytes = versionBytes + timestampBytes + initializationVectorBytes + signatureBytes;
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Token.java
import static com.macasaet.fernet.Constants.charset;
import static com.macasaet.fernet.Constants.cipherTextBlockSize;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.initializationVectorBytes;
import static com.macasaet.fernet.Constants.minimumTokenBytes;
import static com.macasaet.fernet.Constants.signatureBytes;
import static com.macasaet.fernet.Constants.supportedVersion;
import static com.macasaet.fernet.Constants.tokenStaticBytes;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Base64.Encoder;
import java.util.Collection;
import javax.crypto.spec.IvParameterSpec;
throw new IllegalTokenException("hmac must be 256 bits");
}
this.version = version;
this.timestamp = timestamp;
this.initializationVector = initializationVector;
this.cipherText = cipherText;
this.hmac = hmac;
}
/**
* Read a Token from bytes. This does NOT validate that the token was
* generated using a valid {@link Key}.
*
* @param bytes a Fernet token in the form Version | Timestamp | IV |
* Ciphertext | HMAC
* @return a new Token
* @throws IllegalTokenException if the input string cannot be a valid
* token irrespective of key or timestamp.
*/
@SuppressWarnings({"PMD.PrematureDeclaration", "PMD.DataflowAnomalyAnalysis"})
public static Token fromBytes(final byte[] bytes) {
if (bytes.length < minimumTokenBytes) {
throw new IllegalTokenException("Not enough bits to generate a Token");
}
try (ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes)) {
try (DataInputStream dataStream = new DataInputStream(inputStream)) {
final byte version = dataStream.readByte();
final long timestampSeconds = dataStream.readLong();
final byte[] initializationVector = read(dataStream, initializationVectorBytes); | final byte[] cipherText = read(dataStream, bytes.length - tokenStaticBytes); |
l0s/fernet-java8 | fernet-java8/src/main/java/com/macasaet/fernet/Token.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int cipherTextBlockSize = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int initializationVectorBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int minimumTokenBytes = tokenStaticBytes + cipherTextBlockSize;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signatureBytes = 32;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final byte supportedVersion = (byte) 0x80;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenStaticBytes = versionBytes + timestampBytes + initializationVectorBytes + signatureBytes;
| import static com.macasaet.fernet.Constants.charset;
import static com.macasaet.fernet.Constants.cipherTextBlockSize;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.initializationVectorBytes;
import static com.macasaet.fernet.Constants.minimumTokenBytes;
import static com.macasaet.fernet.Constants.signatureBytes;
import static com.macasaet.fernet.Constants.supportedVersion;
import static com.macasaet.fernet.Constants.tokenStaticBytes;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Base64.Encoder;
import java.util.Collection;
import javax.crypto.spec.IvParameterSpec; |
return new Token(version, Instant.ofEpochSecond(timestampSeconds),
new IvParameterSpec(initializationVector), cipherText, hmac);
}
} catch (final IOException ioe) {
// this should not happen as I/O is from memory and stream
// length is verified ahead of time
throw new IllegalStateException(ioe.getMessage(), ioe);
}
}
protected static byte[] read(final DataInputStream stream, final int numBytes) throws IOException {
final byte[] retval = new byte[numBytes];
final int bytesRead = stream.read(retval);
if (bytesRead < numBytes) {
throw new IllegalTokenException("Not enough bits to generate a Token");
}
return retval;
}
/**
* Deserialise a Base64 URL Fernet token string. This does NOT validate that the token was generated using a valid {@link Key}.
*
* @param string
* the Base 64 URL encoding of a token in the form Version | Timestamp | IV | Ciphertext | HMAC
* @return a new Token
* @throws IllegalTokenException
* if the input string cannot be a valid token irrespective of key or timestamp
*/
public static Token fromString(final String string) { | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int cipherTextBlockSize = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int initializationVectorBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int minimumTokenBytes = tokenStaticBytes + cipherTextBlockSize;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signatureBytes = 32;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final byte supportedVersion = (byte) 0x80;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenStaticBytes = versionBytes + timestampBytes + initializationVectorBytes + signatureBytes;
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Token.java
import static com.macasaet.fernet.Constants.charset;
import static com.macasaet.fernet.Constants.cipherTextBlockSize;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.initializationVectorBytes;
import static com.macasaet.fernet.Constants.minimumTokenBytes;
import static com.macasaet.fernet.Constants.signatureBytes;
import static com.macasaet.fernet.Constants.supportedVersion;
import static com.macasaet.fernet.Constants.tokenStaticBytes;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Base64.Encoder;
import java.util.Collection;
import javax.crypto.spec.IvParameterSpec;
return new Token(version, Instant.ofEpochSecond(timestampSeconds),
new IvParameterSpec(initializationVector), cipherText, hmac);
}
} catch (final IOException ioe) {
// this should not happen as I/O is from memory and stream
// length is verified ahead of time
throw new IllegalStateException(ioe.getMessage(), ioe);
}
}
protected static byte[] read(final DataInputStream stream, final int numBytes) throws IOException {
final byte[] retval = new byte[numBytes];
final int bytesRead = stream.read(retval);
if (bytesRead < numBytes) {
throw new IllegalTokenException("Not enough bits to generate a Token");
}
return retval;
}
/**
* Deserialise a Base64 URL Fernet token string. This does NOT validate that the token was generated using a valid {@link Key}.
*
* @param string
* the Base 64 URL encoding of a token in the form Version | Timestamp | IV | Ciphertext | HMAC
* @return a new Token
* @throws IllegalTokenException
* if the input string cannot be a valid token irrespective of key or timestamp
*/
public static Token fromString(final String string) { | return fromBytes(decoder.decode(string)); |
l0s/fernet-java8 | fernet-java8/src/main/java/com/macasaet/fernet/Token.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int cipherTextBlockSize = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int initializationVectorBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int minimumTokenBytes = tokenStaticBytes + cipherTextBlockSize;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signatureBytes = 32;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final byte supportedVersion = (byte) 0x80;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenStaticBytes = versionBytes + timestampBytes + initializationVectorBytes + signatureBytes;
| import static com.macasaet.fernet.Constants.charset;
import static com.macasaet.fernet.Constants.cipherTextBlockSize;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.initializationVectorBytes;
import static com.macasaet.fernet.Constants.minimumTokenBytes;
import static com.macasaet.fernet.Constants.signatureBytes;
import static com.macasaet.fernet.Constants.supportedVersion;
import static com.macasaet.fernet.Constants.tokenStaticBytes;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Base64.Encoder;
import java.util.Collection;
import javax.crypto.spec.IvParameterSpec; | dataStream.write(getCipherText());
dataStream.write(getHmac());
}
}
/**
* @return the Fernet specification version of this token
*/
public byte getVersion() {
return version;
}
/**
* @return the time that this token was generated
*/
public Instant getTimestamp() {
return timestamp;
}
/**
* @return the initialisation vector used to encrypt the token contents
*/
public IvParameterSpec getInitializationVector() {
return initializationVector;
}
public String toString() {
final StringBuilder builder = new StringBuilder(107);
builder.append("Token [version=").append(String.format("0x%x", new BigInteger(1, new byte[] {getVersion()})))
.append(", timestamp=").append(getTimestamp()) | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int cipherTextBlockSize = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Decoder decoder = getUrlDecoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int initializationVectorBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int minimumTokenBytes = tokenStaticBytes + cipherTextBlockSize;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signatureBytes = 32;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final byte supportedVersion = (byte) 0x80;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int tokenStaticBytes = versionBytes + timestampBytes + initializationVectorBytes + signatureBytes;
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Token.java
import static com.macasaet.fernet.Constants.charset;
import static com.macasaet.fernet.Constants.cipherTextBlockSize;
import static com.macasaet.fernet.Constants.decoder;
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.initializationVectorBytes;
import static com.macasaet.fernet.Constants.minimumTokenBytes;
import static com.macasaet.fernet.Constants.signatureBytes;
import static com.macasaet.fernet.Constants.supportedVersion;
import static com.macasaet.fernet.Constants.tokenStaticBytes;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.Base64.Encoder;
import java.util.Collection;
import javax.crypto.spec.IvParameterSpec;
dataStream.write(getCipherText());
dataStream.write(getHmac());
}
}
/**
* @return the Fernet specification version of this token
*/
public byte getVersion() {
return version;
}
/**
* @return the time that this token was generated
*/
public Instant getTimestamp() {
return timestamp;
}
/**
* @return the initialisation vector used to encrypt the token contents
*/
public IvParameterSpec getInitializationVector() {
return initializationVector;
}
public String toString() {
final StringBuilder builder = new StringBuilder(107);
builder.append("Token [version=").append(String.format("0x%x", new BigInteger(1, new byte[] {getVersion()})))
.append(", timestamp=").append(getTimestamp()) | .append(", hmac=").append(encoder.encodeToString(getHmac())).append(']'); |
l0s/fernet-java8 | fernet-java8/src/test/java/com/macasaet/fernet/KeyTest.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int encryptionKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signingKeyBytes = 16;
| import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.encryptionKeyBytes;
import static com.macasaet.fernet.Constants.signingKeyBytes;
import static nl.jqno.equalsverifier.Warning.ALL_FIELDS_SHOULD_BE_USED;
import static nl.jqno.equalsverifier.Warning.STRICT_INHERITANCE;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mutabilitydetector.unittesting.AllowedReason.allowingForSubclassing;
import static org.mutabilitydetector.unittesting.AllowedReason.assumingFields;
import static org.mutabilitydetector.unittesting.MutabilityAssert.assertInstancesOf;
import static org.mutabilitydetector.unittesting.MutabilityMatchers.areImmutable;
import java.security.SecureRandom;
import java.time.Instant;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.junit.Test;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.api.SingleTypeEqualsVerifierApi; | encryptionKey[0] = 0;
// then
assertEquals(1, key.getSigningKeySpec().getEncoded()[0]);
assertEquals(17, key.getEncryptionKeySpec().getEncoded()[0]);
}
@Test
public final void testFromString() {
// given
final String string = "AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA=";
// when
final Key key = new Key(string);
// then
assertArrayEquals(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
key.getSigningKeySpec().getEncoded());
assertArrayEquals(new byte[] {17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32},
key.getEncryptionKeySpec().getEncoded());
}
@Test
public void testGenerateKey() {
// given
final SecureRandom deterministicRandom = new SecureRandom() {
private static final long serialVersionUID = 6548702184401342900L;
public void nextBytes(final byte[] bytes) { | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int encryptionKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signingKeyBytes = 16;
// Path: fernet-java8/src/test/java/com/macasaet/fernet/KeyTest.java
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.encryptionKeyBytes;
import static com.macasaet.fernet.Constants.signingKeyBytes;
import static nl.jqno.equalsverifier.Warning.ALL_FIELDS_SHOULD_BE_USED;
import static nl.jqno.equalsverifier.Warning.STRICT_INHERITANCE;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mutabilitydetector.unittesting.AllowedReason.allowingForSubclassing;
import static org.mutabilitydetector.unittesting.AllowedReason.assumingFields;
import static org.mutabilitydetector.unittesting.MutabilityAssert.assertInstancesOf;
import static org.mutabilitydetector.unittesting.MutabilityMatchers.areImmutable;
import java.security.SecureRandom;
import java.time.Instant;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.junit.Test;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.api.SingleTypeEqualsVerifierApi;
encryptionKey[0] = 0;
// then
assertEquals(1, key.getSigningKeySpec().getEncoded()[0]);
assertEquals(17, key.getEncryptionKeySpec().getEncoded()[0]);
}
@Test
public final void testFromString() {
// given
final String string = "AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA=";
// when
final Key key = new Key(string);
// then
assertArrayEquals(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
key.getSigningKeySpec().getEncoded());
assertArrayEquals(new byte[] {17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32},
key.getEncryptionKeySpec().getEncoded());
}
@Test
public void testGenerateKey() {
// given
final SecureRandom deterministicRandom = new SecureRandom() {
private static final long serialVersionUID = 6548702184401342900L;
public void nextBytes(final byte[] bytes) { | for (int i = signingKeyBytes; --i >= 0; bytes[i] = 1); |
l0s/fernet-java8 | fernet-java8/src/test/java/com/macasaet/fernet/KeyTest.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int encryptionKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signingKeyBytes = 16;
| import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.encryptionKeyBytes;
import static com.macasaet.fernet.Constants.signingKeyBytes;
import static nl.jqno.equalsverifier.Warning.ALL_FIELDS_SHOULD_BE_USED;
import static nl.jqno.equalsverifier.Warning.STRICT_INHERITANCE;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mutabilitydetector.unittesting.AllowedReason.allowingForSubclassing;
import static org.mutabilitydetector.unittesting.AllowedReason.assumingFields;
import static org.mutabilitydetector.unittesting.MutabilityAssert.assertInstancesOf;
import static org.mutabilitydetector.unittesting.MutabilityMatchers.areImmutable;
import java.security.SecureRandom;
import java.time.Instant;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.junit.Test;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.api.SingleTypeEqualsVerifierApi; | final Key key = new Key(string);
// then
assertArrayEquals(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
key.getSigningKeySpec().getEncoded());
assertArrayEquals(new byte[] {17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32},
key.getEncryptionKeySpec().getEncoded());
}
@Test
public void testGenerateKey() {
// given
final SecureRandom deterministicRandom = new SecureRandom() {
private static final long serialVersionUID = 6548702184401342900L;
public void nextBytes(final byte[] bytes) {
for (int i = signingKeyBytes; --i >= 0; bytes[i] = 1);
}
};
// when
final Key result = Key.generateKey(deterministicRandom);
// then
final byte[] signingKey = result.getSigningKeySpec().getEncoded();
for (int i = signingKeyBytes; --i >= 0;) {
assertEquals(1, signingKey[i]);
}
final byte[] encryptionKey = result.getEncryptionKeySpec().getEncoded(); | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int encryptionKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signingKeyBytes = 16;
// Path: fernet-java8/src/test/java/com/macasaet/fernet/KeyTest.java
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.encryptionKeyBytes;
import static com.macasaet.fernet.Constants.signingKeyBytes;
import static nl.jqno.equalsverifier.Warning.ALL_FIELDS_SHOULD_BE_USED;
import static nl.jqno.equalsverifier.Warning.STRICT_INHERITANCE;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mutabilitydetector.unittesting.AllowedReason.allowingForSubclassing;
import static org.mutabilitydetector.unittesting.AllowedReason.assumingFields;
import static org.mutabilitydetector.unittesting.MutabilityAssert.assertInstancesOf;
import static org.mutabilitydetector.unittesting.MutabilityMatchers.areImmutable;
import java.security.SecureRandom;
import java.time.Instant;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.junit.Test;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.api.SingleTypeEqualsVerifierApi;
final Key key = new Key(string);
// then
assertArrayEquals(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
key.getSigningKeySpec().getEncoded());
assertArrayEquals(new byte[] {17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32},
key.getEncryptionKeySpec().getEncoded());
}
@Test
public void testGenerateKey() {
// given
final SecureRandom deterministicRandom = new SecureRandom() {
private static final long serialVersionUID = 6548702184401342900L;
public void nextBytes(final byte[] bytes) {
for (int i = signingKeyBytes; --i >= 0; bytes[i] = 1);
}
};
// when
final Key result = Key.generateKey(deterministicRandom);
// then
final byte[] signingKey = result.getSigningKeySpec().getEncoded();
for (int i = signingKeyBytes; --i >= 0;) {
assertEquals(1, signingKey[i]);
}
final byte[] encryptionKey = result.getEncryptionKeySpec().getEncoded(); | for (int i = encryptionKeyBytes; --i >= 0;) { |
l0s/fernet-java8 | fernet-java8/src/test/java/com/macasaet/fernet/KeyTest.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int encryptionKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signingKeyBytes = 16;
| import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.encryptionKeyBytes;
import static com.macasaet.fernet.Constants.signingKeyBytes;
import static nl.jqno.equalsverifier.Warning.ALL_FIELDS_SHOULD_BE_USED;
import static nl.jqno.equalsverifier.Warning.STRICT_INHERITANCE;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mutabilitydetector.unittesting.AllowedReason.allowingForSubclassing;
import static org.mutabilitydetector.unittesting.AllowedReason.assumingFields;
import static org.mutabilitydetector.unittesting.MutabilityAssert.assertInstancesOf;
import static org.mutabilitydetector.unittesting.MutabilityMatchers.areImmutable;
import java.security.SecureRandom;
import java.time.Instant;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.junit.Test;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.api.SingleTypeEqualsVerifierApi; |
public void nextBytes(final byte[] bytes) {
for (int i = signingKeyBytes; --i >= 0; bytes[i] = 1);
}
};
// when
final Key result = Key.generateKey(deterministicRandom);
// then
final byte[] signingKey = result.getSigningKeySpec().getEncoded();
for (int i = signingKeyBytes; --i >= 0;) {
assertEquals(1, signingKey[i]);
}
final byte[] encryptionKey = result.getEncryptionKeySpec().getEncoded();
for (int i = encryptionKeyBytes; --i >= 0;) {
assertEquals(1, encryptionKey[i]);
}
}
@Test
public void testGetHmac() {
// given
final Key key = new Key("AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA=");
// when
final byte[] result = key.sign((byte) 0x80, Instant.ofEpochSecond(1), new IvParameterSpec(new byte[] {2}),
new byte[] {3});
// then | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final Encoder encoder = getUrlEncoder();
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int encryptionKeyBytes = 16;
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int signingKeyBytes = 16;
// Path: fernet-java8/src/test/java/com/macasaet/fernet/KeyTest.java
import static com.macasaet.fernet.Constants.encoder;
import static com.macasaet.fernet.Constants.encryptionKeyBytes;
import static com.macasaet.fernet.Constants.signingKeyBytes;
import static nl.jqno.equalsverifier.Warning.ALL_FIELDS_SHOULD_BE_USED;
import static nl.jqno.equalsverifier.Warning.STRICT_INHERITANCE;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mutabilitydetector.unittesting.AllowedReason.allowingForSubclassing;
import static org.mutabilitydetector.unittesting.AllowedReason.assumingFields;
import static org.mutabilitydetector.unittesting.MutabilityAssert.assertInstancesOf;
import static org.mutabilitydetector.unittesting.MutabilityMatchers.areImmutable;
import java.security.SecureRandom;
import java.time.Instant;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.junit.Test;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.api.SingleTypeEqualsVerifierApi;
public void nextBytes(final byte[] bytes) {
for (int i = signingKeyBytes; --i >= 0; bytes[i] = 1);
}
};
// when
final Key result = Key.generateKey(deterministicRandom);
// then
final byte[] signingKey = result.getSigningKeySpec().getEncoded();
for (int i = signingKeyBytes; --i >= 0;) {
assertEquals(1, signingKey[i]);
}
final byte[] encryptionKey = result.getEncryptionKeySpec().getEncoded();
for (int i = encryptionKeyBytes; --i >= 0;) {
assertEquals(1, encryptionKey[i]);
}
}
@Test
public void testGetHmac() {
// given
final Key key = new Key("AQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyA=");
// when
final byte[] result = key.sign((byte) 0x80, Instant.ofEpochSecond(1), new IvParameterSpec(new byte[] {2}),
new byte[] {3});
// then | assertEquals("WvLIvt4MSCQKgeLyvltUqN8O7mvcozhsEAgIiytxypw=", encoder.encodeToString(result)); |
l0s/fernet-java8 | fernet-java8/src/test/java/com/macasaet/fernet/TokenTest.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int initializationVectorBytes = 16;
| import static com.macasaet.fernet.Constants.initializationVectorBytes;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mutabilitydetector.unittesting.AllowedReason.allowingForSubclassing;
import static org.mutabilitydetector.unittesting.AllowedReason.assumingFields;
import static org.mutabilitydetector.unittesting.AllowedReason.provided;
import static org.mutabilitydetector.unittesting.MutabilityAssert.assertInstancesOf;
import static org.mutabilitydetector.unittesting.MutabilityMatchers.areImmutable;
import java.security.SecureRandom;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.IntStream;
import javax.crypto.spec.IvParameterSpec;
import org.junit.Before;
import org.junit.Test; | assertEquals("Hello, world!", plainText);
}
@Test
public void testGenerateEmptyToken() {
// given
final SecureRandom deterministicRandom = new SecureRandom() {
private static final long serialVersionUID = 3075400891983079965L;
public void nextBytes(final byte[] bytes) {
for (int i = bytes.length; --i >= 0; bytes[i] = 1);
}
};
final Key key = Key.generateKey(deterministicRandom);
// when
final Token result = Token.generate(deterministicRandom, key, "");
// then
final String plainText = result.validateAndDecrypt(key, validator);
assertEquals("", plainText);
}
@Test
public void testDecryptKey() {
// given
final SecureRandom deterministicRandom = new SecureRandom() {
private static final long serialVersionUID = 3075400891983079965L;
public void nextBytes(final byte[] bytes) { | // Path: fernet-java8/src/main/java/com/macasaet/fernet/Constants.java
// static final int initializationVectorBytes = 16;
// Path: fernet-java8/src/test/java/com/macasaet/fernet/TokenTest.java
import static com.macasaet.fernet.Constants.initializationVectorBytes;
import static java.util.stream.Collectors.toList;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mutabilitydetector.unittesting.AllowedReason.allowingForSubclassing;
import static org.mutabilitydetector.unittesting.AllowedReason.assumingFields;
import static org.mutabilitydetector.unittesting.AllowedReason.provided;
import static org.mutabilitydetector.unittesting.MutabilityAssert.assertInstancesOf;
import static org.mutabilitydetector.unittesting.MutabilityMatchers.areImmutable;
import java.security.SecureRandom;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.IntStream;
import javax.crypto.spec.IvParameterSpec;
import org.junit.Before;
import org.junit.Test;
assertEquals("Hello, world!", plainText);
}
@Test
public void testGenerateEmptyToken() {
// given
final SecureRandom deterministicRandom = new SecureRandom() {
private static final long serialVersionUID = 3075400891983079965L;
public void nextBytes(final byte[] bytes) {
for (int i = bytes.length; --i >= 0; bytes[i] = 1);
}
};
final Key key = Key.generateKey(deterministicRandom);
// when
final Token result = Token.generate(deterministicRandom, key, "");
// then
final String plainText = result.validateAndDecrypt(key, validator);
assertEquals("", plainText);
}
@Test
public void testDecryptKey() {
// given
final SecureRandom deterministicRandom = new SecureRandom() {
private static final long serialVersionUID = 3075400891983079965L;
public void nextBytes(final byte[] bytes) { | for (int i = initializationVectorBytes; --i >= 0; bytes[i] = 1); |
l0s/fernet-java8 | fernet-java8/src/test/java/com/macasaet/fernet/example/rotation/KeyRotationExampleIT.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/TokenValidationException.java
// public class TokenValidationException extends RuntimeException {
//
// private static final long serialVersionUID = 5175834607547919885L;
//
// public TokenValidationException(final String message) {
// super(message);
// }
//
// public TokenValidationException(final Throwable cause) {
// this(cause.getMessage(), cause);
// }
//
// public TokenValidationException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
| import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.embedded.RedisServer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.mockito.MockitoAnnotations.openMocks;
import java.io.IOException;
import java.security.SecureRandom;
import javax.servlet.http.HttpServletResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import com.macasaet.fernet.TokenValidationException; |
@After
public void tearDown() throws Exception {
try {
try {
clearData();
} finally {
redisServer.stop();
}
} finally {
mockContext.close();
}
}
protected void clearData() {
try (final Jedis jedis = pool.getResource()) {
jedis.del("fernet_keys");
}
}
@Test
public final void demonstrateKeyRotation() {
final String initialToken = resource.issueToken("username", "password");
manager.rotate();
String result = resource.getSecret(initialToken);
assertEquals("secret", result);
manager.rotate(); | // Path: fernet-java8/src/main/java/com/macasaet/fernet/TokenValidationException.java
// public class TokenValidationException extends RuntimeException {
//
// private static final long serialVersionUID = 5175834607547919885L;
//
// public TokenValidationException(final String message) {
// super(message);
// }
//
// public TokenValidationException(final Throwable cause) {
// this(cause.getMessage(), cause);
// }
//
// public TokenValidationException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
// Path: fernet-java8/src/test/java/com/macasaet/fernet/example/rotation/KeyRotationExampleIT.java
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.embedded.RedisServer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.mockito.MockitoAnnotations.openMocks;
import java.io.IOException;
import java.security.SecureRandom;
import javax.servlet.http.HttpServletResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import com.macasaet.fernet.TokenValidationException;
@After
public void tearDown() throws Exception {
try {
try {
clearData();
} finally {
redisServer.stop();
}
} finally {
mockContext.close();
}
}
protected void clearData() {
try (final Jedis jedis = pool.getResource()) {
jedis.del("fernet_keys");
}
}
@Test
public final void demonstrateKeyRotation() {
final String initialToken = resource.issueToken("username", "password");
manager.rotate();
String result = resource.getSecret(initialToken);
assertEquals("secret", result);
manager.rotate(); | assertThrows(TokenValidationException.class, () -> resource.getSecret(initialToken)); |
l0s/fernet-java8 | fernet-jersey-auth/src/main/java/com/macasaet/fernet/jaxrs/exception/TokenValidationExceptionMapper.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/PayloadValidationException.java
// public class PayloadValidationException extends TokenValidationException {
//
// private static final long serialVersionUID = -2067765218609208844L;
//
// public PayloadValidationException(final String message) {
// super(message);
// }
//
// public PayloadValidationException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// public PayloadValidationException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/TokenValidationException.java
// public class TokenValidationException extends RuntimeException {
//
// private static final long serialVersionUID = 5175834607547919885L;
//
// public TokenValidationException(final String message) {
// super(message);
// }
//
// public TokenValidationException(final Throwable cause) {
// this(cause.getMessage(), cause);
// }
//
// public TokenValidationException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
| import static javax.ws.rs.core.MediaType.TEXT_PLAIN_TYPE;
import static javax.ws.rs.core.Response.status;
import static javax.ws.rs.core.Response.Status.FORBIDDEN;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import com.macasaet.fernet.PayloadValidationException;
import com.macasaet.fernet.TokenValidationException; | /**
Copyright 2018 Carlos Macasaet
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
https://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.macasaet.fernet.jaxrs.exception;
/**
* An {@link ExceptionMapper} that translates Fernet token validation exceptions into HTTP semantics.
*
* <p>Copyright © 2018 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
*/
@Provider
@SuppressWarnings("PMD.LawOfDemeter") | // Path: fernet-java8/src/main/java/com/macasaet/fernet/PayloadValidationException.java
// public class PayloadValidationException extends TokenValidationException {
//
// private static final long serialVersionUID = -2067765218609208844L;
//
// public PayloadValidationException(final String message) {
// super(message);
// }
//
// public PayloadValidationException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// public PayloadValidationException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/TokenValidationException.java
// public class TokenValidationException extends RuntimeException {
//
// private static final long serialVersionUID = 5175834607547919885L;
//
// public TokenValidationException(final String message) {
// super(message);
// }
//
// public TokenValidationException(final Throwable cause) {
// this(cause.getMessage(), cause);
// }
//
// public TokenValidationException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
// Path: fernet-jersey-auth/src/main/java/com/macasaet/fernet/jaxrs/exception/TokenValidationExceptionMapper.java
import static javax.ws.rs.core.MediaType.TEXT_PLAIN_TYPE;
import static javax.ws.rs.core.Response.status;
import static javax.ws.rs.core.Response.Status.FORBIDDEN;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import com.macasaet.fernet.PayloadValidationException;
import com.macasaet.fernet.TokenValidationException;
/**
Copyright 2018 Carlos Macasaet
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
https://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.macasaet.fernet.jaxrs.exception;
/**
* An {@link ExceptionMapper} that translates Fernet token validation exceptions into HTTP semantics.
*
* <p>Copyright © 2018 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
*/
@Provider
@SuppressWarnings("PMD.LawOfDemeter") | public class TokenValidationExceptionMapper implements ExceptionMapper<TokenValidationException> { |
l0s/fernet-java8 | fernet-jersey-auth/src/main/java/com/macasaet/fernet/jaxrs/exception/TokenValidationExceptionMapper.java | // Path: fernet-java8/src/main/java/com/macasaet/fernet/PayloadValidationException.java
// public class PayloadValidationException extends TokenValidationException {
//
// private static final long serialVersionUID = -2067765218609208844L;
//
// public PayloadValidationException(final String message) {
// super(message);
// }
//
// public PayloadValidationException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// public PayloadValidationException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/TokenValidationException.java
// public class TokenValidationException extends RuntimeException {
//
// private static final long serialVersionUID = 5175834607547919885L;
//
// public TokenValidationException(final String message) {
// super(message);
// }
//
// public TokenValidationException(final Throwable cause) {
// this(cause.getMessage(), cause);
// }
//
// public TokenValidationException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
| import static javax.ws.rs.core.MediaType.TEXT_PLAIN_TYPE;
import static javax.ws.rs.core.Response.status;
import static javax.ws.rs.core.Response.Status.FORBIDDEN;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import com.macasaet.fernet.PayloadValidationException;
import com.macasaet.fernet.TokenValidationException; | /**
Copyright 2018 Carlos Macasaet
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
https://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.macasaet.fernet.jaxrs.exception;
/**
* An {@link ExceptionMapper} that translates Fernet token validation exceptions into HTTP semantics.
*
* <p>Copyright © 2018 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
*/
@Provider
@SuppressWarnings("PMD.LawOfDemeter")
public class TokenValidationExceptionMapper implements ExceptionMapper<TokenValidationException> {
public Response toResponse(final TokenValidationException exception) { | // Path: fernet-java8/src/main/java/com/macasaet/fernet/PayloadValidationException.java
// public class PayloadValidationException extends TokenValidationException {
//
// private static final long serialVersionUID = -2067765218609208844L;
//
// public PayloadValidationException(final String message) {
// super(message);
// }
//
// public PayloadValidationException(final Throwable cause) {
// super(cause.getMessage(), cause);
// }
//
// public PayloadValidationException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
//
// Path: fernet-java8/src/main/java/com/macasaet/fernet/TokenValidationException.java
// public class TokenValidationException extends RuntimeException {
//
// private static final long serialVersionUID = 5175834607547919885L;
//
// public TokenValidationException(final String message) {
// super(message);
// }
//
// public TokenValidationException(final Throwable cause) {
// this(cause.getMessage(), cause);
// }
//
// public TokenValidationException(final String message, final Throwable cause) {
// super(message, cause);
// }
//
// }
// Path: fernet-jersey-auth/src/main/java/com/macasaet/fernet/jaxrs/exception/TokenValidationExceptionMapper.java
import static javax.ws.rs.core.MediaType.TEXT_PLAIN_TYPE;
import static javax.ws.rs.core.Response.status;
import static javax.ws.rs.core.Response.Status.FORBIDDEN;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import com.macasaet.fernet.PayloadValidationException;
import com.macasaet.fernet.TokenValidationException;
/**
Copyright 2018 Carlos Macasaet
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
https://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.macasaet.fernet.jaxrs.exception;
/**
* An {@link ExceptionMapper} that translates Fernet token validation exceptions into HTTP semantics.
*
* <p>Copyright © 2018 Carlos Macasaet.</p>
*
* @author Carlos Macasaet
*/
@Provider
@SuppressWarnings("PMD.LawOfDemeter")
public class TokenValidationExceptionMapper implements ExceptionMapper<TokenValidationException> {
public Response toResponse(final TokenValidationException exception) { | if (exception instanceof PayloadValidationException) { |
wordpress-mobile/WordCamp-Android | app/src/main/java/org/wordcamp/android/notifs/FavoriteSession.java | // Path: app/src/main/java/org/wordcamp/android/objects/SessionDB.java
// public class SessionDB implements Serializable {
//
// private int wc_id;
// private int post_id;
// private String title;
// private int time;
// private String last_scanned_gmt;
// private String location;
// public String category;
// private String gson_object;
// public boolean isMySession;
//
// public SessionDB(int wc_id, int post_id, String title, int time, String last_scanned_gmt,
// String location, String category, String gson_object, boolean isMySession) {
// this.wc_id = wc_id;
// this.post_id = post_id;
// this.title = title;
// this.time = time;
// this.last_scanned_gmt = last_scanned_gmt;
// this.location = location;
// this.category = category;
// this.gson_object = gson_object;
// this.isMySession = isMySession;
// }
//
// public int getWc_id() {
// return wc_id;
// }
//
// public void setWc_id(int wc_id) {
// this.wc_id = wc_id;
// }
//
// public int getPost_id() {
// return post_id;
// }
//
// public void setPost_id(int post_id) {
// this.post_id = post_id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public int getTime() {
// return time;
// }
//
// public void setTime(int time) {
// this.time = time;
// }
//
// public String getLast_scanned_gmt() {
// return last_scanned_gmt;
// }
//
// public void setLast_scanned_gmt(String last_scanned_gmt) {
// this.last_scanned_gmt = last_scanned_gmt;
// }
//
// public String getLocation() {
// return location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getCategory() {
// return category;
// }
//
// public void setCategory(String category) {
// this.category = category;
// }
//
// public String getGson_object() {
// return gson_object;
// }
//
// public void setGson_object(String gson_object) {
// this.gson_object = gson_object;
// }
// }
| import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import org.wordcamp.android.objects.SessionDB;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone; | package org.wordcamp.android.notifs;
/**
* Created by aagam on 10/3/15.
*/
public class FavoriteSession {
private Context context;
public FavoriteSession(Context context) {
this.context = context;
}
| // Path: app/src/main/java/org/wordcamp/android/objects/SessionDB.java
// public class SessionDB implements Serializable {
//
// private int wc_id;
// private int post_id;
// private String title;
// private int time;
// private String last_scanned_gmt;
// private String location;
// public String category;
// private String gson_object;
// public boolean isMySession;
//
// public SessionDB(int wc_id, int post_id, String title, int time, String last_scanned_gmt,
// String location, String category, String gson_object, boolean isMySession) {
// this.wc_id = wc_id;
// this.post_id = post_id;
// this.title = title;
// this.time = time;
// this.last_scanned_gmt = last_scanned_gmt;
// this.location = location;
// this.category = category;
// this.gson_object = gson_object;
// this.isMySession = isMySession;
// }
//
// public int getWc_id() {
// return wc_id;
// }
//
// public void setWc_id(int wc_id) {
// this.wc_id = wc_id;
// }
//
// public int getPost_id() {
// return post_id;
// }
//
// public void setPost_id(int post_id) {
// this.post_id = post_id;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public int getTime() {
// return time;
// }
//
// public void setTime(int time) {
// this.time = time;
// }
//
// public String getLast_scanned_gmt() {
// return last_scanned_gmt;
// }
//
// public void setLast_scanned_gmt(String last_scanned_gmt) {
// this.last_scanned_gmt = last_scanned_gmt;
// }
//
// public String getLocation() {
// return location;
// }
//
// public void setLocation(String location) {
// this.location = location;
// }
//
// public String getCategory() {
// return category;
// }
//
// public void setCategory(String category) {
// this.category = category;
// }
//
// public String getGson_object() {
// return gson_object;
// }
//
// public void setGson_object(String gson_object) {
// this.gson_object = gson_object;
// }
// }
// Path: app/src/main/java/org/wordcamp/android/notifs/FavoriteSession.java
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import org.wordcamp.android.objects.SessionDB;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
package org.wordcamp.android.notifs;
/**
* Created by aagam on 10/3/15.
*/
public class FavoriteSession {
private Context context;
public FavoriteSession(Context context) {
this.context = context;
}
| public void favoriteSession(SessionDB session) { |
wordpress-mobile/WordCamp-Android | app/src/main/java/org/wordcamp/android/wcdetails/SpeakerFragment.java | // Path: app/src/main/java/org/wordcamp/android/adapters/SpeakersListAdapter.java
// public class SpeakersListAdapter extends RecyclerView.Adapter<SpeakersListAdapter.ViewHolder> {
//
// private Context context;
// private LayoutInflater inflater;
// private List<SpeakerDB> speakerDBList;
// private OnSpeakerSelectedListener speakerSelectedListener;
//
// public SpeakersListAdapter(Context ctx, List<SpeakerDB> speakerDBList) {
// this.context = ctx;
// inflater = LayoutInflater.from(this.context);
// this.speakerDBList = speakerDBList;
// }
//
// public void setOnSpeakerSelectedListener(OnSpeakerSelectedListener listener) {
// speakerSelectedListener = listener;
// }
//
// public interface OnSpeakerSelectedListener {
// void onSpeakerSelected(SpeakerDB speakerDB);
// }
//
// @Override
// public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// View v = inflater.inflate(R.layout.item_speaker, parent, false);
// ViewHolder holder = new ViewHolder(v);
// return holder;
// }
//
// @Override
// public void onBindViewHolder(ViewHolder holder, int position) {
// final SpeakerDB speakerDB = speakerDBList.get(position);
// holder.title.setText(speakerDB.getName());
// Picasso.with(context).load(speakerDB.getGravatar())
// .placeholder(R.drawable.ic_account_circle_grey600).into(holder.dp);
//
// holder.itemView.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// speakerSelectedListener.onSpeakerSelected(speakerDB);
// }
// });
// }
//
// @Override
// public long getItemId(int position) {
// return position;
// }
//
// @Override
// public int getItemCount() {
// return speakerDBList.size();
// }
//
// static class ViewHolder extends RecyclerView.ViewHolder {
// TextView title;
// CircleImageView dp;
//
// public ViewHolder(View itemView) {
// super(itemView);
// title = (TextView) itemView.findViewById(R.id.speaker_name);
// dp = (CircleImageView) itemView.findViewById(R.id.speaker_avatar);
// }
// }
// }
//
// Path: app/src/main/java/org/wordcamp/android/objects/SpeakerDB.java
// public class SpeakerDB implements Serializable {
//
// private int wc_id;
// private String name;
// private int speaker_id;
// private String info;
// private String featured_image;
// private String last_scanned_gmt;
// private String gson_object;
// private String gravatar;
//
// public SpeakerDB(int wc_id, String name, int speaker_id,
// String info, String featured_image,
// String last_scanned_gmt, String gson_object, String gravatar) {
// this.wc_id = wc_id;
// this.name = name;
// this.speaker_id = speaker_id;
// this.info = info;
// this.featured_image = featured_image;
// this.last_scanned_gmt = last_scanned_gmt;
// this.gson_object = gson_object;
// this.gravatar = gravatar;
// }
//
// public String getGravatar() {
// return gravatar;
// }
//
// public void setGravatar(String gravatar) {
// this.gravatar = gravatar;
// }
//
// public int getWc_id() {
// return wc_id;
// }
//
// public void setWc_id(int wc_id) {
// this.wc_id = wc_id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getSpeaker_id() {
// return speaker_id;
// }
//
// public void setSpeaker_id(int speaker_id) {
// this.speaker_id = speaker_id;
// }
//
// public String getInfo() {
// return info;
// }
//
// public void setInfo(String info) {
// this.info = info;
// }
//
// public String getFeatured_image() {
// return featured_image;
// }
//
// public void setFeatured_image(String featured_image) {
// this.featured_image = featured_image;
// }
//
// public String getLast_scanned_gmt() {
// return last_scanned_gmt;
// }
//
// public void setLast_scanned_gmt(String last_scanned_gmt) {
// this.last_scanned_gmt = last_scanned_gmt;
// }
//
// public String getGson_object() {
// return gson_object;
// }
//
// public void setGson_object(String gson_object) {
// this.gson_object = gson_object;
// }
// }
| import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import org.wordcamp.android.R;
import org.wordcamp.android.WordCampDetailActivity;
import org.wordcamp.android.adapters.SpeakersListAdapter;
import org.wordcamp.android.objects.SpeakerDB;
import java.util.Collections;
import java.util.Comparator;
import java.util.List; | package org.wordcamp.android.wcdetails;
/**
* Created by aagam on 29/1/15.
*/
public class SpeakerFragment extends Fragment implements SpeakersListAdapter.OnSpeakerSelectedListener {
private RecyclerView lv;
private View emptyView;
private SpeakersListAdapter adapter; | // Path: app/src/main/java/org/wordcamp/android/adapters/SpeakersListAdapter.java
// public class SpeakersListAdapter extends RecyclerView.Adapter<SpeakersListAdapter.ViewHolder> {
//
// private Context context;
// private LayoutInflater inflater;
// private List<SpeakerDB> speakerDBList;
// private OnSpeakerSelectedListener speakerSelectedListener;
//
// public SpeakersListAdapter(Context ctx, List<SpeakerDB> speakerDBList) {
// this.context = ctx;
// inflater = LayoutInflater.from(this.context);
// this.speakerDBList = speakerDBList;
// }
//
// public void setOnSpeakerSelectedListener(OnSpeakerSelectedListener listener) {
// speakerSelectedListener = listener;
// }
//
// public interface OnSpeakerSelectedListener {
// void onSpeakerSelected(SpeakerDB speakerDB);
// }
//
// @Override
// public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// View v = inflater.inflate(R.layout.item_speaker, parent, false);
// ViewHolder holder = new ViewHolder(v);
// return holder;
// }
//
// @Override
// public void onBindViewHolder(ViewHolder holder, int position) {
// final SpeakerDB speakerDB = speakerDBList.get(position);
// holder.title.setText(speakerDB.getName());
// Picasso.with(context).load(speakerDB.getGravatar())
// .placeholder(R.drawable.ic_account_circle_grey600).into(holder.dp);
//
// holder.itemView.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// speakerSelectedListener.onSpeakerSelected(speakerDB);
// }
// });
// }
//
// @Override
// public long getItemId(int position) {
// return position;
// }
//
// @Override
// public int getItemCount() {
// return speakerDBList.size();
// }
//
// static class ViewHolder extends RecyclerView.ViewHolder {
// TextView title;
// CircleImageView dp;
//
// public ViewHolder(View itemView) {
// super(itemView);
// title = (TextView) itemView.findViewById(R.id.speaker_name);
// dp = (CircleImageView) itemView.findViewById(R.id.speaker_avatar);
// }
// }
// }
//
// Path: app/src/main/java/org/wordcamp/android/objects/SpeakerDB.java
// public class SpeakerDB implements Serializable {
//
// private int wc_id;
// private String name;
// private int speaker_id;
// private String info;
// private String featured_image;
// private String last_scanned_gmt;
// private String gson_object;
// private String gravatar;
//
// public SpeakerDB(int wc_id, String name, int speaker_id,
// String info, String featured_image,
// String last_scanned_gmt, String gson_object, String gravatar) {
// this.wc_id = wc_id;
// this.name = name;
// this.speaker_id = speaker_id;
// this.info = info;
// this.featured_image = featured_image;
// this.last_scanned_gmt = last_scanned_gmt;
// this.gson_object = gson_object;
// this.gravatar = gravatar;
// }
//
// public String getGravatar() {
// return gravatar;
// }
//
// public void setGravatar(String gravatar) {
// this.gravatar = gravatar;
// }
//
// public int getWc_id() {
// return wc_id;
// }
//
// public void setWc_id(int wc_id) {
// this.wc_id = wc_id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getSpeaker_id() {
// return speaker_id;
// }
//
// public void setSpeaker_id(int speaker_id) {
// this.speaker_id = speaker_id;
// }
//
// public String getInfo() {
// return info;
// }
//
// public void setInfo(String info) {
// this.info = info;
// }
//
// public String getFeatured_image() {
// return featured_image;
// }
//
// public void setFeatured_image(String featured_image) {
// this.featured_image = featured_image;
// }
//
// public String getLast_scanned_gmt() {
// return last_scanned_gmt;
// }
//
// public void setLast_scanned_gmt(String last_scanned_gmt) {
// this.last_scanned_gmt = last_scanned_gmt;
// }
//
// public String getGson_object() {
// return gson_object;
// }
//
// public void setGson_object(String gson_object) {
// this.gson_object = gson_object;
// }
// }
// Path: app/src/main/java/org/wordcamp/android/wcdetails/SpeakerFragment.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import org.wordcamp.android.R;
import org.wordcamp.android.WordCampDetailActivity;
import org.wordcamp.android.adapters.SpeakersListAdapter;
import org.wordcamp.android.objects.SpeakerDB;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
package org.wordcamp.android.wcdetails;
/**
* Created by aagam on 29/1/15.
*/
public class SpeakerFragment extends Fragment implements SpeakersListAdapter.OnSpeakerSelectedListener {
private RecyclerView lv;
private View emptyView;
private SpeakersListAdapter adapter; | private List<SpeakerDB> speakerDBList; |
wordpress-mobile/WordCamp-Android | app/src/main/java/org/wordcamp/android/networking/WCRequest.java | // Path: app/src/main/java/org/wordcamp/android/objects/speaker/Terms.java
// public class Terms {
//
// @SerializedName("wcb_track")
// @Expose
// private List<WcbTrack> wcbTrack = new ArrayList<WcbTrack>();
//
// /**
// *
// * @return
// * The wcbTrack
// */
// public List<WcbTrack> getWcbTrack() {
// return wcbTrack;
// }
//
// /**
// *
// * @param wcbTrack
// * The wcb_track
// */
// public void setWcbTrack(List<WcbTrack> wcbTrack) {
// this.wcbTrack = wcbTrack;
// }
//
// }
//
// Path: app/src/main/java/org/wordcamp/android/utils/CustomGsonDeSerializer.java
// public class CustomGsonDeSerializer implements JsonDeserializer<Terms> {
//
// @Override
// public Terms deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
// //Terms object when null returns an empty array rather then empty list
// if (json instanceof JsonArray) {
// return null;
// } else {
// Gson gson = new Gson();
// return gson.fromJson(json,Terms.class);
// }
// }
// }
| import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.http.HttpStatus;
import org.wordcamp.android.objects.speaker.Terms;
import org.wordcamp.android.utils.CustomGsonDeSerializer;
import java.io.UnsupportedEncodingException; | package org.wordcamp.android.networking;
/**
* Created by shah.aagam on 30/07/15.
*/
public class WCRequest<T> extends Request<T> {
private final Gson gson;
private ResponseListener<T> responseListener;
private Class<T> requestType;
public WCRequest(String url, Class<T> typeResponse, Response.ErrorListener listener, ResponseListener<T> responseListener) {
super(Method.GET, url, listener);
this.responseListener = responseListener;
| // Path: app/src/main/java/org/wordcamp/android/objects/speaker/Terms.java
// public class Terms {
//
// @SerializedName("wcb_track")
// @Expose
// private List<WcbTrack> wcbTrack = new ArrayList<WcbTrack>();
//
// /**
// *
// * @return
// * The wcbTrack
// */
// public List<WcbTrack> getWcbTrack() {
// return wcbTrack;
// }
//
// /**
// *
// * @param wcbTrack
// * The wcb_track
// */
// public void setWcbTrack(List<WcbTrack> wcbTrack) {
// this.wcbTrack = wcbTrack;
// }
//
// }
//
// Path: app/src/main/java/org/wordcamp/android/utils/CustomGsonDeSerializer.java
// public class CustomGsonDeSerializer implements JsonDeserializer<Terms> {
//
// @Override
// public Terms deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
// //Terms object when null returns an empty array rather then empty list
// if (json instanceof JsonArray) {
// return null;
// } else {
// Gson gson = new Gson();
// return gson.fromJson(json,Terms.class);
// }
// }
// }
// Path: app/src/main/java/org/wordcamp/android/networking/WCRequest.java
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.http.HttpStatus;
import org.wordcamp.android.objects.speaker.Terms;
import org.wordcamp.android.utils.CustomGsonDeSerializer;
import java.io.UnsupportedEncodingException;
package org.wordcamp.android.networking;
/**
* Created by shah.aagam on 30/07/15.
*/
public class WCRequest<T> extends Request<T> {
private final Gson gson;
private ResponseListener<T> responseListener;
private Class<T> requestType;
public WCRequest(String url, Class<T> typeResponse, Response.ErrorListener listener, ResponseListener<T> responseListener) {
super(Method.GET, url, listener);
this.responseListener = responseListener;
| gson = new GsonBuilder().registerTypeHierarchyAdapter(Terms.class, |
wordpress-mobile/WordCamp-Android | app/src/main/java/org/wordcamp/android/networking/WCRequest.java | // Path: app/src/main/java/org/wordcamp/android/objects/speaker/Terms.java
// public class Terms {
//
// @SerializedName("wcb_track")
// @Expose
// private List<WcbTrack> wcbTrack = new ArrayList<WcbTrack>();
//
// /**
// *
// * @return
// * The wcbTrack
// */
// public List<WcbTrack> getWcbTrack() {
// return wcbTrack;
// }
//
// /**
// *
// * @param wcbTrack
// * The wcb_track
// */
// public void setWcbTrack(List<WcbTrack> wcbTrack) {
// this.wcbTrack = wcbTrack;
// }
//
// }
//
// Path: app/src/main/java/org/wordcamp/android/utils/CustomGsonDeSerializer.java
// public class CustomGsonDeSerializer implements JsonDeserializer<Terms> {
//
// @Override
// public Terms deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
// //Terms object when null returns an empty array rather then empty list
// if (json instanceof JsonArray) {
// return null;
// } else {
// Gson gson = new Gson();
// return gson.fromJson(json,Terms.class);
// }
// }
// }
| import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.http.HttpStatus;
import org.wordcamp.android.objects.speaker.Terms;
import org.wordcamp.android.utils.CustomGsonDeSerializer;
import java.io.UnsupportedEncodingException; | package org.wordcamp.android.networking;
/**
* Created by shah.aagam on 30/07/15.
*/
public class WCRequest<T> extends Request<T> {
private final Gson gson;
private ResponseListener<T> responseListener;
private Class<T> requestType;
public WCRequest(String url, Class<T> typeResponse, Response.ErrorListener listener, ResponseListener<T> responseListener) {
super(Method.GET, url, listener);
this.responseListener = responseListener;
gson = new GsonBuilder().registerTypeHierarchyAdapter(Terms.class, | // Path: app/src/main/java/org/wordcamp/android/objects/speaker/Terms.java
// public class Terms {
//
// @SerializedName("wcb_track")
// @Expose
// private List<WcbTrack> wcbTrack = new ArrayList<WcbTrack>();
//
// /**
// *
// * @return
// * The wcbTrack
// */
// public List<WcbTrack> getWcbTrack() {
// return wcbTrack;
// }
//
// /**
// *
// * @param wcbTrack
// * The wcb_track
// */
// public void setWcbTrack(List<WcbTrack> wcbTrack) {
// this.wcbTrack = wcbTrack;
// }
//
// }
//
// Path: app/src/main/java/org/wordcamp/android/utils/CustomGsonDeSerializer.java
// public class CustomGsonDeSerializer implements JsonDeserializer<Terms> {
//
// @Override
// public Terms deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
// //Terms object when null returns an empty array rather then empty list
// if (json instanceof JsonArray) {
// return null;
// } else {
// Gson gson = new Gson();
// return gson.fromJson(json,Terms.class);
// }
// }
// }
// Path: app/src/main/java/org/wordcamp/android/networking/WCRequest.java
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.http.HttpStatus;
import org.wordcamp.android.objects.speaker.Terms;
import org.wordcamp.android.utils.CustomGsonDeSerializer;
import java.io.UnsupportedEncodingException;
package org.wordcamp.android.networking;
/**
* Created by shah.aagam on 30/07/15.
*/
public class WCRequest<T> extends Request<T> {
private final Gson gson;
private ResponseListener<T> responseListener;
private Class<T> requestType;
public WCRequest(String url, Class<T> typeResponse, Response.ErrorListener listener, ResponseListener<T> responseListener) {
super(Method.GET, url, listener);
this.responseListener = responseListener;
gson = new GsonBuilder().registerTypeHierarchyAdapter(Terms.class, | new CustomGsonDeSerializer()).create(); |
wordpress-mobile/WordCamp-Android | app/src/main/java/org/wordcamp/android/adapters/SessionDetailAdapter.java | // Path: app/src/main/java/org/wordcamp/android/objects/MiniSpeaker.java
// public class MiniSpeaker {
// public String name;
// public String dp;
// public int id;
//
// public MiniSpeaker(String name, String dp, int id) {
// this.name = name;
// this.dp = dp;
// this.id = id;
// }
// }
| import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import org.wordcamp.android.R;
import org.wordcamp.android.objects.MiniSpeaker;
import java.util.List; | package org.wordcamp.android.adapters;
/**
* Created by aagam on 12/2/15.
*/
public class SessionDetailAdapter extends BaseAdapter {
private Context mContext; | // Path: app/src/main/java/org/wordcamp/android/objects/MiniSpeaker.java
// public class MiniSpeaker {
// public String name;
// public String dp;
// public int id;
//
// public MiniSpeaker(String name, String dp, int id) {
// this.name = name;
// this.dp = dp;
// this.id = id;
// }
// }
// Path: app/src/main/java/org/wordcamp/android/adapters/SessionDetailAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import org.wordcamp.android.R;
import org.wordcamp.android.objects.MiniSpeaker;
import java.util.List;
package org.wordcamp.android.adapters;
/**
* Created by aagam on 12/2/15.
*/
public class SessionDetailAdapter extends BaseAdapter {
private Context mContext; | private List<MiniSpeaker> speakers; |
wordpress-mobile/WordCamp-Android | app/src/main/java/org/wordcamp/android/FeedbackActivity.java | // Path: app/src/main/java/org/wordcamp/android/utils/Utils.java
// public class Utils {
//
// public static boolean isLollipopOrAbove() {
// return Build.VERSION.SDK_INT >= 21;
// }
//
// public static String getDeviceInfo() {
// return "\n\n Device info :- \n"
// + "API : " + Build.VERSION.SDK_INT + "\n " // API Level
// + "Device : " + Build.DEVICE + "\n" // Device
// + "Manufacturer : " + Build.MANUFACTURER + "\n" // Manufacturer
// + "Model : " + Build.MODEL + "\n" // Model
// + "Product : " + Build.PRODUCT;
// }
// }
| import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import org.wordcamp.android.utils.Utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader; |
@Override
protected String doInBackground(String... params) {
if (bugSwitch.isChecked()) {
try {
Process process = Runtime.getRuntime().exec("logcat -d");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuilder log = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
log.append(line);
log.append("\n");
}
return log.toString();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String appLogs) {
super.onPostExecute(appLogs);
dialog.dismiss();
StringBuilder emailMessage = new StringBuilder(descr.getText().toString());
emailMessage.append("\n\n\n=================================\n"); | // Path: app/src/main/java/org/wordcamp/android/utils/Utils.java
// public class Utils {
//
// public static boolean isLollipopOrAbove() {
// return Build.VERSION.SDK_INT >= 21;
// }
//
// public static String getDeviceInfo() {
// return "\n\n Device info :- \n"
// + "API : " + Build.VERSION.SDK_INT + "\n " // API Level
// + "Device : " + Build.DEVICE + "\n" // Device
// + "Manufacturer : " + Build.MANUFACTURER + "\n" // Manufacturer
// + "Model : " + Build.MODEL + "\n" // Model
// + "Product : " + Build.PRODUCT;
// }
// }
// Path: app/src/main/java/org/wordcamp/android/FeedbackActivity.java
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import org.wordcamp.android.utils.Utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
@Override
protected String doInBackground(String... params) {
if (bugSwitch.isChecked()) {
try {
Process process = Runtime.getRuntime().exec("logcat -d");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuilder log = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
log.append(line);
log.append("\n");
}
return log.toString();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String appLogs) {
super.onPostExecute(appLogs);
dialog.dismiss();
StringBuilder emailMessage = new StringBuilder(descr.getText().toString());
emailMessage.append("\n\n\n=================================\n"); | emailMessage.append(Utils.getDeviceInfo()); |
wordpress-mobile/WordCamp-Android | app/src/main/java/org/wordcamp/android/WordCampApplication.java | // Path: app/src/main/java/org/wordcamp/android/networking/WCHurlStack.java
// public class WCHurlStack implements HttpStack {
//
//
// @Override
// public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError {
//
// String url = request.getUrl();
// HashMap<String, String> map = new HashMap<>();
// map.putAll(request.getHeaders());
// map.putAll(additionalHeaders);
//
//
// if(!url.startsWith("https")){
// url = url.replace("http","https");
// }
// URL parsedUrl = new URL(url);
// HttpURLConnection http = null;
//
// if (parsedUrl.getProtocol().toLowerCase().equals("https")) {
// HttpsURLConnection https = (HttpsURLConnection) parsedUrl.openConnection();
// http = https;
// } else {
// http = (HttpURLConnection) parsedUrl.openConnection();
// }
//
//
// StatusLine responseStatus = new BasicStatusLine(new ProtocolVersion("HTTP",1,1),
// http.getResponseCode(), http.getResponseMessage());
//
// BasicHttpResponse response = new BasicHttpResponse(responseStatus);
// response.setEntity(entityFromConnection(http));
// return response;
// }
//
// private static HttpEntity entityFromConnection(HttpURLConnection connection) {
// BasicHttpEntity entity = new BasicHttpEntity();
// InputStream inputStream;
// try {
// inputStream = connection.getInputStream();
// } catch (IOException ioe) {
// inputStream = connection.getErrorStream();
// }
// entity.setContent(inputStream);
// entity.setContentLength(connection.getContentLength());
// entity.setContentEncoding(connection.getContentEncoding());
// entity.setContentType(connection.getContentType());
// return entity;
// }
// }
| import org.wordcamp.android.networking.WCHurlStack;
import android.app.Application;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley; | package org.wordcamp.android;
public class WordCampApplication extends Application {
public static RequestQueue requestQueue;
@Override
public void onCreate() {
super.onCreate(); | // Path: app/src/main/java/org/wordcamp/android/networking/WCHurlStack.java
// public class WCHurlStack implements HttpStack {
//
//
// @Override
// public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError {
//
// String url = request.getUrl();
// HashMap<String, String> map = new HashMap<>();
// map.putAll(request.getHeaders());
// map.putAll(additionalHeaders);
//
//
// if(!url.startsWith("https")){
// url = url.replace("http","https");
// }
// URL parsedUrl = new URL(url);
// HttpURLConnection http = null;
//
// if (parsedUrl.getProtocol().toLowerCase().equals("https")) {
// HttpsURLConnection https = (HttpsURLConnection) parsedUrl.openConnection();
// http = https;
// } else {
// http = (HttpURLConnection) parsedUrl.openConnection();
// }
//
//
// StatusLine responseStatus = new BasicStatusLine(new ProtocolVersion("HTTP",1,1),
// http.getResponseCode(), http.getResponseMessage());
//
// BasicHttpResponse response = new BasicHttpResponse(responseStatus);
// response.setEntity(entityFromConnection(http));
// return response;
// }
//
// private static HttpEntity entityFromConnection(HttpURLConnection connection) {
// BasicHttpEntity entity = new BasicHttpEntity();
// InputStream inputStream;
// try {
// inputStream = connection.getInputStream();
// } catch (IOException ioe) {
// inputStream = connection.getErrorStream();
// }
// entity.setContent(inputStream);
// entity.setContentLength(connection.getContentLength());
// entity.setContentEncoding(connection.getContentEncoding());
// entity.setContentType(connection.getContentType());
// return entity;
// }
// }
// Path: app/src/main/java/org/wordcamp/android/WordCampApplication.java
import org.wordcamp.android.networking.WCHurlStack;
import android.app.Application;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
package org.wordcamp.android;
public class WordCampApplication extends Application {
public static RequestQueue requestQueue;
@Override
public void onCreate() {
super.onCreate(); | requestQueue = Volley.newRequestQueue(this,new WCHurlStack()); |
wordpress-mobile/WordCamp-Android | app/src/main/java/org/wordcamp/android/adapters/SpeakersListAdapter.java | // Path: app/src/main/java/org/wordcamp/android/objects/SpeakerDB.java
// public class SpeakerDB implements Serializable {
//
// private int wc_id;
// private String name;
// private int speaker_id;
// private String info;
// private String featured_image;
// private String last_scanned_gmt;
// private String gson_object;
// private String gravatar;
//
// public SpeakerDB(int wc_id, String name, int speaker_id,
// String info, String featured_image,
// String last_scanned_gmt, String gson_object, String gravatar) {
// this.wc_id = wc_id;
// this.name = name;
// this.speaker_id = speaker_id;
// this.info = info;
// this.featured_image = featured_image;
// this.last_scanned_gmt = last_scanned_gmt;
// this.gson_object = gson_object;
// this.gravatar = gravatar;
// }
//
// public String getGravatar() {
// return gravatar;
// }
//
// public void setGravatar(String gravatar) {
// this.gravatar = gravatar;
// }
//
// public int getWc_id() {
// return wc_id;
// }
//
// public void setWc_id(int wc_id) {
// this.wc_id = wc_id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getSpeaker_id() {
// return speaker_id;
// }
//
// public void setSpeaker_id(int speaker_id) {
// this.speaker_id = speaker_id;
// }
//
// public String getInfo() {
// return info;
// }
//
// public void setInfo(String info) {
// this.info = info;
// }
//
// public String getFeatured_image() {
// return featured_image;
// }
//
// public void setFeatured_image(String featured_image) {
// this.featured_image = featured_image;
// }
//
// public String getLast_scanned_gmt() {
// return last_scanned_gmt;
// }
//
// public void setLast_scanned_gmt(String last_scanned_gmt) {
// this.last_scanned_gmt = last_scanned_gmt;
// }
//
// public String getGson_object() {
// return gson_object;
// }
//
// public void setGson_object(String gson_object) {
// this.gson_object = gson_object;
// }
// }
| import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import org.wordcamp.android.R;
import org.wordcamp.android.objects.SpeakerDB;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView; | package org.wordcamp.android.adapters;
/**
* Created by aagam on 30/1/15.
*/
public class SpeakersListAdapter extends RecyclerView.Adapter<SpeakersListAdapter.ViewHolder> {
private Context context;
private LayoutInflater inflater; | // Path: app/src/main/java/org/wordcamp/android/objects/SpeakerDB.java
// public class SpeakerDB implements Serializable {
//
// private int wc_id;
// private String name;
// private int speaker_id;
// private String info;
// private String featured_image;
// private String last_scanned_gmt;
// private String gson_object;
// private String gravatar;
//
// public SpeakerDB(int wc_id, String name, int speaker_id,
// String info, String featured_image,
// String last_scanned_gmt, String gson_object, String gravatar) {
// this.wc_id = wc_id;
// this.name = name;
// this.speaker_id = speaker_id;
// this.info = info;
// this.featured_image = featured_image;
// this.last_scanned_gmt = last_scanned_gmt;
// this.gson_object = gson_object;
// this.gravatar = gravatar;
// }
//
// public String getGravatar() {
// return gravatar;
// }
//
// public void setGravatar(String gravatar) {
// this.gravatar = gravatar;
// }
//
// public int getWc_id() {
// return wc_id;
// }
//
// public void setWc_id(int wc_id) {
// this.wc_id = wc_id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public int getSpeaker_id() {
// return speaker_id;
// }
//
// public void setSpeaker_id(int speaker_id) {
// this.speaker_id = speaker_id;
// }
//
// public String getInfo() {
// return info;
// }
//
// public void setInfo(String info) {
// this.info = info;
// }
//
// public String getFeatured_image() {
// return featured_image;
// }
//
// public void setFeatured_image(String featured_image) {
// this.featured_image = featured_image;
// }
//
// public String getLast_scanned_gmt() {
// return last_scanned_gmt;
// }
//
// public void setLast_scanned_gmt(String last_scanned_gmt) {
// this.last_scanned_gmt = last_scanned_gmt;
// }
//
// public String getGson_object() {
// return gson_object;
// }
//
// public void setGson_object(String gson_object) {
// this.gson_object = gson_object;
// }
// }
// Path: app/src/main/java/org/wordcamp/android/adapters/SpeakersListAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import org.wordcamp.android.R;
import org.wordcamp.android.objects.SpeakerDB;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
package org.wordcamp.android.adapters;
/**
* Created by aagam on 30/1/15.
*/
public class SpeakersListAdapter extends RecyclerView.Adapter<SpeakersListAdapter.ViewHolder> {
private Context context;
private LayoutInflater inflater; | private List<SpeakerDB> speakerDBList; |
alexholmes/hadoop-utils | src/main/java/com/alexholmes/hadooputils/test/TextIOJobBuilder.java | // Path: src/main/java/com/alexholmes/hadooputils/io/FileUtils.java
// public final class FileUtils {
//
// /**
// * Private ctor to prevent instantiation.
// */
// private FileUtils() {
// }
//
// /**
// * Read the contents of the supplied file into a list.
// *
// * @param fs a Hadoop file system
// * @param p the file path
// * @return array of lines in the file
// * @throws java.io.IOException if something goes wrong
// */
// public static List<String> readLines(final FileSystem fs, final Path p)
// throws IOException {
// InputStream stream = fs.open(p);
// try {
// return IOUtils.readLines(stream);
// } finally {
// stream.close();
// }
// }
//
// /**
// * Writes the array list into a file as newline-separated lines.
// *
// * @param fs a Hadoop file system
// * @param p the file path
// * @return array of lines to write to the file
// * @throws java.io.IOException if something goes wrong
// */
// public static void writeLines(Collection<?> lines, final FileSystem fs, final Path p)
// throws IOException {
// OutputStream stream = fs.create(p);
// try {
// IOUtils.writeLines(lines, IOUtils.LINE_SEPARATOR, stream);
// } finally {
// stream.close();
// }
// }
// }
| import static org.junit.Assert.assertEquals;
import com.alexholmes.hadooputils.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; |
IOUtils.writeLines(inputs, String.format("%n"), stream);
stream.close();
return this;
}
/**
* Called after the MapReduce job has completed, to verify that the outputs
* generated by the MapReduce job align with the expected outputs that were
* set with calls to {@link #addExpectedOutput(String)} and
* {@link #addExpectedOutput(String...)}.
*
* @return a reference to this object
* @throws IOException if something goes wrong
*/
public TextIOJobBuilder verifyResults() throws IOException {
FileStatus[] outputFiles = fs.listStatus(outputPath, new PathFilter() {
@Override
public boolean accept(final Path path) {
return path.getName().startsWith("part");
}
});
System.out.println("Output files: " + StringUtils.join(outputFiles));
int i = 0;
for (FileStatus file : outputFiles) { | // Path: src/main/java/com/alexholmes/hadooputils/io/FileUtils.java
// public final class FileUtils {
//
// /**
// * Private ctor to prevent instantiation.
// */
// private FileUtils() {
// }
//
// /**
// * Read the contents of the supplied file into a list.
// *
// * @param fs a Hadoop file system
// * @param p the file path
// * @return array of lines in the file
// * @throws java.io.IOException if something goes wrong
// */
// public static List<String> readLines(final FileSystem fs, final Path p)
// throws IOException {
// InputStream stream = fs.open(p);
// try {
// return IOUtils.readLines(stream);
// } finally {
// stream.close();
// }
// }
//
// /**
// * Writes the array list into a file as newline-separated lines.
// *
// * @param fs a Hadoop file system
// * @param p the file path
// * @return array of lines to write to the file
// * @throws java.io.IOException if something goes wrong
// */
// public static void writeLines(Collection<?> lines, final FileSystem fs, final Path p)
// throws IOException {
// OutputStream stream = fs.create(p);
// try {
// IOUtils.writeLines(lines, IOUtils.LINE_SEPARATOR, stream);
// } finally {
// stream.close();
// }
// }
// }
// Path: src/main/java/com/alexholmes/hadooputils/test/TextIOJobBuilder.java
import static org.junit.Assert.assertEquals;
import com.alexholmes.hadooputils.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
IOUtils.writeLines(inputs, String.format("%n"), stream);
stream.close();
return this;
}
/**
* Called after the MapReduce job has completed, to verify that the outputs
* generated by the MapReduce job align with the expected outputs that were
* set with calls to {@link #addExpectedOutput(String)} and
* {@link #addExpectedOutput(String...)}.
*
* @return a reference to this object
* @throws IOException if something goes wrong
*/
public TextIOJobBuilder verifyResults() throws IOException {
FileStatus[] outputFiles = fs.listStatus(outputPath, new PathFilter() {
@Override
public boolean accept(final Path path) {
return path.getName().startsWith("part");
}
});
System.out.println("Output files: " + StringUtils.join(outputFiles));
int i = 0;
for (FileStatus file : outputFiles) { | List<String> actualLines = FileUtils.readLines(fs, file.getPath()); |
alexholmes/hadoop-utils | src/main/java/com/alexholmes/hadooputils/combine/common/mapred/SplitMetricsCombineInputFormat.java | // Path: src/main/java/com/alexholmes/hadooputils/combine/common/CombineFileSplitAdapter.java
// public class CombineFileSplitAdapter {
// org.apache.hadoop.mapred.lib.CombineFileSplit mapredSplit;
// org.apache.hadoop.mapreduce.lib.input.CombineFileSplit mapreduceSplit;
//
// public CombineFileSplitAdapter(CombineFileSplit mapredSplit) {
// this.mapredSplit = mapredSplit;
// }
//
// public CombineFileSplitAdapter(org.apache.hadoop.mapreduce.lib.input.CombineFileSplit mapreduceSplit) {
// this.mapreduceSplit = mapreduceSplit;
// }
//
// public boolean isMapRedSet() {
// return mapredSplit != null;
// }
//
// public long getLength() {
// return isMapRedSet() ? mapredSplit.getLength() : mapreduceSplit.getLength();
// }
//
// /** Returns an array containing the start offsets of the files in the split*/
// public long[] getStartOffsets() {
// return isMapRedSet() ? mapredSplit.getStartOffsets() : mapreduceSplit.getStartOffsets();
// }
//
// /** Returns an array containing the lengths of the files in the split*/
// public long[] getLengths() {
// return isMapRedSet() ? mapredSplit.getLengths() : mapreduceSplit.getLengths();
// }
//
// /** Returns the start offset of the i<sup>th</sup> Path */
// public long getOffset(int i) {
// return isMapRedSet() ? mapredSplit.getOffset(i) : mapreduceSplit.getOffset(i);
// }
//
// /** Returns the length of the i<sup>th</sup> Path */
// public long getLength(int i) {
// return isMapRedSet() ? mapredSplit.getLength(i) : mapreduceSplit.getLength(i);
// }
//
// /** Returns the number of Paths in the split */
// public int getNumPaths() {
// return isMapRedSet() ? mapredSplit.getNumPaths() : mapreduceSplit.getNumPaths();
// }
//
// /** Returns the i<sup>th</sup> Path */
// public Path getPath(int i) {
// return isMapRedSet() ? mapredSplit.getPath(i) : mapreduceSplit.getPath(i);
// }
//
// /** Returns all the Paths in the split */
// public Path[] getPaths() {
// return isMapRedSet() ? mapredSplit.getPaths() : mapreduceSplit.getPaths();
// }
//
// /** Returns all the Paths where this input-split resides */
// public String[] getLocations() throws IOException {
// return isMapRedSet() ? mapredSplit.getLocations() : mapreduceSplit.getLocations();
// }
// }
| import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alexholmes.hadooputils.combine.common.CombineFileSplitAdapter;
import com.alexholmes.hadooputils.combine.common.LoggerSink;
import com.alexholmes.hadooputils.combine.common.MetricsSink;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.lib.CombineFileInputFormat;
import org.apache.hadoop.mapred.lib.CombineFileSplit;
import org.apache.hadoop.util.ReflectionUtils;
import java.io.IOException;
import java.util.ArrayList; | /*
* Copyright 2013 Alex Holmes
*
* 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.alexholmes.hadooputils.combine.common.mapred;
/**
* An input format that writes split details to a sink, the default sink being a logger.
*
* @param <K> The key type.
* @param <V> The value type.
*/
public abstract class SplitMetricsCombineInputFormat<K, V> extends CombineFileInputFormat<K, V> {
private static final Log LOG = LogFactory.getLog(SplitMetricsCombineInputFormat.class);
@Override
public InputSplit[] getSplits(JobConf job, int numSplits) throws IOException {
InputSplit[] splits = super.getSplits(job, numSplits);
if (job.getBoolean("hadooputils.combine.sink.enabled", false)) {
writeSplitsToSink(job, organizeSplitsByLocation(splits));
}
return splits;
}
| // Path: src/main/java/com/alexholmes/hadooputils/combine/common/CombineFileSplitAdapter.java
// public class CombineFileSplitAdapter {
// org.apache.hadoop.mapred.lib.CombineFileSplit mapredSplit;
// org.apache.hadoop.mapreduce.lib.input.CombineFileSplit mapreduceSplit;
//
// public CombineFileSplitAdapter(CombineFileSplit mapredSplit) {
// this.mapredSplit = mapredSplit;
// }
//
// public CombineFileSplitAdapter(org.apache.hadoop.mapreduce.lib.input.CombineFileSplit mapreduceSplit) {
// this.mapreduceSplit = mapreduceSplit;
// }
//
// public boolean isMapRedSet() {
// return mapredSplit != null;
// }
//
// public long getLength() {
// return isMapRedSet() ? mapredSplit.getLength() : mapreduceSplit.getLength();
// }
//
// /** Returns an array containing the start offsets of the files in the split*/
// public long[] getStartOffsets() {
// return isMapRedSet() ? mapredSplit.getStartOffsets() : mapreduceSplit.getStartOffsets();
// }
//
// /** Returns an array containing the lengths of the files in the split*/
// public long[] getLengths() {
// return isMapRedSet() ? mapredSplit.getLengths() : mapreduceSplit.getLengths();
// }
//
// /** Returns the start offset of the i<sup>th</sup> Path */
// public long getOffset(int i) {
// return isMapRedSet() ? mapredSplit.getOffset(i) : mapreduceSplit.getOffset(i);
// }
//
// /** Returns the length of the i<sup>th</sup> Path */
// public long getLength(int i) {
// return isMapRedSet() ? mapredSplit.getLength(i) : mapreduceSplit.getLength(i);
// }
//
// /** Returns the number of Paths in the split */
// public int getNumPaths() {
// return isMapRedSet() ? mapredSplit.getNumPaths() : mapreduceSplit.getNumPaths();
// }
//
// /** Returns the i<sup>th</sup> Path */
// public Path getPath(int i) {
// return isMapRedSet() ? mapredSplit.getPath(i) : mapreduceSplit.getPath(i);
// }
//
// /** Returns all the Paths in the split */
// public Path[] getPaths() {
// return isMapRedSet() ? mapredSplit.getPaths() : mapreduceSplit.getPaths();
// }
//
// /** Returns all the Paths where this input-split resides */
// public String[] getLocations() throws IOException {
// return isMapRedSet() ? mapredSplit.getLocations() : mapreduceSplit.getLocations();
// }
// }
// Path: src/main/java/com/alexholmes/hadooputils/combine/common/mapred/SplitMetricsCombineInputFormat.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alexholmes.hadooputils.combine.common.CombineFileSplitAdapter;
import com.alexholmes.hadooputils.combine.common.LoggerSink;
import com.alexholmes.hadooputils.combine.common.MetricsSink;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.lib.CombineFileInputFormat;
import org.apache.hadoop.mapred.lib.CombineFileSplit;
import org.apache.hadoop.util.ReflectionUtils;
import java.io.IOException;
import java.util.ArrayList;
/*
* Copyright 2013 Alex Holmes
*
* 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.alexholmes.hadooputils.combine.common.mapred;
/**
* An input format that writes split details to a sink, the default sink being a logger.
*
* @param <K> The key type.
* @param <V> The value type.
*/
public abstract class SplitMetricsCombineInputFormat<K, V> extends CombineFileInputFormat<K, V> {
private static final Log LOG = LogFactory.getLog(SplitMetricsCombineInputFormat.class);
@Override
public InputSplit[] getSplits(JobConf job, int numSplits) throws IOException {
InputSplit[] splits = super.getSplits(job, numSplits);
if (job.getBoolean("hadooputils.combine.sink.enabled", false)) {
writeSplitsToSink(job, organizeSplitsByLocation(splits));
}
return splits;
}
| protected void writeSplitsToSink(Configuration conf, Map<String, List<CombineFileSplitAdapter>> splits) { |
alexholmes/hadoop-utils | src/main/java/com/alexholmes/hadooputils/combine/common/mapreduce/SplitMetricsCombineInputFormat.java | // Path: src/main/java/com/alexholmes/hadooputils/combine/common/CombineFileSplitAdapter.java
// public class CombineFileSplitAdapter {
// org.apache.hadoop.mapred.lib.CombineFileSplit mapredSplit;
// org.apache.hadoop.mapreduce.lib.input.CombineFileSplit mapreduceSplit;
//
// public CombineFileSplitAdapter(CombineFileSplit mapredSplit) {
// this.mapredSplit = mapredSplit;
// }
//
// public CombineFileSplitAdapter(org.apache.hadoop.mapreduce.lib.input.CombineFileSplit mapreduceSplit) {
// this.mapreduceSplit = mapreduceSplit;
// }
//
// public boolean isMapRedSet() {
// return mapredSplit != null;
// }
//
// public long getLength() {
// return isMapRedSet() ? mapredSplit.getLength() : mapreduceSplit.getLength();
// }
//
// /** Returns an array containing the start offsets of the files in the split*/
// public long[] getStartOffsets() {
// return isMapRedSet() ? mapredSplit.getStartOffsets() : mapreduceSplit.getStartOffsets();
// }
//
// /** Returns an array containing the lengths of the files in the split*/
// public long[] getLengths() {
// return isMapRedSet() ? mapredSplit.getLengths() : mapreduceSplit.getLengths();
// }
//
// /** Returns the start offset of the i<sup>th</sup> Path */
// public long getOffset(int i) {
// return isMapRedSet() ? mapredSplit.getOffset(i) : mapreduceSplit.getOffset(i);
// }
//
// /** Returns the length of the i<sup>th</sup> Path */
// public long getLength(int i) {
// return isMapRedSet() ? mapredSplit.getLength(i) : mapreduceSplit.getLength(i);
// }
//
// /** Returns the number of Paths in the split */
// public int getNumPaths() {
// return isMapRedSet() ? mapredSplit.getNumPaths() : mapreduceSplit.getNumPaths();
// }
//
// /** Returns the i<sup>th</sup> Path */
// public Path getPath(int i) {
// return isMapRedSet() ? mapredSplit.getPath(i) : mapreduceSplit.getPath(i);
// }
//
// /** Returns all the Paths in the split */
// public Path[] getPaths() {
// return isMapRedSet() ? mapredSplit.getPaths() : mapreduceSplit.getPaths();
// }
//
// /** Returns all the Paths where this input-split resides */
// public String[] getLocations() throws IOException {
// return isMapRedSet() ? mapredSplit.getLocations() : mapreduceSplit.getLocations();
// }
// }
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alexholmes.hadooputils.combine.common.CombineFileSplitAdapter;
import com.alexholmes.hadooputils.combine.common.LoggerSink;
import com.alexholmes.hadooputils.combine.common.MetricsSink;
import com.alexholmes.hadooputils.util.HadoopCompat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.lib.input.CombineFileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.CombineFileSplit;
import org.apache.hadoop.util.ReflectionUtils;
import java.io.IOException; | /*
* Copyright 2013 Alex Holmes
*
* 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.alexholmes.hadooputils.combine.common.mapreduce;
/**
* An input format that writes split details to a sink, the default sink being a logger.
*
* @param <K> The key type.
* @param <V> The value type.
*/
public abstract class SplitMetricsCombineInputFormat<K, V> extends CombineFileInputFormat<K, V> {
private static final Log LOG = LogFactory.getLog(SplitMetricsCombineInputFormat.class);
@Override
public List<InputSplit> getSplits(JobContext job) throws IOException {
List<InputSplit> splits = super.getSplits(job);
Configuration conf = HadoopCompat.getConfiguration(job);
if (conf.getBoolean("hadooputils.combine.sink.enabled", false)) {
writeSplitsToSink(conf, organizeSplitsByLocation(splits));
}
return splits;
}
| // Path: src/main/java/com/alexholmes/hadooputils/combine/common/CombineFileSplitAdapter.java
// public class CombineFileSplitAdapter {
// org.apache.hadoop.mapred.lib.CombineFileSplit mapredSplit;
// org.apache.hadoop.mapreduce.lib.input.CombineFileSplit mapreduceSplit;
//
// public CombineFileSplitAdapter(CombineFileSplit mapredSplit) {
// this.mapredSplit = mapredSplit;
// }
//
// public CombineFileSplitAdapter(org.apache.hadoop.mapreduce.lib.input.CombineFileSplit mapreduceSplit) {
// this.mapreduceSplit = mapreduceSplit;
// }
//
// public boolean isMapRedSet() {
// return mapredSplit != null;
// }
//
// public long getLength() {
// return isMapRedSet() ? mapredSplit.getLength() : mapreduceSplit.getLength();
// }
//
// /** Returns an array containing the start offsets of the files in the split*/
// public long[] getStartOffsets() {
// return isMapRedSet() ? mapredSplit.getStartOffsets() : mapreduceSplit.getStartOffsets();
// }
//
// /** Returns an array containing the lengths of the files in the split*/
// public long[] getLengths() {
// return isMapRedSet() ? mapredSplit.getLengths() : mapreduceSplit.getLengths();
// }
//
// /** Returns the start offset of the i<sup>th</sup> Path */
// public long getOffset(int i) {
// return isMapRedSet() ? mapredSplit.getOffset(i) : mapreduceSplit.getOffset(i);
// }
//
// /** Returns the length of the i<sup>th</sup> Path */
// public long getLength(int i) {
// return isMapRedSet() ? mapredSplit.getLength(i) : mapreduceSplit.getLength(i);
// }
//
// /** Returns the number of Paths in the split */
// public int getNumPaths() {
// return isMapRedSet() ? mapredSplit.getNumPaths() : mapreduceSplit.getNumPaths();
// }
//
// /** Returns the i<sup>th</sup> Path */
// public Path getPath(int i) {
// return isMapRedSet() ? mapredSplit.getPath(i) : mapreduceSplit.getPath(i);
// }
//
// /** Returns all the Paths in the split */
// public Path[] getPaths() {
// return isMapRedSet() ? mapredSplit.getPaths() : mapreduceSplit.getPaths();
// }
//
// /** Returns all the Paths where this input-split resides */
// public String[] getLocations() throws IOException {
// return isMapRedSet() ? mapredSplit.getLocations() : mapreduceSplit.getLocations();
// }
// }
// Path: src/main/java/com/alexholmes/hadooputils/combine/common/mapreduce/SplitMetricsCombineInputFormat.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alexholmes.hadooputils.combine.common.CombineFileSplitAdapter;
import com.alexholmes.hadooputils.combine.common.LoggerSink;
import com.alexholmes.hadooputils.combine.common.MetricsSink;
import com.alexholmes.hadooputils.util.HadoopCompat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.lib.input.CombineFileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.CombineFileSplit;
import org.apache.hadoop.util.ReflectionUtils;
import java.io.IOException;
/*
* Copyright 2013 Alex Holmes
*
* 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.alexholmes.hadooputils.combine.common.mapreduce;
/**
* An input format that writes split details to a sink, the default sink being a logger.
*
* @param <K> The key type.
* @param <V> The value type.
*/
public abstract class SplitMetricsCombineInputFormat<K, V> extends CombineFileInputFormat<K, V> {
private static final Log LOG = LogFactory.getLog(SplitMetricsCombineInputFormat.class);
@Override
public List<InputSplit> getSplits(JobContext job) throws IOException {
List<InputSplit> splits = super.getSplits(job);
Configuration conf = HadoopCompat.getConfiguration(job);
if (conf.getBoolean("hadooputils.combine.sink.enabled", false)) {
writeSplitsToSink(conf, organizeSplitsByLocation(splits));
}
return splits;
}
| protected void writeSplitsToSink(Configuration conf, Map<String, List<CombineFileSplitAdapter>> splits) { |
alexholmes/hadoop-utils | src/test/java/com/alexholmes/hadooputils/combine/seqfile/mapred/CombineSequenceFileTest.java | // Path: src/main/java/com/alexholmes/hadooputils/combine/common/mapred/CommonCombineRecordReader.java
// public class CommonCombineRecordReader<K, V> implements RecordReader<K, V> {
// private static final Log LOG = LogFactory.getLog(CommonCombineRecordReader.class);
//
// protected Configuration conf;
// protected int currentSplit = -1;
// protected RecordReader<K, V> reader;
// protected CombineFileSplit split;
// private final RecordReaderEngineerer<K, V> engineerer;
// private long totalBytes;
//
// /**
// * Create an instance of the class.
// *
// * @param conf the Hadoop config
// * @param split the input split
// * @param engineerer the RecordReader engineering instance
// * @throws IOException on io error
// */
// public CommonCombineRecordReader(Configuration conf, CombineFileSplit split, RecordReaderEngineerer<K, V> engineerer) throws IOException {
// this.conf = conf;
//
// this.split = split;
// this.engineerer = engineerer;
//
// for (int i = 0; i < this.split.getPaths().length; i++) {
// totalBytes += this.split.getLength(i);
//
// if (LOG.isDebugEnabled()) {
// LOG.debug(String.format("Got split %s offest %d len %d", this.split.getPath(i), this.split.getOffset(i), this.split.getLength(i)));
// }
// }
//
// nextReader();
// }
//
// /**
// * Moves on to the next split inside {@link #split}. The {@link #reader} will be {@code null}
// * once we have exhausted all the splits.
// *
// * @return true if we successfully moved on to the next split
// * @throws java.io.IOException if we hit io errors
// */
// public boolean nextReader() throws IOException {
// // close the current reader and set it to null
// close();
//
// currentSplit++;
//
// if (currentSplit >= split.getPaths().length) {
// // hit the end of the line
// return false;
// }
//
// FileSplit fileSplit = new FileSplit(
// split.getPath(currentSplit),
// split.getOffset(currentSplit),
// split.getLength(currentSplit),
// split.getLocations() == null || split.getLocations().length - 1 < currentSplit ? null : new String[]{split.getLocations()[currentSplit]});
//
// reader = engineerer.createRecordReader(conf, fileSplit);
// return true;
// }
//
// /**
// * Return the progress within the input split
// *
// * @return 0.0 to 1.0 of the input byte range
// */
// @Override
// public float getProgress() throws IOException {
// if (reader == null) {
// return 1.0f;
// }
//
// long completeBytes = 0;
//
// for (int i = 0; i < currentSplit - 1; i++) {
// completeBytes += split.getLength(i);
// }
//
// float currentReaderProgress = reader.getProgress();
//
// completeBytes += Math.min(split.getLength(currentSplit), (long) ((float) split.getLength(currentSplit)) * currentReaderProgress);
//
// return (float) completeBytes / (float) totalBytes;
// }
//
// @Override
// public boolean next(K key, V value) throws IOException {
//
// while (reader != null) {
// if (reader.next(key, value)) {
// return true;
// }
// nextReader();
// }
// return false;
// }
//
// @Override
// public K createKey() {
// return reader.createKey();
// }
//
// @Override
// public V createValue() {
// return reader.createValue();
// }
//
// @Override
// public long getPos() throws IOException {
// return (long) (((float) totalBytes) * getProgress());
// }
//
// @Override
// public synchronized void close() throws IOException {
// if (reader != null) {
// reader.close();
// reader = null;
// }
// }
//
// /**
// * Create {@link RecordReader} instances.
// *
// * @param <K> the {@link RecordReader} key type
// * @param <V> the {@link RecordReader} value type
// */
// public static interface RecordReaderEngineerer<K, V> {
// /**
// * Create an instance of a {@link RecordReader}.
// *
// * @param conf the Hadoop conf
// * @param split the input split
// * @return the RR
// */
// public RecordReader<K, V> createRecordReader(Configuration conf, FileSplit split) throws IOException;
// }
// }
| import static org.junit.Assert.*;
import com.alexholmes.hadooputils.combine.common.mapred.CommonCombineRecordReader;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.compress.DefaultCodec;
import org.apache.hadoop.mapred.*;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.IOException; |
SequenceFile.Writer writer =
SequenceFile.createWriter(fs, conf, path, Text.class,
Text.class,
SequenceFile.CompressionType.BLOCK,
new DefaultCodec());
try {
writer.append(key, value);
} finally {
writer.close();
}
}
@Test
public void testOneFile() throws IOException, InterruptedException {
Path dir = new Path(tempFolder.getRoot().getAbsolutePath());
CombineSequenceFileInputFormat<Text, Text> inputFormat = new CombineSequenceFileInputFormat<Text, Text>();
Path inputFile = new Path(dir, "file1.txt");
writeSequenceFile(inputFile);
Configuration conf = new Configuration();
JobConf jobConf = new JobConf(conf);
FileInputFormat.addInputPath(jobConf, inputFile);
InputSplit[] splits = inputFormat.getSplits(jobConf, 1);
assertEquals(1, splits.length);
| // Path: src/main/java/com/alexholmes/hadooputils/combine/common/mapred/CommonCombineRecordReader.java
// public class CommonCombineRecordReader<K, V> implements RecordReader<K, V> {
// private static final Log LOG = LogFactory.getLog(CommonCombineRecordReader.class);
//
// protected Configuration conf;
// protected int currentSplit = -1;
// protected RecordReader<K, V> reader;
// protected CombineFileSplit split;
// private final RecordReaderEngineerer<K, V> engineerer;
// private long totalBytes;
//
// /**
// * Create an instance of the class.
// *
// * @param conf the Hadoop config
// * @param split the input split
// * @param engineerer the RecordReader engineering instance
// * @throws IOException on io error
// */
// public CommonCombineRecordReader(Configuration conf, CombineFileSplit split, RecordReaderEngineerer<K, V> engineerer) throws IOException {
// this.conf = conf;
//
// this.split = split;
// this.engineerer = engineerer;
//
// for (int i = 0; i < this.split.getPaths().length; i++) {
// totalBytes += this.split.getLength(i);
//
// if (LOG.isDebugEnabled()) {
// LOG.debug(String.format("Got split %s offest %d len %d", this.split.getPath(i), this.split.getOffset(i), this.split.getLength(i)));
// }
// }
//
// nextReader();
// }
//
// /**
// * Moves on to the next split inside {@link #split}. The {@link #reader} will be {@code null}
// * once we have exhausted all the splits.
// *
// * @return true if we successfully moved on to the next split
// * @throws java.io.IOException if we hit io errors
// */
// public boolean nextReader() throws IOException {
// // close the current reader and set it to null
// close();
//
// currentSplit++;
//
// if (currentSplit >= split.getPaths().length) {
// // hit the end of the line
// return false;
// }
//
// FileSplit fileSplit = new FileSplit(
// split.getPath(currentSplit),
// split.getOffset(currentSplit),
// split.getLength(currentSplit),
// split.getLocations() == null || split.getLocations().length - 1 < currentSplit ? null : new String[]{split.getLocations()[currentSplit]});
//
// reader = engineerer.createRecordReader(conf, fileSplit);
// return true;
// }
//
// /**
// * Return the progress within the input split
// *
// * @return 0.0 to 1.0 of the input byte range
// */
// @Override
// public float getProgress() throws IOException {
// if (reader == null) {
// return 1.0f;
// }
//
// long completeBytes = 0;
//
// for (int i = 0; i < currentSplit - 1; i++) {
// completeBytes += split.getLength(i);
// }
//
// float currentReaderProgress = reader.getProgress();
//
// completeBytes += Math.min(split.getLength(currentSplit), (long) ((float) split.getLength(currentSplit)) * currentReaderProgress);
//
// return (float) completeBytes / (float) totalBytes;
// }
//
// @Override
// public boolean next(K key, V value) throws IOException {
//
// while (reader != null) {
// if (reader.next(key, value)) {
// return true;
// }
// nextReader();
// }
// return false;
// }
//
// @Override
// public K createKey() {
// return reader.createKey();
// }
//
// @Override
// public V createValue() {
// return reader.createValue();
// }
//
// @Override
// public long getPos() throws IOException {
// return (long) (((float) totalBytes) * getProgress());
// }
//
// @Override
// public synchronized void close() throws IOException {
// if (reader != null) {
// reader.close();
// reader = null;
// }
// }
//
// /**
// * Create {@link RecordReader} instances.
// *
// * @param <K> the {@link RecordReader} key type
// * @param <V> the {@link RecordReader} value type
// */
// public static interface RecordReaderEngineerer<K, V> {
// /**
// * Create an instance of a {@link RecordReader}.
// *
// * @param conf the Hadoop conf
// * @param split the input split
// * @return the RR
// */
// public RecordReader<K, V> createRecordReader(Configuration conf, FileSplit split) throws IOException;
// }
// }
// Path: src/test/java/com/alexholmes/hadooputils/combine/seqfile/mapred/CombineSequenceFileTest.java
import static org.junit.Assert.*;
import com.alexholmes.hadooputils.combine.common.mapred.CommonCombineRecordReader;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.compress.DefaultCodec;
import org.apache.hadoop.mapred.*;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.IOException;
SequenceFile.Writer writer =
SequenceFile.createWriter(fs, conf, path, Text.class,
Text.class,
SequenceFile.CompressionType.BLOCK,
new DefaultCodec());
try {
writer.append(key, value);
} finally {
writer.close();
}
}
@Test
public void testOneFile() throws IOException, InterruptedException {
Path dir = new Path(tempFolder.getRoot().getAbsolutePath());
CombineSequenceFileInputFormat<Text, Text> inputFormat = new CombineSequenceFileInputFormat<Text, Text>();
Path inputFile = new Path(dir, "file1.txt");
writeSequenceFile(inputFile);
Configuration conf = new Configuration();
JobConf jobConf = new JobConf(conf);
FileInputFormat.addInputPath(jobConf, inputFile);
InputSplit[] splits = inputFormat.getSplits(jobConf, 1);
assertEquals(1, splits.length);
| CommonCombineRecordReader<Text, Text> rr = (CommonCombineRecordReader<Text, Text>) inputFormat.getRecordReader(splits[0], jobConf, new DummyReporter()); |
alexholmes/hadoop-utils | src/test/java/com/alexholmes/hadooputils/combine/avro/mapreduce/CombineAvroKeyValueInputFormatTest.java | // Path: src/main/java/com/alexholmes/hadooputils/util/AvroFiles.java
// public final class AvroFiles {
// private AvroFiles() {}
//
// /**
// * Creates an avro container file.
// *
// * @param file The file to create.
// * @param schema The schema for the records the file should contain.
// * @param records The records to put in the file.
// * @param <T> The (java) type of the avro records.
// * @return The created file.
// */
// public static <T> File createFile(File file, Schema schema, T... records)
// throws IOException {
// DatumWriter<T> datumWriter = new GenericDatumWriter<T>(schema);
// DataFileWriter<T> fileWriter = new DataFileWriter<T>(datumWriter);
// fileWriter.create(schema, file);
// for (T record : records) {
// fileWriter.append(record);
// }
// fileWriter.close();
//
// return file;
// }
// }
| import com.alexholmes.hadooputils.util.AvroFiles;
import org.apache.avro.Schema;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.hadoop.io.AvroKeyValue;
import org.apache.avro.io.DatumReader;
import org.apache.avro.mapred.AvroKey;
import org.apache.avro.mapred.AvroValue;
import org.apache.avro.mapreduce.AvroJob;
import org.apache.avro.mapreduce.AvroKeyValueInputFormat;
import org.apache.avro.mapreduce.AvroKeyValueOutputFormat;
import org.apache.avro.specific.SpecificDatumReader;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import static org.junit.Assert.*; | /*
* Copyright 2013 Alex Holmes
*
* 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.alexholmes.hadooputils.combine.avro.mapreduce;
/**
*/
public class CombineAvroKeyValueInputFormatTest {
@Rule
public TemporaryFolder mTempDir = new TemporaryFolder();
/**
* Creates an Avro file of <docid, text> pairs to use for test input:
*
* +-----+-----------------------+
* | KEY | VALUE |
* +-----+-----------------------+
* | 1 | "apple banana carrot" |
* | 2 | "apple banana" |
* | 3 | "apple" |
* +-----+-----------------------+
*
* @return The avro file.
*/
private File createInputFile() throws IOException {
Schema keyValueSchema = AvroKeyValue.getSchema(
Schema.create(Schema.Type.INT), Schema.create(Schema.Type.STRING));
AvroKeyValue<Integer, CharSequence> record1
= new AvroKeyValue<Integer, CharSequence>(new GenericData.Record(keyValueSchema));
record1.setKey(1);
record1.setValue("apple banana carrot");
AvroKeyValue<Integer, CharSequence> record2
= new AvroKeyValue<Integer, CharSequence>(new GenericData.Record(keyValueSchema));
record2.setKey(2);
record2.setValue("apple banana");
AvroKeyValue<Integer, CharSequence> record3
= new AvroKeyValue<Integer, CharSequence>(new GenericData.Record(keyValueSchema));
record3.setKey(3);
record3.setValue("apple");
| // Path: src/main/java/com/alexholmes/hadooputils/util/AvroFiles.java
// public final class AvroFiles {
// private AvroFiles() {}
//
// /**
// * Creates an avro container file.
// *
// * @param file The file to create.
// * @param schema The schema for the records the file should contain.
// * @param records The records to put in the file.
// * @param <T> The (java) type of the avro records.
// * @return The created file.
// */
// public static <T> File createFile(File file, Schema schema, T... records)
// throws IOException {
// DatumWriter<T> datumWriter = new GenericDatumWriter<T>(schema);
// DataFileWriter<T> fileWriter = new DataFileWriter<T>(datumWriter);
// fileWriter.create(schema, file);
// for (T record : records) {
// fileWriter.append(record);
// }
// fileWriter.close();
//
// return file;
// }
// }
// Path: src/test/java/com/alexholmes/hadooputils/combine/avro/mapreduce/CombineAvroKeyValueInputFormatTest.java
import com.alexholmes.hadooputils.util.AvroFiles;
import org.apache.avro.Schema;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.hadoop.io.AvroKeyValue;
import org.apache.avro.io.DatumReader;
import org.apache.avro.mapred.AvroKey;
import org.apache.avro.mapred.AvroValue;
import org.apache.avro.mapreduce.AvroJob;
import org.apache.avro.mapreduce.AvroKeyValueInputFormat;
import org.apache.avro.mapreduce.AvroKeyValueOutputFormat;
import org.apache.avro.specific.SpecificDatumReader;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import static org.junit.Assert.*;
/*
* Copyright 2013 Alex Holmes
*
* 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.alexholmes.hadooputils.combine.avro.mapreduce;
/**
*/
public class CombineAvroKeyValueInputFormatTest {
@Rule
public TemporaryFolder mTempDir = new TemporaryFolder();
/**
* Creates an Avro file of <docid, text> pairs to use for test input:
*
* +-----+-----------------------+
* | KEY | VALUE |
* +-----+-----------------------+
* | 1 | "apple banana carrot" |
* | 2 | "apple banana" |
* | 3 | "apple" |
* +-----+-----------------------+
*
* @return The avro file.
*/
private File createInputFile() throws IOException {
Schema keyValueSchema = AvroKeyValue.getSchema(
Schema.create(Schema.Type.INT), Schema.create(Schema.Type.STRING));
AvroKeyValue<Integer, CharSequence> record1
= new AvroKeyValue<Integer, CharSequence>(new GenericData.Record(keyValueSchema));
record1.setKey(1);
record1.setValue("apple banana carrot");
AvroKeyValue<Integer, CharSequence> record2
= new AvroKeyValue<Integer, CharSequence>(new GenericData.Record(keyValueSchema));
record2.setKey(2);
record2.setValue("apple banana");
AvroKeyValue<Integer, CharSequence> record3
= new AvroKeyValue<Integer, CharSequence>(new GenericData.Record(keyValueSchema));
record3.setKey(3);
record3.setValue("apple");
| return AvroFiles.createFile(new File(mTempDir.getRoot(), "inputKeyValues.avro"), |
paritytrading/nassau | libraries/core/src/test/java/com/paritytrading/nassau/binaryfile/BinaryFILEStatus.java | // Path: libraries/core/src/test/java/com/paritytrading/nassau/Value.java
// public class Value {
//
// private static final ToStringStyle STYLE = new StandardToStringStyle() {
// {
// setUseShortClassName(true);
// setUseFieldNames(false);
// setUseIdentityHashCode(false);
// setContentStart("(");
// setContentEnd(")");
// }
// };
//
// @Override
// public boolean equals(Object obj) {
// return EqualsBuilder.reflectionEquals(this, obj);
// }
//
// @Override
// public int hashCode() {
// return HashCodeBuilder.reflectionHashCode(this);
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this, STYLE);
// }
//
// }
| import com.paritytrading.nassau.Value;
import java.util.ArrayList;
import java.util.List; | /*
* Copyright 2014 Nassau authors
*
* 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.paritytrading.nassau.binaryfile;
class BinaryFILEStatus implements BinaryFILEStatusListener {
private List<Event> events;
public BinaryFILEStatus() {
this.events = new ArrayList<>();
}
public List<Event> collect() {
return events;
}
@Override
public void endOfSession() {
events.add(new EndOfSession());
}
public interface Event {
}
| // Path: libraries/core/src/test/java/com/paritytrading/nassau/Value.java
// public class Value {
//
// private static final ToStringStyle STYLE = new StandardToStringStyle() {
// {
// setUseShortClassName(true);
// setUseFieldNames(false);
// setUseIdentityHashCode(false);
// setContentStart("(");
// setContentEnd(")");
// }
// };
//
// @Override
// public boolean equals(Object obj) {
// return EqualsBuilder.reflectionEquals(this, obj);
// }
//
// @Override
// public int hashCode() {
// return HashCodeBuilder.reflectionHashCode(this);
// }
//
// @Override
// public String toString() {
// return ToStringBuilder.reflectionToString(this, STYLE);
// }
//
// }
// Path: libraries/core/src/test/java/com/paritytrading/nassau/binaryfile/BinaryFILEStatus.java
import com.paritytrading.nassau.Value;
import java.util.ArrayList;
import java.util.List;
/*
* Copyright 2014 Nassau authors
*
* 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.paritytrading.nassau.binaryfile;
class BinaryFILEStatus implements BinaryFILEStatusListener {
private List<Event> events;
public BinaryFILEStatus() {
this.events = new ArrayList<>();
}
public List<Event> collect() {
return events;
}
@Override
public void endOfSession() {
events.add(new EndOfSession());
}
public interface Event {
}
| public static class EndOfSession extends Value implements Event { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.