proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/helper/SqlServerDialect.java
|
SqlServerDialect
|
getPageSql
|
class SqlServerDialect extends AbstractHelperDialect {
protected SqlServerSqlParser sqlServerSqlParser;
protected Cache<String, String> CACHE_COUNTSQL;
protected Cache<String, String> CACHE_PAGESQL;
protected ReplaceSql replaceSql;
@Override
public String getCountSql(MappedStatement ms, BoundSql boundSql, Object parameterObject, RowBounds rowBounds, CacheKey countKey) {
String sql = boundSql.getSql();
String cacheSql = CACHE_COUNTSQL.get(sql);
if (cacheSql != null) {
return cacheSql;
} else {
cacheSql = sql;
}
cacheSql = replaceSql.replace(cacheSql);
cacheSql = countSqlParser.getSmartCountSql(cacheSql);
cacheSql = replaceSql.restore(cacheSql);
CACHE_COUNTSQL.put(sql, cacheSql);
return cacheSql;
}
@Override
public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, Page page, BoundSql boundSql, CacheKey pageKey) {
return paramMap;
}
@Override
public String getPageSql(String sql, Page page, CacheKey pageKey) {<FILL_FUNCTION_BODY>}
/**
* 分页查询,pageHelper转换SQL时报错with(nolock)不识别的问题,
* 重写父类AbstractHelperDialect.getPageSql转换出错的方法。
* 1. this.replaceSql.replace(sql);先转换成假的表名
* 2. 然后进行SQL转换
* 3. this.replaceSql.restore(sql);最后再恢复成真的with(nolock)
*/
@Override
public String getPageSql(MappedStatement ms, BoundSql boundSql, Object parameterObject, RowBounds rowBounds, CacheKey pageKey) {
String sql = boundSql.getSql();
Page page = this.getLocalPage();
String orderBy = page.getOrderBy();
if (StringUtil.isNotEmpty(orderBy)) {
pageKey.update(orderBy);
sql = this.replaceSql.replace(sql);
sql = orderBySqlParser.converToOrderBySql(sql, orderBy);
sql = this.replaceSql.restore(sql);
}
return page.isOrderByOnly() ? sql : this.getPageSql(sql, page, pageKey);
}
@Override
public void setProperties(Properties properties) {
super.setProperties(properties);
this.sqlServerSqlParser = ClassUtil.newInstance(properties.getProperty("sqlServerSqlParser"), SqlServerSqlParser.class, properties, DefaultSqlServerSqlParser::new);
String replaceSql = properties.getProperty("replaceSql");
if (StringUtil.isEmpty(replaceSql) || "regex".equalsIgnoreCase(replaceSql)) {
this.replaceSql = new RegexWithNolockReplaceSql();
} else if ("simple".equalsIgnoreCase(replaceSql)) {
this.replaceSql = new SimpleWithNolockReplaceSql();
} else {
this.replaceSql = ClassUtil.newInstance(replaceSql, properties);
}
String sqlCacheClass = properties.getProperty("sqlCacheClass");
if (StringUtil.isNotEmpty(sqlCacheClass) && !sqlCacheClass.equalsIgnoreCase("false")) {
CACHE_COUNTSQL = CacheFactory.createCache(sqlCacheClass, "count", properties);
CACHE_PAGESQL = CacheFactory.createCache(sqlCacheClass, "page", properties);
} else {
CACHE_COUNTSQL = CacheFactory.createCache(null, "count", properties);
CACHE_PAGESQL = CacheFactory.createCache(null, "page", properties);
}
}
}
|
//处理pageKey
pageKey.update(page.getStartRow());
pageKey.update(page.getPageSize());
String cacheSql = CACHE_PAGESQL.get(sql);
if (cacheSql == null) {
cacheSql = sql;
cacheSql = replaceSql.replace(cacheSql);
cacheSql = sqlServerSqlParser.convertToPageSql(cacheSql, null, null);
cacheSql = replaceSql.restore(cacheSql);
CACHE_PAGESQL.put(sql, cacheSql);
}
cacheSql = cacheSql.replace(String.valueOf(Long.MIN_VALUE), String.valueOf(page.getStartRow()));
cacheSql = cacheSql.replace(String.valueOf(Long.MAX_VALUE), String.valueOf(page.getPageSize()));
return cacheSql;
| 965
| 211
| 1,176
|
<methods>public non-sealed void <init>() ,public void afterAll() ,public boolean afterCount(long, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.Object afterPage(List#RAW, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforeCount(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforePage(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.String getCountSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public Page<T> getLocalPage() ,public java.lang.String getPageSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.String getPageSql(java.lang.String, Page#RAW, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.Object processPageParameter(org.apache.ibatis.mapping.MappedStatement, Map<java.lang.String,java.lang.Object>, Page#RAW, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public java.lang.Object processParameterObject(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) ,public final boolean skip(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) <variables>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/rowbounds/Db2RowBoundsDialect.java
|
Db2RowBoundsDialect
|
getPageSql
|
class Db2RowBoundsDialect extends AbstractRowBoundsDialect {
@Override
public String getPageSql(String sql, RowBounds rowBounds, CacheKey pageKey) {<FILL_FUNCTION_BODY>}
}
|
int startRow = rowBounds.getOffset() + 1;
int endRow = rowBounds.getOffset() + rowBounds.getLimit();
StringBuilder sqlBuilder = new StringBuilder(sql.length() + 120);
sqlBuilder.append("SELECT * FROM (SELECT TMP_PAGE.*,ROWNUMBER() OVER() AS PAGEHELPER_ROW_ID FROM ( \n");
sqlBuilder.append(sql);
sqlBuilder.append("\n ) AS TMP_PAGE) TMP_PAGE WHERE PAGEHELPER_ROW_ID BETWEEN ");
sqlBuilder.append(startRow);
sqlBuilder.append(" AND ");
sqlBuilder.append(endRow);
pageKey.update(startRow);
pageKey.update(endRow);
return sqlBuilder.toString();
| 60
| 199
| 259
|
<methods>public non-sealed void <init>() ,public void afterAll() ,public boolean afterCount(long, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.Object afterPage(List#RAW, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforeCount(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforePage(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.String getPageSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.String getPageSql(java.lang.String, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public java.lang.Object processParameterObject(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) ,public boolean skip(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) <variables>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/rowbounds/HerdDBRowBoundsDialect.java
|
HerdDBRowBoundsDialect
|
getPageSql
|
class HerdDBRowBoundsDialect extends AbstractRowBoundsDialect {
@Override
public String getPageSql(String sql, RowBounds rowBounds, CacheKey pageKey) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sqlBuilder = new StringBuilder(sql.length() + 14);
sqlBuilder.append(sql);
if (rowBounds.getOffset() == 0) {
sqlBuilder.append("\n LIMIT ");
sqlBuilder.append(rowBounds.getLimit());
} else {
sqlBuilder.append("\n LIMIT ");
sqlBuilder.append(rowBounds.getOffset());
sqlBuilder.append(",");
sqlBuilder.append(rowBounds.getLimit());
pageKey.update(rowBounds.getOffset());
}
pageKey.update(rowBounds.getLimit());
return sqlBuilder.toString();
| 60
| 155
| 215
|
<methods>public non-sealed void <init>() ,public void afterAll() ,public boolean afterCount(long, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.Object afterPage(List#RAW, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforeCount(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforePage(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.String getPageSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.String getPageSql(java.lang.String, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public java.lang.Object processParameterObject(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) ,public boolean skip(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) <variables>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/rowbounds/HsqldbRowBoundsDialect.java
|
HsqldbRowBoundsDialect
|
getPageSql
|
class HsqldbRowBoundsDialect extends AbstractRowBoundsDialect {
@Override
public String getPageSql(String sql, RowBounds rowBounds, CacheKey pageKey) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sqlBuilder = new StringBuilder(sql.length() + 20);
sqlBuilder.append(sql);
if (rowBounds.getLimit() > 0) {
sqlBuilder.append("\n LIMIT ");
sqlBuilder.append(rowBounds.getLimit());
pageKey.update(rowBounds.getLimit());
}
if (rowBounds.getOffset() > 0) {
sqlBuilder.append("\n OFFSET ");
sqlBuilder.append(rowBounds.getOffset());
pageKey.update(rowBounds.getOffset());
}
return sqlBuilder.toString();
| 60
| 146
| 206
|
<methods>public non-sealed void <init>() ,public void afterAll() ,public boolean afterCount(long, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.Object afterPage(List#RAW, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforeCount(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforePage(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.String getPageSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.String getPageSql(java.lang.String, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public java.lang.Object processParameterObject(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) ,public boolean skip(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) <variables>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/rowbounds/InformixRowBoundsDialect.java
|
InformixRowBoundsDialect
|
getPageSql
|
class InformixRowBoundsDialect extends AbstractRowBoundsDialect {
@Override
public String getPageSql(String sql, RowBounds rowBounds, CacheKey pageKey) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sqlBuilder = new StringBuilder(sql.length() + 40);
sqlBuilder.append("SELECT ");
if (rowBounds.getOffset() > 0) {
sqlBuilder.append(" SKIP ");
sqlBuilder.append(rowBounds.getOffset());
pageKey.update(rowBounds.getOffset());
}
if (rowBounds.getLimit() > 0) {
sqlBuilder.append(" FIRST ");
sqlBuilder.append(rowBounds.getLimit());
pageKey.update(rowBounds.getLimit());
}
sqlBuilder.append(" * FROM ( \n");
sqlBuilder.append(sql);
sqlBuilder.append("\n ) TEMP_T");
return sqlBuilder.toString();
| 59
| 181
| 240
|
<methods>public non-sealed void <init>() ,public void afterAll() ,public boolean afterCount(long, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.Object afterPage(List#RAW, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforeCount(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforePage(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.String getPageSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.String getPageSql(java.lang.String, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public java.lang.Object processParameterObject(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) ,public boolean skip(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) <variables>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/rowbounds/MySqlRowBoundsDialect.java
|
MySqlRowBoundsDialect
|
getPageSql
|
class MySqlRowBoundsDialect extends AbstractRowBoundsDialect {
@Override
public String getPageSql(String sql, RowBounds rowBounds, CacheKey pageKey) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sqlBuilder = new StringBuilder(sql.length() + 14);
sqlBuilder.append(sql);
if (rowBounds.getOffset() == 0) {
sqlBuilder.append("\n LIMIT ");
sqlBuilder.append(rowBounds.getLimit());
} else {
sqlBuilder.append("\n LIMIT ");
sqlBuilder.append(rowBounds.getOffset());
sqlBuilder.append(",");
sqlBuilder.append(rowBounds.getLimit());
pageKey.update(rowBounds.getOffset());
}
pageKey.update(rowBounds.getLimit());
return sqlBuilder.toString();
| 59
| 155
| 214
|
<methods>public non-sealed void <init>() ,public void afterAll() ,public boolean afterCount(long, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.Object afterPage(List#RAW, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforeCount(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforePage(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.String getPageSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.String getPageSql(java.lang.String, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public java.lang.Object processParameterObject(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) ,public boolean skip(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) <variables>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/rowbounds/OracleRowBoundsDialect.java
|
OracleRowBoundsDialect
|
getPageSql
|
class OracleRowBoundsDialect extends AbstractRowBoundsDialect {
@Override
public String getPageSql(String sql, RowBounds rowBounds, CacheKey pageKey) {<FILL_FUNCTION_BODY>}
}
|
int startRow = rowBounds.getOffset();
int endRow = rowBounds.getOffset() + rowBounds.getLimit();
StringBuilder sqlBuilder = new StringBuilder(sql.length() + 120);
if (startRow > 0) {
sqlBuilder.append("SELECT * FROM ( ");
}
if (endRow > 0) {
sqlBuilder.append(" SELECT TMP_PAGE.*, ROWNUM PAGEHELPER_ROW_ID FROM ( ");
}
sqlBuilder.append("\n");
sqlBuilder.append(sql);
sqlBuilder.append("\n");
if (endRow > 0) {
sqlBuilder.append(" ) TMP_PAGE WHERE ROWNUM <= ");
sqlBuilder.append(endRow);
pageKey.update(endRow);
}
if (startRow > 0) {
sqlBuilder.append(" ) WHERE PAGEHELPER_ROW_ID > ");
sqlBuilder.append(startRow);
pageKey.update(startRow);
}
return sqlBuilder.toString();
| 58
| 262
| 320
|
<methods>public non-sealed void <init>() ,public void afterAll() ,public boolean afterCount(long, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.Object afterPage(List#RAW, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforeCount(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforePage(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.String getPageSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.String getPageSql(java.lang.String, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public java.lang.Object processParameterObject(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) ,public boolean skip(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) <variables>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/rowbounds/PostgreSqlRowBoundsDialect.java
|
PostgreSqlRowBoundsDialect
|
getPageSql
|
class PostgreSqlRowBoundsDialect extends AbstractRowBoundsDialect {
/**
* 构建 <a href="https://www.postgresql.org/docs/current/queries-limit.html">PostgreSQL</a>分页查询语句
*/
@Override
public String getPageSql(String sql, RowBounds rowBounds, CacheKey pageKey) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sqlStr = new StringBuilder(sql.length() + 17);
sqlStr.append(sql);
if (rowBounds.getOffset() == 0) {
sqlStr.append(" LIMIT ");
sqlStr.append(rowBounds.getLimit());
} else {
sqlStr.append(" LIMIT ");
sqlStr.append(rowBounds.getLimit());
sqlStr.append(" OFFSET ");
sqlStr.append(rowBounds.getOffset());
pageKey.update(rowBounds.getOffset());
}
pageKey.update(rowBounds.getLimit());
return sqlStr.toString();
| 110
| 154
| 264
|
<methods>public non-sealed void <init>() ,public void afterAll() ,public boolean afterCount(long, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.Object afterPage(List#RAW, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforeCount(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforePage(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.String getPageSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.String getPageSql(java.lang.String, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public java.lang.Object processParameterObject(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) ,public boolean skip(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) <variables>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/rowbounds/SqlServer2012RowBoundsDialect.java
|
SqlServer2012RowBoundsDialect
|
getPageSql
|
class SqlServer2012RowBoundsDialect extends SqlServerRowBoundsDialect {
@Override
public String getPageSql(String sql, RowBounds rowBounds, CacheKey pageKey) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sqlBuilder = new StringBuilder(sql.length() + 14);
sqlBuilder.append(sql);
sqlBuilder.append("\n OFFSET ");
sqlBuilder.append(rowBounds.getOffset());
sqlBuilder.append(" ROWS ");
pageKey.update(rowBounds.getOffset());
sqlBuilder.append(" FETCH NEXT ");
sqlBuilder.append(rowBounds.getLimit());
sqlBuilder.append(" ROWS ONLY");
pageKey.update(rowBounds.getLimit());
return sqlBuilder.toString();
| 64
| 138
| 202
|
<methods>public non-sealed void <init>() ,public java.lang.String getCountSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public java.lang.String getPageSql(java.lang.String, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) <variables>protected com.github.pagehelper.dialect.ReplaceSql replaceSql,protected com.github.pagehelper.parser.SqlServerSqlParser sqlServerSqlParser
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/dialect/rowbounds/SqlServerRowBoundsDialect.java
|
SqlServerRowBoundsDialect
|
setProperties
|
class SqlServerRowBoundsDialect extends AbstractRowBoundsDialect {
protected SqlServerSqlParser sqlServerSqlParser;
protected ReplaceSql replaceSql;
@Override
public String getCountSql(MappedStatement ms, BoundSql boundSql, Object parameterObject, RowBounds rowBounds, CacheKey countKey) {
String sql = boundSql.getSql();
sql = replaceSql.replace(sql);
sql = countSqlParser.getSmartCountSql(sql);
sql = replaceSql.restore(sql);
return sql;
}
@Override
public String getPageSql(String sql, RowBounds rowBounds, CacheKey pageKey) {
//处理pageKey
pageKey.update(rowBounds.getOffset());
pageKey.update(rowBounds.getLimit());
sql = replaceSql.replace(sql);
sql = sqlServerSqlParser.convertToPageSql(sql, null, null);
sql = replaceSql.restore(sql);
sql = sql.replace(String.valueOf(Long.MIN_VALUE), String.valueOf(rowBounds.getOffset()));
sql = sql.replace(String.valueOf(Long.MAX_VALUE), String.valueOf(rowBounds.getLimit()));
return sql;
}
@Override
public void setProperties(Properties properties) {<FILL_FUNCTION_BODY>}
}
|
super.setProperties(properties);
this.sqlServerSqlParser = ClassUtil.newInstance(properties.getProperty("sqlServerSqlParser"), SqlServerSqlParser.class, properties, DefaultSqlServerSqlParser::new);
String replaceSql = properties.getProperty("replaceSql");
if (StringUtil.isEmpty(replaceSql) || "simple".equalsIgnoreCase(replaceSql)) {
this.replaceSql = new SimpleWithNolockReplaceSql();
} else if ("regex".equalsIgnoreCase(replaceSql)) {
this.replaceSql = new RegexWithNolockReplaceSql();
} else {
this.replaceSql = ClassUtil.newInstance(replaceSql, properties);
}
| 336
| 167
| 503
|
<methods>public non-sealed void <init>() ,public void afterAll() ,public boolean afterCount(long, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.Object afterPage(List#RAW, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforeCount(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public boolean beforePage(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) ,public java.lang.String getPageSql(org.apache.ibatis.mapping.MappedStatement, org.apache.ibatis.mapping.BoundSql, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public abstract java.lang.String getPageSql(java.lang.String, org.apache.ibatis.session.RowBounds, org.apache.ibatis.cache.CacheKey) ,public java.lang.Object processParameterObject(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.mapping.BoundSql, org.apache.ibatis.cache.CacheKey) ,public void setProperties(java.util.Properties) ,public boolean skip(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds) <variables>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/page/PageBoundSqlInterceptors.java
|
PageBoundSqlInterceptors
|
setProperties
|
class PageBoundSqlInterceptors {
private BoundSqlInterceptor.Chain chain;
public void setProperties(Properties properties) {<FILL_FUNCTION_BODY>}
public BoundSqlInterceptor.Chain getChain() {
return chain;
}
}
|
//初始化 boundSqlInterceptorChain
String boundSqlInterceptorStr = properties.getProperty("boundSqlInterceptors");
if (StringUtil.isNotEmpty(boundSqlInterceptorStr)) {
String[] boundSqlInterceptors = boundSqlInterceptorStr.split("[;|,]");
List<BoundSqlInterceptor> list = new ArrayList<BoundSqlInterceptor>();
for (int i = 0; i < boundSqlInterceptors.length; i++) {
list.add(ClassUtil.newInstance(boundSqlInterceptors[i], properties));
}
if (list.size() > 0) {
chain = new BoundSqlInterceptorChain(null, list);
}
}
| 73
| 185
| 258
|
<no_super_class>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/page/PageMethod.java
|
PageMethod
|
startPage
|
class PageMethod {
protected static final ThreadLocal<Page> LOCAL_PAGE = new ThreadLocal<Page>();
protected static boolean DEFAULT_COUNT = true;
/**
* 设置 Page 参数
*
* @param page
*/
public static void setLocalPage(Page page) {
LOCAL_PAGE.set(page);
}
/**
* 获取 Page 参数
*
* @return
*/
public static <T> Page<T> getLocalPage() {
return LOCAL_PAGE.get();
}
/**
* 移除本地变量
*/
public static void clearPage() {
LOCAL_PAGE.remove();
}
/**
* 获取任意查询方法的count总数
*
* @param select
* @return
*/
public static long count(ISelect select) {
//单纯count查询时禁用异步count
Page<?> page = startPage(1, -1, true).disableAsyncCount();
select.doSelect();
return page.getTotal();
}
/**
* 开始分页
*
* @param params
*/
public static <E> Page<E> startPage(Object params) {<FILL_FUNCTION_BODY>}
/**
* 开始分页
*
* @param pageNum 页码
* @param pageSize 每页显示数量
*/
public static <E> Page<E> startPage(int pageNum, int pageSize) {
return startPage(pageNum, pageSize, DEFAULT_COUNT);
}
/**
* 开始分页
*
* @param pageNum 页码
* @param pageSize 每页显示数量
* @param count 是否进行count查询
*/
public static <E> Page<E> startPage(int pageNum, int pageSize, boolean count) {
return startPage(pageNum, pageSize, count, null, null);
}
/**
* 开始分页
*
* @param pageNum 页码
* @param pageSize 每页显示数量
* @param orderBy 排序
*/
public static <E> Page<E> startPage(int pageNum, int pageSize, String orderBy) {
Page<E> page = startPage(pageNum, pageSize);
page.setOrderBy(orderBy);
return page;
}
/**
* 开始分页
*
* @param pageNum 页码
* @param pageSize 每页显示数量
* @param count 是否进行count查询
* @param reasonable 分页合理化,null时用默认配置
* @param pageSizeZero true且pageSize=0时返回全部结果,false时分页,null时用默认配置
*/
public static <E> Page<E> startPage(int pageNum, int pageSize, boolean count, Boolean reasonable, Boolean pageSizeZero) {
Page<E> page = new Page<E>(pageNum, pageSize, count);
page.setReasonable(reasonable);
page.setPageSizeZero(pageSizeZero);
//当已经执行过orderBy的时候
Page<E> oldPage = getLocalPage();
if (oldPage != null && oldPage.isOrderByOnly()) {
page.setOrderBy(oldPage.getOrderBy());
}
setLocalPage(page);
return page;
}
/**
* 开始分页
*
* @param offset 起始位置,偏移位置
* @param limit 每页显示数量
*/
public static <E> Page<E> offsetPage(int offset, int limit) {
return offsetPage(offset, limit, DEFAULT_COUNT);
}
/**
* 开始分页
*
* @param offset 起始位置,偏移位置
* @param limit 每页显示数量
* @param count 是否进行count查询
*/
public static <E> Page<E> offsetPage(int offset, int limit, boolean count) {
Page<E> page = new Page<E>(new int[]{offset, limit}, count);
//当已经执行过orderBy的时候
Page<E> oldPage = getLocalPage();
if (oldPage != null && oldPage.isOrderByOnly()) {
page.setOrderBy(oldPage.getOrderBy());
}
setLocalPage(page);
return page;
}
/**
* 排序
*
* @param orderBy
*/
public static void orderBy(String orderBy) {
Page<?> page = getLocalPage();
if (page != null) {
page.setOrderBy(orderBy);
if (page.getPageSizeZero() != null && page.getPageSizeZero() && page.getPageSize() == 0) {
page.setOrderByOnly(true);
}
} else {
page = new Page();
page.setOrderBy(orderBy);
page.setOrderByOnly(true);
setLocalPage(page);
}
}
/**
* 设置参数
*
* @param properties 插件属性
*/
protected static void setStaticProperties(Properties properties) {
//defaultCount,这是一个全局生效的参数,多数据源时也是统一的行为
if (properties != null) {
DEFAULT_COUNT = Boolean.valueOf(properties.getProperty("defaultCount", "true"));
}
}
}
|
Page<E> page = PageObjectUtil.getPageFromObject(params, true);
//当已经执行过orderBy的时候
Page<E> oldPage = getLocalPage();
if (oldPage != null && oldPage.isOrderByOnly()) {
page.setOrderBy(oldPage.getOrderBy());
}
setLocalPage(page);
return page;
| 1,422
| 97
| 1,519
|
<no_super_class>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/page/PageParams.java
|
PageParams
|
getPage
|
class PageParams {
/**
* RowBounds参数offset作为PageNum使用 - 默认不使用
*/
protected boolean offsetAsPageNum = false;
/**
* RowBounds是否进行count查询 - 默认不查询
*/
protected boolean rowBoundsWithCount = false;
/**
* 当设置为true的时候,如果pagesize设置为0(或RowBounds的limit=0),就不执行分页,返回全部结果
*/
protected boolean pageSizeZero = false;
/**
* 分页合理化
*/
protected boolean reasonable = false;
/**
* 是否支持接口参数来传递分页参数,默认false
*/
protected boolean supportMethodsArguments = false;
/**
* 默认count(0)
*/
protected String countColumn = "0";
/**
* 转换count查询时保留 order by 排序
*/
private boolean keepOrderBy = false;
/**
* 转换count查询时保留子查询的 order by 排序
*/
private boolean keepSubSelectOrderBy = false;
/**
* 异步count查询
*/
private boolean asyncCount = false;
/**
* 获取分页参数
*
* @param parameterObject
* @param rowBounds
* @return
*/
public Page getPage(Object parameterObject, RowBounds rowBounds) {<FILL_FUNCTION_BODY>}
public void setProperties(Properties properties) {
//offset作为PageNum使用
String offsetAsPageNum = properties.getProperty("offsetAsPageNum");
this.offsetAsPageNum = Boolean.parseBoolean(offsetAsPageNum);
//RowBounds方式是否做count查询
String rowBoundsWithCount = properties.getProperty("rowBoundsWithCount");
this.rowBoundsWithCount = Boolean.parseBoolean(rowBoundsWithCount);
//当设置为true的时候,如果pagesize设置为0(或RowBounds的limit=0),就不执行分页
String pageSizeZero = properties.getProperty("pageSizeZero");
this.pageSizeZero = Boolean.parseBoolean(pageSizeZero);
//分页合理化,true开启,如果分页参数不合理会自动修正。默认false不启用
String reasonable = properties.getProperty("reasonable");
this.reasonable = Boolean.parseBoolean(reasonable);
//是否支持接口参数来传递分页参数,默认false
String supportMethodsArguments = properties.getProperty("supportMethodsArguments");
this.supportMethodsArguments = Boolean.parseBoolean(supportMethodsArguments);
//默认count列
String countColumn = properties.getProperty("countColumn");
if (StringUtil.isNotEmpty(countColumn)) {
this.countColumn = countColumn;
}
//当offsetAsPageNum=false的时候,不能
//参数映射
PageObjectUtil.setParams(properties.getProperty("params"));
// count查询时,是否保留查询中的 order by
keepOrderBy = Boolean.parseBoolean(properties.getProperty("keepOrderBy"));
// count查询时,是否保留子查询中的 order by
keepSubSelectOrderBy = Boolean.parseBoolean(properties.getProperty("keepSubSelectOrderBy"));
// 异步count查询
asyncCount = Boolean.parseBoolean(properties.getProperty("asyncCount"));
}
public boolean isOffsetAsPageNum() {
return offsetAsPageNum;
}
public boolean isRowBoundsWithCount() {
return rowBoundsWithCount;
}
public boolean isPageSizeZero() {
return pageSizeZero;
}
public boolean isReasonable() {
return reasonable;
}
public boolean isSupportMethodsArguments() {
return supportMethodsArguments;
}
public String getCountColumn() {
return countColumn;
}
public boolean isAsyncCount() {
return asyncCount;
}
}
|
Page page = PageHelper.getLocalPage();
if (page == null) {
if (rowBounds != RowBounds.DEFAULT) {
if (offsetAsPageNum) {
page = new Page(rowBounds.getOffset(), rowBounds.getLimit(), rowBoundsWithCount);
} else {
page = new Page(new int[]{rowBounds.getOffset(), rowBounds.getLimit()}, rowBoundsWithCount);
//offsetAsPageNum=false的时候,由于PageNum问题,不能使用reasonable,这里会强制为false
page.setReasonable(false);
}
if (rowBounds instanceof PageRowBounds) {
PageRowBounds pageRowBounds = (PageRowBounds) rowBounds;
page.setCount(pageRowBounds.getCount() == null || pageRowBounds.getCount());
}
} else if (parameterObject instanceof IPage || supportMethodsArguments) {
try {
page = PageObjectUtil.getPageFromObject(parameterObject, false);
} catch (Exception e) {
return null;
}
}
if (page == null) {
return null;
}
PageHelper.setLocalPage(page);
}
//分页合理化
if (page.getReasonable() == null) {
page.setReasonable(reasonable);
}
//当设置为true的时候,如果pagesize设置为0(或RowBounds的limit=0),就不执行分页,返回全部结果
if (page.getPageSizeZero() == null) {
page.setPageSizeZero(pageSizeZero);
}
if (page.getKeepOrderBy() == null) {
page.setKeepOrderBy(keepOrderBy);
}
if (page.getKeepSubSelectOrderBy() == null) {
page.setKeepSubSelectOrderBy(keepSubSelectOrderBy);
}
return page;
| 991
| 466
| 1,457
|
<no_super_class>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/parser/SqlParserUtil.java
|
SqlParserUtil
|
parse
|
class SqlParserUtil {
private static final SqlParser SQL_PARSER;
static {
SqlParser temp = null;
ServiceLoader<SqlParser> loader = ServiceLoader.load(SqlParser.class);
for (SqlParser sqlParser : loader) {
temp = sqlParser;
break;
}
if (temp == null) {
temp = SqlParser.DEFAULT;
}
SQL_PARSER = temp;
}
public static Statement parse(String statementReader) {<FILL_FUNCTION_BODY>}
}
|
try {
return SQL_PARSER.parse(statementReader);
} catch (JSQLParserException | ParseException e) {
throw new RuntimeException(e);
}
| 141
| 48
| 189
|
<no_super_class>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/parser/defaults/DefaultOrderBySqlParser.java
|
DefaultOrderBySqlParser
|
converToOrderBySql
|
class DefaultOrderBySqlParser implements OrderBySqlParser {
private static final Log log = LogFactory.getLog(DefaultOrderBySqlParser.class);
/**
* convert to order by sql
*
* @param sql
* @param orderBy
* @return
*/
@Override
public String converToOrderBySql(String sql, String orderBy) {<FILL_FUNCTION_BODY>}
/**
* extra order by and set default orderby to null
*
* @param select
*/
public static List<OrderByElement> extraOrderBy(Select select) {
if (select != null) {
if (select instanceof PlainSelect || select instanceof SetOperationList) {
List<OrderByElement> orderByElements = select.getOrderByElements();
select.setOrderByElements(null);
return orderByElements;
} else if (select instanceof ParenthesedSelect) {
extraOrderBy(((ParenthesedSelect) select).getSelect());
}
}
return null;
}
}
|
//解析SQL
Statement stmt = null;
try {
stmt = SqlParserUtil.parse(sql);
Select select = (Select) stmt;
//处理body-去最外层order by
List<OrderByElement> orderByElements = extraOrderBy(select);
String defaultOrderBy = PlainSelect.orderByToString(orderByElements);
if (defaultOrderBy.indexOf('?') != -1) {
throw new PageException("The order by in the original SQL[" + sql + "] contains parameters, so it cannot be modified using the OrderBy plugin!");
}
//新的sql
sql = select.toString();
} catch (Throwable e) {
log.warn("Failed to handle sorting: " + e + ", downgraded to a direct splice of the order by parameter");
}
return sql + " order by " + orderBy;
| 263
| 221
| 484
|
<no_super_class>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/util/ClassUtil.java
|
ClassUtil
|
newInstance
|
class ClassUtil {
/**
* 支持配置和SPI,优先级:配置类 > SPI > 默认值
*
* @param classStr 配置串,可空
* @param spi SPI 接口
* @param properties 配置属性
* @param defaultSupplier 默认值
*/
@SuppressWarnings("unchecked")
public static <T> T newInstance(String classStr, Class<T> spi, Properties properties, Supplier<T> defaultSupplier) {
if (StringUtil.isNotEmpty(classStr)) {
try {
Class<?> cls = Class.forName(classStr);
return (T) newInstance(cls, properties);
} catch (Exception ignored) {
}
}
T result = null;
if (spi != null) {
ServiceLoader<T> loader = ServiceLoader.load(spi);
for (T t : loader) {
result = t;
break;
}
}
if (result == null) {
result = defaultSupplier.get();
}
if (result instanceof PageProperties) {
((PageProperties) result).setProperties(properties);
}
return result;
}
@SuppressWarnings("unchecked")
public static <T> T newInstance(String classStr, Properties properties) {
try {
Class<?> cls = Class.forName(classStr);
return (T) newInstance(cls, properties);
} catch (Exception e) {
throw new PageException(e);
}
}
public static <T> T newInstance(Class<T> cls, Properties properties) {<FILL_FUNCTION_BODY>}
public static Class<?> getServletRequestClass() throws ClassNotFoundException {
Class<?> requestClass = null;
try {
requestClass = Class.forName("javax.servlet.ServletRequest");
}catch (ClassNotFoundException exception){
}
if (requestClass != null){
return requestClass;
}
return Class.forName("jakarta.servlet.ServletRequest");
}
}
|
try {
T instance = cls.newInstance();
if (instance instanceof PageProperties) {
((PageProperties) instance).setProperties(properties);
}
return instance;
} catch (Exception e) {
throw new PageException(e);
}
| 549
| 70
| 619
|
<no_super_class>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/util/ExecutorUtil.java
|
ExecutorUtil
|
executeAutoCount
|
class ExecutorUtil {
private static Field additionalParametersField;
private static Field providerMethodArgumentNamesField;
static {
try {
additionalParametersField = BoundSql.class.getDeclaredField("additionalParameters");
additionalParametersField.setAccessible(true);
} catch (NoSuchFieldException e) {
throw new PageException("Failed to get the BoundSql property additionalParameters: " + e, e);
}
try {
//兼容低版本
providerMethodArgumentNamesField = ProviderSqlSource.class.getDeclaredField("providerMethodArgumentNames");
providerMethodArgumentNamesField.setAccessible(true);
} catch (NoSuchFieldException ignore) {
}
}
/**
* 获取 BoundSql 属性值 additionalParameters
*
* @param boundSql
* @return
*/
public static Map<String, Object> getAdditionalParameter(BoundSql boundSql) {
try {
return (Map<String, Object>) additionalParametersField.get(boundSql);
} catch (IllegalAccessException e) {
throw new PageException("Failed to get the BoundSql property additionalParameters: " + e, e);
}
}
/**
* 获取 ProviderSqlSource 属性值 providerMethodArgumentNames
*
* @param providerSqlSource
* @return
*/
public static String[] getProviderMethodArgumentNames(ProviderSqlSource providerSqlSource) {
try {
return providerMethodArgumentNamesField != null ? (String[]) providerMethodArgumentNamesField.get(providerSqlSource) : null;
} catch (IllegalAccessException e) {
throw new PageException("Get the ProviderSqlSource property value of providerMethodArgumentNames: " + e, e);
}
}
/**
* 尝试获取已经存在的在 MS,提供对手写count和page的支持
*
* @param configuration
* @param msId
* @return
*/
public static MappedStatement getExistedMappedStatement(Configuration configuration, String msId) {
MappedStatement mappedStatement = null;
try {
mappedStatement = configuration.getMappedStatement(msId, false);
} catch (Throwable t) {
//ignore
}
return mappedStatement;
}
/**
* 执行手动设置的 count 查询,该查询支持的参数必须和被分页的方法相同
*
* @param executor
* @param countMs
* @param parameter
* @param boundSql
* @param resultHandler
* @return
* @throws SQLException
*/
public static Long executeManualCount(Executor executor, MappedStatement countMs,
Object parameter, BoundSql boundSql,
ResultHandler resultHandler) throws SQLException {
CacheKey countKey = executor.createCacheKey(countMs, parameter, RowBounds.DEFAULT, boundSql);
BoundSql countBoundSql = countMs.getBoundSql(parameter);
Object countResultList = executor.query(countMs, parameter, RowBounds.DEFAULT, resultHandler, countKey, countBoundSql);
//某些数据(如 TDEngine)查询 count 无结果时返回 null
if (countResultList == null || ((List) countResultList).isEmpty()) {
return 0L;
}
return ((Number) ((List) countResultList).get(0)).longValue();
}
/**
* 执行自动生成的 count 查询
*
* @param dialect
* @param executor
* @param countMs
* @param parameter
* @param boundSql
* @param rowBounds
* @param resultHandler
* @return
* @throws SQLException
*/
public static Long executeAutoCount(Dialect dialect, Executor executor, MappedStatement countMs,
Object parameter, BoundSql boundSql,
RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {<FILL_FUNCTION_BODY>}
/**
* 分页查询
*
* @param dialect
* @param executor
* @param ms
* @param parameter
* @param rowBounds
* @param resultHandler
* @param boundSql
* @param cacheKey
* @param <E>
* @return
* @throws SQLException
*/
public static <E> List<E> pageQuery(Dialect dialect, Executor executor, MappedStatement ms, Object parameter,
RowBounds rowBounds, ResultHandler resultHandler,
BoundSql boundSql, CacheKey cacheKey) throws SQLException {
//判断是否需要进行分页查询
if (dialect.beforePage(ms, parameter, rowBounds)) {
//生成分页的缓存 key
CacheKey pageKey = cacheKey;
//处理参数对象
parameter = dialect.processParameterObject(ms, parameter, boundSql, pageKey);
//调用方言获取分页 sql
String pageSql = dialect.getPageSql(ms, boundSql, parameter, rowBounds, pageKey);
BoundSql pageBoundSql = new BoundSql(ms.getConfiguration(), pageSql, boundSql.getParameterMappings(), parameter);
Map<String, Object> additionalParameters = getAdditionalParameter(boundSql);
//设置动态参数
for (String key : additionalParameters.keySet()) {
pageBoundSql.setAdditionalParameter(key, additionalParameters.get(key));
}
//对 boundSql 的拦截处理
if (dialect instanceof BoundSqlInterceptor.Chain) {
pageBoundSql = ((BoundSqlInterceptor.Chain) dialect).doBoundSql(BoundSqlInterceptor.Type.PAGE_SQL, pageBoundSql, pageKey);
}
//执行分页查询
return executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, pageKey, pageBoundSql);
} else {
//不执行分页的情况下,也不执行内存分页
return executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, boundSql);
}
}
}
|
Map<String, Object> additionalParameters = getAdditionalParameter(boundSql);
//创建 count 查询的缓存 key
CacheKey countKey = executor.createCacheKey(countMs, parameter, RowBounds.DEFAULT, boundSql);
//调用方言获取 count sql
String countSql = dialect.getCountSql(countMs, boundSql, parameter, rowBounds, countKey);
//countKey.update(countSql);
BoundSql countBoundSql = new BoundSql(countMs.getConfiguration(), countSql, boundSql.getParameterMappings(), parameter);
//当使用动态 SQL 时,可能会产生临时的参数,这些参数需要手动设置到新的 BoundSql 中
for (String key : additionalParameters.keySet()) {
countBoundSql.setAdditionalParameter(key, additionalParameters.get(key));
}
//对 boundSql 的拦截处理
if (dialect instanceof BoundSqlInterceptor.Chain) {
countBoundSql = ((BoundSqlInterceptor.Chain) dialect).doBoundSql(BoundSqlInterceptor.Type.COUNT_SQL, countBoundSql, countKey);
}
//执行 count 查询
Object countResultList = executor.query(countMs, parameter, RowBounds.DEFAULT, resultHandler, countKey, countBoundSql);
//某些数据(如 TDEngine)查询 count 无结果时返回 null
if (countResultList == null || ((List) countResultList).isEmpty()) {
return 0L;
}
return ((Number) ((List) countResultList).get(0)).longValue();
| 1,511
| 392
| 1,903
|
<no_super_class>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/util/MSUtils.java
|
MSUtils
|
newCountMappedStatement
|
class MSUtils {
private static final List<ResultMapping> EMPTY_RESULTMAPPING = new ArrayList<ResultMapping>(0);
/**
* 新建count查询的MappedStatement
*
* @param ms
* @param newMsId
* @return
*/
public static MappedStatement newCountMappedStatement(MappedStatement ms, String newMsId) {<FILL_FUNCTION_BODY>}
}
|
MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), newMsId, ms.getSqlSource(), ms.getSqlCommandType());
builder.resource(ms.getResource());
builder.fetchSize(ms.getFetchSize());
builder.statementType(ms.getStatementType());
builder.keyGenerator(ms.getKeyGenerator());
if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) {
StringBuilder keyProperties = new StringBuilder();
for (String keyProperty : ms.getKeyProperties()) {
keyProperties.append(keyProperty).append(",");
}
keyProperties.delete(keyProperties.length() - 1, keyProperties.length());
builder.keyProperty(keyProperties.toString());
}
builder.timeout(ms.getTimeout());
builder.parameterMap(ms.getParameterMap());
//count查询返回值int
List<ResultMap> resultMaps = new ArrayList<ResultMap>();
ResultMap resultMap = new ResultMap.Builder(ms.getConfiguration(), ms.getId(), Long.class, EMPTY_RESULTMAPPING).build();
resultMaps.add(resultMap);
builder.resultMaps(resultMaps);
builder.resultSetType(ms.getResultSetType());
builder.cache(ms.getCache());
builder.flushCacheRequired(ms.isFlushCacheRequired());
builder.useCache(ms.isUseCache());
return builder.build();
| 114
| 372
| 486
|
<no_super_class>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/util/MetaObjectUtil.java
|
MetaObjectUtil
|
forObject
|
class MetaObjectUtil {
public static Method method;
static {
try {
// 高版本中的 MetaObject.forObject 有 4 个参数,低版本是 1 个
//先判断当前使用的是否为高版本
Class.forName("org.apache.ibatis.reflection.ReflectorFactory");
// 下面这个 MetaObjectWithReflectCache 带反射的缓存信息
Class<?> metaClass = Class.forName("com.github.pagehelper.util.MetaObjectWithReflectCache");
method = metaClass.getDeclaredMethod("forObject", Object.class);
} catch (Throwable e1) {
try {
Class<?> metaClass = Class.forName("org.apache.ibatis.reflection.SystemMetaObject");
method = metaClass.getDeclaredMethod("forObject", Object.class);
} catch (Exception e2) {
try {
Class<?> metaClass = Class.forName("org.apache.ibatis.reflection.MetaObject");
method = metaClass.getDeclaredMethod("forObject", Object.class);
} catch (Exception e3) {
throw new PageException(e3);
}
}
}
}
public static MetaObject forObject(Object object) {<FILL_FUNCTION_BODY>}
}
|
try {
return (MetaObject) method.invoke(null, object);
} catch (Exception e) {
throw new PageException(e);
}
| 342
| 43
| 385
|
<no_super_class>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/util/MetaObjectWithReflectCache.java
|
MetaObjectWithReflectCache
|
forObject
|
class MetaObjectWithReflectCache {
public static final ObjectFactory DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory();
public static final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY = new DefaultObjectWrapperFactory();
public static final ReflectorFactory DEFAULT_REFLECTOR_FACTORY = new DefaultReflectorFactory();
public static MetaObject forObject(Object object) {<FILL_FUNCTION_BODY>}
}
|
try {
return MetaObject.forObject(object, DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY, DEFAULT_REFLECTOR_FACTORY);
} catch (Exception e) {
throw new PageException(e);
}
| 114
| 72
| 186
|
<no_super_class>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/util/PageObjectUtil.java
|
PageObjectUtil
|
getPageFromObject
|
class PageObjectUtil {
//request获取方法
protected static Boolean hasRequest;
protected static Class<?> requestClass;
protected static Method getParameterMap;
protected static Map<String, String> PARAMS = new HashMap<String, String>(6, 1);
static {
try {
requestClass = ClassUtil.getServletRequestClass();
getParameterMap = requestClass.getMethod("getParameterMap", new Class[]{});
hasRequest = true;
} catch (Throwable e) {
hasRequest = false;
}
PARAMS.put("pageNum", "pageNum");
PARAMS.put("pageSize", "pageSize");
PARAMS.put("count", "countSql");
PARAMS.put("orderBy", "orderBy");
PARAMS.put("reasonable", "reasonable");
PARAMS.put("pageSizeZero", "pageSizeZero");
}
/**
* 对象中获取分页参数
*
* @param params
* @return
*/
public static <T> Page<T> getPageFromObject(Object params, boolean required) {<FILL_FUNCTION_BODY>}
/**
* 从对象中取参数
*
* @param paramsObject
* @param paramName
* @param required
* @return
*/
protected static Object getParamValue(MetaObject paramsObject, String paramName, boolean required) {
Object value = null;
if (paramsObject.hasGetter(PARAMS.get(paramName))) {
value = paramsObject.getValue(PARAMS.get(paramName));
}
if (value != null && value.getClass().isArray()) {
Object[] values = (Object[]) value;
if (values.length == 0) {
value = null;
} else {
value = values[0];
}
}
if (required && value == null) {
throw new PageException("Paginated queries are missing the necessary parameters:" + PARAMS.get(paramName));
}
return value;
}
public static void setParams(String params) {
if (StringUtil.isNotEmpty(params)) {
String[] ps = params.split("[;|,|&]");
for (String s : ps) {
String[] ss = s.split("[=|:]");
if (ss.length == 2) {
PARAMS.put(ss[0], ss[1]);
}
}
}
}
}
|
if (params == null) {
throw new PageException("unable to get paginated query parameters!");
}
if(params instanceof IPage){
IPage pageParams = (IPage) params;
Page page = null;
if(pageParams.getPageNum() != null && pageParams.getPageSize() != null){
page = new Page(pageParams.getPageNum(), pageParams.getPageSize());
}
if (StringUtil.isNotEmpty(pageParams.getOrderBy())) {
if(page != null){
page.setOrderBy(pageParams.getOrderBy());
} else {
page = new Page();
page.setOrderBy(pageParams.getOrderBy());
page.setOrderByOnly(true);
}
}
return page;
}
int pageNum;
int pageSize;
MetaObject paramsObject = null;
if (hasRequest && requestClass.isAssignableFrom(params.getClass())) {
try {
paramsObject = MetaObjectUtil.forObject(getParameterMap.invoke(params, new Object[]{}));
} catch (Exception e) {
//忽略
}
} else {
paramsObject = MetaObjectUtil.forObject(params);
}
if (paramsObject == null) {
throw new PageException("The pagination query parameter failed to be processed!");
}
Object orderBy = getParamValue(paramsObject, "orderBy", false);
boolean hasOrderBy = false;
if (orderBy != null && orderBy.toString().length() > 0) {
hasOrderBy = true;
}
try {
Object _pageNum = getParamValue(paramsObject, "pageNum", required);
Object _pageSize = getParamValue(paramsObject, "pageSize", required);
if (_pageNum == null || _pageSize == null) {
if(hasOrderBy){
Page page = new Page();
page.setOrderBy(orderBy.toString());
page.setOrderByOnly(true);
return page;
}
return null;
}
pageNum = Integer.parseInt(String.valueOf(_pageNum));
pageSize = Integer.parseInt(String.valueOf(_pageSize));
} catch (NumberFormatException e) {
throw new PageException("pagination parameters are not a valid number type!", e);
}
Page page = new Page(pageNum, pageSize);
//count查询
Object _count = getParamValue(paramsObject, "count", false);
if (_count != null) {
page.setCount(Boolean.valueOf(String.valueOf(_count)));
}
//排序
if (hasOrderBy) {
page.setOrderBy(orderBy.toString());
}
//分页合理化
Object reasonable = getParamValue(paramsObject, "reasonable", false);
if (reasonable != null) {
page.setReasonable(Boolean.valueOf(String.valueOf(reasonable)));
}
//查询全部
Object pageSizeZero = getParamValue(paramsObject, "pageSizeZero", false);
if (pageSizeZero != null) {
page.setPageSizeZero(Boolean.valueOf(String.valueOf(pageSizeZero)));
}
return page;
| 637
| 827
| 1,464
|
<no_super_class>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/util/SqlSafeUtil.java
|
SqlSafeUtil
|
check
|
class SqlSafeUtil {
/**
* SQL语法检查正则:符合两个关键字(有先后顺序)才算匹配
* <p>
* 参考: mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/toolkit/sql/SqlInjectionUtils.java
*/
private static final Pattern SQL_SYNTAX_PATTERN = Pattern.compile("(insert|delete|update|select|create|drop|truncate|grant|alter|deny|revoke|call|execute|exec|declare|show|rename|set)" +
"\\s+.*(into|from|set|where|table|database|view|index|on|cursor|procedure|trigger|for|password|union|and|or)|(select\\s*\\*\\s*from\\s+)", Pattern.CASE_INSENSITIVE);
/**
* 使用'、;或注释截断SQL检查正则
* <p>
* 参考: mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/toolkit/sql/SqlInjectionUtils.java
*/
private static final Pattern SQL_COMMENT_PATTERN = Pattern.compile("'.*(or|union|--|#|/*|;)", Pattern.CASE_INSENSITIVE);
/**
* 检查参数是否存在 SQL 注入
*
* @param value 检查参数
* @return true 非法 false 合法
*/
public static boolean check(String value) {<FILL_FUNCTION_BODY>}
}
|
if (value == null) {
return false;
}
// 不允许使用任何函数(不能出现括号),否则无法检测后面这个注入 order by id,if(1=2,1,(sleep(100)));
return value.contains("(") || SQL_COMMENT_PATTERN.matcher(value).find() || SQL_SYNTAX_PATTERN.matcher(value).find();
| 414
| 110
| 524
|
<no_super_class>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/util/StackTraceUtil.java
|
StackTraceUtil
|
current
|
class StackTraceUtil {
/**
* 当前方法堆栈信息
*/
public static String current() {<FILL_FUNCTION_BODY>}
}
|
Exception exception = new Exception("Stack information when setting pagination parameters");
StringWriter writer = new StringWriter();
exception.printStackTrace(new PrintWriter(writer));
return writer.toString();
| 46
| 50
| 96
|
<no_super_class>
|
pagehelper_Mybatis-PageHelper
|
Mybatis-PageHelper/src/main/java/com/github/pagehelper/util/StringUtil.java
|
StringUtil
|
isEmpty
|
class StringUtil {
public static boolean isEmpty(String str) {<FILL_FUNCTION_BODY>}
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
}
|
if (str == null || str.length() == 0) {
return true;
}
return false;
| 57
| 32
| 89
|
<no_super_class>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-client/src/main/java/com/netty/rpc/client/RpcClient.java
|
RpcClient
|
setApplicationContext
|
class RpcClient implements ApplicationContextAware, DisposableBean {
private static final Logger logger = LoggerFactory.getLogger(RpcClient.class);
private ServiceDiscovery serviceDiscovery;
private static ThreadPoolExecutor threadPoolExecutor = ThreadPoolUtil.createThreadPool(RpcClient.class.getSimpleName(), 8, 16);
public RpcClient(String address) {
this.serviceDiscovery = new ServiceDiscovery(address);
}
@SuppressWarnings("unchecked")
public static <T, P> T createService(Class<T> interfaceClass, String version) {
return (T) Proxy.newProxyInstance(
interfaceClass.getClassLoader(),
new Class<?>[]{interfaceClass},
new ObjectProxy<T, P>(interfaceClass, version)
);
}
public static <T, P> RpcService createAsyncService(Class<T> interfaceClass, String version) {
return new ObjectProxy<T, P>(interfaceClass, version);
}
public static void submit(Runnable task) {
threadPoolExecutor.submit(task);
}
public void stop() {
threadPoolExecutor.shutdown();
serviceDiscovery.stop();
ConnectionManager.getInstance().stop();
}
@Override
public void destroy() throws Exception {
this.stop();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {<FILL_FUNCTION_BODY>}
}
|
String[] beanNames = applicationContext.getBeanDefinitionNames();
for (String beanName : beanNames) {
Object bean = applicationContext.getBean(beanName);
Field[] fields = bean.getClass().getDeclaredFields();
try {
for (Field field : fields) {
RpcAutowired rpcAutowired = field.getAnnotation(RpcAutowired.class);
if (rpcAutowired != null) {
String version = rpcAutowired.version();
field.setAccessible(true);
field.set(bean, createService(field.getType(), version));
}
}
} catch (IllegalAccessException e) {
logger.error(e.toString());
}
}
| 380
| 189
| 569
|
<no_super_class>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-client/src/main/java/com/netty/rpc/client/connect/ConnectionManager.java
|
SingletonHolder
|
run
|
class SingletonHolder {
private static final ConnectionManager instance = new ConnectionManager();
}
public static ConnectionManager getInstance() {
return SingletonHolder.instance;
}
public void updateConnectedServer(List<RpcProtocol> serviceList) {
// Now using 2 collections to manage the service info and TCP connections because making the connection is async
// Once service info is updated on ZK, will trigger this function
// Actually client should only care about the service it is using
if (serviceList != null && serviceList.size() > 0) {
// Update local server nodes cache
HashSet<RpcProtocol> serviceSet = new HashSet<>(serviceList.size());
for (int i = 0; i < serviceList.size(); ++i) {
RpcProtocol rpcProtocol = serviceList.get(i);
serviceSet.add(rpcProtocol);
}
// Add new server info
for (final RpcProtocol rpcProtocol : serviceSet) {
if (!rpcProtocolSet.contains(rpcProtocol)) {
connectServerNode(rpcProtocol);
}
}
// Close and remove invalid server nodes
for (RpcProtocol rpcProtocol : rpcProtocolSet) {
if (!serviceSet.contains(rpcProtocol)) {
logger.info("Remove invalid service: " + rpcProtocol.toJson());
removeAndCloseHandler(rpcProtocol);
}
}
} else {
// No available service
logger.error("No available service!");
for (RpcProtocol rpcProtocol : rpcProtocolSet) {
removeAndCloseHandler(rpcProtocol);
}
}
}
public void updateConnectedServer(RpcProtocol rpcProtocol, PathChildrenCacheEvent.Type type) {
if (rpcProtocol == null) {
return;
}
if (type == PathChildrenCacheEvent.Type.CHILD_ADDED && !rpcProtocolSet.contains(rpcProtocol)) {
connectServerNode(rpcProtocol);
} else if (type == PathChildrenCacheEvent.Type.CHILD_UPDATED) {
//TODO We may don't need to reconnect remote server if the server'IP and server'port are not changed
removeAndCloseHandler(rpcProtocol);
connectServerNode(rpcProtocol);
} else if (type == PathChildrenCacheEvent.Type.CHILD_REMOVED) {
removeAndCloseHandler(rpcProtocol);
} else {
throw new IllegalArgumentException("Unknow type:" + type);
}
}
private void connectServerNode(RpcProtocol rpcProtocol) {
if (rpcProtocol.getServiceInfoList() == null || rpcProtocol.getServiceInfoList().isEmpty()) {
logger.info("No service on node, host: {}, port: {}", rpcProtocol.getHost(), rpcProtocol.getPort());
return;
}
rpcProtocolSet.add(rpcProtocol);
logger.info("New service node, host: {}, port: {}", rpcProtocol.getHost(), rpcProtocol.getPort());
for (RpcServiceInfo serviceProtocol : rpcProtocol.getServiceInfoList()) {
logger.info("New service info, name: {}, version: {}", serviceProtocol.getServiceName(), serviceProtocol.getVersion());
}
final InetSocketAddress remotePeer = new InetSocketAddress(rpcProtocol.getHost(), rpcProtocol.getPort());
threadPoolExecutor.submit(new Runnable() {
@Override
public void run() {<FILL_FUNCTION_BODY>
|
Bootstrap b = new Bootstrap();
b.group(eventLoopGroup)
.channel(NioSocketChannel.class)
.handler(new RpcClientInitializer());
ChannelFuture channelFuture = b.connect(remotePeer);
channelFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(final ChannelFuture channelFuture) throws Exception {
if (channelFuture.isSuccess()) {
logger.info("Successfully connect to remote server, remote peer = " + remotePeer);
RpcClientHandler handler = channelFuture.channel().pipeline().get(RpcClientHandler.class);
connectedServerNodes.put(rpcProtocol, handler);
handler.setRpcProtocol(rpcProtocol);
signalAvailableHandler();
} else {
logger.error("Can not connect to remote server, remote peer = " + remotePeer);
}
}
});
| 876
| 224
| 1,100
|
<no_super_class>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-client/src/main/java/com/netty/rpc/client/discovery/ServiceDiscovery.java
|
ServiceDiscovery
|
getServiceAndUpdateServer
|
class ServiceDiscovery {
private static final Logger logger = LoggerFactory.getLogger(ServiceDiscovery.class);
private CuratorClient curatorClient;
public ServiceDiscovery(String registryAddress) {
this.curatorClient = new CuratorClient(registryAddress);
discoveryService();
}
private void discoveryService() {
try {
// Get initial service info
logger.info("Get initial service info");
getServiceAndUpdateServer();
// Add watch listener
curatorClient.watchPathChildrenNode(Constant.ZK_REGISTRY_PATH, new PathChildrenCacheListener() {
@Override
public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
PathChildrenCacheEvent.Type type = pathChildrenCacheEvent.getType();
ChildData childData = pathChildrenCacheEvent.getData();
switch (type) {
case CONNECTION_RECONNECTED:
logger.info("Reconnected to zk, try to get latest service list");
getServiceAndUpdateServer();
break;
case CHILD_ADDED:
getServiceAndUpdateServer(childData, PathChildrenCacheEvent.Type.CHILD_ADDED);
break;
case CHILD_UPDATED:
getServiceAndUpdateServer(childData, PathChildrenCacheEvent.Type.CHILD_UPDATED);
break;
case CHILD_REMOVED:
getServiceAndUpdateServer(childData, PathChildrenCacheEvent.Type.CHILD_REMOVED);
break;
}
}
});
} catch (Exception ex) {
logger.error("Watch node exception: " + ex.getMessage());
}
}
private void getServiceAndUpdateServer() {
try {
List<String> nodeList = curatorClient.getChildren(Constant.ZK_REGISTRY_PATH);
List<RpcProtocol> dataList = new ArrayList<>();
for (String node : nodeList) {
logger.debug("Service node: " + node);
byte[] bytes = curatorClient.getData(Constant.ZK_REGISTRY_PATH + "/" + node);
String json = new String(bytes);
RpcProtocol rpcProtocol = RpcProtocol.fromJson(json);
dataList.add(rpcProtocol);
}
logger.debug("Service node data: {}", dataList);
//Update the service info based on the latest data
UpdateConnectedServer(dataList);
} catch (Exception e) {
logger.error("Get node exception: " + e.getMessage());
}
}
private void getServiceAndUpdateServer(ChildData childData, PathChildrenCacheEvent.Type type) {<FILL_FUNCTION_BODY>}
private void UpdateConnectedServer(List<RpcProtocol> dataList) {
ConnectionManager.getInstance().updateConnectedServer(dataList);
}
private void updateConnectedServer(RpcProtocol rpcProtocol, PathChildrenCacheEvent.Type type) {
ConnectionManager.getInstance().updateConnectedServer(rpcProtocol, type);
}
public void stop() {
this.curatorClient.close();
}
}
|
String path = childData.getPath();
String data = new String(childData.getData(), StandardCharsets.UTF_8);
logger.info("Child data updated, path:{},type:{},data:{},", path, type, data);
RpcProtocol rpcProtocol = RpcProtocol.fromJson(data);
updateConnectedServer(rpcProtocol, type);
| 791
| 96
| 887
|
<no_super_class>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-client/src/main/java/com/netty/rpc/client/handler/RpcClientHandler.java
|
RpcClientHandler
|
channelRead0
|
class RpcClientHandler extends SimpleChannelInboundHandler<RpcResponse> {
private static final Logger logger = LoggerFactory.getLogger(RpcClientHandler.class);
private ConcurrentHashMap<String, RpcFuture> pendingRPC = new ConcurrentHashMap<>();
private volatile Channel channel;
private SocketAddress remotePeer;
private RpcProtocol rpcProtocol;
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
super.channelActive(ctx);
this.remotePeer = this.channel.remoteAddress();
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
super.channelRegistered(ctx);
this.channel = ctx.channel();
}
@Override
public void channelRead0(ChannelHandlerContext ctx, RpcResponse response) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
logger.error("Client caught exception: " + cause.getMessage());
ctx.close();
}
public void close() {
channel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
}
public RpcFuture sendRequest(RpcRequest request) {
RpcFuture rpcFuture = new RpcFuture(request);
pendingRPC.put(request.getRequestId(), rpcFuture);
try {
ChannelFuture channelFuture = channel.writeAndFlush(request).sync();
if (!channelFuture.isSuccess()) {
logger.error("Send request {} error", request.getRequestId());
}
} catch (InterruptedException e) {
logger.error("Send request exception: " + e.getMessage());
}
return rpcFuture;
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
//Send ping
sendRequest(Beat.BEAT_PING);
logger.debug("Client send beat-ping to " + remotePeer);
} else {
super.userEventTriggered(ctx, evt);
}
}
public void setRpcProtocol(RpcProtocol rpcProtocol) {
this.rpcProtocol = rpcProtocol;
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx);
ConnectionManager.getInstance().removeHandler(rpcProtocol);
}
}
|
String requestId = response.getRequestId();
logger.debug("Receive response: " + requestId);
RpcFuture rpcFuture = pendingRPC.get(requestId);
if (rpcFuture != null) {
pendingRPC.remove(requestId);
rpcFuture.done(response);
} else {
logger.warn("Can not get pending response for request id: " + requestId);
}
| 644
| 107
| 751
|
<no_super_class>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-client/src/main/java/com/netty/rpc/client/handler/RpcClientInitializer.java
|
RpcClientInitializer
|
initChannel
|
class RpcClientInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {<FILL_FUNCTION_BODY>}
}
|
// Serializer serializer = ProtostuffSerializer.class.newInstance();
// Serializer serializer = HessianSerializer.class.newInstance();
Serializer serializer = KryoSerializer.class.newInstance();
ChannelPipeline cp = socketChannel.pipeline();
cp.addLast(new IdleStateHandler(0, 0, Beat.BEAT_INTERVAL, TimeUnit.SECONDS));
cp.addLast(new RpcEncoder(RpcRequest.class, serializer));
cp.addLast(new LengthFieldBasedFrameDecoder(65536, 0, 4, 0, 0));
cp.addLast(new RpcDecoder(RpcResponse.class, serializer));
cp.addLast(new RpcClientHandler());
| 49
| 194
| 243
|
<no_super_class>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-client/src/main/java/com/netty/rpc/client/handler/RpcFuture.java
|
Sync
|
tryRelease
|
class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 1L;
//future status
private final int done = 1;
private final int pending = 0;
@Override
protected boolean tryAcquire(int arg) {
return getState() == done;
}
@Override
protected boolean tryRelease(int arg) {<FILL_FUNCTION_BODY>}
protected boolean isDone() {
return getState() == done;
}
}
|
if (getState() == pending) {
if (compareAndSetState(pending, done)) {
return true;
} else {
return false;
}
} else {
return true;
}
| 130
| 59
| 189
|
<no_super_class>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-client/src/main/java/com/netty/rpc/client/proxy/ObjectProxy.java
|
ObjectProxy
|
call
|
class ObjectProxy<T, P> implements InvocationHandler, RpcService<T, P, SerializableFunction<T>> {
private static final Logger logger = LoggerFactory.getLogger(ObjectProxy.class);
private Class<T> clazz;
private String version;
public ObjectProxy(Class<T> clazz, String version) {
this.clazz = clazz;
this.version = version;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (Object.class == method.getDeclaringClass()) {
String name = method.getName();
if ("equals".equals(name)) {
return proxy == args[0];
} else if ("hashCode".equals(name)) {
return System.identityHashCode(proxy);
} else if ("toString".equals(name)) {
return proxy.getClass().getName() + "@" +
Integer.toHexString(System.identityHashCode(proxy)) +
", with InvocationHandler " + this;
} else {
throw new IllegalStateException(String.valueOf(method));
}
}
RpcRequest request = new RpcRequest();
request.setRequestId(UUID.randomUUID().toString());
request.setClassName(method.getDeclaringClass().getName());
request.setMethodName(method.getName());
request.setParameterTypes(method.getParameterTypes());
request.setParameters(args);
request.setVersion(version);
// Debug
if (logger.isDebugEnabled()) {
logger.debug(method.getDeclaringClass().getName());
logger.debug(method.getName());
for (int i = 0; i < method.getParameterTypes().length; ++i) {
logger.debug(method.getParameterTypes()[i].getName());
}
for (int i = 0; i < args.length; ++i) {
logger.debug(args[i].toString());
}
}
String serviceKey = ServiceUtil.makeServiceKey(method.getDeclaringClass().getName(), version);
RpcClientHandler handler = ConnectionManager.getInstance().chooseHandler(serviceKey);
RpcFuture rpcFuture = handler.sendRequest(request);
return rpcFuture.get();
}
@Override
public RpcFuture call(String funcName, Object... args) throws Exception {
String serviceKey = ServiceUtil.makeServiceKey(this.clazz.getName(), version);
RpcClientHandler handler = ConnectionManager.getInstance().chooseHandler(serviceKey);
RpcRequest request = createRequest(this.clazz.getName(), funcName, args);
RpcFuture rpcFuture = handler.sendRequest(request);
return rpcFuture;
}
@Override
public RpcFuture call(SerializableFunction<T> tSerializableFunction, Object... args) throws Exception {<FILL_FUNCTION_BODY>}
private RpcRequest createRequest(String className, String methodName, Object[] args) {
RpcRequest request = new RpcRequest();
request.setRequestId(UUID.randomUUID().toString());
request.setClassName(className);
request.setMethodName(methodName);
request.setParameters(args);
request.setVersion(version);
Class[] parameterTypes = new Class[args.length];
// Get the right class type
for (int i = 0; i < args.length; i++) {
parameterTypes[i] = getClassType(args[i]);
}
request.setParameterTypes(parameterTypes);
// Debug
if (logger.isDebugEnabled()) {
logger.debug(className);
logger.debug(methodName);
for (int i = 0; i < parameterTypes.length; ++i) {
logger.debug(parameterTypes[i].getName());
}
for (int i = 0; i < args.length; ++i) {
logger.debug(args[i].toString());
}
}
return request;
}
private Class<?> getClassType(Object obj) {
Class<?> classType = obj.getClass();
// String typeName = classType.getName();
// switch (typeName) {
// case "java.lang.Integer":
// return Integer.TYPE;
// case "java.lang.Long":
// return Long.TYPE;
// case "java.lang.Float":
// return Float.TYPE;
// case "java.lang.Double":
// return Double.TYPE;
// case "java.lang.Character":
// return Character.TYPE;
// case "java.lang.Boolean":
// return Boolean.TYPE;
// case "java.lang.Short":
// return Short.TYPE;
// case "java.lang.Byte":
// return Byte.TYPE;
// }
return classType;
}
}
|
String serviceKey = ServiceUtil.makeServiceKey(this.clazz.getName(), version);
RpcClientHandler handler = ConnectionManager.getInstance().chooseHandler(serviceKey);
RpcRequest request = createRequest(this.clazz.getName(), tSerializableFunction.getName(), args);
RpcFuture rpcFuture = handler.sendRequest(request);
return rpcFuture;
| 1,215
| 93
| 1,308
|
<no_super_class>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-client/src/main/java/com/netty/rpc/client/route/RpcLoadBalance.java
|
RpcLoadBalance
|
getServiceMap
|
class RpcLoadBalance {
// Service map: group by service name
protected Map<String, List<RpcProtocol>> getServiceMap(Map<RpcProtocol, RpcClientHandler> connectedServerNodes) {<FILL_FUNCTION_BODY>}
// Route the connection for service key
public abstract RpcProtocol route(String serviceKey, Map<RpcProtocol, RpcClientHandler> connectedServerNodes) throws Exception;
}
|
Map<String, List<RpcProtocol>> serviceMap = new HashedMap<>();
if (connectedServerNodes != null && connectedServerNodes.size() > 0) {
for (RpcProtocol rpcProtocol : connectedServerNodes.keySet()) {
for (RpcServiceInfo serviceInfo : rpcProtocol.getServiceInfoList()) {
String serviceKey = ServiceUtil.makeServiceKey(serviceInfo.getServiceName(), serviceInfo.getVersion());
List<RpcProtocol> rpcProtocolList = serviceMap.get(serviceKey);
if (rpcProtocolList == null) {
rpcProtocolList = new ArrayList<>();
}
rpcProtocolList.add(rpcProtocol);
serviceMap.putIfAbsent(serviceKey, rpcProtocolList);
}
}
}
return serviceMap;
| 106
| 204
| 310
|
<no_super_class>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-client/src/main/java/com/netty/rpc/client/route/impl/RpcLoadBalanceConsistentHash.java
|
RpcLoadBalanceConsistentHash
|
route
|
class RpcLoadBalanceConsistentHash extends RpcLoadBalance {
public RpcProtocol doRoute(String serviceKey, List<RpcProtocol> addressList) {
int index = Hashing.consistentHash(serviceKey.hashCode(), addressList.size());
return addressList.get(index);
}
@Override
public RpcProtocol route(String serviceKey, Map<RpcProtocol, RpcClientHandler> connectedServerNodes) throws Exception {<FILL_FUNCTION_BODY>}
}
|
Map<String, List<RpcProtocol>> serviceMap = getServiceMap(connectedServerNodes);
List<RpcProtocol> addressList = serviceMap.get(serviceKey);
if (addressList != null && addressList.size() > 0) {
return doRoute(serviceKey, addressList);
} else {
throw new Exception("Can not find connection for service: " + serviceKey);
}
| 125
| 102
| 227
|
<methods>public non-sealed void <init>() ,public abstract com.netty.rpc.protocol.RpcProtocol route(java.lang.String, Map<com.netty.rpc.protocol.RpcProtocol,com.netty.rpc.client.handler.RpcClientHandler>) throws java.lang.Exception<variables>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-client/src/main/java/com/netty/rpc/client/route/impl/RpcLoadBalanceLFU.java
|
RpcLoadBalanceLFU
|
doRoute
|
class RpcLoadBalanceLFU extends RpcLoadBalance {
private ConcurrentMap<String, HashMap<RpcProtocol, Integer>> jobLfuMap = new ConcurrentHashMap<String, HashMap<RpcProtocol, Integer>>();
private long CACHE_VALID_TIME = 0;
public RpcProtocol doRoute(String serviceKey, List<RpcProtocol> addressList) {<FILL_FUNCTION_BODY>}
@Override
public RpcProtocol route(String serviceKey, Map<RpcProtocol, RpcClientHandler> connectedServerNodes) throws Exception {
Map<String, List<RpcProtocol>> serviceMap = getServiceMap(connectedServerNodes);
List<RpcProtocol> addressList = serviceMap.get(serviceKey);
if (addressList != null && addressList.size() > 0) {
return doRoute(serviceKey, addressList);
} else {
throw new Exception("Can not find connection for service: " + serviceKey);
}
}
}
|
// cache clear
if (System.currentTimeMillis() > CACHE_VALID_TIME) {
jobLfuMap.clear();
CACHE_VALID_TIME = System.currentTimeMillis() + 1000 * 60 * 60 * 24;
}
// lfu item init
HashMap<RpcProtocol, Integer> lfuItemMap = jobLfuMap.get(serviceKey);
if (lfuItemMap == null) {
lfuItemMap = new HashMap<RpcProtocol, Integer>();
jobLfuMap.putIfAbsent(serviceKey, lfuItemMap); // 避免重复覆盖
}
// put new
for (RpcProtocol address : addressList) {
if (!lfuItemMap.containsKey(address) || lfuItemMap.get(address) > 1000000) {
lfuItemMap.put(address, 0);
}
}
// remove old
List<RpcProtocol> delKeys = new ArrayList<>();
for (RpcProtocol existKey : lfuItemMap.keySet()) {
if (!addressList.contains(existKey)) {
delKeys.add(existKey);
}
}
if (delKeys.size() > 0) {
for (RpcProtocol delKey : delKeys) {
lfuItemMap.remove(delKey);
}
}
// load least used count address
List<Map.Entry<RpcProtocol, Integer>> lfuItemList = new ArrayList<Map.Entry<RpcProtocol, Integer>>(lfuItemMap.entrySet());
Collections.sort(lfuItemList, new Comparator<Map.Entry<RpcProtocol, Integer>>() {
@Override
public int compare(Map.Entry<RpcProtocol, Integer> o1, Map.Entry<RpcProtocol, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
Map.Entry<RpcProtocol, Integer> addressItem = lfuItemList.get(0);
RpcProtocol minAddress = addressItem.getKey();
addressItem.setValue(addressItem.getValue() + 1);
return minAddress;
| 248
| 574
| 822
|
<methods>public non-sealed void <init>() ,public abstract com.netty.rpc.protocol.RpcProtocol route(java.lang.String, Map<com.netty.rpc.protocol.RpcProtocol,com.netty.rpc.client.handler.RpcClientHandler>) throws java.lang.Exception<variables>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-client/src/main/java/com/netty/rpc/client/route/impl/RpcLoadBalanceLRU.java
|
RpcLoadBalanceLRU
|
removeEldestEntry
|
class RpcLoadBalanceLRU extends RpcLoadBalance {
private ConcurrentMap<String, LinkedHashMap<RpcProtocol, RpcProtocol>> jobLRUMap =
new ConcurrentHashMap<String, LinkedHashMap<RpcProtocol, RpcProtocol>>();
private long CACHE_VALID_TIME = 0;
public RpcProtocol doRoute(String serviceKey, List<RpcProtocol> addressList) {
// cache clear
if (System.currentTimeMillis() > CACHE_VALID_TIME) {
jobLRUMap.clear();
CACHE_VALID_TIME = System.currentTimeMillis() + 1000 * 60 * 60 * 24;
}
// init lru
LinkedHashMap<RpcProtocol, RpcProtocol> lruHashMap = jobLRUMap.get(serviceKey);
if (lruHashMap == null) {
/**
* LinkedHashMap
* a、accessOrder:ture=访问顺序排序(get/put时排序)/ACCESS-LAST;false=插入顺序排期/FIFO;
* b、removeEldestEntry:新增元素时将会调用,返回true时会删除最老元素;
* 可封装LinkedHashMap并重写该方法,比如定义最大容量,超出是返回true即可实现固定长度的LRU算法;
*/
lruHashMap = new LinkedHashMap<RpcProtocol, RpcProtocol>(16, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<RpcProtocol, RpcProtocol> eldest) {<FILL_FUNCTION_BODY>}
};
jobLRUMap.putIfAbsent(serviceKey, lruHashMap);
}
// put new
for (RpcProtocol address : addressList) {
if (!lruHashMap.containsKey(address)) {
lruHashMap.put(address, address);
}
}
// remove old
List<RpcProtocol> delKeys = new ArrayList<>();
for (RpcProtocol existKey : lruHashMap.keySet()) {
if (!addressList.contains(existKey)) {
delKeys.add(existKey);
}
}
if (delKeys.size() > 0) {
for (RpcProtocol delKey : delKeys) {
lruHashMap.remove(delKey);
}
}
// load
RpcProtocol eldestKey = lruHashMap.entrySet().iterator().next().getKey();
RpcProtocol eldestValue = lruHashMap.get(eldestKey);
return eldestValue;
}
@Override
public RpcProtocol route(String serviceKey, Map<RpcProtocol, RpcClientHandler> connectedServerNodes) throws Exception {
Map<String, List<RpcProtocol>> serviceMap = getServiceMap(connectedServerNodes);
List<RpcProtocol> addressList = serviceMap.get(serviceKey);
if (addressList != null && addressList.size() > 0) {
return doRoute(serviceKey, addressList);
} else {
throw new Exception("Can not find connection for service: " + serviceKey);
}
}
}
|
if (super.size() > 1000) {
return true;
} else {
return false;
}
| 820
| 36
| 856
|
<methods>public non-sealed void <init>() ,public abstract com.netty.rpc.protocol.RpcProtocol route(java.lang.String, Map<com.netty.rpc.protocol.RpcProtocol,com.netty.rpc.client.handler.RpcClientHandler>) throws java.lang.Exception<variables>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-client/src/main/java/com/netty/rpc/client/route/impl/RpcLoadBalanceRandom.java
|
RpcLoadBalanceRandom
|
route
|
class RpcLoadBalanceRandom extends RpcLoadBalance {
private Random random = new Random();
public RpcProtocol doRoute(List<RpcProtocol> addressList) {
int size = addressList.size();
// Random
return addressList.get(random.nextInt(size));
}
@Override
public RpcProtocol route(String serviceKey, Map<RpcProtocol, RpcClientHandler> connectedServerNodes) throws Exception {<FILL_FUNCTION_BODY>}
}
|
Map<String, List<RpcProtocol>> serviceMap = getServiceMap(connectedServerNodes);
List<RpcProtocol> addressList = serviceMap.get(serviceKey);
if (addressList != null && addressList.size() > 0) {
return doRoute(addressList);
} else {
throw new Exception("Can not find connection for service: " + serviceKey);
}
| 125
| 99
| 224
|
<methods>public non-sealed void <init>() ,public abstract com.netty.rpc.protocol.RpcProtocol route(java.lang.String, Map<com.netty.rpc.protocol.RpcProtocol,com.netty.rpc.client.handler.RpcClientHandler>) throws java.lang.Exception<variables>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-client/src/main/java/com/netty/rpc/client/route/impl/RpcLoadBalanceRoundRobin.java
|
RpcLoadBalanceRoundRobin
|
route
|
class RpcLoadBalanceRoundRobin extends RpcLoadBalance {
private AtomicInteger roundRobin = new AtomicInteger(0);
public RpcProtocol doRoute(List<RpcProtocol> addressList) {
int size = addressList.size();
// Round robin
int index = (roundRobin.getAndAdd(1) + size) % size;
return addressList.get(index);
}
@Override
public RpcProtocol route(String serviceKey, Map<RpcProtocol, RpcClientHandler> connectedServerNodes) throws Exception {<FILL_FUNCTION_BODY>}
}
|
Map<String, List<RpcProtocol>> serviceMap = getServiceMap(connectedServerNodes);
List<RpcProtocol> addressList = serviceMap.get(serviceKey);
if (addressList != null && addressList.size() > 0) {
return doRoute(addressList);
} else {
throw new Exception("Can not find connection for service: " + serviceKey);
}
| 155
| 99
| 254
|
<methods>public non-sealed void <init>() ,public abstract com.netty.rpc.protocol.RpcProtocol route(java.lang.String, Map<com.netty.rpc.protocol.RpcProtocol,com.netty.rpc.client.handler.RpcClientHandler>) throws java.lang.Exception<variables>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-common/src/main/java/com/netty/rpc/codec/RpcDecoder.java
|
RpcDecoder
|
decode
|
class RpcDecoder extends ByteToMessageDecoder {
private static final Logger logger = LoggerFactory.getLogger(RpcDecoder.class);
private Class<?> genericClass;
private Serializer serializer;
public RpcDecoder(Class<?> genericClass, Serializer serializer) {
this.genericClass = genericClass;
this.serializer = serializer;
}
@Override
public final void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {<FILL_FUNCTION_BODY>}
}
|
if (in.readableBytes() < 4) {
return;
}
in.markReaderIndex();
int dataLength = in.readInt();
if (in.readableBytes() < dataLength) {
in.resetReaderIndex();
return;
}
byte[] data = new byte[dataLength];
in.readBytes(data);
Object obj = null;
try {
obj = serializer.deserialize(data, genericClass);
out.add(obj);
} catch (Exception ex) {
logger.error("Decode error: " + ex.toString());
}
| 145
| 157
| 302
|
<no_super_class>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-common/src/main/java/com/netty/rpc/codec/RpcEncoder.java
|
RpcEncoder
|
encode
|
class RpcEncoder extends MessageToByteEncoder {
private static final Logger logger = LoggerFactory.getLogger(RpcEncoder.class);
private Class<?> genericClass;
private Serializer serializer;
public RpcEncoder(Class<?> genericClass, Serializer serializer) {
this.genericClass = genericClass;
this.serializer = serializer;
}
@Override
public void encode(ChannelHandlerContext ctx, Object in, ByteBuf out) throws Exception {<FILL_FUNCTION_BODY>}
}
|
if (genericClass.isInstance(in)) {
try {
byte[] data = serializer.serialize(in);
out.writeInt(data.length);
out.writeBytes(data);
} catch (Exception ex) {
logger.error("Encode error: " + ex.toString());
}
}
| 139
| 85
| 224
|
<no_super_class>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-common/src/main/java/com/netty/rpc/protocol/RpcProtocol.java
|
RpcProtocol
|
isListEquals
|
class RpcProtocol implements Serializable {
private static final long serialVersionUID = -1102180003395190700L;
// service host
private String host;
// service port
private int port;
// service info list
private List<RpcServiceInfo> serviceInfoList;
public String toJson() {
String json = JsonUtil.objectToJson(this);
return json;
}
public static RpcProtocol fromJson(String json) {
return JsonUtil.jsonToObject(json, RpcProtocol.class);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RpcProtocol that = (RpcProtocol) o;
return port == that.port &&
Objects.equals(host, that.host) &&
isListEquals(serviceInfoList, that.getServiceInfoList());
}
private boolean isListEquals(List<RpcServiceInfo> thisList, List<RpcServiceInfo> thatList) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(host, port, serviceInfoList.hashCode());
}
@Override
public String toString() {
return toJson();
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public List<RpcServiceInfo> getServiceInfoList() {
return serviceInfoList;
}
public void setServiceInfoList(List<RpcServiceInfo> serviceInfoList) {
this.serviceInfoList = serviceInfoList;
}
}
|
if (thisList == null && thatList == null) {
return true;
}
if ((thisList == null && thatList != null)
|| (thisList != null && thatList == null)
|| (thisList.size() != thatList.size())) {
return false;
}
return thisList.containsAll(thatList) && thatList.containsAll(thisList);
| 499
| 103
| 602
|
<no_super_class>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-common/src/main/java/com/netty/rpc/protocol/RpcServiceInfo.java
|
RpcServiceInfo
|
equals
|
class RpcServiceInfo implements Serializable {
// interface name
private String serviceName;
// service version
private String version;
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(serviceName, version);
}
public String toJson() {
String json = JsonUtil.objectToJson(this);
return json;
}
@Override
public String toString() {
return toJson();
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RpcServiceInfo that = (RpcServiceInfo) o;
return Objects.equals(serviceName, that.serviceName) &&
Objects.equals(version, that.version);
| 230
| 81
| 311
|
<no_super_class>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-common/src/main/java/com/netty/rpc/serializer/hessian/Hessian1Serializer.java
|
Hessian1Serializer
|
serialize
|
class Hessian1Serializer extends Serializer {
@Override
public <T> byte[] serialize(T obj) {<FILL_FUNCTION_BODY>}
@Override
public <T> Object deserialize(byte[] bytes, Class<T> clazz) {
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
HessianInput hi = new HessianInput(is);
try {
Object result = hi.readObject();
return result;
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
hi.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
try {
is.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
|
ByteArrayOutputStream os = new ByteArrayOutputStream();
HessianOutput ho = new HessianOutput(os);
try {
ho.writeObject(obj);
ho.flush();
byte[] result = os.toByteArray();
return result;
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
ho.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
os.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
| 214
| 155
| 369
|
<methods>public non-sealed void <init>() ,public abstract java.lang.Object deserialize(byte[], Class<T>) ,public abstract byte[] serialize(T) <variables>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-common/src/main/java/com/netty/rpc/serializer/hessian/HessianSerializer.java
|
HessianSerializer
|
deserialize
|
class HessianSerializer extends Serializer {
@Override
public <T> byte[] serialize(T obj) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
Hessian2Output ho = new Hessian2Output(os);
try {
ho.writeObject(obj);
ho.flush();
byte[] result = os.toByteArray();
return result;
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
ho.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
os.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@Override
public <T> Object deserialize(byte[] bytes, Class<T> clazz) {<FILL_FUNCTION_BODY>}
}
|
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
Hessian2Input hi = new Hessian2Input(is);
try {
Object result = hi.readObject();
return result;
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
hi.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
try {
is.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
| 231
| 142
| 373
|
<methods>public non-sealed void <init>() ,public abstract java.lang.Object deserialize(byte[], Class<T>) ,public abstract byte[] serialize(T) <variables>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-common/src/main/java/com/netty/rpc/serializer/kryo/KryoPoolFactory.java
|
KryoPoolFactory
|
create
|
class KryoPoolFactory {
private static volatile KryoPoolFactory poolFactory = null;
private KryoFactory factory = new KryoFactory() {
@Override
public Kryo create() {<FILL_FUNCTION_BODY>}
};
private KryoPool pool = new KryoPool.Builder(factory).build();
private KryoPoolFactory() {
}
public static KryoPool getKryoPoolInstance() {
if (poolFactory == null) {
synchronized (KryoPoolFactory.class) {
if (poolFactory == null) {
poolFactory = new KryoPoolFactory();
}
}
}
return poolFactory.getPool();
}
public KryoPool getPool() {
return pool;
}
}
|
Kryo kryo = new Kryo();
kryo.setReferences(false);
kryo.register(RpcRequest.class);
kryo.register(RpcResponse.class);
Kryo.DefaultInstantiatorStrategy strategy = (Kryo.DefaultInstantiatorStrategy) kryo.getInstantiatorStrategy();
strategy.setFallbackInstantiatorStrategy(new StdInstantiatorStrategy());
return kryo;
| 210
| 119
| 329
|
<no_super_class>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-common/src/main/java/com/netty/rpc/serializer/kryo/KryoSerializer.java
|
KryoSerializer
|
deserialize
|
class KryoSerializer extends Serializer {
private KryoPool pool = KryoPoolFactory.getKryoPoolInstance();
@Override
public <T> byte[] serialize(T obj) {
Kryo kryo = pool.borrow();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Output out = new Output(byteArrayOutputStream);
try {
kryo.writeObject(out, obj);
out.close();
return byteArrayOutputStream.toByteArray();
} catch (Exception ex) {
throw new RuntimeException(ex);
} finally {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
pool.release(kryo);
}
}
@Override
public <T> Object deserialize(byte[] bytes, Class<T> clazz) {<FILL_FUNCTION_BODY>}
}
|
Kryo kryo = pool.borrow();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
Input in = new Input(byteArrayInputStream);
try {
Object result = kryo.readObject(in, clazz);
in.close();
return result;
} catch (Exception ex) {
throw new RuntimeException(ex);
} finally {
try {
byteArrayInputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
pool.release(kryo);
}
| 240
| 146
| 386
|
<methods>public non-sealed void <init>() ,public abstract java.lang.Object deserialize(byte[], Class<T>) ,public abstract byte[] serialize(T) <variables>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-common/src/main/java/com/netty/rpc/serializer/protostuff/ProtostuffSerializer.java
|
ProtostuffSerializer
|
deserialize
|
class ProtostuffSerializer extends Serializer {
private Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<>();
private Objenesis objenesis = new ObjenesisStd(true);
@SuppressWarnings("unchecked")
private <T> Schema<T> getSchema(Class<T> cls) {
// for thread-safe
return (Schema<T>) cachedSchema.computeIfAbsent(cls, RuntimeSchema::createFrom);
}
@Override
public <T> byte[] serialize(T obj) {
Class<T> cls = (Class<T>) obj.getClass();
LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
try {
Schema<T> schema = getSchema(cls);
return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
} finally {
buffer.clear();
}
}
@Override
public <T> Object deserialize(byte[] bytes, Class<T> clazz) {<FILL_FUNCTION_BODY>}
}
|
try {
T message = (T) objenesis.newInstance(clazz);
Schema<T> schema = getSchema(clazz);
ProtostuffIOUtil.mergeFrom(bytes, message, schema);
return message;
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
| 311
| 89
| 400
|
<methods>public non-sealed void <init>() ,public abstract java.lang.Object deserialize(byte[], Class<T>) ,public abstract byte[] serialize(T) <variables>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-common/src/main/java/com/netty/rpc/util/JsonUtil.java
|
JsonUtil
|
jsonToObjectHashMap
|
class JsonUtil {
private static ObjectMapper objMapper = new ObjectMapper();
static {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
objMapper.setDateFormat(dateFormat);
objMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objMapper.enable(SerializationFeature.INDENT_OUTPUT);
objMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
objMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_JSON_CONTENT, false);
objMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE);
objMapper.disable(SerializationFeature.CLOSE_CLOSEABLE);
objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
objMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
objMapper.configure(JsonParser.Feature.IGNORE_UNDEFINED, true);
}
public static <T> byte[] serialize(T obj) {
byte[] bytes = new byte[0];
try {
bytes = objMapper.writeValueAsBytes(obj);
} catch (JsonProcessingException e) {
throw new IllegalStateException(e.getMessage(), e);
}
return bytes;
}
public static <T> T deserialize(byte[] data, Class<T> cls) {
T obj = null;
try {
obj = objMapper.readValue(data, cls);
} catch (IOException e) {
throw new IllegalStateException(e.getMessage(), e);
}
return obj;
}
public static <type> type jsonToObject(String json, Class<?> cls) {
type obj = null;
JavaType javaType = objMapper.getTypeFactory().constructType(cls);
try {
obj = objMapper.readValue(json, javaType);
} catch (IOException e) {
throw new IllegalStateException(e.getMessage(), e);
}
return obj;
}
public static <type> type jsonToObjectList(String json,
Class<?> collectionClass, Class<?>... elementClass) {
type obj = null;
JavaType javaType = objMapper.getTypeFactory().constructParametricType(
collectionClass, elementClass);
try {
obj = objMapper.readValue(json, javaType);
} catch (IOException e) {
throw new IllegalStateException(e.getMessage(), e);
}
return obj;
}
public static <type> type jsonToObjectHashMap(String json,
Class<?> keyClass, Class<?> valueClass) {<FILL_FUNCTION_BODY>}
public static String objectToJson(Object o) {
String json = "";
try {
json = objMapper.writeValueAsString(o);
} catch (IOException e) {
throw new IllegalStateException(e.getMessage(), e);
}
return json;
}
}
|
type obj = null;
JavaType javaType = objMapper.getTypeFactory().constructParametricType(HashMap.class, keyClass, valueClass);
try {
obj = objMapper.readValue(json, javaType);
} catch (IOException e) {
throw new IllegalStateException(e.getMessage(), e);
}
return obj;
| 790
| 91
| 881
|
<no_super_class>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-common/src/main/java/com/netty/rpc/util/SerializationUtil.java
|
SerializationUtil
|
serialize
|
class SerializationUtil {
private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<>();
private static Objenesis objenesis = new ObjenesisStd(true);
private SerializationUtil() {
}
@SuppressWarnings("unchecked")
private static <T> Schema<T> getSchema(Class<T> cls) {
// Schema<T> schema = (Schema<T>) cachedSchema.get(cls);
// if (schema == null) {
// schema = RuntimeSchema.createFrom(cls);
// if (schema != null) {
// cachedSchema.put(cls, schema);
// }
// }
// return schema;
// for thread-safe
return (Schema<T>) cachedSchema.computeIfAbsent(cls, RuntimeSchema::createFrom);
}
/**
* 序列化(对象 -> 字节数组)
*/
@SuppressWarnings("unchecked")
public static <T> byte[] serialize(T obj) {<FILL_FUNCTION_BODY>}
/**
* 反序列化(字节数组 -> 对象)
*/
public static <T> T deserialize(byte[] data, Class<T> cls) {
try {
T message = (T) objenesis.newInstance(cls);
Schema<T> schema = getSchema(cls);
ProtostuffIOUtil.mergeFrom(data, message, schema);
return message;
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}
|
Class<T> cls = (Class<T>) obj.getClass();
LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
try {
Schema<T> schema = getSchema(cls);
return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
} finally {
buffer.clear();
}
| 428
| 121
| 549
|
<no_super_class>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-common/src/main/java/com/netty/rpc/util/ServiceUtil.java
|
ServiceUtil
|
makeServiceKey
|
class ServiceUtil {
public static final String SERVICE_CONCAT_TOKEN = "#";
public static String makeServiceKey(String interfaceName, String version) {<FILL_FUNCTION_BODY>}
}
|
String serviceKey = interfaceName;
if (version != null && version.trim().length() > 0) {
serviceKey += SERVICE_CONCAT_TOKEN.concat(version);
}
return serviceKey;
| 55
| 59
| 114
|
<no_super_class>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-common/src/main/java/com/netty/rpc/util/ThreadPoolUtil.java
|
ThreadPoolUtil
|
newThread
|
class ThreadPoolUtil {
public static ThreadPoolExecutor createThreadPool(final String name, int corePoolSize, int maxPoolSize) {
ThreadPoolExecutor serverHandlerPool = new ThreadPoolExecutor(
corePoolSize,
maxPoolSize,
60L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(1000),
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {<FILL_FUNCTION_BODY>}
},
new ThreadPoolExecutor.AbortPolicy());
return serverHandlerPool;
}
}
|
return new Thread(r, "netty-rpc-" + name + "-" + r.hashCode());
| 150
| 29
| 179
|
<no_super_class>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-common/src/main/java/com/netty/rpc/zookeeper/CuratorClient.java
|
CuratorClient
|
watchPathChildrenNode
|
class CuratorClient {
private CuratorFramework client;
public CuratorClient(String connectString, String namespace, int sessionTimeout, int connectionTimeout) {
client = CuratorFrameworkFactory.builder().namespace(namespace).connectString(connectString)
.sessionTimeoutMs(sessionTimeout).connectionTimeoutMs(connectionTimeout)
.retryPolicy(new ExponentialBackoffRetry(1000, 10))
.build();
client.start();
}
public CuratorClient(String connectString, int timeout) {
this(connectString, Constant.ZK_NAMESPACE, timeout, timeout);
}
public CuratorClient(String connectString) {
this(connectString, Constant.ZK_NAMESPACE, Constant.ZK_SESSION_TIMEOUT, Constant.ZK_CONNECTION_TIMEOUT);
}
public CuratorFramework getClient() {
return client;
}
public void addConnectionStateListener(ConnectionStateListener connectionStateListener) {
client.getConnectionStateListenable().addListener(connectionStateListener);
}
public String createPathData(String path, byte[] data) throws Exception {
return client.create().creatingParentsIfNeeded()
.withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
.forPath(path, data);
}
public void updatePathData(String path, byte[] data) throws Exception {
client.setData().forPath(path, data);
}
public void deletePath(String path) throws Exception {
client.delete().forPath(path);
}
public void watchNode(String path, Watcher watcher) throws Exception {
client.getData().usingWatcher(watcher).forPath(path);
}
public byte[] getData(String path) throws Exception {
return client.getData().forPath(path);
}
public List<String> getChildren(String path) throws Exception {
return client.getChildren().forPath(path);
}
public void watchTreeNode(String path, TreeCacheListener listener) {
TreeCache treeCache = new TreeCache(client, path);
treeCache.getListenable().addListener(listener);
}
public void watchPathChildrenNode(String path, PathChildrenCacheListener listener) throws Exception {<FILL_FUNCTION_BODY>}
public void close() {
client.close();
}
}
|
PathChildrenCache pathChildrenCache = new PathChildrenCache(client, path, true);
//BUILD_INITIAL_CACHE 代表使用同步的方式进行缓存初始化。
pathChildrenCache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
pathChildrenCache.getListenable().addListener(listener);
| 606
| 91
| 697
|
<no_super_class>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-server/src/main/java/com/netty/rpc/server/RpcServer.java
|
RpcServer
|
setApplicationContext
|
class RpcServer extends NettyServer implements ApplicationContextAware, InitializingBean, DisposableBean {
public RpcServer(String serverAddress, String registryAddress) {
super(serverAddress, registryAddress);
}
@Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException {<FILL_FUNCTION_BODY>}
@Override
public void afterPropertiesSet() throws Exception {
super.start();
}
@Override
public void destroy() {
super.stop();
}
}
|
Map<String, Object> serviceBeanMap = ctx.getBeansWithAnnotation(NettyRpcService.class);
if (MapUtils.isNotEmpty(serviceBeanMap)) {
for (Object serviceBean : serviceBeanMap.values()) {
NettyRpcService nettyRpcService = serviceBean.getClass().getAnnotation(NettyRpcService.class);
String interfaceName = nettyRpcService.value().getName();
String version = nettyRpcService.version();
super.addService(interfaceName, version, serviceBean);
}
}
| 135
| 142
| 277
|
<methods>public void <init>(java.lang.String, java.lang.String) ,public void addService(java.lang.String, java.lang.String, java.lang.Object) ,public void start() ,public void stop() <variables>private static final Logger logger,private java.lang.String serverAddress,private Map<java.lang.String,java.lang.Object> serviceMap,private com.netty.rpc.server.registry.ServiceRegistry serviceRegistry,private java.lang.Thread thread
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-server/src/main/java/com/netty/rpc/server/core/NettyServer.java
|
NettyServer
|
start
|
class NettyServer extends Server {
private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);
private Thread thread;
private String serverAddress;
private ServiceRegistry serviceRegistry;
private Map<String, Object> serviceMap = new HashMap<>();
public NettyServer(String serverAddress, String registryAddress) {
this.serverAddress = serverAddress;
this.serviceRegistry = new ServiceRegistry(registryAddress);
}
public void addService(String interfaceName, String version, Object serviceBean) {
logger.info("Adding service, interface: {}, version: {}, bean:{}", interfaceName, version, serviceBean);
String serviceKey = ServiceUtil.makeServiceKey(interfaceName, version);
serviceMap.put(serviceKey, serviceBean);
}
public void start() {<FILL_FUNCTION_BODY>}
public void stop() {
// destroy server thread
if (thread != null && thread.isAlive()) {
thread.interrupt();
}
}
}
|
thread = new Thread(new Runnable() {
ThreadPoolExecutor threadPoolExecutor = ThreadPoolUtil.createThreadPool(
NettyServer.class.getSimpleName(), 16, 32);
@Override
public void run() {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
.childHandler(new RpcServerInitializer(serviceMap, threadPoolExecutor))
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
String[] array = serverAddress.split(":");
String host = array[0];
int port = Integer.parseInt(array[1]);
ChannelFuture future = bootstrap.bind(host, port).sync();
if (serviceRegistry != null) {
serviceRegistry.registerService(host, port, serviceMap);
}
logger.info("Server started on port {}", port);
future.channel().closeFuture().sync();
} catch (Exception e) {
if (e instanceof InterruptedException) {
logger.info("Rpc server remoting server stop");
} else {
logger.error("Rpc server remoting server error", e);
}
} finally {
try {
serviceRegistry.unregisterService();
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
} catch (Exception ex) {
logger.error(ex.getMessage(), ex);
}
}
}
});
thread.start();
| 263
| 438
| 701
|
<methods>public non-sealed void <init>() ,public abstract void start() throws java.lang.Exception,public abstract void stop() throws java.lang.Exception<variables>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-server/src/main/java/com/netty/rpc/server/core/RpcServerHandler.java
|
RpcServerHandler
|
run
|
class RpcServerHandler extends SimpleChannelInboundHandler<RpcRequest> {
private static final Logger logger = LoggerFactory.getLogger(RpcServerHandler.class);
private final Map<String, Object> handlerMap;
private final ThreadPoolExecutor serverHandlerPool;
public RpcServerHandler(Map<String, Object> handlerMap, final ThreadPoolExecutor threadPoolExecutor) {
this.handlerMap = handlerMap;
this.serverHandlerPool = threadPoolExecutor;
}
@Override
public void channelRead0(final ChannelHandlerContext ctx, final RpcRequest request) {
// filter beat ping
if (Beat.BEAT_ID.equalsIgnoreCase(request.getRequestId())) {
logger.info("Server read heartbeat ping");
return;
}
serverHandlerPool.execute(new Runnable() {
@Override
public void run() {<FILL_FUNCTION_BODY>}
});
}
private Object handle(RpcRequest request) throws Throwable {
String className = request.getClassName();
String version = request.getVersion();
String serviceKey = ServiceUtil.makeServiceKey(className, version);
Object serviceBean = handlerMap.get(serviceKey);
if (serviceBean == null) {
logger.error("Can not find service implement with interface name: {} and version: {}", className, version);
return null;
}
Class<?> serviceClass = serviceBean.getClass();
String methodName = request.getMethodName();
Class<?>[] parameterTypes = request.getParameterTypes();
Object[] parameters = request.getParameters();
logger.debug(serviceClass.getName());
logger.debug(methodName);
for (int i = 0; i < parameterTypes.length; ++i) {
logger.debug(parameterTypes[i].getName());
}
for (int i = 0; i < parameters.length; ++i) {
logger.debug(parameters[i].toString());
}
// JDK reflect
// Method method = serviceClass.getMethod(methodName, parameterTypes);
// method.setAccessible(true);
// return method.invoke(serviceBean, parameters);
// Cglib reflect
FastClass serviceFastClass = FastClass.create(serviceClass);
// FastMethod serviceFastMethod = serviceFastClass.getMethod(methodName, parameterTypes);
// return serviceFastMethod.invoke(serviceBean, parameters);
// for higher-performance
int methodIndex = serviceFastClass.getIndex(methodName, parameterTypes);
return serviceFastClass.invoke(methodIndex, serviceBean, parameters);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
logger.warn("Server caught exception: " + cause.getMessage());
ctx.close();
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
ctx.channel().close();
logger.warn("Channel idle in last {} seconds, close it", Beat.BEAT_TIMEOUT);
} else {
super.userEventTriggered(ctx, evt);
}
}
}
|
logger.info("Receive request " + request.getRequestId());
RpcResponse response = new RpcResponse();
response.setRequestId(request.getRequestId());
try {
Object result = handle(request);
response.setResult(result);
} catch (Throwable t) {
response.setError(t.toString());
logger.error("RPC Server handle request error", t);
}
ctx.writeAndFlush(response).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture channelFuture) throws Exception {
logger.info("Send response for request " + request.getRequestId());
}
});
| 800
| 169
| 969
|
<no_super_class>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-server/src/main/java/com/netty/rpc/server/core/RpcServerInitializer.java
|
RpcServerInitializer
|
initChannel
|
class RpcServerInitializer extends ChannelInitializer<SocketChannel> {
private Map<String, Object> handlerMap;
private ThreadPoolExecutor threadPoolExecutor;
public RpcServerInitializer(Map<String, Object> handlerMap, ThreadPoolExecutor threadPoolExecutor) {
this.handlerMap = handlerMap;
this.threadPoolExecutor = threadPoolExecutor;
}
@Override
public void initChannel(SocketChannel channel) throws Exception {<FILL_FUNCTION_BODY>}
}
|
// Serializer serializer = ProtostuffSerializer.class.newInstance();
// Serializer serializer = HessianSerializer.class.newInstance();
Serializer serializer = KryoSerializer.class.newInstance();
ChannelPipeline cp = channel.pipeline();
cp.addLast(new IdleStateHandler(0, 0, Beat.BEAT_TIMEOUT, TimeUnit.SECONDS));
cp.addLast(new LengthFieldBasedFrameDecoder(65536, 0, 4, 0, 0));
cp.addLast(new RpcDecoder(RpcRequest.class, serializer));
cp.addLast(new RpcEncoder(RpcResponse.class, serializer));
cp.addLast(new RpcServerHandler(handlerMap, threadPoolExecutor));
| 123
| 200
| 323
|
<no_super_class>
|
luxiaoxun_NettyRpc
|
NettyRpc/netty-rpc-server/src/main/java/com/netty/rpc/server/registry/ServiceRegistry.java
|
ServiceRegistry
|
registerService
|
class ServiceRegistry {
private static final Logger logger = LoggerFactory.getLogger(ServiceRegistry.class);
private CuratorClient curatorClient;
private List<String> pathList = new ArrayList<>();
public ServiceRegistry(String registryAddress) {
this.curatorClient = new CuratorClient(registryAddress, 5000);
}
public void registerService(String host, int port, Map<String, Object> serviceMap) {<FILL_FUNCTION_BODY>}
public void unregisterService() {
logger.info("Unregister all service");
for (String path : pathList) {
try {
this.curatorClient.deletePath(path);
} catch (Exception ex) {
logger.error("Delete service path error: " + ex.getMessage());
}
}
this.curatorClient.close();
}
}
|
// Register service info
List<RpcServiceInfo> serviceInfoList = new ArrayList<>();
for (String key : serviceMap.keySet()) {
String[] serviceInfo = key.split(ServiceUtil.SERVICE_CONCAT_TOKEN);
if (serviceInfo.length > 0) {
RpcServiceInfo rpcServiceInfo = new RpcServiceInfo();
rpcServiceInfo.setServiceName(serviceInfo[0]);
if (serviceInfo.length == 2) {
rpcServiceInfo.setVersion(serviceInfo[1]);
} else {
rpcServiceInfo.setVersion("");
}
logger.info("Register new service: {} ", key);
serviceInfoList.add(rpcServiceInfo);
} else {
logger.warn("Can not get service name and version: {} ", key);
}
}
try {
RpcProtocol rpcProtocol = new RpcProtocol();
rpcProtocol.setHost(host);
rpcProtocol.setPort(port);
rpcProtocol.setServiceInfoList(serviceInfoList);
String serviceData = rpcProtocol.toJson();
byte[] bytes = serviceData.getBytes();
String path = Constant.ZK_DATA_PATH + "-" + rpcProtocol.hashCode();
path = this.curatorClient.createPathData(path, bytes);
pathList.add(path);
logger.info("Register {} new service, host: {}, port: {}", serviceInfoList.size(), host, port);
} catch (Exception e) {
logger.error("Register service fail, exception: {}", e.getMessage());
}
curatorClient.addConnectionStateListener(new ConnectionStateListener() {
@Override
public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) {
if (connectionState == ConnectionState.RECONNECTED) {
logger.info("Connection state: {}, register service after reconnected", connectionState);
registerService(host, port, serviceMap);
}
}
});
| 221
| 499
| 720
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/bouncycastle/BouncyCastleHelper.java
|
BouncyCastleHelper
|
getEnvelopedData
|
class BouncyCastleHelper {
public static void checkCertificateEncodingOrThrowException(Certificate certificate) {
// OJO...
try {
new X509CertificateHolder(certificate.getEncoded());
} catch (CertificateEncodingException | IOException f) {
throw new ExceptionConverter(f);
}
// ******************************************************************************
}
@SuppressWarnings("unchecked")
public static byte[] getEnvelopedData(PdfArray recipients, List<PdfObject> strings, Certificate certificate,
Key certificateKey, String certificateKeyProvider) {<FILL_FUNCTION_BODY>}
}
|
byte[] envelopedData = null;
for (PdfObject recipient : recipients.getElements()) {
strings.remove(recipient);
try {
CMSEnvelopedData data = new CMSEnvelopedData(recipient.getBytes());
final Collection<RecipientInformation> recipientInformations = data.getRecipientInfos().getRecipients();
for (RecipientInformation recipientInfo : recipientInformations) {
if (recipientInfo.getRID().match(certificate)) {
// OJO...
// https://www.bouncycastle.org/docs/pkixdocs1.5on/org/bouncycastle/cms/CMSEnvelopedData.html
Recipient rec = new JceKeyTransEnvelopedRecipient(
(PrivateKey) certificateKey)
.setProvider(certificateKeyProvider);
envelopedData = recipientInfo.getContent(rec);
// ******************************************************************************
break;
}
}
} catch (Exception f) {
throw new ExceptionConverter(f);
}
}
return envelopedData;
| 161
| 288
| 449
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/Anchor.java
|
Anchor
|
getUrl
|
class Anchor extends Phrase {
// constant
private static final long serialVersionUID = -852278536049236911L;
// membervariables
/**
* This is the name of the <CODE>Anchor</CODE>.
*/
protected String name = null;
/**
* This is the reference of the <CODE>Anchor</CODE>.
*/
protected String reference = null;
// constructors
/**
* Constructs an <CODE>Anchor</CODE> without specifying a leading.
*/
public Anchor() {
super(16);
}
/**
* Constructs an <CODE>Anchor</CODE> with a certain leading.
*
* @param leading the leading
*/
public Anchor(float leading) {
super(leading);
}
/**
* Constructs an <CODE>Anchor</CODE> with a certain <CODE>Chunk</CODE>.
*
* @param chunk a <CODE>Chunk</CODE>
*/
public Anchor(Chunk chunk) {
super(chunk);
}
/**
* Constructs an <CODE>Anchor</CODE> with a certain <CODE>String</CODE>.
*
* @param string a <CODE>String</CODE>
*/
public Anchor(String string) {
super(string);
}
/**
* Constructs an <CODE>Anchor</CODE> with a certain <CODE>String</CODE> and a certain <CODE>Font</CODE>.
*
* @param string a <CODE>String</CODE>
* @param font a <CODE>Font</CODE>
*/
public Anchor(String string, Font font) {
super(string, font);
}
/**
* Constructs an <CODE>Anchor</CODE> with a certain <CODE>Chunk</CODE> and a certain leading.
*
* @param leading the leading
* @param chunk a <CODE>Chunk</CODE>
*/
public Anchor(float leading, Chunk chunk) {
super(leading, chunk);
}
/**
* Constructs an <CODE>Anchor</CODE> with a certain leading and a certain <CODE>String</CODE>.
*
* @param leading the leading
* @param string a <CODE>String</CODE>
*/
public Anchor(float leading, String string) {
super(leading, string);
}
/**
* Constructs an <CODE>Anchor</CODE> with a certain leading, a certain <CODE>String</CODE> and a certain
* <CODE>Font</CODE>.
*
* @param leading the leading
* @param string a <CODE>String</CODE>
* @param font a <CODE>Font</CODE>
*/
public Anchor(float leading, String string, Font font) {
super(leading, string, font);
}
/**
* Constructs an <CODE>Anchor</CODE> with a certain <CODE>Phrase</CODE>.
*
* @param phrase a <CODE>Phrase</CODE>
*/
public Anchor(Phrase phrase) {
super(phrase);
if (phrase instanceof Anchor) {
Anchor a = (Anchor) phrase;
setName(a.name);
setReference(a.reference);
}
}
// implementation of the Element-methods
/**
* Processes the element by adding it (or the different parts) to an
* <CODE>ElementListener</CODE>.
*
* @param listener an <CODE>ElementListener</CODE>
* @return <CODE>true</CODE> if the element was processed successfully
*/
public boolean process(ElementListener listener) {
try {
Chunk chunk;
Iterator i = getChunks().iterator();
boolean localDestination = (reference != null && reference.startsWith("#"));
boolean notGotoOK = true;
while (i.hasNext()) {
chunk = (Chunk) i.next();
if (name != null && notGotoOK && !chunk.isEmpty()) {
chunk.setLocalDestination(name);
notGotoOK = false;
}
if (localDestination) {
chunk.setLocalGoto(reference.substring(1));
}
listener.add(chunk);
}
return true;
} catch (DocumentException de) {
return false;
}
}
/**
* Gets all the chunks in this element.
*
* @return an <CODE>ArrayList</CODE>
*/
public ArrayList<Element> getChunks() {
ArrayList<Element> tmp = new ArrayList<>();
Chunk chunk;
Iterator<Element> i = iterator();
boolean localDestination = (reference != null && reference.startsWith("#"));
boolean notGotoOK = true;
while (i.hasNext()) {
chunk = (Chunk) i.next();
if (name != null && notGotoOK && !chunk.isEmpty()) {
chunk.setLocalDestination(name);
notGotoOK = false;
}
if (localDestination) {
chunk.setLocalGoto(reference.substring(1));
} else if (reference != null) {
chunk.setAnchor(reference);
}
tmp.add(chunk);
}
return tmp;
}
/**
* Gets the type of the text element.
*
* @return a type
*/
public int type() {
return Element.ANCHOR;
}
// methods
/**
* Returns the name of this <CODE>Anchor</CODE>.
*
* @return a name
*/
public String getName() {
return name;
}
/**
* Sets the name of this <CODE>Anchor</CODE>.
*
* @param name a new name
*/
public void setName(String name) {
this.name = name;
}
// methods to retrieve information
/**
* Gets the reference of this <CODE>Anchor</CODE>.
*
* @return a reference
*/
public String getReference() {
return reference;
}
/**
* Sets the reference of this <CODE>Anchor</CODE>.
*
* @param reference a new reference
*/
public void setReference(String reference) {
this.reference = reference;
}
/**
* Gets the reference of this <CODE>Anchor</CODE>.
*
* @return an <CODE>URL</CODE>
*/
public URL getUrl() {<FILL_FUNCTION_BODY>}
}
|
try {
return new URL(reference);
} catch (MalformedURLException mue) {
return null;
}
| 1,769
| 36
| 1,805
|
<methods>public void <init>() ,public void <init>(com.lowagie.text.Phrase) ,public void <init>(float) ,public void <init>(com.lowagie.text.Chunk) ,public void <init>(float, com.lowagie.text.Chunk) ,public void <init>(java.lang.String) ,public void <init>(java.lang.String, com.lowagie.text.Font) ,public void <init>(float, java.lang.String) ,public void <init>(float, java.lang.String, com.lowagie.text.Font) ,public void add(int, com.lowagie.text.Element) ,public boolean add(java.lang.String) ,public boolean add(com.lowagie.text.Element) ,public boolean addAll(Collection<? extends com.lowagie.text.Element>) ,public ArrayList<com.lowagie.text.Element> getChunks() ,public java.lang.String getContent() ,public com.lowagie.text.Font getFont() ,public com.lowagie.text.pdf.HyphenationEvent getHyphenation() ,public static final com.lowagie.text.Phrase getInstance(java.lang.String) ,public static final com.lowagie.text.Phrase getInstance(int, java.lang.String) ,public static final com.lowagie.text.Phrase getInstance(int, java.lang.String, com.lowagie.text.Font) ,public float getLeading() ,public boolean hasLeading() ,public boolean isContent() ,public boolean isEmpty() ,public boolean isNestable() ,public boolean process(com.lowagie.text.ElementListener) ,public void setFont(com.lowagie.text.Font) ,public void setHyphenation(com.lowagie.text.pdf.HyphenationEvent) ,public void setLeading(float) ,public int type() <variables>protected com.lowagie.text.Font font,protected com.lowagie.text.pdf.HyphenationEvent hyphenation,protected float leading,private static final long serialVersionUID
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/ChapterAutoNumber.java
|
ChapterAutoNumber
|
addSection
|
class ChapterAutoNumber extends Chapter {
// constant
private static final long serialVersionUID = -9217457637987854167L;
/**
* Is the chapter number already set?
*
* @since 2.1.4
*/
protected boolean numberSet = false;
/**
* Create a new object.
*
* @param para the Chapter title (as a <CODE>Paragraph</CODE>)
*/
public ChapterAutoNumber(final Paragraph para) {
super(para, 0);
}
/**
* Create a new object.
*
* @param title the Chapter title (as a <CODE>String</CODE>)
*/
public ChapterAutoNumber(final String title) {
super(title, 0);
}
/**
* Create a new section for this chapter and ad it.
*
* @param title the Section title (as a <CODE>String</CODE>)
* @return Returns the new section.
*/
public Section addSection(final String title) {<FILL_FUNCTION_BODY>}
/**
* Create a new section for this chapter and add it.
*
* @param title the Section title (as a <CODE>Paragraph</CODE>)
* @return Returns the new section.
*/
public Section addSection(final Paragraph title) {
if (isAddedCompletely()) {
throw new IllegalStateException(
MessageLocalization.getComposedMessage("this.largeelement.has.already.been.added.to.the.document"));
}
return addSection(title, 2);
}
/**
* Changes the Chapter number.
*
* @param number the new chapter number
* @return updated chapter number
* @since 2.1.4
*/
public int setAutomaticNumber(int number) {
if (!numberSet) {
number++;
super.setChapterNumber(number);
numberSet = true;
}
return number;
}
}
|
if (isAddedCompletely()) {
throw new IllegalStateException(
MessageLocalization.getComposedMessage("this.largeelement.has.already.been.added.to.the.document"));
}
return addSection(title, 2);
| 532
| 66
| 598
|
<methods>public void <init>(int) ,public void <init>(com.lowagie.text.Paragraph, int) ,public void <init>(java.lang.String, int) ,public boolean isNestable() ,public int type() <variables>private static final long serialVersionUID
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/ExceptionConverter.java
|
ExceptionConverter
|
convertException
|
class ExceptionConverter extends RuntimeException {
private static final long serialVersionUID = 8657630363395849399L;
/**
* we keep a handle to the wrapped exception
*/
private Exception ex;
/**
* prefix for the exception
*/
private String prefix;
/**
* Construct a RuntimeException based on another Exception
*
* @param ex the exception that has to be turned into a RuntimeException
*/
public ExceptionConverter(Exception ex) {
this.ex = ex;
prefix = (ex instanceof RuntimeException) ? "" : "ExceptionConverter: ";
}
/**
* Convert an Exception into an unchecked exception. Return the exception if it is already an unchecked exception or
* return an ExceptionConverter wrapper otherwise
*
* @param ex the exception to convert
* @return an unchecked exception
* @since 2.1.6
*/
public static final RuntimeException convertException(Exception ex) {<FILL_FUNCTION_BODY>}
/**
* and allow the user of ExceptionConverter to get a handle to it.
*
* @return the original exception
*/
public Exception getException() {
return ex;
}
/**
* We print the message of the checked exception
*
* @return message of the original exception
*/
public String getMessage() {
return ex.getMessage();
}
/**
* and make sure we also produce a localized version
*
* @return localized version of the message
*/
public String getLocalizedMessage() {
return ex.getLocalizedMessage();
}
/**
* The toString() is changed to be prefixed with ExceptionConverter
*
* @return String version of the exception
*/
public String toString() {
return prefix + ex;
}
/**
* we have to override this as well
*/
public void printStackTrace() {
printStackTrace(System.err);
}
/**
* here we prefix, with printStream.print(), not printStream.println(), the stack trace with "ExceptionConverter:"
*
* @param printStream printStream
*/
public void printStackTrace(java.io.PrintStream printStream) {
synchronized (printStream) {
printStream.print(prefix);
ex.printStackTrace(printStream);
}
}
/**
* Again, we prefix the stack trace with "ExceptionConverter:"
*
* @param printWriter printWriter
*/
public void printStackTrace(java.io.PrintWriter printWriter) {
synchronized (printWriter) {
printWriter.print(prefix);
ex.printStackTrace(printWriter);
}
}
/**
* requests to fill in the stack trace we will have to ignore. We can't throw an exception here, because this method
* is called by the constructor of Throwable
*
* @return a Throwable
*/
public synchronized Throwable fillInStackTrace() {
return this;
}
}
|
if (ex instanceof RuntimeException) {
return (RuntimeException) ex;
}
return new ExceptionConverter(ex);
| 775
| 34
| 809
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.Throwable) ,public void <init>(java.lang.String, java.lang.Throwable) <variables>static final long serialVersionUID
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/GreekList.java
|
GreekList
|
add
|
class GreekList extends List {
// constructors
/**
* Initialization
*/
public GreekList() {
super(true);
setGreekFont();
}
/**
* Initialization
*
* @param symbolIndent indent
*/
public GreekList(int symbolIndent) {
super(true, symbolIndent);
setGreekFont();
}
/**
* Initialization
*
* @param greeklower greek-char in lowercase
* @param symbolIndent indent
*/
public GreekList(boolean greeklower, int symbolIndent) {
super(true, symbolIndent);
lowercase = greeklower;
setGreekFont();
}
// helper method
/**
* change the font to SYMBOL
*/
protected void setGreekFont() {
float fontsize = symbol.getFont().getSize();
symbol.setFont(FontFactory.getFont(FontFactory.SYMBOL, fontsize, Font.NORMAL));
}
// overridden methods
/**
* Adds an <CODE>Element</CODE> to the <CODE>List</CODE>.
*
* @param o the element to add.
* @return true if adding the element succeeded
*/
@Override
public boolean add(Element o) {<FILL_FUNCTION_BODY>}
/**
* Adds a <CODE>String</CODE> to the <CODE>List</CODE>.
*
* @param s the string to add.
* @return true if adding the string succeeded
*/
@Override
public boolean add(String s) {
return this.add(new ListItem(s));
}
}
|
if (o instanceof ListItem) {
ListItem item = (ListItem) o;
Chunk chunk = new Chunk(preSymbol, symbol.getFont());
chunk.append(GreekAlphabetFactory.getString(first + list.size(), lowercase));
chunk.append(postSymbol);
item.setListSymbol(chunk);
item.setIndentationLeft(symbolIndent, autoindent);
item.setIndentationRight(0);
list.add(item);
} else if (o instanceof List) {
List nested = (List) o;
nested.setIndentationLeft(nested.getIndentationLeft() + symbolIndent);
first--;
return list.add(nested);
}
return false;
| 452
| 191
| 643
|
<methods>public void <init>() ,public void <init>(float) ,public void <init>(boolean) ,public void <init>(boolean, boolean) ,public void <init>(boolean, float) ,public void <init>(boolean, boolean, float) ,public boolean add(com.lowagie.text.Element) ,public boolean add(com.lowagie.text.List) ,public boolean add(java.lang.String) ,public ArrayList<com.lowagie.text.Element> getChunks() ,public int getFirst() ,public float getIndentationLeft() ,public float getIndentationRight() ,public List<com.lowagie.text.Element> getItems() ,public java.lang.String getPostSymbol() ,public java.lang.String getPreSymbol() ,public com.lowagie.text.Chunk getSymbol() ,public float getSymbolIndent() ,public float getTotalLeading() ,public boolean isAlignindent() ,public boolean isAutoindent() ,public boolean isContent() ,public boolean isEmpty() ,public boolean isLettered() ,public boolean isLowercase() ,public boolean isNestable() ,public boolean isNumbered() ,public void normalizeIndentation() ,public boolean process(com.lowagie.text.ElementListener) ,public void setAlignindent(boolean) ,public void setAutoindent(boolean) ,public void setFirst(int) ,public void setIndentationLeft(float) ,public void setIndentationRight(float) ,public void setLettered(boolean) ,public void setListSymbol(com.lowagie.text.Chunk) ,public void setListSymbol(java.lang.String) ,public void setLowercase(boolean) ,public void setNumbered(boolean) ,public void setPostSymbol(java.lang.String) ,public void setPreSymbol(java.lang.String) ,public void setSymbolIndent(float) ,public int size() ,public int type() <variables>public static final boolean ALPHABETICAL,public static final boolean LOWERCASE,public static final boolean NUMERICAL,public static final boolean ORDERED,public static final boolean UNORDERED,public static final boolean UPPERCASE,protected boolean alignindent,protected boolean autoindent,protected int first,protected float indentationLeft,protected float indentationRight,protected boolean lettered,protected List<com.lowagie.text.Element> list,protected boolean lowercase,protected boolean numbered,protected java.lang.String postSymbol,protected java.lang.String preSymbol,protected com.lowagie.text.Chunk symbol,protected float symbolIndent
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/HeaderFooter.java
|
HeaderFooter
|
paragraph
|
class HeaderFooter extends Rectangle {
// membervariables
/**
* Does the page contain a pagenumber?
*/
private boolean numbered;
/**
* This is the <CODE>Phrase</CODE> that comes before the pagenumber.
*/
private Phrase before = null;
/**
* This is number of the page.
*/
private int pageN;
/**
* This is the <CODE>Phrase</CODE> that comes after the pagenumber.
*/
private Phrase after = null;
/**
* This is alignment of the header/footer.
*/
private int alignment;
/**
* This is the <CODE>List</CODE> containing non-text <CODE>Element</CODE>.
*/
private java.util.List<Element> specialContent = null;
/**
* This is the padding of height of header/footer.
*/
private float padding;
// constructors
/**
* Constructs a <CODE>HeaderFooter</CODE>-object.
*
* @param before the <CODE>Phrase</CODE> before the pagenumber
* @param after the <CODE>Phrase</CODE> before the pagenumber
*/
public HeaderFooter(Phrase before, Phrase after) {
super(0, 0, 0, 0);
setBorder(TOP + BOTTOM);
setBorderWidth(1);
numbered = true;
this.before = before;
this.after = after;
}
/**
* Constructs a <CODE>Header</CODE>-object with a pagenumber at the end.
*
* @param before the <CODE>Phrase</CODE> before the pagenumber
* @param numbered page will be numbered if <CODE>true</CODE>
*/
public HeaderFooter(Phrase before, boolean numbered) {
super(0, 0, 0, 0);
setBorder(TOP + BOTTOM);
setBorderWidth(1);
this.numbered = numbered;
this.before = before;
}
/**
* Constructs a <CODE>Header</CODE>-object with a pagenumber at the beginning.
*
* @param numbered page will be numbered if <CODE>true</CODE>
* @param after the <CODE>Phrase</CODE> after the pagenumber
*/
public HeaderFooter(boolean numbered, Phrase after) {
super(0, 0, 0, 0);
setBorder(TOP + BOTTOM);
setBorderWidth(1);
this.numbered = numbered;
this.after = after;
}
/**
* Constructs a <CODE>Header</CODE>-object with only a pagenumber.
*
* @param numbered <CODE>true</CODE> if the page has to be numbered
*/
public HeaderFooter(boolean numbered) {
this(null, true);
this.numbered = numbered;
}
// methods
/**
* Checks if the HeaderFooter contains a page number.
*
* @return true if the page has to be numbered
*/
public boolean isNumbered() {
return numbered;
}
/**
* Gets the part that comes before the pageNumber.
*
* @return a Phrase
*/
public Phrase getBefore() {
return before;
}
/**
* Gets the part that comes after the pageNumber.
*
* @return a Phrase
*/
public Phrase getAfter() {
return after;
}
/**
* Sets the page number.
*
* @param pageN the new page number
*/
public void setPageNumber(int pageN) {
this.pageN = pageN;
}
/**
* Sets the alignment.
*
* @param alignment the new alignment
*/
public void setAlignment(int alignment) {
this.alignment = alignment;
}
/**
* Gets padding of height of header/footer.
*
* @return the padding of height
*/
public float getPadding() {
return padding;
}
/**
* Sets padding of height of header/footer.
*
* @param padding the new padding of height
*/
public void setPadding(float padding) {
this.padding = padding;
}
/**
* Increases current padding by adding new value into it
*
* @param augment the new value
*/
public void addPadding(float augment) {
padding += augment;
}
/**
* Adds non-text <CODE>Element</CODE> into <CODE>specialContent</CODE>
*
* @param element the new non-text <CODE>Element</CODE>
*/
public void addSpecialContent(Element element) {
if (specialContent == null) {
specialContent = new ArrayList<>();
}
specialContent.add(element);
}
/**
* Gets <CODE>specialContent</CODE>
*
* @return <CODE>specialContent</CODE>
*/
public List<Element> getSpecialContent() {
return specialContent;
}
// methods to retrieve the membervariables
/**
* Gets the <CODE>Paragraph</CODE> that can be used as header or footer.
*
* @return a <CODE>Paragraph</CODE>
*/
public Paragraph paragraph() {<FILL_FUNCTION_BODY>}
private Font getFont() {
if (before != null) {
return before.getFont();
}
if (after != null) {
return after.getFont();
}
return null;
}
/**
* Gets the alignment of this HeaderFooter.
*
* @return alignment
*/
public int alignment() {
return alignment;
}
}
|
Paragraph paragraph;
if (before != null) {
paragraph = new Paragraph(before.getLeading());
paragraph.add(before);
// Adding a Paragraph to another Paraghraph adds a newline that needs to be removed in headers and footers
if (before instanceof Paragraph
&&
paragraph.size() >= 2
&&
"\n".equals(paragraph.get(paragraph.size() - 1).toString())) {
paragraph.remove(paragraph.size() - 1);
}
} else {
paragraph = new Paragraph();
}
if (numbered) {
Font font = getFont();
if (font != null) {
paragraph.addSpecial(new Chunk(String.valueOf(pageN), font));
} else {
paragraph.addSpecial(new Chunk(String.valueOf(pageN)));
}
}
if (after != null) {
paragraph.addSpecial(after);
}
paragraph.setAlignment(alignment);
return paragraph;
| 1,566
| 267
| 1,833
|
<methods>public void <init>(float, float, float, float) ,public void <init>(float, float) ,public void <init>(float, float, float, float, int) ,public void <init>(float, float, int) ,public void <init>(com.lowagie.text.Rectangle) ,public void cloneNonPositionParameters(com.lowagie.text.Rectangle) ,public void disableBorderSide(int) ,public void enableBorderSide(int) ,public java.awt.Color getBackgroundColor() ,public int getBorder() ,public java.awt.Color getBorderColor() ,public java.awt.Color getBorderColorBottom() ,public java.awt.Color getBorderColorLeft() ,public java.awt.Color getBorderColorRight() ,public java.awt.Color getBorderColorTop() ,public float getBorderWidth() ,public float getBorderWidthBottom() ,public float getBorderWidthLeft() ,public float getBorderWidthRight() ,public float getBorderWidthTop() ,public float getBottom() ,public float getBottom(float) ,public ArrayList<com.lowagie.text.Element> getChunks() ,public float getGrayFill() ,public float getHeight() ,public float getLeft() ,public float getLeft(float) ,public float getRelativeTop() ,public float getRight() ,public float getRight(float) ,public int getRotation() ,public float getTop() ,public float getTop(float) ,public float getWidth() ,public boolean hasBorder(int) ,public boolean hasBorders() ,public boolean isContent() ,public boolean isNestable() ,public boolean isUseVariableBorders() ,public void normalize() ,public boolean process(com.lowagie.text.ElementListener) ,public com.lowagie.text.Rectangle rectangle(float, float) ,public com.lowagie.text.Rectangle rotate() ,public void setBackgroundColor(java.awt.Color) ,public void setBorder(int) ,public void setBorderColor(java.awt.Color) ,public void setBorderColorBottom(java.awt.Color) ,public void setBorderColorLeft(java.awt.Color) ,public void setBorderColorRight(java.awt.Color) ,public void setBorderColorTop(java.awt.Color) ,public void setBorderWidth(float) ,public void setBorderWidthBottom(float) ,public void setBorderWidthLeft(float) ,public void setBorderWidthRight(float) ,public void setBorderWidthTop(float) ,public void setBottom(float) ,public void setGrayFill(float) ,public void setLeft(float) ,public void setRelativeTop(float) ,public void setRight(float) ,public void setRotation(int) ,public void setTop(float) ,public void setUseVariableBorders(boolean) ,public void softCloneNonPositionParameters(com.lowagie.text.Rectangle) ,public java.lang.String toString() ,public int type() <variables>public static final int BOTTOM,public static final int BOX,public static final int LEFT,public static final int NO_BORDER,public static final int RIGHT,public static final int TOP,public static final int UNDEFINED,protected java.awt.Color backgroundColor,protected int border,protected java.awt.Color borderColor,protected java.awt.Color borderColorBottom,protected java.awt.Color borderColorLeft,protected java.awt.Color borderColorRight,protected java.awt.Color borderColorTop,protected float borderWidth,protected float borderWidthBottom,protected float borderWidthLeft,protected float borderWidthRight,protected float borderWidthTop,protected float llx,protected float lly,protected float offsetToTop,protected int rotation,protected float urx,protected float ury,protected boolean useVariableBorders
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/ImageLoader.java
|
ImageLoader
|
getPngImage
|
class ImageLoader {
/**
* Creates an Image from a PNG image file in an URL.
*
* @param url url of the image
* @return an object of type <code>Image</code>
*/
public static Image getPngImage(URL url) {<FILL_FUNCTION_BODY>}
public static Image getGifImage(URL url) {
try (InputStream is = url.openStream()) {
BufferedImage bufferedImage = ImageIO.read(is);
return Image.getInstance(bufferedImage, null, false);
} catch (Exception e) {
throw new ExceptionConverter(e);
}
}
public static Image getTiffImage(URL url) {
try (InputStream is = url.openStream()) {
BufferedImage bufferedImage = ImageIO.read(is);
return Image.getInstance(bufferedImage, null, false);
} catch (Exception e) {
throw new ExceptionConverter(e);
}
}
public static Image getBmpImage(URL url) {
try (InputStream is = url.openStream()) {
BufferedImage bufferedImage = ImageIO.read(is);
return Image.getInstance(bufferedImage, null, false);
} catch (Exception e) {
throw new ExceptionConverter(e);
}
}
/**
* Creates an Image from a JPEG image file in an URL.
*
* @param url url of the image
* @return an object of type <code>Image</code>
*/
public static Image getJpegImage(URL url) {
try (InputStream is = url.openStream()) {
byte[] imageBytes = Utilities.toByteArray(is);
return new Jpeg(imageBytes);
} catch (Exception e) {
throw new ExceptionConverter(e);
}
}
public static Image getJpeg2000Image(URL url) {
try (InputStream is = url.openStream()) {
byte[] imageBytes = Utilities.toByteArray(is);
return new Jpeg2000(imageBytes);
} catch (Exception e) {
throw new ExceptionConverter(e);
}
}
public static Image getGifImage(byte[] imageData) {
try (InputStream is = new ByteArrayInputStream(imageData)) {
BufferedImage bufferedImage = ImageIO.read(is);
return Image.getInstance(bufferedImage, null, false);
} catch (Exception e) {
throw new ExceptionConverter(e);
}
}
public static Image getPngImage(byte[] imageData) {
try (InputStream is = new ByteArrayInputStream(imageData)) {
BufferedImage bufferedImage = ImageIO.read(is);
return Image.getInstance(bufferedImage, null, false);
} catch (Exception e) {
throw new ExceptionConverter(e);
}
}
public static Image getBmpImage(byte[] imageData) {
try (InputStream is = new ByteArrayInputStream(imageData)) {
BufferedImage bufferedImage = ImageIO.read(is);
return Image.getInstance(bufferedImage, null, false);
} catch (Exception e) {
throw new ExceptionConverter(e);
}
}
/**
* Creates an Image from an array of tiff image bytes.
*
* @param imageData bytes of the tiff image
* @return an objet of type <code>Image</code>
*/
public static Image getTiffImage(byte[] imageData) {
try (InputStream is = new ByteArrayInputStream(imageData)) {
BufferedImage bufferedImage = ImageIO.read(is);
return Image.getInstance(bufferedImage, null, false);
} catch (Exception e) {
throw new ExceptionConverter(e);
}
}
/**
* Creates an Image from a JPEG image file in a byte array.
*
* @param imageData bytes of the image
* @return an object of type <code>Image</code>
*/
public static Image getJpegImage(byte[] imageData) {
try {
return new Jpeg(imageData);
} catch (Exception e) {
throw new ExceptionConverter(e);
}
}
public static Image getJpeg2000Image(byte[] imageData) {
try {
return new Jpeg2000(imageData);
} catch (Exception e) {
throw new ExceptionConverter(e);
}
}
}
|
try (InputStream is = url.openStream()) {
BufferedImage bufferedImage = ImageIO.read(is);
return Image.getInstance(bufferedImage, null, false);
} catch (Exception e) {
throw new ExceptionConverter(e);
}
| 1,142
| 68
| 1,210
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/ImgWMF.java
|
ImgWMF
|
readWMF
|
class ImgWMF extends Image {
// Constructors
ImgWMF(Image image) {
super(image);
}
/**
* Constructs an <CODE>ImgWMF</CODE>-object, using an <VAR>url</VAR>.
*
* @param url the <CODE>URL</CODE> where the image can be found
* @throws BadElementException on error
* @throws IOException on error
*/
public ImgWMF(URL url) throws BadElementException, IOException {
super(url);
processParameters();
}
/**
* Constructs an <CODE>ImgWMF</CODE>-object, using a <VAR>filename</VAR>.
*
* @param filename a <CODE>String</CODE>-representation of the file that contains the image.
* @throws BadElementException on error
* @throws MalformedURLException on error
* @throws IOException on error
*/
public ImgWMF(String filename) throws BadElementException, IOException {
this(Utilities.toURL(filename));
}
/**
* Constructs an <CODE>ImgWMF</CODE>-object from memory.
*
* @param img the memory image
* @throws BadElementException on error
* @throws IOException on error
*/
public ImgWMF(byte[] img) throws BadElementException, IOException {
super((URL) null);
rawData = img;
originalData = img;
processParameters();
}
/**
* This method checks if the image is a valid WMF and processes some parameters.
*
* @throws BadElementException
* @throws IOException
*/
private void processParameters() throws BadElementException, IOException {
type = IMGTEMPLATE;
originalType = ORIGINAL_WMF;
InputStream is = null;
try {
String errorID;
if (rawData == null) {
is = url.openStream();
errorID = url.toString();
} else {
is = new java.io.ByteArrayInputStream(rawData);
errorID = "Byte array";
}
InputMeta in = new InputMeta(is);
if (in.readInt() != 0x9AC6CDD7) {
throw new BadElementException(
MessageLocalization.getComposedMessage("1.is.not.a.valid.placeable.windows.metafile", errorID));
}
in.readWord();
int left = in.readShort();
int top = in.readShort();
int right = in.readShort();
int bottom = in.readShort();
int inch = in.readWord();
dpiX = 72;
dpiY = 72;
scaledHeight = (float) (bottom - top) / inch * 72f;
setTop(scaledHeight);
scaledWidth = (float) (right - left) / inch * 72f;
setRight(scaledWidth);
} finally {
if (is != null) {
is.close();
}
plainWidth = getWidth();
plainHeight = getHeight();
}
}
/**
* Reads the WMF into a template.
*
* @param template the template to read to
* @throws IOException on error
* @throws DocumentException on error
*/
public void readWMF(PdfTemplate template) throws IOException, DocumentException {<FILL_FUNCTION_BODY>}
}
|
setTemplateData(template);
template.setWidth(getWidth());
template.setHeight(getHeight());
InputStream is = null;
try {
if (rawData == null) {
is = url.openStream();
} else {
is = new java.io.ByteArrayInputStream(rawData);
}
MetaDo meta = new MetaDo(is, template);
meta.readAll();
} finally {
if (is != null) {
is.close();
}
}
| 894
| 136
| 1,030
|
<methods>public void <init>(java.net.URL) ,public float getAbsoluteX() ,public float getAbsoluteY() ,public com.lowagie.text.pdf.PdfDictionary getAdditional() ,public int getAlignment() ,public java.lang.String getAlt() ,public com.lowagie.text.Annotation getAnnotation() ,public int getBpc() ,public int getColorspace() ,public int getCompressionLevel() ,public com.lowagie.text.pdf.PdfIndirectReference getDirectReference() ,public int getDpiX() ,public int getDpiY() ,public java.awt.color.ICC_Profile getICCProfile() ,public com.lowagie.text.Image getImageMask() ,public float getImageRotation() ,public float getIndentationLeft() ,public float getIndentationRight() ,public float getInitialRotation() ,public static com.lowagie.text.Image getInstance(java.net.URL) throws com.lowagie.text.BadElementException, java.io.IOException,public static com.lowagie.text.Image getInstance(java.lang.String) throws com.lowagie.text.BadElementException, java.io.IOException,public static com.lowagie.text.Image getInstance(byte[]) throws com.lowagie.text.BadElementException, java.io.IOException,public static com.lowagie.text.Image getInstance(int, int, int, int, byte[]) throws com.lowagie.text.BadElementException,public static com.lowagie.text.Image getInstance(int, int, byte[], byte[]) ,public static com.lowagie.text.Image getInstance(int, int, boolean, int, int, byte[]) throws com.lowagie.text.BadElementException,public static com.lowagie.text.Image getInstance(int, int, boolean, int, int, byte[], int[]) throws com.lowagie.text.BadElementException,public static com.lowagie.text.Image getInstance(int, int, int, int, byte[], int[]) throws com.lowagie.text.BadElementException,public static com.lowagie.text.Image getInstance(com.lowagie.text.pdf.PdfTemplate) throws com.lowagie.text.BadElementException,public static com.lowagie.text.Image getInstance(java.awt.Image, java.awt.Color, boolean) throws com.lowagie.text.BadElementException, java.io.IOException,public static com.lowagie.text.Image getInstance(java.awt.Image, java.awt.Color) throws com.lowagie.text.BadElementException, java.io.IOException,public static com.lowagie.text.Image getInstance(com.lowagie.text.pdf.PdfWriter, java.awt.Image, float) throws com.lowagie.text.BadElementException, java.io.IOException,public static com.lowagie.text.Image getInstance(com.lowagie.text.pdf.PdfContentByte, java.awt.Image, float) throws com.lowagie.text.BadElementException, java.io.IOException,public static com.lowagie.text.Image getInstance(com.lowagie.text.pdf.PRIndirectReference) throws com.lowagie.text.BadElementException,public static com.lowagie.text.Image getInstance(com.lowagie.text.Image) ,public static com.lowagie.text.Image getInstanceFromClasspath(java.lang.String) throws com.lowagie.text.BadElementException, java.io.IOException,public com.lowagie.text.pdf.PdfOCG getLayer() ,public java.lang.Long getMySerialId() ,public byte[] getOriginalData() ,public int getOriginalType() ,public float getPlainHeight() ,public float getPlainWidth() ,public byte[] getRawData() ,public float getScaledHeight() ,public float getScaledWidth() ,public float getSpacingAfter() ,public float getSpacingBefore() ,public com.lowagie.text.pdf.PdfTemplate getTemplateData() ,public int[] getTransparency() ,public java.net.URL getUrl() ,public float getWidthPercentage() ,public float getXYRatio() ,public boolean hasAbsoluteX() ,public boolean hasAbsoluteY() ,public boolean hasICCProfile() ,public boolean isDeflated() ,public boolean isImgRaw() ,public boolean isImgTemplate() ,public boolean isInterpolation() ,public boolean isInverted() ,public boolean isJpeg() ,public boolean isMask() ,public boolean isMaskCandidate() ,public boolean isNestable() ,public boolean isSmask() ,public void makeMask() throws com.lowagie.text.DocumentException,public float[] matrix() ,public void scaleAbsolute(float, float) ,public void scaleAbsoluteHeight(float) ,public void scaleAbsoluteWidth(float) ,public void scalePercent(float) ,public void scalePercent(float, float) ,public void scaleToFit(float, float) ,public void setAbsolutePosition(float, float) ,public void setAdditional(com.lowagie.text.pdf.PdfDictionary) ,public void setAlignment(int) ,public void setAlt(java.lang.String) ,public void setAnnotation(com.lowagie.text.Annotation) ,public void setCompressionLevel(int) ,public void setDeflated(boolean) ,public void setDirectReference(com.lowagie.text.pdf.PdfIndirectReference) ,public void setDpi(int, int) ,public void setImageMask(com.lowagie.text.Image) throws com.lowagie.text.DocumentException,public void setIndentationLeft(float) ,public void setIndentationRight(float) ,public void setInitialRotation(float) ,public void setInterpolation(boolean) ,public void setInverted(boolean) ,public void setLayer(com.lowagie.text.pdf.PdfOCG) ,public void setOriginalData(byte[]) ,public void setOriginalType(int) ,public void setRotation(float) ,public void setRotationDegrees(float) ,public void setSmask(boolean) ,public void setSpacingAfter(float) ,public void setSpacingBefore(float) ,public void setTemplateData(com.lowagie.text.pdf.PdfTemplate) ,public void setTransparency(int[]) ,public void setUrl(java.net.URL) ,public void setWidthPercentage(float) ,public void setXYRatio(float) ,public void simplifyColorspace() ,public void tagICC(java.awt.color.ICC_Profile) ,public int type() <variables>public static final int AX,public static final int AY,public static final int BX,public static final int BY,public static final int CX,public static final int CY,public static final int DEFAULT,public static final int DX,public static final int DY,public static final int LEFT,public static final int MIDDLE,public static final int ORIGINAL_BMP,public static final int ORIGINAL_GIF,public static final int ORIGINAL_JBIG2,public static final int ORIGINAL_JPEG,public static final int ORIGINAL_JPEG2000,public static final int ORIGINAL_NONE,public static final int ORIGINAL_PNG,public static final int ORIGINAL_PS,public static final int ORIGINAL_TIFF,public static final int ORIGINAL_WMF,public static final int[] PNGID,public static final int RIGHT,public static final int TEXTWRAP,public static final int UNDERLYING,private float XYRatio,protected float absoluteX,protected float absoluteY,private com.lowagie.text.pdf.PdfDictionary additional,protected int alignment,protected java.lang.String alt,protected com.lowagie.text.Annotation annotation,protected int bpc,protected int colorspace,protected int compressionLevel,protected boolean deflated,private com.lowagie.text.pdf.PdfIndirectReference directReference,protected int dpiX,protected int dpiY,protected com.lowagie.text.Image imageMask,protected float indentationLeft,protected float indentationRight,private float initialRotation,protected boolean interpolation,protected boolean invert,protected com.lowagie.text.pdf.PdfOCG layer,protected boolean mask,protected java.lang.Long mySerialId,protected byte[] originalData,protected int originalType,protected float plainHeight,protected float plainWidth,protected java.awt.color.ICC_Profile profile,protected byte[] rawData,protected float rotationRadians,protected float scaledHeight,protected float scaledWidth,static long serialId,private boolean smask,protected float spacingAfter,protected float spacingBefore,protected com.lowagie.text.pdf.PdfTemplate[] template,protected int[] transparency,protected int type,protected java.net.URL url,private float widthPercentage
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/Jpeg2000.java
|
Jpeg2000
|
processParameters
|
class Jpeg2000 extends Image {
// public static final membervariables
public static final int JP2_JP = 0x6a502020;
public static final int JP2_IHDR = 0x69686472;
public static final int JPIP_JPIP = 0x6a706970;
public static final int JP2_FTYP = 0x66747970;
public static final int JP2_JP2H = 0x6a703268;
public static final int JP2_COLR = 0x636f6c72;
public static final int JP2_JP2C = 0x6a703263;
public static final int JP2_URL = 0x75726c20;
public static final int JP2_DBTL = 0x6474626c;
public static final int JP2_BPCC = 0x62706363;
public static final int JP2_JP2 = 0x6a703220;
InputStream inp;
int boxLength;
int boxType;
// Constructors
Jpeg2000(Image image) {
super(image);
}
/**
* Constructs a <CODE>Jpeg2000</CODE>-object, using an <VAR>url</VAR>.
*
* @param url the <CODE>URL</CODE> where the image can be found
* @throws BadElementException on error
* @throws IOException on error
*/
public Jpeg2000(URL url) throws BadElementException, IOException {
super(url);
processParameters();
}
/**
* Constructs a <CODE>Jpeg2000</CODE>-object from memory.
*
* @param img the memory image
* @throws BadElementException on error
* @throws IOException on error
*/
public Jpeg2000(byte[] img) throws BadElementException, IOException {
super((URL) null);
rawData = img;
originalData = img;
processParameters();
}
/**
* Constructs a <CODE>Jpeg2000</CODE>-object from memory.
*
* @param img the memory image.
* @param width the width you want the image to have
* @param height the height you want the image to have
* @throws BadElementException on error
* @throws IOException on error
*/
public Jpeg2000(byte[] img, float width, float height) throws BadElementException, IOException {
this(img);
scaledWidth = width;
scaledHeight = height;
}
private int cio_read(int n) throws IOException {
int v = 0;
for (int i = n - 1; i >= 0; i--) {
v += inp.read() << (i << 3);
}
return v;
}
public void jp2_read_boxhdr() throws IOException {
boxLength = cio_read(4);
boxType = cio_read(4);
if (boxLength == 1) {
if (cio_read(4) != 0) {
throw new IOException(
MessageLocalization.getComposedMessage("cannot.handle.box.sizes.higher.than.2.32"));
}
boxLength = cio_read(4);
if (boxLength == 0) {
throw new IOException(MessageLocalization.getComposedMessage("unsupported.box.size.eq.eq.0"));
}
} else if (boxLength == 0) {
throw new IOException(MessageLocalization.getComposedMessage("unsupported.box.size.eq.eq.0"));
}
}
/**
* This method checks if the image is a valid JPEG and processes some parameters.
*
* @throws IOException on error
*/
private void processParameters() throws IOException {<FILL_FUNCTION_BODY>}
}
|
type = JPEG2000;
originalType = ORIGINAL_JPEG2000;
inp = null;
try {
String errorID;
if (rawData == null) {
inp = url.openStream();
errorID = url.toString();
} else {
inp = new java.io.ByteArrayInputStream(rawData);
errorID = "Byte array";
}
boxLength = cio_read(4);
if (boxLength == 0x0000000c) {
boxType = cio_read(4);
if (JP2_JP != boxType) {
throw new IOException(MessageLocalization.getComposedMessage("expected.jp.marker"));
}
if (0x0d0a870a != cio_read(4)) {
throw new IOException(MessageLocalization.getComposedMessage("error.with.jp.marker"));
}
jp2_read_boxhdr();
if (JP2_FTYP != boxType) {
throw new IOException(MessageLocalization.getComposedMessage("expected.ftyp.marker"));
}
Utilities.skip(inp, boxLength - 8);
jp2_read_boxhdr();
do {
if (JP2_JP2H != boxType) {
if (boxType == JP2_JP2C) {
throw new IOException(MessageLocalization.getComposedMessage("expected.jp2h.marker"));
}
Utilities.skip(inp, boxLength - 8);
jp2_read_boxhdr();
}
} while (JP2_JP2H != boxType);
jp2_read_boxhdr();
if (JP2_IHDR != boxType) {
throw new IOException(MessageLocalization.getComposedMessage("expected.ihdr.marker"));
}
scaledHeight = cio_read(4);
setTop(scaledHeight);
scaledWidth = cio_read(4);
setRight(scaledWidth);
bpc = -1;
} else if (boxLength == 0xff4fff51) {
Utilities.skip(inp, 4);
int x1 = cio_read(4);
int y1 = cio_read(4);
int x0 = cio_read(4);
int y0 = cio_read(4);
Utilities.skip(inp, 16);
colorspace = cio_read(2);
bpc = 8;
scaledHeight = y1 - y0;
setTop(scaledHeight);
scaledWidth = x1 - x0;
setRight(scaledWidth);
} else {
throw new IOException(MessageLocalization.getComposedMessage("not.a.valid.jpeg2000.file"));
}
} finally {
if (inp != null) {
try {
inp.close();
} catch (Exception e) {
}
inp = null;
}
}
plainWidth = getWidth();
plainHeight = getHeight();
| 1,053
| 817
| 1,870
|
<methods>public void <init>(java.net.URL) ,public float getAbsoluteX() ,public float getAbsoluteY() ,public com.lowagie.text.pdf.PdfDictionary getAdditional() ,public int getAlignment() ,public java.lang.String getAlt() ,public com.lowagie.text.Annotation getAnnotation() ,public int getBpc() ,public int getColorspace() ,public int getCompressionLevel() ,public com.lowagie.text.pdf.PdfIndirectReference getDirectReference() ,public int getDpiX() ,public int getDpiY() ,public java.awt.color.ICC_Profile getICCProfile() ,public com.lowagie.text.Image getImageMask() ,public float getImageRotation() ,public float getIndentationLeft() ,public float getIndentationRight() ,public float getInitialRotation() ,public static com.lowagie.text.Image getInstance(java.net.URL) throws com.lowagie.text.BadElementException, java.io.IOException,public static com.lowagie.text.Image getInstance(java.lang.String) throws com.lowagie.text.BadElementException, java.io.IOException,public static com.lowagie.text.Image getInstance(byte[]) throws com.lowagie.text.BadElementException, java.io.IOException,public static com.lowagie.text.Image getInstance(int, int, int, int, byte[]) throws com.lowagie.text.BadElementException,public static com.lowagie.text.Image getInstance(int, int, byte[], byte[]) ,public static com.lowagie.text.Image getInstance(int, int, boolean, int, int, byte[]) throws com.lowagie.text.BadElementException,public static com.lowagie.text.Image getInstance(int, int, boolean, int, int, byte[], int[]) throws com.lowagie.text.BadElementException,public static com.lowagie.text.Image getInstance(int, int, int, int, byte[], int[]) throws com.lowagie.text.BadElementException,public static com.lowagie.text.Image getInstance(com.lowagie.text.pdf.PdfTemplate) throws com.lowagie.text.BadElementException,public static com.lowagie.text.Image getInstance(java.awt.Image, java.awt.Color, boolean) throws com.lowagie.text.BadElementException, java.io.IOException,public static com.lowagie.text.Image getInstance(java.awt.Image, java.awt.Color) throws com.lowagie.text.BadElementException, java.io.IOException,public static com.lowagie.text.Image getInstance(com.lowagie.text.pdf.PdfWriter, java.awt.Image, float) throws com.lowagie.text.BadElementException, java.io.IOException,public static com.lowagie.text.Image getInstance(com.lowagie.text.pdf.PdfContentByte, java.awt.Image, float) throws com.lowagie.text.BadElementException, java.io.IOException,public static com.lowagie.text.Image getInstance(com.lowagie.text.pdf.PRIndirectReference) throws com.lowagie.text.BadElementException,public static com.lowagie.text.Image getInstance(com.lowagie.text.Image) ,public static com.lowagie.text.Image getInstanceFromClasspath(java.lang.String) throws com.lowagie.text.BadElementException, java.io.IOException,public com.lowagie.text.pdf.PdfOCG getLayer() ,public java.lang.Long getMySerialId() ,public byte[] getOriginalData() ,public int getOriginalType() ,public float getPlainHeight() ,public float getPlainWidth() ,public byte[] getRawData() ,public float getScaledHeight() ,public float getScaledWidth() ,public float getSpacingAfter() ,public float getSpacingBefore() ,public com.lowagie.text.pdf.PdfTemplate getTemplateData() ,public int[] getTransparency() ,public java.net.URL getUrl() ,public float getWidthPercentage() ,public float getXYRatio() ,public boolean hasAbsoluteX() ,public boolean hasAbsoluteY() ,public boolean hasICCProfile() ,public boolean isDeflated() ,public boolean isImgRaw() ,public boolean isImgTemplate() ,public boolean isInterpolation() ,public boolean isInverted() ,public boolean isJpeg() ,public boolean isMask() ,public boolean isMaskCandidate() ,public boolean isNestable() ,public boolean isSmask() ,public void makeMask() throws com.lowagie.text.DocumentException,public float[] matrix() ,public void scaleAbsolute(float, float) ,public void scaleAbsoluteHeight(float) ,public void scaleAbsoluteWidth(float) ,public void scalePercent(float) ,public void scalePercent(float, float) ,public void scaleToFit(float, float) ,public void setAbsolutePosition(float, float) ,public void setAdditional(com.lowagie.text.pdf.PdfDictionary) ,public void setAlignment(int) ,public void setAlt(java.lang.String) ,public void setAnnotation(com.lowagie.text.Annotation) ,public void setCompressionLevel(int) ,public void setDeflated(boolean) ,public void setDirectReference(com.lowagie.text.pdf.PdfIndirectReference) ,public void setDpi(int, int) ,public void setImageMask(com.lowagie.text.Image) throws com.lowagie.text.DocumentException,public void setIndentationLeft(float) ,public void setIndentationRight(float) ,public void setInitialRotation(float) ,public void setInterpolation(boolean) ,public void setInverted(boolean) ,public void setLayer(com.lowagie.text.pdf.PdfOCG) ,public void setOriginalData(byte[]) ,public void setOriginalType(int) ,public void setRotation(float) ,public void setRotationDegrees(float) ,public void setSmask(boolean) ,public void setSpacingAfter(float) ,public void setSpacingBefore(float) ,public void setTemplateData(com.lowagie.text.pdf.PdfTemplate) ,public void setTransparency(int[]) ,public void setUrl(java.net.URL) ,public void setWidthPercentage(float) ,public void setXYRatio(float) ,public void simplifyColorspace() ,public void tagICC(java.awt.color.ICC_Profile) ,public int type() <variables>public static final int AX,public static final int AY,public static final int BX,public static final int BY,public static final int CX,public static final int CY,public static final int DEFAULT,public static final int DX,public static final int DY,public static final int LEFT,public static final int MIDDLE,public static final int ORIGINAL_BMP,public static final int ORIGINAL_GIF,public static final int ORIGINAL_JBIG2,public static final int ORIGINAL_JPEG,public static final int ORIGINAL_JPEG2000,public static final int ORIGINAL_NONE,public static final int ORIGINAL_PNG,public static final int ORIGINAL_PS,public static final int ORIGINAL_TIFF,public static final int ORIGINAL_WMF,public static final int[] PNGID,public static final int RIGHT,public static final int TEXTWRAP,public static final int UNDERLYING,private float XYRatio,protected float absoluteX,protected float absoluteY,private com.lowagie.text.pdf.PdfDictionary additional,protected int alignment,protected java.lang.String alt,protected com.lowagie.text.Annotation annotation,protected int bpc,protected int colorspace,protected int compressionLevel,protected boolean deflated,private com.lowagie.text.pdf.PdfIndirectReference directReference,protected int dpiX,protected int dpiY,protected com.lowagie.text.Image imageMask,protected float indentationLeft,protected float indentationRight,private float initialRotation,protected boolean interpolation,protected boolean invert,protected com.lowagie.text.pdf.PdfOCG layer,protected boolean mask,protected java.lang.Long mySerialId,protected byte[] originalData,protected int originalType,protected float plainHeight,protected float plainWidth,protected java.awt.color.ICC_Profile profile,protected byte[] rawData,protected float rotationRadians,protected float scaledHeight,protected float scaledWidth,static long serialId,private boolean smask,protected float spacingAfter,protected float spacingBefore,protected com.lowagie.text.pdf.PdfTemplate[] template,protected int[] transparency,protected int type,protected java.net.URL url,private float widthPercentage
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/ListItem.java
|
ListItem
|
setIndentationLeft
|
class ListItem extends Paragraph {
// constants
private static final long serialVersionUID = 1970670787169329006L;
// member variables
/**
* this is the symbol that will precede the listitem.
*
* @since 5.0 used to be private
*/
protected Chunk symbol;
// constructors
/**
* Constructs a <CODE>ListItem</CODE>.
*/
public ListItem() {
super();
}
/**
* Constructs a <CODE>ListItem</CODE> with a certain leading.
*
* @param leading the leading
*/
public ListItem(float leading) {
super(leading);
}
/**
* Constructs a <CODE>ListItem</CODE> with a certain <CODE>Chunk</CODE>.
*
* @param chunk a <CODE>Chunk</CODE>
*/
public ListItem(Chunk chunk) {
super(chunk);
}
/**
* Constructs a <CODE>ListItem</CODE> with a certain <CODE>String</CODE>.
*
* @param string a <CODE>String</CODE>
*/
public ListItem(String string) {
super(string);
}
/**
* Constructs a <CODE>ListItem</CODE> with a certain <CODE>String</CODE> and a certain <CODE>Font</CODE>.
*
* @param string a <CODE>String</CODE>
* @param font a <CODE>String</CODE>
*/
public ListItem(String string, Font font) {
super(string, font);
}
/**
* Constructs a <CODE>ListItem</CODE> with a certain <CODE>Chunk</CODE> and a certain leading.
*
* @param leading the leading
* @param chunk a <CODE>Chunk</CODE>
*/
public ListItem(float leading, Chunk chunk) {
super(leading, chunk);
}
/**
* Constructs a <CODE>ListItem</CODE> with a certain <CODE>String</CODE> and a certain leading.
*
* @param leading the leading
* @param string a <CODE>String</CODE>
*/
public ListItem(float leading, String string) {
super(leading, string);
}
/**
* Constructs a <CODE>ListItem</CODE> with a certain leading, <CODE>String</CODE> and <CODE>Font</CODE>.
*
* @param leading the leading
* @param string a <CODE>String</CODE>
* @param font a <CODE>Font</CODE>
*/
public ListItem(float leading, String string, Font font) {
super(leading, string, font);
}
/**
* Constructs a <CODE>ListItem</CODE> with a certain <CODE>Phrase</CODE>.
*
* @param phrase a <CODE>Phrase</CODE>
*/
public ListItem(Phrase phrase) {
super(phrase);
}
// implementation of the Element-methods
/**
* Gets the type of the text element.
*
* @return a type
*/
public int type() {
return Element.LISTITEM;
}
// methods
/**
* Sets the indentation of this paragraph on the left side.
*
* @param indentation the new indentation
* @param autoindent if auto indentation, if set as <code>true</code>
* <code>indentation</code> will not be used
*/
public void setIndentationLeft(float indentation, boolean autoindent) {<FILL_FUNCTION_BODY>}
/**
* Returns the listsymbol.
*
* @return a <CODE>Chunk</CODE>
*/
public Chunk getListSymbol() {
return symbol;
}
// methods to retrieve information
/**
* Sets the listsymbol.
*
* @param symbol a <CODE>Chunk</CODE>
*/
public void setListSymbol(Chunk symbol) {
if (this.symbol == null) {
this.symbol = symbol;
if (this.symbol.getFont().isStandardFont()) {
this.symbol.setFont(font);
}
}
}
}
|
if (autoindent) {
setIndentationLeft(getListSymbol().getWidthPoint());
} else {
setIndentationLeft(indentation);
}
| 1,155
| 46
| 1,201
|
<methods>public void <init>() ,public void <init>(float) ,public void <init>(com.lowagie.text.Chunk) ,public void <init>(float, com.lowagie.text.Chunk) ,public void <init>(java.lang.String) ,public void <init>(java.lang.String, com.lowagie.text.Font) ,public void <init>(float, java.lang.String) ,public void <init>(float, java.lang.String, com.lowagie.text.Font) ,public void <init>(com.lowagie.text.Phrase) ,public boolean add(com.lowagie.text.Element) ,public int getAlignment() ,public float getExtraParagraphSpace() ,public float getFirstLineIndent() ,public float getIndentationLeft() ,public float getIndentationRight() ,public boolean getKeepTogether() ,public float getMultipliedLeading() ,public int getRunDirection() ,public float getSpacingAfter() ,public float getSpacingBefore() ,public float getTotalLeading() ,public void setAlignment(int) ,public void setAlignment(java.lang.String) ,public void setExtraParagraphSpace(float) ,public void setFirstLineIndent(float) ,public void setIndentationLeft(float) ,public void setIndentationRight(float) ,public void setKeepTogether(boolean) ,public void setLeading(float) ,public void setLeading(float, float) ,public void setMultipliedLeading(float) ,public void setRunDirection(int) ,public void setSpacingAfter(float) ,public void setSpacingBefore(float) ,public int type() <variables>protected int alignment,private float extraParagraphSpace,private float firstLineIndent,protected float indentationLeft,protected float indentationRight,protected boolean keeptogether,protected float multipliedLeading,protected int runDirection,private static final long serialVersionUID,protected float spacingAfter,protected float spacingBefore
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/MarkedObject.java
|
MarkedObject
|
process
|
class MarkedObject implements Element {
/**
* The element that is wrapped in a MarkedObject.
*/
protected Element element;
/**
* Contains extra markupAttributes
*/
protected Properties markupAttributes = new Properties();
/**
* This constructor is for internal use only.
*/
protected MarkedObject() {
element = null;
}
/**
* Creates a MarkedObject.
*
* @param element an object of type {@link Element}
*/
public MarkedObject(Element element) {
this.element = element;
}
/**
* Gets all the chunks in this element.
*
* @return an <CODE>ArrayList</CODE>
*/
public ArrayList<Element> getChunks() {
return element.getChunks();
}
/**
* Processes the element by adding it (or the different parts) to an
* <CODE>ElementListener</CODE>.
*
* @param listener an <CODE>ElementListener</CODE>
* @return <CODE>true</CODE> if the element was processed successfully
*/
public boolean process(ElementListener listener) {<FILL_FUNCTION_BODY>}
/**
* Gets the type of the text element.
*
* @return a type
*/
public int type() {
return MARKED;
}
/**
* @see com.lowagie.text.Element#isContent()
* @since iText 2.0.8
*/
public boolean isContent() {
return true;
}
/**
* @see com.lowagie.text.Element#isNestable()
* @since iText 2.0.8
*/
public boolean isNestable() {
return true;
}
/**
* Getter for the markup attributes.
*
* @return the markupAttributes
*/
public Properties getMarkupAttributes() {
return markupAttributes;
}
/**
* Adds one markup attribute.
*
* @param key attribute's key
* @param value attribute's value
*/
public void setMarkupAttribute(String key, String value) {
markupAttributes.setProperty(key, value);
}
}
|
try {
return listener.add(element);
} catch (DocumentException de) {
return false;
}
| 595
| 34
| 629
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/Meta.java
|
Meta
|
process
|
class Meta implements Element {
// membervariables
/**
* This is the type of Meta-information this object contains.
*/
private int type;
/**
* This is the content of the Meta-information.
*/
private StringBuffer content;
// constructors
/**
* Constructs a <CODE>Meta</CODE>.
*
* @param type the type of meta-information
* @param content the content
*/
Meta(int type, String content) {
this.type = type;
this.content = new StringBuffer(content);
}
/**
* Constructs a <CODE>Meta</CODE>.
*
* @param tag the tagname of the meta-information
* @param content the content
*/
public Meta(String tag, String content) {
this.type = Meta.getType(tag);
this.content = new StringBuffer(content);
}
// implementation of the Element-methods
/**
* Returns the name of the meta information.
*
* @param tag iText tag for meta information
* @return the Element value corresponding with the given tag
*/
public static int getType(String tag) {
if (ElementTags.SUBJECT.equals(tag)) {
return Element.SUBJECT;
}
if (ElementTags.KEYWORDS.equals(tag)) {
return Element.KEYWORDS;
}
if (ElementTags.AUTHOR.equals(tag)) {
return Element.AUTHOR;
}
if (ElementTags.TITLE.equals(tag)) {
return Element.TITLE;
}
if (ElementTags.PRODUCER.equals(tag)) {
return Element.PRODUCER;
}
if (ElementTags.CREATIONDATE.equals(tag)) {
return Element.CREATIONDATE;
}
return Element.HEADER;
}
/**
* Processes the element by adding it (or the different parts) to a
* <CODE>ElementListener</CODE>.
*
* @param listener the <CODE>ElementListener</CODE>
* @return <CODE>true</CODE> if the element was processed successfully
*/
public boolean process(ElementListener listener) {<FILL_FUNCTION_BODY>}
/**
* Gets the type of the text element.
*
* @return a type
*/
public int type() {
return type;
}
/**
* Gets all the chunks in this element.
*
* @return an <CODE>ArrayList</CODE>
*/
public ArrayList<Element> getChunks() {
return new ArrayList<>();
}
/**
* @see com.lowagie.text.Element#isContent()
* @since iText 2.0.8
*/
public boolean isContent() {
return false;
}
// methods
/**
* @see com.lowagie.text.Element#isNestable()
* @since iText 2.0.8
*/
public boolean isNestable() {
return false;
}
// methods to retrieve information
/**
* appends some text to this <CODE>Meta</CODE>.
*
* @param string a <CODE>String</CODE>
* @return a <CODE>StringBuffer</CODE>
*/
public StringBuffer append(String string) {
return content.append(string);
}
/**
* Returns the content of the meta information.
*
* @return a <CODE>String</CODE>
*/
public String getContent() {
return content.toString();
}
/**
* Returns the name of the meta information.
*
* @return a <CODE>String</CODE>
*/
public String getName() {
switch (type) {
case Element.SUBJECT:
return ElementTags.SUBJECT;
case Element.KEYWORDS:
return ElementTags.KEYWORDS;
case Element.AUTHOR:
return ElementTags.AUTHOR;
case Element.TITLE:
return ElementTags.TITLE;
case Element.PRODUCER:
return ElementTags.PRODUCER;
case Element.CREATIONDATE:
return ElementTags.CREATIONDATE;
default:
return ElementTags.UNKNOWN;
}
}
}
|
try {
return listener.add(this);
} catch (DocumentException de) {
return false;
}
| 1,143
| 34
| 1,177
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/RomanList.java
|
RomanList
|
add
|
class RomanList extends List {
// constructors
/**
* Initialization
*/
public RomanList() {
super(true);
}
/**
* Initialization
*
* @param symbolIndent indent
*/
public RomanList(int symbolIndent) {
super(true, symbolIndent);
}
/**
* Initialization
*
* @param lowercase roman-char in lowercase
* @param symbolIndent indent
*/
public RomanList(boolean lowercase, int symbolIndent) {
super(true, symbolIndent);
this.lowercase = lowercase;
}
// overridden methods
/**
* Adds an <CODE>Element</CODE> to the <CODE>List</CODE>.
*
* @param o the element to add.
* @return true if adding the element succeeded
*/
@Override
public boolean add(Element o) {<FILL_FUNCTION_BODY>}
/**
* Adds a <CODE>String</CODE> to the <CODE>List</CODE>.
*
* @param s the string to add.
* @return true if adding the string succeeded
*/
@Override
public boolean add(String s) {
return this.add(new ListItem(s));
}
}
|
if (o instanceof ListItem) {
ListItem item = (ListItem) o;
Chunk chunk;
chunk = new Chunk(preSymbol, symbol.getFont());
chunk.append(RomanNumberFactory.getString(first + list.size(), lowercase));
chunk.append(postSymbol);
item.setListSymbol(chunk);
item.setIndentationLeft(symbolIndent, autoindent);
item.setIndentationRight(0);
list.add(item);
} else if (o instanceof List) {
List nested = (List) o;
nested.setIndentationLeft(nested.getIndentationLeft() + symbolIndent);
first--;
return list.add(nested);
}
return false;
| 351
| 194
| 545
|
<methods>public void <init>() ,public void <init>(float) ,public void <init>(boolean) ,public void <init>(boolean, boolean) ,public void <init>(boolean, float) ,public void <init>(boolean, boolean, float) ,public boolean add(com.lowagie.text.Element) ,public boolean add(com.lowagie.text.List) ,public boolean add(java.lang.String) ,public ArrayList<com.lowagie.text.Element> getChunks() ,public int getFirst() ,public float getIndentationLeft() ,public float getIndentationRight() ,public List<com.lowagie.text.Element> getItems() ,public java.lang.String getPostSymbol() ,public java.lang.String getPreSymbol() ,public com.lowagie.text.Chunk getSymbol() ,public float getSymbolIndent() ,public float getTotalLeading() ,public boolean isAlignindent() ,public boolean isAutoindent() ,public boolean isContent() ,public boolean isEmpty() ,public boolean isLettered() ,public boolean isLowercase() ,public boolean isNestable() ,public boolean isNumbered() ,public void normalizeIndentation() ,public boolean process(com.lowagie.text.ElementListener) ,public void setAlignindent(boolean) ,public void setAutoindent(boolean) ,public void setFirst(int) ,public void setIndentationLeft(float) ,public void setIndentationRight(float) ,public void setLettered(boolean) ,public void setListSymbol(com.lowagie.text.Chunk) ,public void setListSymbol(java.lang.String) ,public void setLowercase(boolean) ,public void setNumbered(boolean) ,public void setPostSymbol(java.lang.String) ,public void setPreSymbol(java.lang.String) ,public void setSymbolIndent(float) ,public int size() ,public int type() <variables>public static final boolean ALPHABETICAL,public static final boolean LOWERCASE,public static final boolean NUMERICAL,public static final boolean ORDERED,public static final boolean UNORDERED,public static final boolean UPPERCASE,protected boolean alignindent,protected boolean autoindent,protected int first,protected float indentationLeft,protected float indentationRight,protected boolean lettered,protected List<com.lowagie.text.Element> list,protected boolean lowercase,protected boolean numbered,protected java.lang.String postSymbol,protected java.lang.String preSymbol,protected com.lowagie.text.Chunk symbol,protected float symbolIndent
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/SpecialSymbol.java
|
SpecialSymbol
|
getCorrespondingSymbol
|
class SpecialSymbol {
/**
* Returns the first occurrence of a special symbol in a <CODE>String</CODE>.
*
* @param string a <CODE>String</CODE>
* @return an index of -1 if no special symbol was found
*/
public static int index(String string) {
int length = string.length();
for (int i = 0; i < length; i++) {
if (getCorrespondingSymbol(string.charAt(i)) != ' ') {
return i;
}
}
return -1;
}
/**
* Gets a chunk with a symbol character.
*
* @param c a character that has to be changed into a symbol
* @param font Font if there is no SYMBOL character corresponding with c
* @return a SYMBOL version of a character
*/
public static Chunk get(char c, Font font) {
char greek = SpecialSymbol.getCorrespondingSymbol(c);
if (greek == ' ') {
return new Chunk(String.valueOf(c), font);
}
Font symbol = new Font(Font.SYMBOL, font.getSize(), font.getStyle(), font.getColor());
String s = String.valueOf(greek);
return new Chunk(s, symbol);
}
/**
* Looks for the corresponding symbol in the font Symbol.
*
* @param c the original ASCII-char
* @return the corresponding symbol in font Symbol
*/
public static char getCorrespondingSymbol(char c) {<FILL_FUNCTION_BODY>}
}
|
switch (c) {
case 913:
return 'A'; // ALFA
case 914:
return 'B'; // BETA
case 915:
return 'G'; // GAMMA
case 916:
return 'D'; // DELTA
case 917:
return 'E'; // EPSILON
case 918:
return 'Z'; // ZETA
case 919:
return 'H'; // ETA
case 920:
return 'Q'; // THETA
case 921:
return 'I'; // IOTA
case 922:
return 'K'; // KAPPA
case 923:
return 'L'; // LAMBDA
case 924:
return 'M'; // MU
case 925:
return 'N'; // NU
case 926:
return 'X'; // XI
case 927:
return 'O'; // OMICRON
case 928:
return 'P'; // PI
case 929:
return 'R'; // RHO
case 931:
return 'S'; // SIGMA
case 932:
return 'T'; // TAU
case 933:
return 'U'; // UPSILON
case 934:
return 'F'; // PHI
case 935:
return 'C'; // CHI
case 936:
return 'Y'; // PSI
case 937:
return 'W'; // OMEGA
case 945:
return 'a'; // alfa
case 946:
return 'b'; // beta
case 947:
return 'g'; // gamma
case 948:
return 'd'; // delta
case 949:
return 'e'; // epsilon
case 950:
return 'z'; // zeta
case 951:
return 'h'; // eta
case 952:
return 'q'; // theta
case 953:
return 'i'; // iota
case 954:
return 'k'; // kappa
case 955:
return 'l'; // lambda
case 956:
return 'm'; // mu
case 957:
return 'n'; // nu
case 958:
return 'x'; // xi
case 959:
return 'o'; // omicron
case 960:
return 'p'; // pi
case 961:
return 'r'; // rho
case 962:
return 'V'; // sigma
case 963:
return 's'; // sigma
case 964:
return 't'; // tau
case 965:
return 'u'; // upsilon
case 966:
return 'f'; // phi
case 967:
return 'c'; // chi
case 968:
return 'y'; // psi
case 969:
return 'w'; // omega
default:
return ' ';
}
| 411
| 864
| 1,275
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/ZapfDingbatsList.java
|
ZapfDingbatsList
|
add
|
class ZapfDingbatsList extends List {
/**
* char-number in zapfdingbats
*/
protected int zn;
/**
* Creates a ZapfDingbatsList
*
* @param zn a char-number
*/
public ZapfDingbatsList(int zn) {
super(true);
this.zn = zn;
float fontsize = symbol.getFont().getSize();
symbol.setFont(FontFactory.getFont(FontFactory.ZAPFDINGBATS, fontsize, Font.NORMAL));
postSymbol = " ";
}
/**
* Creates a ZapfDingbatsList
*
* @param zn a char-number
* @param symbolIndent indent
*/
public ZapfDingbatsList(int zn, int symbolIndent) {
super(true, symbolIndent);
this.zn = zn;
float fontsize = symbol.getFont().getSize();
symbol.setFont(FontFactory.getFont(FontFactory.ZAPFDINGBATS, fontsize, Font.NORMAL));
postSymbol = " ";
}
/**
* get the char-number
*
* @return char-number
*/
public int getCharNumber() {
return zn;
}
/**
* set the char-number
*
* @param zn a char-number
*/
public void setCharNumber(int zn) {
this.zn = zn;
}
/**
* Adds an <CODE>Element</CODE> to the <CODE>List</CODE>.
*
* @param o the element to add.
* @return true if adding the element succeeded
*/
@Override
public boolean add(Element o) {<FILL_FUNCTION_BODY>}
/**
* Adds a <CODE>String</CODE> to the <CODE>List</CODE>.
*
* @param s the string to add.
* @return true if adding the string succeeded
*/
@Override
public boolean add(String s) {
return this.add(new ListItem(s));
}
}
|
if (o instanceof ListItem) {
ListItem item = (ListItem) o;
Chunk chunk = new Chunk(preSymbol, symbol.getFont());
chunk.append(String.valueOf((char) zn));
chunk.append(postSymbol);
item.setListSymbol(chunk);
item.setIndentationLeft(symbolIndent, autoindent);
item.setIndentationRight(0);
list.add(item);
} else if (o instanceof List) {
List nested = (List) o;
nested.setIndentationLeft(nested.getIndentationLeft() + symbolIndent);
first--;
return list.add(nested);
}
return false;
| 582
| 184
| 766
|
<methods>public void <init>() ,public void <init>(float) ,public void <init>(boolean) ,public void <init>(boolean, boolean) ,public void <init>(boolean, float) ,public void <init>(boolean, boolean, float) ,public boolean add(com.lowagie.text.Element) ,public boolean add(com.lowagie.text.List) ,public boolean add(java.lang.String) ,public ArrayList<com.lowagie.text.Element> getChunks() ,public int getFirst() ,public float getIndentationLeft() ,public float getIndentationRight() ,public List<com.lowagie.text.Element> getItems() ,public java.lang.String getPostSymbol() ,public java.lang.String getPreSymbol() ,public com.lowagie.text.Chunk getSymbol() ,public float getSymbolIndent() ,public float getTotalLeading() ,public boolean isAlignindent() ,public boolean isAutoindent() ,public boolean isContent() ,public boolean isEmpty() ,public boolean isLettered() ,public boolean isLowercase() ,public boolean isNestable() ,public boolean isNumbered() ,public void normalizeIndentation() ,public boolean process(com.lowagie.text.ElementListener) ,public void setAlignindent(boolean) ,public void setAutoindent(boolean) ,public void setFirst(int) ,public void setIndentationLeft(float) ,public void setIndentationRight(float) ,public void setLettered(boolean) ,public void setListSymbol(com.lowagie.text.Chunk) ,public void setListSymbol(java.lang.String) ,public void setLowercase(boolean) ,public void setNumbered(boolean) ,public void setPostSymbol(java.lang.String) ,public void setPreSymbol(java.lang.String) ,public void setSymbolIndent(float) ,public int size() ,public int type() <variables>public static final boolean ALPHABETICAL,public static final boolean LOWERCASE,public static final boolean NUMERICAL,public static final boolean ORDERED,public static final boolean UNORDERED,public static final boolean UPPERCASE,protected boolean alignindent,protected boolean autoindent,protected int first,protected float indentationLeft,protected float indentationRight,protected boolean lettered,protected List<com.lowagie.text.Element> list,protected boolean lowercase,protected boolean numbered,protected java.lang.String postSymbol,protected java.lang.String preSymbol,protected com.lowagie.text.Chunk symbol,protected float symbolIndent
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/ZapfDingbatsNumberList.java
|
ZapfDingbatsNumberList
|
add
|
class ZapfDingbatsNumberList extends List {
/**
* which type
*/
protected int type;
/**
* Creates a ZapdDingbatsNumberList
*
* @param type the type of list
*/
public ZapfDingbatsNumberList(int type) {
super(true);
this.type = type;
float fontsize = symbol.getFont().getSize();
symbol.setFont(FontFactory.getFont(FontFactory.ZAPFDINGBATS, fontsize, Font.NORMAL));
postSymbol = " ";
}
/**
* Creates a ZapdDingbatsNumberList
*
* @param type the type of list
* @param symbolIndent indent
*/
public ZapfDingbatsNumberList(int type, int symbolIndent) {
super(true, symbolIndent);
this.type = type;
float fontsize = symbol.getFont().getSize();
symbol.setFont(FontFactory.getFont(FontFactory.ZAPFDINGBATS, fontsize, Font.NORMAL));
postSymbol = " ";
}
/**
* get the type
*
* @return char-number
*/
public int getType() {
return type;
}
/**
* set the type
*
* @param type {@link ZapfDingbatsNumberList#type}
*/
public void setType(int type) {
this.type = type;
}
/**
* Adds an <CODE>Element</CODE> to the <CODE>List</CODE>.
*
* @param o the element to add.
* @return true if adding the element succeeded
*/
@Override
public boolean add(Element o) {<FILL_FUNCTION_BODY>}
/**
* Adds a <CODE>String</CODE> to the <CODE>List</CODE>.
*
* @param s the string to add.
* @return true if adding the string succeeded
*/
@Override
public boolean add(String s) {
return this.add(new ListItem(s));
}
}
|
if (o instanceof ListItem) {
ListItem item = (ListItem) o;
Chunk chunk = new Chunk(preSymbol, symbol.getFont());
switch (type) {
case 0:
chunk.append(String.valueOf((char) (first + list.size() + 171)));
break;
case 1:
chunk.append(String.valueOf((char) (first + list.size() + 181)));
break;
case 2:
chunk.append(String.valueOf((char) (first + list.size() + 191)));
break;
default:
chunk.append(String.valueOf((char) (first + list.size() + 201)));
}
chunk.append(postSymbol);
item.setListSymbol(chunk);
item.setIndentationLeft(symbolIndent, autoindent);
item.setIndentationRight(0);
list.add(item);
} else if (o instanceof List) {
List nested = (List) o;
nested.setIndentationLeft(nested.getIndentationLeft() + symbolIndent);
first--;
return list.add(nested);
}
return false;
| 568
| 312
| 880
|
<methods>public void <init>() ,public void <init>(float) ,public void <init>(boolean) ,public void <init>(boolean, boolean) ,public void <init>(boolean, float) ,public void <init>(boolean, boolean, float) ,public boolean add(com.lowagie.text.Element) ,public boolean add(com.lowagie.text.List) ,public boolean add(java.lang.String) ,public ArrayList<com.lowagie.text.Element> getChunks() ,public int getFirst() ,public float getIndentationLeft() ,public float getIndentationRight() ,public List<com.lowagie.text.Element> getItems() ,public java.lang.String getPostSymbol() ,public java.lang.String getPreSymbol() ,public com.lowagie.text.Chunk getSymbol() ,public float getSymbolIndent() ,public float getTotalLeading() ,public boolean isAlignindent() ,public boolean isAutoindent() ,public boolean isContent() ,public boolean isEmpty() ,public boolean isLettered() ,public boolean isLowercase() ,public boolean isNestable() ,public boolean isNumbered() ,public void normalizeIndentation() ,public boolean process(com.lowagie.text.ElementListener) ,public void setAlignindent(boolean) ,public void setAutoindent(boolean) ,public void setFirst(int) ,public void setIndentationLeft(float) ,public void setIndentationRight(float) ,public void setLettered(boolean) ,public void setListSymbol(com.lowagie.text.Chunk) ,public void setListSymbol(java.lang.String) ,public void setLowercase(boolean) ,public void setNumbered(boolean) ,public void setPostSymbol(java.lang.String) ,public void setPreSymbol(java.lang.String) ,public void setSymbolIndent(float) ,public int size() ,public int type() <variables>public static final boolean ALPHABETICAL,public static final boolean LOWERCASE,public static final boolean NUMERICAL,public static final boolean ORDERED,public static final boolean UNORDERED,public static final boolean UPPERCASE,protected boolean alignindent,protected boolean autoindent,protected int first,protected float indentationLeft,protected float indentationRight,protected boolean lettered,protected List<com.lowagie.text.Element> list,protected boolean lowercase,protected boolean numbered,protected java.lang.String postSymbol,protected java.lang.String preSymbol,protected com.lowagie.text.Chunk symbol,protected float symbolIndent
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/error_messages/MessageLocalization.java
|
MessageLocalization
|
getLanguageMessages
|
class MessageLocalization {
private static final String BASE_PATH = "com/lowagie/text/error_messages/";
private static Map<String, String> defaultLanguage = new HashMap<>();
private static Map<String, String> currentLanguage;
static {
try {
defaultLanguage = getLanguageMessages("en", null);
} catch (Exception ex) {
// do nothing
}
if (defaultLanguage == null) {
defaultLanguage = new HashMap<>();
}
}
private MessageLocalization() {
}
/**
* Get a message without parameters.
*
* @param key the key to the message
* @return the message
*/
public static String getMessage(String key) {
Map<String, String> cl = currentLanguage;
String val;
if (cl != null) {
val = cl.get(key);
if (val != null) {
return val;
}
}
cl = defaultLanguage;
val = cl.get(key);
if (val != null) {
return val;
}
return "No message found for " + key;
}
/**
* Get a message without parameters.
*
* @param key the key to the message
* @return the message
*/
public static String getComposedMessage(String key) {
return getComposedMessage(key, null, null, null, null);
}
/**
* Get a message with one parameter. The parameter will replace the string "{1}" found in the message.
*
* @param key the key to the message
* @param p1 the parameter
* @return the message
*/
public static String getComposedMessage(String key, Object p1) {
return getComposedMessage(key, p1, null, null, null);
}
/**
* Get a message with one parameter. The parameter will replace the string "{1}" found in the message.
*
* @param key the key to the message
* @param p1 the parameter
* @return the message
*/
public static String getComposedMessage(String key, int p1) {
return getComposedMessage(key, String.valueOf(p1), null, null, null);
}
/**
* Get a message with one parameter. The parameter will replace the string "{1}", "{2}" found in the message.
*
* @param key the key to the message
* @param p1 the parameter
* @param p2 the parameter
* @return the message
*/
public static String getComposedMessage(String key, Object p1, Object p2) {
return getComposedMessage(key, p1, p2, null, null);
}
/**
* Get a message with one parameter. The parameter will replace the string "{1}", "{2}", "{3}" found in the
* message.
*
* @param key the key to the message
* @param p1 the parameter
* @param p2 the parameter
* @param p3 the parameter
* @return the message
*/
public static String getComposedMessage(String key, Object p1, Object p2, Object p3) {
return getComposedMessage(key, p1, p2, p3, null);
}
/**
* Get a message with two parameters. The parameters will replace the strings "{1}", "{2}", "{3}", "{4}" found in
* the message.
*
* @param key the key to the message
* @param p1 the parameter
* @param p2 the parameter
* @param p3 the parameter
* @param p4 the parameter
* @return the message
*/
public static String getComposedMessage(String key, Object p1, Object p2, Object p3, Object p4) {
String msg = getMessage(key);
if (p1 != null) {
msg = msg.replace("{1}", p1.toString());
}
if (p2 != null) {
msg = msg.replace("{2}", p2.toString());
}
if (p3 != null) {
msg = msg.replace("{3}", p3.toString());
}
if (p4 != null) {
msg = msg.replace("{4}", p4.toString());
}
return msg;
}
/**
* Sets the language to be used globally for the error messages. The language is a two letter lowercase country
* designation like "en" or "pt". The country is an optional two letter uppercase code like "US" or "PT".
*
* @param language the language
* @param country the country
* @return true if the language was found, false otherwise
* @throws IOException on error
*/
public static boolean setLanguage(String language, String country) throws IOException {
Map<String, String> lang = getLanguageMessages(language, country);
if (lang == null) {
return false;
}
currentLanguage = lang;
return true;
}
/**
* Sets the error messages directly from a Reader.
*
* @param r the Reader
* @throws IOException on error
*/
public static void setMessages(Reader r) throws IOException {
currentLanguage = readLanguageStream(r);
}
private static Map<String, String> getLanguageMessages(String language, String country) throws IOException {<FILL_FUNCTION_BODY>}
private static Map<String, String> readLanguageStream(InputStream is) throws IOException {
return readLanguageStream(new InputStreamReader(is, StandardCharsets.UTF_8));
}
private static Map<String, String> readLanguageStream(Reader r) throws IOException {
Map<String, String> lang = new HashMap<>();
BufferedReader br = new BufferedReader(r);
String line;
while ((line = br.readLine()) != null) {
int idxeq = line.indexOf('=');
if (idxeq < 0) {
continue;
}
String key = line.substring(0, idxeq).trim();
if (key.startsWith("#")) {
continue;
}
lang.put(key, line.substring(idxeq + 1));
}
return lang;
}
// For tests only
public static Set<String> getAllKeys() {
return defaultLanguage.keySet();
}
}
|
if (language == null) {
throw new IllegalArgumentException("The language cannot be null.");
}
InputStream is = null;
try {
String file;
if (country != null) {
file = language + "_" + country + ".lng";
} else {
file = language + ".lng";
}
is = BaseFont.getResourceStream(BASE_PATH + file, MessageLocalization.class.getClassLoader());
if (is != null) {
return readLanguageStream(is);
}
if (country == null) {
return null;
}
file = language + ".lng";
is = BaseFont.getResourceStream(BASE_PATH + file, MessageLocalization.class.getClassLoader());
if (is != null) {
return readLanguageStream(is);
} else {
return null;
}
} finally {
try {
if (is != null) {
is.close();
}
} catch (Exception ignored) {
// do nothing
}
}
| 1,651
| 271
| 1,922
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/factories/GreekAlphabetFactory.java
|
GreekAlphabetFactory
|
getString
|
class GreekAlphabetFactory {
/**
* Changes an int into a lower case Greek letter combination.
*
* @param index the original number
* @return the letter combination
*/
public static final String getString(int index) {
return getString(index, true);
}
/**
* Changes an int into a lower case Greek letter combination.
*
* @param index the original number
* @return the letter combination
*/
public static final String getLowerCaseString(int index) {
return getString(index);
}
/**
* Changes an int into a upper case Greek letter combination.
*
* @param index the original number
* @return the letter combination
*/
public static final String getUpperCaseString(int index) {
return getString(index).toUpperCase();
}
/**
* Changes an int into a Greek letter combination.
*
* @param index the original number
* @param lowercase true for lowercase, false for uppercase
* @return the letter combination
*/
public static final String getString(int index, boolean lowercase) {<FILL_FUNCTION_BODY>}
}
|
if (index < 1) {
return "";
}
index--;
int bytes = 1;
int start = 0;
int symbols = 24;
while (index >= symbols + start) {
bytes++;
start += symbols;
symbols *= 24;
}
int c = index - start;
char[] value = new char[bytes];
while (bytes > 0) {
bytes--;
value[bytes] = (char) (c % 24);
if (value[bytes] > 16) {
value[bytes]++;
}
value[bytes] += (lowercase ? 945 : 913);
value[bytes] = SpecialSymbol.getCorrespondingSymbol(value[bytes]);
c /= 24;
}
return String.valueOf(value);
| 305
| 220
| 525
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/factories/RomanAlphabetFactory.java
|
RomanAlphabetFactory
|
getString
|
class RomanAlphabetFactory {
/**
* Translates a positive integer (not equal to zero) into a String using the letters 'a' to 'z'; 1 = a, 2 = b, ...,
* 26 = z, 27 = aa, 28 = ab,...
*
* @param index the integer to translate
* @return the lowercase String representing the integer
*/
public static final String getString(int index) {<FILL_FUNCTION_BODY>}
/**
* Translates a positive integer (not equal to zero) into a String using the letters 'a' to 'z'; 1 = a, 2 = b, ...,
* 26 = z, 27 = aa, 28 = ab,...
*
* @param index the number to translate
* @return the lowercase String representing the integer
*/
public static final String getLowerCaseString(int index) {
return getString(index);
}
/**
* Translates a positive integer (not equal to zero) into a String using the letters 'A' to 'Z'; 1 = A, 2 = B, ...,
* 26 = Z, 27 = AA, 28 = AB,...
*
* @param index the number to translate
* @return the uppercase String representing the integer
*/
public static final String getUpperCaseString(int index) {
return getString(index).toUpperCase();
}
/**
* Translates a positive integer (not equal to zero) into a String using the letters 'a' to 'z' (a = 1, b = 2, ...,
* z = 26, aa = 27, ab = 28,...).
*
* @param index the number to translate
* @param lowercase true for lowercase, false for uppercase
* @return the lowercase String representing the integer
*/
public static final String getString(int index, boolean lowercase) {
if (lowercase) {
return getLowerCaseString(index);
} else {
return getUpperCaseString(index);
}
}
}
|
if (index < 1) {
throw new NumberFormatException(MessageLocalization.getComposedMessage(
"you.can.t.translate.a.negative.number.into.an.alphabetical.value"));
}
index--;
int bytes = 1;
int start = 0;
int symbols = 26;
while (index >= symbols + start) {
bytes++;
start += symbols;
symbols *= 26;
}
int c = index - start;
char[] value = new char[bytes];
while (bytes > 0) {
value[--bytes] = (char) ('a' + (c % 26));
c /= 26;
}
return new String(value);
| 541
| 192
| 733
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/factories/RomanNumberFactory.java
|
RomanNumberFactory
|
getString
|
class RomanNumberFactory {
/**
* Array with Roman digits.
*/
private static final RomanDigit[] roman = {
new RomanDigit('m', 1000, false),
new RomanDigit('d', 500, false),
new RomanDigit('c', 100, true),
new RomanDigit('l', 50, false),
new RomanDigit('x', 10, true),
new RomanDigit('v', 5, false),
new RomanDigit('i', 1, true)
};
/**
* Changes an int into a lower case roman number.
*
* @param index the original number
* @return the roman number (lower case)
*/
public static String getString(int index) {<FILL_FUNCTION_BODY>}
/**
* Changes an int into a lower case roman number.
*
* @param index the original number
* @return the roman number (lower case)
*/
public static String getLowerCaseString(int index) {
return getString(index);
}
/**
* Changes an int into an upper case roman number.
*
* @param index the original number
* @return the roman number (lower case)
*/
public static String getUpperCaseString(int index) {
return getString(index).toUpperCase();
}
/**
* Changes an int into a roman number.
*
* @param index the original number
* @param lowercase true for lowercase, false for uppercase
* @return the roman number (lower case)
*/
public static String getString(int index, boolean lowercase) {
if (lowercase) {
return getLowerCaseString(index);
} else {
return getUpperCaseString(index);
}
}
/**
* Helper class for Roman Digits
*/
private static class RomanDigit {
/**
* part of a roman number
*/
public char digit;
/**
* value of the roman digit
*/
public int value;
/**
* can the digit be used as a prefix
*/
public boolean pre;
/**
* Constructs a roman digit
*
* @param digit the roman digit
* @param value the value
* @param pre can it be used as a prefix
*/
RomanDigit(char digit, int value, boolean pre) {
this.digit = digit;
this.value = value;
this.pre = pre;
}
}
}
|
StringBuilder buf = new StringBuilder();
// lower than 0 ? Add minus
if (index < 0) {
buf.append('-');
index = -index;
}
// greater than 3000
if (index > 3000) {
buf.append('|');
buf.append(getString(index / 1000));
buf.append('|');
// remainder
index = index - (index / 1000) * 1000;
}
// number between 1 and 3000
int pos = 0;
while (true) {
// loop over the array with values for m-d-c-l-x-v-i
RomanDigit dig = roman[pos];
// adding as many digits as we can
while (index >= dig.value) {
buf.append(dig.digit);
index -= dig.value;
}
// we have the complete number
if (index <= 0) {
break;
}
// look for the next digit that can be used in a special way
int j = pos;
while (!roman[++j].pre) {
// find j
}
// does the special notation apply?
if (index + roman[j].value >= dig.value) {
buf.append(roman[j].digit).append(dig.digit);
index -= dig.value - roman[j].value;
}
pos++;
}
return buf.toString();
| 666
| 391
| 1,057
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/html/HtmlEncoder.java
|
HtmlEncoder
|
encode
|
class HtmlEncoder {
// membervariables
/**
* List with the HTML translation of all the characters.
*/
private static final String[] htmlCode = new String[256];
static {
for (int i = 0; i < 10; i++) {
htmlCode[i] = "�" + i + ";";
}
for (int i = 10; i < 32; i++) {
htmlCode[i] = "�" + i + ";";
}
for (int i = 32; i < 128; i++) {
htmlCode[i] = String.valueOf((char) i);
}
// Special characters
htmlCode['\t'] = "\t";
htmlCode['\n'] = "<" + HtmlTags.NEWLINE + " />\n";
htmlCode['\"'] = """; // double quote
htmlCode['&'] = "&"; // ampersand
htmlCode['<'] = "<"; // lower than
htmlCode['>'] = ">"; // greater than
for (int i = 128; i < 256; i++) {
htmlCode[i] = "&#" + i + ";";
}
}
// constructors
/**
* This class will never be constructed.
* <p>
* HtmlEncoder only contains static methods.
*/
private HtmlEncoder() {
}
// methods
/**
* Converts a <CODE>String</CODE> to the HTML-format of this <CODE>String</CODE>.
*
* @param string The <CODE>String</CODE> to convert
* @return a <CODE>String</CODE>
*/
public static String encode(String string) {<FILL_FUNCTION_BODY>}
/**
* Converts a <CODE>Color</CODE> into a HTML representation of this <CODE>Color</CODE>.
*
* @param color the <CODE>Color</CODE> that has to be converted.
* @return the HTML representation of this <CODE>Color</CODE>
*/
public static String encode(Color color) {
StringBuilder buffer = new StringBuilder("#");
if (color.getRed() < 16) {
buffer.append('0');
}
buffer.append(Integer.toString(color.getRed(), 16));
if (color.getGreen() < 16) {
buffer.append('0');
}
buffer.append(Integer.toString(color.getGreen(), 16));
if (color.getBlue() < 16) {
buffer.append('0');
}
buffer.append(Integer.toString(color.getBlue(), 16));
return buffer.toString();
}
/**
* Translates the alignment value.
*
* @param alignment the alignment value
* @return the translated value
*/
public static String getAlignment(int alignment) {
switch (alignment) {
case Element.ALIGN_LEFT:
return HtmlTags.ALIGN_LEFT;
case Element.ALIGN_CENTER:
return HtmlTags.ALIGN_CENTER;
case Element.ALIGN_RIGHT:
return HtmlTags.ALIGN_RIGHT;
case Element.ALIGN_JUSTIFIED:
case Element.ALIGN_JUSTIFIED_ALL:
return HtmlTags.ALIGN_JUSTIFIED;
case Element.ALIGN_TOP:
return HtmlTags.ALIGN_TOP;
case Element.ALIGN_MIDDLE:
return HtmlTags.ALIGN_MIDDLE;
case Element.ALIGN_BOTTOM:
return HtmlTags.ALIGN_BOTTOM;
case Element.ALIGN_BASELINE:
return HtmlTags.ALIGN_BASELINE;
default:
return "";
}
}
}
|
int n = string.length();
char character;
StringBuilder buffer = new StringBuilder();
// loop over all the characters of the String.
for (int i = 0; i < n; i++) {
character = string.charAt(i);
// the Htmlcode of these characters are added to a StringBuffer one by one
if (character < 256) {
buffer.append(htmlCode[character]);
} else {
// Improvement posted by Joachim Eyrich
buffer.append("&#").append((int) character).append(';');
}
}
return buffer.toString();
| 1,022
| 158
| 1,180
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/html/HtmlParser.java
|
HtmlParser
|
go
|
class HtmlParser extends XmlParser {
/**
* Parses a given file that validates with the iText DTD and writes the content to a document.
*
* @param document the document the parser will write to
* @param is the InputSource with the content
*/
public static void parse(DocListener document, InputSource is) {
HtmlParser parser = new HtmlParser();
parser.go(document, is);
}
/**
* Parses a given file that validates with the iText DTD and writes the content to a document.
*
* @param document the document the parser will write to
* @param file the file with the content
*/
public static void parse(DocListener document, String file) {
HtmlParser parser = new HtmlParser();
parser.go(document, file);
}
/**
* Parses a given file that validates with the iText DTD and writes the content to a document.
*
* @param document the document the parser will write to
* @param is the InputStream with the content
*/
public static void parse(DocListener document, InputStream is) {
HtmlParser parser = new HtmlParser();
parser.go(document, new InputSource(is));
}
/**
* Parses a given file that validates with the iText DTD and writes the content to a document.
*
* @param document the document the parser will write to
* @param is the Reader with the content
*/
public static void parse(DocListener document, Reader is) {
HtmlParser parser = new HtmlParser();
parser.go(document, new InputSource(is));
}
/**
* Parses a given file.
*
* @param document the document the parser will write to
* @param is the InputSource with the content
*/
@Override
public void go(DocListener document, InputSource is) {<FILL_FUNCTION_BODY>}
/**
* Parses a given file.
*
* @param document the document the parser will write to
* @param file the file with the content
*/
@Override
public void go(DocListener document, String file) {
try {
parser.parse(file, new SAXmyHtmlHandler(document));
} catch (SAXException | IOException se) {
throw new ExceptionConverter(se);
}
}
/**
* Parses a given file.
*
* @param document the document the parser will write to
* @param is the InputStream with the content
*/
public void go(DocListener document, InputStream is) {
try {
parser.parse(new InputSource(is), new SAXmyHtmlHandler(document));
} catch (SAXException | IOException se) {
throw new ExceptionConverter(se);
}
}
/**
* Parses a given file.
*
* @param document the document the parser will write to
* @param is the Reader with the content
*/
public void go(DocListener document, Reader is) {
try {
parser.parse(new InputSource(is), new SAXmyHtmlHandler(document));
} catch (SAXException | IOException se) {
throw new ExceptionConverter(se);
}
}
}
|
try {
parser.parse(is, new SAXmyHtmlHandler(document));
} catch (SAXException | IOException se) {
throw new ExceptionConverter(se);
}
| 846
| 49
| 895
|
<methods>public void <init>() ,public void go(com.lowagie.text.DocListener, org.xml.sax.InputSource) ,public void go(com.lowagie.text.DocListener, org.xml.sax.InputSource, java.lang.String) ,public void go(com.lowagie.text.DocListener, org.xml.sax.InputSource, java.io.InputStream) ,public void go(com.lowagie.text.DocListener, org.xml.sax.InputSource, Map<java.lang.String,com.lowagie.text.xml.XmlPeer>) ,public void go(com.lowagie.text.DocListener, java.lang.String) ,public void go(com.lowagie.text.DocListener, java.lang.String, java.lang.String) ,public void go(com.lowagie.text.DocListener, java.lang.String, Map<java.lang.String,com.lowagie.text.xml.XmlPeer>) ,public static void parse(com.lowagie.text.DocListener, org.xml.sax.InputSource) ,public static void parse(com.lowagie.text.DocListener, org.xml.sax.InputSource, java.lang.String) ,public static void parse(com.lowagie.text.DocListener, org.xml.sax.InputSource, Map<java.lang.String,com.lowagie.text.xml.XmlPeer>) ,public static void parse(com.lowagie.text.DocListener, java.lang.String) ,public static void parse(com.lowagie.text.DocListener, java.lang.String, java.lang.String) ,public static void parse(com.lowagie.text.DocListener, java.lang.String, Map<java.lang.String,com.lowagie.text.xml.XmlPeer>) ,public static void parse(com.lowagie.text.DocListener, java.io.InputStream) ,public static void parse(com.lowagie.text.DocListener, java.io.InputStream, java.lang.String) ,public static void parse(com.lowagie.text.DocListener, java.io.InputStream, Map<java.lang.String,com.lowagie.text.xml.XmlPeer>) ,public static void parse(com.lowagie.text.DocListener, java.io.Reader) ,public static void parse(com.lowagie.text.DocListener, java.io.Reader, java.lang.String) ,public static void parse(com.lowagie.text.DocListener, java.io.Reader, Map<java.lang.String,com.lowagie.text.xml.XmlPeer>) <variables>protected javax.xml.parsers.SAXParser parser
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/html/HtmlPeer.java
|
HtmlPeer
|
getAttributes
|
class HtmlPeer extends XmlPeer {
/**
* Creates a XmlPeer.
*
* @param name the iText name of the tag
* @param alias the Html name of the tag
*/
public HtmlPeer(String name, String alias) {
super(name, alias.toLowerCase());
}
/**
* Sets an alias for an attribute.
*
* @param name the iText tagname
* @param alias the custom tagname
*/
public void addAlias(String name, String alias) {
attributeAliases.put(alias.toLowerCase(), name);
}
/**
* @see com.lowagie.text.xml.XmlPeer#getAttributes(org.xml.sax.Attributes)
*/
public Properties getAttributes(Attributes attrs) {<FILL_FUNCTION_BODY>}
}
|
Properties attributes = new Properties();
attributes.putAll(attributeValues);
if (defaultContent != null) {
attributes.put(ElementTags.ITEXT, defaultContent);
}
if (attrs != null) {
String attribute, value;
for (int i = 0; i < attrs.getLength(); i++) {
attribute = getName(attrs.getQName(i).toLowerCase());
value = attrs.getValue(i);
attributes.setProperty(attribute, value);
}
}
return attributes;
| 232
| 142
| 374
|
<methods>public void <init>(java.lang.String, java.lang.String) ,public void addAlias(java.lang.String, java.lang.String) ,public void addValue(java.lang.String, java.lang.String) ,public java.lang.String getAlias() ,public java.util.Properties getAttributes(org.xml.sax.Attributes) ,public java.util.Properties getDefaultValues() ,public java.lang.String getName(java.lang.String) ,public java.lang.String getTag() ,public void setContent(java.lang.String) <variables>protected java.util.Properties attributeAliases,protected java.util.Properties attributeValues,protected java.lang.String customTagname,protected java.lang.String defaultContent,protected java.lang.String tagname
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/html/SAXmyHtmlHandler.java
|
SAXmyHtmlHandler
|
startElement
|
class SAXmyHtmlHandler extends SAXiTextHandler<HtmlPeer> {
// SAXmyHandler
/**
* These are the properties of the body section.
*/
private final Properties bodyAttributes = new Properties();
/**
* This is the status of the table border.
*/
private boolean tableBorder = false;
/**
* Constructs a new SAXiTextHandler that will translate all the events triggered by the parser to actions on the
* <CODE>Document</CODE>-object.
*
* @param document this is the document on which events must be triggered
*/
public SAXmyHtmlHandler(DocListener document) {
this(document, new HtmlTagMap());
}
/**
* Constructs a new SAXiTextHandler that will translate all the events triggered by the parser to actions on the
* <CODE>Document</CODE>-object.
*
* @param document this is the document on which events must be triggered
* @param htmlTags a tagmap translating HTML tags to iText tags
*/
public SAXmyHtmlHandler(DocListener document, HtmlTagMap htmlTags) {
this(document, htmlTags, null);
}
public SAXmyHtmlHandler(DocListener document, HtmlTagMap htmlTags, BaseFont bf) {
super(document, htmlTags, bf);
}
/**
* Constructs a new SAXiTextHandler that will translate all the events triggered by the parser to actions on the
* <CODE>Document</CODE>-object.
*
* @param document this is the document on which events must be triggered
* @param bf the base class for the supported fonts
*/
public SAXmyHtmlHandler(DocListener document, BaseFont bf) {
this(document, new HtmlTagMap(), bf);
}
/**
* This method gets called when a start tag is encountered.
*
* @param uri the Uniform Resource Identifier
* @param localName the local name (without prefix), or the empty string if Namespace processing is not being
* performed.
* @param name the name of the tag that is encountered
* @param attrs the list of attributes
*/
@Override
public void startElement(String uri, String localName, String name, Attributes attrs) {<FILL_FUNCTION_BODY>}
/**
* This method gets called when an end tag is encountered.
*
* @param uri the Uniform Resource Identifier
* @param localName the local name (without prefix), or the empty string if Namespace processing is not being
* performed.
* @param name the name of the tag that ends
*/
@Override
public void endElement(String uri, String localName, String name) {
String lowerCaseName = name.toLowerCase();
if (ElementTags.PARAGRAPH.equals(lowerCaseName)) {
try {
document.add(stack.pop());
return;
} catch (DocumentException e) {
throw new ExceptionConverter(e);
}
}
if (HtmlTagMap.isHead(lowerCaseName)) {
// we do nothing
return;
}
if (HtmlTagMap.isTitle(lowerCaseName)) {
if (currentChunk != null) {
bodyAttributes.put(ElementTags.TITLE, currentChunk.getContent());
currentChunk = null;
}
return;
}
if (HtmlTagMap.isMeta(lowerCaseName)) {
// we do nothing
return;
}
if (HtmlTagMap.isLink(lowerCaseName)) {
// we do nothing
return;
}
if (HtmlTagMap.isBody(lowerCaseName)) {
// we do nothing
return;
}
if (myTags.containsKey(lowerCaseName)) {
HtmlPeer peer = myTags.get(lowerCaseName);
if (ElementTags.TABLE.equals(peer.getTag())) {
tableBorder = false;
}
super.handleEndingTags(peer.getTag());
return;
}
// super.handleEndingTags is replaced with handleEndingTags
// suggestion by Ken Auer
handleEndingTags(lowerCaseName);
}
}
|
// super.handleStartingTags is replaced with handleStartingTags
// suggestion by Vu Ngoc Tan/Hop
String lowerCaseName = name.toLowerCase();
if (HtmlTagMap.isHtml(lowerCaseName)) {
// we do nothing
return;
}
if (HtmlTagMap.isHead(lowerCaseName)) {
// we do nothing
return;
}
if (HtmlTagMap.isTitle(lowerCaseName)) {
// we do nothing
return;
}
if (HtmlTagMap.isMeta(lowerCaseName)) {
// we look if we can change the body attributes
String meta = null;
String content = null;
if (attrs != null) {
for (int i = 0; i < attrs.getLength(); i++) {
String attribute = attrs.getQName(i);
if (attribute.equalsIgnoreCase(HtmlTags.CONTENT)) {
content = attrs.getValue(i);
} else if (attribute.equalsIgnoreCase(HtmlTags.NAME)) {
meta = attrs.getValue(i);
}
}
}
if (meta != null && content != null) {
bodyAttributes.put(meta, content);
}
return;
}
if (HtmlTagMap.isLink(lowerCaseName)) {
// we do nothing for the moment, in a later version we could extract
// the style sheet
return;
}
if (HtmlTagMap.isBody(lowerCaseName)) {
// maybe we could extract some info about the document: color,
// margins,...
// but that's for a later version...
HtmlPeer peer = new HtmlPeer(ElementTags.ITEXT, lowerCaseName);
peer.addAlias(ElementTags.TOP, HtmlTags.TOPMARGIN);
peer.addAlias(ElementTags.BOTTOM, HtmlTags.BOTTOMMARGIN);
peer.addAlias(ElementTags.RIGHT, HtmlTags.RIGHTMARGIN);
peer.addAlias(ElementTags.LEFT, HtmlTags.LEFTMARGIN);
bodyAttributes.putAll(peer.getAttributes(attrs));
handleStartingTags(peer.getTag(), bodyAttributes);
return;
}
if (myTags.containsKey(lowerCaseName)) {
HtmlPeer peer = myTags.get(lowerCaseName);
if (ElementTags.TABLE.equals(peer.getTag()) || ElementTags.CELL.equals(peer.getTag())) {
Properties p = peer.getAttributes(attrs);
String value;
if (ElementTags.TABLE.equals(peer.getTag())
&& (value = p.getProperty(ElementTags.BORDERWIDTH)) != null) {
if (Float.parseFloat(value + "f") > 0) {
tableBorder = true;
}
}
if (tableBorder) {
p.put(ElementTags.LEFT, String.valueOf(true));
p.put(ElementTags.RIGHT, String.valueOf(true));
p.put(ElementTags.TOP, String.valueOf(true));
p.put(ElementTags.BOTTOM, String.valueOf(true));
}
handleStartingTags(peer.getTag(), p);
return;
}
handleStartingTags(peer.getTag(), peer.getAttributes(attrs));
return;
}
Properties attributes = new Properties();
if (attrs != null) {
for (int i = 0; i < attrs.getLength(); i++) {
String attribute = attrs.getQName(i).toLowerCase();
attributes.setProperty(attribute, attrs.getValue(i).toLowerCase());
}
}
handleStartingTags(lowerCaseName, attributes);
| 1,072
| 966
| 2,038
|
<methods>public void <init>(com.lowagie.text.DocListener) ,public void <init>(com.lowagie.text.DocListener, Map<java.lang.String,com.lowagie.text.html.HtmlPeer>, com.lowagie.text.pdf.BaseFont) ,public void <init>(com.lowagie.text.DocListener, Map<java.lang.String,com.lowagie.text.html.HtmlPeer>) ,public void characters(char[], int, int) ,public void endElement(java.lang.String, java.lang.String, java.lang.String) ,public void handleEndingTags(java.lang.String) ,public void handleStartingTags(java.lang.String, java.util.Properties) ,public void ignorableWhitespace(char[], int, int) ,public void setBaseFont(com.lowagie.text.pdf.BaseFont) ,public void setControlOpenClose(boolean) ,public void startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) <variables>private com.lowagie.text.pdf.BaseFont bf,private float bottomMargin,protected int chapters,private boolean controlOpenClose,protected com.lowagie.text.Chunk currentChunk,protected com.lowagie.text.DocListener document,protected boolean ignore,private float leftMargin,protected Map<java.lang.String,com.lowagie.text.html.HtmlPeer> myTags,private float rightMargin,protected Stack<com.lowagie.text.Element> stack,private float topMargin
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/html/simpleparser/ChainedProperties.java
|
ChainedProperties
|
addToChain
|
class ChainedProperties {
public final static int[] fontSizes = {8, 10, 12, 14, 18, 24, 36};
/**
* Will be replaced with types alternative
*/
public ArrayList<Object[]> chain = new ArrayList<>();
/**
* Creates a new instance of ChainedProperties
*/
public ChainedProperties() {
}
public String getProperty(String key) {
return findProperty(key).orElse(null);
}
/**
* Try find property by its name
*
* @param key property name
* @return {@link Optional} containing the value or {@link Optional#empty()} if there is no value or it equals
* {@code null}
*/
public Optional<String> findProperty(String key) {
for (int k = chain.size() - 1; k >= 0; --k) {
Object[] obj = chain.get(k);
HashMap prop = (HashMap) obj[1];
String ret = (String) prop.get(key);
if (ret != null) {
return Optional.of(ret);
}
}
return Optional.empty();
}
/**
* Get property by its name or return default value when property is not present or is <CODE>null</CODE>
*
* @param key property name
* @param defaultValue default property value
* @return property or default value if it's null
*/
public String getOrDefault(String key, String defaultValue) {
return findProperty(key).orElse(defaultValue);
}
public boolean hasProperty(String key) {
for (int k = chain.size() - 1; k >= 0; --k) {
Object[] obj = (Object[]) chain.get(k);
HashMap prop = (HashMap) obj[1];
if (prop.containsKey(key)) {
return true;
}
}
return false;
}
public void addToChain(String key, Map<String, String> prop) {<FILL_FUNCTION_BODY>}
public void removeChain(String key) {
for (int k = chain.size() - 1; k >= 0; --k) {
if (key.equals(((Object[]) chain.get(k))[0])) {
chain.remove(k);
return;
}
}
}
}
|
// adjust the font size
String value = prop.get(ElementTags.SIZE);
if (value != null) {
if (value.endsWith("pt")) {
prop.put(ElementTags.SIZE, value.substring(0,
value.length() - 2));
} else {
int s = 0;
if (value.startsWith("+") || value.startsWith("-")) {
String old = getOrDefault("basefontsize", "12");
float f = Float.parseFloat(old);
int c = (int) f;
for (int k = fontSizes.length - 1; k >= 0; --k) {
if (c >= fontSizes[k]) {
s = k;
break;
}
}
int inc = Integer.parseInt(value.startsWith("+") ? value
.substring(1) : value);
s += inc;
} else {
try {
s = Integer.parseInt(value) - 1;
} catch (NumberFormatException nfe) {
s = 0;
}
}
if (s < 0) {
s = 0;
} else if (s >= fontSizes.length) {
s = fontSizes.length - 1;
}
prop.put(ElementTags.SIZE, Integer.toString(fontSizes[s]));
}
}
chain.add(new Object[]{key, prop});
| 621
| 373
| 994
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/html/simpleparser/IncTable.java
|
IncTable
|
addCol
|
class IncTable {
private Map<String, String> props = new HashMap<>();
private List<List<PdfPCell>> rows = new ArrayList<>();
private List<PdfPCell> cols;
public IncTable(Map<String, String> props) {
this.props.putAll(props);
}
public void addCol(PdfPCell cell) {<FILL_FUNCTION_BODY>}
public void addCols(List<PdfPCell> ncols) {
if (cols == null) {
cols = new ArrayList<>(ncols);
} else {
cols.addAll(ncols);
}
}
public void endRow() {
if (cols != null) {
Collections.reverse(cols);
rows.add(cols);
cols = null;
}
}
public List<List<PdfPCell>> getTableRows() {
return rows;
}
public PdfPTable buildTable() {
if (rows.isEmpty()) {
return new PdfPTable(1);
}
int ncol = 0;
for (PdfPCell pCell : rows.get(0)) {
ncol += pCell.getColspan();
}
PdfPTable table = new PdfPTable(ncol);
String width = props.get("width");
if (width == null) {
table.setWidthPercentage(100);
} else {
if (width.endsWith("%")) {
table.setWidthPercentage(Float.parseFloat(width.substring(0, width.length() - 1)));
} else {
table.setTotalWidth(Float.parseFloat(width));
table.setLockedWidth(true);
}
}
for (List<PdfPCell> col : rows) {
for (PdfPCell pdfPCell : col) {
table.addCell(pdfPCell);
}
}
return table;
}
}
|
if (cols == null) {
cols = new ArrayList<>();
}
cols.add(cell);
| 522
| 34
| 556
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/html/simpleparser/StyleSheet.java
|
StyleSheet
|
applyStyle
|
class StyleSheet {
private final Map<String, Map<String, String>> classMap = new HashMap<>();
private final Map<String, Map<String, String>> tagMap = new HashMap<>();
public void applyStyle(String tag, Map<String, String> props) {<FILL_FUNCTION_BODY>}
public void loadStyle(String style, Map<String, String> props) {
classMap.put(style.toLowerCase(), props);
}
public void loadStyle(String style, String key, String value) {
style = style.toLowerCase();
Map<String, String> props = classMap.computeIfAbsent(style, k -> new HashMap<>());
props.put(key, value);
}
public void loadTagStyle(String tag, Map<String, String> props) {
tagMap.put(tag.toLowerCase(), props);
}
public void loadTagStyle(String tag, String key, String value) {
tag = tag.toLowerCase();
Map<String, String> props = tagMap.computeIfAbsent(tag, k -> new HashMap<>());
props.put(key, value);
}
}
|
Map<String, String> map = tagMap.get(tag.toLowerCase());
if (map != null) {
Map<String, String> temp = new HashMap<>(map);
temp.putAll(props);
props.putAll(temp);
}
String cm = props.get(Markup.HTML_ATTR_CSS_CLASS);
if (cm == null) {
return;
}
map = classMap.get(cm.toLowerCase());
if (map == null) {
return;
}
props.remove(Markup.HTML_ATTR_CSS_CLASS);
Map<String, String> temp = new HashMap<>(map);
temp.putAll(props);
props.putAll(temp);
| 302
| 193
| 495
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/AsianFontMapper.java
|
AsianFontMapper
|
awtToPdf
|
class AsianFontMapper extends DefaultFontMapper {
public static final String ChineseSimplifiedFont = "STSong-Light";
public static final String ChineseSimplifiedEncoding_H = "UniGB-UCS2-H";
public static final String ChineseSimplifiedEncoding_V = "UniGB-UCS2-V";
public static final String ChineseTraditionalFont_MHei = "MHei-Medium";
public static final String ChineseTraditionalFont_MSung = "MSung-Light";
public static final String ChineseTraditionalEncoding_H = "UniCNS-UCS2-H";
public static final String ChineseTraditionalEncoding_V = "UniCNS-UCS2-V";
public static final String JapaneseFont_Go = "HeiseiKakuGo-W5";
public static final String JapaneseFont_Min = "HeiseiMin-W3";
public static final String JapaneseEncoding_H = "UniJIS-UCS2-H";
public static final String JapaneseEncoding_V = "UniJIS-UCS2-V";
public static final String JapaneseEncoding_HW_H = "UniJIS-UCS2-HW-H";
public static final String JapaneseEncoding_HW_V = "UniJIS-UCS2-HW-V";
public static final String KoreanFont_GoThic = "HYGoThic-Medium";
public static final String KoreanFont_SMyeongJo = "HYSMyeongJo-Medium";
public static final String KoreanEncoding_H = "UniKS-UCS2-H";
public static final String KoreanEncoding_V = "UniKS-UCS2-V";
private final String defaultFont;
private final String encoding;
public AsianFontMapper(String font, String encoding) {
super();
this.defaultFont = font;
this.encoding = encoding;
}
public BaseFont awtToPdf(Font font) {<FILL_FUNCTION_BODY>}
}
|
try {
BaseFontParameters p = getBaseFontParameters(font.getFontName());
if (p != null) {
return BaseFont.createFont(p.fontName, p.encoding, p.embedded, p.cached, p.ttfAfm, p.pfb);
} else {
return BaseFont.createFont(defaultFont, encoding, true);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
| 507
| 125
| 632
|
<methods>public non-sealed void <init>() ,public com.lowagie.text.pdf.BaseFont awtToPdf(java.awt.Font) ,public HashMap<java.lang.String,java.lang.String> getAliases() ,public com.lowagie.text.pdf.DefaultFontMapper.BaseFontParameters getBaseFontParameters(java.lang.String) ,public HashMap<java.lang.String,com.lowagie.text.pdf.DefaultFontMapper.BaseFontParameters> getMapper() ,public int insertDirectory(java.lang.String) ,public void insertNames(java.lang.Object[], java.lang.String) ,public java.awt.Font pdfToAwt(com.lowagie.text.pdf.BaseFont, int) ,public void putAlias(java.lang.String, java.lang.String) ,public void putName(java.lang.String, com.lowagie.text.pdf.DefaultFontMapper.BaseFontParameters) <variables>private HashMap<java.lang.String,java.lang.String> aliases,private HashMap<java.lang.String,com.lowagie.text.pdf.DefaultFontMapper.BaseFontParameters> mapper
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/BarcodeDatamatrix.java
|
Placement
|
corner1
|
class Placement {
private static final Map<Integer, short[]> cache = new HashMap<>();
private int nrow;
private int ncol;
private short[] array;
private Placement() {
}
static short[] doPlacement(int nrow, int ncol) {
Integer key = nrow * 1000 + ncol;
short[] pc = cache.get(key);
if (pc != null) {
return pc;
}
Placement p = new Placement();
p.nrow = nrow;
p.ncol = ncol;
p.array = new short[nrow * ncol];
p.ecc200();
cache.put(key, p.array);
return p.array;
}
/* "module" places "chr+bit" with appropriate wrapping within array[] */
private void module(int row, int col, int chr, int bit) {
if (row < 0) {
row += nrow;
col += 4 - ((nrow + 4) % 8);
}
if (col < 0) {
col += ncol;
row += 4 - ((ncol + 4) % 8);
}
array[row * ncol + col] = (short) (8 * chr + bit);
}
/* "utah" places the 8 bits of a utah-shaped symbol character in ECC200 */
private void utah(int row, int col, int chr) {
module(row - 2, col - 2, chr, 0);
module(row - 2, col - 1, chr, 1);
module(row - 1, col - 2, chr, 2);
module(row - 1, col - 1, chr, 3);
module(row - 1, col, chr, 4);
module(row, col - 2, chr, 5);
module(row, col - 1, chr, 6);
module(row, col, chr, 7);
}
/* "cornerN" places 8 bits of the four special corner cases in ECC200 */
private void corner1(int chr) {<FILL_FUNCTION_BODY>}
private void corner2(int chr) {
module(nrow - 3, 0, chr, 0);
module(nrow - 2, 0, chr, 1);
module(nrow - 1, 0, chr, 2);
module(0, ncol - 4, chr, 3);
module(0, ncol - 3, chr, 4);
module(0, ncol - 2, chr, 5);
module(0, ncol - 1, chr, 6);
module(1, ncol - 1, chr, 7);
}
private void corner3(int chr) {
module(nrow - 3, 0, chr, 0);
module(nrow - 2, 0, chr, 1);
module(nrow - 1, 0, chr, 2);
module(0, ncol - 2, chr, 3);
module(0, ncol - 1, chr, 4);
module(1, ncol - 1, chr, 5);
module(2, ncol - 1, chr, 6);
module(3, ncol - 1, chr, 7);
}
private void corner4(int chr) {
module(nrow - 1, 0, chr, 0);
module(nrow - 1, ncol - 1, chr, 1);
module(0, ncol - 3, chr, 2);
module(0, ncol - 2, chr, 3);
module(0, ncol - 1, chr, 4);
module(1, ncol - 3, chr, 5);
module(1, ncol - 2, chr, 6);
module(1, ncol - 1, chr, 7);
}
/* "ECC200" fills an nrow x ncol array with appropriate values for ECC200 */
private void ecc200() {
/* First, fill the array[] with invalid entries */
Arrays.fill(array, (short) 0);
/* Starting in the correct location for character #1, bit 8,... */
int chr = 1;
int row = 4;
int col = 0;
do {
/* repeatedly first check for one of the special corner cases, then... */
if ((row == nrow) && (col == 0)) {
corner1(chr++);
}
if ((row == nrow - 2) && (col == 0) && (ncol % 4 != 0)) {
corner2(chr++);
}
if ((row == nrow - 2) && (col == 0) && (ncol % 8 == 4)) {
corner3(chr++);
}
if ((row == nrow + 4) && (col == 2) && (ncol % 8 == 0)) {
corner4(chr++);
}
/* sweep upward diagonally, inserting successive characters,... */
do {
if ((row < nrow) && (col >= 0) && array[row * ncol + col] == 0) {
utah(row, col, chr++);
}
row -= 2;
col += 2;
} while ((row >= 0) && (col < ncol));
row += 1;
col += 3;
/* & then sweep downward diagonally, inserting successive characters,... */
do {
if ((row >= 0) && (col < ncol) && array[row * ncol + col] == 0) {
utah(row, col, chr++);
}
row += 2;
col -= 2;
} while ((row < nrow) && (col >= 0));
row += 3;
col += 1;
/* ... until the entire array is scanned */
} while ((row < nrow) || (col < ncol));
/* Lastly, if the lower righthand corner is untouched, fill in fixed pattern */
if (array[nrow * ncol - 1] == 0) {
array[nrow * ncol - 1] = array[nrow * ncol - ncol - 2] = 1;
}
}
}
|
module(nrow - 1, 0, chr, 0);
module(nrow - 1, 1, chr, 1);
module(nrow - 1, 2, chr, 2);
module(0, ncol - 2, chr, 3);
module(0, ncol - 1, chr, 4);
module(1, ncol - 1, chr, 5);
module(2, ncol - 1, chr, 6);
module(3, ncol - 1, chr, 7);
| 1,679
| 150
| 1,829
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/BarcodeEANSUPP.java
|
BarcodeEANSUPP
|
placeBarcode
|
class BarcodeEANSUPP extends Barcode {
/**
* The barcode with the EAN/UPC.
*/
protected Barcode ean;
/**
* The barcode with the supplemental.
*/
protected Barcode supp;
/**
* Creates new combined barcode.
*
* @param ean the EAN/UPC barcode
* @param supp the supplemental barcode
*/
public BarcodeEANSUPP(Barcode ean, Barcode supp) {
n = 8; // horizontal distance between the two barcodes
this.ean = ean;
this.supp = supp;
}
/**
* Gets the maximum area that the barcode and the text, if any, will occupy. The lower left corner is always (0,
* 0).
*
* @return the size the barcode occupies.
*/
public Rectangle getBarcodeSize() {
Rectangle rect = ean.getBarcodeSize();
rect.setRight(rect.getWidth() + supp.getBarcodeSize().getWidth() + n);
return rect;
}
/**
* Places the barcode in a <CODE>PdfContentByte</CODE>. The barcode is always placed at coordinates (0, 0). Use the
* translation matrix to move it elsewhere.
* <p> The bars and text are written in the following colors:</p>
* <TABLE BORDER=1>
* <CAPTION>table of the colors of the bars and text</CAPTION>
* <TR>
* <TH><P><CODE>barColor</CODE></TH>
* <TH><P><CODE>textColor</CODE></TH>
* <TH><P>Result</TH>
* </TR>
* <TR>
* <TD><P><CODE>null</CODE></TD>
* <TD><P><CODE>null</CODE></TD>
* <TD><P>bars and text painted with current fill color</TD>
* </TR>
* <TR>
* <TD><P><CODE>barColor</CODE></TD>
* <TD><P><CODE>null</CODE></TD>
* <TD><P>bars and text painted with <CODE>barColor</CODE></TD>
* </TR>
* <TR>
* <TD><P><CODE>null</CODE></TD>
* <TD><P><CODE>textColor</CODE></TD>
* <TD><P>bars painted with current color<br>text painted with <CODE>textColor</CODE></TD>
* </TR>
* <TR>
* <TD><P><CODE>barColor</CODE></TD>
* <TD><P><CODE>textColor</CODE></TD>
* <TD><P>bars painted with <CODE>barColor</CODE><br>text painted with <CODE>textColor</CODE></TD>
* </TR>
* </TABLE>
*
* @param cb the <CODE>PdfContentByte</CODE> where the barcode will be placed
* @param barColor the color of the bars. It can be <CODE>null</CODE>
* @param textColor the color of the text. It can be <CODE>null</CODE>
* @return the dimensions the barcode occupies
*/
public Rectangle placeBarcode(PdfContentByte cb, Color barColor, Color textColor) {<FILL_FUNCTION_BODY>}
/**
* Creates a <CODE>java.awt.Image</CODE>. This image only contains the bars without any text.
*
* @param foreground the color of the bars
* @param background the color of the background
* @return the image
*/
public java.awt.Image createAwtImage(Color foreground, Color background) {
throw new UnsupportedOperationException(
MessageLocalization.getComposedMessage("the.two.barcodes.must.be.composed.externally"));
}
}
|
if (supp.getFont() != null) {
supp.setBarHeight(ean.getBarHeight() + supp.getBaseline() - supp.getFont()
.getFontDescriptor(BaseFont.CAPHEIGHT, supp.getSize()));
} else {
supp.setBarHeight(ean.getBarHeight());
}
Rectangle eanR = ean.getBarcodeSize();
cb.saveState();
ean.placeBarcode(cb, barColor, textColor);
cb.restoreState();
cb.saveState();
cb.concatCTM(1, 0, 0, 1, eanR.getWidth() + n, eanR.getHeight() - ean.getBarHeight());
supp.placeBarcode(cb, barColor, textColor);
cb.restoreState();
return getBarcodeSize();
| 1,069
| 228
| 1,297
|
<methods>public non-sealed void <init>() ,public abstract java.awt.Image createAwtImage(java.awt.Color, java.awt.Color) ,public com.lowagie.text.Image createImageWithBarcode(com.lowagie.text.pdf.PdfContentByte, java.awt.Color, java.awt.Color) ,public com.lowagie.text.pdf.PdfTemplate createTemplateWithBarcode(com.lowagie.text.pdf.PdfContentByte, java.awt.Color, java.awt.Color) ,public java.lang.String getAltText() ,public float getBarHeight() ,public abstract com.lowagie.text.Rectangle getBarcodeSize() ,public float getBaseline() ,public java.lang.String getCode() ,public int getCodeType() ,public com.lowagie.text.pdf.BaseFont getFont() ,public float getInkSpreading() ,public float getN() ,public float getSize() ,public int getTextAlignment() ,public float getX() ,public boolean isChecksumText() ,public boolean isExtended() ,public boolean isGenerateChecksum() ,public boolean isGuardBars() ,public boolean isStartStopText() ,public abstract com.lowagie.text.Rectangle placeBarcode(com.lowagie.text.pdf.PdfContentByte, java.awt.Color, java.awt.Color) ,public void setAltText(java.lang.String) ,public void setBarHeight(float) ,public void setBaseline(float) ,public void setChecksumText(boolean) ,public void setCode(java.lang.String) ,public void setCodeType(int) ,public void setExtended(boolean) ,public void setFont(com.lowagie.text.pdf.BaseFont) ,public void setGenerateChecksum(boolean) ,public void setGuardBars(boolean) ,public void setInkSpreading(float) ,public void setN(float) ,public void setSize(float) ,public void setStartStopText(boolean) ,public void setTextAlignment(int) ,public void setX(float) <variables>public static final int CODABAR,public static final int CODE128,public static final int CODE128_RAW,public static final int CODE128_UCC,public static final int EAN13,public static final int EAN8,public static final int PLANET,public static final int POSTNET,public static final int SUPP2,public static final int SUPP5,public static final int UPCA,public static final int UPCE,protected java.lang.String altText,protected float barHeight,protected float baseline,protected boolean checksumText,protected java.lang.String code,protected int codeType,protected boolean extended,protected com.lowagie.text.pdf.BaseFont font,protected boolean generateChecksum,protected boolean guardBars,protected float inkSpreading,protected float n,protected float size,protected boolean startStopText,protected int textAlignment,protected float x
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/CMYKColor.java
|
CMYKColor
|
hashCode
|
class CMYKColor extends ExtendedColor {
private static final long serialVersionUID = 5940378778276468452L;
float cyan;
float magenta;
float yellow;
float black;
/**
* Constructs a CMYK Color based on 4 color values (values are integers from 0 to 255).
*
* @param intCyan cyan value
* @param intMagenta magenta value
* @param intYellow yellow value
* @param intBlack black value
*/
public CMYKColor(int intCyan, int intMagenta, int intYellow, int intBlack) {
this(normalize(intCyan) / MAX_INT_COLOR_VALUE, normalize(intMagenta) / MAX_INT_COLOR_VALUE,
normalize(intYellow) / MAX_INT_COLOR_VALUE, normalize(intBlack) / MAX_INT_COLOR_VALUE);
}
/**
* Constructs a CMYK Color based on 4 color values (values are integers from 0 to 255).
*
* @param intCyan cyan value
* @param intMagenta magenta value
* @param intYellow yellow value
* @param intBlack black value
* @param intAlpha alpha value
*/
public CMYKColor(int intCyan, int intMagenta, int intYellow, int intBlack, int intAlpha) {
this(normalize(intCyan) / MAX_INT_COLOR_VALUE, normalize(intMagenta) / MAX_INT_COLOR_VALUE,
normalize(intYellow) / MAX_INT_COLOR_VALUE, normalize(intBlack) / MAX_INT_COLOR_VALUE,
normalize(intAlpha) / MAX_INT_COLOR_VALUE);
}
/**
* Construct a CMYK Color.
*
* @param floatCyan cyan value
* @param floatMagenta magenta value
* @param floatYellow yellow value
* @param floatBlack black value
*/
public CMYKColor(float floatCyan, float floatMagenta, float floatYellow, float floatBlack) {
this(floatCyan, floatMagenta, floatYellow, floatBlack, MAX_FLOAT_COLOR_VALUE);
}
/**
* Construct a CMYK Color.
*
* @param floatCyan cyan value
* @param floatMagenta magenta value
* @param floatYellow yellow value
* @param floatBlack black value
* @param floatAlpha alpha value
*/
public CMYKColor(float floatCyan, float floatMagenta, float floatYellow, float floatBlack, float floatAlpha) {
super(TYPE_CMYK, MAX_FLOAT_COLOR_VALUE - normalize(floatCyan) - normalize(floatBlack),
MAX_FLOAT_COLOR_VALUE - normalize(floatMagenta) - normalize(floatBlack),
MAX_FLOAT_COLOR_VALUE - normalize(floatYellow) - normalize(floatBlack), normalize(floatAlpha));
cyan = normalize(floatCyan);
magenta = normalize(floatMagenta);
yellow = normalize(floatYellow);
black = normalize(floatBlack);
}
/**
* @return the cyan value
*/
public float getCyan() {
return cyan;
}
/**
* @return the magenta value
*/
public float getMagenta() {
return magenta;
}
/**
* @return the yellow value
*/
public float getYellow() {
return yellow;
}
/**
* @return the black value
*/
public float getBlack() {
return black;
}
public boolean equals(Object obj) {
if (!(obj instanceof CMYKColor)) {
return false;
}
CMYKColor c2 = (CMYKColor) obj;
return (cyan == c2.cyan && magenta == c2.magenta && yellow == c2.yellow && black == c2.black
&& getAlpha() == c2.getAlpha());
}
public int hashCode() {<FILL_FUNCTION_BODY>}
}
|
return Float.floatToIntBits(cyan)
^ Float.floatToIntBits(magenta)
^ Float.floatToIntBits(yellow)
^ Float.floatToIntBits(black)
^ Float.floatToIntBits(getAlpha())
;
| 1,095
| 80
| 1,175
|
<methods>public void <init>(int) ,public void <init>(int, float, float, float) ,public void <init>(int, float, float, float, float) ,public static int getType(java.awt.Color) ,public int getType() <variables>public static final int MAX_COLOR_VALUE,public static final float MAX_FLOAT_COLOR_VALUE,public static final float MAX_INT_COLOR_VALUE,public static final int TYPE_CMYK,public static final int TYPE_GRAY,public static final int TYPE_PATTERN,public static final int TYPE_RGB,public static final int TYPE_SEPARATION,public static final int TYPE_SHADING,private static final long serialVersionUID,protected int type
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/DefaultSplitCharacter.java
|
DefaultSplitCharacter
|
isSplitCharacter
|
class DefaultSplitCharacter implements SplitCharacter {
/**
* An instance of the default SplitCharacter.
*/
public static final SplitCharacter DEFAULT = new DefaultSplitCharacter();
/**
* Checks if a character can be used to split a <CODE>PdfString</CODE>.
* <p>
* for the moment every character less than or equal to SPACE, the character '-' and some specific unicode ranges
* are 'splitCharacters'.
*
* @param start start position in the array
* @param current current position in the array
* @param end end position in the array
* @param cc the character array that has to be checked
* @param ck chunk array
* @return <CODE>true</CODE> if the character can be used to split a string, <CODE>false</CODE> otherwise
*/
public boolean isSplitCharacter(int start, int current, int end, char[] cc, PdfChunk[] ck) {<FILL_FUNCTION_BODY>}
/**
* Returns the current character
*
* @param current current position in the array
* @param cc the character array that has to be checked
* @param ck chunk array
* @return the current character
*/
protected char getCurrentCharacter(int current, char[] cc, PdfChunk[] ck) {
if (ck == null) {
return cc[current];
}
return (char) ck[Math.min(current, ck.length - 1)].getUnicodeEquivalent(cc[current]);
}
}
|
char c = getCurrentCharacter(current, cc, ck);
if (c <= ' ' || c == '-' || c == '\u2010') {
return true;
}
if (c < 0x2002) {
return false;
}
return c <= 0x200b
|| c >= 0x2e80 && c < 0xd7a0
|| c >= 0xf900 && c < 0xfb00
|| c >= 0xfe30 && c < 0xfe50
|| c >= 0xff61 && c < 0xffa0;
| 398
| 158
| 556
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/EnumerateTTC.java
|
EnumerateTTC
|
findNames
|
class EnumerateTTC extends TrueTypeFont {
/**
* OpenType fonts that contain TrueType outlines should use the value of 0x00010000 for the sfntVersion. OpenType
* fonts containing CFF data (version 1 or 2) should use 0x4F54544F ('OTTO', when re-interpreted as a Tag) for
* sfntVersion.
* <p>
* Note: The Apple specification for TrueType fonts allows for 'true' and 'typ1' for sfnt version. These version
* tags should not be used for fonts which contain OpenType tables. See more at:
* https://docs.microsoft.com/de-de/typography/opentype/spec/otff#organization-of-an-opentype-font
*/
private static final int TRUE_TYPE_SFNT_VERSION = 0x00010000;
private static final int CFF_DATA_SFNT_VERSION = 0x4F54544F; //'OTTO'
protected String[] names;
EnumerateTTC(String ttcFile) throws DocumentException, IOException {
fileName = ttcFile;
rf = new RandomAccessFileOrArray(ttcFile);
findNames();
}
EnumerateTTC(byte[] ttcArray) throws DocumentException, IOException {
fileName = "Byte array TTC";
rf = new RandomAccessFileOrArray(ttcArray);
findNames();
}
void findNames() throws DocumentException, IOException {<FILL_FUNCTION_BODY>}
String[] getNames() {
return names;
}
}
|
tables = new HashMap<>();
try {
String mainTag = readStandardString(4);
if (!mainTag.equals("ttcf")) {
throw new DocumentException(
MessageLocalization.getComposedMessage("1.is.not.a.valid.ttc.file", fileName));
}
int majorVersion = rf.readShort();
rf.skipBytes(2);
int dirCount = rf.readInt();
names = new String[dirCount];
int dirPos = rf.getFilePointer();
for (int dirIdx = 0; dirIdx < dirCount; ++dirIdx) {
tables.clear();
rf.seek(dirPos);
rf.skipBytes(dirIdx * 4);
directoryOffset = rf.readInt();
rf.seek(directoryOffset);
int sfntVersion = rf.readInt();
boolean trueTypeFont = sfntVersion == TRUE_TYPE_SFNT_VERSION;
boolean cffDataFont = sfntVersion == CFF_DATA_SFNT_VERSION &&
(majorVersion == 1 || majorVersion == 2);
if (!trueTypeFont && !cffDataFont) {
throw new DocumentException(
MessageLocalization.getComposedMessage("1.is.not.a.valid.ttf.file", fileName));
}
int num_tables = rf.readUnsignedShort();
rf.skipBytes(6);
for (int k = 0; k < num_tables; ++k) {
String tag = readStandardString(4);
rf.skipBytes(4);
int[] table_location = new int[2];
table_location[0] = rf.readInt();
table_location[1] = rf.readInt();
tables.put(tag, table_location);
}
names[dirIdx] = getBaseFont();
}
} finally {
if (rf != null) {
rf.close();
}
}
| 419
| 508
| 927
|
<methods>public java.lang.String[][] getAllNameEntries() ,public java.lang.String[] getCodePagesSupported() ,public java.lang.String[][] getFamilyFontName() ,public float getFontDescriptor(int, float) ,public java.lang.String[][] getFullFontName() ,public com.lowagie.text.pdf.PdfStream getFullFontStream() throws java.io.IOException, com.lowagie.text.DocumentException,public int getKerning(int, int) ,public int[] getMetricsTT(int) ,public java.lang.String getPostscriptFontName() ,public boolean hasKernPairs() ,public boolean setKerning(int, int, int) ,public void setPostscriptFontName(java.lang.String) <variables>protected int[] GlyphWidths,protected java.lang.String[][] allNameEntries,protected int[][] bboxes,protected boolean cff,protected int cffLength,protected int cffOffset,protected HashMap<java.lang.Integer,int[]> cmap10,protected HashMap<java.lang.Integer,int[]> cmap31,protected HashMap<java.lang.Integer,int[]> cmapExt,static final java.lang.String[] codePages,protected int directoryOffset,protected java.lang.String[][] familyName,protected java.lang.String fileName,protected java.lang.String fontName,protected java.lang.String[][] fullName,protected com.lowagie.text.pdf.TrueTypeFont.FontHeader head,protected com.lowagie.text.pdf.TrueTypeFont.HorizontalHeader hhea,protected boolean isFixedPitch,protected double italicAngle,protected boolean justNames,protected com.lowagie.text.pdf.IntHashtable kerning,protected com.lowagie.text.pdf.TrueTypeFont.WindowsMetrics os_2,protected com.lowagie.text.pdf.RandomAccessFileOrArray rf,protected java.lang.String style,protected HashMap<java.lang.String,int[]> tables,protected java.lang.String ttcIndex,protected int underlinePosition,protected int underlineThickness
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/ExtendedColor.java
|
ExtendedColor
|
normalize
|
class ExtendedColor extends Color {
/**
* a type of extended color.
*/
public static final int TYPE_RGB = 0;
/**
* a type of extended color.
*/
public static final int TYPE_GRAY = 1;
/**
* a type of extended color.
*/
public static final int TYPE_CMYK = 2;
/**
* a type of extended color.
*/
public static final int TYPE_SEPARATION = 3;
/**
* a type of extended color.
*/
public static final int TYPE_PATTERN = 4;
/**
* a type of extended color.
*/
public static final int TYPE_SHADING = 5;
/**
* the max int color value (255) expressed in int
*/
public static final int MAX_COLOR_VALUE = 0xFF;
/**
* the max int color value (255) expressed in float
*/
public static final float MAX_INT_COLOR_VALUE = 0xFF;
/**
* the max float color value (1) expressed in float
*/
public static final float MAX_FLOAT_COLOR_VALUE = 0x1;
private static final long serialVersionUID = 2722660170712380080L;
protected int type;
/**
* Constructs an extended color of a certain type.
*
* @param type {@link ExtendedColor#type}
*/
public ExtendedColor(int type) {
super(0, 0, 0);
this.type = type;
}
/**
* Constructs an extended color of a certain type and a certain color.
*
* @param type {@link ExtendedColor#type}
* @param red red quotient
* @param green green quotient
* @param blue blue quotient
*/
public ExtendedColor(int type, float red, float green, float blue) {
this(type, normalize(red), normalize(green), normalize(blue), MAX_FLOAT_COLOR_VALUE);
}
/**
* Constructs an extended color of a certain type and a certain color.
*
* @param type {@link ExtendedColor#type}
* @param red red quotient
* @param green green quotient
* @param blue blue quotient
* @param alpha alpha quotient
*/
public ExtendedColor(int type, float red, float green, float blue, float alpha) {
super(normalize(red), normalize(green), normalize(blue), normalize(alpha));
this.type = type;
}
/**
* Gets the type of a given color.
*
* @param color an object of {@link Color}
* @return one of the types (see constants)
*/
public static int getType(Color color) {
if (color instanceof ExtendedColor) {
return ((ExtendedColor) color).getType();
}
return TYPE_RGB;
}
static final float normalize(float value) {<FILL_FUNCTION_BODY>}
static final int normalize(int value) {
if (value < 0) {
return 0;
}
if (value > (int) MAX_INT_COLOR_VALUE) {
return (int) MAX_INT_COLOR_VALUE;
}
return value;
}
/**
* Gets the type of this color.
*
* @return one of the types (see constants)
*/
public int getType() {
return type;
}
}
|
if (value < 0f) {
return 0f;
}
if (value > MAX_FLOAT_COLOR_VALUE) {
return MAX_FLOAT_COLOR_VALUE;
}
return value;
| 917
| 61
| 978
|
<methods>public void <init>(int) ,public void <init>(int, boolean) ,public void <init>(int, int, int) ,public void <init>(float, float, float) ,public void <init>(java.awt.color.ColorSpace, float[], float) ,public void <init>(int, int, int, int) ,public void <init>(float, float, float, float) ,public static int HSBtoRGB(float, float, float) ,public static float[] RGBtoHSB(int, int, int, float[]) ,public java.awt.Color brighter() ,public synchronized java.awt.PaintContext createContext(java.awt.image.ColorModel, java.awt.Rectangle, java.awt.geom.Rectangle2D, java.awt.geom.AffineTransform, java.awt.RenderingHints) ,public java.awt.Color darker() ,public static java.awt.Color decode(java.lang.String) throws java.lang.NumberFormatException,public boolean equals(java.lang.Object) ,public int getAlpha() ,public int getBlue() ,public static java.awt.Color getColor(java.lang.String) ,public static java.awt.Color getColor(java.lang.String, java.awt.Color) ,public static java.awt.Color getColor(java.lang.String, int) ,public float[] getColorComponents(float[]) ,public float[] getColorComponents(java.awt.color.ColorSpace, float[]) ,public java.awt.color.ColorSpace getColorSpace() ,public float[] getComponents(float[]) ,public float[] getComponents(java.awt.color.ColorSpace, float[]) ,public int getGreen() ,public static java.awt.Color getHSBColor(float, float, float) ,public int getRGB() ,public float[] getRGBColorComponents(float[]) ,public float[] getRGBComponents(float[]) ,public int getRed() ,public int getTransparency() ,public int hashCode() ,public java.lang.String toString() <variables>public static final java.awt.Color BLACK,public static final java.awt.Color BLUE,public static final java.awt.Color CYAN,public static final java.awt.Color DARK_GRAY,private static final double FACTOR,public static final java.awt.Color GRAY,public static final java.awt.Color GREEN,public static final java.awt.Color LIGHT_GRAY,public static final java.awt.Color MAGENTA,public static final java.awt.Color ORANGE,public static final java.awt.Color PINK,public static final java.awt.Color RED,public static final java.awt.Color WHITE,public static final java.awt.Color YELLOW,public static final java.awt.Color black,public static final java.awt.Color blue,private java.awt.color.ColorSpace cs,public static final java.awt.Color cyan,public static final java.awt.Color darkGray,private float falpha,private float[] frgbvalue,private float[] fvalue,public static final java.awt.Color gray,public static final java.awt.Color green,public static final java.awt.Color lightGray,public static final java.awt.Color magenta,public static final java.awt.Color orange,public static final java.awt.Color pink,public static final java.awt.Color red,private static final long serialVersionUID,int value,public static final java.awt.Color white,public static final java.awt.Color yellow
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/FdfReader.java
|
FdfReader
|
readPdf
|
class FdfReader extends PdfReader {
PdfName encoding;
private Map<String, PdfDictionary> fields;
private String fileSpec;
/**
* Reads an FDF form.
*
* @param filename the file name of the form
* @throws IOException on error
*/
public FdfReader(String filename) throws IOException {
super(filename);
}
/**
* Reads an FDF form.
*
* @param pdfIn the byte array with the form
* @throws IOException on error
*/
public FdfReader(byte[] pdfIn) throws IOException {
super(pdfIn);
}
/**
* Reads an FDF form.
*
* @param url the URL of the document
* @throws IOException on error
*/
public FdfReader(URL url) throws IOException {
super(url);
}
/**
* Reads an FDF form.
*
* @param is the <CODE>InputStream</CODE> containing the document. The stream is read to the end but is not closed
* @throws IOException on error
*/
public FdfReader(InputStream is) throws IOException {
super(is);
}
protected void readPdf() throws IOException {<FILL_FUNCTION_BODY>}
protected void kidNode(PdfDictionary merged, String name) {
PdfArray kids = merged.getAsArray(PdfName.KIDS);
if (kids == null || kids.isEmpty()) {
if (!name.isEmpty()) {
name = name.substring(1);
}
fields.put(name, merged);
} else {
merged.remove(PdfName.KIDS);
for (int k = 0; k < kids.size(); ++k) {
PdfDictionary dic = new PdfDictionary();
dic.merge(merged);
PdfDictionary newDic = kids.getAsDict(k);
PdfString t = newDic.getAsString(PdfName.T);
String newName = name;
if (t != null) {
newName += "." + t.toUnicodeString();
}
dic.merge(newDic);
dic.remove(PdfName.T);
kidNode(dic, newName);
}
}
}
protected void readFields() {
catalog = trailer.getAsDict(PdfName.ROOT);
PdfDictionary fdf = catalog.getAsDict(PdfName.FDF);
if (fdf == null) {
return;
}
PdfString fs = fdf.getAsString(PdfName.F);
if (fs != null) {
fileSpec = fs.toUnicodeString();
}
PdfArray fld = fdf.getAsArray(PdfName.FIELDS);
if (fld == null) {
return;
}
encoding = fdf.getAsName(PdfName.ENCODING);
PdfDictionary merged = new PdfDictionary();
merged.put(PdfName.KIDS, fld);
kidNode(merged, "");
}
/**
* Gets all the fields. The map is keyed by the fully qualified field name and the value is a merged
* <CODE>PdfDictionary</CODE> with the field content.
*
* @return all the fields
*/
public Map<String, PdfDictionary> getAllFields() {
return fields;
}
/**
* Gets the field dictionary.
*
* @param name the fully qualified field name
* @return the field dictionary
*/
public PdfDictionary getField(String name) {
return fields.get(name);
}
/**
* Gets the field value or <CODE>null</CODE> if the field does not exist or has no value defined.
*
* @param name the fully qualified field name
* @return the field value or <CODE>null</CODE>
*/
public String getFieldValue(String name) {
PdfDictionary field = fields.get(name);
if (field == null) {
return null;
}
PdfObject v = getPdfObject(field.get(PdfName.V));
if (v == null) {
return null;
}
if (v.isName()) {
return PdfName.decodeName(v.toString());
} else if (v.isString()) {
PdfString vs = (PdfString) v;
if (encoding == null || vs.getEncoding() != null) {
return vs.toUnicodeString();
}
byte[] b = vs.getBytes();
if (b.length >= 2 && b[0] == (byte) 254 && b[1] == (byte) 255) {
return vs.toUnicodeString();
}
try {
if (encoding.equals(PdfName.SHIFT_JIS)) {
return new String(b, "SJIS");
} else if (encoding.equals(PdfName.UHC)) {
return new String(b, "MS949");
} else if (encoding.equals(PdfName.GBK)) {
return new String(b, "GBK");
} else if (encoding.equals(PdfName.BIGFIVE)) {
return new String(b, "Big5");
}
} catch (Exception e) {
}
return vs.toUnicodeString();
}
return null;
}
/**
* Gets the PDF file specification contained in the FDF.
*
* @return the PDF file specification contained in the FDF
*/
public String getFileSpec() {
return fileSpec;
}
}
|
fields = new HashMap<>();
try {
tokens.checkFdfHeader();
rebuildXref();
readDocObj();
} finally {
try {
tokens.close();
} catch (Exception e) {
// empty on purpose
}
}
readFields();
| 1,462
| 78
| 1,540
|
<methods>public void <init>(java.lang.String) throws java.io.IOException,public void <init>(java.lang.String, byte[]) throws java.io.IOException,public void <init>(byte[]) throws java.io.IOException,public void <init>(byte[], byte[]) throws java.io.IOException,public void <init>(java.lang.String, java.security.cert.Certificate, java.security.Key, java.lang.String) throws java.io.IOException,public void <init>(java.net.URL) throws java.io.IOException,public void <init>(java.net.URL, byte[]) throws java.io.IOException,public void <init>(java.io.InputStream, byte[]) throws java.io.IOException,public void <init>(java.io.InputStream) throws java.io.IOException,public void <init>(com.lowagie.text.pdf.RandomAccessFileOrArray, byte[]) throws java.io.IOException,public void <init>(com.lowagie.text.pdf.PdfReader) ,public static byte[] ASCII85Decode(byte[]) ,public static byte[] ASCIIHexDecode(byte[]) ,public static byte[] FlateDecode(byte[]) ,public static byte[] FlateDecode(byte[], boolean) ,public static byte[] LZWDecode(byte[]) ,public com.lowagie.text.pdf.PRIndirectReference addPdfObject(com.lowagie.text.pdf.PdfObject) ,public void addViewerPreference(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void close() ,public byte[] computeUserPassword() ,public void consolidateNamedDestinations() ,public static com.lowagie.text.pdf.PdfObject convertPdfNull(com.lowagie.text.pdf.PdfObject) ,public int createFakeFontSubsets() ,public static byte[] decodePredictor(byte[], com.lowagie.text.pdf.PdfObject) ,public double dumpPerc() ,public void eliminateSharedStreams() ,public com.lowagie.text.pdf.AcroFields getAcroFields() ,public com.lowagie.text.pdf.PRAcroForm getAcroForm() ,public com.lowagie.text.Rectangle getBoxSize(int, java.lang.String) ,public com.lowagie.text.pdf.PdfDictionary getCatalog() ,public int getCertificationLevel() ,public com.lowagie.text.Rectangle getCropBox(int) ,public int getCryptoMode() ,public byte[] getDocumentId() ,public int getEofPos() ,public int getFileLength() ,public Map<java.lang.String,java.lang.String> getInfo() ,public java.lang.String getJavaScript(com.lowagie.text.pdf.RandomAccessFileOrArray) throws java.io.IOException,public java.lang.String getJavaScript() throws java.io.IOException,public int getLastXref() ,public ArrayList<com.lowagie.text.pdf.PdfAnnotation.PdfImportedLink> getLinks(int) ,public byte[] getMetadata() throws java.io.IOException,public HashMap<java.lang.Object,com.lowagie.text.pdf.PdfObject> getNamedDestination() ,public HashMap<java.lang.Object,com.lowagie.text.pdf.PdfObject> getNamedDestination(boolean) ,public HashMap#RAW getNamedDestinationFromNames() ,public HashMap<java.lang.Object,com.lowagie.text.pdf.PdfObject> getNamedDestinationFromNames(boolean) ,public HashMap#RAW getNamedDestinationFromStrings() ,public static com.lowagie.text.Rectangle getNormalizedRectangle(com.lowagie.text.pdf.PdfArray) ,public int getNumberOfPages() ,public byte[] getPageContent(int, com.lowagie.text.pdf.RandomAccessFileOrArray) throws java.io.IOException,public byte[] getPageContent(int) throws java.io.IOException,public com.lowagie.text.pdf.PdfDictionary getPageN(int) ,public com.lowagie.text.pdf.PdfDictionary getPageNRelease(int) ,public com.lowagie.text.pdf.PRIndirectReference getPageOrigRef(int) ,public int getPageRotation(int) ,public com.lowagie.text.Rectangle getPageSize(int) ,public com.lowagie.text.Rectangle getPageSize(com.lowagie.text.pdf.PdfDictionary) ,public com.lowagie.text.Rectangle getPageSizeWithRotation(int) ,public com.lowagie.text.Rectangle getPageSizeWithRotation(com.lowagie.text.pdf.PdfDictionary) ,public com.lowagie.text.Rectangle getPageSizeWithRotation(int, java.lang.String) ,public static com.lowagie.text.pdf.PdfObject getPdfObject(com.lowagie.text.pdf.PdfObject) ,public static com.lowagie.text.pdf.PdfObject getPdfObject(com.lowagie.text.pdf.PdfObject, com.lowagie.text.pdf.PdfObject) ,public com.lowagie.text.pdf.PdfObject getPdfObject(int) ,public static com.lowagie.text.pdf.PdfObject getPdfObjectNullConverting(com.lowagie.text.pdf.PdfObject, com.lowagie.text.pdf.PdfObject) ,public static com.lowagie.text.pdf.PdfObject getPdfObjectRelease(com.lowagie.text.pdf.PdfObject) ,public static com.lowagie.text.pdf.PdfObject getPdfObjectRelease(com.lowagie.text.pdf.PdfObject, com.lowagie.text.pdf.PdfObject) ,public com.lowagie.text.pdf.PdfObject getPdfObjectRelease(int) ,public static com.lowagie.text.pdf.PdfObject getPdfObjectReleaseNullConverting(com.lowagie.text.pdf.PdfObject) ,public char getPdfVersion() ,public int getPermissions() ,public com.lowagie.text.pdf.RandomAccessFileOrArray getSafeFile() ,public int getSimpleViewerPreferences() ,public static byte[] getStreamBytes(com.lowagie.text.pdf.PRStream, com.lowagie.text.pdf.RandomAccessFileOrArray) throws java.io.IOException,public static byte[] getStreamBytes(com.lowagie.text.pdf.PRStream) throws java.io.IOException,public static byte[] getStreamBytesRaw(com.lowagie.text.pdf.PRStream, com.lowagie.text.pdf.RandomAccessFileOrArray) throws java.io.IOException,public static byte[] getStreamBytesRaw(com.lowagie.text.pdf.PRStream) throws java.io.IOException,public com.lowagie.text.pdf.PdfDictionary getTrailer() ,public int getXrefSize() ,public boolean is128Key() ,public boolean isAppendable() ,public boolean isEncrypted() ,public boolean isHybridXref() ,public boolean isMetadataEncrypted() ,public boolean isModificationlowedWithoutOwnerPassword() ,public boolean isNewXrefType() ,public final boolean isOpenedWithFullPermissions() ,public boolean isOwnerPasswordUsed() ,public boolean isRebuilt() ,public boolean isTampered() ,public static com.lowagie.text.pdf.PdfObject killIndirect(com.lowagie.text.pdf.PdfObject) ,public void makeRemoteNamedDestinationsLocal() ,public static void releaseLastXrefPartial(com.lowagie.text.pdf.PdfObject) ,public void releaseLastXrefPartial() ,public void releasePage(int) ,public void removeAnnotations() ,public void removeFields() ,public int removeUnusedObjects() ,public void removeUsageRights() ,public void resetLastXrefPartial() ,public void resetReleasePage() ,public void selectPages(java.lang.String) ,public void selectPages(List<java.lang.Integer>) ,public void setAppendable(boolean) ,public void setModificationAllowedWithoutOwnerPassword(boolean) ,public void setPageContent(int, byte[]) ,public void setPageContent(int, byte[], int) ,public void setPermissions(int) ,public void setTampered(boolean) ,public void setViewerPreferences(int) ,public int shuffleSubsetNames() <variables>protected com.lowagie.text.pdf.PRAcroForm acroForm,protected boolean acroFormParsed,private boolean appendable,protected com.lowagie.text.pdf.PdfDictionary catalog,protected java.security.cert.Certificate certificate,protected java.security.Key certificateKey,protected java.lang.String certificateKeyProvider,protected boolean consolidateNamedDestinations,private com.lowagie.text.pdf.PRIndirectReference cryptoRef,protected com.lowagie.text.pdf.PdfEncryption decrypt,protected boolean encrypted,private boolean encryptionError,private static final byte[] endobj,private static final byte[] endstream,protected int eofPos,private int fileLength,protected int freeXref,private boolean hybridXref,protected int lastXref,private int lastXrefPartial,private boolean modificationAllowedWithoutOwnerPassword,protected boolean newXrefType,private int objGen,private int objNum,protected Map<java.lang.Integer,com.lowagie.text.pdf.IntHashtable> objStmMark,protected com.lowagie.text.pdf.IntHashtable objStmToOffset,private boolean ownerPasswordUsed,protected int pValue,static final com.lowagie.text.pdf.PdfName[] pageInhCandidates,protected com.lowagie.text.pdf.PdfReader.PageRefs pageRefs,private boolean partial,protected byte[] password,protected char pdfVersion,protected int rValue,private int readDepth,protected boolean rebuilt,protected boolean remoteToLocalNamedDestinations,com.lowagie.text.pdf.PdfDictionary rootPages,protected boolean sharedStreams,protected List<com.lowagie.text.pdf.PdfObject> strings,protected boolean tampered,protected com.lowagie.text.pdf.PRTokeniser tokens,protected com.lowagie.text.pdf.PdfDictionary trailer,private final com.lowagie.text.pdf.internal.PdfViewerPreferencesImp viewerPreferences,protected int[] xref,private List<com.lowagie.text.pdf.PdfObject> xrefObj
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/FontSelector.java
|
FontSelector
|
process
|
class FontSelector {
protected ArrayList<Font> fonts = new ArrayList<>();
public FontSelector() {
FontFactory.register("font-fallback/LiberationSans-Regular.ttf", "sans");
Font font = FontFactory.getFont("sans", BaseFont.IDENTITY_H);
fonts.add(font);
}
/**
* change the color of default font in <CODE>FontSelector</CODE>.
*
* @param color the <CODE>Color</CODE> of default font
*/
public void setDefaultColor(Color color) {
fonts.get(fonts.size() - 1).setColor(color);
}
/**
* change the size of default font in <CODE>FontSelector</CODE>.
*
* @param size the size of default font
*/
public void setDefaultSize(float size) {
fonts.get(fonts.size() - 1).setSize(size);
}
/**
* Adds a <CODE>Font</CODE> to be searched for valid characters.
*
* @param font the <CODE>Font</CODE>
*/
public void addFont(Font font) {
if (font.getBaseFont() != null) {
fonts.add(fonts.size() - 1, font);
return;
}
BaseFont bf = font.getCalculatedBaseFont(true);
Font f2 = new Font(bf, font.getSize(), font.getCalculatedStyle(), font.getColor());
fonts.add(fonts.size() - 1, f2);
}
/**
* Process the text so that it will render with a combination of fonts if needed.
*
* @param text the text
* @return a <CODE>Phrase</CODE> with one or more chunks
*/
public Phrase process(String text) {<FILL_FUNCTION_BODY>}
}
|
int fsize = fonts.size();
char[] cc = text.toCharArray();
int len = cc.length;
StringBuilder sb = new StringBuilder();
Font font = null;
int lastidx = -1;
Phrase ret = new Phrase();
for (int k = 0; k < len; ++k) {
char c = cc[k];
if (c == '\n' || c == '\r') {
sb.append(c);
continue;
}
if (Utilities.isSurrogatePair(cc, k)) {
int u = Utilities.convertToUtf32(cc, k);
for (int f = 0; f < fsize; ++f) {
font = fonts.get(f);
if (font.getBaseFont().charExists(u)) {
if (lastidx != f) {
if (sb.length() > 0 && lastidx != -1) {
Chunk ck = new Chunk(sb.toString(), fonts.get(lastidx));
ret.add(ck);
sb.setLength(0);
}
lastidx = f;
}
sb.append(c);
if (cc.length > k + 1) {
sb.append(cc[++k]);
}
break;
}
}
} else {
for (int f = 0; f < fsize; ++f) {
font = fonts.get(f);
if (font.getBaseFont().charExists(c)) {
if (lastidx != f) {
if (sb.length() > 0 && lastidx != -1) {
Chunk ck = new Chunk(sb.toString(), fonts.get(lastidx));
ret.add(ck);
sb.setLength(0);
}
lastidx = f;
}
sb.append(c);
break;
}
}
}
}
if (sb.length() > 0) {
Chunk ck;
if (lastidx == -1) {
ck = new Chunk(sb.toString());
} else {
ck = new Chunk(sb.toString(), fonts.get(lastidx));
}
ret.add(ck);
}
return ret;
| 488
| 577
| 1,065
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/FopGlyphProcessor.java
|
FopGlyphProcessor
|
convertToBytesWithGlyphs
|
class FopGlyphProcessor {
private static boolean isFopSupported;
static {
try {
Class.forName("org.apache.fop.complexscripts.util.GlyphSequence");
isFopSupported = true;
} catch (ClassNotFoundException e) {
isFopSupported = false;
}
}
public static boolean isFopSupported() {
return isFopSupported;
}
public static byte[] convertToBytesWithGlyphs(BaseFont font, String text, String fileName,
Map<Integer, int[]> longTag, String language) throws UnsupportedEncodingException {<FILL_FUNCTION_BODY>}
}
|
TrueTypeFontUnicode ttu = (TrueTypeFontUnicode) font;
IntBuffer charBuffer = IntBuffer.allocate(text.length());
IntBuffer glyphBuffer = IntBuffer.allocate(text.length());
int textLength = text.length();
for (char c : text.toCharArray()) {
int[] metrics = ttu.getMetricsTT(c);
// metrics will be null in case glyph not defined in TTF font, skip these characters.
if (metrics == null) {
textLength--;
continue;
}
charBuffer.put(c);
glyphBuffer.put(metrics[0]);
}
charBuffer.limit(textLength);
glyphBuffer.limit(textLength);
GlyphSequence glyphSequence = new GlyphSequence(charBuffer, glyphBuffer, null);
TTFFile ttf = TTFCache.getTTFFile(fileName, ttu);
GlyphSubstitutionTable gsubTable = ttf.getGSUB();
if (gsubTable != null) {
String script = CharScript.scriptTagFromCode(CharScript.dominantScript(text));
if ("zyyy".equals(script) || "auto".equals(script)) {
script = "*";
}
glyphSequence = gsubTable.substitute(glyphSequence, script, language);
}
int limit = glyphSequence.getGlyphs().limit();
int[] processedChars = glyphSequence.getGlyphs().array();
char[] charEncodedGlyphCodes = new char[limit];
for (int i = 0; i < limit; i++) {
charEncodedGlyphCodes[i] = (char) processedChars[i];
Integer glyphCode = processedChars[i];
if (!longTag.containsKey(glyphCode)) {
longTag.put(glyphCode,
new int[]{processedChars[i], ttu.getGlyphWidth(processedChars[i]), charBuffer.get(i)});
}
}
return new String(charEncodedGlyphCodes).getBytes(CJKFont.CJK_ENCODING);
| 176
| 544
| 720
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/GrayColor.java
|
GrayColor
|
equals
|
class GrayColor extends ExtendedColor {
public static final GrayColor GRAYBLACK = new GrayColor(0);
public static final GrayColor GRAYWHITE = new GrayColor(MAX_FLOAT_COLOR_VALUE);
private static final long serialVersionUID = -6571835680819282746L;
private float gray;
public GrayColor(int intGray) {
this(normalize(intGray) / MAX_INT_COLOR_VALUE);
}
public GrayColor(float floatGray) {
this(floatGray, MAX_FLOAT_COLOR_VALUE);
}
public GrayColor(int intGray, int alpha) {
this(normalize(intGray) / MAX_INT_COLOR_VALUE, normalize(alpha) / MAX_INT_COLOR_VALUE);
}
public GrayColor(float floatGray, float alpha) {
super(TYPE_GRAY, normalize(floatGray), normalize(floatGray), normalize(floatGray), normalize(alpha));
gray = normalize(floatGray);
}
public float getGray() {
return gray;
}
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
public int hashCode() {
return Float.floatToIntBits(gray);
}
}
|
return obj instanceof GrayColor && ((GrayColor) obj).gray == this.gray;
| 350
| 24
| 374
|
<methods>public void <init>(int) ,public void <init>(int, float, float, float) ,public void <init>(int, float, float, float, float) ,public static int getType(java.awt.Color) ,public int getType() <variables>public static final int MAX_COLOR_VALUE,public static final float MAX_FLOAT_COLOR_VALUE,public static final float MAX_INT_COLOR_VALUE,public static final int TYPE_CMYK,public static final int TYPE_GRAY,public static final int TYPE_PATTERN,public static final int TYPE_RGB,public static final int TYPE_SEPARATION,public static final int TYPE_SHADING,private static final long serialVersionUID,protected int type
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/HyphenationAuto.java
|
HyphenationAuto
|
getHyphenatedWordPre
|
class HyphenationAuto implements HyphenationEvent {
/**
* The hyphenator engine.
*/
protected Hyphenator hyphenator;
/**
* The second part of the hyphenated word.
*/
protected String post;
/**
* Creates a new hyphenation instance usable in <CODE>Chunk</CODE>.
*
* @param lang the language ("en" for English, for example)
* @param country the country ("GB" for Great-Britain or "none" for no country, for example)
* @param leftMin the minimum number of letters before the hyphen
* @param rightMin the minimum number of letters after the hyphen
*/
public HyphenationAuto(String lang, String country, int leftMin, int rightMin) {
hyphenator = new Hyphenator(lang, country, leftMin, rightMin);
}
/**
* Gets the hyphen symbol.
*
* @return the hyphen symbol
*/
public String getHyphenSymbol() {
return "-";
}
/**
* Hyphenates a word and returns the first part of it. To get the second part of the hyphenated word call
* <CODE>getHyphenatedWordPost()</CODE>.
*
* @param word the word to hyphenate
* @param font the font used by this word
* @param fontSize the font size used by this word
* @param remainingWidth the width available to fit this word in
* @return the first part of the hyphenated word including the hyphen symbol, if any
*/
public String getHyphenatedWordPre(String word, BaseFont font, float fontSize, float remainingWidth) {<FILL_FUNCTION_BODY>}
/**
* Gets the second part of the hyphenated word. Must be called after <CODE>getHyphenatedWordPre()</CODE>.
*
* @return the second part of the hyphenated word
*/
public String getHyphenatedWordPost() {
return post;
}
}
|
post = word;
String hyphen = getHyphenSymbol();
float hyphenWidth = font.getWidthPoint(hyphen, fontSize);
if (hyphenWidth > remainingWidth) {
return "";
}
Hyphenation hyphenation = hyphenator.hyphenate(word);
if (hyphenation == null) {
return "";
}
int len = hyphenation.length();
int k;
for (k = 0; k < len; ++k) {
if (font.getWidthPoint(hyphenation.getPreHyphenText(k), fontSize) + hyphenWidth > remainingWidth) {
break;
}
}
--k;
if (k < 0) {
return "";
}
post = hyphenation.getPostHyphenText(k);
return hyphenation.getPreHyphenText(k) + hyphen;
| 533
| 232
| 765
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/LZWDecoder.java
|
LZWDecoder
|
addStringToTable
|
class LZWDecoder {
byte[][] stringTable;
byte[] data = null;
OutputStream uncompData;
int tableIndex, bitsToGet = 9;
int bytePointer, bitPointer;
int nextData = 0;
int nextBits = 0;
int[] andTable = {
511,
1023,
2047,
4095
};
public LZWDecoder() {
}
/**
* Method to decode LZW compressed data.
*
* @param data The compressed data.
* @param uncompData Array to return the uncompressed data in.
*/
public void decode(byte[] data, OutputStream uncompData) {
if (data[0] == (byte) 0x00 && data[1] == (byte) 0x01) {
throw new RuntimeException(MessageLocalization.getComposedMessage("lzw.flavour.not.supported"));
}
initializeStringTable();
this.data = data;
this.uncompData = uncompData;
// Initialize pointers
bytePointer = 0;
bitPointer = 0;
nextData = 0;
nextBits = 0;
int code, oldCode = 0;
byte[] string;
while ((code = getNextCode()) != 257) {
if (code == 256) {
initializeStringTable();
code = getNextCode();
if (code == 257) {
break;
}
writeString(stringTable[code]);
oldCode = code;
} else {
if (code < tableIndex) {
string = stringTable[code];
writeString(string);
addStringToTable(stringTable[oldCode], string[0]);
oldCode = code;
} else {
string = stringTable[oldCode];
string = composeString(string, string[0]);
writeString(string);
addStringToTable(string);
oldCode = code;
}
}
}
}
/**
* Initialize the string table.
*/
public void initializeStringTable() {
stringTable = new byte[8192][];
for (int i = 0; i < 256; i++) {
stringTable[i] = new byte[1];
stringTable[i][0] = (byte) i;
}
tableIndex = 258;
bitsToGet = 9;
}
/**
* Write out the string just uncompressed.
*
* @param string bytes
*/
public void writeString(byte[] string) {
try {
uncompData.write(string);
} catch (IOException e) {
throw new ExceptionConverter(e);
}
}
/**
* Add a new string to the string table.
*
* @param newString new string bytes
* @param oldString old string bytes
*/
public void addStringToTable(byte[] oldString, byte newString) {<FILL_FUNCTION_BODY>}
/**
* Add a new string to the string table.
*
* @param string bytes
*/
public void addStringToTable(byte[] string) {
// Add this new String to the table
stringTable[tableIndex++] = string;
if (tableIndex == 511) {
bitsToGet = 10;
} else if (tableIndex == 1023) {
bitsToGet = 11;
} else if (tableIndex == 2047) {
bitsToGet = 12;
}
}
/**
* Append <code>newString</code> to the end of <code>oldString</code>.
*
* @param oldString old string bytes
* @param newString new string bytes
* @return byes
*/
public byte[] composeString(byte[] oldString, byte newString) {
int length = oldString.length;
byte[] string = new byte[length + 1];
System.arraycopy(oldString, 0, string, 0, length);
string[length] = newString;
return string;
}
// Returns the next 9, 10, 11 or 12 bits
public int getNextCode() {
// Attempt to get the next code. The exception is caught to make
// this robust to cases wherein the EndOfInformation code has been
// omitted from a strip. Examples of such cases have been observed
// in practice.
try {
nextData = (nextData << 8) | (data[bytePointer++] & 0xff);
nextBits += 8;
if (nextBits < bitsToGet) {
nextData = (nextData << 8) | (data[bytePointer++] & 0xff);
nextBits += 8;
}
int code =
(nextData >> (nextBits - bitsToGet)) & andTable[bitsToGet - 9];
nextBits -= bitsToGet;
return code;
} catch (ArrayIndexOutOfBoundsException e) {
// Strip not terminated as expected: return EndOfInformation code.
return 257;
}
}
}
|
int length = oldString.length;
byte[] string = new byte[length + 1];
System.arraycopy(oldString, 0, string, 0, length);
string[length] = newString;
// Add this new String to the table
stringTable[tableIndex++] = string;
if (tableIndex == 511) {
bitsToGet = 10;
} else if (tableIndex == 1023) {
bitsToGet = 11;
} else if (tableIndex == 2047) {
bitsToGet = 12;
}
| 1,368
| 152
| 1,520
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/MappedRandomAccessFile.java
|
MappedRandomAccessFile
|
cleanJava11
|
class MappedRandomAccessFile implements AutoCloseable {
private MappedByteBuffer mappedByteBuffer = null;
private FileChannel channel = null;
/**
* Constructs a new MappedRandomAccessFile instance
*
* @param filename String
* @param mode String r, w or rw
* @throws FileNotFoundException on error
* @throws IOException on error
*/
public MappedRandomAccessFile(String filename, String mode)
throws IOException {
if (mode.equals("rw")) {
init(
new java.io.RandomAccessFile(filename, mode).getChannel(),
FileChannel.MapMode.READ_WRITE);
} else {
init(
new FileInputStream(filename).getChannel(),
FileChannel.MapMode.READ_ONLY);
}
}
/**
* invokes the clean method on the ByteBuffer's cleaner
*
* @param buffer ByteBuffer
* @return boolean true on success
*/
public static boolean clean(final java.nio.ByteBuffer buffer) {
if (buffer == null || !buffer.isDirect()) {
return false;
}
return cleanJava11(buffer);
}
private static boolean cleanJava11(final ByteBuffer buffer) {<FILL_FUNCTION_BODY>}
/**
* initializes the channel and mapped bytebuffer
*
* @param channel FileChannel
* @param mapMode FileChannel.MapMode
* @throws IOException
*/
private void init(FileChannel channel, FileChannel.MapMode mapMode)
throws IOException {
if (channel.size() > Integer.MAX_VALUE) {
throw new PdfException("The PDF file is too large. Max 2GB. Size: " + channel.size());
}
this.channel = channel;
this.mappedByteBuffer = channel.map(mapMode, 0L, channel.size());
mappedByteBuffer.load();
}
/**
* @return FileChannel
* @since 2.0.8
*/
public FileChannel getChannel() {
return channel;
}
/**
* @return int next integer or -1 on EOF
* @see java.io.RandomAccessFile#read()
*/
public int read() {
try {
byte b = mappedByteBuffer.get();
int n = b & 0xff;
return n;
} catch (BufferUnderflowException e) {
return -1; // EOF
}
}
/**
* @param bytes byte[]
* @param off int offset
* @param len int length
* @return int bytes read or -1 on EOF
* @see java.io.RandomAccessFile#read(byte[], int, int)
*/
public int read(byte[] bytes, int off, int len) {
int pos = mappedByteBuffer.position();
int limit = mappedByteBuffer.limit();
if (pos == limit) {
return -1; // EOF
}
int newlimit = pos + len - off;
if (newlimit > limit) {
len = limit - pos; // don't read beyond EOF
}
mappedByteBuffer.get(bytes, off, len);
return len;
}
/**
* @return long
* @see java.io.RandomAccessFile#getFilePointer()
*/
public long getFilePointer() {
return mappedByteBuffer.position();
}
/**
* @param pos long position
* @see java.io.RandomAccessFile#seek(long)
*/
public void seek(long pos) {
mappedByteBuffer.position((int) pos);
}
/**
* @return long length
* @see java.io.RandomAccessFile#length()
*/
public long length() {
return mappedByteBuffer.limit();
}
/**
* Cleans the mapped bytebuffer and closes the channel
*
* @throws IOException on error
* @see java.io.RandomAccessFile#close()
*/
public void close() throws IOException {
clean(mappedByteBuffer);
mappedByteBuffer = null;
if (channel != null) {
channel.close();
}
channel = null;
}
/**
* invokes the close method
*
* @see java.lang.Object#finalize()
*/
@Override
@Deprecated(since = "OpenPDF-2.0.2", forRemoval = true)
protected void finalize() throws Throwable {
close();
super.finalize();
}
}
|
Boolean success = Boolean.FALSE;
try {
MethodHandles.Lookup lookup = MethodHandles.lookup();
Class<?> unsafeClass = Class.forName("sun.misc.Unsafe");
MethodHandle methodHandle = lookup.findStatic(unsafeClass, "getUnsafe", MethodType.methodType(unsafeClass));
Object theUnsafe = methodHandle.invoke();
MethodHandle invokeCleanerMethod = lookup.findVirtual(unsafeClass, "invokeCleaner",
MethodType.methodType(void.class, ByteBuffer.class));
invokeCleanerMethod.invoke(theUnsafe, buffer);
success = Boolean.TRUE;
} catch (Throwable ignore) {
// Ignore
}
return success;
| 1,176
| 185
| 1,361
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/OcspClientBouncyCastle.java
|
OcspClientBouncyCastle
|
generateOCSPRequest
|
class OcspClientBouncyCastle implements OcspClient {
/**
* root certificate
*/
private final X509Certificate rootCert;
/**
* check certificate
*/
private final X509Certificate checkCert;
/**
* OCSP URL
*/
private final String url;
/**
* HTTP proxy used to access the OCSP URL
*/
private Proxy proxy;
/**
* Creates an instance of an OcspClient that will be using BouncyCastle.
*
* @param checkCert the check certificate
* @param rootCert the root certificate
* @param url the OCSP URL
*/
public OcspClientBouncyCastle(X509Certificate checkCert,
X509Certificate rootCert, String url) {
this.checkCert = checkCert;
this.rootCert = rootCert;
this.url = url;
}
/**
* Generates an OCSP request using BouncyCastle.
*
* @param issuerCert certificate of the issues
* @param serialNumber serial number
* @return an OCSP request
* @throws OCSPException
* @throws IOException
*/
private static OCSPReq generateOCSPRequest(X509Certificate issuerCert,
BigInteger serialNumber) throws OCSPException, IOException,
OperatorCreationException, CertificateEncodingException {<FILL_FUNCTION_BODY>}
/**
* @return a byte array
* @see com.lowagie.text.pdf.OcspClient
*/
@Override
public byte[] getEncoded() {
try {
OCSPReq request = generateOCSPRequest(rootCert,
checkCert.getSerialNumber());
byte[] array = request.getEncoded();
URL urlt = new URL(url);
Proxy tmpProxy = proxy == null ? Proxy.NO_PROXY : proxy;
HttpURLConnection con = (HttpURLConnection) urlt.openConnection(tmpProxy);
con.setRequestProperty("Content-Type", "application/ocsp-request");
con.setRequestProperty("Accept", "application/ocsp-response");
con.setDoOutput(true);
OutputStream out = con.getOutputStream();
DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(
out));
dataOut.write(array);
dataOut.flush();
dataOut.close();
if (con.getResponseCode() / 100 != 2) {
throw new IOException(MessageLocalization.getComposedMessage(
"invalid.http.response.1", con.getResponseCode()));
}
// Get Response
InputStream in = (InputStream) con.getContent();
OCSPResp ocspResponse = new OCSPResp(in);
if (ocspResponse.getStatus() != 0) {
throw new IOException(MessageLocalization.getComposedMessage(
"invalid.status.1", ocspResponse.getStatus()));
}
BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse
.getResponseObject();
if (basicResponse != null) {
SingleResp[] responses = basicResponse.getResponses();
if (responses.length == 1) {
SingleResp resp = responses[0];
Object status = resp.getCertStatus();
if (status == null) {
return basicResponse.getEncoded();
} else if (status instanceof org.bouncycastle.cert.ocsp.RevokedStatus) {
throw new IOException(
MessageLocalization
.getComposedMessage("ocsp.status.is.revoked"));
} else {
throw new IOException(
MessageLocalization
.getComposedMessage("ocsp.status.is.unknown"));
}
}
}
} catch (Exception ex) {
throw new ExceptionConverter(ex);
}
return null;
}
/**
* Returns Proxy object used for URL connections.
*
* @return configured proxy
*/
public Proxy getProxy() {
return proxy;
}
/**
* Sets Proxy which will be used for URL connection.
*
* @param aProxy Proxy to set
*/
public void setProxy(final Proxy aProxy) {
this.proxy = aProxy;
}
}
|
// Add provider BC
Provider prov = new org.bouncycastle.jce.provider.BouncyCastleProvider();
Security.addProvider(prov);
// Generate the id for the certificate we are looking for
// OJO... Modificacion de
// Felix--------------------------------------------------
// CertificateID id = new CertificateID(CertificateID.HASH_SHA1, issuerCert,
// serialNumber);
// Example from
// http://grepcode.com/file/repo1.maven.org/maven2/org.bouncycastle/bcmail-jdk16/1.46/org/bouncycastle/cert/ocsp/test/OCSPTest.java
DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder()
.setProvider(prov).build();
CertificateID id = new CertificateID(
digCalcProv.get(CertificateID.HASH_SHA1), new JcaX509CertificateHolder(
issuerCert), serialNumber);
// basic request generation with nonce
OCSPReqBuilder gen = new OCSPReqBuilder();
gen.addRequest(id);
// create details for nonce extension
// Vector oids = new Vector();
// Vector values = new Vector();
// oids.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
// values.add(new X509Extension(false, new DEROctetString(new
// DEROctetString(PdfEncryption.createDocumentId()).getEncoded())));
// gen.setRequestExtensions(new X509Extensions(oids, values));
// Add nonce extension
ExtensionsGenerator extGen = new ExtensionsGenerator();
byte[] nonce = new byte[16];
Random rand = new Random();
rand.nextBytes(nonce);
extGen.addExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false,
new DEROctetString(nonce));
gen.setRequestExtensions(extGen.generate());
// Build request
return gen.build();
// ******************************************************************************
| 1,101
| 549
| 1,650
|
<no_super_class>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/OutputStreamEncryption.java
|
OutputStreamEncryption
|
write
|
class OutputStreamEncryption extends OutputStream {
private static final int AES_128 = 4;
private static final int AES_256_V3 = 6;
protected OutputStream out;
protected ARCFOUREncryption arcfour;
protected AESCipher cipher;
private byte[] sb = new byte[1];
private boolean aes;
private boolean finished;
/**
* Creates a new instance of OutputStreamCounter
*
* @param key bytes for key
* @param len length
* @param off offset
* @param out output stream
* @param revision revision number
*/
public OutputStreamEncryption(OutputStream out, byte[] key, int off, int len, int revision) {
try {
this.out = out;
aes = (revision == AES_128) || (revision == AES_256_V3);
if (aes) {
byte[] iv = IVGenerator.getIV();
byte[] nkey = new byte[len];
System.arraycopy(key, off, nkey, 0, len);
cipher = new AESCipher(true, nkey, iv);
write(iv);
} else {
arcfour = new ARCFOUREncryption();
arcfour.prepareARCFOURKey(key, off, len);
}
} catch (Exception ex) {
throw new ExceptionConverter(ex);
}
}
public OutputStreamEncryption(OutputStream out, byte[] key, int revision) {
this(out, key, 0, key.length, revision);
}
/**
* Closes this output stream and releases any system resources associated with this stream. The general contract of
* <code>close</code> is that it closes the output stream. A closed stream cannot perform output operations and
* cannot be reopened.
* <p>
* The <code>close</code> method of <code>OutputStream</code> does nothing.
*
* @throws IOException if an I/O error occurs.
*/
public void close() throws IOException {
finish();
out.close();
}
/**
* Flushes this output stream and forces any buffered output bytes to be written out. The general contract of
* <code>flush</code> is that calling it is an indication that, if any bytes previously written have been buffered
* by the implementation of the output stream, such bytes should immediately be written to their intended
* destination.
* <p>
* The <code>flush</code> method of <code>OutputStream</code> does nothing.
*
* @throws IOException if an I/O error occurs.
*/
public void flush() throws IOException {
out.flush();
}
/**
* Writes <code>b.length</code> bytes from the specified byte array to this output stream. The general contract for
* <code>write(b)</code> is that it should have exactly the same effect as the call
* <code>write(b, 0, b.length)</code>.
*
* @param b the data.
* @throws IOException if an I/O error occurs.
* @see java.io.OutputStream#write(byte[], int, int)
*/
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
/**
* Writes the specified byte to this output stream. The general contract for <code>write</code> is that one byte is
* written to the output stream. The byte to be written is the eight low-order bits of the argument <code>b</code>.
* The 24 high-order bits of <code>b</code> are ignored.
* <p>
* Subclasses of <code>OutputStream</code> must provide an implementation for this method.
*
* @param b the <code>byte</code>.
* @throws IOException if an I/O error occurs. In particular, an <code>IOException</code> may be thrown if the
* output stream has been closed.
*/
public void write(int b) throws IOException {
sb[0] = (byte) b;
write(sb, 0, 1);
}
/**
* Writes <code>len</code> bytes from the specified byte array starting at offset <code>off</code> to this output
* stream. The general contract for <code>write(b, off, len)</code> is that some of the bytes in the array
* <code>b</code> are written to the output stream in order; element <code>b[off]</code> is the first byte written
* and <code>b[off+len-1]</code> is the last byte written by this operation.
* <p>
* The <code>write</code> method of <code>OutputStream</code> calls the write method of one argument on each of the
* bytes to be written out. Subclasses are encouraged to override this method and provide a more efficient
* implementation.
* <p>
* If <code>b</code> is <code>null</code>, a
* <code>NullPointerException</code> is thrown.
* <p>
* If <code>off</code> is negative, or <code>len</code> is negative, or
* <code>off+len</code> is greater than the length of the array
* <code>b</code>, then an <code>IndexOutOfBoundsException</code> is thrown.
*
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
* @throws IOException if an I/O error occurs. In particular, an <code>IOException</code> is thrown if the output
* stream is closed.
*/
public void write(byte[] b, int off, int len) throws IOException {<FILL_FUNCTION_BODY>}
public void finish() throws IOException {
if (!finished) {
finished = true;
if (aes) {
byte[] b;
try {
b = cipher.doFinal();
} catch (Exception ex) {
throw new ExceptionConverter(ex);
}
out.write(b, 0, b.length);
}
}
}
}
|
if (aes) {
byte[] b2 = cipher.update(b, off, len);
if (b2 == null || b2.length == 0) {
return;
}
out.write(b2, 0, b2.length);
} else {
byte[] b2 = new byte[Math.min(len, 4192)];
while (len > 0) {
int sz = Math.min(len, b2.length);
arcfour.encryptARCFOUR(b, off, sz, b2, 0);
out.write(b2, 0, sz);
len -= sz;
off += sz;
}
}
| 1,619
| 186
| 1,805
|
<methods>public void <init>() ,public void close() throws java.io.IOException,public void flush() throws java.io.IOException,public static java.io.OutputStream nullOutputStream() ,public abstract void write(int) throws java.io.IOException,public void write(byte[]) throws java.io.IOException,public void write(byte[], int, int) throws java.io.IOException<variables>
|
LibrePDF_OpenPDF
|
OpenPDF/openpdf/src/main/java/com/lowagie/text/pdf/PRAcroForm.java
|
PRAcroForm
|
iterateFields
|
class PRAcroForm extends PdfDictionary {
ArrayList<FieldInformation> fields;
ArrayList<PdfDictionary> stack;
HashMap<String, FieldInformation> fieldByName;
PdfReader reader;
/**
* Constructor
*
* @param reader reader of the input file
*/
public PRAcroForm(PdfReader reader) {
this.reader = reader;
fields = new ArrayList<>();
fieldByName = new HashMap<>();
stack = new ArrayList<>();
}
/**
* Number of fields found
*
* @return size
*/
public int size() {
return fields.size();
}
public ArrayList<FieldInformation> getFields() {
return fields;
}
public FieldInformation getField(String name) {
return fieldByName.get(name);
}
/**
* Given the title (/T) of a reference, return the associated reference
*
* @param name a string containing the path
* @return a reference to the field, or null
*/
public PRIndirectReference getRefByName(String name) {
FieldInformation fi = fieldByName.get(name);
if (fi == null) {
return null;
}
return fi.getRef();
}
/**
* Read, and comprehend the acroform
*
* @param root the document root
*/
public void readAcroForm(PdfDictionary root) {
if (root == null) {
return;
}
hashMap = root.hashMap;
pushAttrib(root);
PdfArray fieldlist = (PdfArray) PdfReader.getPdfObjectRelease(root.get(PdfName.FIELDS));
iterateFields(fieldlist, null, null);
}
/**
* After reading, we index all of the fields. Recursive.
*
* @param fieldlist An array of fields
* @param fieldDict the last field dictionary we encountered (recursively)
* @param title the pathname of the field, up to this point or null
*/
protected void iterateFields(PdfArray fieldlist, PRIndirectReference fieldDict, String title) {<FILL_FUNCTION_BODY>}
/**
* merge field attributes from two dictionaries
*
* @param parent one dictionary
* @param child the other dictionary
* @return a merged dictionary
*/
protected PdfDictionary mergeAttrib(PdfDictionary parent, PdfDictionary child) {
PdfDictionary targ = new PdfDictionary();
if (parent != null) {
targ.putAll(parent);
}
for (PdfName key : child.getKeys()) {
if (key.equals(PdfName.DR) || key.equals(PdfName.DA) ||
key.equals(PdfName.Q) || key.equals(PdfName.FF) ||
key.equals(PdfName.DV) || key.equals(PdfName.V)
|| key.equals(PdfName.FT)
|| key.equals(PdfName.F)) {
targ.put(key, child.get(key));
}
}
return targ;
}
/**
* stack a level of dictionary. Merge in a dictionary from this level
*
* @param dict the PfdDictionary
*/
protected void pushAttrib(PdfDictionary dict) {
PdfDictionary dic = null;
if (!stack.isEmpty()) {
dic = stack.get(stack.size() - 1);
}
dic = mergeAttrib(dic, dict);
stack.add(dic);
}
/**
* This class holds the information for a single field
*/
public static class FieldInformation {
String name;
PdfDictionary info;
PRIndirectReference ref;
FieldInformation(String name, PdfDictionary info, PRIndirectReference ref) {
this.name = name;
this.info = info;
this.ref = ref;
}
public String getName() {
return name;
}
public PdfDictionary getInfo() {
return info;
}
public PRIndirectReference getRef() {
return ref;
}
}
}
|
for (PdfObject pdfObject : fieldlist.getElements()) {
PRIndirectReference ref = (PRIndirectReference) pdfObject;
PdfDictionary dict = (PdfDictionary) PdfReader.getPdfObjectRelease(ref);
// if we are not a field dictionary, pass our parent's values
PRIndirectReference myFieldDict = fieldDict;
String myTitle = title;
PdfString tField = (PdfString) dict.get(PdfName.T);
boolean isFieldDict = tField != null;
if (isFieldDict) {
myFieldDict = ref;
if (title == null) {
myTitle = tField.toString();
} else {
myTitle = title + '.' + tField.toString();
}
}
PdfArray kids = (PdfArray) dict.get(PdfName.KIDS);
if (kids != null) {
pushAttrib(dict);
List<PdfObject> elements = kids.getElements();
Iterator<PdfObject> kidIter = elements.iterator();
while (kidIter.hasNext()) {
PdfIndirectReference kidRef = (PdfIndirectReference) kidIter.next();
if (ref.getNumber() == kidRef.getNumber()) {
kidIter.remove();
}
}
iterateFields(new PdfArray(elements), myFieldDict, myTitle);
stack.remove(stack.size() - 1); // pop
} else { // leaf node
if (myFieldDict != null) {
PdfDictionary mergedDict = stack.get(stack.size() - 1);
if (isFieldDict) {
mergedDict = mergeAttrib(mergedDict, dict);
}
mergedDict.put(PdfName.T, new PdfString(myTitle));
FieldInformation fi = new FieldInformation(myTitle, mergedDict, myFieldDict);
fields.add(fi);
fieldByName.put(myTitle, fi);
}
}
}
| 1,092
| 528
| 1,620
|
<methods>public void <init>() ,public void <init>(com.lowagie.text.pdf.PdfName) ,public void clear() ,public boolean contains(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfObject get(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfArray getAsArray(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfBoolean getAsBoolean(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfDictionary getAsDict(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfIndirectReference getAsIndirectObject(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfName getAsName(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfNumber getAsNumber(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfStream getAsStream(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfString getAsString(com.lowagie.text.pdf.PdfName) ,public com.lowagie.text.pdf.PdfObject getDirectObject(com.lowagie.text.pdf.PdfName) ,public Set<com.lowagie.text.pdf.PdfName> getKeys() ,public Set<Entry<com.lowagie.text.pdf.PdfName,com.lowagie.text.pdf.PdfObject>> getKeysAndValues() ,public boolean isCatalog() ,public boolean isFont() ,public boolean isOutlineTree() ,public boolean isPage() ,public boolean isPages() ,public void merge(com.lowagie.text.pdf.PdfDictionary) ,public void mergeDifferent(com.lowagie.text.pdf.PdfDictionary) ,public void put(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void putAll(com.lowagie.text.pdf.PdfDictionary) ,public void putEx(com.lowagie.text.pdf.PdfName, com.lowagie.text.pdf.PdfObject) ,public void remove(com.lowagie.text.pdf.PdfName) ,public int size() ,public void toPdf(com.lowagie.text.pdf.PdfWriter, java.io.OutputStream) throws java.io.IOException,public java.lang.String toString() <variables>public static final com.lowagie.text.pdf.PdfName CATALOG,public static final com.lowagie.text.pdf.PdfName FONT,public static final com.lowagie.text.pdf.PdfName OUTLINES,public static final com.lowagie.text.pdf.PdfName PAGE,public static final com.lowagie.text.pdf.PdfName PAGES,private com.lowagie.text.pdf.PdfName dictionaryType,protected Map<com.lowagie.text.pdf.PdfName,com.lowagie.text.pdf.PdfObject> hashMap
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.